nex-code 0.3.22 → 0.3.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +167 -5
- package/dist/nex-code.js +427 -252
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,127 +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 P=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var dn=P((mg,hl)=>{hl.exports={name:"nex-code",version:"0.3.23",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 ur=P((pg,lr)=>{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"},ir=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ar=["\u273D","\u2726","\u2727","\u2726"],hs=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ir[this.frame%ir.length],o="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let s=Math.floor(n/60),r=n%60;o=` ${O.dim}${s}m ${String(r).padStart(2,"0")}s${O.reset}`}else n>=1&&(o=` ${O.dim}${n}s${O.reset}`)}process.stderr.write(`\x1B[2K\r${O.cyan}${e}${O.reset} ${O.dim}${this.text}${O.reset}${o}`),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}},cr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gs=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 o=Math.floor(e/60),n=e%60;return o>0?`${o}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=cr[this.frame%cr.length],o=this._formatElapsed(),n=o?` ${O.dim}${o}${O.reset}`:"",s="";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:"";s+=`\x1B[2K ${a} ${c}${this.labels[r]}${O.reset}${l}
|
|
3
|
+
`}this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let o=0;o<this.lineCount;o++)e+=`
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,o){e>=0&&e<this.statuses.length&&(this.statuses[e]=o)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),o=e?` ${O.dim}${e}${O.reset}`:"",n="";for(let s=0;s<this.labels.length;s++){let r;switch(this.statuses[s]){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=s===this.labels.length-1?o:"";n+=`\x1B[2K ${r} ${O.dim}${this.labels[s]}${O.reset}${a}
|
|
5
|
+
`}process.stderr.write(n)}},fn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},mn={done:O.green,in_progress:O.cyan,pending:O.dim,failed:O.red},He=null,$s=class{constructor(e,o){this.name=e,this.tasks=o.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 o=Math.floor(e/60),n=e%60;return o>0?`${o}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=ar[this.frame%ar.length],o=this._formatElapsed(),n=this._formatTokens(),s=[o,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${O.dim}(${s})${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=fn[l.status]||fn.pending,f=mn[l.status]||mn.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 o=0;o<this.lineCount;o++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),He=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,He===this&&(He=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let o=0;o<this.lineCount;o++)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 o=0;o<this.lineCount;o++)e+=`
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,o){let n=this.tasks.find(s=>s.id===e);n&&(n.status=o)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),o=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,s=this.tasks.length,r=n>0?`${o}/${s} done, ${n} failed`:`${o}/${s} 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=fn[l.status]||fn.pending,f=mn[l.status]||mn.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 gl(t){He=t}function $l(){return He}function yl(){He&&(He.stop(),He=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}lr.exports={C:O,Spinner:hs,MultiProgress:gs,TaskProgress:$s,setActiveTaskProgress:gl,getActiveTaskProgress:$l,cleanupTerminal:yl}});var fr=P((hg,dr)=>{var Z={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 wl(t,e){let o;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":o=e.path||"";break;case"bash":o=(e.command||"").substring(0,80);break;case"grep":case"search_files":o=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":o=e.pattern||"";break;case"web_fetch":o=(e.url||"").substring(0,60);break;case"web_search":o=(e.query||"").substring(0,50);break;default:o=JSON.stringify(e).substring(0,80)}let n=o?`${Z.dim}(${o})${Z.reset}`:"";return`${Z.cyan}\u23FA${Z.reset} ${Z.bold}${t}${Z.reset}${n}`}function bl(t,e=8){let o=t.split(`
|
|
13
|
+
`),n=o.slice(0,e),s=o.length-e,r=`${Z.dim} \u23BF ${Z.reset}`,a=" ",c=n.map((l,u)=>`${u===0?r:a}${Z.green}${l}${Z.reset}`).join(`
|
|
14
|
+
`);return s>0&&(c+=`
|
|
15
|
+
${Z.gray} \u2026+${s} more lines${Z.reset}`),c}function xl(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 kl(t,e,o,n){let s=String(o||"");if(n){let a=s.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=s.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
+
${Z.dim}${c[1].substring(0,100)}${Z.reset}`:"";return` ${Z.red}\u23BF ${a}${Z.reset}${l}`}let r;switch(t){case"read_file":{let a=s.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=s.match(/^EXIT (\d+)/);if(a){let c=a[1],l=s.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=s.split(`
|
|
20
|
+
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=s.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(s.includes("(no matches)")||s==="no matches")r="No matches";else{let a=s.split(`
|
|
22
|
+
`).filter(Boolean).length;r=`${a} match${a!==1?"es":""}`}break}case"glob":{if(s==="(no matches)")r="No files found";else{let a=s.split(`
|
|
23
|
+
`).filter(Boolean).length;r=`${a} file${a!==1?"s":""} found`}break}case"list_directory":{let a=s==="(empty)"?0:s.split(`
|
|
24
|
+
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=s.match(/Branch:\s*(\S+)/),c=s.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=(s.match(/^\+[^+]/gm)||[]).length,c=(s.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=s.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=s.split(`
|
|
27
|
+
|
|
28
|
+
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(s.match(/✓ Agent/g)||[]).length,c=(s.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=s.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${Z.dim}\u23BF ${r}${Z.reset}`}dr.exports={C:Z,formatToolCall:wl,formatResult:bl,getToolSpinnerText:xl,formatToolSummary:kl}});var ee=P((gg,mr)=>{var mt={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 vl(t,e){return[...t].map(o=>o===" "?o:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${o}`).join("")+mt.reset}function _l(t,e){let o=(t.length-1)*e,n=Math.min(Math.floor(o),t.length-2),s=o-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*s),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*s),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*s)]}function Sl(t,e,o={}){let n=mt.bold,s=mt.dim,r=mt.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 vl(d,_l(c,m))}).join(`
|
|
29
|
+
`),u=o.yolo?` ${n}${mt.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`)};return
|
|
35
|
-
`);h=
|
|
31
|
+
${s}Agentic Coding CLI v${dn().version}${r}
|
|
32
|
+
${s}Model: ${t}${r} ${s}\xB7 /help${r}${u}
|
|
33
|
+
`)}var{Spinner:El,MultiProgress:Cl,TaskProgress:Tl,setActiveTaskProgress:Rl,getActiveTaskProgress:Al,cleanupTerminal:Nl}=ur(),{formatToolCall:Ml,formatResult:Ol,getToolSpinnerText:Pl,formatToolSummary:ql}=fr();mr.exports={C:mt,banner:Sl,Spinner:El,MultiProgress:Cl,TaskProgress:Tl,setActiveTaskProgress:Rl,getActiveTaskProgress:Al,cleanupTerminal:Nl,formatToolCall:Ml,formatResult:Ol,getToolSpinnerText:Pl,formatToolSummary:ql}});var Ce=P(($g,wr)=>{var Il=require("readline"),{C:pn}=ee(),pr=[/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/],ys=[/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 hr(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 s=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=>s(u)):ys.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:ys.some(c=>c.test(a))};return n.every(s)}var bs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],gr=[/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/],$r=[...bs,...gr],xs=!1,ws=null;function Ll(t){xs=t}function jl(){return xs}function Dl(t){ws=t}function Fl(t){for(let e of pr)if(e.test(t))return e;return null}function Ul(t){if(/ssh\s/.test(t)&&hr(t))return!1;for(let e of $r)if(e.test(t))return!0;return!1}function Bl(t){for(let e of bs)if(e.test(t))return!0;return!1}function Wl(t,e={}){if(xs)return Promise.resolve(!0);let o=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let s=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(yr(e.toolName),n(!0)):n(a!=="n")};if(ws)ws.question(`${pn.yellow}${t} ${o}${pn.reset}`,s);else{let r=Il.createInterface({input:process.stdin,output:process.stdout});r.question(`${pn.yellow}${t} ${o}${pn.reset}`,a=>{r.close(),s(a)})}})}var yr=()=>{};function Hl(t){yr=t}wr.exports={FORBIDDEN_PATTERNS:pr,SSH_SAFE_PATTERNS:ys,isSSHReadOnly:hr,DANGEROUS_BASH:$r,CRITICAL_BASH:bs,NOTABLE_BASH:gr,isForbidden:Fl,isDangerous:Ul,isCritical:Bl,confirm:Wl,setAutoConfirm:Ll,getAutoConfirm:jl,setReadlineInterface:Dl,setAllowAlwaysHandler:Hl}});var pt=P((yg,br)=>{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,o,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,o,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`)}};br.exports={BaseProvider:ks}});var vr=P((wg,kr)=>{var hn=require("axios"),zl=require("http"),Gl=require("https"),{BaseProvider:Kl}=pt(),gn=new zl.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),$n=new Gl.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),xr={"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 Kl{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||xr,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){hn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:gn,httpsAgent:$n}).then(e=>{let o=e.data?.models||[];for(let n of o){let s=(n.name||n.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:n.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let o=(await hn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:gn,httpsAgent:$n})).data?.models||[];for(let n of o){let s=(n.name||n.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:n.name||s,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(o=>{if(o.role==="user"&&Array.isArray(o.content)){let n=[],s=[];for(let a of o.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&s.push(a.data);let r={role:"user",content:n.join(`
|
|
34
|
+
`)};return s.length>0&&(r.images=s),r}return o})}async chat(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||16384,c=await hn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:gn,httpsAgent:$n});return this.normalizeResponse(c.data)}async stream(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await hn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:gn,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 y of g){if(!y.trim())continue;let w;try{w=JSON.parse(y)}catch{continue}if(w.message?.content&&(c(w.message.content),f+=w.message.content),w.message?.tool_calls&&(m=m.concat(w.message.tool_calls)),w.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 o=e.message||{};return{content:o.content||"",tool_calls:this._normalizeToolCalls(o.tool_calls||[])}}_normalizeToolCalls(e){return e.map((o,n)=>({id:o.id||`ollama-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}};kr.exports={OllamaProvider:vs,OLLAMA_MODELS:xr}});var Rr=P((bg,Tr)=>{var{callChat:Jl}=ie(),{estimateTokens:_s}=ke(),_r=process.env.NEX_COMPACTION!=="false",Sr=6,Er=500,Yl=`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 Xl(t){if(!_r||t.length<Sr)return null;let e=[{role:"system",content:Yl},{role:"user",content:Cr(t)}];try{let n=((await Jl(e,[],{temperature:0,maxTokens:Er})).content||"").trim();if(!n)return null;let s=t.reduce((a,c)=>a+_s(c.content||"")+(c.tool_calls?_s(JSON.stringify(c.tool_calls)):0),0),r=_s(n);return r>=s*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function Cr(t){return t.map(e=>{let o=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${o}] ${n}
|
|
42
|
+
tools: ${s}`}return`[${o}] ${n}`}).join(`
|
|
43
43
|
|
|
44
|
-
`)}
|
|
45
|
-
`);if(
|
|
44
|
+
`)}Tr.exports={compactMessages:Xl,formatMessagesForSummary:Cr,COMPACTION_ENABLED:_r,COMPACTION_MIN_MESSAGES:Sr,COMPACTION_SUMMARY_BUDGET:Er}});var ke=P((xg,jr)=>{function Mr(){return ie().getActiveModel()}var Vl={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},qt=new Map,Ar=1e3,yn=new WeakMap,ht=new Map,Nr=500,It=null;function Ql(){if(It!==null)return It;try{let e=Mr()?.provider||"ollama";return It=Vl[e]||4,It}catch{return 4}}function Zl(){It=null}function et(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)}`,o=qt.get(e);if(o!==void 0)return o;let n=Math.ceil(t.length/Ql());if(qt.size>=Ar){let s=Ar>>1,r=qt.keys();for(let a=0;a<s;a++)qt.delete(r.next().value)}return qt.set(e,n),n}function eu(t){if(yn.has(t))return yn.get(t);let e=Or(t);if(ht.has(e)){let n=ht.get(e);return yn.set(t,n),n}let o=JSON.stringify(t);if(ht.size>=Nr){let n=Nr>>1,s=ht.keys();for(let r=0;r<n;r++)ht.delete(s.next().value)}return ht.set(e,o),yn.set(t,o),o}function Or(t){let e=t.role||"",o=typeof t.content=="string"?t.content.substring(0,100):"",n=t.tool_calls?t.tool_calls.length:0;return`${e}:${o.length}:${n}`}function gt(t){let o=4;if(t.content&&(o+=et(t.content)),t.tool_calls)for(let n of t.tool_calls){o+=4,o+=et(n.function?.name||"");let s=n.function?.arguments;typeof s=="string"?o+=et(s):s&&(o+=et(JSON.stringify(s)))}return o}function ve(t){let e=0;for(let o of t)e+=gt(o);return e}function tu(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 o=t?t.length:0,n=e.length,s=0;for(let r=o;r<n;r++)s+=gt(e[r]);return s}function wn(t){return!t||t.length===0?0:et(JSON.stringify(t))}function bn(){return Mr()?.contextWindow||32768}function nu(t,e){let o=ve(t),n=wn(e),s=o+n,r=bn(),a=r>0?s/r*100:0,c=0,l=0,u=0;for(let d of t){let f=gt(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:s,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Pr=.75,qr=.1,Ir=10,su=200,ou=500;function Lr(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 s=t.split(`
|
|
45
|
+
`);if(s.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,p),w=t.substring(t.length-g);return y+`
|
|
46
46
|
...(${t.length} chars total)...
|
|
47
|
-
|
|
47
|
+
`+w}let r=Math.floor(s.length*.4),a=Math.floor(s.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<r&&l<u;p++)c.push(s[p]),l+=s[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=s.length-1;p>=s.length-a&&f<m;p--)d.unshift(s[p]),f+=s[p].length+1;let h=s.length-c.length-d.length;return c.join(`
|
|
48
48
|
`)+`
|
|
49
|
-
...(${h} lines omitted, ${
|
|
49
|
+
...(${h} lines omitted, ${s.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 Lt(t,e="light"){let o=e==="aggressive"?100:e==="medium"?200:ou,n=e==="aggressive"?50:e==="medium"?100:su;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>n?{...t,content:Lr(s,n)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>o&&(s.content=s.content.substring(0,o)+`
|
|
52
|
+
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.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}}))),s}return t}async function ru(t,e,o={}){let n=o.threshold??Pr,s=o.safetyMargin??qr,r=o.keepRecent??Ir,a=bn(),c=wn(e),l=Math.floor(a*(n-s)),u=l-c,d=ve(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),y=t.slice(p,g),w=t.slice(g),k=y.filter(C=>!C._compacted);if(k.length>=6)try{let{compactMessages:C}=Rr(),A=await C(k);if(A){let L=[...y.filter(F=>F._compacted),A.message],N=Ze(h,L,w),M=ve(N);if(M+c<=l)return{messages:N,compressed:!0,compacted:!0,tokensRemoved:m-M};y=L}}catch{}let E=(f-l)/l,x=y.map(C=>Lt(C,"light")),v=Ze(h,x,w),S=ve(v);if(S+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-S};if(x=y.map(C=>Lt(C,"medium")),v=Ze(h,x,w),S=ve(v),S+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-S};if(x=y.map(C=>Lt(C,"aggressive")),v=Ze(h,x,w),S=ve(v),S+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-S};for(;x.length>0&&S+c>u;){let C=x.shift();S-=gt(C)}return v=Ze(h,x,w),S=ve(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-S}}function Ze(t,e,o){let n=[];return t&&n.push(t),n.push(...e,...o),n}function iu(t,e){if(!t)return"";if(et(t)<=e)return t;let n=e*4,s=t.split(`
|
|
53
|
+
`),r=Math.floor(n*.6),a=Math.floor(n*.4),c="",l=0;for(let h of s){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
|
+
`:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let p=s[h]+(u?`
|
|
55
55
|
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
56
56
|
|
|
57
|
-
... (${
|
|
57
|
+
... (${s.length-l-d} lines omitted, ${s.length} total) ...
|
|
58
58
|
|
|
59
|
-
`;return c+m+u}var
|
|
60
|
-
`);
|
|
59
|
+
`;return c+m+u}var au=6;function cu(t,e){let o=bn(),n=wn(e),s=Math.floor(o*.5)-n,r=ve(t),a=null,c=0;t.length>0&&t[0].role==="system"&&(a=t[0],c=1);let l=Math.max(c,t.length-au),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Lt(p,"aggressive")),m=Ze(a,f,d),h=ve(m);for(;f.length>0&&h>s;){let p=f.shift();h-=gt(p)}return m=Ze(a,f,d),h=ve(m),{messages:m,tokensRemoved:r-h}}jr.exports={estimateTokens:et,estimateMessageTokens:gt,estimateMessagesTokens:ve,estimateDeltaTokens:tu,estimateToolsTokens:wn,serializeMessage:eu,getMessageCacheKey:Or,getContextWindow:bn,getUsage:nu,compressMessage:Lt,compressToolResult:Lr,fitToContext:ru,forceCompress:cu,truncateFileContent:iu,invalidateTokenRatioCache:Zl,COMPRESSION_THRESHOLD:Pr,SAFETY_MARGIN:qr,KEEP_RECENT:Ir}});var Br=P((vg,Ur)=>{var Dr=require("axios"),{BaseProvider:lu}=pt(),{serializeMessage:kg}=ke(),Fr={"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}},Ss=class extends lu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Fr,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 o=[];for(let n of e){if(this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let s=this._getMessageCacheKey(n);if(this._messageStringCache.has(s)){let a=this._messageStringCache.get(s);this._messageFormatCache.set(n,a),o.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(n,r),o.push(r)}return{messages:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(o=>({id:o.id||`call-${Date.now()}`,type:"function",function:{name:o.function.name,arguments:typeof o.function.arguments=="string"?o.function.arguments:JSON.stringify(o.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 o=[];for(let n of e.content)if(n.type==="text")o.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let s=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;o.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:o}}return{role:e.role,content:e.content}}async chat(e,o,n={}){let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};o&&o.length>0&&(l.tools=o);let u=await Dr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};o&&o.length>0&&(u.tools=o);let d;try{d=await Dr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
60
|
+
`);g=w.pop()||"";for(let k of w){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let x=E.slice(6);if(x==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(x)}catch{continue}let S=v.choices?.[0]?.delta;if(S&&(S.content&&(c(S.content),h+=S.content),S.tool_calls))for(let C of S.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",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let o=e.choices?.[0]?.message||{},n=(o.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:o.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(o=>o.name).map(o=>({id:o.id||`openai-${Date.now()}`,function:{name:o.name,arguments:o.arguments}}))}};Ur.exports={OpenAIProvider:Ss,OPENAI_MODELS:Fr}});var Gr=P((Sg,zr)=>{var Wr=require("axios"),{BaseProvider:uu}=pt(),{serializeMessage:_g}=ke(),Hr={"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}},du="2023-06-01",Es=class extends uu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Hr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||du}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 o="",n=[];for(let s of e){if(s.role==="system"){o+=(o?`
|
|
61
61
|
|
|
62
|
-
`:"")+
|
|
63
|
-
`);
|
|
64
|
-
`);
|
|
65
|
-
`)};return
|
|
66
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw
|
|
62
|
+
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,n);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(s);this._messageStringCache.set(a,r),this._messageFormatCache.set(s,r)}n.push(r)}}return{messages:n,system:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e,o=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)n.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=o[o.length-1],s={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(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let n=[];for(let s of e.content)s.type==="text"?n.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&n.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(o=>({name:o.function.name,description:o.function.description||"",input_schema:o.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,o,n={}){let s=n.model||this.defaultModel,r=this._resolveModelId(s),a=this.getModel(s),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(o);f.length>0&&(d.tools=f);let m=await Wr.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,r=this._resolveModelId(s),a=this.getModel(s),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(o);m.length>0&&(f.tools=m);let h;try{h=await Wr.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let y="",w=[],k=-1,E="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",x=>{E+=x.toString();let v=E.split(`
|
|
63
|
+
`);E=v.pop()||"";for(let S of v){let C=S.trim();if(C.startsWith("data: ")){let A=C.slice(6),I;try{I=JSON.parse(A)}catch{continue}switch(I.type){case"content_block_start":{let L=I.content_block;L?.type==="tool_use"&&(k=w.length,w.push({id:L.id,name:L.name,inputJson:""}));break}case"content_block_delta":{let L=I.delta;L?.type==="text_delta"&&L.text&&(l(L.text),y+=L.text),L?.type==="input_json_delta"&&L.partial_json!==void 0&&k>=0&&(w[k].inputJson+=L.partial_json);break}case"content_block_stop":k=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls(w)});return}}}}),h.data.on("error",x=>{n.signal?.aborted||g(new Error(`Stream error: ${x.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls(w)})})})}normalizeResponse(e){let o="",n=[];for(let s of e.content||[])s.type==="text"?o+=s.text:s.type==="tool_use"&&n.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:o,tool_calls:n}}_buildToolCalls(e){return e.filter(o=>o.name).map(o=>{let n={};if(o.inputJson)try{n=JSON.parse(o.inputJson)}catch{n=o.inputJson}return{id:o.id||`anthropic-${Date.now()}`,function:{name:o.name,arguments:n}}})}};zr.exports={AnthropicProvider:Es,ANTHROPIC_MODELS:Hr}});var Xr=P((Cg,Yr)=>{var Kr=require("axios"),{BaseProvider:fu}=pt(),{serializeMessage:Eg}=ke(),Jr={"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}},Cs=class extends fu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Jr,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 o=[];for(let n of e){if(this._messageFormatCache.has(n)){o.push(this._messageFormatCache.get(n));continue}let s=this._getMessageCacheKey(n);if(this._messageStringCache.has(s)){let a=this._messageStringCache.get(s);this._messageFormatCache.set(n,a),o.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(n,r),o.push(r)}return{messages:o}}_getMessageCacheKey(e){let o=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${o}:${n.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(o=>({id:o.id||`call-${Date.now()}`,type:"function",function:{name:o.function.name,arguments:typeof o.function.arguments=="string"?o.function.arguments:JSON.stringify(o.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 o=[];for(let n of e.content)if(n.type==="text")o.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let s=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;o.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:o}}return{role:e.role,content:e.content}}async chat(e,o,n={}){let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:s,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};o&&o.length>0&&(l.tools=o);let u=await Kr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,o,n={}){let s=n.model||this.defaultModel,r=this.getModel(s),a=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};o&&o.length>0&&(u.tools=o);let d;try{d=await Kr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
64
|
+
`);g=w.pop()||"";for(let k of w){let E=k.trim();if(!E||!E.startsWith("data: "))continue;let x=E.slice(6);if(x==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(x)}catch{continue}let S=v.choices?.[0]?.delta;if(S&&(S.content&&(c(S.content),h+=S.content),S.tool_calls))for(let C of S.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",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let o=e.choices?.[0]?.message||{},n=(o.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:o.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(o=>o.name).map(o=>({id:o.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:o.name,arguments:o.arguments}}))}};Yr.exports={GeminiProvider:Cs,GEMINI_MODELS:Jr}});var Zr=P((Tg,Qr)=>{var xn=require("axios"),{BaseProvider:mu}=pt(),Vr="http://localhost:11434",Ts=class extends mu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Vr,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 o=(await xn.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of o){let s=n.name||n.model;if(!s)continue;let r=s.replace(/:latest$/,""),a=32768;try{let c=await xn.post(`${this.baseUrl}/api/show`,{name:s},{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(o=>{if(o.role==="user"&&Array.isArray(o.content)){let n=[],s=[];for(let a of o.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&s.push(a.data);let r={role:"user",content:n.join(`
|
|
65
|
+
`)};return s.length>0&&(r.images=s),r}return o})}async chat(e,o,n={}){this._modelsLoaded||await this.loadModels();let s=n.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=await xn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,o,n={}){this._modelsLoaded||await this.loadModels();let s=n.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),a;try{a=await xn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict: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 o=e.message||{};return{content:o.content||"",tool_calls:this._normalizeToolCalls(o.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let o=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return o?parseInt(o[1],10):null}_normalizeToolCalls(e){return e.map((o,n)=>({id:o.id||`local-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}};Qr.exports={LocalProvider:Ts,DEFAULT_LOCAL_URL:Vr}});var $t=P((Rg,ii)=>{var tt=require("fs"),Rs=require("path"),ei={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:{}},kn=[],ze={};function pu(t,e,o,n){if(kn.push({provider:t,model:e,input:o,output:n}),ze[t]!==void 0){let s=oi(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
|
|
67
|
+
`)}}function As(t,e){let o=ei[t];return o?o[e]||{input:0,output:0}:{input:0,output:0}}function ti(t){let e=As(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ni(){let t={};for(let r of kn){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:ti(r)})),o=e.reduce((r,a)=>r+a.cost,0),n=e.reduce((r,a)=>r+a.input,0),s=e.reduce((r,a)=>r+a.output,0);return{totalCost:o,totalInput:n,totalOutput:s,breakdown:e}}function hu(){let{totalCost:t,totalInput:e,totalOutput:o,breakdown:n}=ni();if(n.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of n){let a=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${a}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${o.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
|
|
68
|
+
`)}function gu(t,e,o,n){let s=As(t,e),r=(o*s.input+n*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function $u(){kn=[]}function yu(t,e){ze[t]=e}function wu(t){delete ze[t]}function bu(){return{...ze}}function si(t){let e=0;for(let o of kn)o.provider===t&&(e+=ti(o));return e}function oi(t){let e=si(t),o=ze[t];if(o===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,o-e);return{allowed:e<o,spent:e,limit:o,remaining:n}}function ri(){let t=Rs.join(process.cwd(),".nex","config.json");if(tt.existsSync(t))try{let e=JSON.parse(tt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(ze={...e.costLimits})}catch{}}function xu(){let t=Rs.join(process.cwd(),".nex"),e=Rs.join(t,"config.json"),o={};if(tt.existsSync(e))try{o=JSON.parse(tt.readFileSync(e,"utf-8"))}catch{o={}}o.costLimits=ze,tt.existsSync(t)||tt.mkdirSync(t,{recursive:!0}),tt.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function ku(){ze={}}ri();ii.exports={PRICING:ei,trackUsage:pu,getSessionCosts:ni,formatCosts:hu,formatCostHint:gu,resetCosts:$u,getPricing:As,setCostLimit:yu,removeCostLimit:wu,getCostLimits:bu,getProviderSpend:si,checkBudget:oi,loadCostLimits:ri,saveCostLimits:xu,resetCostLimits:ku}});var vn=P((Ag,ai)=>{var jt=ie(),vu={"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 _u(){return jt.getActiveModel()}function Su(t){return jt.setActiveModel(t)}function Eu(){return jt.getModelNames()}function Cu(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 o=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(o)try{return JSON.parse(o[1].trim())}catch{}return null}async function Tu(t,e){let{C:o}=ee(),{Spinner:n}=ee(),s=new n("Thinking...");s.start();let r=!0,a="";try{let c=await jt.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${o.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?s.stop():process.stdout.write(`${o.reset}
|
|
69
|
+
`),c}catch(c){throw s.stop(),c}}async function Ru(t,e){return jt.callChat(t,e)}ai.exports={MODELS:vu,getActiveModel:_u,setActiveModel:Su,getModelNames:Eu,callOllamaStream:Tu,callOllama:Ru,parseToolArgs:Cu}});var ui=P((Ng,li)=>{var _n=require("path"),{C:b}=ee(),{confirm:Au,getAutoConfirm:Nu}=Ce(),ci=2e3;function Dt(t,e){let o=t.split(`
|
|
70
70
|
`),n=e.split(`
|
|
71
|
-
`),
|
|
72
|
-
${
|
|
73
|
-
${
|
|
74
|
-
${
|
|
75
|
-
`),n=
|
|
76
|
-
${
|
|
77
|
-
`)}function
|
|
78
|
-
${
|
|
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
|
-
${
|
|
82
|
-
`).filter(Boolean).map(e=>{let
|
|
83
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
${
|
|
71
|
+
`),s=[],r=o.length,a=n.length;if(r>ci||a>ci){for(let f of o)s.push({type:"remove",line:f});for(let f of n)s.push({type:"add",line:f});return s}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++)o[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&&o[l-1]===n[u-1]?(d.unshift({type:"same",line:o[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:o[l-1]}),l--);return d}function Mu(t,e,o,n=3){console.log(`
|
|
72
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let s=Dt(e,o),r=[];if(s.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(s.length,r[r.length-1]+n+1);a>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=a;l<c;l++){let u=s[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<s.length&&console.log(`${b.gray} ...${b.reset}`),console.log()}function Ou(t,e,o){console.log(`
|
|
73
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Dt(e,o),s=0;for(let a of n)a.type!=="same"&&s++;if(s===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} ...(${s-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 Pu(t,e){console.log(`
|
|
74
|
+
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let o=e.split(`
|
|
75
|
+
`),n=o.slice(0,20);for(let s of n)console.log(`${b.green} + ${s}${b.reset}`);o.length>20&&console.log(`${b.gray} ...+${o.length-20} more lines${b.reset}`),console.log()}async function qu(t){return Nu()?!0:Au(` ${t}?`)}function Iu(t,e,o,n){let s=n||process.stdout.columns||80,r=Math.floor((s-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=Dt(e,o),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 y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",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)}`,y=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${b.reset}
|
|
77
|
+
`)}function Lu(t,e,o,n={}){let s=n.label||"Update",r=n.context||3,a=n.annotations||[],c=_n.isAbsolute(t)?_n.relative(process.cwd(),t):t,l=Dt(e,o),u=1,d=1;for(let x of l)x.type==="same"?(x.oldLine=u++,x.newLine=d++):x.type==="remove"?(x.oldLine=u++,x.newLine=null):(x.oldLine=null,x.newLine=d++);let f=0,m=0;for(let x of l)x.type==="add"?f++:x.type==="remove"&&m++;if(console.log(`
|
|
78
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}${s}(${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 x=a.filter(A=>A.severity==="error").length,v=a.filter(A=>A.severity==="warn").length,S=a.filter(A=>A.severity==="info").length,C=[];x>0&&C.push(`${b.red}${x} error${x!==1?"s":""}${b.dim}`),v>0&&C.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),S>0&&C.push(`${b.cyan}${S} info${S!==1?"s":""}${b.dim}`),h.push(`found ${C.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((x,v)=>{x.type!=="same"&&g.push(v)});let y=[],w=null,k=null;for(let x of g){let v=Math.max(0,x-r),S=Math.min(l.length-1,x+r);w===null?(w=v,k=S):(v<=k+1||(y.push([w,k]),w=v),k=S)}w!==null&&y.push([w,k]);let E=" ";for(let x=0;x<y.length;x++){x>0&&console.log(`${E}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,S]=y[x];for(let C=v;C<=S;C++){let A=l[C],I=A.newLine!=null?A.newLine:A.oldLine,L=String(I).padStart(4),N=A.type!=="remove"?a.filter(M=>M.line===A.newLine):[];A.type==="remove"?console.log(`${E}${b.red}${L} -${A.line}${b.reset}`):A.type==="add"?console.log(`${E}${b.green}${L} +${A.line}${b.reset}`):console.log(`${E}${b.dim}${L}${b.reset} ${A.line}`);for(let M of N){let F=b.cyan,j="\u2139";M.severity==="error"?(F=b.red,j="\u2716"):M.severity==="warn"&&(F=b.yellow,j="\u26A0"),console.log(`${E} ${F}${j} ${M.message}${b.reset}`)}}}console.log()}function ju(t,e,o={}){let n=_n.isAbsolute(t)?_n.relative(process.cwd(),t):t,s=e.split(`
|
|
80
|
+
`),r=o.annotations||[];console.log(`
|
|
81
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let a=[`${s.length} line${s.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(s.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} +${s[d]}${b.reset}`);for(let p of h){let g=b.cyan,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}s.length>20&&console.log(`${l}${b.dim} ...+${s.length-20} more lines${b.reset}`),console.log()}li.exports={diffLines:Dt,showEditDiff:Mu,showWriteDiff:Ou,showNewFilePreview:Pu,confirmFileChange:qu,showSideBySideDiff:Iu,showClaudeDiff:Lu,showClaudeNewFile:ju}});var nt=P((Mg,mi)=>{var di=require("util").promisify(require("child_process").exec),Du=require("util").promisify(require("child_process").execFile),{C:X}=ee();async function Ns(t){try{let{stdout:e}=await di(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Sn(...t){try{let{stdout:e}=await Du("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Fu(){return await Ns("git rev-parse --is-inside-work-tree")==="true"}async function Uu(){return await Ns("git branch --show-current")}async function Ms(){try{let{stdout:t}=await di("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
82
|
+
`).filter(Boolean).map(e=>{let o=e.substring(0,2).trim(),n=e.substring(3);return{status:o,file:n}})}catch{return[]}}async function En(t=!1){return await Ns(`git diff ${t?"--cached":""}`)||""}async function Os(){return(await Ms()).map(e=>e.file)}async function fi(){let t=await Os();if(t.length===0)return null;let e=await En(),n=await En(!0)||e,s=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":s>r*2?a="feat":r>s?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:s,deletions:r}}}async function Bu(t){let o=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Sn("checkout","-b",o)!==null?o:null}async function Wu(t){return await Sn("add","-A"),await Sn("commit","-m",t)?await Sn("rev-parse","--short","HEAD"):null}async function Hu(){let t=await fi();if(!t)return`${X.dim}No changes${X.reset}`;let e=[];e.push(`
|
|
84
|
+
${X.bold}${X.cyan}Git Diff Summary:${X.reset}`),e.push(` ${X.green}+${t.stats.additions}${X.reset} ${X.red}-${t.stats.deletions}${X.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
|
+
${X.bold}${X.cyan}Files:${X.reset}`);for(let o of t.files.slice(0,20))e.push(` ${X.dim}${o}${X.reset}`);return t.files.length>20&&e.push(` ${X.dim}...+${t.files.length-20} more${X.reset}`),e.push(`
|
|
86
|
+
${X.bold}${X.cyan}Suggested message:${X.reset}`),e.push(` ${X.cyan}${t.summary}${X.reset}
|
|
87
87
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
89
|
-
...(truncated)`:
|
|
88
|
+
`)}async function zu(){return(await Ms()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Gu(){let t=await Os();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let o=await En();if(o){let n=o.length>5e3?o.substring(0,5e3)+`
|
|
89
|
+
...(truncated)`:o;e.push(`
|
|
90
90
|
DIFF:
|
|
91
91
|
${n}`)}return e.join(`
|
|
92
|
-
`)}
|
|
92
|
+
`)}mi.exports={isGitRepo:Fu,getCurrentBranch:Uu,getStatus:Ms,getDiff:En,getChangedFiles:Os,analyzeDiff:fi,createBranch:Bu,commit:Wu,formatDiffSummary:Hu,getDiffContext:Gu,getMergeConflicts:zu}});var wt=P((Og,pi)=>{var Ps=require("fs").promises,Ku=50,Pe=[],yt=[];function Ju(t,e,o,n){for(Pe.push({tool:t,filePath:e,oldContent:o,newContent:n,timestamp:Date.now()});Pe.length>Ku;)Pe.shift();yt.length=0}async function Yu(){if(Pe.length===0)return null;let t=Pe.pop();if(t.oldContent===null)try{await Ps.unlink(t.filePath)}catch{}else await Ps.writeFile(t.filePath,t.oldContent,"utf-8");return yt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Xu(){if(yt.length===0)return null;let t=yt.pop();return await Ps.writeFile(t.filePath,t.newContent,"utf-8"),Pe.push(t),{tool:t.tool,filePath:t.filePath}}function Vu(t=10){return Pe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Qu(){return Pe.length}function Zu(){return yt.length}function ed(){Pe.length=0,yt.length=0}pi.exports={recordChange:Ju,undo:Yu,redo:Xu,getHistory:Vu,getUndoCount:Qu,getRedoCount:Zu,clearHistory:ed}});var Ft=P((Pg,bi)=>{var ge=require("fs"),bt=require("path"),fe=[];function qs(){return bt.join(process.cwd(),".nex","skills")}function hi(){return bt.join(process.cwd(),".nex","config.json")}function td(){let t=qs();return ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0}),t}function Is(){let t=hi();if(!ge.existsSync(t))return[];try{let e=JSON.parse(ge.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function gi(t){let e=hi(),o={};if(ge.existsSync(e))try{o=JSON.parse(ge.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t;let n=bt.dirname(e);ge.existsSync(n)||ge.mkdirSync(n,{recursive:!0}),ge.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function $i(t,e){let o=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&o.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&o.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&o.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))o.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let s=t.commands[n];(!s.cmd||typeof s.cmd!="string")&&o.push(`commands[${n}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&o.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))o.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let s=t.tools[n];(!s.function||!s.function.name||typeof s.function.name!="string")&&o.push(`tools[${n}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&o.push(`tools[${n}].execute must be a function`)}return{valid:o.length===0,errors:o}}function yi(t){try{let e=ge.readFileSync(t,"utf-8").trim();return e?{name:bt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function wi(t){try{let e=require(t),{valid:o,errors:n}=$i(e,t);return o?{name:e.name||bt.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 nd(){fe=[];let t=qs();if(!ge.existsSync(t))return fe;let e=Is(),o;try{o=ge.readdirSync(t)}catch{return fe}for(let n of o){let s=bt.join(t,n),r;try{r=ge.statSync(s)}catch{continue}if(!r.isFile())continue;let a=null;n.endsWith(".md")?a=yi(s):n.endsWith(".js")&&(a=wi(s)),a&&(a.enabled=!e.includes(a.name),fe.push(a))}return fe}function sd(){let t=[];for(let e of fe)!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 od(){let t=[];for(let e of fe)if(e.enabled)for(let o of e.commands)t.push({cmd:o.cmd,desc:o.desc||`[skill: ${e.name}]`});return t}function rd(){let t=[];for(let e of fe)if(e.enabled)for(let o of e.tools)t.push({type:"function",function:{name:`skill_${o.function.name}`,description:`[Skill:${e.name}] ${o.function.description}`,parameters:o.function.parameters}});return t}async function id(t,e){if(!t.startsWith("skill_"))return null;let o=t.substring(6);for(let n of fe)if(n.enabled){for(let s of n.tools)if(s.function.name===o&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${o}' failed: ${r.message}`}}return`ERROR: Skill tool '${o}' not found`}function ad(t){let[e,...o]=t.split(/\s+/),n=o.join(" ").trim();for(let s of fe)if(s.enabled){for(let r of s.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 cd(){return fe.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 ld(t){let e=fe.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let o=Is().filter(n=>n!==t);return gi(o),!0}function ud(t){let e=fe.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let o=Is();return o.includes(t)||(o.push(t),gi(o)),!0}function dd(){return fe}bi.exports={initSkillsDir:td,loadAllSkills:nd,getSkillInstructions:sd,getSkillCommands:od,getSkillToolDefinitions:rd,routeSkillCall:id,handleSkillCommand:ad,listSkills:cd,enableSkill:ld,disableSkill:ud,getLoadedSkills:dd,_getSkillsDir:qs,_validateScriptSkill:$i,_loadMarkdownSkill:yi,_loadScriptSkill:wi}});var Tn=P((qg,Ei)=>{var{spawn:fd}=require("child_process"),md=require("path"),xi=require("fs"),qe=new Map;function pd(){return md.join(process.cwd(),".nex","config.json")}function Ls(){let t=pd();if(!xi.existsSync(t))return{};try{return JSON.parse(xi.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Cn(t,e,o={},n=1e4){return new Promise((s,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:o})+`
|
|
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
|
|
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)}`)):s(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(qe.has(t))return qe.get(t);let o=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let a of o)process.env[a]&&(n[a]=process.env[a]);let s=fd(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await Cn(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await Cn(s,"tools/list",{});return r.tools=a&&a.tools||[],qe.set(t,r),r}catch(a){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function vi(t){let e=qe.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return qe.delete(t),!0}function hd(){for(let[t]of qe)vi(t)}async function _i(t,e,o={}){let n=qe.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let s=await Cn(n.proc,"tools/call",{name:e,arguments:o});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
101
|
+
`):JSON.stringify(s)}function Si(){let t=[];for(let[e,o]of qe)for(let n of o.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function gd(){return Si().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function $d(t,e){if(!t.startsWith("mcp_"))return null;let o=t.substring(4).split("_");if(o.length<2)return null;let n=o[0],s=o.slice(1).join("_");return _i(n,s,e)}function yd(){let t=Ls();return Object.entries(t).map(([e,o])=>{let n=qe.get(e);return{name:e,command:o.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function wd(){let t=Ls(),e=[];for(let[o,n]of Object.entries(t))try{let s=await ki(o,n);e.push({name:o,tools:s.tools.length})}catch(s){e.push({name:o,tools:0,error:s.message})}return e}Ei.exports={loadMCPConfig:Ls,sendRequest:Cn,connectServer:ki,disconnectServer:vi,disconnectAll:hd,callTool:_i,getAllTools:Si,getMCPToolDefinitions:gd,routeMCPCall:$d,listServers:yd,connectAll:wd}});var js=P((Ig,Ai)=>{var{getSkillToolDefinitions:bd}=Ft(),{getMCPToolDefinitions:xd}=Tn(),Rn=new Map;function Ci(){let{TOOL_DEFINITIONS:t}=Ie();return[...t,...bd(),...xd()]}function Ti(t){if(Rn.has(t))return Rn.get(t);let o=Ci().find(s=>s.function.name===t);if(!o)return null;let n=o.function.parameters;return Rn.set(t,n),n}function kd(){Rn.clear()}function An(t,e){if(!t||e.length===0)return null;let o=null,n=1/0;for(let s of e){let r=Ri(t.toLowerCase(),s.toLowerCase());r<n&&(n=r,o=s)}return n<=Math.ceil(t.length/2)?o:null}function Ri(t,e){let o=t.length,n=e.length,s=Array.from({length:o+1},()=>Array(n+1).fill(0));for(let r=0;r<=o;r++)s[r][0]=r;for(let r=0;r<=n;r++)s[0][r]=r;for(let r=1;r<=o;r++)for(let a=1;a<=n;a++)s[r][a]=t[r-1]===e[a-1]?s[r-1][a-1]:1+Math.min(s[r-1][a],s[r][a-1],s[r-1][a-1]);return s[o][n]}function vd(t,e){let o=Ti(t);if(o===null){let d=Ci().map(m=>m.function.name),f=An(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!o||!o.properties)return{valid:!0};let n=o.required||[],s=Object.keys(o.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=An(u,r);d&&!s.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${o.properties[u]?.description||o.properties[u]?.type||"unknown"})`)}for(let u of r)if(!s.includes(u)){let d=An(u,s);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(!o.properties[u])continue;let d=o.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(o.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Ai.exports={validateToolArgs:vd,closestMatch:An,levenshtein:Ri,getCachedSchema:Ti,clearSchemaCache:kd}});var Pi=P((Lg,Oi)=>{var{levenshtein:Nn}=js(),_d=200,Sd=.3,Ed=2;function Ds(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(Ed)).split(`
|
|
109
|
+
`).map(e=>{let o=e.replace(/\s+$/,""),n=o.match(/^(\s*)(.*)/);if(!n)return o;let[,s,r]=n;return s+r.replace(/ {2,}/g," ")}).join(`
|
|
110
|
+
`)}function Cd(t,e){if(t.includes(e))return e;let o=Ds(t),n=Ds(e);if(!o.includes(n))return null;let s=t.split(`
|
|
111
|
+
`),r=o.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)
|
|
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 s.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 s[u]}return null}function Td(t,e){if(!t||!e)return null;let o=t.split(`
|
|
115
|
+
`),s=e.split(`
|
|
116
|
+
`).length;return o.length===0||s===0?null:s===1?Rd(o,e):Nd(o,e,s)}function Ni(t){return Math.max(1,Math.floor(t/_d))}function Mi(t,e){return t<=Math.ceil(e*Sd)}function Rd(t,e){let o=e.trim(),n=Ni(t.length),s=null,r=1/0;for(let a=0;a<t.length;a+=n){let c=t[a];if(!c.trim())continue;let l=Nn(c.trim(),o);l<r&&(r=l,s={text:c,distance:l,line:a+1})}return s&&n>1&&(s=Ad(t,o,s,n)||s,r=s.distance),Mi(r,e.length)?s:null}function Ad(t,e,o,n){let s=o.line-1,r=Math.max(0,s-n),a=Math.min(t.length-1,s+n),c=o.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=Nn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Nd(t,e,o){let n=t.length-o+1;if(n<=0)return null;let s=Ni(n),r=null,a=1/0;for(let c=0;c<n;c+=s){let l=t.slice(c,c+o).join(`
|
|
117
|
+
`),u=Nn(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=Md(t,e,r,s,o,n)||r,a=r.distance),Mi(a,e.length)?r:null}function Md(t,e,o,n,s,r){let a=o.line-1,c=Math.max(0,a-n),l=Math.min(r-1,a+n),u=o.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+s).join(`
|
|
118
|
+
`),h=Nn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Oi.exports={normalizeWhitespace:Ds,fuzzyFindText:Cd,findMostSimilar:Td}});var Ii=P((Dg,qi)=>{var{C:jg}=ee(),Od=[{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}],Pd=[{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 qd(t,e){let o=e.split(`
|
|
119
|
+
`),n=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<o.length;r++){let a=o[r],c=r+1;for(let l of Od)l.regex.test(a)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Pd)l.ext&&!l.ext.includes(s)||l.regex.test(a)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return o.length>500&&n.push({line:0,message:`Large file detected (${o.length} lines). Consider refactoring.`,severity:"info"}),n}qi.exports={runDiagnostics:qd}});var Bs=P((Fg,Di)=>{var Id=require("fs").promises,Li=require("path"),{exec:Ld}=require("util").promisify(require("child_process").exec),xt=[],Us=null,Mn=!1,Fs=0,jd=6e4;function ji(t){return!(xt.length===0||Us!==t||Date.now()-Fs>jd)}async function Dd(t){if(!Mn&&!ji(t)){Mn=!0,Us=t;try{try{let{stdout:n}=await Ld("rg --files",{cwd:t,timeout:5e3});xt=n.split(`
|
|
120
|
+
`).filter(Boolean),Fs=Date.now(),Mn=!1;return}catch{}let e=[],o=async(n,s)=>{let r;try{r=await Id.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=s?`${s}/${a.name}`:a.name;a.isDirectory()?await o(Li.join(n,a.name),c):e.push(c)}};await o(t,""),xt=e,Fs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Mn=!1}}}function Fd(){return xt}function Ud(){return Us}function Bd(t){return xt.filter(e=>Li.basename(e)===t)}function Wd(t){let e=t.toLowerCase();return xt.filter(o=>o.toLowerCase().includes(e)).slice(0,20)}Di.exports={refreshIndex:Dd,getFileIndex:Fd,getIndexedCwd:Ud,findFileInIndex:Bd,searchIndex:Wd,isIndexValid:ji}});var kt=P((Ug,Wi)=>{var On=require("fs"),qn=require("path"),Ws=require("os"),{execFile:Hd}=require("child_process"),{promisify:zd}=require("util"),Hs=zd(Hd),Gd=qn.join(".nex","servers.json"),Pn=qn.join(Ws.tmpdir(),"nex-ssh-sockets");function Kd(){return qn.join(process.cwd(),Gd)}function Fi(){let t=Kd();if(!On.existsSync(t))return{};try{return JSON.parse(On.readFileSync(t,"utf-8"))}catch{return{}}}function Jd(t){let e=Fi();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let o=Object.keys(e),n=o.length?`Available profiles: ${o.join(", ")}`:"No profiles configured. Create .nex/servers.json";throw new Error(`Unknown server: "${t}". ${n}`)}function Yd(){On.existsSync(Pn)||On.mkdirSync(Pn,{recursive:!0})}function Ui(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ws.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Yd();let o=t.user?`${t.user}@${t.host}`:t.host,n=qn.join(Pn,o.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(o),{args:e,target:o}}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(/^~/,Ws.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Xd(t,e,{timeout:o=3e4,sudo:n=!1}={}){let{args:s}=Ui(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:a,stderr:c}=await Hs("ssh",[...s,r],{timeout:o,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:In(l,t)}}}async function Vd(t,e,o,{timeout:n=12e4}={}){let s=Bi(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${o}`);try{let{stdout:a,stderr:c}=await Hs("scp",s,{timeout:n,maxBuffer:1048576});return a||c||`Uploaded ${e} \u2192 ${r}:${o}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(In(c,t)||c)}}async function Qd(t,e,o,{timeout:n=12e4}={}){let s=Bi(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,o);try{let{stdout:a,stderr:c}=await Hs("scp",s,{timeout:n,maxBuffer:1048576});return a||c||`Downloaded ${r}:${e} \u2192 ${o}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(In(c,t)||c)}}function In(t,e){if(!t)return"";if(/connection refused/i.test(t)){let o=e.port||22;return`${t}
|
|
121
|
+
HINT: Connection refused on ${e.host}:${o}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${o} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let o=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
122
|
+
HINT: Auth failed using ${o} 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
|
+
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
|
+
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
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 Zd(t,e){let o=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",a=e.sudo?" sudo:yes":"";return`${t}: ${o}${n}${s}${r}${a}`}Wi.exports={loadServerProfiles:Fi,resolveProfile:Jd,buildSSHArgs:Ui,sshExec:Xd,scpUpload:Vd,scpDownload:Qd,enrichSSHError:In,formatProfile:Zd,SSH_SOCKET_DIR:Pn}});var Ks=P((Bg,zi)=>{var Ut=require("fs"),zs=require("path"),ef=zs.join(".nex","deploy.json");function Gs(){return zs.join(process.cwd(),ef)}function Hi(){let t=Gs();if(!Ut.existsSync(t))return{};try{return JSON.parse(Ut.readFileSync(t,"utf-8"))}catch{return{}}}function tf(t){let e=Hi();if(e[t])return{...e[t],_name:t};let o=Object.keys(e),n=o.length?`Available: ${o.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function nf(t){let e=zs.join(process.cwd(),".nex");Ut.existsSync(e)||Ut.mkdirSync(e,{recursive:!0}),Ut.writeFileSync(Gs(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}zi.exports={loadDeployConfigs:Hi,resolveDeployConfig:tf,saveDeployConfigs:nf,getDeployConfigPath:Gs}});var Wt=P((Wg,Ji)=>{var Js=null,Le=null,Bt=null,Gi=`Playwright is not installed. Install with:
|
|
121
128
|
npm install playwright && npx playwright install chromium
|
|
122
|
-
Then restart nex-code.`;function
|
|
123
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await
|
|
124
|
-
`)}function
|
|
129
|
+
Then restart nex-code.`;function Ki(){if(Bt!==null)return Bt;try{require("playwright"),Bt=!0}catch{Bt=!1}return Bt}async function Ln(){if(!Ki())throw new Error(Gi);return Js||(Js=require("playwright")),(!Le||!Le.isConnected())&&(Le=await Js.chromium.launch({headless:!0})),Le}async function sf(){if(Le){try{await Le.close()}catch{}Le=null}}process.on("exit",()=>{if(Le)try{Le.close()}catch{}});async function of(t,{timeout:e=3e4,waitFor:o="domcontentloaded"}={}){let s=await(await Ln()).newPage();try{await s.goto(t,{waitUntil:o,timeout:e});let r=await s.title(),a=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await s.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:s.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
130
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function rf(t,{width:e=1280,height:o=800,fullPage:n=!1,timeout:s=3e4}={}){let a=await(await Ln()).newPage();try{await a.setViewportSize({width:e,height:o}),await a.goto(t,{waitUntil:"networkidle",timeout:s});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 af(t,{selector:e,text:o,timeout:n=3e4}={}){if(!e&&!o)throw new Error("selector or text is required");let r=await(await Ln()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),o?await r.getByText(o,{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 cf(t,{selector:e,value:o,submit:n=!1,timeout:s=3e4}={}){if(!e||o===void 0)throw new Error("selector and value are required");let a=await(await Ln()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await a.fill(e,String(o)),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()}}Ji.exports={isPlaywrightAvailable:Ki,browserNavigate:of,browserScreenshot:rf,browserClick:af,browserFill:cf,closeBrowser:sf,INSTALL_MSG:Gi}});var jn=P((Hg,Yi)=>{var{C:z}=ee(),zt="",le=[],Ht=0,st=null;function lf(t){st=t}function uf(t,e){zt=t,le=[],Ht=0;for(let n of e){Ht++;let s=`t${Ht}`;le.push({id:s,description:n.description||n.title||n.name||n.task||`Task ${Ht}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let o=le.map(n=>({...n}));return st&&st("create",{name:t,tasks:o}),o}function df(t,e,o){let n=le.find(s=>s.id===t);return n?(n.status=e,o!==void 0&&(n.result=o),st&&st("update",{id:t,status:e,result:o}),{...n}):null}function ff(){return{name:zt,tasks:le.map(t=>({...t}))}}function mf(){zt="",le=[],Ht=0,st&&st("clear",{})}function pf(){return le.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let o=le.find(n=>n.id===e);return o&&o.status==="done"}))}function hf(){if(le.length===0)return`${z.dim}No active tasks${z.reset}`;let t=[];zt&&(t.push(` ${z.bold}${z.cyan}Tasks: ${zt}${z.reset}`),t.push(` ${z.dim}${"\u2500".repeat(40)}${z.reset}`));for(let s of le){let r,a;switch(s.status){case"done":r="\u2713",a=z.green;break;case"in_progress":r="\u2192",a=z.cyan;break;case"failed":r="\u2717",a=z.red;break;default:r="\xB7",a=z.dim}let c=s.dependsOn.length>0?` ${z.dim}(after: ${s.dependsOn.join(", ")})${z.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${a}${r}${z.reset} ${z.bold}${s.id}${z.reset} ${u.padEnd(40)} ${a}${l}${z.reset}${c}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${z.dim}\u2192 ${d}${z.reset}`)}}let e=le.filter(s=>s.status==="done").length,o=le.filter(s=>s.status==="failed").length,n=le.length;return t.push(` ${z.dim}${"\u2500".repeat(40)}${z.reset}`),t.push(` ${z.dim}${e}/${n} done${o>0?`, ${o} failed`:""}${z.reset}`),t.join(`
|
|
131
|
+
`)}function gf(){return le.length>0&&le.some(t=>t.status==="pending"||t.status==="in_progress")}Yi.exports={createTasks:uf,updateTask:df,getTaskList:ff,clearTasks:mf,getReadyTasks:pf,renderTaskList:hf,setOnChange:lf,hasActiveTasks:gf}});var Xs=P((zg,Vi)=>{var{getActiveModel:$f,getActiveProviderName:yf}=ie(),Gt={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},Kt={"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"},Jt={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Te={};function Xi(){try{let t=require("fs"),o=require("path").join(process.cwd(),".nex","config.json");t.existsSync(o)&&(Te=JSON.parse(t.readFileSync(o,"utf-8")).toolTiers||{})}catch{Te={}}}Xi();function Ys(){let e=$f()?.id,o=yf();return e&&Te[e]?Te[e]:o&&Te[`${o}:*`]?Te[`${o}:*`]:e&&Kt[e]?Kt[e]:o&&Jt[o]?Jt[o]:"full"}function wf(t,e){return t&&Te[t]?Te[t]:e&&Te[`${e}:*`]?Te[`${e}:*`]:t&&Kt[t]?Kt[t]:e&&Jt[e]?Jt[e]:"full"}function bf(t,e){let o=e||Ys();if(o==="full"||!Gt[o])return t;let n=new Set(Gt[o]);return t.filter(s=>n.has(s.function.name))}function xf(){let t=Ys(),e=Gt[t]?Gt[t].length:"all";return{tier:t,toolCount:e}}Vi.exports={filterToolsForModel:bf,getActiveTier:Ys,getModelTier:wf,getTierInfo:xf,TIERS:Gt,MODEL_TIERS:Kt,PROVIDER_DEFAULT_TIER:Jt,loadConfigOverrides:Xi}});var la=P((Kg,ca)=>{var{callStream:kf,getActiveProviderName:Fn,getActiveModelId:vf,getConfiguredProviders:_f,getProvider:Qi,getActiveProvider:Zi,parseModelSpec:ea}=ie(),{parseToolArgs:Sf}=vn(),{filterToolsForModel:Ef,getModelTier:Dn}=Xs(),{trackUsage:Cf}=$t(),{MultiProgress:Tf,C:Gg}=ee(),Rf=15,ta=5,na=3,Un=new Map;function Af(t,e){let o=Un.get(t);return o&&o!==e?!1:(Un.set(t,e),!0)}function Vs(t){Un.delete(t)}function Qs(){Un.clear()}function sa(t){let e=t.message||"",o=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||o==="ECONNRESET"||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function oa(t,e,o){let n;for(let s=0;s<=na;s++)try{return await kf(t,e,o)}catch(r){if(n=r,s<na&&sa(r)){let a=Math.min(2e3*Math.pow(2,s),15e3);await new Promise(c=>setTimeout(c,a).unref());continue}throw r}throw n}var Nf=new Set(["ask_user","task_list","spawn_agents"]),Mf=new Set(["write_file","edit_file","patch_file"]),Of=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Pf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ra(t){return Pf.test(t)?"full":Of.test(t)?"essential":"standard"}function ia(t){let e=_f(),o=Fn(),n=[...e].sort((s,r)=>(s.name===o?-1:1)-(r.name===o?-1:1));for(let s of n)for(let r of s.models)if(Dn(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var qf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Zs(t){if(t.model){let{provider:s,model:r}=ea(t.model),a=s?Qi(s):Zi(),c=s||Fn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Dn(r,c);return{provider:c,model:r,tier:l}}}let e=ra(t.task),o=qf[e];if(o){let{provider:s,model:r}=ea(o),a=s?Qi(s):Zi(),c=s||Fn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Dn(r,c);return{provider:c,model:r,tier:l}}}let n=ia(e);if(n){let s=Dn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:s}}return{provider:null,model:null,tier:null}}async function aa(t,e={}){let o=Math.min(t.max_iterations||10,Rf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,s=[],r={input:0,output:0},a=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
125
132
|
|
|
126
133
|
TASK: ${t.task}
|
|
127
134
|
${t.context?`
|
|
@@ -143,95 +150,150 @@ TOOL STRATEGY:
|
|
|
143
150
|
ERROR RECOVERY:
|
|
144
151
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
145
152
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
146
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
147
|
-
`)}let
|
|
148
|
-
...(truncated)`:
|
|
149
|
-
`)}catch(r){return
|
|
150
|
-
|
|
151
|
-
`)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
`)}function Ti(t,e,s){let n=As(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 ki=!1,jt=null;function vd(){jt&&(jt(),jt=null)}async function Es(){if(!ki){ki=!0;try{let{stdout:t}=await Me("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Me('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Me("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Me("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Sd=[/\.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 le(t){let e=ue.isAbsolute(t)?ue.resolve(t):ue.resolve(process.cwd(),t);for(let s of Sd)if(s.test(e))return null;return e}var Td=[{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"]}}}];async function _i(t,e,s={}){switch(t){case"bash":{let n=e.command,o=fd(n);if(o){let l=_d(n);return`BLOCKED: Command matches forbidden pattern: ${o}${l?`
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
153
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=Zs(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ie(),g=Ef(h.filter(w=>!Nf.has(w.function.name)),m);if(f&&!t._skipLog){let w=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${w}]
|
|
154
|
+
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let w=0;w<o;w++){let k=await oa(l,g,y);if(!k||typeof k!="object")throw new Error("Empty or invalid response from provider");if(k.usage){let A=k.usage.prompt_tokens||0,I=k.usage.completion_tokens||0;r.input+=A,r.output+=I;let L=d||Fn(),N=f||vf();Cf(L,N,A,I)}let E=k.content||"",x=k.tool_calls,v={role:"assistant",content:E||""};if(x&&x.length>0&&(v.tool_calls=x),l.push(v),!x||x.length===0){for(let A of a)Vs(A);return{task:t.task,status:"done",result:E||"(no response)",toolsUsed:s,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let S=x.map(A=>{let I=A.function.name,L=Sf(A.function.arguments),N=A.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!L)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${I}`,tool_call_id:N});if(Mf.has(I)&&L.path){let M=require("path"),F=M.isAbsolute(L.path)?L.path:M.resolve(process.cwd(),L.path);if(!Af(F,n))return Promise.resolve({role:"tool",content:`ERROR: File '${L.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:N});a.add(F)}return s.push(I),p(I,L,{autoConfirm:!0,silent:!0}).then(M=>{let F=String(M??"");return{role:"tool",content:F.length>2e4?F.substring(0,2e4)+`
|
|
155
|
+
...(truncated)`:F,tool_call_id:N}}).catch(M=>({role:"tool",content:`ERROR: ${M.message}`,tool_call_id:N}))}),C=await Promise.all(S);l.push(...C),e.onUpdate&&e.onUpdate(`step ${w+1}/${o}`)}for(let w of a)Vs(w);return{task:t.task,status:"done",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:s,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch(w){for(let k of a)Vs(k);return{task:t.task,status:"failed",result:`Error: ${w.message}`,toolsUsed:s,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function If(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ta)return`ERROR: Max ${ta} parallel agents allowed, got ${e.length}`;let o=e.map(r=>Zs(r)),n=e.map((r,a)=>{let c=o[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?"...":""}`}),s=new Tf(n);s.start();try{let r=e.map((d,f)=>{let m=o[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return aa(h,{onUpdate:()=>{}}).then(p=>(s.update(f,p.status==="done"?"done":"error"),p)).catch(p=>(s.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),a=await Promise.all(r);s.stop(),Qs();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 s.stop(),Qs(),`ERROR: Sub-agent execution failed: ${r.message}`}}ca.exports={runSubAgent:aa,executeSpawnAgents:If,clearAllLocks:Qs,classifyTask:ra,pickModelForTier:ia,resolveSubAgentModel:Zs,isRetryableError:sa,callWithRetry:oa}});var Vt=P((Jg,ka)=>{var K=require("fs"),je=require("path"),Lf=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 vt(){let t=je.join(process.cwd(),".nex","brain");return K.existsSync(t)||K.mkdirSync(t,{recursive:!0}),t}function ua(){return je.join(vt(),".brain-index.json")}function no(){return je.join(vt(),".embeddings.json")}function Yt(){let t=je.join(process.cwd(),".nex","brain");if(!K.existsSync(t))return[];try{return K.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let o=je.join(t,e),n=K.statSync(o);return{name:e.replace(/\.md$/,""),path:o,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,o)=>o.modified-e.modified)}catch{return[]}}function Xt(t){let e={},o=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let s=n[1].split(`
|
|
157
|
+
`);for(let r of s){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}o=n[2]}return{frontmatter:e,body:o}}function da(t){let e=je.join(vt(),`${t}.md`);if(!K.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let o=K.readFileSync(e,"utf-8"),{frontmatter:n,body:s}=Xt(o);return{name:t,content:o,body:s,frontmatter:n}}function jf(t,e){let o=je.join(vt(),`${t}.md`);K.writeFileSync(o,e,"utf-8"),Uf(t,e),Df()}function Df(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=no();K.existsSync(t)&&setImmediate(async()=>{try{await ya()}catch{}})}function Ff(t){let e=je.join(vt(),`${t}.md`);return K.existsSync(e)?(K.unlinkSync(e),Bf(t),!0):!1}function Bn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Lf.has(e))}function so(t){let e={},{frontmatter:o,body:n}=Xt(t),s=Array.isArray(o.tags)?o.tags:[];for(let a of s){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 Bn(c))e[l]=(e[l]||0)+3}for(let a of Bn(n||t))e[a]=(e[a]||0)+1;return e}function oo(){let t=ua();if(!K.existsSync(t))return{documents:{}};try{return JSON.parse(K.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ro(t){K.writeFileSync(ua(),JSON.stringify(t,null,2),"utf-8")}function Uf(t,e){let o=oo(),{frontmatter:n}=Xt(e),s=Array.isArray(n.tags)?n.tags:[];o.documents[t]={keywords:so(e),tags:s,modified:new Date().toISOString()},ro(o)}function Bf(t){let e=oo();delete e.documents[t],ro(e)}function to(){let t=Yt(),e={documents:{}};for(let o of t){let n=K.readFileSync(o.path,"utf-8"),{frontmatter:s}=Xt(n),r=Array.isArray(s.tags)?s.tags:[];e.documents[o.name]={keywords:so(n),tags:r,modified:o.modified.toISOString()}}return ro(e),e}function fa(){let t=oo(),e=Yt();for(let o of e){let n=t.documents[o.name];if(!n||new Date(n.modified)<o.modified)return to()}for(let o of Object.keys(t.documents))if(!e.some(n=>n.name===o))return to();return t}function ma(t,e={}){let{topK:o=3,minScore:n=.1}=e,s=Bn(t);if(s.length===0)return[];let r=fa(),a=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of s){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,o)}var pa=process.env.NEX_EMBED_MODEL||"nomic-embed-text",eo=400,Wf=50;async function ha(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),o=require("https"),n=new URL(`${t}/api/tags`),s=n.protocol==="https:"?o:e;return((await new Promise((c,l)=>{let u=s.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(pa.split(":")[0]))}catch{return!1}}async function io(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",o=require("http"),n=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?n:o,a=JSON.stringify({model:pa,prompt:t});return new Promise((c,l)=>{let u=r.request(s,{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 ga(t,e){if(!t||!e||t.length!==e.length)return 0;let o=0,n=0,s=0;for(let a=0;a<t.length;a++)o+=t[a]*e[a],n+=t[a]*t[a],s+=e[a]*e[a];let r=Math.sqrt(n)*Math.sqrt(s);return r===0?0:o/r}function $a(t){let e=t.split(/\s+/),o=[],n=0;for(;n<e.length;){let s=e.slice(n,n+eo).join(" ");if(o.push({text:s,offset:n}),n+eo>=e.length)break;n+=eo-Wf}return o}async function ya(){let t=Yt(),e={documents:{}},o=no();if(K.existsSync(o))try{e=JSON.parse(K.readFileSync(o,"utf-8"))}catch{}for(let n of t){let s=e.documents[n.name];if(s&&new Date(s.modified)>=n.modified)continue;let r=K.readFileSync(n.path,"utf-8"),a=$a(r),c=[];for(let l of a){let u=await io(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(s=>s.name===n)||delete e.documents[n];return K.writeFileSync(o,JSON.stringify(e),"utf-8"),e}async function wa(t,e={}){let{topK:o=3,minSimilarity:n=.3}=e,s=no();if(!K.existsSync(s))return[];let r;try{r=JSON.parse(K.readFileSync(s,"utf-8"))}catch{return[]}let a=await io(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=ga(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,o)}function ba(t,e,o={}){let{k:n=60,topK:s=3}=o,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,s)}async function xa(t,e={}){let{topK:o=3,minScore:n=.1}=e,s=ma(t,{topK:o,minScore:n}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ha()){let c=await wa(t,{topK:o});r=ba(s,c,{topK:o})}}catch{}return r.map(a=>{let c=da(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 Hf(t){if(!t||!t.trim())return"";let e=je.join(process.cwd(),".nex","brain");if(!K.existsSync(e)||Yt().length===0)return"";let n;try{n=await xa(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let s;try{s=ke().estimateTokens}catch{s=l=>Math.ceil(l.length/4)}let r=25e3,a=[],c=0;for(let l of n){let u=l.content||"",d=s(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
|
+
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(a.push(`--- ${l.name} (relevance: ${f}) ---
|
|
160
|
+
${u}`),c+=s(u),c>=r)break}return a.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
|
+
|
|
162
|
+
${a.join(`
|
|
163
|
+
|
|
164
|
+
`)}`}ka.exports={getBrainDir:vt,listDocuments:Yt,readDocument:da,writeDocument:jf,removeDocument:Ff,buildIndex:to,getIndex:fa,query:xa,getBrainContext:Hf,isEmbeddingAvailable:ha,generateEmbedding:io,buildEmbeddingIndex:ya,semanticQuery:wa,cosineSimilarity:ga,_keywordQuery:ma,_extractKeywords:so,_chunkText:$a,parseFrontmatter:Xt,tokenize:Bn,_fuseResults:ba}});var Ie=P((Qg,Ma)=>{var J=require("fs").promises,zf=require("fs"),pe=require("path"),V=require("util").promisify(require("child_process").exec),va=require("util").promisify(require("child_process").execFile),{spawnSync:Gf}=require("child_process"),ao=require("axios"),{isForbidden:Kf,isDangerous:Jf,isCritical:_a,confirm:Re}=Ce(),{showClaudeDiff:Wn,showClaudeNewFile:Yf,showEditDiff:Yg,confirmFileChange:Qt}=ui(),{C:q,Spinner:Ra,getToolSpinnerText:Xf}=ee(),{isGitRepo:co,getCurrentBranch:Sa,getStatus:Vf,getDiff:Qf}=nt(),{recordChange:Hn}=wt(),{fuzzyFindText:Ea,findMostSimilar:uo}=Pi(),{runDiagnostics:Zt}=Ii(),{findFileInIndex:Zf,getFileIndex:Xg}=Bs(),{resolveProfile:Ae,sshExec:Ge,scpUpload:em,scpDownload:tm}=kt(),{resolveDeployConfig:nm,loadDeployConfigs:Vg}=Ks(),sm=/^(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/,om=/^ssh\s/,rm=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function zn(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),o=me(e);if(o&&await J.access(o).then(()=>!0).catch(()=>!1))return{fixedPath:o,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=pe.extname(t);if(!s)for(let a of n){let c=me(t+a);if(c&&await J.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(s){let a=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===s)continue;let l=me(a+c);if(l&&await J.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let r=pe.basename(t);if(r&&r.length>2)try{let a=Zf(r).map(c=>me(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${pe.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=>pe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function im(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 Aa(t,e){let o=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),s=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?o.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?o.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):o.push(`HINT: "${s}" 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 '([^']+)'/),s=n?n[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?o.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):o.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&o.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+)/),s=n?n[1]||n[2]:"";o.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&o.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&o.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&o.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&o.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+)\)/),s=n?parseInt(n[1],10):null;s===6||/Could not resolve host/i.test(t)?o.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?o.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?o.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?o.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&o.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+)/),s=n?n[1]:"";o.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&o.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)&&o.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),o.length===0?t:t+`
|
|
167
|
+
|
|
168
|
+
`+o.join(`
|
|
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: ${l}`:""}`}if(o.autoConfirm?_a(n):Jf(n)){let l=_a(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
171
|
+
${q.yellow}${l}: ${n}${q.reset}`),!await Re(" Execute?"))return"CANCELLED: User declined to execute this command."}let a=om.test(n.trim())&&!rm.test(n.trim());if(sm.test(n.trim())||a){o.silent||console.log(`${q.dim} \u25B6 interactive: ${n}${q.reset}`);let l=Gf("sh",["-c",n],{stdio:"inherit",cwd:process.cwd()});return l.error?`ERROR: ${l.error.message}`:l.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${l.status})`}let c=o.silent?null:new Ra(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);c&&c.start();try{let{stdout:l,stderr:u}=await V(n,{cwd:process.cwd(),timeout:9e4,maxBuffer:5242880});return c&&c.stop(),l||u||"(no output)"}catch(l){c&&c.stop();let u=(l.stderr||l.stdout||l.message||"").toString().substring(0,5e3),d=Aa(u,n);return`EXIT ${l.code||1}
|
|
172
|
+
${d}`}}case"read_file":{let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let m=await zn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${q.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${q.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
173
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await zf.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 J.readFile(n,"utf-8");if(!l&&(await J.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
159
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(`
|
|
160
|
-
`)}case"write_file":{await
|
|
161
|
-
`+d.message:""}`}let r=await
|
|
175
|
+
`)}case"write_file":{await lo();let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await J.access(n).then(()=>!0).catch(()=>!1),r=null;if(o.autoConfirm)s&&(r=await J.readFile(n,"utf-8"));else if(s){r=await J.readFile(n,"utf-8");let l=await Zt(n,e.content);if(Wn(n,r,e.content,{annotations:l}),!await Qt("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await Zt(n,e.content);if(Yf(n,e.content,{annotations:l}),!await Qt("Create"))return"CANCELLED: User declined to create file."}let a=pe.dirname(n);return await J.access(a).then(()=>!0).catch(()=>!1)||await J.mkdir(a,{recursive:!0}),await J.writeFile(n,e.content,"utf-8"),Hn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await lo();let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let d=await zn(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${q.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${q.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
176
|
+
`+d.message:""}`}let r=await J.readFile(n,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Ea(r,e.old_text);if(d)a=d,c=!0,console.log(`${q.dim} \u2713 fuzzy whitespace match applied${q.reset}`);else{let f=Na(r,e.old_text,e.new_text);if(f){if(!o.autoConfirm){let p=await Zt(n,f.content);if(Wn(n,r,f.content,{annotations:p}),!await Qt(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await J.writeFile(n,f.content,"utf-8"),Hn("edit_file",n,r,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${q.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${q.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=uo(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
162
177
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
163
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!
|
|
164
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
178
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!o.autoConfirm){let d=r.split(a).join(e.new_text),f=await Zt(n,d);if(Wn(n,r,d,{annotations:f}),!await Qt(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await J.writeFile(n,u,"utf-8"),Hn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=me(u),f=await J.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 J.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(pe.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
179
|
+
`)||"(empty)"}case"search_files":{let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,n);try{let{stdout:r}=await va("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
165
180
|
`).slice(0,50).join(`
|
|
166
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let
|
|
167
|
-
`);return k?`${
|
|
181
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?me(e.path):s,a=e.pattern,c=x=>{let v=x.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=Bs(),g=f(),y=m();p(r)||(await h(r),g=f());let w=g.filter(x=>l.test(x)||d.test(pe.basename(x))).map(x=>pe.join(r,x));if(w.length===0)return"(no matches)";let k=w.length>200,E=w.slice(0,200).join(`
|
|
182
|
+
`);return k?`${E}
|
|
168
183
|
|
|
169
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
184
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:E}case"grep":{let n=e.path?me(e.path):process.cwd(),s=["-rn","-E"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,n);try{let{stdout:r}=await va("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
170
185
|
`).slice(0,100).join(`
|
|
171
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
172
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await
|
|
173
|
-
Most similar text (line ${
|
|
174
|
-
${
|
|
186
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await lo();let n=me(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let m=await zn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${q.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${pe.relative(process.cwd(),n)}${q.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 J.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=Ea(a,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let y=uo(a,h);if(y){let w=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=w)c.push({old_text:y.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
188
|
+
Most similar text (line ${y.line}, distance ${y.distance}):
|
|
189
|
+
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!o.autoConfirm){let m=await Zt(n,d);if(Wn(n,a,d,{annotations:m}),!await Qt(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await J.writeFile(n,d,"utf-8"),Hn("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,s=e.max_length||1e4;try{let r=await ao.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,s)||"(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 s=await ao.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=s.data?.choices?.[0]?.message?.content||"",a=s.data?.citations||[],c=`[Perplexity grounded search]
|
|
175
190
|
|
|
176
191
|
${r}`;return a.length>0&&(c+=`
|
|
177
192
|
|
|
178
193
|
Sources:
|
|
179
194
|
`+a.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
180
|
-
`)),c}catch(
|
|
195
|
+
`)),c}catch(s){console.error(`${q.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${q.reset}`)}try{let r=(await ao.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}
|
|
181
196
|
${u.url}`).join(`
|
|
182
197
|
|
|
183
|
-
`)}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}=Wt();try{let s=await n(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
|
|
184
199
|
|
|
185
200
|
Links:
|
|
186
|
-
`+
|
|
187
|
-
`):"";return`Title: ${
|
|
188
|
-
URL: ${
|
|
189
|
-
|
|
190
|
-
${
|
|
191
|
-
Title: ${
|
|
192
|
-
URL: ${
|
|
193
|
-
|
|
194
|
-
To analyze visually, paste the path into your next message: ${
|
|
195
|
-
${
|
|
196
|
-
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${
|
|
197
|
-
`)}case"git_diff":{if(!await
|
|
201
|
+
`+s.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
202
|
+
`):"";return`Title: ${s.title}
|
|
203
|
+
URL: ${s.url}
|
|
204
|
+
|
|
205
|
+
${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Wt();try{let s=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${s.path}
|
|
206
|
+
Title: ${s.title}
|
|
207
|
+
URL: ${s.url}
|
|
208
|
+
|
|
209
|
+
To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:n}=Wt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:n}=Wt();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"ask_user":{let n=e.question;return new Promise(s=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});tn=()=>{r.close(),s("CANCELLED")},console.log(`
|
|
210
|
+
${q.cyan}${q.bold} ? ${n}${q.reset}`),r.question(`${q.cyan} > ${q.reset}`,a=>{tn=null,r.close(),s(a.trim()||"(no response)")})})}case"git_status":{if(!await co())return"ERROR: Not a git repository";let n=await Sa()||"(detached)",s=await Vf();if(s.length===0)return`Branch: ${n}
|
|
211
|
+
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${s.length}):`];for(let a of s){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 co())return"ERROR: Not a git repository";let n;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{n=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await Qf(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await co())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:s,getTaskList:r,renderTaskList:a,hasActiveTasks:c}=jn(),{getActiveTaskProgress:l}=ee(),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(`
|
|
198
213
|
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
199
214
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
200
|
-
`)}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":s(e.task_id,e.status,e.result)?(u||console.log(`
|
|
201
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(`
|
|
202
|
-
`+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}=la();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:s,getActiveModelId:r}=ie();return n(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),s=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await V(`gh ${s.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(`
|
|
203
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(`
|
|
204
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await
|
|
205
|
-
...(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 V(`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 V(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(n),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of s.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(`
|
|
206
221
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
207
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
208
|
-
${
|
|
209
|
-
`)[0]}`}}
|
|
222
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Ce(),s=e.branch||await Sa()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${s} ${r}`.trim();if(console.log(`
|
|
223
|
+
${q.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${q.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await V(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". 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",s=e.label?`-l ${e.label}`:"",r=en(`get pods ${n} ${s} -o wide`.trim(),e);try{let{stdout:a,stderr:c}=await V(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",s=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let a=en(r,e);try{let{stdout:c,stderr:l}=await V(a,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
226
|
+
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
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
|
+
${q.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${q.reset}`),console.log(`${q.dim} Command: ${e.command}${q.reset}`),!await Re(" 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=en(r,e);try{let{stdout:c,stderr:l}=await V(a,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
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
|
+
${q.yellow} \u26A0 kubectl apply: ${a}${e.namespace?` (ns: ${e.namespace})`:""}${q.reset}`),!await Re(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),n&&(s+=" --dry-run=client");let r=en(s,e);try{let{stdout:a,stderr:c}=await V(r,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
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
|
+
${q.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${q.reset}`),!await Re(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,a=en(r,e);try{let{stdout:c,stderr:l}=await V(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:s}=Vt(),{name:r,content:a,mode:c}=e;if(c==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=s(r),u=l.content?l.content+`
|
|
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=Ae(e.server)}catch(h){return`ERROR: ${h.message}`}let s=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(s)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
236
|
+
${q.yellow} \u26A0 Remote command on ${h}: ${s}${q.reset}`),!await Re(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ge(n,s,{timeout:a,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
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=Ae(e.server)}catch(a){return`ERROR: ${a.message}`}let s=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
239
|
+
${q.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${q.reset}`),!await Re(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await em(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=Ae(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await tm(n,e.remote_path,e.local_path)}catch(s){return`ERROR: ${s.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 s=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",a=null;if(!s)try{a=Ae(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=s?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
240
|
+
${q.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${q.reset}`),!await Re(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(s){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await V(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 Ge(a,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
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",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${s} ${r} ${a} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await V(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=Ae(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ge(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
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 V(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=Ae(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Ge(a,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
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",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",a=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await V(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=Ae(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ge(c,a,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
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",s=/^(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(!o.autoConfirm&&!s.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
253
|
+
${q.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${q.reset}`),!await Re(" 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 V(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=Ae(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ge(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
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 s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!o.autoConfirm){let p=s?"local":e.server;if(console.log(`
|
|
257
|
+
${q.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${q.reset}`),!await Re(" 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(s)try{let{stdout:p,stderr:g}=await V(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=Ae(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ge(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
|
+
`).trim();return f!==0?`EXIT ${f}
|
|
260
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...nm(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=Ae(e.server)}catch(p){return`ERROR: ${p.message}`}let s=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} ${s}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!o.autoConfirm&&(console.log(`
|
|
261
|
+
${q.yellow} \u26A0 Deploy: ${d} \u2192 ${s}:${e.remote_path}${q.reset}`),e.deploy_script&&console.log(`${q.yellow} Then run: ${e.deploy_script}${q.reset}`),!await Re(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await V(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:y,error:w}=await Ge(n,e.deploy_script,{timeout:6e4}),k=[p,g].filter(Boolean).join(`
|
|
263
|
+
`).trim();if(y!==0)return`rsync OK
|
|
264
|
+
|
|
265
|
+
ERROR (deploy_script, exit ${y}):
|
|
266
|
+
${w||k}`;h=`
|
|
267
|
+
|
|
268
|
+
Remote script output:
|
|
269
|
+
${k||"(no output)"}`}return`Deployed ${d} \u2192 ${s}:${e.remote_path}
|
|
270
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function um(t,e,o={}){let n=o.silent?null:Xf(t,e);if(!n)return Ta(t,e,o);let s=new Ra(n);s.start();try{let r=await Ta(t,e,o);return s.stop(),r}catch(r){throw s.stop(),r}}Ma.exports={TOOL_DEFINITIONS:lm,executeTool:um,resolvePath:me,autoFixPath:zn,autoFixEdit:Na,enrichBashError:Aa,cancelPendingAskUser:am}});var Pa=P((Zg,Oa)=>{var{loadServerProfiles:mo}=kt(),fo={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function dm(){let t=mo();if(Object.keys(t).length===0)return null;let o=["## Remote Servers (.nex/servers.json)"];o.push(""),o.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[s,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":"";o.push(`- **${s}**: ${a}${c}${l}${u}`)}let n=new Set;for(let s of Object.values(t))s.os&&fo[s.os]&&n.add(s.os);if(n.size>0){o.push("");for(let s of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;o.push(`### ${r} Notes`);for(let a of fo[s])o.push(`- ${a}`)}}return o.join(`
|
|
271
|
+
`)}function fm(t){let e=mo();return Object.values(e).some(o=>o.os&&o.os.startsWith(t))}function mm(){return Object.keys(mo())}Oa.exports={getServerContext:dm,hasServerOS:fm,getProfileNames:mm,OS_HINTS:fo}});var ho=P((e$,Ia)=>{var _e=require("fs").promises,we=require("path"),Gn=require("util").promisify(require("child_process").exec),{C:Ne}=ee(),{getMergeConflicts:qa}=nt(),{getServerContext:pm}=Pa(),po=new Map,_t=new Map,Kn=null,hm=3e4;async function Ke(t){try{return await t()}catch{return null}}async function gm(){if(!Kn||Date.now()>Kn)return!1;let t=[we.join(process.cwd(),"package.json"),we.join(process.cwd(),"README.md"),we.join(process.cwd(),".gitignore")];for(let e of t)try{let o=await _e.stat(e),n=_t.get(e);if(!n||o.mtimeMs!==n)return!1}catch{if(_t.has(e))return!1}try{let e=we.join(process.cwd(),".git","HEAD"),o=await _e.stat(e),n=_t.get(e);if(!n||o.mtimeMs!==n)return!1}catch{}return!0}async function $m(){let t=[we.join(process.cwd(),"package.json"),we.join(process.cwd(),"README.md"),we.join(process.cwd(),".gitignore"),we.join(process.cwd(),".git","HEAD")];for(let e of t)try{let o=await _e.stat(e);_t.set(e,o.mtimeMs)}catch{_t.delete(e)}}async function ym(t){let e="fileContext",o=po.get(e),n=!1;if(o&&await gm()&&(n=!0),!n){let u=[],d=we.join(t,"package.json");if(await Ke(()=>_e.access(d).then(()=>!0).catch(()=>!1)))try{let y=await _e.readFile(d,"utf-8"),w=JSON.parse(y),k={name:w.name,version:w.version};w.scripts&&(k.scripts=Object.keys(w.scripts).slice(0,15)),w.dependencies&&(k.deps=Object.keys(w.dependencies).length),w.devDependencies&&(k.devDeps=Object.keys(w.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(k)}`)}catch{}let m=we.join(t,"README.md");if(await Ke(()=>_e.access(m).then(()=>!0).catch(()=>!1))){let w=(await _e.readFile(m,"utf-8")).split(`
|
|
210
272
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
211
|
-
${
|
|
212
|
-
`)}`)}let p=
|
|
213
|
-
${
|
|
273
|
+
${w.join(`
|
|
274
|
+
`)}`)}let p=we.join(t,".gitignore");if(await Ke(()=>_e.access(p).then(()=>!0).catch(()=>!1))){let y=await _e.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
|
+
${y.trim()}`)}o=u.join(`
|
|
214
276
|
|
|
215
|
-
`),
|
|
216
|
-
${a}`),c&&
|
|
277
|
+
`),po.set(e,o),Kn=Date.now()+hm,await $m()}let s=[o],[r,a,c,l]=await Promise.all([Ke(async()=>{let{stdout:u}=await Gn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ke(async()=>{let{stdout:u}=await Gn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ke(async()=>{let{stdout:u}=await Gn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),qa()]);if(r&&s.push(`GIT BRANCH: ${r}`),a&&s.push(`GIT STATUS:
|
|
278
|
+
${a}`),c&&s.push(`RECENT COMMITS:
|
|
217
279
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
218
|
-
`);
|
|
219
|
-
${u}`)}return
|
|
280
|
+
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
+
${u}`)}try{let u=pm();u&&s.push(u)}catch{}return s.join(`
|
|
220
282
|
|
|
221
|
-
`)}async function
|
|
222
|
-
${e}`);let
|
|
223
|
-
${
|
|
283
|
+
`)}async function wm(t){let e=we.join(t,"package.json"),o="";if(await Ke(()=>_e.access(e).then(()=>!0).catch(()=>!1)))try{let a=await _e.readFile(e,"utf-8"),c=JSON.parse(a);o=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([Ke(async()=>{let{stdout:a}=await Gn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),qa()]);if(o&&console.log(`${Ne.dim} project: ${o}${Ne.reset}`),s&&console.log(`${Ne.dim} branch: ${s}${Ne.reset}`),r&&r.length>0){console.log(`${Ne.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ne.reset}`);for(let a of r)console.log(`${Ne.red} ${a.file}${Ne.reset}`);console.log(`${Ne.yellow} \u2192 Resolve conflicts before starting tasks${Ne.reset}`)}console.log()}Ia.exports={gatherProjectContext:ym,printContext:wm,_clearContextCache:()=>{po.clear(),_t.clear(),Kn=null}}});var rt=P((t$,Fa)=>{var Fe=require("fs"),go=require("path");function Jn(){return go.join(process.cwd(),".nex","sessions")}function La(){let t=Jn();Fe.existsSync(t)||Fe.mkdirSync(t,{recursive:!0})}function $o(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return go.join(Jn(),`${e}.json`)}function yo(t,e,o={}){La();let n=$o(t),s={name:t,createdAt:o.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:o.model||null,provider:o.provider||null,messages:e};return Fe.writeFileSync(n,JSON.stringify(s,null,2),"utf-8"),{path:n,name:t}}function ja(t){let e=$o(t);if(!Fe.existsSync(e))return null;try{return JSON.parse(Fe.readFileSync(e,"utf-8"))}catch{return null}}function Da(){La();let t=Jn(),e=Fe.readdirSync(t).filter(n=>n.endsWith(".json")),o=[];for(let n of e)try{let s=JSON.parse(Fe.readFileSync(go.join(t,n),"utf-8"));o.push({name:s.name||n.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider})}catch{}return o.sort((n,s)=>(s.updatedAt||"").localeCompare(n.updatedAt||""))}function bm(t){let e=$o(t);return Fe.existsSync(e)?(Fe.unlinkSync(e),!0):!1}function xm(){let t=Da();return t.length===0?null:ja(t[0].name)}var ot=null,De=null,nn=null;function km(t,e={}){t.length!==0&&(ot&&clearTimeout(ot),De=t,nn=e||{},ot=setTimeout(()=>{De&&De.length>0&&yo("_autosave",De,nn),ot=null,De=null,nn=null},5e3))}function vm(){ot&&(clearTimeout(ot),ot=null),De&&De.length>0&&(yo("_autosave",De,nn),De=null,nn=null)}Fa.exports={saveSession:yo,loadSession:ja,listSessions:Da,deleteSession:bm,getLastSession:xm,autoSave:km,flushAutoSave:vm,_getSessionsDir:Jn}});var Je=P((n$,Ga)=>{var Ue=require("fs"),Yn=require("path"),_m=require("os");function wo(){return Yn.join(process.cwd(),".nex","memory")}function bo(){return Yn.join(wo(),"memory.json")}function Sm(){return Yn.join(process.cwd(),"NEX.md")}function Ua(){return Yn.join(_m.homedir(),".nex","NEX.md")}function Em(){let t=wo();Ue.existsSync(t)||Ue.mkdirSync(t,{recursive:!0})}function Xn(){let t=bo();if(!Ue.existsSync(t))return{};try{return JSON.parse(Ue.readFileSync(t,"utf-8"))}catch{return{}}}function Ba(t){Em(),Ue.writeFileSync(bo(),JSON.stringify(t,null,2),"utf-8")}function Cm(t,e){let o=Xn();o[t]={value:e,updatedAt:new Date().toISOString()},Ba(o)}function Tm(t){let e=Xn();return e[t]?e[t].value:null}function Rm(t){let e=Xn();return t in e?(delete e[t],Ba(e),!0):!1}function Wa(){let t=Xn();return Object.entries(t).map(([e,o])=>({key:e,value:o.value,updatedAt:o.updatedAt}))}function Ha(){let t=Ua();if(!Ue.existsSync(t))return"";try{return Ue.readFileSync(t,"utf-8").trim()}catch{return""}}function za(){let t=Sm();if(!Ue.existsSync(t))return"";try{return Ue.readFileSync(t,"utf-8").trim()}catch{return""}}function Am(){let t=[],e=Ha();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
|
+
${e}`);let o=za();o&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
|
+
${o}`);let n=Wa();if(n.length>0){let s=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
224
286
|
`);t.push(`PROJECT MEMORY:
|
|
225
|
-
${
|
|
287
|
+
${s}`)}return t.join(`
|
|
226
288
|
|
|
227
|
-
`)}
|
|
228
|
-
${
|
|
229
|
-
`);for(let n=0;n<t.steps.length;n++){let
|
|
230
|
-
`)}function
|
|
289
|
+
`)}Ga.exports={remember:Cm,recall:Tm,forget:Rm,listMemories:Wa,loadGlobalInstructions:Ha,loadProjectInstructions:za,getMemoryContext:Am,_getMemoryDir:wo,_getMemoryFile:bo,_getGlobalNexMdPath:Ua}});var sn=P((o$,Ya)=>{var it=require("fs"),xo=require("path"),{C:s$}=ee(),Vn={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"},St={...Vn};function Ka(){let t=xo.join(process.cwd(),".nex","config.json");if(it.existsSync(t))try{let e=JSON.parse(it.readFileSync(t,"utf-8"));e.permissions&&(St={...Vn,...e.permissions})}catch{}}function Nm(){let t=xo.join(process.cwd(),".nex"),e=xo.join(t,"config.json"),o={};if(it.existsSync(e))try{o=JSON.parse(it.readFileSync(e,"utf-8"))}catch{o={}}o.permissions=St,it.existsSync(t)||it.mkdirSync(t,{recursive:!0}),it.writeFileSync(e,JSON.stringify(o,null,2),"utf-8")}function Ja(t){return St[t]||"ask"}function Mm(t,e){return["allow","ask","deny"].includes(e)?(St[t]=e,!0):!1}function Om(t){return Ja(t)}function Pm(){return Object.entries(St).map(([t,e])=>({tool:t,mode:e}))}function qm(){St={...Vn}}Ka();Ya.exports={getPermission:Ja,setPermission:Mm,checkPermission:Om,listPermissions:Pm,loadPermissions:Ka,savePermissions:Nm,resetPermissions:qm,DEFAULT_PERMISSIONS:Vn}});var Et=P((i$,ec)=>{var at=require("fs"),Qn=require("path"),r$=require("readline"),{C:H}=ee(),te=null,ko=!1,vo=null,Xa=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 Zn(){return Qn.join(process.cwd(),".nex","plans")}function Va(){let t=Zn();at.existsSync(t)||at.mkdirSync(t,{recursive:!0})}function Im(t,e=[]){return te={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(o=>({description:o.description||o,files:o.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},te}function Lm(){return te}function jm(t){ko=t}function Dm(){return ko}function Fm(){return!te||te.status!=="draft"?!1:(te.status="approved",te.updatedAt=new Date().toISOString(),!0)}function Um(){return!te||te.status!=="approved"?!1:(te.status="executing",!0)}function Bm(t,e){return!te||t<0||t>=te.steps.length?!1:(te.steps[t].status=e,te.updatedAt=new Date().toISOString(),te.steps.every(o=>o.status==="done"||o.status==="skipped")&&(te.status="completed"),!0)}function Wm(t){if(!t)return`${H.dim}No active plan${H.reset}`;let e={draft:`${H.yellow}DRAFT${H.reset}`,approved:`${H.green}APPROVED${H.reset}`,executing:`${H.blue}EXECUTING${H.reset}`,completed:`${H.green}COMPLETED${H.reset}`},o=[];o.push(`
|
|
290
|
+
${H.bold}${H.cyan}Plan: ${t.task}${H.reset}`),o.push(`${H.dim}Status: ${e[t.status]||t.status}${H.reset}
|
|
291
|
+
`);for(let n=0;n<t.steps.length;n++){let s=t.steps[n],r;switch(s.status){case"done":r=`${H.green}\u2713${H.reset}`;break;case"in_progress":r=`${H.blue}\u2192${H.reset}`;break;case"skipped":r=`${H.dim}\u25CB${H.reset}`;break;default:r=`${H.dim} ${H.reset}`}o.push(` ${r} ${H.bold}Step ${n+1}:${H.reset} ${s.description}`),s.files.length>0&&o.push(` ${H.dim}Files: ${s.files.join(", ")}${H.reset}`)}return o.push(""),o.join(`
|
|
292
|
+
`)}function Hm(t){if(t||(t=te),!t)return null;Va();let e=Qn.join(Zn(),`${t.name}.json`);return at.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function zm(t){let e=Qn.join(Zn(),`${t}.json`);if(!at.existsSync(e))return null;try{let o=JSON.parse(at.readFileSync(e,"utf-8"));return te=o,o}catch{return null}}function Gm(){Va();let t=Zn(),e=at.readdirSync(t).filter(n=>n.endsWith(".json")),o=[];for(let n of e)try{let s=JSON.parse(at.readFileSync(Qn.join(t,n),"utf-8"));o.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return o.sort((n,s)=>(s.createdAt||"").localeCompare(n.createdAt||""))}function Km(t){vo=t}function Jm(){return vo}function Ym(){te=null,ko=!1,vo=null}function Xm(){return`
|
|
231
293
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
232
294
|
|
|
233
295
|
# Allowed Tools (read-only)
|
|
234
|
-
You may ONLY use these tools: ${[...
|
|
296
|
+
You may ONLY use these tools: ${[...Xa].join(", ")}
|
|
235
297
|
Any other tool call will be blocked and returned with an error.
|
|
236
298
|
|
|
237
299
|
# Analysis Phase
|
|
@@ -262,54 +324,54 @@ Bullet list of potential issues and mitigations.
|
|
|
262
324
|
# Important
|
|
263
325
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
264
326
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
265
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
266
|
-
`),
|
|
267
|
-
`)}function
|
|
268
|
-
`)}function
|
|
269
|
-
`))!==-1;){let n=this.buffer.substring(0,
|
|
270
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${
|
|
271
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
272
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
273
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
274
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
275
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
276
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
277
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
278
|
-
`);return}}this._safeWrite(`${
|
|
279
|
-
`)}};
|
|
327
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Qa=["interactive","semi-auto","autonomous"],Za="interactive";function Vm(t){return Qa.includes(t)?(Za=t,!0):!1}function Qm(){return Za}ec.exports={createPlan:Im,getActivePlan:Lm,setPlanMode:jm,isPlanMode:Dm,approvePlan:Fm,startExecution:Um,updateStep:Bm,formatPlan:Wm,savePlan:Hm,loadPlan:zm,listPlans:Gm,clearPlan:Ym,getPlanModePrompt:Xm,setPlanContent:Km,getPlanContent:Jm,PLAN_MODE_ALLOWED_TOOLS:Xa,setAutonomyLevel:Vm,getAutonomyLevel:Qm,AUTONOMY_LEVELS:Qa}});var uc=P((a$,lc)=>{var{C:$}=ee();function Zm(t){if(!t)return"";let e=t.split(`
|
|
328
|
+
`),o=[],n=!1,s="";for(let r of e){if(r.trim().startsWith("```")){if(n)o.push(`${$.dim}${"\u2500".repeat(40)}${$.reset}`),n=!1,s="";else{n=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";o.push(`${$.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${$.reset}`)}continue}if(n){o.push(` ${So(r,s)}`);continue}if(r.startsWith("### ")){o.push(`${$.bold}${$.cyan} ${ct(r.substring(4))}${$.reset}`);continue}if(r.startsWith("## ")){o.push(`${$.bold}${$.cyan} ${ct(r.substring(3))}${$.reset}`);continue}if(r.startsWith("# ")){o.push(`${$.bold}${$.cyan}${ct(r.substring(2))}${$.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");o.push(`${a}${$.cyan}\u2022${$.reset} ${lt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){o.push(`${a[1]}${$.cyan}${a[2]}.${$.reset} ${lt(a[3])}`);continue}}o.push(lt(r))}return o.join(`
|
|
329
|
+
`)}function ct(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function lt(t){return t?t.replace(/`([^`]+)`/g,`${$.cyan}$1${$.reset}`).replace(/\*\*([^*]+)\*\*/g,`${$.bold}$1${$.reset}`).replace(/\*([^*]+)\*/g,`${$.dim}$1${$.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${$.cyan}$1${$.reset} ${$.dim}($2)${$.reset}`):""}function So(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?tc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?nc(t):e==="json"||e==="jsonc"?sc(t):e==="python"||e==="py"?oc(t):e==="go"||e==="golang"?rc(t):e==="rust"||e==="rs"?ic(t):e==="css"||e==="scss"||e==="less"?ac(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?cc(t):t:""}function tc(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,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${$.yellow}$1${$.reset}`),r=r.replace(e,`${$.magenta}$1${$.reset}`),r=r.replace(o,`${$.green}$&${$.reset}`),r=r.replace(n,`${$.dim}$1${$.reset}`),r}function nc(t){let e=/^(\s*)([\w-]+)/,o=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(o,`${$.cyan}$1${$.reset}`),r=r.replace(e,`$1${$.green}$2${$.reset}`),r=r.replace(n,`${$.yellow}$&${$.reset}`),r=r.replace(s,`${$.dim}$1${$.reset}`),r}function sc(t){let e=/("[\w-]+")\s*:/g,o=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${$.cyan}$1${$.reset}:`),r=r.replace(o,`: ${$.green}$1${$.reset}`),r=r.replace(n,`: ${$.yellow}$1${$.reset}`),r=r.replace(s,`: ${$.magenta}$1${$.reset}`),r}function oc(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,o=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,a=t;return a=a.replace(s,`${$.yellow}$1${$.reset}`),a=a.replace(e,`${$.magenta}$1${$.reset}`),a=a.replace(r,`${$.cyan}$1${$.reset}`),a=a.replace(o,`${$.green}$&${$.reset}`),a=a.replace(n,`${$.dim}$1${$.reset}`),a}function rc(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,o=/\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,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${$.yellow}$1${$.reset}`),a=a.replace(o,`${$.cyan}$1${$.reset}`),a=a.replace(e,`${$.magenta}$1${$.reset}`),a=a.replace(n,`${$.green}$&${$.reset}`),a=a.replace(s,`${$.dim}$1${$.reset}`),a}function ic(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,o=/\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,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${$.yellow}$1${$.reset}`),c=c.replace(o,`${$.cyan}$1${$.reset}`),c=c.replace(e,`${$.magenta}$1${$.reset}`),c=c.replace(a,`${$.yellow}$1${$.reset}`),c=c.replace(n,`${$.green}$&${$.reset}`),c=c.replace(s,`${$.dim}$1${$.reset}`),c}function ac(t){let e=/^(\s*)([\w-]+)\s*:/,o=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,s=/\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,`${$.yellow}$1${$.reset}`),c=c.replace(s,`${$.yellow}$1${$.reset}`),c=c.replace(e,`$1${$.cyan}$2${$.reset}:`),c=c.replace(n,`$1${$.magenta}$&${$.reset}`),c=c.replace(r,`${$.dim}$1${$.reset}`),c}function cc(t){let e=/<\/?(\w[\w-]*)/g,o=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(s,`${$.dim}$1${$.reset}`),a=a.replace(n,`${$.green}$&${$.reset}`),a=a.replace(e,`<${$.magenta}$1${$.reset}`),a=a.replace(o,` ${$.cyan}$1${$.reset}=`),a=a.replace(r,`${$.yellow}$1${$.reset}`),a}function ep(t,e){if(!t||t.length===0)return"";let o=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),n=o.map(a=>"\u2500".repeat(a+2)).join("\u253C"),s=t.map((a,c)=>` ${$.bold}${a.padEnd(o[c])}${$.reset} `).join("\u2502"),r=[];r.push(`${$.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${$.reset}`),r.push(`${$.dim}\u2502${$.reset}${s}${$.dim}\u2502${$.reset}`),r.push(`${$.dim}\u251C${n}\u2524${$.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(o[u])} `).join(`${$.dim}\u2502${$.reset}`);r.push(`${$.dim}\u2502${$.reset}${c}${$.dim}\u2502${$.reset}`)}return r.push(`${$.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${$.reset}`),r.join(`
|
|
330
|
+
`)}function tp(t,e,o,n=30){let s=o>0?Math.round(e/o*100):0,r=Math.round(s/100*n),a=n-r,c=s>=100?$.green:s>50?$.yellow:$.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${$.dim}${"\u2591".repeat(a)}${$.reset} ${s}% (${e}/${o})`}var _o=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(o){if(o.code!=="EPIPE")throw o}}_cursorWrite(e){try{process.stderr.write(e)}catch(o){if(o.code!=="EPIPE")throw o}}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"],o=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${o}\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 o;for(;(o=this.buffer.indexOf(`
|
|
331
|
+
`))!==-1;){let n=this.buffer.substring(0,o);this.buffer=this.buffer.substring(o+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(`${$.dim}${"\u2500".repeat(40)}${$.reset}
|
|
332
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${$.dim}${"\u2500".repeat(40)}${$.reset}
|
|
333
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${$.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${$.reset}
|
|
334
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${So(e,this.codeBlockLang)}
|
|
335
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${$.bold}${$.cyan} ${ct(e.substring(4))}${$.reset}
|
|
336
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${$.bold}${$.cyan} ${ct(e.substring(3))}${$.reset}
|
|
337
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${$.bold}${$.cyan}${ct(e.substring(2))}${$.reset}
|
|
338
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${o}${$.cyan}\u2022${$.reset} ${lt(n)}
|
|
339
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){this._safeWrite(`${o[1]}${$.cyan}${o[2]}.${$.reset} ${lt(o[3])}
|
|
340
|
+
`);return}}this._safeWrite(`${lt(e)}
|
|
341
|
+
`)}};lc.exports={renderMarkdown:Zm,renderInline:lt,stripHeadingMarkers:ct,highlightCode:So,highlightJS:tc,highlightBash:nc,highlightJSON:sc,highlightPython:oc,highlightGo:rc,highlightRust:ic,highlightCSS:ac,highlightHTML:cc,renderTable:ep,renderProgress:tp,StreamRenderer:_o}});var To=P((c$,pc)=>{var{execSync:np}=require("child_process"),Eo=require("path"),on=require("fs"),Co=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function dc(){return Eo.join(process.cwd(),".nex","hooks")}function sp(){return Eo.join(process.cwd(),".nex","config.json")}function fc(){let t=sp();if(!on.existsSync(t))return{};try{return JSON.parse(on.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function es(t){if(!Co.includes(t))return[];let e=[],o=dc(),n=Eo.join(o,t);on.existsSync(n)&&e.push(n);let s=fc();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function mc(t,e={},o=3e4){try{return{success:!0,output:np(t,{cwd:process.cwd(),encoding:"utf-8",timeout:o,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function op(t,e={}){let o=es(t);if(o.length===0)return[];let n={};for(let[r,a]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(a);let s=[];for(let r of o){let a=mc(r,n);if(s.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return s}function rp(t){return es(t).length>0}function ip(){let t=[];for(let e of Co){let o=es(e);o.length>0&&t.push({event:e,commands:o})}return t}function ap(){let t=dc();return on.existsSync(t)||on.mkdirSync(t,{recursive:!0}),t}pc.exports={HOOK_EVENTS:Co,loadHookConfig:fc,getHooksForEvent:es,executeHook:mc,runHooks:op,hasHooks:rp,listHooks:ip,initHooksDir:ap}});var ne=P((d$,Ec)=>{var{C:_,Spinner:Ct,TaskProgress:cp,formatToolCall:lp,formatResult:up,formatToolSummary:yc,setActiveTaskProgress:l$}=ee(),{callStream:dp}=ie(),{parseToolArgs:fp}=vn(),{executeTool:mp}=Ie(),{gatherProjectContext:pp}=ho(),{fitToContext:hp,forceCompress:Ro,getUsage:gp,estimateTokens:$p}=ke(),{autoSave:ut}=rt(),{getMemoryContext:yp}=Je(),{checkPermission:wp,setPermission:bp,savePermissions:xp}=sn(),{confirm:wc,setAllowAlwaysHandler:kp}=Ce(),{isPlanMode:rs,getPlanModePrompt:vp,PLAN_MODE_ALLOWED_TOOLS:bc,setPlanContent:_p}=Et(),{StreamRenderer:Sp}=uc(),{runHooks:hc}=To(),{routeMCPCall:Ep,getMCPToolDefinitions:Cp}=Tn(),{getSkillInstructions:Tp,getSkillToolDefinitions:Rp,routeSkillCall:Ap}=Ft(),{trackUsage:Np}=$t(),{validateToolArgs:Mp}=js(),{filterToolsForModel:gc,getModelTier:Op,PROVIDER_DEFAULT_TIER:u$}=Xs(),{getConfiguredProviders:Pp,getActiveProviderName:qp,getActiveModelId:Ip}=ie(),jo=require("fs"),xc=require("path"),$c=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Lp(t){let e=[],o;for($c.lastIndex=0;(o=$c.exec(t))!==null;){let n=o[1].trim(),s=n.startsWith("~")?n.replace("~",process.env.HOME||""):xc.resolve(n);jo.existsSync(s)&&e.push({raw:n,abs:s})}return e}function jp(t){let e=jo.readFileSync(t),o=xc.extname(t).toLowerCase().replace(".",""),n=o==="jpg"||o==="jpeg"?"image/jpeg":o==="png"?"image/png":o==="gif"?"image/gif":o==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function kc(t){let e=Lp(t);if(e.length===0)return t;let o=[{type:"text",text:t}];for(let n of e)try{let{data:s,media_type:r}=jp(n.abs);o.push({type:"image",media_type:r,data:s})}catch{}return o.length>1?o:t}var Ao=null,No=null,Mo=null;function Tt(){if(Ao===null){let{TOOL_DEFINITIONS:t}=Ie();Ao=t}return No===null&&(No=Rp()),Mo===null&&(Mo=Cp()),[...Ao,...No,...Mo]}var Io=50;function Dp(t){Number.isFinite(t)&&t>0&&(Io=t)}var ns=()=>null;function Fp(t){ns=t}var rn=null,Lo=null,Rt=null,ss=new Map,Up=1e4,Bp=6e3;function Wp(t){if($p(t)>Up)try{let{compressToolResult:o}=ke();return o(t,Bp)}catch{return t}return t}function vc(t){try{let{getActiveModel:e}=ie(),o=e(),n=o?`${o.provider}:${o.id}`:"default";if(ss.has(n))return ss.get(n);let s=gc(t);return ss.set(n,s),s}catch{return gc(t)}}function Hp(){ss.clear()}async function _c(){try{let t=require("fs").promises,e=require("path"),o=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(o.map(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Je(),a=r();a&&s.push(`memory:${a}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(jo.existsSync(r)){let a=await t.stat(r);s.push(`brain:${a.mtimeMs}`)}}catch{}return s.join("|")}catch{return`fallback:${Date.now()}`}}function zp(){rn=null,Lo=null,Rt=null}var Gp=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"]),Oo=5,Po=3,ts=2,Kp=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),Jp=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function Yp(t){try{let e=require("fs"),o=require("path"),n=o.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let s=o.join(n,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}kp(t=>{bp(t,"allow"),xp(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function Xp(t){let e=t.function.name,o=fp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!o){let l=Tt().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${_.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${_.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
280
342
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
281
343
|
|
|
282
344
|
Expected JSON schema for "${e}":
|
|
283
345
|
${u}
|
|
284
346
|
|
|
285
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let
|
|
286
|
-
`)[0]}${_.reset}`),{callId:n,fnName:e,args:
|
|
287
|
-
...(truncated ${n.length-5e4} chars)`:n,r=
|
|
288
|
-
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(
|
|
289
|
-
`)}function
|
|
290
|
-
`];
|
|
291
|
-
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 s=Mp(e,o);if(!s.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
348
|
+
`)[0]}${_.reset}`),{callId:n,fnName:e,args:o,canExecute:!1,errorResult:{role:"tool",content:s.error,tool_call_id:n}};let r=s.corrected||o;if(s.corrected){let c=Object.keys(o),l=Object.keys(s.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${_.dim} \u2713 ${e}: corrected args (${u.join(", ")})${_.reset}`)}if(rs()&&!bc.has(e))return console.log(`${_.yellow} \u2717 ${e}: blocked in plan mode${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let a=wp(e);if(a==="deny")return console.log(`${_.red} \u2717 ${e}: denied by permissions${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await wc(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 Vp(t,e,o={}){let n=await Ap(t,e);if(n!==null)return n;let s=await Ep(t,e);return s!==null?s:mp(t,e,o)}function Qp(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(lp(t.fnName,t.args)),hc("pre-tool",{tool_name:t.fnName});let o=await Vp(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(o??""),s=n.length>5e4?n.substring(0,5e4)+`
|
|
349
|
+
...(truncated ${n.length-5e4} chars)`:n,r=s.split(`
|
|
350
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(s)&&/✗ Agent/.test(s),c=yc(t.fnName,t.args,s,a);return e||(console.log(up(s)),console.log(c)),hc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:Wp(s),tool_call_id:t.callId},summary:c}}async function Zp(t,e=!1,o={}){let n=new Array(t.length),s=[],r=[],a=null;if(e&&!o.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=Qp(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 Ct(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,s.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,s.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,s.push(yc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Gp.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,s.push(f)}}if(await c(),a&&a.stop(),e&&s.length>0&&!o.skipSummaries)for(let l of s)console.log(l);return n}var ae=[],os=[];function eh(t){os.push(t.trim())}function th(){return os.length===0?null:os.splice(0,os.length).join(`
|
|
351
|
+
`)}function nh(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,o=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,s=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
352
|
+
`];n?s.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.`):s.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."),s.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets.");let r=e||(n?"English":null);r&&s.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let a=o||(n?"English":null);return a&&s.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),n&&s.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.`),s.join(`
|
|
292
354
|
`)+`
|
|
293
355
|
|
|
294
|
-
`}function
|
|
356
|
+
`}function sh(){if(Rt!==null)return Rt;try{let e=Pp().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:Op(r.id,s.name),name:r.name})));if(e.length<2)return Rt="","";let o={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
295
357
|
# Sub-Agent Model Routing
|
|
296
358
|
|
|
297
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 |
|
|
298
360
|
|---|---|---|
|
|
299
|
-
`;for(let
|
|
300
|
-
`;return
|
|
361
|
+
`;for(let s of e)n+=`| ${s.spec} | ${s.tier} | ${o[s.tier]||s.tier} |
|
|
362
|
+
`;return Rt=n,n}catch{return Rt="",""}}async function Sc(){let t=await _c();if(rn!==null&&t===Lo)return rn;let e=await pp(process.cwd()),o=yp(),n=Tp(),s=rs()?vp():"",r=nh();return rn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
301
363
|
|
|
302
364
|
WORKING DIRECTORY: ${process.cwd()}
|
|
303
365
|
All relative paths resolve from this directory.
|
|
304
366
|
${r?`
|
|
305
367
|
${r}`:""}PROJECT CONTEXT:
|
|
306
368
|
${e}
|
|
307
|
-
${
|
|
308
|
-
${
|
|
369
|
+
${o?`
|
|
370
|
+
${o}
|
|
309
371
|
`:""}${n?`
|
|
310
372
|
${n}
|
|
311
|
-
`:""}${
|
|
312
|
-
${
|
|
373
|
+
`:""}${s?`
|
|
374
|
+
${s}
|
|
313
375
|
`:""}
|
|
314
376
|
# Core Behavior
|
|
315
377
|
|
|
@@ -333,7 +395,7 @@ Response patterns by request type:
|
|
|
333
395
|
- **Questions / analysis / "status" / "explain" / "what is"**: Gather data with tools, then respond with a clear, structured summary. NEVER just run tools and stop.
|
|
334
396
|
- **Coding tasks (implement, fix, refactor)**: Brief confirmation of what you'll do, then use tools. After changes, summarize what you did and any important details.
|
|
335
397
|
- **Simple questions ("what does X do?")**: Answer directly without tools when you have enough context.
|
|
336
|
-
- **Ambiguous requests**: When a request is vague
|
|
398
|
+
- **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.
|
|
337
399
|
- **Server/SSH commands**: After running remote commands, ALWAYS present the results: service status, log errors, findings.
|
|
338
400
|
|
|
339
401
|
After completing multi-step tasks, suggest logical next steps (e.g. "You can run npm test to verify" or "Consider committing with /commit").
|
|
@@ -369,7 +431,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
369
431
|
- Good for: reading multiple files, analyzing separate modules.
|
|
370
432
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
371
433
|
- Max 5 parallel agents.
|
|
372
|
-
${
|
|
434
|
+
${sh()}
|
|
373
435
|
|
|
374
436
|
# Edit Reliability (Critical)
|
|
375
437
|
|
|
@@ -409,14 +471,27 @@ When a tool call returns ERROR:
|
|
|
409
471
|
- Prefer creating new git commits over amending. Never force-push without explicit permission.
|
|
410
472
|
- If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
|
|
411
473
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
474
|
+
# Brain Knowledge Base
|
|
475
|
+
|
|
476
|
+
You have access to a persistent knowledge base in .nex/brain/.
|
|
477
|
+
- Use brain_write to save important discoveries, patterns, or decisions
|
|
478
|
+
- Write when you find: architecture insights, recurring error patterns, API quirks, deployment steps
|
|
479
|
+
- Do NOT write trivial or session-specific information
|
|
480
|
+
- Do NOT duplicate what's already in NEX.md or project memory
|
|
481
|
+
- Use descriptive kebab-case names: "auth-flow", "db-migration-steps"
|
|
482
|
+
- Include tags in frontmatter for better retrieval
|
|
483
|
+
- The user reviews all brain writes via /brain review or git diff
|
|
484
|
+
|
|
485
|
+
`,Lo=t,rn}function oh(){ae=[]}function rh(){return ae.length}function ih(){return ae}function ah(t){ae=t}function dt(t,e,o,n,s){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(o.size>0&&(a+=` \xB7 ${o.size} ${o.size===1?"file":"files"} modified`),s){let c=Date.now()-s,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(`
|
|
486
|
+
${_.dim} ${a}${_.reset}`),o.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function ch(t){let e=kc(t);ae.push({role:"user",content:e});let{setOnChange:o}=jn(),n=null,s=0;o((j,D)=>{j==="create"?(n&&n.stop(),n=new cp(D.name,D.tasks),n.setStats({tokens:s}),n.start()):j==="update"&&n?n.updateTask(D.id,D.status):j==="clear"&&n&&(n.stop(),n=null)});let r=await Sc(),a=r;try{let{getBrainContext:j}=Vt(),D=await j(t);D&&(a=r+`
|
|
487
|
+
`+D+`
|
|
488
|
+
`)}catch{}let c=[{role:"system",content:a},...ae],l=new Ct("Thinking...");l.start();let u=Tt(),{messages:d,compressed:f,compacted:m,tokensRemoved:h}=await hp(c,u),p=gp(c,u);if(l.stop(),m)console.log(`${_.dim} [context compacted \u2014 summary (~${h} tokens freed)]${_.reset}`);else if(f){let j=p.limit>0?Math.round(h/p.limit*100):0;console.log(`${_.dim} [context compressed \u2014 ~${h} tokens freed (${j}%)]${_.reset}`)}p.percentage>85&&console.log(`${_.yellow} \u26A0 Context ${Math.round(p.percentage)}% full \u2014 consider /clear or /save + start fresh${_.reset}`);let g=d,y=0,w=0,k=0,E=0,x=0,v=new Map,S=new Set,C=new Set,A=Date.now(),I,L=Io,N=0,M=10;e:for(;;){for(I=0;I<L;I++){let Y=function(){D||(console.log(`${_.cyan} \u25C6 Step ${x}${_.reset}`),D=!0)};var F=Y;if(ns()?.aborted)break;let D=!0,B=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let R=x>0?`Thinking... (step ${x+1})`:"Thinking...";B=new Ct(R),B.start()}let ce=!0,We="",de=new Sp,Ee,un=Date.now(),us=!1,ds=new AbortController,nr=setInterval(()=>{let R=Date.now()-un;R>=Jp?(de._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(R/1e3)}s \u2014 aborting and retrying${_.reset}`),ds.abort()):R>=Kp&&!us&&(us=!0,de._clearCursorLine(),console.log(`${_.yellow} \u26A0 No tokens received for ${Math.round(R/1e3)}s \u2014 waiting...${_.reset}`))},5e3),ye="",Oe=null;try{let R=vc(Tt()),U=rs()?R.filter(re=>bc.has(re.function.name)):R,ft=ns(),W=new AbortController;ft&&ft.addEventListener("abort",()=>W.abort(),{once:!0}),ds.signal.addEventListener("abort",()=>W.abort(),{once:!0}),Ee=await dp(g,U,{signal:W.signal,onToken:re=>{un=Date.now(),us=!1,ye+=re,process.stdout.isTTY?Oe||(Oe=setTimeout(()=>{ye&&de&&de.push(ye),ye="",Oe=null},50)):(de.push(ye),ye=""),ce&&(n&&!n._paused?n.pause():B&&B.stop(),Y(),de.startCursor(),ce=!1),We+=re}})}catch(R){if(clearInterval(nr),Oe&&(clearTimeout(Oe),Oe=null),ye&&de&&(de.push(ye),ye=""),n&&!n._paused&&n.pause(),B&&B.stop(),de.stopCursor(),ds.signal.aborted&&!ns()?.aborted){if(k++,k>ts){if(E<1){E++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let xe=Tt(),{messages:Ot,tokensRemoved:Pt}=Ro(g,xe);g=Ot,console.log(`${_.dim} [force-compressed \u2014 ~${Pt} tokens freed]${_.reset}`),k=0,I--;continue}console.log(`${_.red} \u2717 Stream stale: max retries (${ts}) exceeded. The model may be overloaded \u2014 try again or switch models.${_.reset}`),n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);break}let W=k===1?3e3:5e3;if(k>=2&&E<1){E++,console.log(`${_.yellow} \u26A0 Stale retry ${k}/${ts} \u2014 force-compressing before retry...${_.reset}`);let xe=Tt(),{messages:Ot,tokensRemoved:Pt}=Ro(g,xe);g=Ot,console.log(`${_.dim} [force-compressed \u2014 ~${Pt} tokens freed]${_.reset}`)}else console.log(`${_.yellow} \u26A0 Stale retry ${k}/${ts} \u2014 retrying in ${W/1e3}s...${_.reset}`);let re=new Ct(`Waiting ${W/1e3}s before retry...`);re.start(),await new Promise(xe=>setTimeout(xe,W)),re.stop(),I--;continue}if(R.name==="AbortError"||R.name==="CanceledError"||R.message?.includes("canceled")||R.message?.includes("aborted")){n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);break}let U=R.message;if(R.code==="ECONNREFUSED"||R.message.includes("ECONNREFUSED"))U="Connection refused \u2014 please check your internet connection or API endpoint";else if(R.code==="ENOTFOUND"||R.message.includes("ENOTFOUND"))U="Network error \u2014 could not reach the API server. Please check your connection";else if(R.code==="ETIMEDOUT"||R.message.includes("timeout"))U="Request timed out \u2014 the API server took too long to respond. Please try again";else if(R.message.includes("401")||R.message.includes("Unauthorized"))U="Authentication failed \u2014 please check your API key in the .env file";else if(R.message.includes("403")||R.message.includes("Forbidden"))U="Access denied \u2014 your API key may not have permission for this model";else if(R.message.includes("400")){let W=(R.message||"").toLowerCase(),re=W.includes("context")||W.includes("token")||W.includes("length")||W.includes("too long")||W.includes("too many")||W.includes("prompt")||W.includes("size")||W.includes("exceeds")||W.includes("num_ctx")||W.includes("input");if(re&&E<1){E++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let xe=Tt(),{messages:Ot,tokensRemoved:Pt}=Ro(g,xe);g=Ot,console.log(`${_.dim} [force-compressed \u2014 ~${Pt} tokens freed]${_.reset}`),I--;continue}re?U="Context too long \u2014 force compression exhausted. Use /clear to start fresh":U="Bad request \u2014 the conversation may be too long or contain unsupported content. Try /clear and retry"}else R.message.includes("500")||R.message.includes("502")||R.message.includes("503")||R.message.includes("504")?U="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(R.message.includes("fetch failed")||R.message.includes("fetch"))&&(U="Network request failed \u2014 please check your internet connection");if(console.log(`${_.red} \u2717 ${U}${_.reset}`),R.message.includes("429")){if(y++,y>Oo){console.log(`${_.red} Rate limit: max retries (${Oo}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);break}let W=Math.min(1e4*Math.pow(2,y-1),12e4),re=new Ct(`Rate limit \u2014 waiting ${Math.round(W/1e3)}s (retry ${y}/${Oo})`);re.start(),await new Promise(xe=>setTimeout(xe,W)),re.stop();continue}if(R.message.includes("socket disconnected")||R.message.includes("TLS")||R.message.includes("ECONNRESET")||R.message.includes("ECONNABORTED")||R.message.includes("ETIMEDOUT")||R.code==="ECONNRESET"||R.code==="ECONNABORTED"){if(w++,w>Po){console.log(`${_.red} Network error: max retries (${Po}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);break}let W=Math.min(2e3*Math.pow(2,w-1),3e4),re=new Ct(`Network error \u2014 retrying in ${Math.round(W/1e3)}s (${w}/${Po})`);re.start(),await new Promise(xe=>setTimeout(xe,W)),re.stop(),I--;continue}n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);break}clearInterval(nr),ce&&(n&&!n._paused&&n.pause(),B&&B.stop()),Oe&&(clearTimeout(Oe),Oe=null),ye&&de&&(de.push(ye),ye=""),We&&de.flush(),w=0,k=0,Ee&&Ee.usage&&(Np(qp(),Ip(),Ee.usage.prompt_tokens||0,Ee.usage.completion_tokens||0),s+=(Ee.usage.prompt_tokens||0)+(Ee.usage.completion_tokens||0),n&&n.setStats({tokens:s}));let{content:fs,tool_calls:Qe}=Ee,ms={role:"assistant",content:fs||""};if(Qe&&Qe.length>0&&(ms.tool_calls=Qe),ae.push(ms),g.push(ms),!Qe||Qe.length===0){let R=(fs||"").trim().length>0||We.trim().length>0;if(!R&&x>0&&I<Io-1){let U={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(U);continue}if(rs()&&R){let U=(fs||We||"").trim();_p(U),Yp(U),console.log(`
|
|
489
|
+
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);return}x++,x>1&&(D=!1);for(let R of Qe){let U=R.function.name;v.set(U,(v.get(U)||0)+1)}let ps=await Promise.all(Qe.map(R=>Xp(R))),sr=n?{skipSpinner:!0,skipSummaries:!0}:{};sr.skipSummaries||Y(),n&&n._paused&&n.resume();let or=await Zp(ps,!0,sr);for(let R=0;R<ps.length;R++){let U=ps[R];if(!U.canExecute)continue;let ft=or[R].content,W=!ft.startsWith("ERROR")&&!ft.includes("CANCELLED");W&&["write_file","edit_file","patch_file"].includes(U.fnName)&&U.args&&U.args.path&&S.add(U.args.path),W&&U.fnName==="read_file"&&U.args&&U.args.path&&C.add(U.args.path)}for(let R of or)ae.push(R),g.push(R);let rr=th();if(rr){let R={role:"user",content:`[User note mid-run]: ${rr}`};ae.push(R),g.push(R),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(I>=L){n&&(n.stop(),n=null),o(null),dt(x,v,S,C,A),ut(ae);let{getActiveProviderName:j}=ie();if(j()==="ollama"&&N<M){N++,L+=20,console.log(`${_.dim} \u2500\u2500 auto-extending to ${L} turns \u2500\u2500${_.reset}`);continue e}if(console.log(`
|
|
490
|
+
${_.yellow}\u26A0 Max iterations (${L}) reached.${_.reset}`),await wc(" Continue for 20 more turns?")){L+=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}Ec.exports={processInput:ch,clearConversation:oh,getConversationLength:rh,getConversationMessages:ih,setConversationMessages:ah,setAbortSignalGetter:Fp,setMaxIterations:Dp,invalidateSystemPromptCache:zp,clearToolFilterCache:Hp,getCachedFilteredTools:vc,buildSystemPrompt:Sc,getProjectContextHash:_c,buildUserContent:kc,injectMidRunNote:eh}});var ie=P((f$,Mc)=>{var{OllamaProvider:lh}=vr(),{OpenAIProvider:uh}=Br(),{AnthropicProvider:dh}=Gr(),{GeminiProvider:fh}=Xr(),{LocalProvider:mh}=Zr(),{checkBudget:ph}=$t(),Cc={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"}},Tc={};for(let[t,e]of Object.entries(Cc))for(let o of Object.values(e))Tc[o]=t;function Rc(t,e){let o=Tc[t];return o&&Cc[o][e]||t}var oe={},he=null,se=null,an=[];function be(){if(Object.keys(oe).length>0)return;At("ollama",new lh),At("openai",new uh),At("anthropic",new dh),At("gemini",new fh),At("local",new mh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;oe[t]?(he=t,se=e||oe[t].defaultModel):(he="ollama",se="kimi-k2.5");let o=process.env.FALLBACK_CHAIN;o&&(an=o.split(",").map(n=>n.trim()).filter(Boolean))}function At(t,e){oe[t]=e}function hh(t){return be(),oe[t]||null}function Do(){return be(),oe[he]||null}function gh(){return be(),he}function $h(){return be(),se}function yh(){be();let t=Do();if(!t)return{id:se,name:se,provider:he};let e=t.getModel(se);return e?{...e,provider:he}:{id:se,name:se,provider:he}}function Ac(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let o=t.slice(0,e);if(oe[o]||["ollama","openai","anthropic","gemini","local"].includes(o))return{provider:o,model:t.slice(e+1)}}return{provider:null,model:t}}function wh(t){be();let{provider:e,model:o}=Ac(t);if(e){let s=oe[e];return s&&(s.getModel(o)||e==="local"||e==="ollama")?(he=e,se=o,is(),!0):!1}let n=Do();if(n&&n.getModel(o))return se=o,is(),!0;for(let[s,r]of Object.entries(oe))if(r.getModel(o))return he=s,se=o,is(),!0;return!1}function is(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ne();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=ke();t()}catch{}}function bh(){be();let t=new Set;for(let e of Object.values(oe))for(let o of e.getModelNames())t.add(o);return Array.from(t)}function xh(){return be(),Object.entries(oe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(o=>({...o,active:t===he&&o.id===se}))}))}function kh(){be();let t=[];for(let[e,o]of Object.entries(oe)){let n=o.isConfigured();for(let s of Object.values(o.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:n})}return t}function vh(t){an=Array.isArray(t)?t:[]}function _h(){return[...an]}function Sh(t){let e=t.message||"",o=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||o==="ECONNABORTED"||o==="ETIMEDOUT"||o==="ECONNREFUSED"||o==="ECONNRESET"||o==="EHOSTUNREACH"||o==="ENETUNREACH"||o==="EPIPE"||o==="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=[he,...an.filter(r=>r!==he)],o,n=0,s=0;for(let r=0;r<e.length;r++){let a=e[r],c=oe[a];if(!c||!c.isConfigured())continue;s++;let l=ph(a);if(!l.allowed){n++,o=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Rc(se,a):se;return u&&d!==se&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
491
|
+
`),await t(c,a,d)}catch(u){if(o=u,Sh(u)&&r<e.length-1)continue;throw u}}throw n>0&&n===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o||new Error("No configured provider available")}async function Eh(t,e,o={}){return be(),Nc((n,s,r)=>n.stream(t,e,{model:r,signal:o.signal,...o}))}async function Ch(t,e,o={}){if(be(),o.provider){let n=oe[o.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${o.provider}' is not available`);let s={model:o.model||se,...o};try{return await n.chat(t,e,s)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Nc(async(n,s,r)=>{try{return await n.chat(t,e,{model:r,...o})}catch(a){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...o,onToken:()=>{}})}catch{}throw a}})}function Th(){be();let t=[];for(let[e,o]of Object.entries(oe))o.isConfigured()&&t.push({name:e,models:Object.values(o.getModels())});return t}function Rh(){for(let t of Object.keys(oe))delete oe[t];he=null,se=null,an=[]}Mc.exports={registerProvider:At,getProvider:hh,getActiveProvider:Do,getActiveProviderName:gh,getActiveModelId:$h,getActiveModel:yh,setActiveModel:wh,getModelNames:bh,parseModelSpec:Ac,listProviders:xh,listAllModels:kh,callStream:Eh,callChat:Ch,getConfiguredProviders:Th,setFallbackChain:vh,getFallbackChain:_h,resolveModelForProvider:Rc,_reset:Rh}});var qc=P((m$,Pc)=>{var{C:G}=ee(),{listProviders:Ah,getActiveProviderName:Nh,getActiveModelId:Mh,setActiveModel:Oh}=ie();function Oc(t,e,o={}){let{title:n="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=o;return new Promise(r=>{let a=e.map((w,k)=>w.isHeader?-1:k).filter(w=>w>=0);if(a.length===0){r(null);return}let c=e.findIndex(w=>w.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 w=a[l];return w<d?d=w:w>=d+u&&(d=w-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let v=0;v<m;v++)process.stdout.write(`\x1B[2K
|
|
492
|
+
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${G.bold}${G.cyan}${n}${G.reset}`),w.push(` ${G.dim}${s}${G.reset}`),w.push("");let{start:k,end:E}=f();k>0&&w.push(` ${G.dim}\u2191 more${G.reset}`);for(let v=k;v<E;v++){let S=e[v];if(S.isHeader){w.push(` ${G.bold}${G.dim}${S.label}${G.reset}`);continue}let C=a[l]===v,A=C?`${G.cyan}> `:" ",I=S.isCurrent?` ${G.yellow}<current>${G.reset}`:"";C?w.push(`${A}${G.bold}${S.label}${G.reset}${I}`):w.push(`${A}${G.dim}${S.label}${G.reset}${I}`)}E<e.length&&w.push(` ${G.dim}\u2193 more${G.reset}`);let x=w.join(`
|
|
493
|
+
`);process.stdout.write(x+`
|
|
494
|
+
`),m=w.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y(w,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){l>0&&(l--,h());return}if(k.name==="down"||k.ctrl&&k.name==="n"){l<a.length-1&&(l++,h());return}if(k.name==="return"){let E=e[a[l]];g(),r(E?E.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function Ph(t){let e=Ah(),o=Nh(),n=Mh(),s=[];for(let a of e)if(a.models.length!==0){s.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===o&&c.id===n;s.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await Oc(t,s,{title:"Select Model"});return r?(Oh(r),console.log(`${G.green}Switched to ${r}${G.reset}`),!0):(console.log(`${G.dim}Cancelled${G.reset}`),!1)}Pc.exports={pickFromList:Oc,showModelPicker:Ph}});var Bo=P((h$,Bc)=>{var Fo=require("fs"),qh=require("path"),{callChat:Ic}=ie(),{remember:Ih,listMemories:p$,recall:Lh}=Je(),Uo=4,jh=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
420
495
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
421
496
|
|
|
422
497
|
Return ONLY valid JSON in this exact format:
|
|
@@ -442,17 +517,79 @@ Rules:
|
|
|
442
517
|
- value: concise actionable instruction, max 120 chars
|
|
443
518
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
444
519
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
445
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
520
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Lc(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
|
+
|
|
522
|
+
`)}async function jc(t){if(t.filter(s=>s.role==="user").length<Uo)return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=Lc(t);if(!o.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:jh},{role:"user",content:`Conversation to analyze:
|
|
523
|
+
|
|
524
|
+
${o}`}];try{let a=((await Ic(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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function Dc(t){let e=[];for(let{key:o,value:n}of t||[]){if(!o||!n||typeof o!="string"||typeof n!="string")continue;let s=o.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!s||!r)continue;let a=Lh(s);a!==r&&(Ih(s,r),e.push({key:s,value:r,action:a?"updated":"added"}))}return e}function Fc(t){if(!t||t.length===0)return[];let e=qh.join(process.cwd(),"NEX.md"),o="";try{Fo.existsSync(e)&&(o=Fo.readFileSync(e,"utf-8"))}catch{}let n=[],s=o;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();o.toLowerCase().includes(c)||(n.push(a),s=s?s.endsWith(`
|
|
525
|
+
`)?s+a:s+`
|
|
526
|
+
`+a:a)}return n.length>0&&(s.endsWith(`
|
|
527
|
+
`)||(s+=`
|
|
528
|
+
`),Fo.writeFileSync(e,s,"utf-8")),n}async function Dh(t){let e=await jc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let o=Dc(e.memories),n=Fc(e.nex_additions);return{applied:o,nexAdded:n,summary:e.summary}}var Fh=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
529
|
+
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
446
530
|
|
|
447
|
-
|
|
531
|
+
Return ONLY valid JSON in this exact format:
|
|
532
|
+
{
|
|
533
|
+
"documents": [
|
|
534
|
+
{
|
|
535
|
+
"name": "kebab-case-name",
|
|
536
|
+
"content": "# Title\\n\\nMarkdown content with details...",
|
|
537
|
+
"reason": "one sentence: why this is worth persisting"
|
|
538
|
+
}
|
|
539
|
+
],
|
|
540
|
+
"skip_reason": "why nothing was extracted (only if documents is empty)"
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
Extract documents ONLY for these categories:
|
|
544
|
+
1. ARCHITECTURE DECISIONS \u2014 How the system is structured, why certain choices were made
|
|
545
|
+
2. DEBUGGING INSIGHTS \u2014 Non-obvious bugs, error patterns, tricky workarounds discovered this session
|
|
546
|
+
3. API QUIRKS \u2014 Undocumented behaviors, edge cases of libraries/frameworks/services used
|
|
547
|
+
4. DEPLOYMENT PATTERNS \u2014 Steps, configs, sequences required to deploy/run the system
|
|
548
|
+
5. CODE CONVENTIONS \u2014 Project-specific patterns beyond what's obviously in the codebase
|
|
448
549
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
550
|
+
Rules:
|
|
551
|
+
- ONLY extract if the information is genuinely reusable in future sessions
|
|
552
|
+
- Do NOT extract session-specific context ("we decided today...") \u2014 only durable facts and patterns
|
|
553
|
+
- Do NOT extract trivial information (e.g. "the project uses React")
|
|
554
|
+
- Do NOT duplicate what's clearly in README, package.json, or NEX.md
|
|
555
|
+
- name: kebab-case, max 40 chars, descriptive (e.g. "jwt-redis-caching", "docker-deploy-sequence")
|
|
556
|
+
- content: proper Markdown \u2014 use headings (#), lists (-), code blocks (\`\`\`). Include YAML frontmatter with tags if helpful:
|
|
557
|
+
---
|
|
558
|
+
tags: [auth, redis, caching]
|
|
559
|
+
---
|
|
560
|
+
- Maximum 3 documents per session. Quality over quantity.
|
|
561
|
+
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
562
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Uc(t){if(t.filter(s=>s.role==="user").length<Uo)return{documents:[],skip_reason:"Session too short"};let o=Lc(t);if(!o.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:Fh},{role:"user",content:`Conversation to analyze:
|
|
563
|
+
|
|
564
|
+
${o}`}];try{let a=((await Ic(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(s){return{documents:[],error:s.message}}}async function Uh(t){let e=await Uc(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:o,readDocument:n}=Vt(),s=[],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
|
+
|
|
566
|
+
## Update ${new Date().toISOString().split("T")[0]}
|
|
567
|
+
|
|
568
|
+
${a.content}`;o(c,l.content+d),s.push({name:c,reason:a.reason||"",action:"updated"})}else o(c,a.content),s.push({name:c,reason:a.reason||"",action:"created"})}return{written:s,skipped:r}}Bc.exports={learnFromSession:Dh,learnBrainFromSession:Uh,reflectOnSession:jc,reflectBrain:Uc,applyMemories:Dc,applyNexAdditions:Fc,LEARN_MIN_MESSAGES:Uo}});var Kc=P(($$,Gc)=>{var ue=require("fs"),Mt=require("path"),g$=require("os"),Bh=require("readline"),{C:T}=ee(),Wc=".nex",Wo=null;function Wh(t){Wo=t}function $e(t,e=""){let o=e?` ${T.dim}[${e}]${T.reset}`:"",n=` ${T.cyan}${t}${o}${T.reset}: `;return new Promise(s=>{let r=a=>{let c=a.trim()||e;s(c)};if(Wo)Wo.question(n,r);else{let a=Bh.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 Hc(t,e,o){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 s=o?e.indexOf(o)+1:1,r=await $e("Enter number",String(s)),a=parseInt(r,10)-1;return e[Math.max(0,Math.min(a,e.length-1))]}async function Hh(){let t=Mt.join(process.cwd(),Wc),e=Mt.join(t,"servers.json"),o={};if(ue.existsSync(e))try{o=JSON.parse(ue.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
569
|
+
${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(o);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}
|
|
571
|
+
`);return}let s={...o},r=!0;for(;r;){console.log(`
|
|
572
|
+
${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 Hc("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Nt("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),s[l]=y,console.log(`
|
|
573
|
+
${T.green}\u2713${T.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await Nt(`
|
|
574
|
+
Add another server?`,!1)}ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0}),ue.writeFileSync(e,JSON.stringify(s,null,2)+`
|
|
575
|
+
`,"utf-8"),console.log(`
|
|
576
|
+
${T.green}\u2713 Saved .nex/servers.json (${Object.keys(s).length} profile${Object.keys(s).length!==1?"s":""})${T.reset}`);let a=Mt.join(process.cwd(),".gitignore");ue.existsSync(a)&&(ue.readFileSync(a,"utf-8").includes(".nex/")||await Nt("Add .nex/ to .gitignore?",!0)&&(ue.appendFileSync(a,`
|
|
577
|
+
# nex-code server profiles
|
|
578
|
+
.nex/
|
|
579
|
+
`),console.log(`${T.green}\u2713 Added .nex/ to .gitignore${T.reset}`))),await Nt(`
|
|
580
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await zc(s,t),console.log(`
|
|
581
|
+
${T.dim}Use /servers to list profiles, /servers ping to check connectivity.${T.reset}
|
|
582
|
+
`)}async function zc(t,e){let o=e||Mt.join(process.cwd(),Wc),n=Mt.join(o,"deploy.json"),s={};if(ue.existsSync(n))try{s=JSON.parse(ue.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Mt.join(o,"servers.json");if(ue.existsSync(u))try{t=JSON.parse(ue.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
583
|
+
${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(s);a.length>0&&console.log(`${T.dim}Existing deploy configs: ${a.join(", ")}${T.reset}`);let c={...s},l=!0;for(;l;){console.log(`
|
|
585
|
+
${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 Hc("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(k=>k.trim()).filter(Boolean):[],y={server:d,local_path:f,remote_path:m};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let w=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
586
|
+
${T.green}\u2713${T.reset} Deploy config "${u}": ${w} \u2192 ${d}:${m}`),h&&console.log(` ${T.dim} Then: ${h}${T.reset}`),l=await Nt(`
|
|
587
|
+
Add another deploy config?`,!1)}ue.existsSync(o)||ue.mkdirSync(o,{recursive:!0}),ue.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
588
|
+
`,"utf-8"),console.log(`
|
|
589
|
+
${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
|
+
`)}Gc.exports={runServerWizard:Hh,runDeployWizard:zc,setWizardRL:Wh}});var Xc=P((y$,Yc)=>{var zh=require("axios"),cn=require("fs"),Jc=require("path"),Gh="nex-code",Ho=Jc.join(process.cwd(),".nex"),zo=Jc.join(Ho,"last-version-check");cn.existsSync(Ho)||cn.mkdirSync(Ho,{recursive:!0});async function Kh(){try{let t=Yh(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Xh(e);let o=Jh(),s=(await zh.get(`https://registry.npmjs.org/${Gh}/latest`,{timeout:5e3})).data.version,r=Vh(s,o);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?o:void 0}}catch{return{hasNewVersion:!1}}}function Jh(){return dn().version}function Yh(){try{if(cn.existsSync(zo)){let t=cn.readFileSync(zo,"utf8");return parseInt(t,10)}}catch{}return null}function Xh(t){try{cn.writeFileSync(zo,t.toString())}catch{}}function Vh(t,e){try{let o=t.split(".").map(Number),n=e.split(".").map(Number);return o[0]>n[0]?!0:o[0]<n[0]?!1:o[1]>n[1]?!0:o[1]<n[1]?!1:o[2]>n[2]}catch{return!1}}Yc.exports={checkForNewVersion:Kh}});var dl=P((b$,ul)=>{var Qh=require("readline"),Ve=require("fs"),Me=require("path"),{C:i,banner:Zh,cleanupTerminal:Vc}=ee(),{listProviders:Ko,getActiveProviderName:Ye,listAllModels:w$,setFallbackChain:eg,getFallbackChain:tg,getProvider:ng}=ie(),{flushAutoSave:Qc}=rt(),{getActiveModel:Xe,setActiveModel:Zc}=vn(),{printContext:el}=ho(),{loadAllSkills:sg,getSkillCommands:Jo,handleSkillCommand:og}=Ft(),{setReadlineInterface:rg,setAutoConfirm:ig,getAutoConfirm:tl}=Ce(),cs=process.cwd(),Be=null;function nl(){return Be?.signal??null}var ls=[{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 sl(){let t=Jo(),e=[...ls,...t],o=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:s}of ls)console.log(` ${i.cyan}${n.padEnd(o+2)}${i.reset}${i.dim}${s}${i.reset}`);for(let{cmd:n,desc:s}of t)console.log(` ${i.cyan}${n.padEnd(o+2)}${i.reset}${i.dim}${s} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
454
591
|
${i.dim}Type /help for detailed usage${i.reset}
|
|
455
|
-
`)}function
|
|
592
|
+
`)}function ol(t){try{let e,o;t.endsWith("/")||t.endsWith(Me.sep)?(e=t,o=""):(e=Me.dirname(t),o=Me.basename(t)),e.startsWith("~")&&(e=Me.join(require("os").homedir(),e.slice(1)));let n=Me.isAbsolute(e)?e:Me.resolve(cs,e);if(!Ve.existsSync(n)||!Ve.statSync(n).isDirectory())return[];let s=Ve.readdirSync(n,{withFileTypes:!0}),r=[];for(let a of s){if(a.name.startsWith(".")||a.name==="node_modules"||o&&!a.name.startsWith(o))continue;let c=t.endsWith("/")||t.endsWith(Me.sep)?t:Me.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function rl(t){if(t.startsWith("/")){let n=[...ls,...Jo()],s=n.map(r=>r.cmd).filter(r=>r.startsWith(t));return[s.length?s:n.map(r=>r.cmd),t]}let e=t.split(/\s+/),o=e[e.length-1]||"";return o&&(o.includes("/")||o.startsWith("./")||o.startsWith("../")||o.startsWith("~"))?[ol(o),o]:[[],t]}function il(){console.log(`
|
|
456
593
|
${i.bold}${i.cyan}Commands:${i.reset}
|
|
457
594
|
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
458
595
|
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
@@ -513,76 +650,114 @@ ${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
|
513
650
|
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
514
651
|
|
|
515
652
|
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
516
|
-
`)}function
|
|
517
|
-
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let
|
|
518
|
-
${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=
|
|
519
|
-
${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:
|
|
520
|
-
${
|
|
521
|
-
`),!0)}case"/budget":{let{getCostLimits:
|
|
522
|
-
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let
|
|
653
|
+
`)}function al(t){let o=Math.round(t/100*30),n=30-o;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(o)}${i.dim}${"\u2591".repeat(n)}${i.reset} ${t}%`}function Go(){let t=Ko(),e=Ye(),o=Xe();console.log(`
|
|
654
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let s=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=s?` ${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===o.id&&s?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function cl(t,e){let[o,...n]=t.split(/\s+/);switch(o){case"/help":return il(),!0;case"/model":{let s=n.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=qc();await r(e)}else{let r=Xe(),a=Ye();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(s==="list")return Go(),!0;if(Zc(s)){let r=Xe(),a=Ye();console.log(`${i.green}Switched to ${a}:${r.id} (${r.name})${i.reset}`)}else console.log(`${i.red}Unknown model: ${s}${i.reset}`),console.log(`${i.gray}Use /providers to see available models${i.reset}`);return!0}case"/providers":return Go(),!0;case"/fallback":{let s=n.join(" ").trim();if(!s){let a=tg();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=s.split(",").map(a=>a.trim()).filter(Boolean);return eg(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=ne(),{getUsage:r}=ke(),{TOOL_DEFINITIONS:a}=Ie(),c=s(),l=r(c,a),u=Xe(),d=Ye();console.log(`
|
|
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=al(l.percentage);return console.log(` ${f}`),console.log(`
|
|
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:s,resetCosts:r}=$t();return n.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
657
|
+
${s()}
|
|
658
|
+
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=$t(),d=n[0];if(!d){let h=s(),p=Ko();console.log(`
|
|
659
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let y of p){let w=r(y.provider),k=h[y.provider];if(k!==void 0){g=!0;let E=Math.min(100,Math.round(w/k*100)),x=10,v=Math.round(E/100*x),S=x-v,A=`${E>=100?i.red:E>=80?i.yellow:i.green}${"\u2588".repeat(v)}${i.dim}${"\u2591".repeat(S)}${i.reset}`;console.log(` ${i.bold}${y.provider}:${i.reset} $${w.toFixed(2)} / $${k.toFixed(2)} (${E}%) ${A}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${i.bold}${y.provider}:${i.reset} ${i.dim}free (no limit)${i.reset}`):w>0&&console.log(` ${i.bold}${y.provider}:${i.reset} $${w.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:s,getConversationMessages:r}=ne(),{clearHistory:a}=wt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=Bo();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}
|
|
523
660
|
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
524
661
|
`)}).catch(()=>process.stdout.write(`
|
|
525
|
-
`))}return
|
|
526
|
-
${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:
|
|
527
|
-
${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"/
|
|
662
|
+
`))}return s(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await el(cs),!0;case"/autoconfirm":{let s=!tl();return ig(s),console.log(`${i.green}Auto-confirm: ${s?"ON":"OFF"}${i.reset}`),s&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:s}=rt(),{getConversationMessages:r}=ne(),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=Xe(),u=Ye();return s(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:s}=rt(),{setConversationMessages:r}=ne(),a=n.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=s(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:s}=rt(),r=s();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
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:s}=rt(),{setConversationMessages:r}=ne(),a=s();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:s}=Je(),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),s(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:s}=Je(),r=n.join(" ").trim();return r?(s(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:s}=Je(),r=s();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
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:s,readDocument:r,writeDocument:a,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Vt(),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}
|
|
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),y=h.substring(p+1);a(g,y),console.log(`${i.green}Added to brain: ${g}${i.reset}`)}return!0}case"list":{let p=s();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(`
|
|
667
|
+
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map(w=>w.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let w of p){let{frontmatter:k}=r(w.name),E=Array.isArray(k.tags)?k.tags.join(", "):"",x=w.size<1024?`${w.size}B`:`${(w.size/1024).toFixed(1)}K`,v=w.modified.toLocaleDateString();console.log(` ${i.cyan}${w.name.padEnd(g+2)}${i.reset}${i.dim}${E.substring(0,y-1).padEnd(y)}${x.padStart(7)} ${v}${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(`
|
|
668
|
+
${i.bold}${i.cyan}Brain Search: "${h}"${i.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
669
|
+
${i.cyan}${g.name}${i.reset} ${i.dim}(score: ${y})${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
|
+
${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}=Ce();if(!await p(`Remove brain document "${h}"?`))return console.log(`${i.dim}Cancelled${i.reset}`),!0;let y=c(h);return console.log(y?`${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(),y=Object.keys(g.documents||{}).length;console.log(`${i.green}Embedding index built: ${y} document(s)${i.reset}`)}catch(g){console.log(`${i.red}Embedding failed: ${g.message}${i.reset}`)}return!0}case"status":{let p=s(),g=require("fs"),y=require("path"),w=y.join(process.cwd(),".nex","brain",".brain-index.json"),k=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
672
|
+
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(w)?i.green+"present"+i.reset:i.dim+"not built"+i.reset}`),console.log(` Embeddings: ${g.existsSync(k)?i.green+"present"+i.reset:i.dim+"not built (run /brain embed)"+i.reset}`),p.length>0){let E=p.reduce((x,v)=>x+v.size,0);console.log(` Total size: ${E<1024?E+"B":(E/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),y=g(p);try{let{stdout:w}=await y("git diff .nex/brain/",{cwd:process.cwd()});w.trim()?(console.log(`
|
|
673
|
+
${i.bold}${i.cyan}Brain Changes (git diff):${i.reset}
|
|
674
|
+
`),console.log(w)):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"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${i.dim}No brain directory found${i.reset}`),!0;let w=s();if(w.length===0)return console.log(`${i.dim}No brain documents to undo${i.reset}`),!0;let k=w[0],{exec:E}=require("child_process"),{promisify:x}=require("util"),v=x(E);try{await v(`git checkout -- ".nex/brain/${k.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${i.green}Undone: restored ${k.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=s();if(p.length===0)console.log(`
|
|
675
|
+
${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
|
+
${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
|
+
`);else{console.log(`
|
|
678
|
+
${i.bold}${i.cyan}Brain: ${p.length} document(s)${i.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),w=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${i.cyan}${g.name}${i.reset}${i.dim}${w}${i.reset}`)}console.log(`
|
|
679
|
+
${i.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${i.reset}
|
|
680
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=Bo(),{getConversationMessages:a}=ne(),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([s(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:y}of u.applied){let w=y==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${w} ${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:y}of d.written){let w=y==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${w} ${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:s}=ne(),{getUsage:r}=ke(),{TOOL_DEFINITIONS:a}=Ie(),{listMemories:c}=Je(),l=s(),u=r(l,a),d=Xe(),f=Ye(),m=c();console.log(`
|
|
528
681
|
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
529
682
|
`);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(`
|
|
530
|
-
${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
|
|
531
|
-
${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
|
|
532
|
-
${i.bold}Session:${i.reset} ${
|
|
533
|
-
${i.bold}Quick Wins:${i.reset}`);for(let k of
|
|
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 E=[...m].sort((S,C)=>new Date(C.updatedAt)-new Date(S.updatedAt))[0],x=E?Math.round((Date.now()-new Date(E.updatedAt))/6e4):null,v=x!==null?x<60?`${x}m ago`:`${Math.round(x/60)}h ago`:"?";console.log(` ${i.dim}Latest update: ${v}${i.reset}`),m.length>30&&console.log(` ${i.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${i.reset}`)}console.log(`
|
|
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(k=>k.role==="user").length;console.log(`
|
|
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 y=[],w=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(w)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
686
|
+
${i.bold}Quick Wins:${i.reset}`);for(let k of y)console.log(` ${i.cyan}\u2192${i.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=Et(),{invalidateSystemPromptCache:d}=ne(),f=n.join(" ").trim();if(f==="status"){let m=s();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(`
|
|
534
687
|
${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}
|
|
535
688
|
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
536
689
|
${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}
|
|
537
|
-
${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:
|
|
538
|
-
${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:
|
|
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:s}=Et(),r=s();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
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:s,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=Et(),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} ${s()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:s}=sn(),r=s();console.log(`
|
|
539
692
|
${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(`
|
|
540
693
|
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
541
|
-
`),!0}case"/allow":{let{setPermission:
|
|
694
|
+
`),!0}case"/allow":{let{setPermission:s,savePermissions:r}=sn(),a=n.join(" ").trim();return a?(s(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:s,savePermissions:r}=sn(),a=n.join(" ").trim();return a?(s(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:s,commit:r,analyzeDiff:a,formatDiffSummary:c}=nt(),{confirm:l}=Ce();if(!s())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:s,formatDiffSummary:r}=nt();return s()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:s,getDiff:r}=nt(),{processInput:a}=ne(),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(!s())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):
|
|
542
695
|
|
|
543
696
|
\`\`\`diff
|
|
544
697
|
${f.substring(0,2e4)}
|
|
545
|
-
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:
|
|
698
|
+
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:r,createBranch:a}=nt();if(!s())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:s,connectAll:r,disconnectAll:a}=Tn(),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=s();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(`
|
|
546
699
|
${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(`
|
|
547
700
|
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
548
|
-
`),!0}case"/hooks":{let{listHooks:
|
|
549
|
-
${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:
|
|
701
|
+
`),!0}case"/hooks":{let{listHooks:s}=To(),r=s();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(`
|
|
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:s,enableSkill:r,disableSkill:a}=Ft(),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=s();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(`
|
|
550
703
|
${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(`
|
|
551
704
|
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
552
|
-
`),!0}case"/tasks":{let{renderTaskList:
|
|
553
|
-
`+
|
|
554
|
-
`),!0)}case"/undo":{let{undo:
|
|
705
|
+
`),!0}case"/tasks":{let{renderTaskList:s,clearTasks:r}=jn();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
706
|
+
`+s()+`
|
|
707
|
+
`),!0)}case"/undo":{let{undo:s,getUndoCount:r}=wt(),a=s();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:s,getRedoCount:r}=wt(),a=s();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:s,getUndoCount:r,getRedoCount:a}=wt(),c=s(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
555
708
|
${i.bold}File Change History${i.reset}
|
|
556
709
|
`);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(`
|
|
557
710
|
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
558
|
-
`),!0}case"/
|
|
559
|
-
${i.
|
|
560
|
-
`)
|
|
561
|
-
`)
|
|
562
|
-
`),!0
|
|
711
|
+
`),!0}case"/k8s":{let s=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:a}=require("util"),c=a(r),l=s||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
|
+
${i.bold}${i.cyan}Kubernetes Overview${i.reset}${l?i.dim+" (remote: "+l+")"+i.reset:""}
|
|
713
|
+
`);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
|
+
`).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
|
+
`),!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(w=>w.includes("Running")).length,p=m.filter(w=>w.includes("Pending")).length,g=m.filter(w=>w.includes("Failed")||w.includes("Error")||w.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}
|
|
717
|
+
`);let y=m.filter(w=>!w.includes("Running")&&!w.includes("<none>"));if(y.length>0){console.log(`${i.bold}${i.red}Unhealthy Pods:${i.reset}`);for(let w of y)console.log(` ${i.red}${w}${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
|
+
`)}catch(f){console.log(`${i.dim}Could not list pods: ${f.message}${i.reset}
|
|
719
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:r,sshExec:a}=kt(),c=s(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
720
|
+
${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
|
+
`),!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}=kt();console.log(`
|
|
723
|
+
${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
|
+
${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:s,sshExec:r}=kt(),{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=s(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
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:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${i.red}SSH error (${y.exitCode})${i.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${i.dim}(no containers)${i.reset}`):(console.log(` ${p}:`),g.split(`
|
|
727
|
+
`).forEach(y=>console.log(` ${i.dim}${y}${i.reset}`)))}catch(g){console.log(` ${p}: ${i.red}${g.message}${i.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=Ks(),r=s(),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}=Ie();console.log(`
|
|
728
|
+
${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
|
+
${i.dim}No deploy configs. Run /init to create .nex/deploy.json${i.reset}
|
|
730
|
+
`),!0;console.log(`
|
|
731
|
+
${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
|
+
${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:s,runDeployWizard:r,setWizardRL:a}=Kc();return a(e),n[0]==="deploy"?await r():await s(),!0}case"/exit":case"/quit":console.log(`
|
|
734
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return og(t)||console.log(`${i.red}Unknown command: ${o}. Type /help${i.reset}`),!0}}var Yo=1e3;function Xo(){return Me.join(process.cwd(),".nex","repl_history")}function ll(){try{let t=Xo();if(Ve.existsSync(t))return Ve.readFileSync(t,"utf-8").split(`
|
|
735
|
+
`).filter(Boolean).slice(-Yo)}catch{}return[]}function as(t){try{let e=Xo(),o=Me.dirname(e);Ve.existsSync(o)||Ve.mkdirSync(o,{recursive:!0}),Ve.appendFileSync(e,t+`
|
|
736
|
+
`)}catch{}}function Se(){let{isPlanMode:t,getAutonomyLevel:e}=Et(),o=[];t()&&o.push("plan");let n=e();n!=="interactive"&&o.push(n);let s=Ye(),r=Xe();return o.push(`${s}:${r.id}`),`${o.length>0?`${i.dim}[${o.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var Vo="\x1B[200~",Qo="\x1B[201~";function ag(t){return typeof t=="string"&&t.includes(Vo)}function cg(t){return typeof t=="string"&&t.includes(Qo)}function ln(t){return typeof t!="string"?t:t.split(Vo).join("").split(Qo).join("")}async function lg(){if(!ng("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:o}=require("util");return await o(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),Zc("local:llama3"),!0}catch{return!1}}async function ug(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:o}=ne();t(nl);let s=Ko().some(N=>N.configured),r=(async()=>{sg();let N=Xe(),M=Ye();return{model:N,providerName:M}})(),a=(async()=>s?!0:await lg()?(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}
|
|
737
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=Xc();return await N()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!s&&(console.error(`
|
|
563
738
|
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
564
|
-
`),process.exit(1)),
|
|
565
|
-
`),await
|
|
566
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM"
|
|
567
|
-
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(
|
|
739
|
+
`),process.exit(1)),Zh(`${l.providerName}:${l.model.id}`,cs,{yolo:tl()}),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}
|
|
740
|
+
`),await el(cs);let f=ll(),m=Qh.createInterface({input:process.stdin,output:process.stdout,prompt:Se(),completer:rl,history:f,historySize:Yo});rg(m);let h=!1,p=0,g=!1,y=null;function w(){Qc(),Vc(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
741
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",w),process.on("exit",()=>{Qc()}),m.on("SIGINT",()=>{if(Vc(),h){if(p++,p>=2){w();return}Be&&Be.abort();let{cancelPendingAskUser:N}=Ie();N(),console.log(`
|
|
742
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(Se()),m.prompt();return}g?w():(g=!0,process.stdout.write(`
|
|
568
743
|
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
569
|
-
`),m.setPrompt(
|
|
570
|
-
`).trim();if(
|
|
571
|
-
`),
|
|
572
|
-
${i.dim} ${D}${i.reset}`),console.log(`${i.dim} \u23BF ${
|
|
573
|
-
`)),
|
|
574
|
-
`)),!0}if(
|
|
575
|
-
`)),
|
|
576
|
-
`)),!0}return
|
|
577
|
-
\x1B[2K ${i.cyan}${
|
|
578
|
-
\x1B[2K ${i.dim}\u2026 +${
|
|
579
|
-
`)}return}if(
|
|
580
|
-
`).trim();if(
|
|
581
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
582
|
-
`).trim();if(
|
|
583
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
584
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
585
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)})}
|
|
744
|
+
`),m.setPrompt(Se()),m.prompt(),y&&clearTimeout(y),y=setTimeout(()=>{g=!1,y=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||w()});let k=!1,E=[],x=null;function v(){let N=E.join(`
|
|
745
|
+
`).trim();if(E=[],k=!1,!N)return!0;x=N;let M=N.split(`
|
|
746
|
+
`),F=M.length,j=M[0].length>80?M[0].substring(0,77)+"...":M[0],D=F>1?`[Pasted content \u2014 ${F} lines]`:"[Pasted content]";return console.log(`
|
|
747
|
+
${i.dim} ${D}${i.reset}`),console.log(`${i.dim} \u23BF ${j}${i.reset}`),F>1&&console.log(`${i.dim} \u23BF \u2026 +${F-1} more lines${i.reset}`),console.log(`${i.dim} Press Enter to send${i.reset}`),!0}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(M,...F){if(M!=="data")return N.call(process.stdin,M,...F);let j=F[0];if(Buffer.isBuffer(j)&&(j=j.toString("utf8")),typeof j!="string")return N.call(process.stdin,M,...F);let D=j.includes(Vo),Y=j.includes(Qo);if(D&&Y){let B=ln(j);return B&&E.push(...B.split(`
|
|
748
|
+
`)),v()}if(D){k=!0,E=[];let B=ln(j);return B&&E.push(...B.split(`
|
|
749
|
+
`)),!0}if(Y){let B=ln(j);return B&&E.push(...B.split(`
|
|
750
|
+
`)),v()}if(k){let B=ln(j);return B&&E.push(...B.split(`
|
|
751
|
+
`)),!0}return N.call(process.stdin,M,...F)}}let S=0;function C(){if(S>0){let N="";for(let M=0;M<S;M++)N+="\x1B[1B\x1B[2K";N+=`\x1B[${S}A`,process.stdout.write(N),S=0}}function A(N){let M=[...ls,...Jo()].filter(ce=>ce.cmd.startsWith(N));if(!M.length||M.length===1&&M[0].cmd===N)return;let F=10,j=M.slice(0,F),D=Math.max(...j.map(ce=>ce.cmd.length)),Y="";for(let{cmd:ce,desc:We}of j){let de=ce.substring(0,N.length),Ee=ce.substring(N.length),un=" ".repeat(Math.max(0,D-ce.length+2));Y+=`
|
|
752
|
+
\x1B[2K ${i.cyan}${de}${i.reset}${i.dim}${Ee}${un}${We}${i.reset}`}S=j.length,M.length>F&&(Y+=`
|
|
753
|
+
\x1B[2K ${i.dim}\u2026 +${M.length-F} more${i.reset}`,S++);let B=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;Y+=`\x1B[${S}A\x1B[${B+m.cursor+1}G`,process.stdout.write(Y)}process.stdin.isTTY&&process.stdin.on("keypress",(N,M)=>{C(),!(M&&(M.name==="tab"||M.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&A(m.line)})});let I=null,L=`${i.dim}...${i.reset} `;m.setPrompt(Se()),m.prompt(),m.on("line",async N=>{if(C(),h){let D=(x!==null?x:N).trim();if(x=null,D){let{injectMidRunNote:Y}=ne();Y(D),process.stdout.write(`${i.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${i.reset}
|
|
754
|
+
`)}return}if(x!==null&&(N=x,x=null),I!==null){if(I._mode==="triple"){if(N.trim()==='"""'){let D=I.join(`
|
|
755
|
+
`).trim();if(I=null,D){as(D.replace(/\n/g,"\\n")),h=!0,p=0,g=!1,y&&(clearTimeout(y),y=null),Be=new AbortController;try{await o(D)}catch(B){if(!Be?.signal?.aborted){let ce=B.message?.split(`
|
|
756
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${ce}${i.reset}`)}}h=!1;let Y=F();Y>0&&process.stdout.write(`${i.gray}[${Y} messages] ${i.reset}`)}m.setPrompt(Se()),m.prompt();return}I.push(N),m.setPrompt(L),m.prompt();return}if(N.endsWith("\\"))I.push(N.slice(0,-1));else{I.push(N);let D=I.join(`
|
|
757
|
+
`).trim();if(I=null,D){as(D.replace(/\n/g,"\\n")),h=!0,p=0,g=!1,y&&(clearTimeout(y),y=null),Be=new AbortController;try{await o(D)}catch(ce){if(!Be?.signal?.aborted){let We=ce.message?.split(`
|
|
758
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${We}${i.reset}`)}}let{getConversationLength:Y}=ne();h=!1;let B=Y();B>0&&process.stdout.write(`${i.gray}[${B} messages] ${i.reset}`)}m.setPrompt(Se()),m.prompt();return}m.setPrompt(L),m.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let D=N.trim().substring(3);I=D?[D]:[],I._mode="triple",m.setPrompt(L),m.prompt();return}if(N.endsWith("\\")){I=[N.slice(0,-1)],I._mode="backslash",m.setPrompt(L),m.prompt();return}let M=N.trim();if(!M){m.setPrompt(Se()),m.prompt();return}if(as(M),M==="/"){sl(),m.setPrompt(Se()),m.prompt();return}if(M.startsWith("/")){await cl(M,m),m.setPrompt(Se()),m.prompt();return}h=!0,p=0,g=!1,y&&(clearTimeout(y),y=null),Be=new AbortController;try{await o(M)}catch(D){if(!Be?.signal?.aborted){let Y=D.message?.split(`
|
|
759
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${Y}${i.reset}`)}}h=!1;let{getConversationLength:F}=ne(),j=F();j>0&&process.stdout.write(`${i.gray}[${j} messages] ${i.reset}`),m.setPrompt(Se()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
760
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}ul.exports={startREPL:ug,getPrompt:Se,loadHistory:ll,appendHistory:as,getHistoryPath:Xo,HISTORY_MAX:Yo,showCommandList:sl,completer:rl,completeFilePath:ol,handleSlashCommand:cl,showProviders:Go,showHelp:il,renderBar:al,hasPasteStart:ag,hasPasteEnd:cg,stripPasteSequences:ln,getAbortSignal:nl}});var pl=require("path");require("dotenv").config({path:pl.join(__dirname,"..",".env")});require("dotenv").config();var Q=process.argv.slice(2);(Q.includes("--help")||Q.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
586
761
|
|
|
587
762
|
Options:
|
|
588
763
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -595,4 +770,4 @@ Options:
|
|
|
595
770
|
--json Output result as JSON (for CI parsing)
|
|
596
771
|
-h, --help Show this help
|
|
597
772
|
-v, --version Show version
|
|
598
|
-
`),process.exit(0));if(
|
|
773
|
+
`),process.exit(0));if(Q.includes("-v")||Q.includes("--version")){let t=dn();console.log(t.version),process.exit(0)}var dg=Q.includes("--yolo")||Q.includes("-yolo");if(dg){let{setAutoConfirm:t}=Ce();t(!0)}var Zo=Q.indexOf("--model");if(Zo!==-1&&Q[Zo+1]){let{setActiveModel:t}=ie();t(Q[Zo+1])}var er=Q.indexOf("--max-turns");if(er!==-1&&Q[er+1]){let t=parseInt(Q[er+1],10);if(t>0){let{setMaxIterations:e}=ne();e(t)}}else try{let t=require("fs"),e=pl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let o=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(o.maxIterations,10);if(n>0){let{setMaxIterations:s}=ne();s(n)}}}catch{}function tr(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let o=()=>{try{e.kill()}catch{}};process.on("exit",o),process.on("SIGINT",o),process.on("SIGTERM",o)}catch{}}function fl(t){if(Q.includes("--auto")){let{setAutoConfirm:s}=Ce();s(!0)}if(!Q.includes("--model")){let{setActiveModel:s}=ie(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";s(r)}let{processInput:o,getConversationMessages:n}=ne();o(t).then(()=>{if(Q.includes("--json")){let r=n().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(s=>{Q.includes("--json")?console.log(JSON.stringify({success:!1,error:s.message})):console.error(s.message),process.exit(1)})}var ml=Q.indexOf("--prompt-file");if(ml!==-1){let t=Q[ml+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),o;try{o=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(o||(console.error("--prompt-file: file is empty"),process.exit(1)),Q.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}tr(),fl(o)}else{let t=Q.indexOf("--task");if(t!==-1){let e=Q[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),tr(),fl(e)}else{tr();let{startREPL:e}=dl();e()}}
|