nex-code 0.3.23 → 0.3.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +351 -325
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,134 +1,134 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
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(),80)}update(e,
|
|
5
|
-
`}process.stderr.write(n)}}
|
|
6
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d
|
|
7
|
-
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let
|
|
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(a)}};function
|
|
13
|
-
`),n=
|
|
14
|
-
`);return
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=
|
|
17
|
-
${
|
|
2
|
+
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var gn=N((Sg,xl)=>{xl.exports={name:"nex-code",version:"0.3.24",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 dr=N((Eg,ur)=>{var O={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},ar=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],cr=["\u273D","\u2726","\u2727","\u2726"],gs=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ar[this.frame%ar.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),r=n%60;s=` ${O.dim}${o}m ${String(r).padStart(2,"0")}s${O.reset}`}else n>=1&&(s=` ${O.dim}${n}s${O.reset}`)}process.stderr.write(`\x1B[2K\r${O.cyan}${e}${O.reset} ${O.dim}${this.text}${O.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),80))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},lr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$s=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=lr[this.frame%lr.length],s=this._formatElapsed(),n=s?` ${O.dim}${s}${O.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let a,c;switch(this.statuses[r]){case"done":a=`${O.green}\u2713${O.reset}`,c=O.dim;break;case"error":a=`${O.red}\u2717${O.reset}`,c=O.dim;break;default:a=`${O.cyan}${e}${O.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${a} ${c}${this.labels[r]}${O.reset}${l}
|
|
3
|
+
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${O.dim}${e}${O.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${O.green}\u2713${O.reset}`;break;case"error":r=`${O.red}\u2717${O.reset}`;break;default:r=`${O.yellow}\u25CB${O.reset}`}let a=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${O.dim}${this.labels[o]}${O.reset}${a}
|
|
5
|
+
`}process.stderr.write(n)}},$n={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},yn={done:O.green,in_progress:O.cyan,pending:O.dim,failed:O.red},Ke=null,ys=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=cr[this.frame%cr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${O.dim}(${o})${O.reset}`:"",a=`\x1B[2K${O.cyan}${e}${O.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=$n[l.status]||$n.pending,f=yn[l.status]||yn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${O.dim}${u}${O.reset} ${f}${d}${O.reset} ${m}
|
|
7
|
+
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Ke=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Ke===this&&(Ke=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,a=`\x1B[2K${O.green}\u2714${O.reset} ${this.name} ${O.dim}(${e} \xB7 ${r})${O.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=$n[l.status]||$n.pending,f=yn[l.status]||yn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${O.dim}${u}${O.reset} ${f}${d}${O.reset} ${O.dim}${m}${O.reset}
|
|
12
|
+
`}process.stderr.write(a)}};function _l(t){Ke=t}function kl(){return Ke}function vl(){Ke&&(Ke.stop(),Ke=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}ur.exports={C:O,Spinner:gs,MultiProgress:$s,TaskProgress:ys,setActiveTaskProgress:_l,getActiveTaskProgress:kl,cleanupTerminal:vl}});var mr=N((Cg,fr)=>{var J={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"},Sl={read_file:"Read file",write_file:"Write file",edit_file:"Edit file",patch_file:"Patch file",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"},El={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",patch_file:"Patching file",list_directory:"Listing directory",bash:"Running command",grep:"Searching code",search_files:"Searching files",glob:"Finding files",web_fetch:"Fetching content",web_search:"Searching the web",git_status:"Checking repository",git_diff:"Analyzing changes",git_log:"Reading git history",git_commit:"Creating commit",git_push:"Pushing changes",git_pull:"Pulling changes",git_branch:"Managing branches",git_stash:"Stashing changes",task_list:"Managing tasks",spawn_agents:"Delegating to agents",ask_user:"Awaiting input",switch_model:"Switching model",gh_run_list:"GitHub Actions",gh_run_view:"GitHub Actions",gh_workflow_trigger:"Triggering workflow",browser_open:"Opening browser",browser_screenshot:"Taking screenshot",browser_click:"Clicking element",browser_fill:"Filling form",ssh_exec:"Running on server",ssh_upload:"Uploading to server",ssh_download:"Downloading from server",service_manage:"Managing service",service_logs:"Reading service logs",container_list:"Listing containers",container_logs:"Reading container logs",container_exec:"Running in container",brain_write:"Saving to memory",deploy:"Deploying"};function Cl(t,e){let s=(t||[]).filter(r=>r&&r.canExecute!==!1);if(s.length===0)return`${J.cyan} \u25C6 Step ${e}${J.reset}`;let n=[...new Set(s.map(r=>El[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let a=s[0].args||{},c=` ${J.reset}${J.dim}`;a.path?o+=`${c}${a.path.split("/").pop()}`:a.command?o+=`${c}${String(a.command).substring(0,50)}`:a.query?o+=`${c}${String(a.query).substring(0,50)}`:a.pattern&&(o+=`${c}${String(a.pattern).substring(0,50)}`)}else n.length===1?o=`${n[0]} (${s.length})`:n.length<=3?o=n.join(" \xB7 "):o=`${s.length} actions`;return`${J.cyan} \u25C6 ${o}${J.reset}`}function Tl(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Sl[t]||t.replace(/_/g," "),o=s?` ${J.dim}${s}${J.reset}`:"";return`${J.cyan} \u23FA${J.reset} ${J.bold}${n}${J.reset}${o}`}function Rl(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${J.dim} \u23BF ${J.reset}`,a=" ",c=n.map((l,u)=>`${u===0?r:a}${J.green}${l}${J.reset}`).join(`
|
|
14
|
+
`);return o>0&&(c+=`
|
|
15
|
+
${J.gray} \u2026+${o} more lines${J.reset}`),c}function Al(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 Ol(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
+
${J.dim}${c[1].substring(0,100)}${J.reset}`:"";return` ${J.red}\u23BF ${a}${J.reset}${l}`}let r;switch(t){case"read_file":{let a=o.split(`
|
|
18
18
|
`).filter(Boolean),c=a.length,l=a[a.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let a=(e.content||"").split(`
|
|
19
|
-
`).length;r=`Wrote ${a} line${a!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let a=(e.patches||[]).length;r=`Applied ${a} patch${a!==1?"es":""}`;break}case"bash":{let a=
|
|
20
|
-
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=
|
|
21
|
-
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(
|
|
22
|
-
`).filter(Boolean).length;r=`${a} match${a!==1?"es":""}`}break}case"glob":{if(
|
|
23
|
-
`).filter(Boolean).length;r=`${a} file${a!==1?"s":""} found`}break}case"list_directory":{let a=
|
|
24
|
-
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=
|
|
25
|
-
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(
|
|
26
|
-
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=a>0?`${a} commit${a!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let a=
|
|
27
|
-
|
|
28
|
-
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(
|
|
29
|
-
`),u=
|
|
19
|
+
`).length;r=`Wrote ${a} line${a!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let a=(e.patches||[]).length;r=`Applied ${a} patch${a!==1?"es":""}`;break}case"bash":{let a=o.match(/^EXIT (\d+)/);if(a){let c=a[1],l=o.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=o.split(`
|
|
20
|
+
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=o.split(`
|
|
21
|
+
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let a=o.split(`
|
|
22
|
+
`).filter(Boolean).length;r=`${a} match${a!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let a=o.split(`
|
|
23
|
+
`).filter(Boolean).length;r=`${a} file${a!==1?"s":""} found`}break}case"list_directory":{let a=o==="(empty)"?0:o.split(`
|
|
24
|
+
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
25
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
26
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=a>0?`${a} commit${a!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let a=o.split(`
|
|
27
|
+
|
|
28
|
+
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${J.dim}\u23BF ${r}${J.reset}`}fr.exports={C:J,formatToolCall:Tl,formatResult:Rl,getToolSpinnerText:Al,formatToolSummary:Ol,formatSectionHeader:Cl}});var re=N((Tg,pr)=>{var ht={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 Ml(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+ht.reset}function Nl(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function Pl(t,e,s={}){let n=ht.bold,o=ht.dim,r=ht.reset,a=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=a.map((d,f)=>{let m=f/(a.length-1||1);return Ml(d,Nl(c,m))}).join(`
|
|
29
|
+
`),u=s.yolo?` ${n}${ht.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`)};return
|
|
35
|
-
`);h=g.pop()||"";for(let
|
|
31
|
+
${o}Agentic Coding CLI v${gn().version}${r}
|
|
32
|
+
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
+
`)}var{Spinner:Ll,MultiProgress:ql,TaskProgress:Il,setActiveTaskProgress:jl,getActiveTaskProgress:Dl,cleanupTerminal:Fl}=dr(),{formatToolCall:Ul,formatResult:Wl,getToolSpinnerText:Bl,formatToolSummary:Hl,formatSectionHeader:zl}=mr();pr.exports={C:ht,banner:Pl,Spinner:Ll,MultiProgress:ql,TaskProgress:Il,setActiveTaskProgress:jl,getActiveTaskProgress:Dl,cleanupTerminal:Fl,formatToolCall:Ul,formatResult:Wl,getToolSpinnerText:Bl,formatToolSummary:Hl,formatSectionHeader:zl}});var Ae=N((Rg,br)=>{var Gl=require("readline"),{C:wn}=re(),hr=[/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/],ws=[/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 gr(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let a=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(a))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):ws.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:ws.some(c=>c.test(a))};return n.every(o)}var xs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],$r=[/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/],yr=[...xs,...$r],_s=!1,bs=null;function Kl(t){_s=t}function Jl(){return _s}function Yl(t){bs=t}function Xl(t){for(let e of hr)if(e.test(t))return e;return null}function Vl(t){if(/ssh\s/.test(t)&&gr(t))return!1;for(let e of yr)if(e.test(t))return!0;return!1}function Ql(t){for(let e of xs)if(e.test(t))return!0;return!1}function Zl(t,e={}){if(_s)return Promise.resolve(!0);let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(wr(e.toolName),n(!0)):n(a!=="n")};if(bs)bs.question(`${wn.yellow}${t} ${s}${wn.reset}`,o);else{let r=Gl.createInterface({input:process.stdin,output:process.stdout});r.question(`${wn.yellow}${t} ${s}${wn.reset}`,a=>{r.close(),o(a)})}})}var wr=()=>{};function eu(t){wr=t}br.exports={FORBIDDEN_PATTERNS:hr,SSH_SAFE_PATTERNS:ws,isSSHReadOnly:gr,DANGEROUS_BASH:yr,CRITICAL_BASH:xs,NOTABLE_BASH:$r,isForbidden:Xl,isDangerous:Vl,isCritical:Ql,confirm:Zl,setAutoConfirm:Kl,getAutoConfirm:Jl,setReadlineInterface:Yl,setAllowAlwaysHandler:eu}});var gt=N((Ag,xr)=>{var ks=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`)}};xr.exports={BaseProvider:ks}});var vr=N((Og,kr)=>{var bn=require("axios"),tu=require("http"),nu=require("https"),{BaseProvider:su}=gt(),xn=new tu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),_n=new nu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),_r={"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}},vs=class extends su{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||_r,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){bn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:xn,httpsAgent:_n}).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 bn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:xn,httpsAgent:_n})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
34
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=await bn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:xn,httpsAgent:_n});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await bn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:xn,httpsAgent:_n})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let g=h.split(`
|
|
35
|
+
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};kr.exports={OllamaProvider:vs,OLLAMA_MODELS:_r}});var Ar=N((Mg,Rr)=>{var{callChat:ou}=fe(),{estimateTokens:Ss}=Ce(),Sr=process.env.NEX_COMPACTION!=="false",Er=6,Cr=500,ru=`Summarize this conversation history concisely. Focus on:
|
|
36
36
|
- What files were read, created, or modified
|
|
37
37
|
- Key decisions made and their rationale
|
|
38
38
|
- Current state of the task (what's done, what's pending)
|
|
39
39
|
- Any errors encountered and how they were resolved
|
|
40
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
41
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:
|
|
42
|
-
tools: ${
|
|
40
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function iu(t){if(!Sr||t.length<Er)return null;let e=[{role:"system",content:ru},{role:"user",content:Tr(t)}];try{let n=((await ou(e,[],{temperature:0,maxTokens:Cr})).content||"").trim();if(!n)return null;let o=t.reduce((a,c)=>a+Ss(c.content||"")+(c.tool_calls?Ss(JSON.stringify(c.tool_calls)):0),0),r=Ss(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function Tr(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
|
|
42
|
+
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
43
43
|
|
|
44
|
-
`)}
|
|
45
|
-
`);if(
|
|
44
|
+
`)}Rr.exports={compactMessages:iu,formatMessagesForSummary:Tr,COMPACTION_ENABLED:Sr,COMPACTION_MIN_MESSAGES:Er,COMPACTION_SUMMARY_BUDGET:Cr}});var Ce=N((Ng,Dr)=>{function Nr(){return fe().getActiveModel()}var au={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Dt=new Map,Or=1e3,kn=new WeakMap,$t=new Map,Mr=500,Ft=null;function cu(){if(Ft!==null)return Ft;try{let e=Nr()?.provider||"ollama";return Ft=au[e]||4,Ft}catch{return 4}}function lu(){Ft=null}function nt(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,s=Dt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/cu());if(Dt.size>=Or){let o=Or>>1,r=Dt.keys();for(let a=0;a<o;a++)Dt.delete(r.next().value)}return Dt.set(e,n),n}function uu(t){if(kn.has(t))return kn.get(t);let e=Pr(t);if($t.has(e)){let n=$t.get(e);return kn.set(t,n),n}let s=JSON.stringify(t);if($t.size>=Mr){let n=Mr>>1,o=$t.keys();for(let r=0;r<n;r++)$t.delete(o.next().value)}return $t.set(e,s),kn.set(t,s),s}function Pr(t){let e=t.role||"",s=typeof t.content=="string"?t.content.substring(0,100):"",n=t.tool_calls?t.tool_calls.length:0;return`${e}:${s.length}:${n}`}function yt(t){let s=4;if(t.content&&(s+=nt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=nt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=nt(o):o&&(s+=nt(JSON.stringify(o)))}return s}function Te(t){let e=0;for(let s of t)e+=yt(s);return e}function du(t,e){if(t&&t.length===e.length){let r=!1;for(let a=0;a<e.length;a++)if(t[a]!==e[a]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=yt(e[r]);return o}function vn(t){return!t||t.length===0?0:nt(JSON.stringify(t))}function Sn(){return Nr()?.contextWindow||32768}function fu(t,e){let s=Te(t),n=vn(e),o=s+n,r=Sn(),a=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=yt(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Lr=.75,qr=.1,Ir=10,mu=200,pu=500;function jr(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
45
|
+
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),w=t.substring(0,p),$=t.substring(t.length-g);return w+`
|
|
46
46
|
...(${t.length} chars total)...
|
|
47
|
-
|
|
47
|
+
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<r&&l<u;p++)c.push(o[p]),l+=o[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=o.length-1;p>=o.length-a&&f<m;p--)d.unshift(o[p]),f+=o[p].length+1;let h=o.length-c.length-d.length;return c.join(`
|
|
48
48
|
`)+`
|
|
49
|
-
...(${h} lines omitted, ${
|
|
49
|
+
...(${h} lines omitted, ${o.length} total)...
|
|
50
50
|
`+d.join(`
|
|
51
|
-
`)}function
|
|
52
|
-
...(truncated)`),
|
|
53
|
-
`),r=Math.floor(n*.6),a=Math.floor(n*.4),c="",l=0;for(let h of
|
|
54
|
-
`:"")+h,l++}let u="",d=0;for(let h=
|
|
51
|
+
`)}function Ut(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:pu,n=e==="aggressive"?50:e==="medium"?100:mu;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:jr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
52
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function hu(t,e,s={}){let n=s.threshold??Lr,o=s.safetyMargin??qr,r=s.keepRecent??Ir,a=Sn(),c=vn(e),l=Math.floor(a*(n-o)),u=l-c,d=Te(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),w=t.slice(p,g),$=t.slice(g),x=w.filter(C=>!C._compacted);if(x.length>=6)try{let{compactMessages:C}=Ar(),A=await C(x);if(A){let q=[...w.filter(W=>W._compacted),A.message],ue=tt(h,q,$),z=Te(ue);if(z+c<=l)return{messages:ue,compressed:!0,compacted:!0,tokensRemoved:m-z};w=q}}catch{}let R=(f-l)/l,_=w.map(C=>Ut(C,"light")),k=tt(h,_,$),E=Te(k);if(E+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-E};if(_=w.map(C=>Ut(C,"medium")),k=tt(h,_,$),E=Te(k),E+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-E};if(_=w.map(C=>Ut(C,"aggressive")),k=tt(h,_,$),E=Te(k),E+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-E};for(;_.length>0&&E+c>u;){let C=_.shift();E-=yt(C)}return k=tt(h,_,$),E=Te(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-E}}function tt(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function gu(t,e){if(!t)return"";if(nt(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
|
+
`),r=Math.floor(n*.6),a=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
|
+
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
55
|
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
56
56
|
|
|
57
|
-
... (${
|
|
57
|
+
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
58
|
|
|
59
|
-
`;return c+m+u}var
|
|
60
|
-
`);g
|
|
59
|
+
`;return c+m+u}var $u=6;function yu(t,e){let s=Sn(),n=vn(e),o=Math.floor(s*.5)-n,r=Te(t),a=null,c=0;t.length>0&&t[0].role==="system"&&(a=t[0],c=1);let l=Math.max(c,t.length-$u),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Ut(p,"aggressive")),m=tt(a,f,d),h=Te(m);for(;f.length>0&&h>o;){let p=f.shift();h-=yt(p)}return m=tt(a,f,d),h=Te(m),{messages:m,tokensRemoved:r-h}}Dr.exports={estimateTokens:nt,estimateMessageTokens:yt,estimateMessagesTokens:Te,estimateDeltaTokens:du,estimateToolsTokens:vn,serializeMessage:uu,getMessageCacheKey:Pr,getContextWindow:Sn,getUsage:fu,compressMessage:Ut,compressToolResult:jr,fitToContext:hu,forceCompress:yu,truncateFileContent:gu,invalidateTokenRatioCache:lu,COMPRESSION_THRESHOLD:Lr,SAFETY_MARGIN:qr,KEEP_RECENT:Ir}});var Br=N((Lg,Wr)=>{var Fr=require("axios"),{BaseProvider:wu}=gt(),{serializeMessage:Pg}=Ce(),Ur={"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}},Es=class extends wu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ur,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Fr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Fr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{g+=w.toString();let $=g.split(`
|
|
60
|
+
`);g=$.pop()||"";for(let x of $){let R=x.trim();if(!R||!R.startsWith("data: "))continue;let _=R.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(_)}catch{continue}let E=k.choices?.[0]?.delta;if(E&&(E.content&&(c(E.content),h+=E.content),E.tool_calls))for(let C of E.tool_calls){let A=C.index??0;p[A]||(p[A]={id:C.id||"",name:"",arguments:""}),C.id&&(p[A].id=C.id),C.function?.name&&(p[A].name+=C.function.name),C.function?.arguments&&(p[A].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Wr.exports={OpenAIProvider:Es,OPENAI_MODELS:Ur}});var Kr=N((Ig,Gr)=>{var Hr=require("axios"),{BaseProvider:bu}=gt(),{serializeMessage:qg}=Ce(),zr={"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}},xu="2023-06-01",Cs=class extends bu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||zr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||xu}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
61
61
|
|
|
62
|
-
`:"")+
|
|
63
|
-
`);
|
|
64
|
-
`);g
|
|
65
|
-
`)};return
|
|
66
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw
|
|
62
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(o);this._messageStringCache.set(a,r),this._messageFormatCache.set(o,r)}n.push(r)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await Hr.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(s);m.length>0&&(f.tools=m);let h;try{h=await Hr.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let w="",$=[],x=-1,R="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",_=>{R+=_.toString();let k=R.split(`
|
|
63
|
+
`);R=k.pop()||"";for(let E of k){let C=E.trim();if(C.startsWith("data: ")){let A=C.slice(6),D;try{D=JSON.parse(A)}catch{continue}switch(D.type){case"content_block_start":{let q=D.content_block;q?.type==="tool_use"&&(x=$.length,$.push({id:q.id,name:q.name,inputJson:""}));break}case"content_block_delta":{let q=D.delta;q?.type==="text_delta"&&q.text&&(l(q.text),w+=q.text),q?.type==="input_json_delta"&&q.partial_json!==void 0&&x>=0&&($[x].inputJson+=q.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:w,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",_=>{n.signal?.aborted||g(new Error(`Stream error: ${_.message}`))}),h.data.on("end",()=>{p({content:w,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};Gr.exports={AnthropicProvider:Cs,ANTHROPIC_MODELS:zr}});var Vr=N((Dg,Xr)=>{var Jr=require("axios"),{BaseProvider:_u}=gt(),{serializeMessage:jg}=Ce(),Yr={"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}},Ts=class extends _u{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Yr,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Jr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Jr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{g+=w.toString();let $=g.split(`
|
|
64
|
+
`);g=$.pop()||"";for(let x of $){let R=x.trim();if(!R||!R.startsWith("data: "))continue;let _=R.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(_)}catch{continue}let E=k.choices?.[0]?.delta;if(E&&(E.content&&(c(E.content),h+=E.content),E.tool_calls))for(let C of E.tool_calls){let A=C.index??0;p[A]||(p[A]={id:C.id||"",name:"",arguments:""}),C.id&&(p[A].id=C.id),C.function?.name&&(p[A].name+=C.function.name),C.function?.arguments&&(p[A].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};Xr.exports={GeminiProvider:Ts,GEMINI_MODELS:Yr}});var ei=N((Fg,Zr)=>{var En=require("axios"),{BaseProvider:ku}=gt(),Qr="http://localhost:11434",Rs=class extends ku{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Qr,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 En.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),a=32768;try{let c=await En.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};a=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(a*.1)),contextWindow:a}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
65
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await En.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),a;try{a=await En.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
66
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Zr.exports={LocalProvider:Rs,DEFAULT_LOCAL_URL:Qr}});var wt=N((Ug,ai)=>{var st=require("fs"),As=require("path"),ti={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:{}},Cn=[],Je={};function vu(t,e,s,n){if(Cn.push({provider:t,model:e,input:s,output:n}),Je[t]!==void 0){let o=ri(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
67
|
+
`)}}function Os(t,e){let s=ti[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ni(t){let e=Os(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function si(){let t={};for(let r of Cn){let a=`${r.provider}:${r.model}`;t[a]||(t[a]={provider:r.provider,model:r.model,input:0,output:0}),t[a].input+=r.input,t[a].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:ni(r)})),s=e.reduce((r,a)=>r+a.cost,0),n=e.reduce((r,a)=>r+a.input,0),o=e.reduce((r,a)=>r+a.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Su(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=si();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let a=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${a}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
68
|
+
`)}function Eu(t,e,s,n){let o=Os(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Cu(){Cn=[]}function Tu(t,e){Je[t]=e}function Ru(t){delete Je[t]}function Au(){return{...Je}}function oi(t){let e=0;for(let s of Cn)s.provider===t&&(e+=ni(s));return e}function ri(t){let e=oi(t),s=Je[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function ii(){let t=As.join(process.cwd(),".nex","config.json");if(st.existsSync(t))try{let e=JSON.parse(st.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Je={...e.costLimits})}catch{}}function Ou(){let t=As.join(process.cwd(),".nex"),e=As.join(t,"config.json"),s={};if(st.existsSync(e))try{s=JSON.parse(st.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Je,st.existsSync(t)||st.mkdirSync(t,{recursive:!0}),st.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Mu(){Je={}}ii();ai.exports={PRICING:ti,trackUsage:vu,getSessionCosts:si,formatCosts:Su,formatCostHint:Eu,resetCosts:Cu,getPricing:Os,setCostLimit:Tu,removeCostLimit:Ru,getCostLimits:Au,getProviderSpend:oi,checkBudget:ri,loadCostLimits:ii,saveCostLimits:Ou,resetCostLimits:Mu}});var Tn=N((Wg,ci)=>{var Wt=fe(),Nu={"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 Pu(){return Wt.getActiveModel()}function Lu(t){return Wt.setActiveModel(t)}function qu(){return Wt.getModelNames()}function Iu(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 ju(t,e){let{C:s}=re(),{Spinner:n}=re(),o=new n("Thinking...");o.start();let r=!0,a="";try{let c=await Wt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
69
|
+
`),c}catch(c){throw o.stop(),c}}async function Du(t,e){return Wt.callChat(t,e)}ci.exports={MODELS:Nu,getActiveModel:Pu,setActiveModel:Lu,getModelNames:qu,callOllamaStream:ju,callOllama:Du,parseToolArgs:Iu}});var di=N((Bg,ui)=>{var Rn=require("path"),{C:b}=re(),{confirm:Fu,getAutoConfirm:Uu}=Ae(),li=2e3;function Bt(t,e){let s=t.split(`
|
|
70
70
|
`),n=e.split(`
|
|
71
|
-
`),
|
|
72
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let
|
|
73
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=
|
|
74
|
-
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let
|
|
75
|
-
`),n=
|
|
76
|
-
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let a=
|
|
77
|
-
`)}function
|
|
78
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}${
|
|
79
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let
|
|
80
|
-
`),r=
|
|
81
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let a=[`${
|
|
82
|
-
`).filter(Boolean).map(e=>{let
|
|
83
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
${
|
|
71
|
+
`),o=[],r=s.length,a=n.length;if(r>li||a>li){for(let f of s)o.push({type:"remove",line:f});for(let f of n)o.push({type:"add",line:f});return o}let c=Array.from({length:r+1},()=>new Array(a+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=a;m++)s[f-1]===n[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=a,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===n[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function Wu(t,e,s,n=3){console.log(`
|
|
72
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Bt(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${b.gray} (no changes)${b.reset}`);return}let a=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);a>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=a;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${b.red} - ${u.line}${b.reset}`);break;case"add":console.log(`${b.green} + ${u.line}${b.reset}`);break;default:console.log(`${b.gray} ${u.line}${b.reset}`)}}c<o.length&&console.log(`${b.gray} ...${b.reset}`),console.log()}function Bu(t,e,s){console.log(`
|
|
73
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Bt(e,s),o=0;for(let a of n)a.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let r=0;for(let a of n){if(r>=30){console.log(`${b.gray} ...(${o-r} more changes)${b.reset}`);break}switch(a.type){case"remove":console.log(`${b.red} - ${a.line}${b.reset}`),r++;break;case"add":console.log(`${b.green} + ${a.line}${b.reset}`),r++;break;default:r>0&&console.log(`${b.gray} ${a.line}${b.reset}`)}}console.log()}function Hu(t,e){console.log(`
|
|
74
|
+
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
75
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function zu(t){return Uu()?!0:Fu(` ${t}?`)}function Gu(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
76
|
+
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let a=Bt(e,s),c=[],l=0;for(;l<a.length;)if(a[l].type==="same")c.push({left:a[l].line,right:a[l].line,type:"same"}),l++;else if(a[l].type==="remove"){let h=[];for(;l<a.length&&a[l].type==="remove";)h.push(a[l].line),l++;let p=[];for(;l<a.length&&a[l].type==="add";)p.push(a[l].line),l++;let g=Math.max(h.length,p.length);for(let w=0;w<g;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",type:"changed"})}else a[l].type==="add"&&(c.push({left:"",right:a[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${b.gray}(no changes)${b.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=p?h.substring(0,p):h+" ".repeat(p-g.length)};d>0&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${b.gray}${m(p.left,r)}${b.reset}\u2502${b.gray}${m(p.right,r)}${b.reset}`);else{let g=p.left?`${b.red}${m(p.left,r)}${b.reset}`:`${m("",r)}`,w=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${w}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${b.reset}
|
|
77
|
+
`)}function Ku(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,a=n.annotations||[],c=Rn.isAbsolute(t)?Rn.relative(process.cwd(),t):t,l=Bt(e,s),u=1,d=1;for(let _ of l)_.type==="same"?(_.oldLine=u++,_.newLine=d++):_.type==="remove"?(_.oldLine=u++,_.newLine=null):(_.oldLine=null,_.newLine=d++);let f=0,m=0;for(let _ of l)_.type==="add"?f++:_.type==="remove"&&m++;if(console.log(`
|
|
78
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),f===0&&m===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
79
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let _=a.filter(A=>A.severity==="error").length,k=a.filter(A=>A.severity==="warn").length,E=a.filter(A=>A.severity==="info").length,C=[];_>0&&C.push(`${b.red}${_} error${_!==1?"s":""}${b.dim}`),k>0&&C.push(`${b.yellow}${k} warning${k!==1?"s":""}${b.dim}`),E>0&&C.push(`${b.cyan}${E} info${E!==1?"s":""}${b.dim}`),h.push(`found ${C.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((_,k)=>{_.type!=="same"&&g.push(k)});let w=[],$=null,x=null;for(let _ of g){let k=Math.max(0,_-r),E=Math.min(l.length-1,_+r);$===null?($=k,x=E):(k<=x+1||(w.push([$,x]),$=k),x=E)}$!==null&&w.push([$,x]);let R=" ";for(let _=0;_<w.length;_++){_>0&&console.log(`${R}${b.dim}\xB7\xB7\xB7${b.reset}`);let[k,E]=w[_];for(let C=k;C<=E;C++){let A=l[C],D=A.newLine!=null?A.newLine:A.oldLine,q=String(D).padStart(4),ue=A.type!=="remove"?a.filter(z=>z.line===A.newLine):[];A.type==="remove"?console.log(`${R}${b.red}${q} -${A.line}${b.reset}`):A.type==="add"?console.log(`${R}${b.green}${q} +${A.line}${b.reset}`):console.log(`${R}${b.dim}${q}${b.reset} ${A.line}`);for(let z of ue){let W=b.cyan,te="\u2139";z.severity==="error"?(W=b.red,te="\u2716"):z.severity==="warn"&&(W=b.yellow,te="\u26A0"),console.log(`${R} ${W}${te} ${z.message}${b.reset}`)}}}console.log()}function Ju(t,e,s={}){let n=Rn.isAbsolute(t)?Rn.relative(process.cwd(),t):t,o=e.split(`
|
|
80
|
+
`),r=s.annotations||[];console.log(`
|
|
81
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${b.red}${d} error${d!==1?"s":""}${b.dim}`),f>0&&h.push(`${b.yellow}${f} warning${f!==1?"s":""}${b.dim}`),m>0&&h.push(`${b.cyan}${m} info${m!==1?"s":""}${b.dim}`),a.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${a.join(", ")}${b.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=r.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,w="\u2139";p.severity==="error"?(g=b.red,w="\u2716"):p.severity==="warn"&&(g=b.yellow,w="\u26A0"),console.log(`${l} ${g}${w} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}ui.exports={diffLines:Bt,showEditDiff:Wu,showWriteDiff:Bu,showNewFilePreview:Hu,confirmFileChange:zu,showSideBySideDiff:Gu,showClaudeDiff:Ku,showClaudeNewFile:Ju}});var ot=N((Hg,pi)=>{var fi=require("util").promisify(require("child_process").exec),Yu=require("util").promisify(require("child_process").execFile),{C:ne}=re();async function Ms(t){try{let{stdout:e}=await fi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function An(...t){try{let{stdout:e}=await Yu("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Xu(){return await Ms("git rev-parse --is-inside-work-tree")==="true"}async function Vu(){return await Ms("git branch --show-current")}async function Ns(){try{let{stdout:t}=await fi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
82
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function On(t=!1){return await Ms(`git diff ${t?"--cached":""}`)||""}async function Ps(){return(await Ns()).map(e=>e.file)}async function mi(){let t=await Ps();if(t.length===0)return null;let e=await On(),n=await On(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function Qu(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await An("checkout","-b",s)!==null?s:null}async function Zu(t){return await An("add","-A"),await An("commit","-m",t)?await An("rev-parse","--short","HEAD"):null}async function ed(){let t=await mi();if(!t)return`${ne.dim}No changes${ne.reset}`;let e=[];e.push(`
|
|
84
|
+
${ne.bold}${ne.cyan}Git Diff Summary:${ne.reset}`),e.push(` ${ne.green}+${t.stats.additions}${ne.reset} ${ne.red}-${t.stats.deletions}${ne.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
|
+
${ne.bold}${ne.cyan}Files:${ne.reset}`);for(let s of t.files.slice(0,20))e.push(` ${ne.dim}${s}${ne.reset}`);return t.files.length>20&&e.push(` ${ne.dim}...+${t.files.length-20} more${ne.reset}`),e.push(`
|
|
86
|
+
${ne.bold}${ne.cyan}Suggested message:${ne.reset}`),e.push(` ${ne.cyan}${t.summary}${ne.reset}
|
|
87
87
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
89
|
-
...(truncated)`:
|
|
88
|
+
`)}async function td(){return(await Ns()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function nd(){let t=await Ps();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 On();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
89
|
+
...(truncated)`:s;e.push(`
|
|
90
90
|
DIFF:
|
|
91
91
|
${n}`)}return e.join(`
|
|
92
|
-
`)}
|
|
92
|
+
`)}pi.exports={isGitRepo:Xu,getCurrentBranch:Vu,getStatus:Ns,getDiff:On,getChangedFiles:Ps,analyzeDiff:mi,createBranch:Qu,commit:Zu,formatDiffSummary:ed,getDiffContext:nd,getMergeConflicts:td}});var xt=N((zg,hi)=>{var Ls=require("fs").promises,sd=50,Ie=[],bt=[];function od(t,e,s,n){for(Ie.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Ie.length>sd;)Ie.shift();bt.length=0}async function rd(){if(Ie.length===0)return null;let t=Ie.pop();if(t.oldContent===null)try{await Ls.unlink(t.filePath)}catch{}else await Ls.writeFile(t.filePath,t.oldContent,"utf-8");return bt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function id(){if(bt.length===0)return null;let t=bt.pop();return await Ls.writeFile(t.filePath,t.newContent,"utf-8"),Ie.push(t),{tool:t.tool,filePath:t.filePath}}function ad(t=10){return Ie.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function cd(){return Ie.length}function ld(){return bt.length}function ud(){Ie.length=0,bt.length=0}hi.exports={recordChange:od,undo:rd,redo:id,getHistory:ad,getUndoCount:cd,getRedoCount:ld,clearHistory:ud}});var Ht=N((Gg,xi)=>{var xe=require("fs"),_t=require("path"),ge=[];function qs(){return _t.join(process.cwd(),".nex","skills")}function gi(){return _t.join(process.cwd(),".nex","config.json")}function dd(){let t=qs();return xe.existsSync(t)||xe.mkdirSync(t,{recursive:!0}),t}function Is(){let t=gi();if(!xe.existsSync(t))return[];try{let e=JSON.parse(xe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function $i(t){let e=gi(),s={};if(xe.existsSync(e))try{s=JSON.parse(xe.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=_t.dirname(e);xe.existsSync(n)||xe.mkdirSync(n,{recursive:!0}),xe.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function yi(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 wi(t){try{let e=xe.readFileSync(t,"utf-8").trim();return e?{name:_t.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function bi(t){try{let e=require(t),{valid:s,errors:n}=yi(e,t);return s?{name:e.name||_t.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
93
93
|
${n.join(`
|
|
94
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
94
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function fd(){ge=[];let t=qs();if(!xe.existsSync(t))return ge;let e=Is(),s;try{s=xe.readdirSync(t)}catch{return ge}for(let n of s){let o=_t.join(t,n),r;try{r=xe.statSync(o)}catch{continue}if(!r.isFile())continue;let a=null;n.endsWith(".md")?a=wi(o):n.endsWith(".js")&&(a=bi(o)),a&&(a.enabled=!e.includes(a.name),ge.push(a))}return ge}function md(){let t=[];for(let e of ge)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
95
95
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
96
96
|
${t.join(`
|
|
97
97
|
|
|
98
|
-
`)}`}function
|
|
98
|
+
`)}`}function pd(){let t=[];for(let e of ge)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function hd(){let t=[];for(let e of ge)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 gd(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ge)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 $d(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ge)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(a){console.error(`Skill command error (${e}): ${a.message}`)}return!0}}return!1}function yd(){return ge.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 wd(t){let e=ge.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Is().filter(n=>n!==t);return $i(s),!0}function bd(t){let e=ge.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Is();return s.includes(t)||(s.push(t),$i(s)),!0}function xd(){return ge}xi.exports={initSkillsDir:dd,loadAllSkills:fd,getSkillInstructions:md,getSkillCommands:pd,getSkillToolDefinitions:hd,routeSkillCall:gd,handleSkillCommand:$d,listSkills:yd,enableSkill:wd,disableSkill:bd,getLoadedSkills:xd,_getSkillsDir:qs,_validateScriptSkill:yi,_loadMarkdownSkill:wi,_loadScriptSkill:bi}});var Nn=N((Kg,Ci)=>{var{spawn:_d}=require("child_process"),kd=require("path"),_i=require("fs"),je=new Map;function vd(){return kd.join(process.cwd(),".nex","config.json")}function js(){let t=vd();if(!_i.existsSync(t))return{};try{return JSON.parse(_i.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Mn(t,e,s={},n=1e4){return new Promise((o,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:s})+`
|
|
99
99
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
|
|
100
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===a){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):
|
|
101
|
-
`):JSON.stringify(
|
|
102
|
-
Available tools: ${d.join(", ")}`}}if(!
|
|
100
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===a){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function ki(t,e){if(je.has(t))return je.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let a of s)process.env[a]&&(n[a]=process.env[a]);let o=_d(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Mn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await Mn(o,"tools/list",{});return r.tools=a&&a.tools||[],je.set(t,r),r}catch(a){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function vi(t){let e=je.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return je.delete(t),!0}function Sd(){for(let[t]of je)vi(t)}async function Si(t,e,s={}){let n=je.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Mn(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
101
|
+
`):JSON.stringify(o)}function Ei(){let t=[];for(let[e,s]of je)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 Ed(){return Ei().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Cd(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 Si(n,o,e)}function Td(){let t=js();return Object.entries(t).map(([e,s])=>{let n=je.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Rd(){let t=js(),e=[];for(let[s,n]of Object.entries(t))try{let o=await ki(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Ci.exports={loadMCPConfig:js,sendRequest:Mn,connectServer:ki,disconnectServer:vi,disconnectAll:Sd,callTool:Si,getAllTools:Ei,getMCPToolDefinitions:Ed,routeMCPCall:Cd,listServers:Td,connectAll:Rd}});var Ds=N((Jg,Oi)=>{var{getSkillToolDefinitions:Ad}=Ht(),{getMCPToolDefinitions:Od}=Nn(),Pn=new Map;function Ti(){let{TOOL_DEFINITIONS:t}=De();return[...t,...Ad(),...Od()]}function Ri(t){if(Pn.has(t))return Pn.get(t);let s=Ti().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Pn.set(t,n),n}function Md(){Pn.clear()}function Ln(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Ai(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Ai(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let a=1;a<=n;a++)o[r][a]=t[r-1]===e[a-1]?o[r-1][a-1]:1+Math.min(o[r-1][a],o[r][a-1],o[r-1][a-1]);return o[s][n]}function Nd(t,e){let s=Ri(t);if(s===null){let d=Ti().map(m=>m.function.name),f=Ln(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Ln(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=Ln(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||a.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return a.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
103
103
|
`+a.map(u=>` - ${u}`).join(`
|
|
104
104
|
`)+`
|
|
105
105
|
|
|
106
|
-
Expected parameters: ${JSON.stringify(
|
|
106
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Oi.exports={validateToolArgs:Nd,closestMatch:Ln,levenshtein:Ai,getCachedSchema:Ri,clearSchemaCache:Md}});var Li=N((Yg,Pi)=>{var{levenshtein:qn}=Ds(),Pd=200,Ld=.3,qd=2;function Fs(t){return t.replace(/\r\n/g,`
|
|
107
107
|
`).replace(/\r/g,`
|
|
108
|
-
`).replace(/\t/g," ".repeat(
|
|
109
|
-
`).map(e=>{let
|
|
110
|
-
`)}function
|
|
111
|
-
`),r=
|
|
108
|
+
`).replace(/\t/g," ".repeat(qd)).split(`
|
|
109
|
+
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
110
|
+
`)}function Id(t,e){if(t.includes(e))return e;let s=Fs(t),n=Fs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
111
|
+
`),r=s.split(`
|
|
112
112
|
`),a=n.split(`
|
|
113
|
-
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return
|
|
114
|
-
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return
|
|
115
|
-
`),
|
|
116
|
-
`).length;return
|
|
117
|
-
`),u=
|
|
118
|
-
`),h=
|
|
119
|
-
`),n=[],
|
|
120
|
-
`).filter(Boolean),
|
|
121
|
-
HINT: Connection refused on ${e.host}:${
|
|
122
|
-
HINT: Auth failed using ${
|
|
113
|
+
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return o.slice(u,u+a.length).join(`
|
|
114
|
+
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function jd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
115
|
+
`),o=e.split(`
|
|
116
|
+
`).length;return s.length===0||o===0?null:o===1?Dd(s,e):Ud(s,e,o)}function Mi(t){return Math.max(1,Math.floor(t/Pd))}function Ni(t,e){return t<=Math.ceil(e*Ld)}function Dd(t,e){let s=e.trim(),n=Mi(t.length),o=null,r=1/0;for(let a=0;a<t.length;a+=n){let c=t[a];if(!c.trim())continue;let l=qn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:a+1})}return o&&n>1&&(o=Fd(t,s,o,n)||o,r=o.distance),Ni(r,e.length)?o:null}function Fd(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),a=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=qn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Ud(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Mi(n),r=null,a=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
117
|
+
`),u=qn(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Wd(t,e,r,o,s,n)||r,a=r.distance),Ni(a,e.length)?r:null}function Wd(t,e,s,n,o,r){let a=s.line-1,c=Math.max(0,a-n),l=Math.min(r-1,a+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
118
|
+
`),h=qn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Pi.exports={normalizeWhitespace:Fs,fuzzyFindText:Id,findMostSimilar:jd}});var Ii=N((Vg,qi)=>{var{C:Xg}=re(),Bd=[{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}],Hd=[{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 zd(t,e){let s=e.split(`
|
|
119
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],c=r+1;for(let l of Bd)l.regex.test(a)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Hd)l.ext&&!l.ext.includes(o)||l.regex.test(a)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}qi.exports={runDiagnostics:zd}});var Bs=N((Qg,Fi)=>{var Gd=require("fs").promises,ji=require("path"),{exec:Kd}=require("util").promisify(require("child_process").exec),kt=[],Ws=null,In=!1,Us=0,Jd=6e4;function Di(t){return!(kt.length===0||Ws!==t||Date.now()-Us>Jd)}async function Yd(t){if(!In&&!Di(t)){In=!0,Ws=t;try{try{let{stdout:n}=await Kd("rg --files",{cwd:t,timeout:5e3});kt=n.split(`
|
|
120
|
+
`).filter(Boolean),Us=Date.now(),In=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Gd.readdir(n,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let c=o?`${o}/${a.name}`:a.name;a.isDirectory()?await s(ji.join(n,a.name),c):e.push(c)}};await s(t,""),kt=e,Us=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{In=!1}}}function Xd(){return kt}function Vd(){return Ws}function Qd(t){return kt.filter(e=>ji.basename(e)===t)}function Zd(t){let e=t.toLowerCase();return kt.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Fi.exports={refreshIndex:Yd,getFileIndex:Xd,getIndexedCwd:Vd,findFileInIndex:Qd,searchIndex:Zd,isIndexValid:Di}});var vt=N((Zg,Hi)=>{var jn=require("fs"),Fn=require("path"),Hs=require("os"),{execFile:ef}=require("child_process"),{promisify:tf}=require("util"),zs=tf(ef),nf=Fn.join(".nex","servers.json"),Dn=Fn.join(Hs.tmpdir(),"nex-ssh-sockets");function sf(){return Fn.join(process.cwd(),nf)}function Ui(){let t=sf();if(!jn.existsSync(t))return{};try{return JSON.parse(jn.readFileSync(t,"utf-8"))}catch{return{}}}function of(t){let e=Ui();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 rf(){jn.existsSync(Dn)||jn.mkdirSync(Dn,{recursive:!0})}function Wi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Hs.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),rf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Fn.join(Dn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Bi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Hs.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function af(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Wi(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:a,stderr:c}=await zs("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:a||"",stderr:c||"",exitCode:0}}catch(a){let c=typeof a.code=="number"?a.code:1,l=(a.stderr||a.message||"").toString();return{stdout:(a.stdout||"").toString(),stderr:l,exitCode:c,error:Un(l,t)}}}async function cf(t,e,s,{timeout:n=12e4}={}){let o=Bi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:a,stderr:c}=await zs("scp",o,{timeout:n,maxBuffer:1048576});return a||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(Un(c,t)||c)}}async function lf(t,e,s,{timeout:n=12e4}={}){let o=Bi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:a,stderr:c}=await zs("scp",o,{timeout:n,maxBuffer:1048576});return a||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(Un(c,t)||c)}}function Un(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
121
|
+
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
122
|
+
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
123
123
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
124
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
125
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
126
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
127
|
-
`,"utf-8")}
|
|
126
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function uf(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",a=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${a}`}Hi.exports={loadServerProfiles:Ui,resolveProfile:of,buildSSHArgs:Wi,sshExec:af,scpUpload:cf,scpDownload:lf,enrichSSHError:Un,formatProfile:uf,SSH_SOCKET_DIR:Dn}});var Js=N((e$,Gi)=>{var zt=require("fs"),Gs=require("path"),df=Gs.join(".nex","deploy.json");function Ks(){return Gs.join(process.cwd(),df)}function zi(){let t=Ks();if(!zt.existsSync(t))return{};try{return JSON.parse(zt.readFileSync(t,"utf-8"))}catch{return{}}}function ff(t){let e=zi();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 mf(t){let e=Gs.join(process.cwd(),".nex");zt.existsSync(e)||zt.mkdirSync(e,{recursive:!0}),zt.writeFileSync(Ks(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}Gi.exports={loadDeployConfigs:zi,resolveDeployConfig:ff,saveDeployConfigs:mf,getDeployConfigPath:Ks}});var Kt=N((t$,Yi)=>{var Ys=null,Fe=null,Gt=null,Ki=`Playwright is not installed. Install with:
|
|
128
128
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function
|
|
130
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await
|
|
131
|
-
`)}function
|
|
129
|
+
Then restart nex-code.`;function Ji(){if(Gt!==null)return Gt;try{require("playwright"),Gt=!0}catch{Gt=!1}return Gt}async function Wn(){if(!Ji())throw new Error(Ki);return Ys||(Ys=require("playwright")),(!Fe||!Fe.isConnected())&&(Fe=await Ys.chromium.launch({headless:!0})),Fe}async function pf(){if(Fe){try{await Fe.close()}catch{}Fe=null}}process.on("exit",()=>{if(Fe)try{Fe.close()}catch{}});async function hf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Wn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),a=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
130
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function gf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let a=await(await Wn()).newPage();try{await a.setViewportSize({width:e,height:s}),await a.goto(t,{waitUntil:"networkidle",timeout:o});let c=await a.screenshot({type:"png",fullPage:n}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await a.title(),url:a.url()}}finally{await a.close()}}async function $f(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Wn()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let a=await r.title();return`Clicked \u2014 now at: ${r.url()} (${a})`}finally{await r.close()}}async function yf(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let a=await(await Wn()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await a.fill(e,String(s)),n&&(await a.keyboard.press("Enter"),await a.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${a.url()}`:"Not submitted."}`}finally{await a.close()}}Yi.exports={isPlaywrightAvailable:Ji,browserNavigate:hf,browserScreenshot:gf,browserClick:$f,browserFill:yf,closeBrowser:pf,INSTALL_MSG:Ki}});var Bn=N((n$,Xi)=>{var{C:X}=re(),Yt="",pe=[],Jt=0,rt=null;function wf(t){rt=t}function bf(t,e){Yt=t,pe=[],Jt=0;for(let n of e){Jt++;let o=`t${Jt}`;pe.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Jt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=pe.map(n=>({...n}));return rt&&rt("create",{name:t,tasks:s}),s}function xf(t,e,s){let n=pe.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),rt&&rt("update",{id:t,status:e,result:s}),{...n}):null}function _f(){return{name:Yt,tasks:pe.map(t=>({...t}))}}function kf(){Yt="",pe=[],Jt=0,rt&&rt("clear",{})}function vf(){return pe.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=pe.find(n=>n.id===e);return s&&s.status==="done"}))}function Sf(){if(pe.length===0)return`${X.dim}No active tasks${X.reset}`;let t=[];Yt&&(t.push(` ${X.bold}${X.cyan}Tasks: ${Yt}${X.reset}`),t.push(` ${X.dim}${"\u2500".repeat(40)}${X.reset}`));for(let o of pe){let r,a;switch(o.status){case"done":r="\u2713",a=X.green;break;case"in_progress":r="\u2192",a=X.cyan;break;case"failed":r="\u2717",a=X.red;break;default:r="\xB7",a=X.dim}let c=o.dependsOn.length>0?` ${X.dim}(after: ${o.dependsOn.join(", ")})${X.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${a}${r}${X.reset} ${X.bold}${o.id}${X.reset} ${u.padEnd(40)} ${a}${l}${X.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${X.dim}\u2192 ${d}${X.reset}`)}}let e=pe.filter(o=>o.status==="done").length,s=pe.filter(o=>o.status==="failed").length,n=pe.length;return t.push(` ${X.dim}${"\u2500".repeat(40)}${X.reset}`),t.push(` ${X.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${X.reset}`),t.join(`
|
|
131
|
+
`)}function Ef(){return pe.length>0&&pe.some(t=>t.status==="pending"||t.status==="in_progress")}Xi.exports={createTasks:bf,updateTask:xf,getTaskList:_f,clearTasks:kf,getReadyTasks:vf,renderTaskList:Sf,setOnChange:wf,hasActiveTasks:Ef}});var Vs=N((s$,Qi)=>{var{getActiveModel:Cf,getActiveProviderName:Tf}=fe(),Xt={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},Vt={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},Qt={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Oe={};function Vi(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Oe=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Oe={}}}Vi();function Xs(){let e=Cf()?.id,s=Tf();return e&&Oe[e]?Oe[e]:s&&Oe[`${s}:*`]?Oe[`${s}:*`]:e&&Vt[e]?Vt[e]:s&&Qt[s]?Qt[s]:"full"}function Rf(t,e){return t&&Oe[t]?Oe[t]:e&&Oe[`${e}:*`]?Oe[`${e}:*`]:t&&Vt[t]?Vt[t]:e&&Qt[e]?Qt[e]:"full"}function Af(t,e){let s=e||Xs();if(s==="full"||!Xt[s])return t;let n=new Set(Xt[s]);return t.filter(o=>n.has(o.function.name))}function Of(){let t=Xs(),e=Xt[t]?Xt[t].length:"all";return{tier:t,toolCount:e}}Qi.exports={filterToolsForModel:Af,getActiveTier:Xs,getModelTier:Rf,getTierInfo:Of,TIERS:Xt,MODEL_TIERS:Vt,PROVIDER_DEFAULT_TIER:Qt,loadConfigOverrides:Vi}});var ua=N((r$,la)=>{var{callStream:Mf,getActiveProviderName:zn,getActiveModelId:Nf,getConfiguredProviders:Pf,getProvider:Zi,getActiveProvider:ea,parseModelSpec:ta}=fe(),{parseToolArgs:Lf}=Tn(),{filterToolsForModel:qf,getModelTier:Hn}=Vs(),{trackUsage:If}=wt(),{MultiProgress:jf,C:o$}=re(),Df=15,na=5,sa=3,Gn=new Map;function Ff(t,e){let s=Gn.get(t);return s&&s!==e?!1:(Gn.set(t,e),!0)}function Qs(t){Gn.delete(t)}function Zs(){Gn.clear()}function oa(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 ra(t,e,s){let n;for(let o=0;o<=sa;o++)try{return await Mf(t,e,s)}catch(r){if(n=r,o<sa&&oa(r)){let a=Math.min(2e3*Math.pow(2,o),15e3);await new Promise(c=>setTimeout(c,a).unref());continue}throw r}throw n}var Uf=new Set(["ask_user","task_list","spawn_agents"]),Wf=new Set(["write_file","edit_file","patch_file"]),Bf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Hf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ia(t){return Hf.test(t)?"full":Bf.test(t)?"essential":"standard"}function aa(t){let e=Pf(),s=zn(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(Hn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var zf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function eo(t){if(t.model){let{provider:o,model:r}=ta(t.model),a=o?Zi(o):ea(),c=o||zn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Hn(r,c);return{provider:c,model:r,tier:l}}}let e=ia(t.task),s=zf[e];if(s){let{provider:o,model:r}=ta(s),a=o?Zi(o):ea(),c=o||zn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Hn(r,c);return{provider:c,model:r,tier:l}}}let n=aa(e);if(n){let o=Hn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function ca(t,e={}){let s=Math.min(t.max_iterations||10,Df),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},a=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
132
132
|
|
|
133
133
|
TASK: ${t.task}
|
|
134
134
|
${t.context?`
|
|
@@ -150,150 +150,150 @@ TOOL STRATEGY:
|
|
|
150
150
|
ERROR RECOVERY:
|
|
151
151
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
152
152
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
153
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
154
|
-
`)}let
|
|
155
|
-
...(truncated)`:
|
|
156
|
-
`)}catch(r){return
|
|
157
|
-
`);for(let r of
|
|
158
|
-
`);for(let a of r)if(a.startsWith("#")){let c=a.replace(/^#+\s*/,"");for(let l of
|
|
153
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=eo(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=De(),g=qf(h.filter($=>!Uf.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
154
|
+
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let x=await ra(l,g,w);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let A=x.usage.prompt_tokens||0,D=x.usage.completion_tokens||0;r.input+=A,r.output+=D;let q=d||zn(),ue=f||Nf();If(q,ue,A,D)}let R=x.content||"",_=x.tool_calls,k={role:"assistant",content:R||""};if(_&&_.length>0&&(k.tool_calls=_),l.push(k),!_||_.length===0){for(let A of a)Qs(A);return{task:t.task,status:"done",result:R||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let E=_.map(A=>{let D=A.function.name,q=Lf(A.function.arguments),ue=A.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!q)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${D}`,tool_call_id:ue});if(Wf.has(D)&&q.path){let z=require("path"),W=z.isAbsolute(q.path)?q.path:z.resolve(process.cwd(),q.path);if(!Ff(W,n))return Promise.resolve({role:"tool",content:`ERROR: File '${q.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:ue});a.add(W)}return o.push(D),p(D,q,{autoConfirm:!0,silent:!0}).then(z=>{let W=String(z??"");return{role:"tool",content:W.length>2e4?W.substring(0,2e4)+`
|
|
155
|
+
...(truncated)`:W,tool_call_id:ue}}).catch(z=>({role:"tool",content:`ERROR: ${z.message}`,tool_call_id:ue}))}),C=await Promise.all(E);l.push(...C),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of a)Qs($);return{task:t.task,status:"done",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let x of a)Qs(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function Gf(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>na)return`ERROR: Max ${na} parallel agents allowed, got ${e.length}`;let s=e.map(r=>eo(r)),n=e.map((r,a)=>{let c=s[a],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${a+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new jf(n);o.start();try{let r=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return ca(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="done"?"done":"error"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),a=await Promise.all(r);o.stop(),Zs();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<a.length;d++){let f=a[d],m=f.status==="done"?"\u2713":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
156
|
+
`)}catch(r){return o.stop(),Zs(),`ERROR: Sub-agent execution failed: ${r.message}`}}la.exports={runSubAgent:ca,executeSpawnAgents:Gf,clearAllLocks:Zs,classifyTask:ia,pickModelForTier:aa,resolveSubAgentModel:eo,isRetryableError:oa,callWithRetry:ra}});var tn=N((i$,ka)=>{var Z=require("fs"),Ue=require("path"),Kf=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 St(){let t=Ue.join(process.cwd(),".nex","brain");return Z.existsSync(t)||Z.mkdirSync(t,{recursive:!0}),t}function da(){return Ue.join(St(),".brain-index.json")}function so(){return Ue.join(St(),".embeddings.json")}function Zt(){let t=Ue.join(process.cwd(),".nex","brain");if(!Z.existsSync(t))return[];try{return Z.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Ue.join(t,e),n=Z.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function en(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
157
|
+
`);for(let r of o){let a=r.match(/^(\w+):\s*(.+)$/);if(!a)continue;let c=a[1].trim(),l=a[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function fa(t){let e=Ue.join(St(),`${t}.md`);if(!Z.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Z.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=en(s);return{name:t,content:s,body:o,frontmatter:n}}function Jf(t,e){let s=Ue.join(St(),`${t}.md`);Z.writeFileSync(s,e,"utf-8"),Vf(t,e),Yf()}function Yf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=so();Z.existsSync(t)&&setImmediate(async()=>{try{await wa()}catch{}})}function Xf(t){let e=Ue.join(St(),`${t}.md`);return Z.existsSync(e)?(Z.unlinkSync(e),Qf(t),!0):!1}function Kn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Kf.has(e))}function oo(t){let e={},{frontmatter:s,body:n}=en(t),o=Array.isArray(s.tags)?s.tags:[];for(let a of o){let c=a.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(n||t).split(`
|
|
158
|
+
`);for(let a of r)if(a.startsWith("#")){let c=a.replace(/^#+\s*/,"");for(let l of Kn(c))e[l]=(e[l]||0)+3}for(let a of Kn(n||t))e[a]=(e[a]||0)+1;return e}function ro(){let t=da();if(!Z.existsSync(t))return{documents:{}};try{return JSON.parse(Z.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function io(t){Z.writeFileSync(da(),JSON.stringify(t,null,2),"utf-8")}function Vf(t,e){let s=ro(),{frontmatter:n}=en(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:oo(e),tags:o,modified:new Date().toISOString()},io(s)}function Qf(t){let e=ro();delete e.documents[t],io(e)}function no(){let t=Zt(),e={documents:{}};for(let s of t){let n=Z.readFileSync(s.path,"utf-8"),{frontmatter:o}=en(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:oo(n),tags:r,modified:s.modified.toISOString()}}return io(e),e}function ma(){let t=ro(),e=Zt();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return no()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return no();return t}function pa(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Kn(t);if(o.length===0)return[];let r=ma(),a=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of o){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,m]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=m*.3)}u>=n&&a.push({name:c,score:u})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}var ha=process.env.NEX_EMBED_MODEL||"nomic-embed-text",to=400,Zf=50;async function ga(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=o.get(n.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(ha.split(":")[0]))}catch{return!1}}async function ao(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,a=JSON.stringify({model:ha,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a)},timeout:3e4},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(m){l(m)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(a),u.end()})}function $a(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let a=0;a<t.length;a++)s+=t[a]*e[a],n+=t[a]*t[a],o+=e[a]*e[a];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function ya(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+to).join(" ");if(s.push({text:o,offset:n}),n+to>=e.length)break;n+=to-Zf}return s}async function wa(){let t=Zt(),e={documents:{}},s=so();if(Z.existsSync(s))try{e=JSON.parse(Z.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=Z.readFileSync(n.path,"utf-8"),a=ya(r),c=[];for(let l of a){let u=await ao(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 Z.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function ba(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=so();if(!Z.existsSync(o))return[];let r;try{r=JSON.parse(Z.readFileSync(o,"utf-8"))}catch{return[]}let a=await ao(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=$a(a,m.embedding);h>d&&(d=h,f=m.text)}d>=n&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function xa(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(n+c+1)}),e.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(n+c+1)}),Object.entries(r).map(([a,c])=>({name:a,score:c})).sort((a,c)=>c.score-a.score).slice(0,o)}async function _a(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=pa(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ga()){let c=await ba(t,{topK:s});r=xa(o,c,{topK:s})}}catch{}return r.map(a=>{let c=fa(a.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:a.name,score:a.score,content:c.content,excerpt:l}})}async function em(t){if(!t||!t.trim())return"";let e=Ue.join(process.cwd(),".nex","brain");if(!Z.existsSync(e)||Zt().length===0)return"";let n;try{n=await _a(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Ce().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let r=25e3,a=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>r){let m=r-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
159
159
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(a.push(`--- ${l.name} (relevance: ${f}) ---
|
|
160
|
-
${u}`),c+=
|
|
160
|
+
${u}`),c+=o(u),c>=r)break}return a.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
161
|
|
|
162
162
|
${a.join(`
|
|
163
163
|
|
|
164
|
-
`)}`}ka.exports={getBrainDir:
|
|
165
|
-
${a.map(l=>
|
|
166
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
164
|
+
`)}`}ka.exports={getBrainDir:St,listDocuments:Zt,readDocument:fa,writeDocument:Jf,removeDocument:Xf,buildIndex:no,getIndex:ma,query:_a,getBrainContext:em,isEmbeddingAvailable:ga,generateEmbedding:ao,buildEmbeddingIndex:wa,semanticQuery:ba,cosineSimilarity:$a,_keywordQuery:pa,_extractKeywords:oo,_chunkText:ya,parseFrontmatter:en,tokenize:Kn,_fuseResults:xa}});var De=N((u$,Pa)=>{var ee=require("fs").promises,va=require("fs"),ye=require("path"),se=require("util").promisify(require("child_process").exec),Sa=require("util").promisify(require("child_process").execFile),{spawnSync:tm}=require("child_process"),co=require("axios"),{isForbidden:nm,isDangerous:sm,isCritical:Ea,confirm:Me}=Ae(),{showClaudeDiff:Jn,showClaudeNewFile:om,showEditDiff:a$,confirmFileChange:nn}=di(),{C:P,Spinner:Oa,getToolSpinnerText:rm}=re(),{isGitRepo:lo,getCurrentBranch:Ca,getStatus:im,getDiff:am}=ot(),{recordChange:Yn}=xt(),{fuzzyFindText:Ta,findMostSimilar:fo}=Li(),{runDiagnostics:sn}=Ii(),{findFileInIndex:cm,getFileIndex:c$}=Bs(),{resolveProfile:Ne,sshExec:Ye,scpUpload:lm,scpDownload:um}=vt(),{resolveDeployConfig:dm,loadDeployConfigs:l$}=Js(),fm=/^(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/,mm=/^ssh\s/,pm=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Xn(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=$e(e);if(s&&await ee.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=ye.extname(t);if(!o)for(let a of n){let c=$e(t+a);if(c&&await ee.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(o){let a=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=$e(a+c);if(l&&await ee.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=ye.basename(t);if(r&&r.length>2)try{let a=cm(r).map(c=>$e(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${ye.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
165
|
+
${a.map(l=>ye.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function hm(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 Ma(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),s.length===0?t:t+`
|
|
167
167
|
|
|
168
|
-
`+
|
|
169
|
-
`)}function Na(t,e,o){let n=uo(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 Ca=!1,tn=null;function am(){tn&&(tn(),tn=null)}async function lo(){if(!Ca){Ca=!0;try{let{stdout:t}=await V("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await V('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await V("git stash pop",{cwd:process.cwd(),timeout:1e4}),await V("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 me(t){let e=pe.isAbsolute(t)?pe.resolve(t):pe.resolve(process.cwd(),t);for(let o of cm)if(o.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.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function en(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,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,n){let a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${a}"`}return r}async function Ta(t,e,o={}){switch(t){case"bash":{let n=e.command,s=Kf(n);if(s){let l=im(n);return`BLOCKED: Command matches forbidden pattern: ${s}${l?`
|
|
170
|
-
HINT: ${
|
|
171
|
-
${
|
|
172
|
-
${
|
|
173
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),a=await
|
|
168
|
+
`+s.join(`
|
|
169
|
+
`)}function Na(t,e,s){let n=fo(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Ra=!1,rn=null;function gm(){rn&&(rn(),rn=null)}async function uo(){if(!Ra){Ra=!0;try{let{stdout:t}=await se("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await se('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await se("git stash pop",{cwd:process.cwd(),timeout:1e4}),await se("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var $m=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function $e(t){let e=ye.isAbsolute(t)?ye.resolve(t):ye.resolve(process.cwd(),t);for(let s of $m)if(s.test(e))return null;return e}var ym=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function on(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${a}"`}return r}async function Aa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=nm(n);if(o){let u=hm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Ea(n):sm(n)){let u=Ea(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
171
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Me(" Execute?"))return"CANCELLED: User declined to execute this command."}let a=process.cwd();try{va.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${P.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${P.reset}`)}let c=mm.test(n.trim())&&!pm.test(n.trim());if(fm.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=tm("sh",["-c",n],{stdio:"inherit",cwd:a});return u.error?`ERROR: ${u.error.message}`:u.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${u.status})`}let l=s.silent?null:new Oa(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await se(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),u||d||"(no output)"}catch(u){l&&l.stop();let d=(u.stderr||u.stdout||u.message||"").toString().substring(0,5e3),f=Ma(d,n);return`EXIT ${u.code||1}
|
|
172
|
+
${f}`}}case"read_file":{let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ee.access(n).then(()=>!0).catch(()=>!1)){let m=await Xn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ye.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
173
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await va.promises.open(n,"r"),{bytesRead:c}=await a.read(r,0,8192,0);await a.close();for(let m=0;m<c;m++)if(r[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await ee.readFile(n,"utf-8");if(!l&&(await ee.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
174
174
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
|
|
175
|
-
`)}case"write_file":{await
|
|
176
|
-
`+d.message:""}`}let r=await
|
|
175
|
+
`)}case"write_file":{await uo();let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await ee.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await ee.readFile(n,"utf-8"));else if(o){r=await ee.readFile(n,"utf-8");let l=await sn(n,e.content);if(Jn(n,r,e.content,{annotations:l}),!await nn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await sn(n,e.content);if(om(n,e.content,{annotations:l}),!await nn("Create"))return"CANCELLED: User declined to create file."}let a=ye.dirname(n);return await ee.access(a).then(()=>!0).catch(()=>!1)||await ee.mkdir(a,{recursive:!0}),await ee.writeFile(n,e.content,"utf-8"),Yn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await uo();let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ee.access(n).then(()=>!0).catch(()=>!1)){let d=await Xn(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ye.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
176
|
+
`+d.message:""}`}let r=await ee.readFile(n,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Ta(r,e.old_text);if(d)a=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let f=Na(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await sn(n,f.content);if(Jn(n,r,f.content,{annotations:p}),!await nn(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await ee.writeFile(n,f.content,"utf-8"),Yn("edit_file",n,r,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${P.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${P.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=fo(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
177
177
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
178
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!
|
|
179
|
-
`)||"(empty)"}case"search_files":{let n
|
|
178
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await sn(n,d);if(Jn(n,r,d,{annotations:f}),!await nn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await ee.writeFile(n,u,"utf-8"),Yn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ee.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=$e(u),f=await ee.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await ee.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ye.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
179
|
+
`)||"(empty)"}case"search_files":{let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Sa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
180
180
|
`).slice(0,50).join(`
|
|
181
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let
|
|
182
|
-
`);return
|
|
181
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?$e(e.path):o,a=e.pattern,c=_=>{let k=_.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${k}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=Bs(),g=f(),w=m();p(r)||(await h(r),g=f());let $=g.filter(_=>l.test(_)||d.test(ye.basename(_))).map(_=>ye.join(r,_));if($.length===0)return"(no matches)";let x=$.length>200,R=$.slice(0,200).join(`
|
|
182
|
+
`);return x?`${R}
|
|
183
183
|
|
|
184
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
184
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:R}case"grep":{let n=e.path?$e(e.path):process.cwd(),o=["-rn","-E"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);try{let{stdout:r}=await Sa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
185
185
|
`).slice(0,100).join(`
|
|
186
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
187
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await
|
|
188
|
-
Most similar text (line ${
|
|
189
|
-
${
|
|
186
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await uo();let n=$e(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ee.access(n).then(()=>!0).catch(()=>!1)){let m=await Xn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ye.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
187
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await ee.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:h,new_text:p}=r[m];if(a.includes(h))c.push({old_text:h,new_text:p});else{let g=Ta(a,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let w=fo(a,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
188
|
+
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
189
|
+
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await sn(n,d);if(Jn(n,a,d,{annotations:m}),!await nn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await ee.writeFile(n,d,"utf-8"),Yn("patch_file",n,a,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${f}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await co.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 co.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",a=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
190
190
|
|
|
191
191
|
${r}`;return a.length>0&&(c+=`
|
|
192
192
|
|
|
193
193
|
Sources:
|
|
194
194
|
`+a.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
195
|
-
`)),c}catch(
|
|
195
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await co.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&a.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{a.push({title:d,url:decodeURIComponent(u)})}catch{a.push({title:d,url:u})}}return a.length===0?"(no results)":a.map((u,d)=>`${d+1}. ${u.title}
|
|
196
196
|
${u.url}`).join(`
|
|
197
197
|
|
|
198
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
198
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Kt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
199
199
|
|
|
200
200
|
Links:
|
|
201
|
-
`+
|
|
202
|
-
`):"";return`Title: ${
|
|
203
|
-
URL: ${
|
|
204
|
-
|
|
205
|
-
${
|
|
206
|
-
Title: ${
|
|
207
|
-
URL: ${
|
|
208
|
-
|
|
209
|
-
To analyze visually, paste the path into your next message: ${
|
|
210
|
-
${
|
|
211
|
-
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${
|
|
212
|
-
`)}case"git_diff":{if(!await
|
|
201
|
+
`+o.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
202
|
+
`):"";return`Title: ${o.title}
|
|
203
|
+
URL: ${o.url}
|
|
204
|
+
|
|
205
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Kt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
206
|
+
Title: ${o.title}
|
|
207
|
+
URL: ${o.url}
|
|
208
|
+
|
|
209
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Kt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Kt();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let n=e.question;return new Promise(o=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});rn=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
210
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,a=>{rn=null,r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await lo())return"ERROR: Not a git repository";let n=await Ca()||"(detached)",o=await im();if(o.length===0)return`Branch: ${n}
|
|
211
|
+
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let a of o){let c=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${c}: ${a.file}`)}return r.join(`
|
|
212
|
+
`)}case"git_diff":{if(!await lo())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 am(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await lo())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:a,hasActiveTasks:c}=Bn(),{getActiveTaskProgress:l}=re(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
|
|
213
213
|
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
214
214
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
215
|
-
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":
|
|
215
|
+
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
216
216
|
`+a()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
217
|
-
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=
|
|
217
|
+
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=ua();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=fe();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await se(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
218
218
|
`)}catch(r){let a=(r.stderr||r.message||"").toString();return a.includes("not found")||a.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${a.split(`
|
|
219
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await
|
|
220
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
219
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await se(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
220
|
+
...(truncated)`:"")}let{stdout:n}=await se(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of o.jobs||[]){let c=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${a.name} (${a.conclusion||a.status})`);for(let l of a.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
221
221
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
222
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
223
|
-
${
|
|
224
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",
|
|
225
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",
|
|
222
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Ae(),o=e.branch||await Ca()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
223
|
+
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await se(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
224
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=on(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:a,stderr:c}=await se(r,{timeout:3e4,maxBuffer:2097152});return(a||c||"(no pods)").trim()}catch(a){let c=(a.stderr||a.message||"").toString().split(`
|
|
225
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let a=on(r,e);try{let{stdout:c,stderr:l}=await se(a,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
226
226
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
227
227
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
228
|
-
${
|
|
228
|
+
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Me(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let a=on(r,e);try{let{stdout:c,stderr:l}=await se(a,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
229
229
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let a=e.file;if(console.log(`
|
|
230
|
-
${
|
|
230
|
+
${P.yellow} \u26A0 kubectl apply: ${a}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await Me(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=on(o,e);try{let{stdout:a,stderr:c}=await se(r,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
231
231
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
232
|
-
${
|
|
233
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:
|
|
232
|
+
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Me(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,a=on(r,e);try{let{stdout:c,stderr:l}=await se(a,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
233
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=tn(),{name:r,content:a,mode:c}=e;if(c==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(r),u=l.content?l.content+`
|
|
234
234
|
|
|
235
|
-
`+a:a;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,a),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=
|
|
236
|
-
${
|
|
235
|
+
`+a:a;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,a),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Ne(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,r=!!e.sudo,a=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
236
|
+
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Me(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(n,o,{timeout:a,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
237
237
|
`).trim();return d!==0?`EXIT ${d}
|
|
238
|
-
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=
|
|
239
|
-
${
|
|
240
|
-
${
|
|
241
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
238
|
+
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Ne(e.server)}catch(a){return`ERROR: ${a.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
239
|
+
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Me(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await lm(n,e.local_path,e.remote_path)}catch(a){return`ERROR: ${a.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Ne(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await um(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",a=null;if(!o)try{a=Ne(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
240
|
+
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Me(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await se(u,{timeout:15e3});return(d||f||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let f=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
241
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(a,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
242
242
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
243
|
-
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",
|
|
244
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
243
|
+
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${a} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await se(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
244
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ne(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ye(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
245
245
|
`).trim();return f!==0?`EXIT ${f}
|
|
246
|
-
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await
|
|
247
|
-
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=
|
|
246
|
+
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await se(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
247
|
+
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=Ne(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Ye(a,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
248
248
|
`).trim();return u!==0?`EXIT ${u}
|
|
249
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",
|
|
250
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
249
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await se(a,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
250
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ne(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(c,a,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
251
251
|
`).trim();return d!==0?`EXIT ${d}
|
|
252
|
-
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",
|
|
253
|
-
${
|
|
254
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
252
|
+
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
253
|
+
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Me(" Execute?"))return"CANCELLED: User declined."}let a=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await se(a,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
254
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ne(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
255
255
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
|
-
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let
|
|
257
|
-
${
|
|
258
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
256
|
+
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=o?"local":e.server;if(console.log(`
|
|
257
|
+
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Me(" Execute?"))return"CANCELLED: User declined."}let a=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${a} ${e.container}`;if(o)try{let{stdout:p,stderr:g}=await se(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
258
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ne(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ye(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
259
|
`).trim();return f!==0?`EXIT ${f}
|
|
260
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
261
|
-
${
|
|
262
|
-
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:
|
|
263
|
-
`).trim();if(
|
|
260
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...dm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.local_path)return"ERROR: local_path is required";if(!e.remote_path)return"ERROR: remote_path is required";let n;try{n=Ne(e.server)}catch(p){return`ERROR: ${p.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,r=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",a=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}"`:"",c=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:r,l=(e.exclude||[]).map(p=>`--exclude="${p}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,f=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
|
|
261
|
+
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await Me(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await se(f,{timeout:12e4});m=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
|
|
262
|
+
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:w,error:$}=await Ye(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
263
|
+
`).trim();if(w!==0)return`rsync OK
|
|
264
264
|
|
|
265
|
-
ERROR (deploy_script, exit ${
|
|
266
|
-
${
|
|
265
|
+
ERROR (deploy_script, exit ${w}):
|
|
266
|
+
${$||x}`;h=`
|
|
267
267
|
|
|
268
268
|
Remote script output:
|
|
269
|
-
${
|
|
270
|
-
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
271
|
-
`)}function
|
|
269
|
+
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
270
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function wm(t,e,s={}){let n=s.silent?null:rm(t,e);if(!n)return Aa(t,e,s);let o=new Oa(n);o.start();try{let r=await Aa(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}Pa.exports={TOOL_DEFINITIONS:ym,executeTool:wm,resolvePath:$e,autoFixPath:Xn,autoFixEdit:Na,enrichBashError:Ma,cancelPendingAskUser:gm}});var qa=N((d$,La)=>{var{loadServerProfiles:po}=vt(),mo={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 bm(){let t=po();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let a=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${o}**: ${a}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&mo[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let a of mo[o])s.push(`- ${a}`)}}return s.join(`
|
|
271
|
+
`)}function xm(t){let e=po();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function _m(){return Object.keys(po())}La.exports={getServerContext:bm,hasServerOS:xm,getProfileNames:_m,OS_HINTS:mo}});var go=N((f$,ja)=>{var Re=require("fs").promises,ve=require("path"),Vn=require("util").promisify(require("child_process").exec),{C:Pe}=re(),{getMergeConflicts:Ia}=ot(),{getServerContext:km}=qa(),ho=new Map,Et=new Map,Qn=null,vm=3e4;async function Xe(t){try{return await t()}catch{return null}}async function Sm(){if(!Qn||Date.now()>Qn)return!1;let t=[ve.join(process.cwd(),"package.json"),ve.join(process.cwd(),"README.md"),ve.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Re.stat(e),n=Et.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Et.has(e))return!1}try{let e=ve.join(process.cwd(),".git","HEAD"),s=await Re.stat(e),n=Et.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Em(){let t=[ve.join(process.cwd(),"package.json"),ve.join(process.cwd(),"README.md"),ve.join(process.cwd(),".gitignore"),ve.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Re.stat(e);Et.set(e,s.mtimeMs)}catch{Et.delete(e)}}async function Cm(t){let e="fileContext",s=ho.get(e),n=!1;if(s&&await Sm()&&(n=!0),!n){let u=[],d=ve.join(t,"package.json");if(await Xe(()=>Re.access(d).then(()=>!0).catch(()=>!1)))try{let w=await Re.readFile(d,"utf-8"),$=JSON.parse(w),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=ve.join(t,"README.md");if(await Xe(()=>Re.access(m).then(()=>!0).catch(()=>!1))){let $=(await Re.readFile(m,"utf-8")).split(`
|
|
272
272
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
273
|
-
${
|
|
274
|
-
`)}`)}let p=
|
|
275
|
-
${
|
|
273
|
+
${$.join(`
|
|
274
|
+
`)}`)}let p=ve.join(t,".gitignore");if(await Xe(()=>Re.access(p).then(()=>!0).catch(()=>!1))){let w=await Re.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
|
+
${w.trim()}`)}s=u.join(`
|
|
276
276
|
|
|
277
|
-
`),
|
|
278
|
-
${a}`),c&&
|
|
277
|
+
`),ho.set(e,s),Qn=Date.now()+vm,await Em()}let o=[s],[r,a,c,l]=await Promise.all([Xe(async()=>{let{stdout:u}=await Vn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Xe(async()=>{let{stdout:u}=await Vn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Xe(async()=>{let{stdout:u}=await Vn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ia()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
278
|
+
${a}`),c&&o.push(`RECENT COMMITS:
|
|
279
279
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
280
|
-
`);
|
|
281
|
-
${u}`)}try{let u=
|
|
280
|
+
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
+
${u}`)}try{let u=km();u&&o.push(u)}catch{}return o.join(`
|
|
282
282
|
|
|
283
|
-
`)}async function
|
|
284
|
-
${e}`);let
|
|
285
|
-
${
|
|
283
|
+
`)}async function Tm(t){let e=ve.join(t,"package.json"),s="";if(await Xe(()=>Re.access(e).then(()=>!0).catch(()=>!1)))try{let a=await Re.readFile(e,"utf-8"),c=JSON.parse(a);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Xe(async()=>{let{stdout:a}=await Vn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),Ia()]);if(s&&console.log(`${Pe.dim} project: ${s}${Pe.reset}`),o&&console.log(`${Pe.dim} branch: ${o}${Pe.reset}`),r&&r.length>0){console.log(`${Pe.red} \u26A0 ${r.length} unresolved merge conflict(s):${Pe.reset}`);for(let a of r)console.log(`${Pe.red} ${a.file}${Pe.reset}`);console.log(`${Pe.yellow} \u2192 Resolve conflicts before starting tasks${Pe.reset}`)}console.log()}ja.exports={gatherProjectContext:Cm,printContext:Tm,_clearContextCache:()=>{ho.clear(),Et.clear(),Qn=null}}});var at=N((m$,Wa)=>{var Be=require("fs"),$o=require("path");function Zn(){return $o.join(process.cwd(),".nex","sessions")}function Da(){let t=Zn();Be.existsSync(t)||Be.mkdirSync(t,{recursive:!0})}function yo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return $o.join(Zn(),`${e}.json`)}function wo(t,e,s={}){Da();let n=yo(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 Be.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Fa(t){let e=yo(t);if(!Be.existsSync(e))return null;try{return JSON.parse(Be.readFileSync(e,"utf-8"))}catch{return null}}function Ua(){Da();let t=Zn(),e=Be.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Be.readFileSync($o.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function Rm(t){let e=yo(t);return Be.existsSync(e)?(Be.unlinkSync(e),!0):!1}function Am(){let t=Ua();return t.length===0?null:Fa(t[0].name)}var it=null,We=null,an=null;function Om(t,e={}){t.length!==0&&(it&&clearTimeout(it),We=t,an=e||{},it=setTimeout(()=>{We&&We.length>0&&wo("_autosave",We,an),it=null,We=null,an=null},5e3))}function Mm(){it&&(clearTimeout(it),it=null),We&&We.length>0&&(wo("_autosave",We,an),We=null,an=null)}Wa.exports={saveSession:wo,loadSession:Fa,listSessions:Ua,deleteSession:Rm,getLastSession:Am,autoSave:Om,flushAutoSave:Mm,_getSessionsDir:Zn}});var Ve=N((p$,Ja)=>{var He=require("fs"),es=require("path"),Nm=require("os");function bo(){return es.join(process.cwd(),".nex","memory")}function xo(){return es.join(bo(),"memory.json")}function Pm(){return es.join(process.cwd(),"NEX.md")}function Ba(){return es.join(Nm.homedir(),".nex","NEX.md")}function Lm(){let t=bo();He.existsSync(t)||He.mkdirSync(t,{recursive:!0})}function ts(){let t=xo();if(!He.existsSync(t))return{};try{return JSON.parse(He.readFileSync(t,"utf-8"))}catch{return{}}}function Ha(t){Lm(),He.writeFileSync(xo(),JSON.stringify(t,null,2),"utf-8")}function qm(t,e){let s=ts();s[t]={value:e,updatedAt:new Date().toISOString()},Ha(s)}function Im(t){let e=ts();return e[t]?e[t].value:null}function jm(t){let e=ts();return t in e?(delete e[t],Ha(e),!0):!1}function za(){let t=ts();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Ga(){let t=Ba();if(!He.existsSync(t))return"";try{return He.readFileSync(t,"utf-8").trim()}catch{return""}}function Ka(){let t=Pm();if(!He.existsSync(t))return"";try{return He.readFileSync(t,"utf-8").trim()}catch{return""}}function Dm(){let t=[],e=Ga();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
|
+
${e}`);let s=Ka();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
|
+
${s}`);let n=za();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
286
286
|
`);t.push(`PROJECT MEMORY:
|
|
287
|
-
${
|
|
287
|
+
${o}`)}return t.join(`
|
|
288
288
|
|
|
289
|
-
`)}
|
|
290
|
-
${
|
|
291
|
-
`);for(let n=0;n<t.steps.length;n++){let
|
|
292
|
-
`)}function
|
|
289
|
+
`)}Ja.exports={remember:qm,recall:Im,forget:jm,listMemories:za,loadGlobalInstructions:Ga,loadProjectInstructions:Ka,getMemoryContext:Dm,_getMemoryDir:bo,_getMemoryFile:xo,_getGlobalNexMdPath:Ba}});var cn=N((g$,Va)=>{var ct=require("fs"),_o=require("path"),{C:h$}=re(),ns={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"},Ct={...ns};function Ya(){let t=_o.join(process.cwd(),".nex","config.json");if(ct.existsSync(t))try{let e=JSON.parse(ct.readFileSync(t,"utf-8"));e.permissions&&(Ct={...ns,...e.permissions})}catch{}}function Fm(){let t=_o.join(process.cwd(),".nex"),e=_o.join(t,"config.json"),s={};if(ct.existsSync(e))try{s=JSON.parse(ct.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Ct,ct.existsSync(t)||ct.mkdirSync(t,{recursive:!0}),ct.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Xa(t){return Ct[t]||"ask"}function Um(t,e){return["allow","ask","deny"].includes(e)?(Ct[t]=e,!0):!1}function Wm(t){return Xa(t)}function Bm(){return Object.entries(Ct).map(([t,e])=>({tool:t,mode:e}))}function Hm(){Ct={...ns}}Ya();Va.exports={getPermission:Xa,setPermission:Um,checkPermission:Wm,listPermissions:Bm,loadPermissions:Ya,savePermissions:Fm,resetPermissions:Hm,DEFAULT_PERMISSIONS:ns}});var Tt=N((y$,nc)=>{var lt=require("fs"),ss=require("path"),$$=require("readline"),{C:U}=re(),ie=null,ko=!1,vo=null,Qa=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 os(){return ss.join(process.cwd(),".nex","plans")}function Za(){let t=os();lt.existsSync(t)||lt.mkdirSync(t,{recursive:!0})}function zm(t,e=[]){return ie={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()},ie}function Gm(){return ie}function Km(t){ko=t}function Jm(){return ko}function Ym(){return!ie||ie.status!=="draft"?!1:(ie.status="approved",ie.updatedAt=new Date().toISOString(),!0)}function Xm(){return!ie||ie.status!=="approved"?!1:(ie.status="executing",!0)}function Vm(t,e){return!ie||t<0||t>=ie.steps.length?!1:(ie.steps[t].status=e,ie.updatedAt=new Date().toISOString(),ie.steps.every(s=>s.status==="done"||s.status==="skipped")&&(ie.status="completed"),!0)}function Qm(t){if(!t)return`${U.dim}No active plan${U.reset}`;let e={draft:`${U.yellow}DRAFT${U.reset}`,approved:`${U.green}APPROVED${U.reset}`,executing:`${U.blue}EXECUTING${U.reset}`,completed:`${U.green}COMPLETED${U.reset}`},s=[];s.push(`
|
|
290
|
+
${U.bold}${U.cyan}Plan: ${t.task}${U.reset}`),s.push(`${U.dim}Status: ${e[t.status]||t.status}${U.reset}
|
|
291
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${U.green}\u2713${U.reset}`;break;case"in_progress":r=`${U.blue}\u2192${U.reset}`;break;case"skipped":r=`${U.dim}\u25CB${U.reset}`;break;default:r=`${U.dim} ${U.reset}`}s.push(` ${r} ${U.bold}Step ${n+1}:${U.reset} ${o.description}`),o.files.length>0&&s.push(` ${U.dim}Files: ${o.files.join(", ")}${U.reset}`)}return s.push(""),s.join(`
|
|
292
|
+
`)}function Zm(t){if(t||(t=ie),!t)return null;Za();let e=ss.join(os(),`${t.name}.json`);return lt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function ep(t){let e=ss.join(os(),`${t}.json`);if(!lt.existsSync(e))return null;try{let s=JSON.parse(lt.readFileSync(e,"utf-8"));return ie=s,s}catch{return null}}function tp(){Za();let t=os(),e=lt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(lt.readFileSync(ss.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 np(t){vo=t}function sp(){return vo}function op(){ie=null,ko=!1,vo=null}function rp(){return`
|
|
293
293
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
294
294
|
|
|
295
295
|
# Allowed Tools (read-only)
|
|
296
|
-
You may ONLY use these tools: ${[...
|
|
296
|
+
You may ONLY use these tools: ${[...Qa].join(", ")}
|
|
297
297
|
Any other tool call will be blocked and returned with an error.
|
|
298
298
|
|
|
299
299
|
# Analysis Phase
|
|
@@ -324,54 +324,54 @@ Bullet list of potential issues and mitigations.
|
|
|
324
324
|
# Important
|
|
325
325
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
326
326
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
327
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
328
|
-
`),
|
|
329
|
-
`)}function
|
|
330
|
-
`)}function
|
|
331
|
-
`))!==-1;){let n=this.buffer.substring(0,
|
|
332
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${
|
|
333
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
334
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
335
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
336
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
337
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
338
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
339
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
340
|
-
`);return}}this._safeWrite(`${
|
|
341
|
-
`)}};
|
|
327
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var ec=["interactive","semi-auto","autonomous"],tc="interactive";function ip(t){return ec.includes(t)?(tc=t,!0):!1}function ap(){return tc}nc.exports={createPlan:zm,getActivePlan:Gm,setPlanMode:Km,isPlanMode:Jm,approvePlan:Ym,startExecution:Xm,updateStep:Vm,formatPlan:Qm,savePlan:Zm,loadPlan:ep,listPlans:tp,clearPlan:op,getPlanModePrompt:rp,setPlanContent:np,getPlanContent:sp,PLAN_MODE_ALLOWED_TOOLS:Qa,setAutonomyLevel:ip,getAutonomyLevel:ap,AUTONOMY_LEVELS:ec}});var fc=N((w$,dc)=>{var{C:y}=re();function cp(t){if(!t)return"";let e=t.split(`
|
|
328
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${y.reset}`)}continue}if(n){s.push(` ${Eo(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${y.bold}${y.cyan} ${ut(r.substring(4))}${y.reset}`);continue}if(r.startsWith("## ")){s.push(`${y.bold}${y.cyan} ${ut(r.substring(3))}${y.reset}`);continue}if(r.startsWith("# ")){s.push(`${y.bold}${y.cyan}${ut(r.substring(2))}${y.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${a}${y.cyan}\u2022${y.reset} ${dt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){s.push(`${a[1]}${y.cyan}${a[2]}.${y.reset} ${dt(a[3])}`);continue}}s.push(dt(r))}return s.join(`
|
|
329
|
+
`)}function ut(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function dt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function Eo(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?sc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?oc(t):e==="json"||e==="jsonc"?rc(t):e==="python"||e==="py"?ic(t):e==="go"||e==="golang"?ac(t):e==="rust"||e==="rs"?cc(t):e==="css"||e==="scss"||e==="less"?lc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?uc(t):t:""}function sc(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${y.yellow}$1${y.reset}`),r=r.replace(e,`${y.magenta}$1${y.reset}`),r=r.replace(s,`${y.green}$&${y.reset}`),r=r.replace(n,`${y.dim}$1${y.reset}`),r}function oc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${y.cyan}$1${y.reset}`),r=r.replace(e,`$1${y.green}$2${y.reset}`),r=r.replace(n,`${y.yellow}$&${y.reset}`),r=r.replace(o,`${y.dim}$1${y.reset}`),r}function rc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${y.cyan}$1${y.reset}:`),r=r.replace(s,`: ${y.green}$1${y.reset}`),r=r.replace(n,`: ${y.yellow}$1${y.reset}`),r=r.replace(o,`: ${y.magenta}$1${y.reset}`),r}function ic(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,a=t;return a=a.replace(o,`${y.yellow}$1${y.reset}`),a=a.replace(e,`${y.magenta}$1${y.reset}`),a=a.replace(r,`${y.cyan}$1${y.reset}`),a=a.replace(s,`${y.green}$&${y.reset}`),a=a.replace(n,`${y.dim}$1${y.reset}`),a}function ac(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${y.yellow}$1${y.reset}`),a=a.replace(s,`${y.cyan}$1${y.reset}`),a=a.replace(e,`${y.magenta}$1${y.reset}`),a=a.replace(n,`${y.green}$&${y.reset}`),a=a.replace(o,`${y.dim}$1${y.reset}`),a}function cc(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${y.yellow}$1${y.reset}`),c=c.replace(s,`${y.cyan}$1${y.reset}`),c=c.replace(e,`${y.magenta}$1${y.reset}`),c=c.replace(a,`${y.yellow}$1${y.reset}`),c=c.replace(n,`${y.green}$&${y.reset}`),c=c.replace(o,`${y.dim}$1${y.reset}`),c}function lc(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,a=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(a,`${y.yellow}$1${y.reset}`),c=c.replace(o,`${y.yellow}$1${y.reset}`),c=c.replace(e,`$1${y.cyan}$2${y.reset}:`),c=c.replace(n,`$1${y.magenta}$&${y.reset}`),c=c.replace(r,`${y.dim}$1${y.reset}`),c}function uc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(o,`${y.dim}$1${y.reset}`),a=a.replace(n,`${y.green}$&${y.reset}`),a=a.replace(e,`<${y.magenta}$1${y.reset}`),a=a.replace(s,` ${y.cyan}$1${y.reset}=`),a=a.replace(r,`${y.yellow}$1${y.reset}`),a}function lp(t,e){if(!t||t.length===0)return"";let s=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),n=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),o=t.map((a,c)=>` ${y.bold}${a.padEnd(s[c])}${y.reset} `).join("\u2502"),r=[];r.push(`${y.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${y.reset}`),r.push(`${y.dim}\u2502${y.reset}${o}${y.dim}\u2502${y.reset}`),r.push(`${y.dim}\u251C${n}\u2524${y.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(s[u])} `).join(`${y.dim}\u2502${y.reset}`);r.push(`${y.dim}\u2502${y.reset}${c}${y.dim}\u2502${y.reset}`)}return r.push(`${y.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${y.reset}`),r.join(`
|
|
330
|
+
`)}function up(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),a=n-r,c=o>=100?y.green:o>50?y.yellow:y.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${y.dim}${"\u2591".repeat(a)}${y.reset} ${o}% (${e}/${s})`}var So=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
331
|
+
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
332
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
333
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${y.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${y.reset}
|
|
334
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Eo(e,this.codeBlockLang)}
|
|
335
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${y.bold}${y.cyan} ${ut(e.substring(4))}${y.reset}
|
|
336
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${y.bold}${y.cyan} ${ut(e.substring(3))}${y.reset}
|
|
337
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${y.bold}${y.cyan}${ut(e.substring(2))}${y.reset}
|
|
338
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${y.cyan}\u2022${y.reset} ${dt(n)}
|
|
339
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${y.cyan}${s[2]}.${y.reset} ${dt(s[3])}
|
|
340
|
+
`);return}}this._safeWrite(`${dt(e)}
|
|
341
|
+
`)}};dc.exports={renderMarkdown:cp,renderInline:dt,stripHeadingMarkers:ut,highlightCode:Eo,highlightJS:sc,highlightBash:oc,highlightJSON:rc,highlightPython:ic,highlightGo:ac,highlightRust:cc,highlightCSS:lc,highlightHTML:uc,renderTable:lp,renderProgress:up,StreamRenderer:So}});var Ro=N((b$,gc)=>{var{execSync:dp}=require("child_process"),Co=require("path"),ln=require("fs"),To=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function mc(){return Co.join(process.cwd(),".nex","hooks")}function fp(){return Co.join(process.cwd(),".nex","config.json")}function pc(){let t=fp();if(!ln.existsSync(t))return{};try{return JSON.parse(ln.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function rs(t){if(!To.includes(t))return[];let e=[],s=mc(),n=Co.join(s,t);ln.existsSync(n)&&e.push(n);let o=pc();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function hc(t,e={},s=3e4){try{return{success:!0,output:dp(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 mp(t,e={}){let s=rs(t);if(s.length===0)return[];let n={};for(let[r,a]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(a);let o=[];for(let r of s){let a=hc(r,n);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function pp(t){return rs(t).length>0}function hp(){let t=[];for(let e of To){let s=rs(e);s.length>0&&t.push({event:e,commands:s})}return t}function gp(){let t=mc();return ln.existsSync(t)||ln.mkdirSync(t,{recursive:!0}),t}gc.exports={HOOK_EVENTS:To,loadHookConfig:pc,getHooksForEvent:rs,executeHook:hc,runHooks:mp,hasHooks:pp,listHooks:hp,initHooksDir:gp}});var ae=N((k$,Tc)=>{var{C:v,Spinner:Rt,TaskProgress:$p,formatToolCall:yp,formatResult:wp,formatToolSummary:bc,formatSectionHeader:bp,setActiveTaskProgress:x$}=re(),{callStream:xp}=fe(),{parseToolArgs:_p}=Tn(),{executeTool:kp}=De(),{gatherProjectContext:vp}=go(),{fitToContext:Sp,forceCompress:Ao,getUsage:Ep,estimateTokens:Cp}=Ce(),{autoSave:ft}=at(),{getMemoryContext:Tp}=Ve(),{checkPermission:Rp,setPermission:Ap,savePermissions:Op}=cn(),{confirm:xc,setAllowAlwaysHandler:Mp}=Ae(),{isPlanMode:us,getPlanModePrompt:Np,PLAN_MODE_ALLOWED_TOOLS:_c,setPlanContent:Pp}=Tt(),{StreamRenderer:Lp}=fc(),{runHooks:$c}=Ro(),{routeMCPCall:qp,getMCPToolDefinitions:Ip}=Nn(),{getSkillInstructions:jp,getSkillToolDefinitions:Dp,routeSkillCall:Fp}=Ht(),{trackUsage:Up}=wt(),{validateToolArgs:Wp}=Ds(),{filterToolsForModel:yc,getModelTier:Bp,PROVIDER_DEFAULT_TIER:_$}=Vs(),{getConfiguredProviders:Hp,getActiveProviderName:zp,getActiveModelId:Gp}=fe(),Do=require("fs"),kc=require("path"),wc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Kp(t){let e=[],s;for(wc.lastIndex=0;(s=wc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):kc.resolve(n);Do.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Jp(t){let e=Do.readFileSync(t),s=kc.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 vc(t){let e=Kp(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}=Jp(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Oo=null,Mo=null,No=null;function At(){if(Oo===null){let{TOOL_DEFINITIONS:t}=De();Oo=t}return Mo===null&&(Mo=Dp()),No===null&&(No=Ip()),[...Oo,...Mo,...No]}var Io=50;function Yp(t){Number.isFinite(t)&&t>0&&(Io=t)}var as=()=>null;function Xp(t){as=t}var un=null,jo=null,Ot=null,cs=new Map,Vp=1e4,Qp=6e3;function Zp(t){if(Cp(t)>Vp)try{let{compressToolResult:s}=Ce();return s(t,Qp)}catch{return t}return t}function Sc(t){try{let{getActiveModel:e}=fe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(cs.has(n))return cs.get(n);let o=yc(t);return cs.set(n,o),o}catch{return yc(t)}}function eh(){cs.clear()}async function Ec(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Ve(),a=r();a&&o.push(`memory:${a}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Do.existsSync(r)){let a=await t.stat(r);o.push(`brain:${a.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function th(){un=null,jo=null,Ot=null}var nh=new Set(["read_file","list_directory","search_files","glob","grep","web_fetch","web_search","git_status","git_diff","git_log","task_list","gh_run_list","gh_run_view"]),Po=5,Lo=3,is=2,sh=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),oh=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function rh(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{}}Mp(t=>{Ap(t,"allow"),Op(),console.log(`${v.green} \u2713 ${t}: always allow${v.reset}`)});async function ih(t){let e=t.function.name,s=_p(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=At().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${v.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${v.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
342
342
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
343
343
|
|
|
344
344
|
Expected JSON schema for "${e}":
|
|
345
345
|
${u}
|
|
346
346
|
|
|
347
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let
|
|
348
|
-
`)[0]}${
|
|
349
|
-
...(truncated ${n.length-5e4} chars)`:n,r=
|
|
350
|
-
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(
|
|
351
|
-
`)}function
|
|
352
|
-
`];n?
|
|
353
|
-
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),
|
|
347
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Wp(e,s);if(!o.valid)return console.log(`${v.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
348
|
+
`)[0]}${v.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(`${v.dim} \u2713 ${e}: corrected args (${u.join(", ")})${v.reset}`)}if(us()&&!_c.has(e))return console.log(`${v.yellow} \u2717 ${e}: blocked in plan mode${v.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let a=Rp(e);if(a==="deny")return console.log(`${v.red} \u2717 ${e}: denied by permissions${v.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await xc(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 ah(t,e,s={}){let n=await Fp(t,e);if(n!==null)return n;let o=await qp(t,e);return o!==null?o:kp(t,e,s)}function ch(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 qo(t,e=!1){e||console.log(yp(t.fnName,t.args)),$c("pre-tool",{tool_name:t.fnName});let s=await ah(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
349
|
+
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
350
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=bc(t.fnName,t.args,o,a);return e||(console.log(wp(o)),console.log(c)),$c("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:Zp(o),tool_call_id:t.callId},summary:c}}async function lh(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],a=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=ch(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}a=new Rt(u),a.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await qo(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>qo(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(bc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(nh.has(u.fnName))r.push(l);else{await c(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await qo(u,e);n[l]=d,o.push(f)}}if(await c(),a&&a.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var me=[],ls=[];function uh(t){ls.push(t.trim())}function dh(){return ls.length===0?null:ls.splice(0,ls.length).join(`
|
|
351
|
+
`)}function fh(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
352
|
+
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let a=s||(n?"English":null);return a&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),n&&o.push(`
|
|
353
|
+
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
|
|
354
354
|
`)+`
|
|
355
355
|
|
|
356
|
-
`}function
|
|
356
|
+
`}function mh(){if(Ot!==null)return Ot;try{let e=Hp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Bp(r.id,o.name),name:r.name})));if(e.length<2)return Ot="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
357
357
|
# Sub-Agent Model Routing
|
|
358
358
|
|
|
359
359
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
360
360
|
|---|---|---|
|
|
361
|
-
`;for(let
|
|
362
|
-
`;return
|
|
361
|
+
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
362
|
+
`;return Ot=n,n}catch{return Ot="",""}}async function Cc(){let t=await Ec();if(un!==null&&t===jo)return un;let e=await vp(process.cwd()),s=Tp(),n=jp(),o=us()?Np():"",r=fh();return un=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
363
363
|
|
|
364
364
|
WORKING DIRECTORY: ${process.cwd()}
|
|
365
365
|
All relative paths resolve from this directory.
|
|
366
366
|
${r?`
|
|
367
367
|
${r}`:""}PROJECT CONTEXT:
|
|
368
368
|
${e}
|
|
369
|
-
${
|
|
370
|
-
${
|
|
369
|
+
${s?`
|
|
370
|
+
${s}
|
|
371
371
|
`:""}${n?`
|
|
372
372
|
${n}
|
|
373
|
-
`:""}${
|
|
374
|
-
${
|
|
373
|
+
`:""}${o?`
|
|
374
|
+
${o}
|
|
375
375
|
`:""}
|
|
376
376
|
# Core Behavior
|
|
377
377
|
|
|
@@ -388,6 +388,13 @@ If you run tools but write NO text \u2192 the user sees NOTHING useful. This is
|
|
|
388
388
|
|
|
389
389
|
MANDATORY RULE: After ANY tool call that gathers information (bash, read_file, grep, ssh commands, etc.), you MUST write a text response summarizing the findings. NEVER end your response with only tool calls and no text.
|
|
390
390
|
|
|
391
|
+
CODE DISPLAY RULE: Always show actual code examples, not just descriptions. When explaining code:
|
|
392
|
+
\u2022 Show the complete code snippet, not just describe it
|
|
393
|
+
\u2022 Include file paths and line numbers (e.g., "src/app.js:42")
|
|
394
|
+
\u2022 For regex patterns, show both the pattern and example matches. Note PCRE-only features like (?&name) backreferences
|
|
395
|
+
\u2022 For Makefiles, display the actual .PHONY and target declarations
|
|
396
|
+
\u2022 For dataclasses, show the complete class definition with all fields
|
|
397
|
+
|
|
391
398
|
- 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.
|
|
392
399
|
- Structure longer responses with headers (## Section) so the user can scan quickly.
|
|
393
400
|
|
|
@@ -397,9 +404,26 @@ Response patterns by request type:
|
|
|
397
404
|
- **Simple questions ("what does X do?")**: Answer directly without tools when you have enough context.
|
|
398
405
|
- **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.
|
|
399
406
|
- **Server/SSH commands**: After running remote commands, ALWAYS present the results: service status, log errors, findings.
|
|
407
|
+
- **Regex explanations**: Always show the actual regex pattern and test it with examples. For named groups, use the correct syntax format (question mark open angle bracket name close angle bracket pattern), not incorrect variants. Note PCRE-only features like (?&name) backreferences.
|
|
408
|
+
- **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.
|
|
409
|
+
- **Hook implementations**: When explaining hooks, show the actual hook file content and explain how to configure it in .nex/config.json. Handle edge cases like console.log in strings vs actual code.
|
|
410
|
+
- **Memory leak explanations**: When explaining memory leaks, show actual code examples of both problematic and fixed versions. Explain WHY solutions work, not just what they are.
|
|
411
|
+
- **Makefile tasks**: Always display the actual Makefile code with .PHONY declarations and dependency chains. Show complete target definitions.
|
|
412
|
+
- **Dataclass definitions**: Always show the complete dataclass code with all field types, defaults, and validation logic. Include __post_init__ methods when relevant.
|
|
413
|
+
- **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.
|
|
400
414
|
|
|
401
415
|
After completing multi-step tasks, suggest logical next steps (e.g. "You can run npm test to verify" or "Consider committing with /commit").
|
|
402
416
|
|
|
417
|
+
# Response Content Guidelines
|
|
418
|
+
|
|
419
|
+
- **Avoid opinionated additions**: Only include what was explicitly requested. Do not add:
|
|
420
|
+
- Unrequested fields (e.g., pagination fields not asked for)
|
|
421
|
+
- Unnecessary patterns or interfaces
|
|
422
|
+
- Opinionated design decisions beyond the scope of the request
|
|
423
|
+
- Extra features or improvements not explicitly requested
|
|
424
|
+
- **Preserve existing behavior**: When refactoring or fixing code, maintain the original encoding, error handling, and API behavior unless explicitly instructed to change it.
|
|
425
|
+
- **Be complete**: Ensure responses include all necessary information and are not truncated. If a response would be very long, summarize key points and offer to provide more detail if needed.
|
|
426
|
+
|
|
403
427
|
# Doing Tasks
|
|
404
428
|
|
|
405
429
|
- For non-trivial tasks, briefly state your approach before starting (1 sentence). This helps the user know what to expect.
|
|
@@ -431,7 +455,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
431
455
|
- Good for: reading multiple files, analyzing separate modules.
|
|
432
456
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
433
457
|
- Max 5 parallel agents.
|
|
434
|
-
${
|
|
458
|
+
${mh()}
|
|
435
459
|
|
|
436
460
|
# Edit Reliability (Critical)
|
|
437
461
|
|
|
@@ -482,16 +506,17 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
482
506
|
- Include tags in frontmatter for better retrieval
|
|
483
507
|
- The user reviews all brain writes via /brain review or git diff
|
|
484
508
|
|
|
485
|
-
`,
|
|
486
|
-
${
|
|
487
|
-
`+
|
|
488
|
-
`)}catch{}let c=[{role:"system",content:a},...
|
|
489
|
-
${
|
|
490
|
-
${
|
|
491
|
-
`),await t(c,a,d)}catch(u){if(
|
|
492
|
-
`)
|
|
493
|
-
`);process.stdout.write(x
|
|
494
|
-
`)
|
|
509
|
+
`,jo=t,un}function ph(){me=[]}function hh(){return me.length}function gh(){return me}function $h(t){me=t}function mt(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}a+=" \u2500\u2500",console.log(`
|
|
510
|
+
${v.dim} ${a}${v.reset}`),s.size>0?console.log(`${v.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${v.reset}`):n.size>0&&t>=2&&console.log(`${v.dim} \u{1F4A1} /save \xB7 /clear${v.reset}`)}async function yh(t){let e=vc(t);me.push({role:"user",content:e});let{setOnChange:s}=Bn(),n=null,o=0;s((W,te)=>{W==="create"?(n&&n.stop(),n=new $p(te.name,te.tasks),n.setStats({tokens:o}),n.start()):W==="update"&&n?n.updateTask(te.id,te.status):W==="clear"&&n&&(n.stop(),n=null)});let r=await Cc(),a=r;try{let{getBrainContext:W}=tn(),te=await W(t);te&&(a=r+`
|
|
511
|
+
`+te+`
|
|
512
|
+
`)}catch{}let c=[{role:"system",content:a},...me],l=new Rt("Thinking...");l.start();let u=At(),{messages:d,compressed:f,compacted:m,tokensRemoved:h}=await Sp(c,u),p=Ep(c,u);if(l.stop(),m)console.log(`${v.dim} [context compacted \u2014 summary (~${h} tokens freed)]${v.reset}`);else if(f){let W=p.limit>0?Math.round(h/p.limit*100):0;console.log(`${v.dim} [context compressed \u2014 ~${h} tokens freed (${W}%)]${v.reset}`)}p.percentage>85&&console.log(`${v.yellow} \u26A0 Context ${Math.round(p.percentage)}% full \u2014 consider /clear or /save + start fresh${v.reset}`);let g=d,w=0,$=0,x=0,R=0,_=0,k=new Map,E=new Set,C=new Set,A=Date.now(),D,q=Io,ue=0,z=10;e:for(;;){for(D=0;D<q&&!as()?.aborted;D++){let te=!0,Y=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let S=_>0?`Thinking... (step ${_+1})`:"Thinking...";Y=new Rt(S),Y.start()}let Ge=!0,M="",L=new Lp,G,Q=Date.now(),I=!1,K=new AbortController,B=setInterval(()=>{let S=Date.now()-Q;S>=oh?(L._clearCursorLine(),console.log(`${v.yellow} \u26A0 Stream stale for ${Math.round(S/1e3)}s \u2014 aborting and retrying${v.reset}`),K.abort()):S>=sh&&!I&&(I=!0,L._clearCursorLine(),console.log(`${v.yellow} \u26A0 No tokens received for ${Math.round(S/1e3)}s \u2014 waiting...${v.reset}`))},5e3),H="",be=null;try{let S=Sc(At()),j=us()?S.filter(de=>_c.has(de.function.name)):S,pt=as(),F=new AbortController;pt&&pt.addEventListener("abort",()=>F.abort(),{once:!0}),K.signal.addEventListener("abort",()=>F.abort(),{once:!0}),G=await xp(g,j,{signal:F.signal,onToken:de=>{Q=Date.now(),I=!1,H+=de,process.stdout.isTTY?be||(be=setTimeout(()=>{H&&L&&L.push(H),H="",be=null},50)):(L.push(H),H=""),Ge&&(n&&!n._paused?n.pause():Y&&Y.stop(),te||(te=!0),L.startCursor(),Ge=!1),M+=de}})}catch(S){if(clearInterval(B),be&&(clearTimeout(be),be=null),H&&L&&(L.push(H),H=""),n&&!n._paused&&n.pause(),Y&&Y.stop(),L.stopCursor(),K.signal.aborted&&!as()?.aborted){if(x++,x>is){if(R<1){R++,console.log(`${v.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${v.reset}`);let Ee=At(),{messages:It,tokensRemoved:jt}=Ao(g,Ee);g=It,console.log(`${v.dim} [force-compressed \u2014 ~${jt} tokens freed]${v.reset}`),x=0,D--;continue}console.log(`${v.red} \u2717 Stream stale: max retries (${is}) exceeded. The model may be overloaded \u2014 try again or switch models.${v.reset}`),n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);break}let F=x===1?3e3:5e3;if(x>=2&&R<1){R++,console.log(`${v.yellow} \u26A0 Stale retry ${x}/${is} \u2014 force-compressing before retry...${v.reset}`);let Ee=At(),{messages:It,tokensRemoved:jt}=Ao(g,Ee);g=It,console.log(`${v.dim} [force-compressed \u2014 ~${jt} tokens freed]${v.reset}`)}else console.log(`${v.yellow} \u26A0 Stale retry ${x}/${is} \u2014 retrying in ${F/1e3}s...${v.reset}`);let de=new Rt(`Waiting ${F/1e3}s before retry...`);de.start(),await new Promise(Ee=>setTimeout(Ee,F)),de.stop(),D--;continue}if(S.name==="AbortError"||S.name==="CanceledError"||S.message?.includes("canceled")||S.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);break}let j=S.message;if(S.code==="ECONNREFUSED"||S.message.includes("ECONNREFUSED"))j="Connection refused \u2014 please check your internet connection or API endpoint";else if(S.code==="ENOTFOUND"||S.message.includes("ENOTFOUND"))j="Network error \u2014 could not reach the API server. Please check your connection";else if(S.code==="ETIMEDOUT"||S.message.includes("timeout"))j="Request timed out \u2014 the API server took too long to respond. Please try again";else if(S.message.includes("401")||S.message.includes("Unauthorized"))j="Authentication failed \u2014 please check your API key in the .env file";else if(S.message.includes("403")||S.message.includes("Forbidden"))j="Access denied \u2014 your API key may not have permission for this model";else if(S.message.includes("400")){let F=(S.message||"").toLowerCase(),de=F.includes("context")||F.includes("token")||F.includes("length")||F.includes("too long")||F.includes("too many")||F.includes("prompt")||F.includes("size")||F.includes("exceeds")||F.includes("num_ctx")||F.includes("input");if(de&&R<1){R++,console.log(`${v.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${v.reset}`);let Ee=At(),{messages:It,tokensRemoved:jt}=Ao(g,Ee);g=It,console.log(`${v.dim} [force-compressed \u2014 ~${jt} tokens freed]${v.reset}`),D--;continue}de?j="Context too long \u2014 force compression exhausted. Use /clear to start fresh":j="Bad request \u2014 the conversation may be too long or contain unsupported content. Try /clear and retry"}else S.message.includes("500")||S.message.includes("502")||S.message.includes("503")||S.message.includes("504")?j="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(S.message.includes("fetch failed")||S.message.includes("fetch"))&&(j="Network request failed \u2014 please check your internet connection");if(console.log(`${v.red} \u2717 ${j}${v.reset}`),S.message.includes("429")){if(w++,w>Po){console.log(`${v.red} Rate limit: max retries (${Po}) exceeded. Try again later or use /budget to check your limits.${v.reset}`),n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);break}let F=Math.min(1e4*Math.pow(2,w-1),12e4),de=new Rt(`Rate limit \u2014 waiting ${Math.round(F/1e3)}s (retry ${w}/${Po})`);de.start(),await new Promise(Ee=>setTimeout(Ee,F)),de.stop();continue}if(S.message.includes("socket disconnected")||S.message.includes("TLS")||S.message.includes("ECONNRESET")||S.message.includes("ECONNABORTED")||S.message.includes("ETIMEDOUT")||S.code==="ECONNRESET"||S.code==="ECONNABORTED"){if($++,$>Lo){console.log(`${v.red} Network error: max retries (${Lo}) exceeded. Check your connection and try again.${v.reset}`),n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);break}let F=Math.min(2e3*Math.pow(2,$-1),3e4),de=new Rt(`Network error \u2014 retrying in ${Math.round(F/1e3)}s (${$}/${Lo})`);de.start(),await new Promise(Ee=>setTimeout(Ee,F)),de.stop(),D--;continue}n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);break}clearInterval(B),Ge&&(n&&!n._paused&&n.pause(),Y&&Y.stop()),be&&(clearTimeout(be),be=null),H&&L&&(L.push(H),H=""),M&&L.flush(),$=0,x=0,G&&G.usage&&(Up(zp(),Gp(),G.usage.prompt_tokens||0,G.usage.completion_tokens||0),o+=(G.usage.prompt_tokens||0)+(G.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:Lt,tool_calls:qe}=G,qt={role:"assistant",content:Lt||""};if(qe&&qe.length>0&&(qt.tool_calls=qe),me.push(qt),g.push(qt),!qe||qe.length===0){let S=(Lt||"").trim().length>0||M.trim().length>0;if(!S&&_>0&&D<Io-1){let j={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};g.push(j);continue}if(us()&&S){let j=(Lt||M||"").trim();Pp(j),rh(j),console.log(`
|
|
513
|
+
${v.cyan}${v.bold}Plan ready.${v.reset} ${v.dim}Type ${v.reset}${v.cyan}/plan approve${v.reset}${v.dim} to execute, or ask follow-up questions to refine.${v.reset}`)}n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);return}_++,_>1&&(te=!1);for(let S of qe){let j=S.function.name;k.set(j,(k.get(j)||0)+1)}let pn=await Promise.all(qe.map(S=>ih(S))),hs=n?{skipSpinner:!0,skipSummaries:!0}:{},or=!hs.skipSummaries&&!te;or&&(te=!0),n&&n._paused&&n.resume();let{results:rr,summaries:hn}=await lh(pn,!0,{...hs,skipSummaries:!0});if(!hs.skipSummaries)if(or){let S=bp(pn,_);if(hn.length===1)console.log(S+hn[0]);else{console.log(S);for(let j of hn)console.log(j)}}else for(let S of hn)console.log(S);for(let S=0;S<pn.length;S++){let j=pn[S];if(!j.canExecute)continue;let pt=rr[S].content,F=!pt.startsWith("ERROR")&&!pt.includes("CANCELLED");F&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&E.add(j.args.path),F&&j.fnName==="read_file"&&j.args&&j.args.path&&C.add(j.args.path)}for(let S of rr)me.push(S),g.push(S);let ir=dh();if(ir){let S={role:"user",content:`[User note mid-run]: ${ir}`};me.push(S),g.push(S),console.log(`${v.cyan} \u270E Kontext hinzugef\xFCgt${v.reset}`)}}if(D>=q){n&&(n.stop(),n=null),s(null),mt(_,k,E,C,A),ft(me);let{getActiveProviderName:W}=fe();if(W()==="ollama"&&ue<z){ue++,q+=20,console.log(`${v.dim} \u2500\u2500 auto-extending to ${q} turns \u2500\u2500${v.reset}`);continue e}if(console.log(`
|
|
514
|
+
${v.yellow}\u26A0 Max iterations (${q}) reached.${v.reset}`),await xc(" Continue for 20 more turns?")){q+=20;continue e}console.log(`${v.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${v.reset}`)}break e}}Tc.exports={processInput:yh,clearConversation:ph,getConversationLength:hh,getConversationMessages:gh,setConversationMessages:$h,setAbortSignalGetter:Xp,setMaxIterations:Yp,invalidateSystemPromptCache:th,clearToolFilterCache:eh,getCachedFilteredTools:Sc,buildSystemPrompt:Cc,getProjectContextHash:Ec,buildUserContent:vc,injectMidRunNote:uh}});var fe=N((v$,Pc)=>{var{OllamaProvider:wh}=vr(),{OpenAIProvider:bh}=Br(),{AnthropicProvider:xh}=Kr(),{GeminiProvider:_h}=Vr(),{LocalProvider:kh}=ei(),{checkBudget:vh}=wt(),Rc={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"}},Ac={};for(let[t,e]of Object.entries(Rc))for(let s of Object.values(e))Ac[s]=t;function Oc(t,e){let s=Ac[t];return s&&Rc[s][e]||t}var le={},we=null,ce=null,dn=[];function Se(){if(Object.keys(le).length>0)return;Mt("ollama",new wh),Mt("openai",new bh),Mt("anthropic",new xh),Mt("gemini",new _h),Mt("local",new kh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;le[t]?(we=t,ce=e||le[t].defaultModel):(we="ollama",ce="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(dn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Mt(t,e){le[t]=e}function Sh(t){return Se(),le[t]||null}function Fo(){return Se(),le[we]||null}function Eh(){return Se(),we}function Ch(){return Se(),ce}function Th(){Se();let t=Fo();if(!t)return{id:ce,name:ce,provider:we};let e=t.getModel(ce);return e?{...e,provider:we}:{id:ce,name:ce,provider:we}}function Mc(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(le[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Rh(t){Se();let{provider:e,model:s}=Mc(t);if(e){let o=le[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(we=e,ce=s,ds(),!0):!1}let n=Fo();if(n&&n.getModel(s))return ce=s,ds(),!0;for(let[o,r]of Object.entries(le))if(r.getModel(s))return we=o,ce=s,ds(),!0;return!1}function ds(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ae();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Ce();t()}catch{}}function Ah(){Se();let t=new Set;for(let e of Object.values(le))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Oh(){return Se(),Object.entries(le).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===we&&s.id===ce}))}))}function Mh(){Se();let t=[];for(let[e,s]of Object.entries(le)){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 Nh(t){dn=Array.isArray(t)?t:[]}function Ph(){return[...dn]}function Lh(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 Nc(t){let e=[we,...dn.filter(r=>r!==we)],s,n=0,o=0;for(let r=0;r<e.length;r++){let a=e[r],c=le[a];if(!c||!c.isConfigured())continue;o++;let l=vh(a);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Oc(ce,a):ce;return u&&d!==ce&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
515
|
+
`),await t(c,a,d)}catch(u){if(s=u,Lh(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 qh(t,e,s={}){return Se(),Nc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Ih(t,e,s={}){if(Se(),s.provider){let n=le[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||ce,...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 Nc(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(a){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw a}})}function jh(){Se();let t=[];for(let[e,s]of Object.entries(le))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Dh(){for(let t of Object.keys(le))delete le[t];we=null,ce=null,dn=[]}Pc.exports={registerProvider:Mt,getProvider:Sh,getActiveProvider:Fo,getActiveProviderName:Eh,getActiveModelId:Ch,getActiveModel:Th,setActiveModel:Rh,getModelNames:Ah,parseModelSpec:Mc,listProviders:Oh,listAllModels:Mh,callStream:qh,callChat:Ih,getConfiguredProviders:jh,setFallbackChain:Nh,getFallbackChain:Ph,resolveModelForProvider:Oc,_reset:Dh}});var jc=N((S$,Ic)=>{"use strict";var Lc="\x1B[2m",qc="\x1B[0m";function Fh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Uo=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._lastOutputRow=1}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,s=1){return`\x1B[${e};${s}H`}_statusLine(){return Lc+"\u2500".repeat(this._cols)+qc}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(l,...u){if(s._active&&typeof l=="string"){if(s._cursorOnInputRow){let f=l.replace(/\n/g,"");return f?n(f,...u):!0}let d=(l.match(/\n/g)||[]).length;d>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+d,s._scrollEnd))}return n(l,...u)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(l,...u){if(!s._active)return s._origStderrWrite(l,...u);if(typeof l=="string"&&l.includes("\r")){let d=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(d))}return s._origStderrWrite(l,...u)},this._origLog=console.log,this._origError=console.error;function o(...l){if(!s._active){s._origLog(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...l),s.drawFooter()}function r(...l){if(!s._active){s._origError(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...l),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(l){s._origSetPr(l),s._active&&s.drawFooter(l)},this._origPrompt=e.prompt.bind(e),e.prompt=function(l){if(!s._active)return s._origPrompt(l);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(l),s._cursorOnInputRow=!0};let a=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=a,a&&(e._refreshLine=function(){if(!s._active)return a();let l=s._cols,u=Fh(e._prompt||""),d=l-u-1;if(e.line.length<=d)return a();let f=e.line,m=e.cursor,h=Math.max(1,d-1),g=Math.max(0,m-h),w=(g>0?"\xAB":"")+f.slice(g,g+h+(g>0?0:1));e.line=w,e.cursor=w.length,a(),e.line=f,e.cursor=m}),e.on("line",l=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),l&&l.trim()&&process.stdout.write(Lc+"\u203A "+l+qc+`
|
|
516
|
+
`),s.drawFooter())});let c=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",c),this._offResize=()=>process.stdout.off("resize",c)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Ic.exports={StickyFooter:Uo}});var Uc=N((E$,Fc)=>{var{C:V}=re(),{listProviders:Uh,getActiveProviderName:Wh,getActiveModelId:Bh,setActiveModel:Hh}=fe();function Dc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let a=e.map(($,x)=>$.isHeader?-1:x).filter($=>$>=0);if(a.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?a.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=a[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let k=0;k<m;k++)process.stdout.write(`\x1B[2K
|
|
517
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${V.bold}${V.cyan}${n}${V.reset}`),$.push(` ${V.dim}${o}${V.reset}`),$.push("");let{start:x,end:R}=f();x>0&&$.push(` ${V.dim}\u2191 more${V.reset}`);for(let k=x;k<R;k++){let E=e[k];if(E.isHeader){$.push(` ${V.bold}${V.dim}${E.label}${V.reset}`);continue}let C=a[l]===k,A=C?`${V.cyan}> `:" ",D=E.isCurrent?` ${V.yellow}<current>${V.reset}`:"";C?$.push(`${A}${V.bold}${E.label}${V.reset}${D}`):$.push(`${A}${V.dim}${E.label}${V.reset}${D}`)}R<e.length&&$.push(` ${V.dim}\u2193 more${V.reset}`);let _=$.join(`
|
|
518
|
+
`);process.stdout.write(_+`
|
|
519
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<a.length-1&&(l++,h());return}if(x.name==="return"){let R=e[a[l]];g(),r(R?R.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function zh(t){let e=Uh(),s=Wh(),n=Bh(),o=[];for(let a of e)if(a.models.length!==0){o.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===s&&c.id===n;o.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await Dc(t,o,{title:"Select Model"});return r?(Hh(r),console.log(`${V.green}Switched to ${r}${V.reset}`),!0):(console.log(`${V.dim}Cancelled${V.reset}`),!1)}Fc.exports={pickFromList:Dc,showModelPicker:zh}});var Ho=N((T$,Jc)=>{var Wo=require("fs"),Gh=require("path"),{callChat:Wc}=fe(),{remember:Kh,listMemories:C$,recall:Jh}=Ve(),Bo=4,Yh=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
495
520
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
496
521
|
|
|
497
522
|
Return ONLY valid JSON in this exact format:
|
|
@@ -517,15 +542,15 @@ Rules:
|
|
|
517
542
|
- value: concise actionable instruction, max 120 chars
|
|
518
543
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
519
544
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
520
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
545
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Bc(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(`
|
|
521
546
|
|
|
522
|
-
`)}async function
|
|
547
|
+
`)}async function Hc(t){if(t.filter(o=>o.role==="user").length<Bo)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Bc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:Yh},{role:"user",content:`Conversation to analyze:
|
|
523
548
|
|
|
524
|
-
${
|
|
525
|
-
`)?
|
|
526
|
-
`+a:a)}return n.length>0&&(
|
|
527
|
-
`)||(
|
|
528
|
-
`),
|
|
549
|
+
${s}`}];try{let a=((await Wc(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(a[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function zc(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!o||!r)continue;let a=Jh(o);a!==r&&(Kh(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Gc(t){if(!t||t.length===0)return[];let e=Gh.join(process.cwd(),"NEX.md"),s="";try{Wo.existsSync(e)&&(s=Wo.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let a=r.trim();if(!a)continue;let c=a.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(a),o=o?o.endsWith(`
|
|
550
|
+
`)?o+a:o+`
|
|
551
|
+
`+a:a)}return n.length>0&&(o.endsWith(`
|
|
552
|
+
`)||(o+=`
|
|
553
|
+
`),Wo.writeFileSync(e,o,"utf-8")),n}async function Xh(t){let e=await Hc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=zc(e.memories),n=Gc(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var Vh=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
529
554
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
530
555
|
|
|
531
556
|
Return ONLY valid JSON in this exact format:
|
|
@@ -559,37 +584,37 @@ Rules:
|
|
|
559
584
|
---
|
|
560
585
|
- Maximum 3 documents per session. Quality over quantity.
|
|
561
586
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
562
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
587
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Kc(t){if(t.filter(o=>o.role==="user").length<Bo)return{documents:[],skip_reason:"Session too short"};let s=Bc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:Vh},{role:"user",content:`Conversation to analyze:
|
|
563
588
|
|
|
564
|
-
${
|
|
589
|
+
${s}`}];try{let a=((await Wc(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{documents:[],error:"No JSON in response"};let c=JSON.parse(a[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function Qh(t){let e=await Kc(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:n}=tn(),o=[],r=[];for(let a of e.documents){if(!a.name||!a.content)continue;let c=a.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
|
|
565
590
|
|
|
566
591
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
567
592
|
|
|
568
|
-
${a.content}`;
|
|
593
|
+
${a.content}`;s(c,l.content+d),o.push({name:c,reason:a.reason||"",action:"updated"})}else s(c,a.content),o.push({name:c,reason:a.reason||"",action:"created"})}return{written:o,skipped:r}}Jc.exports={learnFromSession:Xh,learnBrainFromSession:Qh,reflectOnSession:Hc,reflectBrain:Kc,applyMemories:zc,applyNexAdditions:Gc,LEARN_MIN_MESSAGES:Bo}});var Zc=N((A$,Qc)=>{var he=require("fs"),Pt=require("path"),R$=require("os"),Zh=require("readline"),{C:T}=re(),Yc=".nex",zo=null;function eg(t){zo=t}function _e(t,e=""){let s=e?` ${T.dim}[${e}]${T.reset}`:"",n=` ${T.cyan}${t}${s}${T.reset}: `;return new Promise(o=>{let r=a=>{let c=a.trim()||e;o(c)};if(zo)zo.question(n,r);else{let a=Zh.createInterface({input:process.stdin,output:process.stdout});a.question(n,c=>{a.close(),r(c)})}})}function Nt(t,e=!0){return _e(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function Xc(t,e,s){let n=e.map((c,l)=>`${T.dim}${l+1})${T.reset} ${c}`).join(" ");console.log(` ${T.cyan}${t}${T.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await _e("Enter number",String(o)),a=parseInt(r,10)-1;return e[Math.max(0,Math.min(a,e.length-1))]}async function tg(){let t=Pt.join(process.cwd(),Yc),e=Pt.join(t,"servers.json"),s={};if(he.existsSync(e))try{s=JSON.parse(he.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
569
594
|
${T.bold}${T.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${T.reset}`),console.log(`${T.bold}${T.cyan}\u2551 nex-code Server Setup Wizard \u2551${T.reset}`),console.log(`${T.bold}${T.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${T.reset}
|
|
570
|
-
`);let n=Object.keys(
|
|
571
|
-
`);return}let
|
|
572
|
-
${T.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${T.reset}`);let l=await
|
|
595
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${T.dim}Existing profiles: ${n.join(", ")}${T.reset}`),!await Nt("Add or update a server profile?",!0))){console.log(`${T.dim}No changes made.${T.reset}
|
|
596
|
+
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
597
|
+
${T.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${T.reset}`);let l=await _e("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${T.red} Name is required.${T.reset}`);continue}let u=await _e("Host / IP address");if(!u){console.log(`${T.red} Host is required.${T.reset}`);continue}let d=await _e("SSH user","root"),f=await _e("SSH port","22"),m=parseInt(f,10)||22,h=await _e("SSH key path (leave empty for SSH agent)",""),p=await Xc("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Nt("Allow sudo commands?",!0),w={host:u,user:d};m!==22&&(w.port=m),h&&(w.key=h),p!=="other"&&(w.os=p),g&&(w.sudo=!0),o[l]=w,console.log(`
|
|
573
598
|
${T.green}\u2713${T.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await Nt(`
|
|
574
|
-
Add another server?`,!1)}
|
|
599
|
+
Add another server?`,!1)}he.existsSync(t)||he.mkdirSync(t,{recursive:!0}),he.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
575
600
|
`,"utf-8"),console.log(`
|
|
576
|
-
${T.green}\u2713 Saved .nex/servers.json (${Object.keys(
|
|
601
|
+
${T.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${T.reset}`);let a=Pt.join(process.cwd(),".gitignore");he.existsSync(a)&&(he.readFileSync(a,"utf-8").includes(".nex/")||await Nt("Add .nex/ to .gitignore?",!0)&&(he.appendFileSync(a,`
|
|
577
602
|
# nex-code server profiles
|
|
578
603
|
.nex/
|
|
579
604
|
`),console.log(`${T.green}\u2713 Added .nex/ to .gitignore${T.reset}`))),await Nt(`
|
|
580
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
605
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await Vc(o,t),console.log(`
|
|
581
606
|
${T.dim}Use /servers to list profiles, /servers ping to check connectivity.${T.reset}
|
|
582
|
-
`)}async function
|
|
607
|
+
`)}async function Vc(t,e){let s=e||Pt.join(process.cwd(),Yc),n=Pt.join(s,"deploy.json"),o={};if(he.existsSync(n))try{o=JSON.parse(he.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Pt.join(s,"servers.json");if(he.existsSync(u))try{t=JSON.parse(he.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
583
608
|
${T.bold}${T.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${T.reset}`),console.log(`${T.bold}${T.cyan}\u2551 Deploy Config Wizard \u2551${T.reset}`),console.log(`${T.bold}${T.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${T.reset}
|
|
584
|
-
`);let a=Object.keys(
|
|
585
|
-
${T.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${T.reset}`);let u=await
|
|
586
|
-
${T.green}\u2713${T.reset} Deploy config "${u}": ${
|
|
587
|
-
Add another deploy config?`,!1)}
|
|
609
|
+
`);let a=Object.keys(o);a.length>0&&console.log(`${T.dim}Existing deploy configs: ${a.join(", ")}${T.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
610
|
+
${T.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${T.reset}`);let u=await _e("Config name (e.g. prod, staging)");if(!u){console.log(`${T.red} Name is required.${T.reset}`);continue}let d;r.length>0?d=await Xc("Target server",r,r[0]):d=await _e("Target server (profile name or user@host)");let f=await _e("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await _e("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${T.red} Remote path is required.${T.reset}`);continue}let h=await _e("Deploy script to run after sync (leave empty to skip)",""),p=await _e("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],w={server:d,local_path:f,remote_path:m};h&&(w.deploy_script=h),g.length>0&&(w.exclude=g),c[u]=w;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
611
|
+
${T.green}\u2713${T.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${T.dim} Then: ${h}${T.reset}`),l=await Nt(`
|
|
612
|
+
Add another deploy config?`,!1)}he.existsSync(s)||he.mkdirSync(s,{recursive:!0}),he.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
588
613
|
`,"utf-8"),console.log(`
|
|
589
614
|
${T.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${T.reset}`),console.log(`${T.dim}Use: deploy prod (or with explicit params)${T.reset}
|
|
590
|
-
`)}
|
|
615
|
+
`)}Qc.exports={runServerWizard:tg,runDeployWizard:Vc,setWizardRL:eg}});var nl=N((O$,tl)=>{var ng=require("axios"),fn=require("fs"),el=require("path"),sg="nex-code",Go=el.join(process.cwd(),".nex"),Ko=el.join(Go,"last-version-check");fn.existsSync(Go)||fn.mkdirSync(Go,{recursive:!0});async function og(){try{let t=ig(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};ag(e);let s=rg(),o=(await ng.get(`https://registry.npmjs.org/${sg}/latest`,{timeout:5e3})).data.version,r=cg(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function rg(){return gn().version}function ig(){try{if(fn.existsSync(Ko)){let t=fn.readFileSync(Ko,"utf8");return parseInt(t,10)}}catch{}return null}function ag(t){try{fn.writeFileSync(Ko,t.toString())}catch{}}function cg(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}}tl.exports={checkForNewVersion:og}});var $l=N((N$,gl)=>{var lg=require("readline"),et=require("fs"),Le=require("path"),{C:i,banner:ug,cleanupTerminal:sl}=re(),{listProviders:Yo,getActiveProviderName:Qe,listAllModels:M$,setFallbackChain:dg,getFallbackChain:fg,getProvider:mg}=fe(),{flushAutoSave:ol}=at(),{getActiveModel:Ze,setActiveModel:rl}=Tn(),{printContext:il}=go(),{loadAllSkills:pg,getSkillCommands:Xo,handleSkillCommand:hg}=Ht(),{setReadlineInterface:gg,setAutoConfirm:$g,getAutoConfirm:al}=Ae(),{StickyFooter:yg}=jc(),ms=process.cwd(),ze=null;function cl(){return ze?.signal??null}var ps=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review",desc:"Code review on current diff or file"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function ll(){let t=Xo(),e=[...ps,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of ps)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o}${i.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
591
616
|
${i.dim}Type /help for detailed usage${i.reset}
|
|
592
|
-
`)}function
|
|
617
|
+
`)}function ul(t){try{let e,s;t.endsWith("/")||t.endsWith(Le.sep)?(e=t,s=""):(e=Le.dirname(t),s=Le.basename(t)),e.startsWith("~")&&(e=Le.join(require("os").homedir(),e.slice(1)));let n=Le.isAbsolute(e)?e:Le.resolve(ms,e);if(!et.existsSync(n)||!et.statSync(n).isDirectory())return[];let o=et.readdirSync(n,{withFileTypes:!0}),r=[];for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules"||s&&!a.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Le.sep)?t:Le.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function dl(t){if(t.startsWith("/")){let n=[...ps,...Xo()],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("~"))?[ul(s),s]:[[],t]}function fl(){console.log(`
|
|
593
618
|
${i.bold}${i.cyan}Commands:${i.reset}
|
|
594
619
|
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
595
620
|
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
@@ -650,114 +675,115 @@ ${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
|
650
675
|
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
651
676
|
|
|
652
677
|
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
653
|
-
`)}function
|
|
654
|
-
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let
|
|
655
|
-
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=
|
|
656
|
-
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:
|
|
657
|
-
${
|
|
658
|
-
`),!0)}case"/budget":{let{getCostLimits:
|
|
659
|
-
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let
|
|
678
|
+
`)}function ml(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(s)}${i.dim}${"\u2591".repeat(n)}${i.reset} ${t}%`}function Jo(){let t=Yo(),e=Qe(),s=Ze();console.log(`
|
|
679
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${n.provider}${i.reset}${a}`);for(let c of n.models){let l=c.id===s.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function pl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return fl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Uc();await r(e)}else{let r=Ze(),a=Qe();console.log(`${i.bold}${i.cyan}Active model:${i.reset} ${i.dim}${a}:${r.id} (${r.name})${i.reset}`),console.log(`${i.gray}Use /model <provider:model> to switch. /providers to see all.${i.reset}`)}return!0}if(o==="list")return Jo(),!0;if(rl(o)){let r=Ze(),a=Qe();console.log(`${i.green}Switched to ${a}:${r.id} (${r.name})${i.reset}`)}else console.log(`${i.red}Unknown model: ${o}${i.reset}`),console.log(`${i.gray}Use /providers to see available models${i.reset}`);return!0}case"/providers":return Jo(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let a=fg();return a.length===0?(console.log(`${i.dim}No fallback chain configured${i.reset}`),console.log(`${i.dim}Use /fallback anthropic,openai,local to set${i.reset}`)):console.log(`${i.bold}${i.cyan}Fallback chain:${i.reset} ${a.join(" \u2192 ")}`),!0}let r=o.split(",").map(a=>a.trim()).filter(Boolean);return dg(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=ae(),{getUsage:r}=Ce(),{TOOL_DEFINITIONS:a}=De(),c=o(),l=r(c,a),u=Ze(),d=Qe();console.log(`
|
|
680
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=ml(l.percentage);return console.log(` ${f}`),console.log(`
|
|
681
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=wt();return n.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
682
|
+
${o()}
|
|
683
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=wt(),d=n[0];if(!d){let h=o(),p=Yo();console.log(`
|
|
684
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let w of p){let $=r(w.provider),x=h[w.provider];if(x!==void 0){g=!0;let R=Math.min(100,Math.round($/x*100)),_=10,k=Math.round(R/100*_),E=_-k,A=`${R>=100?i.red:R>=80?i.yellow:i.green}${"\u2588".repeat(k)}${i.dim}${"\u2591".repeat(E)}${i.reset}`;console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${R}%) ${A}`)}else w.provider==="ollama"||w.provider==="local"?console.log(` ${i.bold}${w.provider}:${i.reset} ${i.dim}free (no limit)${i.reset}`):$>0&&console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} ${i.dim}(no limit)${i.reset}`)}return g||console.log(` ${i.dim}No limits set. Use /budget <provider> <amount> to set one.${i.reset}`),console.log(),!0}let f=n[1];if(!f){let h=a(d);return h.limit!==null?console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} ${i.dim}(no limit)${i.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${i.green}Removed cost limit for ${d}${i.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${i.red}Invalid amount: ${f}. Use a positive number or 'off'.${i.reset}`),!0):(u(d,m),l(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=ae(),{clearHistory:a}=xt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=Ho();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${i.green}${f} learning(s) saved${i.reset}
|
|
660
685
|
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
661
686
|
`)}).catch(()=>process.stdout.write(`
|
|
662
|
-
`))}return
|
|
663
|
-
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:
|
|
664
|
-
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/brain":{let{listDocuments:
|
|
665
|
-
|
|
666
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${i.green}Created .nex/brain/${h}.md${i.reset}`),console.log(`${i.dim}Edit it directly at: ${g}${i.reset}`)}else{let g=h.substring(0,p),
|
|
667
|
-
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map(
|
|
668
|
-
${i.bold}${i.cyan}Brain Search: "${h}"${i.reset}`);for(let g of p){let
|
|
669
|
-
${i.cyan}${g.name}${i.reset} ${i.dim}(score: ${
|
|
687
|
+
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await il(ms),!0;case"/autoconfirm":{let o=!al();return $g(o),console.log(`${i.green}Auto-confirm: ${o?"ON":"OFF"}${i.reset}`),o&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:o}=at(),{getConversationMessages:r}=ae(),a=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let l=Ze(),u=Qe();return o(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:o}=at(),{setConversationMessages:r}=ae(),a=n.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=o(a);return c?(r(c.messages),console.log(`${i.green}Loaded session: ${c.name} (${c.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:o}=at(),r=o();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
688
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=at(),{setConversationMessages:r}=ae(),a=o();return a?(r(a.messages),console.log(`${i.green}Resumed: ${a.name} (${a.messageCount} messages)${i.reset}`),!0):(console.log(`${i.yellow}No session to resume${i.reset}`),!0)}case"/remember":{let{remember:o}=Ve(),r=n.join(" ").trim();if(!r)return console.log(`${i.red}Usage: /remember <key>=<value> or /remember <text>${i.reset}`),!0;let a=r.indexOf("="),c,l;return a>0?(c=r.substring(0,a).trim(),l=r.substring(a+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:o}=Ve(),r=n.join(" ").trim();return r?(o(r)?console.log(`${i.green}Forgotten: ${r}${i.reset}`):console.log(`${i.red}Memory not found: ${r}${i.reset}`),!0):(console.log(`${i.red}Usage: /forget <key>${i.reset}`),!0)}case"/memory":{let{listMemories:o}=Ve(),r=o();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
689
|
+
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:a,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=tn(),m=n[0],h=n.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${i.red}Usage: /brain add <name> [content]${i.reset}`),console.log(`${i.dim} /brain add api-notes \u2014 creates empty file${i.reset}`),console.log(`${i.dim} /brain add api-notes This is content \u2014 writes directly${i.reset}`),!0;let p=h.indexOf(" ");if(p<0){a(h,`# ${h}
|
|
690
|
+
|
|
691
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${i.green}Created .nex/brain/${h}.md${i.reset}`),console.log(`${i.dim}Edit it directly at: ${g}${i.reset}`)}else{let g=h.substring(0,p),w=h.substring(p+1);a(g,w),console.log(`${i.green}Added to brain: ${g}${i.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${i.dim}No brain documents yet. Use /brain add <name> to create one.${i.reset}`),!0;console.log(`
|
|
692
|
+
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),w=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(w)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(w)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),R=Array.isArray(x.tags)?x.tags.join(", "):"",_=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,k=$.modified.toLocaleDateString();console.log(` ${i.cyan}${$.name.padEnd(g+2)}${i.reset}${i.dim}${R.substring(0,w-1).padEnd(w)}${_.padStart(7)} ${k}${i.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${i.red}Usage: /brain search <query>${i.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${i.dim}No matching brain documents for: ${h}${i.reset}`),!0;console.log(`
|
|
693
|
+
${i.bold}${i.cyan}Brain Search: "${h}"${i.reset}`);for(let g of p){let w=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
694
|
+
${i.cyan}${g.name}${i.reset} ${i.dim}(score: ${w})${i.reset}`),console.log(` ${i.dim}${g.excerpt||""}${i.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${i.red}Usage: /brain show <name>${i.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
670
695
|
${i.bold}${i.cyan}${h}.md${i.reset}
|
|
671
|
-
`),console.log(p.content),!0):(console.log(`${i.red}Document not found: ${h}${i.reset}`),!0)}case"remove":{if(!h)return console.log(`${i.red}Usage: /brain remove <name>${i.reset}`),!0;let{confirm:p}=
|
|
672
|
-
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(
|
|
696
|
+
`),console.log(p.content),!0):(console.log(`${i.red}Document not found: ${h}${i.reset}`),!0)}case"remove":{if(!h)return console.log(`${i.red}Usage: /brain remove <name>${i.reset}`),!0;let{confirm:p}=Ae();if(!await p(`Remove brain document "${h}"?`))return console.log(`${i.dim}Cancelled${i.reset}`),!0;let w=c(h);return console.log(w?`${i.green}Removed: ${h}.md${i.reset}`:`${i.red}Document not found: ${h}${i.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${i.green}Index rebuilt: ${g} document(s)${i.reset}`),!0}case"embed":{if(!await d())return console.log(`${i.yellow}Ollama embedding model not available.${i.reset}`),console.log(`${i.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${i.reset}`),!0;console.log(`${i.dim}Building embedding index...${i.reset}`);try{let g=await u(),w=Object.keys(g.documents||{}).length;console.log(`${i.green}Embedding index built: ${w} document(s)${i.reset}`)}catch(g){console.log(`${i.red}Embedding failed: ${g.message}${i.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),w=require("path"),$=w.join(process.cwd(),".nex","brain",".brain-index.json"),x=w.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
697
|
+
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?i.green+"present"+i.reset:i.dim+"not built"+i.reset}`),console.log(` Embeddings: ${g.existsSync(x)?i.green+"present"+i.reset:i.dim+"not built (run /brain embed)"+i.reset}`),p.length>0){let R=p.reduce((_,k)=>_+k.size,0);console.log(` Total size: ${R<1024?R+"B":(R/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),w=g(p);try{let{stdout:$}=await w("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
673
698
|
${i.bold}${i.cyan}Brain Changes (git diff):${i.reset}
|
|
674
|
-
`),console.log(
|
|
699
|
+
`),console.log($)):console.log(`${i.dim}No pending brain changes (clean git state)${i.reset}`)}catch{console.log(`${i.dim}Not a git repo or no brain dir${i.reset}`)}return!0}case"undo":{let p=require("fs"),w=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(w))return console.log(`${i.dim}No brain directory found${i.reset}`),!0;let $=o();if($.length===0)return console.log(`${i.dim}No brain documents to undo${i.reset}`),!0;let x=$[0],{exec:R}=require("child_process"),{promisify:_}=require("util"),k=_(R);try{await k(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${i.green}Undone: restored ${x.name}.md from git${i.reset}`)}catch{console.log(`${i.red}Could not undo \u2014 not tracked in git or no prior version${i.reset}`)}return!0}default:{let p=o();if(p.length===0)console.log(`
|
|
675
700
|
${i.bold}${i.cyan}Brain Knowledge Base${i.reset}`),console.log(`${i.dim}No documents yet. Create with /brain add <name>${i.reset}`),console.log(`
|
|
676
701
|
${i.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${i.reset}
|
|
677
702
|
`);else{console.log(`
|
|
678
|
-
${i.bold}${i.cyan}Brain: ${p.length} document(s)${i.reset}`);for(let g of p){let{frontmatter:
|
|
703
|
+
${i.bold}${i.cyan}Brain: ${p.length} document(s)${i.reset}`);for(let g of p){let{frontmatter:w}=r(g.name),$=Array.isArray(w.tags)?` [${w.tags.join(", ")}]`:"";console.log(` ${i.cyan}${g.name}${i.reset}${i.dim}${$}${i.reset}`)}console.log(`
|
|
679
704
|
${i.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${i.reset}
|
|
680
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:
|
|
705
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Ho(),{getConversationMessages:a}=ae(),c=a(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${l})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${i.dim}Session too short${i.reset}`),!0;u.error&&console.log(`${i.red}Reflection error: ${u.error}${i.reset}`),console.log(""),u.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${u.summary}${i.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(f){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:p,value:g,action:w}of u.applied){let $=w==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}${i.reset} = ${g}`)}}if(m){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let p of u.nexAdded)console.log(` ${i.green}+${i.reset} ${p}`)}if(h){console.log(`${i.bold}${i.cyan}Brain documents:${i.reset}`);for(let{name:p,reason:g,action:w}of d.written){let $=w==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}.md${i.reset}${g?i.dim+" \u2014 "+g+i.reset:""}`)}}}console.log("")}catch(u){console.log(`${i.red}Learn failed: ${u.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=ae(),{getUsage:r}=Ce(),{TOOL_DEFINITIONS:a}=De(),{listMemories:c}=Ve(),l=o(),u=r(l,a),d=Ze(),f=Qe(),m=c();console.log(`
|
|
681
706
|
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
682
707
|
`);let h=u.percentage>80?i.red:u.percentage>50?i.yellow:i.green;if(console.log(`${i.bold}Context Window:${i.reset} ${h}${u.percentage}%${i.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${i.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${i.reset}`):u.percentage>50?console.log(` ${i.dim}\u2192 Context is filling up, consider /clear soon${i.reset}`):console.log(` ${i.green}\u2192 Context healthy${i.reset}`),console.log(`
|
|
683
|
-
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let
|
|
684
|
-
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let g=l.filter(
|
|
685
|
-
${i.bold}Session:${i.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let
|
|
686
|
-
${i.bold}Quick Wins:${i.reset}`);for(let
|
|
708
|
+
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let R=[...m].sort((E,C)=>new Date(C.updatedAt)-new Date(E.updatedAt))[0],_=R?Math.round((Date.now()-new Date(R.updatedAt))/6e4):null,k=_!==null?_<60?`${_}m ago`:`${Math.round(_/60)}h ago`:"?";console.log(` ${i.dim}Latest update: ${k}${i.reset}`),m.length>30&&console.log(` ${i.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${i.reset}`)}console.log(`
|
|
709
|
+
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
710
|
+
${i.bold}Session:${i.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
711
|
+
${i.bold}Quick Wins:${i.reset}`);for(let x of w)console.log(` ${i.cyan}\u2192${i.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=Tt(),{invalidateSystemPromptCache:d}=ae(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){a(),c(!1),d();let m=!!l();console.log(`${i.green}${i.bold}Plan approved!${i.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${i.dim}Plan mode disabled \u2014 all tools now available.${i.reset}`)}else console.log(`${i.red}No plan to approve. Enter plan mode first with /plan${i.reset}`);return!0}return c(!0),d(),console.log(`
|
|
687
712
|
${i.cyan}${i.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${i.reset}
|
|
688
713
|
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
689
714
|
${i.cyan}${i.bold}\u2502${i.reset} ${i.dim}Read-only tools only \xB7 /plan approve to execute${i.reset} ${i.cyan}${i.bold}\u2502${i.reset}
|
|
690
|
-
${i.cyan}${i.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:
|
|
691
|
-
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:
|
|
715
|
+
${i.cyan}${i.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:o}=Tt(),r=o();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
716
|
+
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=Tt(),c=n.join(" ").trim();return c?(r(c)?console.log(`${i.green}Autonomy: ${c}${i.reset}`):console.log(`${i.red}Unknown level: ${c}. Use: ${a.join(", ")}${i.reset}`),!0):(console.log(`${i.bold}${i.cyan}Autonomy:${i.reset} ${o()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:o}=cn(),r=o();console.log(`
|
|
692
717
|
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let c=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${c} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
693
718
|
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
694
|
-
`),!0}case"/allow":{let{setPermission:
|
|
719
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:c}=ot(),{confirm:l}=Ae();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${i.green}Committed: ${p} \u2014 ${u}${i.reset}`:`${i.red}Commit failed${i.reset}`),!0}if(!a())return console.log(`${i.yellow}No changes to commit${i.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${i.green} \u2713 Committed: ${h}${i.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=ot();return o()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=ot(),{processInput:a}=ae(),c=n.join(" ").trim(),l;if(c)l=`Do a thorough code review of \`${c}\`. Check for bugs, security issues, code quality, correctness, and suggest concrete improvements. Format findings by severity (critical, warning, suggestion).`;else{if(!o())return console.log(`${i.red}Not a git repository \u2014 try /review <file>${i.reset}`),!0;let[u,d]=await Promise.all([r(!1),r(!0)]),f=d||u;if(!f||!f.trim())return console.log(`${i.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${i.reset}`),!0;l=`Review the following code diff for bugs, security issues, code quality, and improvements. Format findings by severity (critical, warning, suggestion):
|
|
695
720
|
|
|
696
721
|
\`\`\`diff
|
|
697
722
|
${f.substring(0,2e4)}
|
|
698
|
-
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:
|
|
723
|
+
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:a}=ot();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let l=a(c);return console.log(l?`${i.green}Created and switched to: ${l}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:a}=Nn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${i.dim}Connecting MCP servers...${i.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${i.red}\u2717${i.reset} ${d.name}: ${d.error}`):console.log(` ${i.green}\u2713${i.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${i.dim}No MCP servers configured in .nex/config.json${i.reset}`)}).catch(u=>{console.log(`${i.red}MCP connection error: ${u.message}${i.reset}`)}),!0;if(c==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let l=o();if(l.length===0)return console.log(`${i.dim}No MCP servers configured${i.reset}`),console.log(`${i.dim}Add servers to .nex/config.json under "mcpServers"${i.reset}`),!0;console.log(`
|
|
699
724
|
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of l){let d=u.connected?`${i.green}\u2713 connected${i.reset}`:`${i.dim}\u25CB disconnected${i.reset}`;console.log(` ${d} ${i.bold}${u.name}${i.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
700
725
|
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
701
|
-
`),!0}case"/hooks":{let{listHooks:
|
|
702
|
-
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:
|
|
726
|
+
`),!0}case"/hooks":{let{listHooks:o}=Ro(),r=o();if(r.length===0)return console.log(`${i.dim}No hooks configured${i.reset}`),console.log(`${i.dim}Add hooks to .nex/config.json or .nex/hooks/${i.reset}`),!0;console.log(`
|
|
727
|
+
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:a}=Ht(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${i.green}Skill enabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return a(u)?console.log(`${i.yellow}Skill disabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}let l=o();if(l.length===0)return console.log(`${i.dim}No skills loaded${i.reset}`),console.log(`${i.dim}Add .md or .js files to .nex/skills/${i.reset}`),!0;console.log(`
|
|
703
728
|
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of l){let d=u.enabled?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,f=u.type==="prompt"?`${i.dim}(prompt)${i.reset}`:`${i.dim}(script)${i.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${i.bold}${u.name}${i.reset} ${f}${h}`)}return console.log(`
|
|
704
729
|
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
705
|
-
`),!0}case"/tasks":{let{renderTaskList:
|
|
706
|
-
`+
|
|
707
|
-
`),!0)}case"/undo":{let{undo:
|
|
730
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Bn();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
731
|
+
`+o()+`
|
|
732
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=xt(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to undo${i.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=xt(),a=o();if(!a)return console.log(`${i.yellow}Nothing to redo${i.reset}`),!0;console.log(`${i.green}Redone: ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:a}=xt(),c=o(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
708
733
|
${i.bold}File Change History${i.reset}
|
|
709
734
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${l.tool}${i.reset} ${l.filePath}`)}return console.log(`
|
|
710
735
|
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
711
|
-
`),!0}case"/k8s":{let
|
|
736
|
+
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:a}=require("util"),c=a(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
712
737
|
${i.bold}${i.cyan}Kubernetes Overview${i.reset}${l?i.dim+" (remote: "+l+")"+i.reset:""}
|
|
713
738
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
714
739
|
`).filter(Boolean);console.log(`${i.bold}Namespaces (${m.length}):${i.reset}`);for(let h of m)console.log(` ${i.cyan}${h}${i.reset}`);console.log()}catch{return console.log(`${i.dim}Could not reach cluster \u2014 is kubectl configured?${i.reset}
|
|
715
740
|
`),!0}try{let{stdout:f}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),m=f.trim().split(`
|
|
716
|
-
`).filter(Boolean),h=m.filter(
|
|
717
|
-
`);let
|
|
741
|
+
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${i.bold}Pods: ${m.length} total ${i.green}${h} running${i.reset} ${i.yellow}${p} pending${i.reset} ${i.red}${g} unhealthy${i.reset}
|
|
742
|
+
`);let w=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(w.length>0){console.log(`${i.bold}${i.red}Unhealthy Pods:${i.reset}`);for(let $ of w)console.log(` ${i.red}${$}${i.reset}`);console.log()}console.log(`${i.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${i.reset}`),console.log(`${i.dim}Or: /k8s user@host to query a remote cluster${i.reset}
|
|
718
743
|
`)}catch(f){console.log(`${i.dim}Could not list pods: ${f.message}${i.reset}
|
|
719
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:
|
|
744
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:a}=vt(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
720
745
|
${i.dim}No servers configured. Create .nex/servers.json:${i.reset}`),console.log(`${i.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${i.reset}
|
|
721
746
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
722
|
-
${i.bold}${i.cyan}Server connectivity:${i.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await a(h,"echo ok",{timeout:8e3});console.log(p===0?` ${i.green}\u2713${i.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${i.red}\u2717${i.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=
|
|
747
|
+
${i.bold}${i.cyan}Server connectivity:${i.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await a(h,"echo ok",{timeout:8e3});console.log(p===0?` ${i.green}\u2713${i.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${i.red}\u2717${i.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=vt();console.log(`
|
|
723
748
|
${i.bold}${i.cyan}Configured servers (${l.length}):${i.reset}`);for(let f of l)console.log(` ${i.green}${f}${i.reset} ${i.dim}${d(f,c[f])}${i.reset}`);return console.log(`
|
|
724
749
|
${i.dim}/servers ping \u2014 check SSH connectivity for all servers${i.reset}`),console.log(`${i.dim}/servers ping <name> \u2014 check a specific server${i.reset}
|
|
725
|
-
`),!0}case"/docker":{let{loadServerProfiles:
|
|
726
|
-
${i.bold}${i.cyan}Docker Containers:${i.reset}`);for(let[m,h]of f){let p=m==="local"?`${i.dim}local${i.reset}`:`${i.cyan}${m}${i.reset}`;try{let g;if(m==="local"){let{stdout:
|
|
727
|
-
`).forEach(
|
|
750
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=vt(),{exec:a}=require("child_process"),{promisify:c}=require("util"),l=c(a),u=n[0]==="-a"||n[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
751
|
+
${i.bold}${i.cyan}Docker Containers:${i.reset}`);for(let[m,h]of f){let p=m==="local"?`${i.dim}local${i.reset}`:`${i.cyan}${m}${i.reset}`;try{let g;if(m==="local"){let{stdout:w}=await l(u,{timeout:8e3});g=(w||"").trim()}else{let w=await r(h,u,{timeout:1e4});if(g=[w.stdout,w.stderr].filter(Boolean).join("").trim(),w.exitCode!==0){console.log(` ${p}: ${i.red}SSH error (${w.exitCode})${i.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${i.dim}(no containers)${i.reset}`):(console.log(` ${p}:`),g.split(`
|
|
752
|
+
`).forEach(w=>console.log(` ${i.dim}${w}${i.reset}`)))}catch(g){console.log(` ${p}: ${i.red}${g.message}${i.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Js(),r=o(),a=Object.keys(r),c=n[0];if(c&&a.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=De();console.log(`
|
|
728
753
|
${i.bold}Running deploy: ${c}${l?" (dry run)":""}${i.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(a.length===0)return console.log(`
|
|
729
754
|
${i.dim}No deploy configs. Run /init to create .nex/deploy.json${i.reset}
|
|
730
755
|
`),!0;console.log(`
|
|
731
756
|
${i.bold}${i.cyan}Deploy configs (${a.length}):${i.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",f=`${u.server}:${u.remote_path}`,m=u.deploy_script?` ${i.dim}\u2192 ${u.deploy_script}${i.reset}`:"";console.log(` ${i.green}${l}${i.reset} ${i.dim}${d} \u2192 ${f}${i.reset}${m}`)}return console.log(`
|
|
732
757
|
${i.dim}/deploy <name> \u2014 run a named deploy${i.reset}`),console.log(`${i.dim}/deploy <name> --dry-run \u2014 preview without syncing${i.reset}
|
|
733
|
-
`),!0}case"/init":{let{runServerWizard:
|
|
734
|
-
${i.dim}Bye!${i.reset}`),process.exit(0);default:return
|
|
735
|
-
`).filter(Boolean).slice(-
|
|
736
|
-
`)}catch{}}function
|
|
737
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
758
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:a}=Zc();return a(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":console.log(`
|
|
759
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return hg(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var Vo=1e3;function Qo(){return Le.join(process.cwd(),".nex","repl_history")}function hl(){try{let t=Qo();if(et.existsSync(t))return et.readFileSync(t,"utf-8").split(`
|
|
760
|
+
`).filter(Boolean).slice(-Vo)}catch{}return[]}function fs(t){try{let e=Qo(),s=Le.dirname(e);et.existsSync(s)||et.mkdirSync(s,{recursive:!0}),et.appendFileSync(e,t+`
|
|
761
|
+
`)}catch{}}function ke(){let{isPlanMode:t,getAutonomyLevel:e}=Tt(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=Qe(),r=Ze(),a=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(a),`${s.length>0?`${i.dim}[${s.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var Zo="\x1B[200~",er="\x1B[201~";function wg(t){return typeof t=="string"&&t.includes(Zo)}function bg(t){return typeof t=="string"&&t.includes(er)}function mn(t){return typeof t!="string"?t:t.split(Zo).join("").split(er).join("")}async function xg(){if(!mg("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"),rl("local:llama3"),!0}catch{return!1}}async function _g(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ae();t(cl);let o=Yo().some(M=>M.configured),r=(async()=>{pg();let M=Ze(),L=Qe();return{model:M,providerName:L}})(),a=(async()=>o?!0:await xg()?(console.log(`${i.green}\u2713 Local Ollama detected \u2014 using local models${i.reset}`),console.log(`${i.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${i.reset}
|
|
762
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:M}=nl();return await M()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!o&&(console.error(`
|
|
738
763
|
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
739
|
-
`),process.exit(1)),
|
|
740
|
-
`),await
|
|
741
|
-
${i.dim}Bye!${i.reset}
|
|
742
|
-
|
|
764
|
+
`),process.exit(1));let f=hl(),m=lg.createInterface({input:process.stdin,output:process.stdout,prompt:ke(),completer:dl,history:f,historySize:Vo});gg(m);let h=new yg;h.activate(m);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;ug(p,ms,{yolo:al()}),d.hasNewVersion&&console.log(`${i.yellow}\u{1F4A1} New version available!${i.reset} Run ${i.cyan}npm update -g nex-code${i.reset} to upgrade from ${i.dim}${d.currentVersion}${i.reset} to ${i.green}${d.latestVersion}${i.reset}
|
|
765
|
+
`),await il(ms);let g=!1,w=0,$=!1,x=null;function R(){ol(),h.deactivate(),sl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write(`
|
|
766
|
+
${i.dim}Bye!${i.reset}
|
|
767
|
+
`),process.exit(0)}process.on("SIGTERM",R),process.on("exit",()=>{ol()}),m.on("SIGINT",()=>{if(sl(),g){if(w++,w>=2){R();return}ze&&ze.abort();let{cancelPendingAskUser:M}=De();M(),console.log(`
|
|
768
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),g=!1,m.setPrompt(ke()),m.prompt();return}$?R():($=!0,process.stdout.write(`
|
|
743
769
|
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
744
|
-
`),m.setPrompt(
|
|
745
|
-
`).trim();if(
|
|
746
|
-
`)
|
|
747
|
-
|
|
748
|
-
`))
|
|
749
|
-
`))
|
|
750
|
-
`)),
|
|
751
|
-
|
|
752
|
-
\x1B[2K ${i.
|
|
753
|
-
|
|
754
|
-
`)
|
|
755
|
-
`).
|
|
756
|
-
`)
|
|
757
|
-
`).
|
|
758
|
-
`)[0]
|
|
759
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
760
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)})}
|
|
770
|
+
`),m.setPrompt(ke()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||R()});let _=!1,k=[],E=0,C={},A=!1;function D(){let M=k.join(`
|
|
771
|
+
`).replace(/\r/g,"").trim();if(k=[],_=!1,!M)return!0;E++,A=!0;let L=E;C[L]=M;let G=M.split(`
|
|
772
|
+
`).length,Q=G>1?`[Pasted content #${L} \u2014 ${G} lines]`:`[Pasted content #${L}]`,I=m.line||"",K=I&&!I.endsWith(" ")?" ":"",B=I+K+Q;return m.setPrompt(ke()),m.prompt(),m.line=B,m.cursor=B.length,m._refreshLine(),!0}function q(M){return M.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,G)=>C[Number(G)]||"")}function ue(){E=0,C={},A=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let M=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(L,...G){if(L!=="data")return M.call(process.stdin,L,...G);let Q=G[0];if(Buffer.isBuffer(Q)&&(Q=Q.toString("utf8")),typeof Q!="string")return M.call(process.stdin,L,...G);let I=Q.includes(Zo),K=Q.includes(er);if(I&&K){let B=mn(Q);return B&&k.push(...B.split(`
|
|
773
|
+
`)),D()}if(I){_=!0,k=[];let B=mn(Q);return B&&k.push(...B.split(`
|
|
774
|
+
`)),!0}if(K){let B=mn(Q);return B&&k.push(...B.split(`
|
|
775
|
+
`)),D()}if(_){let B=mn(Q);return B&&k.push(...B.split(`
|
|
776
|
+
`)),!0}return M.call(process.stdin,L,...G)}}let z=0;function W(){if(z>0){let M="";for(let L=0;L<z;L++)M+="\x1B[1B\x1B[2K";M+=`\x1B[${z}A`,process.stdout.write(M),z=0}}function te(M){let L=[...ps,...Xo()].filter(H=>H.cmd.startsWith(M));if(!L.length||L.length===1&&L[0].cmd===M)return;let G=10,Q=L.slice(0,G),I=Math.max(...Q.map(H=>H.cmd.length)),K="";for(let{cmd:H,desc:be}of Q){let Lt=H.substring(0,M.length),qe=H.substring(M.length),qt=" ".repeat(Math.max(0,I-H.length+2));K+=`
|
|
777
|
+
\x1B[2K ${i.cyan}${Lt}${i.reset}${i.dim}${qe}${qt}${be}${i.reset}`}z=Q.length,L.length>G&&(K+=`
|
|
778
|
+
\x1B[2K ${i.dim}\u2026 +${L.length-G} more${i.reset}`,z++);let B=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;K+=`\x1B[${z}A\x1B[${B+m.cursor+1}G`,process.stdout.write(K)}process.stdin.isTTY&&process.stdin.on("keypress",(M,L)=>{W(),!(L&&(L.name==="tab"||L.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&te(m.line)})});let Y=null,Ge=`${i.dim}...${i.reset} `;m.setPrompt(ke()),m.prompt(),m.on("line",async M=>{if(W(),Object.keys(C).length>0&&(M=q(M),ue(),m.setPrompt(ke())),g){let I=M.trim();if(I){let{injectMidRunNote:K}=ae();K(I),process.stdout.write(`${i.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${i.reset}
|
|
779
|
+
`)}return}if(Y!==null){if(Y._mode==="triple"){if(M.trim()==='"""'){let I=Y.join(`
|
|
780
|
+
`).trim();if(Y=null,I){fs(I.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(I)}catch(B){if(!ze?.signal?.aborted){let H=B.message?.split(`
|
|
781
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${H}${i.reset}`)}}g=!1;let K=G();K>0&&process.stdout.write(`${i.gray}[${K} messages] ${i.reset}`)}m.setPrompt(ke()),m.prompt();return}Y.push(M),m.setPrompt(Ge),m.prompt();return}if(M.endsWith("\\"))Y.push(M.slice(0,-1));else{Y.push(M);let I=Y.join(`
|
|
782
|
+
`).trim();if(Y=null,I){fs(I.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(I)}catch(H){if(!ze?.signal?.aborted){let be=H.message?.split(`
|
|
783
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${be}${i.reset}`)}}let{getConversationLength:K}=ae();g=!1;let B=K();B>0&&process.stdout.write(`${i.gray}[${B} messages] ${i.reset}`)}m.setPrompt(ke()),m.prompt();return}m.setPrompt(Ge),m.prompt();return}if(M.trim()==='"""'||M.trim().startsWith('"""')){let I=M.trim().substring(3);Y=I?[I]:[],Y._mode="triple",m.setPrompt(Ge),m.prompt();return}if(M.endsWith("\\")){Y=[M.slice(0,-1)],Y._mode="backslash",m.setPrompt(Ge),m.prompt();return}let L=M.trim();if(!L){m.setPrompt(ke()),m.prompt();return}if(fs(L),L==="/"){ll(),m.setPrompt(ke()),m.prompt();return}if(L.startsWith("/")){await pl(L,m),m.setPrompt(ke()),m.prompt();return}if(A){let I=L.split(`
|
|
784
|
+
`),K=I.length,B=I[0].length>120?I[0].substring(0,117)+"\u2026":I[0],H=K>1?` ${i.cyan}[+${K-1} lines]${i.reset}`:"";console.log(`${i.dim} \u2570 ${B}${H}${i.reset}`)}g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(L)}catch(I){if(!ze?.signal?.aborted){let K=I.message?.split(`
|
|
785
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${K}${i.reset}`)}}g=!1;let{getConversationLength:G}=ae(),Q=G();Q>0&&process.stdout.write(`${i.gray}[${Q} messages] ${i.reset}`),m.setPrompt(ke()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
786
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}gl.exports={startREPL:_g,getPrompt:ke,loadHistory:hl,appendHistory:fs,getHistoryPath:Qo,HISTORY_MAX:Vo,showCommandList:ll,completer:dl,completeFilePath:ul,handleSlashCommand:pl,showProviders:Jo,showHelp:fl,renderBar:ml,hasPasteStart:wg,hasPasteEnd:bg,stripPasteSequences:mn,getAbortSignal:cl}});var bl=require("path");require("dotenv").config({path:bl.join(__dirname,"..",".env")});require("dotenv").config();var oe=process.argv.slice(2);(oe.includes("--help")||oe.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
761
787
|
|
|
762
788
|
Options:
|
|
763
789
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -770,4 +796,4 @@ Options:
|
|
|
770
796
|
--json Output result as JSON (for CI parsing)
|
|
771
797
|
-h, --help Show this help
|
|
772
798
|
-v, --version Show version
|
|
773
|
-
`),process.exit(0));if(
|
|
799
|
+
`),process.exit(0));if(oe.includes("-v")||oe.includes("--version")){let t=gn();console.log(t.version),process.exit(0)}var kg=oe.includes("--yolo")||oe.includes("-yolo");if(kg){let{setAutoConfirm:t}=Ae();t(!0)}var tr=oe.indexOf("--model");if(tr!==-1&&oe[tr+1]){let{setActiveModel:t}=fe();t(oe[tr+1])}var nr=oe.indexOf("--max-turns");if(nr!==-1&&oe[nr+1]){let t=parseInt(oe[nr+1],10);if(t>0){let{setMaxIterations:e}=ae();e(t)}}else try{let t=require("fs"),e=bl.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}=ae();o(n)}}}catch{}function sr(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}function yl(t){if(oe.includes("--auto")){let{setAutoConfirm:o}=Ae();o(!0)}if(!oe.includes("--model")){let{setActiveModel:o}=fe(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=ae();s(t).then(()=>{if(oe.includes("--json")){let r=n().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{oe.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var wl=oe.indexOf("--prompt-file");if(wl!==-1){let t=oe[wl+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)),oe.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}sr(),yl(s)}else{let t=oe.indexOf("--task");if(t!==-1){let e=oe[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),sr(),yl(e)}else{sr();let{startREPL:e}=$l();e()}}
|