nex-code 0.3.27 → 0.3.28
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 +1 -1
- package/dist/nex-code.js +386 -387
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,134 +1,134 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $n=N((Pg,vl)=>{vl.exports={name:"nex-code",version:"0.3.28",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 $r=N((Lg,gr)=>{var M={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},mr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],pr=["\u273D","\u2726","\u2727","\u2726"],$s=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=mr[this.frame%mr.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),r=n%60;s=` ${M.dim}${o}m ${String(r).padStart(2,"0")}s${M.reset}`}else n>=1&&(s=` ${M.dim}${n}s${M.reset}`)}process.stderr.write(`\x1B[2K\r${M.cyan}${e}${M.reset} ${M.dim}${this.text}${M.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),80))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},hr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ys=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=hr[this.frame%hr.length],s=this._formatElapsed(),n=s?` ${M.dim}${s}${M.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let i,c;switch(this.statuses[r]){case"done":i=`${M.green}\u2713${M.reset}`,c=M.dim;break;case"error":i=`${M.red}\u2717${M.reset}`,c=M.dim;break;default:i=`${M.cyan}${e}${M.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${i} ${c}${this.labels[r]}${M.reset}${l}
|
|
3
3
|
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
5
|
-
`}process.stderr.write(n)}},yn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},wn={done:
|
|
6
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,
|
|
7
|
-
`}
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${M.dim}${e}${M.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${M.green}\u2713${M.reset}`;break;case"error":r=`${M.red}\u2717${M.reset}`;break;default:r=`${M.yellow}\u25CB${M.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${M.dim}${this.labels[o]}${M.reset}${i}
|
|
5
|
+
`}process.stderr.write(n)}},yn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},wn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},Je=null,ws=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=pr[this.frame%pr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${M.dim}(${o})${M.reset}`:"",i=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,m=wn[l.status]||wn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${m}${d}${M.reset} ${f}
|
|
7
|
+
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Je=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Je===this&&(Je=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
9
9
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,
|
|
12
|
-
`}process.stderr.write(
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${r})${M.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,m=wn[l.status]||wn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${m}${d}${M.reset} ${M.dim}${f}${M.reset}
|
|
12
|
+
`}process.stderr.write(i)}};function Sl(t){Je=t}function El(){return Je}function Cl(){Je&&(Je.stop(),Je=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}gr.exports={C:M,Spinner:$s,MultiProgress:ys,TaskProgress:ws,setActiveTaskProgress:Sl,getActiveTaskProgress:El,cleanupTerminal:Cl}});var wr=N((Ig,yr)=>{var G={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Tl={read_file:"Read file",write_file:"Write file",edit_file:"Edit file",patch_file:"Patch file",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"},Rl={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",patch_file:"Patching file",list_directory:"Listing directory",bash:"Running command",grep:"Searching code",search_files:"Searching files",glob:"Finding files",web_fetch:"Fetching content",web_search:"Searching the web",git_status:"Checking repository",git_diff:"Analyzing changes",git_log:"Reading git history",git_commit:"Creating commit",git_push:"Pushing changes",git_pull:"Pulling changes",git_branch:"Managing branches",git_stash:"Stashing changes",task_list:"Managing tasks",spawn_agents:"Delegating to agents",ask_user:"Awaiting input",switch_model:"Switching model",gh_run_list:"GitHub Actions",gh_run_view:"GitHub Actions",gh_workflow_trigger:"Triggering workflow",browser_open:"Opening browser",browser_screenshot:"Taking screenshot",browser_click:"Clicking element",browser_fill:"Filling form",ssh_exec:"Running on server",ssh_upload:"Uploading to server",ssh_download:"Downloading from server",service_manage:"Managing service",service_logs:"Reading service logs",container_list:"Listing containers",container_logs:"Reading container logs",container_exec:"Running in container",brain_write:"Saving to memory",deploy:"Deploying"};function Al(t,e){let s=(t||[]).filter(r=>r&&r.canExecute!==!1);if(s.length===0)return`${G.cyan} \u25C6 Step ${e}${G.reset}`;let n=[...new Set(s.map(r=>Rl[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let i=s[0].args||{},c=` ${G.reset}${G.dim}`;i.path?o+=`${c}${i.path.split("/").pop()}`:i.command?o+=`${c}${String(i.command).substring(0,50)}`:i.query?o+=`${c}${String(i.query).substring(0,50)}`:i.pattern&&(o+=`${c}${String(i.pattern).substring(0,50)}`)}else n.length===1?o=`${n[0]} (${s.length})`:n.length<=3?o=n.join(" \xB7 "):o=`${s.length} actions`;return`${G.cyan} \u25C6 ${o}${G.reset}`}function Ol(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Tl[t]||t.replace(/_/g," "),o=s?` ${G.dim}${s}${G.reset}`:"";return`${G.cyan} \u23FA${G.reset} ${G.bold}${n}${G.reset}${o}`}function Ml(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${G.dim} \u23BF ${G.reset}`,i=" ",c=n.map((l,u)=>`${u===0?r:i}${G.green}${l}${G.reset}`).join(`
|
|
14
14
|
`);return o>0&&(c+=`
|
|
15
|
-
${
|
|
15
|
+
${G.gray} \u2026+${o} more lines${G.reset}`),c}function Nl(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 Pl(t,e,s,n){let o=String(s||"");if(n){let i=o.split(`
|
|
16
16
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
-
${
|
|
18
|
-
`).filter(Boolean),c=
|
|
19
|
-
`).length;r=`Wrote ${
|
|
20
|
-
`).filter(
|
|
21
|
-
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let
|
|
22
|
-
`).filter(Boolean).length;r=`${
|
|
23
|
-
`).filter(Boolean).length;r=`${
|
|
24
|
-
`).filter(Boolean).length;r=`${
|
|
25
|
-
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=
|
|
26
|
-
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=
|
|
27
|
-
|
|
28
|
-
`).filter(Boolean).length;r=`${
|
|
29
|
-
`),u=s.yolo?` ${n}${
|
|
17
|
+
${G.dim}${c[1].substring(0,100)}${G.reset}`:"";return` ${G.red}\u23BF ${i}${G.reset}${l}`}let r;switch(t){case"read_file":{let i=o.split(`
|
|
18
|
+
`).filter(Boolean),c=i.length,l=i[i.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let i=(e.content||"").split(`
|
|
19
|
+
`).length;r=`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let i=(e.patches||[]).length;r=`Applied ${i} patch${i!==1?"es":""}`;break}case"bash":{let i=o.match(/^EXIT (\d+)/);if(i){let c=i[1],l=o.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=o.split(`
|
|
20
|
+
`).filter(m=>m&&!m.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=o.split(`
|
|
21
|
+
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let i=o.split(`
|
|
22
|
+
`).filter(Boolean).length;r=`${i} match${i!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let i=o.split(`
|
|
23
|
+
`).filter(Boolean).length;r=`${i} file${i!==1?"s":""} found`}break}case"list_directory":{let i=o==="(empty)"?0:o.split(`
|
|
24
|
+
`).filter(Boolean).length;r=`${i} entr${i!==1?"ies":"y"}`;break}case"git_status":{let i=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
25
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=i?`${i[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let i=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=i||c?`+${i} \u2212${c} lines`:"No diff";break}case"git_log":{let i=o.split(`
|
|
26
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=i>0?`${i} commit${i!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let i=o.split(`
|
|
27
|
+
|
|
28
|
+
`).filter(Boolean).length;r=`${i} result${i!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let i=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${i} done, ${c} failed`:`${i} agent${i!==1?"s":""} done`;break}case"switch_model":{let i=o.match(/Switched to (.+)/);r=i?`\u2192 ${i[1]}`:"Done";break}default:r="Done"}return` ${G.dim}\u23BF ${r}${G.reset}`}yr.exports={C:G,formatToolCall:Ol,formatResult:Ml,getToolSpinnerText:Nl,formatToolSummary:Pl,formatSectionHeader:Al}});var oe=N((qg,br)=>{var yt={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 Ll(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+yt.reset}function Il(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function ql(t,e,s={}){let n=yt.bold,o=yt.dim,r=yt.reset,i=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=i.map((d,m)=>{let f=m/(i.length-1||1);return Ll(d,Il(c,f))}).join(`
|
|
29
|
+
`),u=s.yolo?` ${n}${yt.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
31
|
${o}Agentic Coding CLI v${$n().version}${r}
|
|
32
32
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),
|
|
35
|
-
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),
|
|
33
|
+
`)}var{Spinner:jl,MultiProgress:Dl,TaskProgress:Fl,setActiveTaskProgress:Ul,getActiveTaskProgress:Wl,cleanupTerminal:Bl}=$r(),{formatToolCall:Hl,formatResult:Gl,getToolSpinnerText:zl,formatToolSummary:Kl,formatSectionHeader:Jl}=wr();br.exports={C:yt,banner:ql,Spinner:jl,MultiProgress:Dl,TaskProgress:Fl,setActiveTaskProgress:Ul,getActiveTaskProgress:Wl,cleanupTerminal:Bl,formatToolCall:Hl,formatResult:Gl,getToolSpinnerText:zl,formatToolSummary:Kl,formatSectionHeader:Jl}});var Me=N((jg,Er)=>{var Yl=require("readline"),{C:bn}=oe(),xr=[/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/],bs=[/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 _r(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):bs.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:bs.some(c=>c.test(i))};return n.every(o)}var _s=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],kr=[/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/],vr=[..._s,...kr],ks=!1,xs=null;function Xl(t){ks=t}function Vl(){return ks}function Ql(t){xs=t}function Zl(t){for(let e of xr)if(e.test(t))return e;return null}function eu(t){if(/ssh\s/.test(t)&&_r(t))return!1;for(let e of vr)if(e.test(t))return!0;return!1}function tu(t){for(let e of _s)if(e.test(t))return!0;return!1}function nu(t,e={}){if(ks)return Promise.resolve(!0);let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Sr(e.toolName),n(!0)):n(i!=="n")};if(xs)xs.question(`${bn.yellow}${t} ${s}${bn.reset}`,o);else{let r=Yl.createInterface({input:process.stdin,output:process.stdout});r.question(`${bn.yellow}${t} ${s}${bn.reset}`,i=>{r.close(),o(i)})}})}var Sr=()=>{};function su(t){Sr=t}Er.exports={FORBIDDEN_PATTERNS:xr,SSH_SAFE_PATTERNS:bs,isSSHReadOnly:_r,DANGEROUS_BASH:vr,CRITICAL_BASH:_s,NOTABLE_BASH:kr,isForbidden:Zl,isDangerous:eu,isCritical:tu,confirm:nu,setAutoConfirm:Xl,getAutoConfirm:Vl,setReadlineInterface:Ql,setAllowAlwaysHandler:su}});var wt=N((Dg,Cr)=>{var vs=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Cr.exports={BaseProvider:vs}});var Ar=N((Fg,Rr)=>{var xn=require("axios"),ou=require("http"),ru=require("https"),{BaseProvider:iu}=wt(),_n=new ou.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),kn=new ru.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Tr={"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}},Ss=class extends iu{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Tr,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){xn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await xn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
34
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=await xn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await xn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:_n,httpsAgent:kn})}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 m="",f=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let g=h.split(`
|
|
35
|
+
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),m+=$.message.content),$.message?.tool_calls&&(f=f.concat($.message.tool_calls)),$.done){u({content:m,tool_calls:this._normalizeToolCalls(f)});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),m+=p.message.content),p.message?.tool_calls&&(f=f.concat(p.message.tool_calls))}catch{}u({content:m,tool_calls:this._normalizeToolCalls(f)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Rr.exports={OllamaProvider:Ss,OLLAMA_MODELS:Tr}});var Ir=N((Ug,Lr)=>{var{callChat:au}=ge(),{estimateTokens:Es}=Re(),Or=process.env.NEX_COMPACTION!=="false",Mr=6,Nr=500,cu=`Summarize this conversation history concisely. Focus on:
|
|
36
36
|
- What files were read, created, or modified
|
|
37
37
|
- Key decisions made and their rationale
|
|
38
38
|
- Current state of the task (what's done, what's pending)
|
|
39
39
|
- Any errors encountered and how they were resolved
|
|
40
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
41
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function
|
|
40
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function lu(t){if(!Or||t.length<Mr)return null;let e=[{role:"system",content:cu},{role:"user",content:Pr(t)}];try{let n=((await au(e,[],{temperature:0,maxTokens:Nr})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+Es(c.content||"")+(c.tool_calls?Es(JSON.stringify(c.tool_calls)):0),0),r=Es(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function Pr(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
|
|
42
42
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
43
43
|
|
|
44
|
-
`)}
|
|
44
|
+
`)}Lr.exports={compactMessages:lu,formatMessagesForSummary:Pr,COMPACTION_ENABLED:Or,COMPACTION_MIN_MESSAGES:Mr,COMPACTION_SUMMARY_BUDGET:Nr}});var Re=N((Wg,Br)=>{function jr(){return ge().getActiveModel()}var uu={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Dt=new Map,qr=1e3,Cs=new WeakMap,Ft=null;function du(){if(Ft!==null)return Ft;try{let e=jr()?.provider||"ollama";return Ft=uu[e]||4,Ft}catch{return 4}}function fu(){Ft=null}function ot(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,s=Dt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/du());if(Dt.size>=qr){let o=qr>>1,r=Dt.keys();for(let i=0;i<o;i++)Dt.delete(r.next().value)}return Dt.set(e,n),n}function mu(t){if(Cs.has(t))return Cs.get(t);let e=JSON.stringify(t);return Cs.set(t,e),e}function bt(t){let s=4;if(t.content&&(s+=ot(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=ot(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=ot(o):o&&(s+=ot(JSON.stringify(o)))}return s}function Ae(t){let e=0;for(let s of t)e+=bt(s);return e}function pu(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=bt(e[r]);return o}function vn(t){return!t||t.length===0?0:ot(JSON.stringify(t))}function Sn(){return jr()?.contextWindow||32768}function hu(t,e){let s=Ae(t),n=vn(e),o=s+n,r=Sn(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let m=bt(d);d.role==="system"?c+=m:d.role==="tool"?u+=m:l+=m}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Dr=.75,Fr=.1,Ur=10,gu=200,$u=500;function Wr(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
45
45
|
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),w=t.substring(0,p),$=t.substring(t.length-g);return w+`
|
|
46
46
|
...(${t.length} chars total)...
|
|
47
|
-
`+$}let r=Math.floor(o.length*.4),
|
|
47
|
+
`+$}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<r&&l<u;p++)c.push(o[p]),l+=o[p].length+1;let d=[],m=0,f=Math.floor(n*.4);for(let p=o.length-1;p>=o.length-i&&m<f;p--)d.push(o[p]),m+=o[p].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
|
|
48
48
|
`)+`
|
|
49
49
|
...(${h} lines omitted, ${o.length} total)...
|
|
50
50
|
`+d.join(`
|
|
51
|
-
`)}function
|
|
52
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function
|
|
53
|
-
`),r=Math.floor(n*.6),
|
|
51
|
+
`)}function Ut(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:$u,n=e==="aggressive"?50:e==="medium"?100:gu;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Wr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
52
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function yu(t,e,s={}){let n=s.threshold??Dr,o=s.safetyMargin??Fr,r=s.keepRecent??Ur,i=Sn(),c=vn(e),l=Math.floor(i*(n-o)),u=l-c,d=Ae(t),m=d+c;if(m<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let f=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),w=t.slice(p,g),$=t.slice(g),x=w.filter(S=>!S._compacted);if(x.length>=6)try{let{compactMessages:S}=Ir(),T=await S(x);if(T){let I=[...w.filter(ne=>ne._compacted),T.message],V=st(h,I,$),D=Ae(V);if(D+c<=l)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:f-D};w=I}}catch(S){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",S.message)}let O=(m-l)/l,k=w.map(S=>Ut(S,"light")),v=st(h,k,$),C=Ae(v);if(C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-C};if(k=w.map(S=>Ut(S,"medium")),v=st(h,k,$),C=Ae(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-C};if(k=w.map(S=>Ut(S,"aggressive")),v=st(h,k,$),C=Ae(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-C};for(;k.length>0&&C>u;){let S=k.shift();C-=bt(S)}return v=st(h,k,$),C=Ae(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-C}}function st(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function wu(t,e){if(!t)return"";if(ot(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
|
+
`),r=Math.floor(n*.6),i=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
54
|
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
|
-
`:"")+u;if(p.length>
|
|
55
|
+
`:"")+u;if(p.length>i)break;u=p,d++}let f=`
|
|
56
56
|
|
|
57
57
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
58
|
|
|
59
|
-
`;return c+
|
|
60
|
-
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let
|
|
61
|
-
|
|
62
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let
|
|
63
|
-
`);O=
|
|
64
|
-
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let
|
|
65
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await En.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),
|
|
66
|
-
`);
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
59
|
+
`;return c+f+u}var bu=6;function xu(t,e){let s=Sn(),n=vn(e),o=Math.floor(s*.5)-n,r=Ae(t),i=null,c=0;t.length>0&&t[0].role==="system"&&(i=t[0],c=1);let l=Math.max(c,t.length-bu),u=t.slice(c,l),d=t.slice(l),m=u.map(p=>Ut(p,"aggressive")),f=st(i,m,d),h=Ae(f);for(;m.length>0&&h>o;){let p=m.shift();h-=bt(p)}return f=st(i,m,d),h=Ae(f),{messages:f,tokensRemoved:r-h}}Br.exports={estimateTokens:ot,estimateMessageTokens:bt,estimateMessagesTokens:Ae,estimateDeltaTokens:pu,estimateToolsTokens:vn,serializeMessage:mu,getContextWindow:Sn,getUsage:hu,compressMessage:Ut,compressToolResult:Wr,fitToContext:yu,forceCompress:xu,truncateFileContent:wu,invalidateTokenRatioCache:fu,COMPRESSION_THRESHOLD:Dr,SAFETY_MARGIN:Fr,KEEP_RECENT:Ur}});var Kr=N((Hg,zr)=>{var Hr=require("axios"),{BaseProvider:_u}=wt(),{serializeMessage:Bg}=Re(),Gr={"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}},Ts=class extends _u{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Gr,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Hr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Hr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let f=m.response?.data?.error?.message||m.message;throw new Error(`API Error: ${f}`)}return new Promise((m,f)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{g+=w.toString();let $=g.split(`
|
|
60
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){m({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let T=S.index??0;p[T]||(p[T]={id:S.id||"",name:"",arguments:""}),S.id&&(p[T].id=S.id),S.function?.name&&(p[T].name+=S.function.name),S.function?.arguments&&(p[T].arguments+=S.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||f(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{m({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};zr.exports={OpenAIProvider:Ts,OPENAI_MODELS:Gr}});var Vr=N((zg,Xr)=>{var Jr=require("axios"),{BaseProvider:ku}=wt(),{serializeMessage:Gg}=Re(),Yr={"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}},vu="2023-06-01",Rs=class extends ku{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Yr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||vu}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
61
|
+
|
|
62
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=n.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let m=this.formatTools(s);m.length>0&&(d.tools=m);let f=await Jr.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=n.maxTokens||i?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),m={model:r,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(m.system=d);let f=this.formatTools(s);f.length>0&&(m.tools=f);let h;try{h=await Jr.post(`${this.baseUrl}/messages`,m,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let w="",$=[],x=-1,O="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{O+=k.toString();let v=O.split(`
|
|
63
|
+
`);O=v.pop()||"";for(let C of v){let S=C.trim();if(S.startsWith("data: ")){let T=S.slice(6),F;try{F=JSON.parse(T)}catch{continue}switch(F.type){case"content_block_start":{let I=F.content_block;I?.type==="tool_use"&&(x=$.length,$.push({id:I.id,name:I.name,inputJson:""}));break}case"content_block_delta":{let I=F.delta;I?.type==="text_delta"&&I.text&&(l(I.text),w+=I.text),I?.type==="input_json_delta"&&I.partial_json!==void 0&&x>=0&&($[x].inputJson+=I.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:w,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:w,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};Xr.exports={AnthropicProvider:Rs,ANTHROPIC_MODELS:Yr}});var ti=N((Jg,ei)=>{var Qr=require("axios"),{BaseProvider:Su}=wt(),{serializeMessage:Kg}=Re(),Zr={"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}},As=class extends Su{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Zr,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Qr.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Qr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let f=m.response?.data?.error?.message||m.message;throw new Error(`API Error: ${f}`)}return new Promise((m,f)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{g+=w.toString();let $=g.split(`
|
|
64
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){m({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let T=S.index??0;p[T]||(p[T]={id:S.id||"",name:"",arguments:""}),S.id&&(p[T].id=S.id),S.function?.name&&(p[T].name+=S.function.name),S.function?.arguments&&(p[T].arguments+=S.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||f(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{m({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ei.exports={GeminiProvider:As,GEMINI_MODELS:Zr}});var oi=N((Yg,si)=>{var En=require("axios"),{BaseProvider:Eu}=wt(),ni="http://localhost:11434",Os=class extends Eu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ni,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await En.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let c=await En.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
65
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await En.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i;try{i=await En.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],m="";n.signal&&n.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",f=>{m+=f.toString();let h=m.split(`
|
|
66
|
+
`);m=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",f=>{n.signal?.aborted||l(new Error(`Stream error: ${f.message}`))}),i.data.on("end",()=>{if(m.trim())try{let f=JSON.parse(m);f.message?.content&&(r(f.message.content),u+=f.message.content),f.message?.tool_calls&&(d=d.concat(f.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};si.exports={LocalProvider:Os,DEFAULT_LOCAL_URL:ni}});var xt=N((Xg,di)=>{var rt=require("fs"),Ms=require("path"),ri={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Cn=[],Ye={};function Cu(t,e,s,n){if(Cn.push({provider:t,model:e,input:s,output:n}),Ye[t]!==void 0){let o=li(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
67
|
+
`)}}function Ns(t,e){let s=ri[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ii(t){let e=Ns(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ai(){let t={};for(let r of Cn){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:ii(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Tu(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=ai();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
68
|
+
`)}function Ru(t,e,s,n){let o=Ns(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Au(){Cn=[]}function Ou(t,e){Ye[t]=e}function Mu(t){delete Ye[t]}function Nu(){return{...Ye}}function ci(t){let e=0;for(let s of Cn)s.provider===t&&(e+=ii(s));return e}function li(t){let e=ci(t),s=Ye[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function ui(){let t=Ms.join(process.cwd(),".nex","config.json");if(rt.existsSync(t))try{let e=JSON.parse(rt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Ye={...e.costLimits})}catch{}}function Pu(){let t=Ms.join(process.cwd(),".nex"),e=Ms.join(t,"config.json"),s={};if(rt.existsSync(e))try{s=JSON.parse(rt.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Ye,rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0}),rt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Lu(){Ye={}}ui();di.exports={PRICING:ri,trackUsage:Cu,getSessionCosts:ai,formatCosts:Tu,formatCostHint:Ru,resetCosts:Au,getPricing:Ns,setCostLimit:Ou,removeCostLimit:Mu,getCostLimits:Nu,getProviderSpend:ci,checkBudget:li,loadCostLimits:ui,saveCostLimits:Pu,resetCostLimits:Lu}});var Tn=N((Vg,fi)=>{var Wt=ge(),Iu={"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 qu(){return Wt.getActiveModel()}function ju(t){return Wt.setActiveModel(t)}function Du(){return Wt.getModelNames()}function Fu(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Uu(t,e){let{C:s}=oe(),{Spinner:n}=oe(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await Wt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
69
|
+
`),c}catch(c){throw o.stop(),c}}async function Wu(t,e){return Wt.callChat(t,e)}fi.exports={MODELS:Iu,getActiveModel:qu,setActiveModel:ju,getModelNames:Du,callOllamaStream:Uu,callOllama:Wu,parseToolArgs:Fu}});var hi=N((Qg,pi)=>{var Rn=require("path"),{C:b}=oe(),{confirm:Bu,getAutoConfirm:Hu}=Me(),mi=2e3;function Bt(t,e){let s=t.split(`
|
|
70
70
|
`),n=e.split(`
|
|
71
|
-
`),o=[],r=s.length,
|
|
72
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=
|
|
73
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=
|
|
71
|
+
`),o=[],r=s.length,i=n.length;if(r>mi||i>mi){for(let m of s)o.push({type:"remove",line:m});for(let m of n)o.push({type:"add",line:m});return o}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let m=1;m<=r;m++)for(let f=1;f<=i;f++)s[m-1]===n[f-1]?c[m][f]=c[m-1][f-1]+1:c[m][f]=Math.max(c[m-1][f],c[m][f-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===n[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function Gu(t,e,s,n=3){console.log(`
|
|
72
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Bt(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${b.gray} (no changes)${b.reset}`);return}let i=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=i;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${b.red} - ${u.line}${b.reset}`);break;case"add":console.log(`${b.green} + ${u.line}${b.reset}`);break;default:console.log(`${b.gray} ${u.line}${b.reset}`)}}c<o.length&&console.log(`${b.gray} ...${b.reset}`),console.log()}function zu(t,e,s){console.log(`
|
|
73
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Bt(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${b.gray} ...(${o-r} more changes)${b.reset}`);break}switch(i.type){case"remove":console.log(`${b.red} - ${i.line}${b.reset}`),r++;break;case"add":console.log(`${b.green} + ${i.line}${b.reset}`),r++;break;default:r>0&&console.log(`${b.gray} ${i.line}${b.reset}`)}}console.log()}function Ku(t,e){console.log(`
|
|
74
74
|
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
75
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function
|
|
76
|
-
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let
|
|
77
|
-
`)}function
|
|
78
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),
|
|
79
|
-
`);return}let h=[];if(
|
|
75
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function Ju(t){return Hu()?!0:Bu(` ${t}?`)}function Yu(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
76
|
+
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let i=Bt(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let w=0;w<g;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${b.gray}(no changes)${b.reset}`);return}let d=Math.max(0,u[0]-2),m=Math.min(c.length,u[u.length-1]+3),f=(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<m;h++){let p=c[h];if(p.type==="same")console.log(` ${b.gray}${f(p.left,r)}${b.reset}\u2502${b.gray}${f(p.right,r)}${b.reset}`);else{let g=p.left?`${b.red}${f(p.left,r)}${b.reset}`:`${f("",r)}`,w=p.right?`${b.green}${f(p.right,r)}${b.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${w}`)}}m<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 Xu(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=Rn.isAbsolute(t)?Rn.relative(process.cwd(),t):t,l=Bt(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let m=0,f=0;for(let k of l)k.type==="add"?m++:k.type==="remove"&&f++;if(console.log(`
|
|
78
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),m===0&&f===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
79
|
+
`);return}let h=[];if(m>0&&h.push(`Added ${m} line${m!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let k=i.filter(T=>T.severity==="error").length,v=i.filter(T=>T.severity==="warn").length,C=i.filter(T=>T.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),C>0&&S.push(`${b.cyan}${C} info${C!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let w=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),C=Math.min(l.length-1,k+r);$===null?($=v,x=C):(v<=x+1||(w.push([$,x]),$=v),x=C)}$!==null&&w.push([$,x]);let O=" ";for(let k=0;k<w.length;k++){k>0&&console.log(`${O}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,C]=w[k];for(let S=v;S<=C;S++){let T=l[S],F=T.newLine!=null?T.newLine:T.oldLine,I=String(F).padStart(4),V=T.type!=="remove"?i.filter(D=>D.line===T.newLine):[];T.type==="remove"?console.log(`${O}${b.red}${I} -${T.line}${b.reset}`):T.type==="add"?console.log(`${O}${b.green}${I} +${T.line}${b.reset}`):console.log(`${O}${b.dim}${I}${b.reset} ${T.line}`);for(let D of V){let ne=b.cyan,ie="\u2139";D.severity==="error"?(ne=b.red,ie="\u2716"):D.severity==="warn"&&(ne=b.yellow,ie="\u26A0"),console.log(`${O} ${ne}${ie} ${D.message}${b.reset}`)}}}console.log()}function Vu(t,e,s={}){let n=Rn.isAbsolute(t)?Rn.relative(process.cwd(),t):t,o=e.split(`
|
|
80
80
|
`),r=s.annotations||[];console.log(`
|
|
81
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let
|
|
82
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function On(t=!1){return await
|
|
83
|
-
`);for(let
|
|
81
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,m=r.filter(p=>p.severity==="warn").length,f=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${b.red}${d} error${d!==1?"s":""}${b.dim}`),m>0&&h.push(`${b.yellow}${m} warning${m!==1?"s":""}${b.dim}`),f>0&&h.push(`${b.cyan}${f} info${f!==1?"s":""}${b.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${i.join(", ")}${b.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let m=String(d+1).padStart(4),f=d+1,h=r.filter(p=>p.line===f);console.log(`${l}${b.green}${m} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,w="\u2139";p.severity==="error"?(g=b.red,w="\u2716"):p.severity==="warn"&&(g=b.yellow,w="\u26A0"),console.log(`${l} ${g}${w} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}pi.exports={diffLines:Bt,showEditDiff:Gu,showWriteDiff:zu,showNewFilePreview:Ku,confirmFileChange:Ju,showSideBySideDiff:Yu,showClaudeDiff:Xu,showClaudeNewFile:Vu}});var it=N((Zg,yi)=>{var gi=require("util").promisify(require("child_process").exec),Qu=require("util").promisify(require("child_process").execFile),{C:Q}=oe();async function Ps(t){try{let{stdout:e}=await gi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function An(...t){try{let{stdout:e}=await Qu("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Zu(){return await Ps("git rev-parse --is-inside-work-tree")==="true"}async function ed(){return await Ps("git branch --show-current")}async function Ls(){try{let{stdout:t}=await gi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
82
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function On(t=!1){return await Ps(`git diff ${t?"--cached":""}`)||""}async function Is(){return(await Ls()).map(e=>e.file)}async function $i(){let t=await Is();if(t.length===0)return null;let e=await On(),n=await On(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let m of d)m.startsWith("+")&&!m.startsWith("+++")&&o++,m.startsWith("-")&&!m.startsWith("---")&&r++}else o=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function td(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await An("checkout","-b",s)!==null?s:null}async function nd(t){return await An("add","-A"),await An("commit","-m",t)?await An("rev-parse","--short","HEAD"):null}async function sd(){let t=await $i();if(!t)return`${Q.dim}No changes${Q.reset}`;let e=[];e.push(`
|
|
84
84
|
${Q.bold}${Q.cyan}Git Diff Summary:${Q.reset}`),e.push(` ${Q.green}+${t.stats.additions}${Q.reset} ${Q.red}-${t.stats.deletions}${Q.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
85
|
${Q.bold}${Q.cyan}Files:${Q.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Q.dim}${s}${Q.reset}`);return t.files.length>20&&e.push(` ${Q.dim}...+${t.files.length-20} more${Q.reset}`),e.push(`
|
|
86
86
|
${Q.bold}${Q.cyan}Suggested message:${Q.reset}`),e.push(` ${Q.cyan}${t.summary}${Q.reset}
|
|
87
87
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
88
|
+
`)}async function od(){return(await Ls()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function rd(){let t=await Is();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await On();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
89
89
|
...(truncated)`:s;e.push(`
|
|
90
90
|
DIFF:
|
|
91
91
|
${n}`)}return e.join(`
|
|
92
|
-
`)}
|
|
92
|
+
`)}yi.exports={isGitRepo:Zu,getCurrentBranch:ed,getStatus:Ls,getDiff:On,getChangedFiles:Is,analyzeDiff:$i,createBranch:td,commit:nd,formatDiffSummary:sd,getDiffContext:rd,getMergeConflicts:od}});var kt=N((e$,wi)=>{var qs=require("fs").promises,id=50,De=[],_t=[];function ad(t,e,s,n){for(De.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});De.length>id;)De.shift();_t.length=0}async function cd(){if(De.length===0)return null;let t=De.pop();if(t.oldContent===null)try{await qs.unlink(t.filePath)}catch{}else await qs.writeFile(t.filePath,t.oldContent,"utf-8");return _t.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ld(){if(_t.length===0)return null;let t=_t.pop();return await qs.writeFile(t.filePath,t.newContent,"utf-8"),De.push(t),{tool:t.tool,filePath:t.filePath}}function ud(t=10){return De.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function dd(){return De.length}function fd(){return _t.length}function md(){De.length=0,_t.length=0}wi.exports={recordChange:ad,undo:cd,redo:ld,getHistory:ud,getUndoCount:dd,getRedoCount:fd,clearHistory:md}});var Ht=N((t$,Si)=>{var ve=require("fs"),vt=require("path"),we=[];function js(){return vt.join(process.cwd(),".nex","skills")}function bi(){return vt.join(process.cwd(),".nex","config.json")}function pd(){let t=js();return ve.existsSync(t)||ve.mkdirSync(t,{recursive:!0}),t}function Ds(){let t=bi();if(!ve.existsSync(t))return[];try{let e=JSON.parse(ve.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function xi(t){let e=bi(),s={};if(ve.existsSync(e))try{s=JSON.parse(ve.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=vt.dirname(e);ve.existsSync(n)||ve.mkdirSync(n,{recursive:!0}),ve.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function _i(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function ki(t){try{let e=ve.readFileSync(t,"utf-8").trim();return e?{name:vt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function vi(t){try{let e=require(t),{valid:s,errors:n}=_i(e,t);return s?{name:e.name||vt.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 hd(){we=[];let t=js();if(!ve.existsSync(t))return we;let e=Ds(),s;try{s=ve.readdirSync(t)}catch{return we}for(let n of s){let o=vt.join(t,n),r;try{r=ve.statSync(o)}catch{continue}if(!r.isFile())continue;let i=null;n.endsWith(".md")?i=ki(o):n.endsWith(".js")&&(i=vi(o)),i&&(i.enabled=!e.includes(i.name),we.push(i))}return we}function gd(){let t=[];for(let e of we)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
95
95
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
96
96
|
${t.join(`
|
|
97
97
|
|
|
98
|
-
`)}`}function
|
|
99
|
-
`,l="",u=setTimeout(()=>{
|
|
100
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===
|
|
101
|
-
`):JSON.stringify(o)}function
|
|
102
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),
|
|
103
|
-
`+
|
|
98
|
+
`)}`}function $d(){let t=[];for(let e of we)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function yd(){let t=[];for(let e of we)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function wd(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of we)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function bd(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of we)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return!0}}return!1}function xd(){return we.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function _d(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Ds().filter(n=>n!==t);return xi(s),!0}function kd(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Ds();return s.includes(t)||(s.push(t),xi(s)),!0}function vd(){return we}Si.exports={initSkillsDir:pd,loadAllSkills:hd,getSkillInstructions:gd,getSkillCommands:$d,getSkillToolDefinitions:yd,routeSkillCall:wd,handleSkillCommand:bd,listSkills:xd,enableSkill:_d,disableSkill:kd,getLoadedSkills:vd,_getSkillsDir:js,_validateScriptSkill:_i,_loadMarkdownSkill:ki,_loadScriptSkill:vi}});var Nn=N((n$,Oi)=>{var{spawn:Sd}=require("child_process"),Ed=require("path"),Ei=require("fs"),Fe=new Map;function Cd(){return Ed.join(process.cwd(),".nex","config.json")}function Fs(){let t=Cd();if(!Ei.existsSync(t))return{};try{return JSON.parse(Ei.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Mn(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
|
|
99
|
+
`,l="",u=setTimeout(()=>{m(),r(new Error(`MCP request timeout: ${e}`))},n);function d(f){l+=f.toString();let h=l.split(`
|
|
100
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){m(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=h[h.length-1]||""}function m(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(f){m(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Ci(t,e){if(Fe.has(t))return Fe.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=Sd(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Mn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Mn(o,"tools/list",{});return r.tools=i&&i.tools||[],Fe.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Ti(t){let e=Fe.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Fe.delete(t),!0}function Td(){for(let[t]of Fe)Ti(t)}async function Ri(t,e,s={}){let n=Fe.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Mn(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
101
|
+
`):JSON.stringify(o)}function Ai(){let t=[];for(let[e,s]of Fe)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Rd(){return Ai().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Ad(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Ri(n,o,e)}function Od(){let t=Fs();return Object.entries(t).map(([e,s])=>{let n=Fe.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Md(){let t=Fs(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ci(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Oi.exports={loadMCPConfig:Fs,sendRequest:Mn,connectServer:Ci,disconnectServer:Ti,disconnectAll:Td,callTool:Ri,getAllTools:Ai,getMCPToolDefinitions:Rd,routeMCPCall:Ad,listServers:Od,connectAll:Md}});var Us=N((s$,Li)=>{var{getSkillToolDefinitions:Nd}=Ht(),{getMCPToolDefinitions:Pd}=Nn(),Pn=new Map;function Mi(){let{TOOL_DEFINITIONS:t}=Ue();return[...t,...Nd(),...Pd()]}function Ni(t){if(Pn.has(t))return Pn.get(t);let s=Mi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Pn.set(t,n),n}function Ld(){Pn.clear()}function Ln(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Pi(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Pi(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Id(t,e){let s=Ni(t);if(s===null){let d=Mi().map(f=>f.function.name),m=Ln(t,d);return{valid:!1,error:`Unknown tool "${t}".${m?` Did you mean "${m}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Ln(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=Ln(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||i.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,m=typeof c[u];d==="string"&&m==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&m==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&m==="string"&&(c[u]=c[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
103
|
+
`+i.map(u=>` - ${u}`).join(`
|
|
104
104
|
`)+`
|
|
105
105
|
|
|
106
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}
|
|
106
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Li.exports={validateToolArgs:Id,closestMatch:Ln,levenshtein:Pi,getCachedSchema:Ni,clearSchemaCache:Ld}});var Di=N((o$,ji)=>{var{levenshtein:In}=Us(),qd=200,jd=.3,Dd=2;function Ws(t){return t.replace(/\r\n/g,`
|
|
107
107
|
`).replace(/\r/g,`
|
|
108
|
-
`).replace(/\t/g," ".repeat(
|
|
108
|
+
`).replace(/\t/g," ".repeat(Dd)).split(`
|
|
109
109
|
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
110
|
-
`)}function
|
|
110
|
+
`)}function Fd(t,e){if(t.includes(e))return e;let s=Ws(t),n=Ws(e);if(!s.includes(n))return null;let o=t.split(`
|
|
111
111
|
`),r=s.split(`
|
|
112
|
-
`),
|
|
113
|
-
`),c=
|
|
114
|
-
`)}if(
|
|
112
|
+
`),i=n.split(`
|
|
113
|
+
`),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let m=0;m<i.length;m++)if(r[u+m]!==i[m]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
|
|
114
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Ud(t,e){if(!t||!e)return null;let s=t.split(`
|
|
115
115
|
`),o=e.split(`
|
|
116
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
117
|
-
`),u=In(l,e);u<
|
|
118
|
-
`),h=In(
|
|
119
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let
|
|
120
|
-
`).filter(Boolean),
|
|
116
|
+
`).length;return s.length===0||o===0?null:o===1?Wd(s,e):Hd(s,e,o)}function Ii(t){return Math.max(1,Math.floor(t/qd))}function qi(t,e){return t<=Math.ceil(e*jd)}function Wd(t,e){let s=e.trim(),n=Ii(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let c=t[i];if(!c.trim())continue;let l=In(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=Bd(t,s,o,n)||o,r=o.distance),qi(r,e.length)?o:null}function Bd(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let m=In(d.trim(),e);m<c&&(c=m,l={text:d,distance:m,line:u+1})}return l}function Hd(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Ii(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
117
|
+
`),u=In(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Gd(t,e,r,o,s,n)||r,i=r.distance),qi(i,e.length)?r:null}function Gd(t,e,s,n,o,r){let i=s.line-1,c=Math.max(0,i-n),l=Math.min(r-1,i+n),u=s.distance,d=null;for(let m=c;m<=l;m++){let f=t.slice(m,m+o).join(`
|
|
118
|
+
`),h=In(f,e);h<u&&(u=h,d={text:f,distance:h,line:m+1})}return d}ji.exports={normalizeWhitespace:Ws,fuzzyFindText:Fd,findMostSimilar:Ud}});var Ui=N((i$,Fi)=>{var{C:r$}=oe(),zd=[{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}],Kd=[{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 Jd(t,e){let s=e.split(`
|
|
119
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of zd)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Kd)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}Fi.exports={runDiagnostics:Jd}});var Gs=N((a$,Hi)=>{var Yd=require("fs").promises,Wi=require("path"),{exec:Xd}=require("util").promisify(require("child_process").exec),St=[],Hs=null,qn=!1,Bs=0,Vd=6e4;function Bi(t){return!(St.length===0||Hs!==t||Date.now()-Bs>Vd)}async function Qd(t){if(!qn&&!Bi(t)){qn=!0,Hs=t;try{try{let{stdout:n}=await Xd("rg --files",{cwd:t,timeout:5e3});St=n.split(`
|
|
120
|
+
`).filter(Boolean),Bs=Date.now(),qn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Yd.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Wi.join(n,i.name),c):e.push(c)}};await s(t,""),St=e,Bs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{qn=!1}}}function Zd(){return St}function ef(){return Hs}function tf(t){return St.filter(e=>Wi.basename(e)===t)}function nf(t){let e=t.toLowerCase();return St.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Hi.exports={refreshIndex:Qd,getFileIndex:Zd,getIndexedCwd:ef,findFileInIndex:tf,searchIndex:nf,isIndexValid:Bi}});var Et=N((c$,Ji)=>{var jn=require("fs"),Fn=require("path"),zs=require("os"),{execFile:sf}=require("child_process"),{promisify:of}=require("util"),Ks=of(sf),rf=Fn.join(".nex","servers.json"),Dn=Fn.join(zs.tmpdir(),"nex-ssh-sockets");function af(){return Fn.join(process.cwd(),rf)}function Gi(){let t=af();if(!jn.existsSync(t))return{};try{return JSON.parse(jn.readFileSync(t,"utf-8"))}catch{return{}}}function cf(t){let e=Gi();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json";throw new Error(`Unknown server: "${t}". ${n}`)}function lf(){jn.existsSync(Dn)||jn.mkdirSync(Dn,{recursive:!0})}function zi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,zs.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),lf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Fn.join(Dn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Ki(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,zs.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function uf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=zi(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Ks("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:Un(l,t)}}}async function df(t,e,s,{timeout:n=12e4}={}){let o=Ki(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await Ks("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Un(c,t)||c)}}async function ff(t,e,s,{timeout:n=12e4}={}){let o=Ki(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await Ks("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Un(c,t)||c)}}function Un(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
121
121
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
122
122
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
123
123
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
124
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
125
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
126
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
127
|
-
`,"utf-8")}
|
|
126
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function mf(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Ji.exports={loadServerProfiles:Gi,resolveProfile:cf,buildSSHArgs:zi,sshExec:uf,scpUpload:df,scpDownload:ff,enrichSSHError:Un,formatProfile:mf,SSH_SOCKET_DIR:Dn}});var Xs=N((l$,Xi)=>{var Gt=require("fs"),Js=require("path"),pf=Js.join(".nex","deploy.json");function Ys(){return Js.join(process.cwd(),pf)}function Yi(){let t=Ys();if(!Gt.existsSync(t))return{};try{return JSON.parse(Gt.readFileSync(t,"utf-8"))}catch{return{}}}function hf(t){let e=Yi();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function gf(t){let e=Js.join(process.cwd(),".nex");Gt.existsSync(e)||Gt.mkdirSync(e,{recursive:!0}),Gt.writeFileSync(Ys(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}Xi.exports={loadDeployConfigs:Yi,resolveDeployConfig:hf,saveDeployConfigs:gf,getDeployConfigPath:Ys}});var Kt=N((u$,Zi)=>{var Vs=null,We=null,zt=null,Vi=`Playwright is not installed. Install with:
|
|
128
128
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function
|
|
130
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
131
|
-
`)}function
|
|
129
|
+
Then restart nex-code.`;function Qi(){if(zt!==null)return zt;try{require("playwright"),zt=!0}catch{zt=!1}return zt}async function Wn(){if(!Qi())throw new Error(Vi);return Vs||(Vs=require("playwright")),(!We||!We.isConnected())&&(We=await Vs.chromium.launch({headless:!0})),We}async function $f(){if(We){try{await We.close()}catch{}We=null}}process.on("exit",()=>{if(We)try{We.close()}catch{}});async function yf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Wn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
130
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function wf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await Wn()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let c=await i.screenshot({type:"png",fullPage:n}),l=require("os"),u=require("path"),d=require("fs"),m=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(m,c),{path:m,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function bf(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Wn()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function xf(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await Wn()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Zi.exports={isPlaywrightAvailable:Qi,browserNavigate:yf,browserScreenshot:wf,browserClick:bf,browserFill:xf,closeBrowser:$f,INSTALL_MSG:Vi}});var Bn=N((d$,ea)=>{var{C:K}=oe(),Yt="",$e=[],Jt=0,at=null;function _f(t){at=t}function kf(t,e){Yt=t,$e=[],Jt=0;for(let n of e){Jt++;let o=`t${Jt}`;$e.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Jt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=$e.map(n=>({...n}));return at&&at("create",{name:t,tasks:s}),s}function vf(t,e,s){let n=$e.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),at&&at("update",{id:t,status:e,result:s}),{...n}):null}function Sf(){return{name:Yt,tasks:$e.map(t=>({...t}))}}function Ef(){Yt="",$e=[],Jt=0,at&&at("clear",{})}function Cf(){return $e.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=$e.find(n=>n.id===e);return s&&s.status==="done"}))}function Tf(){if($e.length===0)return`${K.dim}No active tasks${K.reset}`;let t=[];Yt&&(t.push(` ${K.bold}${K.cyan}Tasks: ${Yt}${K.reset}`),t.push(` ${K.dim}${"\u2500".repeat(40)}${K.reset}`));for(let o of $e){let r,i;switch(o.status){case"done":r="\u2713",i=K.green;break;case"in_progress":r="\u2192",i=K.cyan;break;case"failed":r="\u2717",i=K.red;break;default:r="\xB7",i=K.dim}let c=o.dependsOn.length>0?` ${K.dim}(after: ${o.dependsOn.join(", ")})${K.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${K.reset} ${K.bold}${o.id}${K.reset} ${u.padEnd(40)} ${i}${l}${K.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${K.dim}\u2192 ${d}${K.reset}`)}}let e=$e.filter(o=>o.status==="done").length,s=$e.filter(o=>o.status==="failed").length,n=$e.length;return t.push(` ${K.dim}${"\u2500".repeat(40)}${K.reset}`),t.push(` ${K.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${K.reset}`),t.join(`
|
|
131
|
+
`)}function Rf(){return $e.length>0&&$e.some(t=>t.status==="pending"||t.status==="in_progress")}ea.exports={createTasks:kf,updateTask:vf,getTaskList:Sf,clearTasks:Ef,getReadyTasks:Cf,renderTaskList:Tf,setOnChange:_f,hasActiveTasks:Rf}});var Zs=N((f$,na)=>{var{getActiveModel:Af,getActiveProviderName:Of}=ge(),Xt={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},Vt={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},Qt={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Ne={};function ta(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Ne=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Ne={}}}ta();function Qs(){let e=Af()?.id,s=Of();return e&&Ne[e]?Ne[e]:s&&Ne[`${s}:*`]?Ne[`${s}:*`]:e&&Vt[e]?Vt[e]:s&&Qt[s]?Qt[s]:"full"}function Mf(t,e){return t&&Ne[t]?Ne[t]:e&&Ne[`${e}:*`]?Ne[`${e}:*`]:t&&Vt[t]?Vt[t]:e&&Qt[e]?Qt[e]:"full"}function Nf(t,e){let s=e||Qs();if(s==="full"||!Xt[s])return t;let n=new Set(Xt[s]);return t.filter(o=>n.has(o.function.name))}function Pf(){let t=Qs(),e=Xt[t]?Xt[t].length:"all";return{tier:t,toolCount:e}}na.exports={filterToolsForModel:Nf,getActiveTier:Qs,getModelTier:Mf,getTierInfo:Pf,TIERS:Xt,MODEL_TIERS:Vt,PROVIDER_DEFAULT_TIER:Qt,loadConfigOverrides:ta}});var pa=N((p$,ma)=>{var{callStream:Lf,getActiveProviderName:Gn,getActiveModelId:If,getConfiguredProviders:qf,getProvider:sa,getActiveProvider:oa,parseModelSpec:ra}=ge(),{parseToolArgs:jf}=Tn(),{filterToolsForModel:Df,getModelTier:Hn}=Zs(),{trackUsage:Ff}=xt(),{MultiProgress:Uf,C:m$}=oe(),Wf=15,ia=5,aa=3,zn=new Map;function Bf(t,e){let s=zn.get(t);return s&&s!==e?!1:(zn.set(t,e),!0)}function Zt(t){zn.delete(t)}function eo(){zn.clear()}function ca(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function la(t,e,s){let n;for(let o=0;o<=aa;o++)try{return await Lf(t,e,s)}catch(r){if(n=r,o<aa&&ca(r)){let c=(r.message||"").includes("429")?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Hf=new Set(["ask_user","task_list","spawn_agents"]),Gf=new Set(["write_file","edit_file","patch_file"]),zf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Kf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ua(t){return Kf.test(t)?"full":zf.test(t)?"essential":"standard"}function da(t){let e=qf(),s=Gn(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(Hn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Jf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function to(t){if(t.model){let{provider:o,model:r}=ra(t.model),i=o?sa(o):oa(),c=o||Gn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Hn(r,c);return{provider:c,model:r,tier:l}}}let e=ua(t.task),s=Jf[e];if(s){let{provider:o,model:r}=ra(s),i=o?sa(o):oa(),c=o||Gn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Hn(r,c);return{provider:c,model:r,tier:l}}}let n=da(e);if(n){let o=Hn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function fa(t,e={}){let s=Math.min(t.max_iterations||10,Wf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},i=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
132
132
|
|
|
133
133
|
TASK: ${t.task}
|
|
134
134
|
${t.context?`
|
|
@@ -150,116 +150,116 @@ TOOL STRATEGY:
|
|
|
150
150
|
ERROR RECOVERY:
|
|
151
151
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
152
152
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
153
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
154
|
-
`)}let w={};d&&(w.provider=d),
|
|
155
|
-
...(truncated)`:ie,tool_call_id:V}}).catch(ne=>(
|
|
156
|
-
`)}catch(r){return o.stop(),
|
|
157
|
-
`);for(let r of o){let
|
|
158
|
-
`);for(let
|
|
159
|
-
...(truncated)`}let
|
|
160
|
-
${u}`),c+=o(u),c>=r)break}return
|
|
153
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=to(t),d=u.provider,m=u.model,f=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ue(),g=Df(h.filter($=>!Hf.has($.function.name)),f);if(m&&!t._skipLog){let $=f?` (${f})`:"";process.stderr.write(` [sub-agent: ${d}:${m}${$}]
|
|
154
|
+
`)}let w={};d&&(w.provider=d),m&&(w.model=m);try{for(let $=0;$<s;$++){let x=await la(l,g,w);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let T=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=T,r.output+=F;let I=d||Gn(),V=m||If();Ff(I,V,T,F)}let O=x.content||"",k=x.tool_calls,v={role:"assistant",content:O||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let T of i)Zt(T);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&m?`${d}:${m}`:null}}let C=k.map(T=>{let F=T.function.name,I=jf(T.function.arguments),V=T.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!I)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${F}`,tool_call_id:V});let D=null;if(Gf.has(F)&&I.path){let ne=require("path"),ie=ne.isAbsolute(I.path)?I.path:ne.resolve(process.cwd(),I.path);if(i.has(ie)||!Bf(ie,n))return Promise.resolve({role:"tool",content:`ERROR: File '${I.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:V});i.add(ie),D=ie}return o.push(F),p(F,I,{autoConfirm:!0,silent:!0}).then(ne=>{D&&(Zt(D),i.delete(D));let ie=String(ne??"");return{role:"tool",content:ie.length>2e4?ie.substring(0,2e4)+`
|
|
155
|
+
...(truncated)`:ie,tool_call_id:V}}).catch(ne=>(D&&(Zt(D),i.delete(D)),{role:"tool",content:`ERROR: ${ne.message}`,tool_call_id:V}))}),S=await Promise.all(C);l.push(...S),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)Zt($);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&m?`${d}:${m}`:null}}catch($){for(let x of i)Zt(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&m?`${d}:${m}`:null}}}async function Yf(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ia)return`ERROR: Max ${ia} parallel agents allowed, got ${e.length}`;let s=e.map(r=>to(r)),n=e.map((r,i)=>{let c=s[i],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${i+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new Uf(n);o.start();try{let r=e.map((d,m)=>{let f=s[m],h=f.model?{...d,model:`${f.provider}:${f.model}`,_skipLog:!0}:{...d,_skipLog:!0};return fa(h,{onUpdate:()=>{}}).then(p=>(o.update(m,p.status==="failed"?"error":"done"),p)).catch(p=>(o.update(m,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),i=await Promise.all(r);o.stop(),eo();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<i.length;d++){let m=i[d],f=m.status==="done"?"\u2713":m.status==="truncated"?"\u26A0":"\u2717",h=m.modelSpec?` [${m.modelSpec}]`:"";c.push(`${f} Agent ${d+1}${h}: ${m.task}`),c.push(` Status: ${m.status}`),c.push(` Tools used: ${m.toolsUsed.length>0?m.toolsUsed.join(", "):"none"}`),c.push(` Result: ${m.result}`),c.push(""),l+=m.tokensUsed.input,u+=m.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
156
|
+
`)}catch(r){return o.stop(),eo(),`ERROR: Sub-agent execution failed: ${r.message}`}}ma.exports={runSubAgent:fa,executeSpawnAgents:Yf,clearAllLocks:eo,classifyTask:ua,pickModelForTier:da,resolveSubAgentModel:to,isRetryableError:ca,callWithRetry:la}});var nn=N((h$,Ca)=>{var Y=require("fs"),Be=require("path"),Xf=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 Ct(){let t=Be.join(process.cwd(),".nex","brain");return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),t}function ha(){return Be.join(Ct(),".brain-index.json")}function oo(){return Be.join(Ct(),".embeddings.json")}function en(){let t=Be.join(process.cwd(),".nex","brain");if(!Y.existsSync(t))return[];try{return Y.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Be.join(t,e),n=Y.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function tn(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
157
|
+
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function ga(t){let e=Be.join(Ct(),`${t}.md`);if(!Y.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Y.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=tn(s);return{name:t,content:s,body:o,frontmatter:n}}function Vf(t,e){let s=Be.join(Ct(),`${t}.md`);Y.writeFileSync(s,e,"utf-8"),em(t,e),Qf()}function Qf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=oo();Y.existsSync(t)&&setImmediate(async()=>{try{await ka()}catch{}})}function Zf(t){let e=Be.join(Ct(),`${t}.md`);return Y.existsSync(e)?(Y.unlinkSync(e),tm(t),!0):!1}function Kn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Xf.has(e))}function ro(t){let e={},{frontmatter:s,body:n}=tn(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(n||t).split(`
|
|
158
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Kn(c))e[l]=(e[l]||0)+3}for(let i of Kn(n||t))e[i]=(e[i]||0)+1;return e}function io(){let t=ha();if(!Y.existsSync(t))return{documents:{}};try{return JSON.parse(Y.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ao(t){Y.writeFileSync(ha(),JSON.stringify(t,null,2),"utf-8")}function em(t,e){let s=io(),{frontmatter:n}=tn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ro(e),tags:o,modified:new Date().toISOString()},ao(s)}function tm(t){let e=io();delete e.documents[t],ao(e)}function so(){let t=en(),e={documents:{}};for(let s of t){let n=Y.readFileSync(s.path,"utf-8"),{frontmatter:o}=tn(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ro(n),tags:r,modified:s.modified.toISOString()}}return ao(e),e}function $a(){let t=io(),e=en();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return so()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return so();return t}function ya(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Kn(t);if(o.length===0)return[];let r=$a(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of o){l.keywords[d]&&(u+=l.keywords[d]);for(let[m,f]of Object.entries(l.keywords))m!==d&&m.length>3&&d.length>3&&(m.includes(d)||d.includes(m))&&(u+=f*.3)}u>=n&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var wa=process.env.NEX_EMBED_MODEL||"nomic-embed-text",no=400,nm=50;async function ba(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=o.get(n.toString(),{timeout:2e3},d=>{let m="";d.on("data",f=>m+=f),d.on("end",()=>{try{c(JSON.parse(m))}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(wa.split(":")[0]))}catch{return!1}}async function co(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:wa,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let m="";d.on("data",f=>m+=f),d.on("end",()=>{try{c(JSON.parse(m).embedding||[])}catch(f){l(f)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function xa(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function _a(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+no).join(" ");if(s.push({text:o,offset:n}),n+no>=e.length)break;n+=no-nm}return s}async function ka(){let t=en(),e={documents:{}},s=oo();if(Y.existsSync(s))try{e=JSON.parse(Y.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=Y.readFileSync(n.path,"utf-8"),i=_a(r),c=[];for(let l of i){let u=await co(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[n.name]={chunks:c,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return Y.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function va(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=oo();if(!Y.existsSync(o))return[];let r;try{r=JSON.parse(Y.readFileSync(o,"utf-8"))}catch{return[]}let i=await co(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,m="";for(let f of u.chunks||[]){let h=xa(i,f.embedding);h>d&&(d=h,m=f.text)}d>=n&&c.push({name:l,score:d,bestChunk:m})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function Sa(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,o)}async function Ea(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ya(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ba()){let c=await va(t,{topK:s});r=Sa(o,c,{topK:s})}}catch{}return r.map(i=>{let c=ga(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}async function sm(t){if(!t||!t.trim())return"";let e=Be.join(process.cwd(),".nex","brain");if(!Y.existsSync(e)||en().length===0)return"";let n;try{n=await Ea(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Re().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let r=25e3,i=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>r){let f=r-c;if(f<100)break;let h=f/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
159
|
+
...(truncated)`}let m=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${m}) ---
|
|
160
|
+
${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
161
|
|
|
162
|
-
${
|
|
162
|
+
${i.join(`
|
|
163
163
|
|
|
164
|
-
`)}`}
|
|
165
|
-
${
|
|
166
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
164
|
+
`)}`}Ca.exports={getBrainDir:Ct,listDocuments:en,readDocument:ga,writeDocument:Vf,removeDocument:Zf,buildIndex:so,getIndex:$a,query:Ea,getBrainContext:sm,isEmbeddingAvailable:ba,generateEmbedding:co,buildEmbeddingIndex:ka,semanticQuery:va,cosineSimilarity:xa,_keywordQuery:ya,_extractKeywords:ro,_chunkText:_a,parseFrontmatter:tn,tokenize:Kn,_fuseResults:Sa}});var Ue=N((w$,ja)=>{var X=require("fs").promises,Ta=require("fs"),xe=require("path"),Z=require("util").promisify(require("child_process").exec),Ra=require("util").promisify(require("child_process").execFile),{spawnSync:om}=require("child_process"),lo=require("axios"),{isForbidden:rm,isDangerous:im,isCritical:Aa,confirm:Pe}=Me(),{showClaudeDiff:Jn,showClaudeNewFile:am,showEditDiff:g$,confirmFileChange:sn}=hi(),{C:P,Spinner:La,getToolSpinnerText:cm}=oe(),{isGitRepo:uo,getCurrentBranch:Oa,getStatus:lm,getDiff:um}=it(),{recordChange:Yn}=kt(),{fuzzyFindText:Ma,findMostSimilar:mo}=Di(),{runDiagnostics:on}=Ui(),{findFileInIndex:dm,getFileIndex:$$}=Gs(),{resolveProfile:Le,sshExec:Xe,scpUpload:fm,scpDownload:mm}=Et(),{resolveDeployConfig:pm,loadDeployConfigs:y$}=Xs(),hm=/^(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/,gm=/^ssh\s/,$m=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Xn(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=be(e);if(s&&await X.access(s).then(()=>!0).catch(()=>!1))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=xe.extname(t);if(!o)for(let i of n){let c=be(t+i);if(c&&await X.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=be(i+c);if(l&&await X.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=xe.basename(t);if(r&&r.length>2)try{let i=dm(r).map(c=>be(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${xe.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
165
|
+
${i.map(l=>xe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function ym(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 Ia(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),s.length===0?t:t+`
|
|
167
167
|
|
|
168
168
|
`+s.join(`
|
|
169
|
-
`)}function Pa(t,e,s){let n=po(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 Aa=!1,rn=null;function $m(){rn&&(rn(),rn=null)}async function mo(){if(!Aa){Aa=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var ym=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function we(t){let e=be.isAbsolute(t)?be.resolve(t):be.resolve(process.cwd(),t);for(let s of ym)if(s.test(e))return null;return e}var wm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function on(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${a}"`}return r}async function Oa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=sm(n);if(o){let u=gm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
-
HINT: ${u}`:""}`}if(s.autoConfirm?
|
|
171
|
-
${P.yellow}${u}: ${n}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined to execute this command."}let
|
|
172
|
-
${
|
|
173
|
-
`+
|
|
174
|
-
`),d=(e.line_start||1)-1,
|
|
175
|
-
`)}case"write_file":{await
|
|
176
|
-
`+d.message:""}`}let r=await X.readFile(n,"utf-8"),
|
|
177
|
-
Most similar text (line ${
|
|
178
|
-
${
|
|
179
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
169
|
+
`)}function qa(t,e,s){let n=mo(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Na=!1,an=null;function wm(){an&&(an(),an=null)}async function fo(){if(!Na){Na=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var bm=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of bm)if(s.test(e))return null;return e}var xm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function rn(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Pa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=rm(n);if(o){let u=ym(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Aa(n):im(n)){let u=Aa(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
171
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{Ta.accessSync(i)}catch{i=require("os").homedir(),s.silent||console.log(`${P.yellow} \u26A0 Working directory no longer exists \u2014 running in ${i}${P.reset}`)}let c=gm.test(n.trim())&&!$m.test(n.trim());if(hm.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=om("sh",["-c",n],{stdio:"inherit",cwd:i});return u.error?`ERROR: ${u.error.message}`:u.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${u.status})`}let l=s.silent?null:new La(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await Z(n,{cwd:i,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),u||d||"(no output)"}catch(u){l&&l.stop();let d=(u.stderr||u.stdout||u.message||"").toString().substring(0,5e3),m=Ia(d,n);return`EXIT ${u.code||1}
|
|
172
|
+
${m}`}}case"read_file":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let f=await Xn(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
|
|
173
|
+
`+f.message:""}`}let r=Buffer.alloc(8192),i=await Ta.promises.open(n,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let f=0;f<c;f++)if(r[f]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await X.readFile(n,"utf-8");if(!l&&(await X.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
174
|
+
`),d=(e.line_start||1)-1,m=e.line_end||u.length;return u.slice(d,m).map((f,h)=>`${d+h+1}: ${f}`).join(`
|
|
175
|
+
`)}case"write_file":{await fo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await X.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await X.readFile(n,"utf-8"));else if(o){r=await X.readFile(n,"utf-8");let l=await on(n,e.content);if(Jn(n,r,e.content,{annotations:l}),!await sn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await on(n,e.content);if(am(n,e.content,{annotations:l}),!await sn("Create"))return"CANCELLED: User declined to create file."}let i=xe.dirname(n);return await X.access(i).then(()=>!0).catch(()=>!1)||await X.mkdir(i,{recursive:!0}),await X.writeFile(n,e.content,"utf-8"),Yn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await fo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let d=await Xn(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
176
|
+
`+d.message:""}`}let r=await X.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Ma(r,e.old_text);if(d)i=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let m=qa(r,e.old_text,e.new_text);if(m){if(!s.autoConfirm){let p=await on(n,m.content);if(Jn(n,r,m.content,{annotations:p}),!await sn(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await X.writeFile(n,m.content,"utf-8"),Yn("edit_file",n,r,m.content);let h=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${P.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${P.reset}`),`Edited: ${n} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${h}")`}let f=mo(r,e.old_text);return f?`ERROR: old_text not found in ${n}
|
|
177
|
+
Most similar text (line ${f.line}, distance ${f.distance}):
|
|
178
|
+
${f.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),m=await on(n,d);if(Jn(n,r,d,{annotations:m}),!await sn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await X.writeFile(n,u,"utf-8"),Yn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=be(u),m=await X.access(d).then(()=>!0).catch(()=>!1);if(d&&m)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,m)=>{if(d>r)return;let f;try{f=await X.readdir(u,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${m}${h.name}${p}`),h.isDirectory()&&await l(xe.join(u,h.name),d+1,m+" ")}};return await l(n,1,""),c.join(`
|
|
179
|
+
`)||"(empty)"}case"search_files":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
180
180
|
`).slice(0,50).join(`
|
|
181
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
181
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?be(e.path):o,i=e.pattern,c=k=>{let v=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{getFileIndex:m,getIndexedCwd:f,refreshIndex:h,isIndexValid:p}=Gs(),g=m(),w=f();p(r)||(await h(r),g=m());let $=g.filter(k=>l.test(k)||d.test(xe.basename(k))).map(k=>xe.join(r,k));if($.length===0)return"(no matches)";let x=$.length>200,O=$.slice(0,200).join(`
|
|
182
182
|
`);return x?`${O}
|
|
183
183
|
|
|
184
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:O}case"grep":{let n=e.path?
|
|
184
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:O}case"grep":{let n=e.path?be(e.path):process.cwd(),o=["-rn","-E"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);try{let{stdout:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
185
185
|
`).slice(0,100).join(`
|
|
186
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
187
|
-
`+
|
|
186
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await fo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let f=await Xn(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
|
|
187
|
+
`+f.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await X.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let f=0;f<r.length;f++){let{old_text:h,new_text:p}=r[f];if(i.includes(h))c.push({old_text:h,new_text:p});else{let g=Ma(i,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let w=mo(i,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${f+1} old_text not found in ${n}
|
|
188
188
|
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
189
|
-
${w.text}`}else return`ERROR: Patch ${
|
|
189
|
+
${w.text}`}else return`ERROR: Patch ${f+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:f,new_text:h}of c)d=d.split(f).join(h);if(!s.autoConfirm){let f=await on(n,d);if(Jn(n,i,d,{annotations:f}),!await sn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await X.writeFile(n,d,"utf-8"),Yn("patch_file",n,i,d);let m=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${m}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await lo.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await lo.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
190
190
|
|
|
191
|
-
${r}`;return
|
|
191
|
+
${r}`;return i.length>0&&(c+=`
|
|
192
192
|
|
|
193
193
|
Sources:
|
|
194
|
-
`+
|
|
195
|
-
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await
|
|
194
|
+
`+i.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
195
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await lo.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
|
|
196
196
|
${u.url}`).join(`
|
|
197
197
|
|
|
198
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
198
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Kt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
199
199
|
|
|
200
200
|
Links:
|
|
201
|
-
`+o.links.map(
|
|
201
|
+
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
202
202
|
`):"";return`Title: ${o.title}
|
|
203
203
|
URL: ${o.url}
|
|
204
204
|
|
|
205
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
205
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Kt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
206
206
|
Title: ${o.title}
|
|
207
207
|
URL: ${o.url}
|
|
208
208
|
|
|
209
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=
|
|
210
|
-
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,
|
|
211
|
-
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let
|
|
212
|
-
`)}case"git_diff":{if(!await
|
|
213
|
-
`+
|
|
214
|
-
`+d.map(
|
|
209
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Kt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Kt();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let n=e.question;return new Promise(o=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});an=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
210
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{an=null,r.close(),o(i.trim()||"(no response)")})})}case"git_status":{if(!await uo())return"ERROR: Not a git repository";let n=await Oa()||"(detached)",o=await lm();if(o.length===0)return`Branch: ${n}
|
|
211
|
+
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
|
|
212
|
+
`)}case"git_diff":{if(!await uo())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await um(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await uo())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=Bn(),{getActiveTaskProgress:l}=oe(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
|
|
213
|
+
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
214
|
+
`+d.map(m=>` ${m.id}: ${m.description}`).join(`
|
|
215
215
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
216
|
-
`+
|
|
217
|
-
`+
|
|
218
|
-
`)}catch(r){let
|
|
219
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:
|
|
220
|
-
...(truncated)`:"")}let{stdout:n}=await Z(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let
|
|
216
|
+
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
217
|
+
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=pa();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Z(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",m=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${m}`}).join(`
|
|
218
|
+
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
219
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Z(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
220
|
+
...(truncated)`:"")}let{stdout:n}=await Z(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
221
221
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
222
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
223
|
-
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Z(
|
|
224
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=
|
|
225
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let
|
|
222
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Me(),o=e.branch||await Oa()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
223
|
+
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Z(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
224
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=rn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await Z(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
225
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=rn(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
226
226
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
227
227
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
228
|
-
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Pe(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let
|
|
229
|
-
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let
|
|
230
|
-
${P.yellow} \u26A0 kubectl apply: ${
|
|
228
|
+
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Pe(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=rn(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
229
|
+
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
|
|
230
|
+
${P.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await Pe(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=rn(o,e);try{let{stdout:i,stderr:c}=await Z(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
231
231
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
232
|
-
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Pe(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,
|
|
233
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=
|
|
232
|
+
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Pe(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=rn(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
233
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=nn(),{name:r,content:i,mode:c}=e;if(c==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(r),u=l.content?l.content+`
|
|
234
234
|
|
|
235
|
-
`+
|
|
236
|
-
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Pe(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:
|
|
235
|
+
`+i:i;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
236
|
+
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Pe(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:m}=await Xe(n,o,{timeout:i,sudo:r}),f=[l,u].filter(Boolean).join(`
|
|
237
237
|
`).trim();return d!==0?`EXIT ${d}
|
|
238
|
-
${f||
|
|
239
|
-
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Pe(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await
|
|
240
|
-
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:
|
|
241
|
-
${
|
|
242
|
-
`).trim();return d!==0?/not found|loaded.*not-found/i.test(
|
|
243
|
-
${f||
|
|
244
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:
|
|
245
|
-
`).trim();return
|
|
246
|
-
${
|
|
247
|
-
${(
|
|
238
|
+
${m||f||"(no output)"}`:f||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Le(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
239
|
+
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Pe(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await fm(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Le(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await mm(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=Le(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
240
|
+
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:m}=await Z(u,{timeout:15e3});return(d||m||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let m=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
241
|
+
${m}`}}else{let{stdout:l,stderr:u,exitCode:d,error:m}=await Xe(i,c,{timeout:15e3,sudo:!0}),f=[l,u].filter(Boolean).join(`
|
|
242
|
+
`).trim();return d!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
243
|
+
${m||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await Z(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
244
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:m,error:f}=await Xe(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
245
|
+
`).trim();return m!==0?`EXIT ${m}
|
|
246
|
+
${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await Z(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
247
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=Le(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Xe(i,r,{timeout:15e3}),m=[c,l].filter(Boolean).join(`
|
|
248
248
|
`).trim();return u!==0?`EXIT ${u}
|
|
249
|
-
${d||
|
|
250
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:
|
|
249
|
+
${d||m}`:m||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await Z(i,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
250
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:m}=await Xe(c,i,{timeout:2e4}),f=[l,u].filter(Boolean).join(`
|
|
251
251
|
`).trim();return d!==0?`EXIT ${d}
|
|
252
|
-
${f
|
|
253
|
-
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined."}let
|
|
254
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:
|
|
252
|
+
${m||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
253
|
+
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await Z(i,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
254
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:m}=await Xe(c,i,{timeout:35e3}),f=[l,u].filter(Boolean).join(`
|
|
255
255
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
|
-
${f
|
|
257
|
-
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined."}let
|
|
258
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:
|
|
259
|
-
`).trim();return
|
|
260
|
-
${
|
|
261
|
-
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await Pe(" Proceed with deployment?")))return"CANCELLED: User declined.";let
|
|
262
|
-
${
|
|
256
|
+
${m||f}`:f||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=o?"local":e.server;if(console.log(`
|
|
257
|
+
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:p,stderr:g}=await Z(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
258
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:m,error:f}=await Xe(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
|
+
`).trim();return m!==0?`EXIT ${m}
|
|
260
|
+
${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...pm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.local_path)return"ERROR: local_path is required";if(!e.remote_path)return"ERROR: remote_path is required";let n;try{n=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,r=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",i=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}"`:"",c=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:r,l=(e.exclude||[]).map(p=>`--exclude="${p}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
|
|
261
|
+
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await Pe(" Proceed with deployment?")))return"CANCELLED: User declined.";let f="";try{let{stdout:p,stderr:g}=await Z(m,{timeout:12e4});f=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
|
|
262
|
+
${f||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:w,error:$}=await Xe(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
263
263
|
`).trim();if(w!==0)return`rsync OK
|
|
264
264
|
|
|
265
265
|
ERROR (deploy_script, exit ${w}):
|
|
@@ -267,33 +267,33 @@ ${$||x}`;h=`
|
|
|
267
267
|
|
|
268
268
|
Remote script output:
|
|
269
269
|
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
270
|
-
${
|
|
271
|
-
`)}function
|
|
270
|
+
${f}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function _m(t,e,s={}){let n=s.silent?null:cm(t,e);if(!n)return Pa(t,e,s);let o=new La(n);o.start();try{let r=await Pa(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}ja.exports={TOOL_DEFINITIONS:xm,executeTool:_m,resolvePath:be,autoFixPath:Xn,autoFixEdit:qa,enrichBashError:Ia,cancelPendingAskUser:wm}});var Fa=N((b$,Da)=>{var{loadServerProfiles:ho}=Et(),po={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 km(){let t=ho();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&po[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of po[o])s.push(`- ${i}`)}}return s.join(`
|
|
271
|
+
`)}function vm(t){let e=ho();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Sm(){return Object.keys(ho())}Da.exports={getServerContext:km,hasServerOS:vm,getProfileNames:Sm,OS_HINTS:po}});var $o=N((x$,Wa)=>{var Oe=require("fs").promises,Ce=require("path"),Vn=require("util").promisify(require("child_process").exec),{C:Ie}=oe(),{getMergeConflicts:Ua}=it(),{getServerContext:Em}=Fa(),go=new Map,Tt=new Map,Qn=null,Cm=3e4;async function Ve(t){try{return await t()}catch{return null}}async function Tm(){if(!Qn||Date.now()>Qn)return!1;let t=[Ce.join(process.cwd(),"package.json"),Ce.join(process.cwd(),"README.md"),Ce.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Oe.stat(e),n=Tt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Tt.has(e))return!1}try{let e=Ce.join(process.cwd(),".git","HEAD"),s=await Oe.stat(e),n=Tt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Rm(){let t=[Ce.join(process.cwd(),"package.json"),Ce.join(process.cwd(),"README.md"),Ce.join(process.cwd(),".gitignore"),Ce.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Oe.stat(e);Tt.set(e,s.mtimeMs)}catch{Tt.delete(e)}}async function Am(t){let e="fileContext",s=go.get(e),n=!1;if(s&&await Tm()&&(n=!0),!n){let u=[],d=Ce.join(t,"package.json");if(await Ve(()=>Oe.access(d).then(()=>!0).catch(()=>!1)))try{let w=await Oe.readFile(d,"utf-8"),$=JSON.parse(w),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let f=Ce.join(t,"README.md");if(await Ve(()=>Oe.access(f).then(()=>!0).catch(()=>!1))){let $=(await Oe.readFile(f,"utf-8")).split(`
|
|
272
272
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
273
273
|
${$.join(`
|
|
274
|
-
`)}`)}let p=
|
|
274
|
+
`)}`)}let p=Ce.join(t,".gitignore");if(await Ve(()=>Oe.access(p).then(()=>!0).catch(()=>!1))){let w=await Oe.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
275
|
${w.trim()}`)}s=u.join(`
|
|
276
276
|
|
|
277
|
-
`)
|
|
278
|
-
${
|
|
277
|
+
`),go.set(e,s),Qn=Date.now()+Cm,await Rm()}let o=[s],[r,i,c,l]=await Promise.all([Ve(async()=>{let{stdout:u}=await Vn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ve(async()=>{let{stdout:u}=await Vn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ve(async()=>{let{stdout:u}=await Vn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ua()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
278
|
+
${i}`),c&&o.push(`RECENT COMMITS:
|
|
279
279
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
280
280
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
-
${u}`)}try{let u=
|
|
281
|
+
${u}`)}try{let u=Em();u&&o.push(u)}catch{}return o.join(`
|
|
282
282
|
|
|
283
|
-
`)}async function
|
|
284
|
-
${e}`);let s=
|
|
285
|
-
${s}`);let n=
|
|
283
|
+
`)}async function Om(t){let e=Ce.join(t,"package.json"),s="";if(await Ve(()=>Oe.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Oe.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Ve(async()=>{let{stdout:i}=await Vn("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Ua()]);if(s&&console.log(`${Ie.dim} project: ${s}${Ie.reset}`),o&&console.log(`${Ie.dim} branch: ${o}${Ie.reset}`),r&&r.length>0){console.log(`${Ie.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ie.reset}`);for(let i of r)console.log(`${Ie.red} ${i.file}${Ie.reset}`);console.log(`${Ie.yellow} \u2192 Resolve conflicts before starting tasks${Ie.reset}`)}console.log()}Wa.exports={gatherProjectContext:Am,printContext:Om,_clearContextCache:()=>{go.clear(),Tt.clear(),Qn=null}}});var lt=N((_$,za)=>{var Ge=require("fs"),yo=require("path");function Zn(){return yo.join(process.cwd(),".nex","sessions")}function Ba(){let t=Zn();Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0})}function wo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return yo.join(Zn(),`${e}.json`)}function bo(t,e,s={}){Ba();let n=wo(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return Ge.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Ha(t){let e=wo(t);if(!Ge.existsSync(e))return null;try{return JSON.parse(Ge.readFileSync(e,"utf-8"))}catch{return null}}function Ga(){Ba();let t=Zn(),e=Ge.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Ge.readFileSync(yo.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function Mm(t){let e=wo(t);return Ge.existsSync(e)?(Ge.unlinkSync(e),!0):!1}function Nm(){let t=Ga();return t.length===0?null:Ha(t[0].name)}var ct=null,He=null,cn=null;function Pm(t,e={}){t.length!==0&&(ct&&clearTimeout(ct),He=t,cn=e||{},ct=setTimeout(()=>{He&&He.length>0&&bo("_autosave",He,cn),ct=null,He=null,cn=null},5e3))}function Lm(){ct&&(clearTimeout(ct),ct=null),He&&He.length>0&&(bo("_autosave",He,cn),He=null,cn=null)}za.exports={saveSession:bo,loadSession:Ha,listSessions:Ga,deleteSession:Mm,getLastSession:Nm,autoSave:Pm,flushAutoSave:Lm,_getSessionsDir:Zn}});var Qe=N((k$,Qa)=>{var ze=require("fs"),es=require("path"),Im=require("os");function xo(){return es.join(process.cwd(),".nex","memory")}function _o(){return es.join(xo(),"memory.json")}function qm(){return es.join(process.cwd(),"NEX.md")}function Ka(){return es.join(Im.homedir(),".nex","NEX.md")}function jm(){let t=xo();ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0})}function ts(){let t=_o();if(!ze.existsSync(t))return{};try{return JSON.parse(ze.readFileSync(t,"utf-8"))}catch{return{}}}function Ja(t){jm(),ze.writeFileSync(_o(),JSON.stringify(t,null,2),"utf-8")}function Dm(t,e){let s=ts();s[t]={value:e,updatedAt:new Date().toISOString()},Ja(s)}function Fm(t){let e=ts();return e[t]?e[t].value:null}function Um(t){let e=ts();return t in e?(delete e[t],Ja(e),!0):!1}function Ya(){let t=ts();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Xa(){let t=Ka();if(!ze.existsSync(t))return"";try{return ze.readFileSync(t,"utf-8").trim()}catch{return""}}function Va(){let t=qm();if(!ze.existsSync(t))return"";try{return ze.readFileSync(t,"utf-8").trim()}catch{return""}}function Wm(){let t=[],e=Xa();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
|
+
${e}`);let s=Va();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
|
+
${s}`);let n=Ya();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
286
286
|
`);t.push(`PROJECT MEMORY:
|
|
287
287
|
${o}`)}return t.join(`
|
|
288
288
|
|
|
289
|
-
`)}
|
|
289
|
+
`)}Qa.exports={remember:Dm,recall:Fm,forget:Um,listMemories:Ya,loadGlobalInstructions:Xa,loadProjectInstructions:Va,getMemoryContext:Wm,_getMemoryDir:xo,_getMemoryFile:_o,_getGlobalNexMdPath:Ka}});var ln=N((S$,tc)=>{var ut=require("fs"),ko=require("path"),{C:v$}=oe(),ns={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask"},Rt={...ns};function Za(){let t=ko.join(process.cwd(),".nex","config.json");if(ut.existsSync(t))try{let e=JSON.parse(ut.readFileSync(t,"utf-8"));e.permissions&&(Rt={...ns,...e.permissions})}catch{}}function Bm(){let t=ko.join(process.cwd(),".nex"),e=ko.join(t,"config.json"),s={};if(ut.existsSync(e))try{s=JSON.parse(ut.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Rt,ut.existsSync(t)||ut.mkdirSync(t,{recursive:!0}),ut.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function ec(t){return Rt[t]||"ask"}function Hm(t,e){return["allow","ask","deny"].includes(e)?(Rt[t]=e,!0):!1}function Gm(t){return ec(t)}function zm(){return Object.entries(Rt).map(([t,e])=>({tool:t,mode:e}))}function Km(){Rt={...ns}}Za();tc.exports={getPermission:ec,setPermission:Hm,checkPermission:Gm,listPermissions:zm,loadPermissions:Za,savePermissions:Bm,resetPermissions:Km,DEFAULT_PERMISSIONS:ns}});var At=N((C$,ic)=>{var dt=require("fs"),ss=require("path"),E$=require("readline"),{C:B}=oe(),re=null,vo=!1,So=null,nc=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show","ask_user"]);function os(){return ss.join(process.cwd(),".nex","plans")}function sc(){let t=os();dt.existsSync(t)||dt.mkdirSync(t,{recursive:!0})}function Jm(t,e=[]){return re={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},re}function Ym(){return re}function Xm(t){vo=t}function Vm(){return vo}function Qm(){return!re||re.status!=="draft"?!1:(re.status="approved",re.updatedAt=new Date().toISOString(),!0)}function Zm(){return!re||re.status!=="approved"?!1:(re.status="executing",!0)}function ep(t,e){return!re||t<0||t>=re.steps.length?!1:(re.steps[t].status=e,re.updatedAt=new Date().toISOString(),re.steps.every(s=>s.status==="done"||s.status==="skipped")&&(re.status="completed"),!0)}function tp(t){if(!t)return`${B.dim}No active plan${B.reset}`;let e={draft:`${B.yellow}DRAFT${B.reset}`,approved:`${B.green}APPROVED${B.reset}`,executing:`${B.blue}EXECUTING${B.reset}`,completed:`${B.green}COMPLETED${B.reset}`},s=[];s.push(`
|
|
290
290
|
${B.bold}${B.cyan}Plan: ${t.task}${B.reset}`),s.push(`${B.dim}Status: ${e[t.status]||t.status}${B.reset}
|
|
291
291
|
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${B.green}\u2713${B.reset}`;break;case"in_progress":r=`${B.blue}\u2192${B.reset}`;break;case"skipped":r=`${B.dim}\u25CB${B.reset}`;break;default:r=`${B.dim} ${B.reset}`}s.push(` ${r} ${B.bold}Step ${n+1}:${B.reset} ${o.description}`),o.files.length>0&&s.push(` ${B.dim}Files: ${o.files.join(", ")}${B.reset}`)}return s.push(""),s.join(`
|
|
292
|
-
`)}function
|
|
292
|
+
`)}function np(t){if(t||(t=re),!t)return null;sc();let e=ss.join(os(),`${t.name}.json`);return dt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function sp(t){let e=ss.join(os(),`${t}.json`);if(!dt.existsSync(e))return null;try{let s=JSON.parse(dt.readFileSync(e,"utf-8"));return re=s,s}catch{return null}}function op(){sc();let t=os(),e=dt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(dt.readFileSync(ss.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function rp(t){So=t}function ip(){return So}function ap(){re=null,vo=!1,So=null}function cp(){return`
|
|
293
293
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
294
294
|
|
|
295
295
|
# Allowed Tools (read-only)
|
|
296
|
-
You may ONLY use these tools: ${[...
|
|
296
|
+
You may ONLY use these tools: ${[...nc].join(", ")}
|
|
297
297
|
Any other tool call will be blocked and returned with an error.
|
|
298
298
|
|
|
299
299
|
# Analysis Phase
|
|
@@ -324,42 +324,42 @@ Bullet list of potential issues and mitigations.
|
|
|
324
324
|
# Important
|
|
325
325
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
326
326
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
327
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
328
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let
|
|
329
|
-
`)}function ft(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function mt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function
|
|
330
|
-
`)}function
|
|
327
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var oc=["interactive","semi-auto","autonomous"],rc="interactive";function lp(t){return oc.includes(t)?(rc=t,!0):!1}function up(){return rc}ic.exports={createPlan:Jm,getActivePlan:Ym,setPlanMode:Xm,isPlanMode:Vm,approvePlan:Qm,startExecution:Zm,updateStep:ep,formatPlan:tp,savePlan:np,loadPlan:sp,listPlans:op,clearPlan:ap,getPlanModePrompt:cp,setPlanContent:rp,getPlanContent:ip,PLAN_MODE_ALLOWED_TOOLS:nc,setAutonomyLevel:lp,getAutonomyLevel:up,AUTONOMY_LEVELS:oc}});var gc=N((T$,hc)=>{var{C:y}=oe();function dp(t){if(!t)return"";let e=t.split(`
|
|
328
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${y.reset}`)}continue}if(n){s.push(` ${Co(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(4))}${y.reset}`);continue}if(r.startsWith("## ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(3))}${y.reset}`);continue}if(r.startsWith("# ")){s.push(`${y.bold}${y.cyan}${ft(r.substring(2))}${y.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${y.cyan}\u2022${y.reset} ${mt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let i=r.match(/^(\s*)(\d+)\.\s(.*)/);if(i){s.push(`${i[1]}${y.cyan}${i[2]}.${y.reset} ${mt(i[3])}`);continue}}s.push(mt(r))}return s.join(`
|
|
329
|
+
`)}function ft(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function mt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function Co(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?ac(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?cc(t):e==="json"||e==="jsonc"?lc(t):e==="python"||e==="py"?uc(t):e==="go"||e==="golang"?dc(t):e==="rust"||e==="rs"?fc(t):e==="css"||e==="scss"||e==="less"?mc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?pc(t):t:""}function ac(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${y.yellow}$1${y.reset}`),r=r.replace(e,`${y.magenta}$1${y.reset}`),r=r.replace(s,`${y.green}$&${y.reset}`),r=r.replace(n,`${y.dim}$1${y.reset}`),r}function cc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${y.cyan}$1${y.reset}`),r=r.replace(e,`$1${y.green}$2${y.reset}`),r=r.replace(n,`${y.yellow}$&${y.reset}`),r=r.replace(o,`${y.dim}$1${y.reset}`),r}function lc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${y.cyan}$1${y.reset}:`),r=r.replace(s,`: ${y.green}$1${y.reset}`),r=r.replace(n,`: ${y.yellow}$1${y.reset}`),r=r.replace(o,`: ${y.magenta}$1${y.reset}`),r}function uc(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${y.yellow}$1${y.reset}`),i=i.replace(e,`${y.magenta}$1${y.reset}`),i=i.replace(r,`${y.cyan}$1${y.reset}`),i=i.replace(s,`${y.green}$&${y.reset}`),i=i.replace(n,`${y.dim}$1${y.reset}`),i}function dc(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${y.yellow}$1${y.reset}`),i=i.replace(s,`${y.cyan}$1${y.reset}`),i=i.replace(e,`${y.magenta}$1${y.reset}`),i=i.replace(n,`${y.green}$&${y.reset}`),i=i.replace(o,`${y.dim}$1${y.reset}`),i}function fc(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${y.yellow}$1${y.reset}`),c=c.replace(s,`${y.cyan}$1${y.reset}`),c=c.replace(e,`${y.magenta}$1${y.reset}`),c=c.replace(i,`${y.yellow}$1${y.reset}`),c=c.replace(n,`${y.green}$&${y.reset}`),c=c.replace(o,`${y.dim}$1${y.reset}`),c}function mc(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${y.yellow}$1${y.reset}`),c=c.replace(o,`${y.yellow}$1${y.reset}`),c=c.replace(e,`$1${y.cyan}$2${y.reset}:`),c=c.replace(n,`$1${y.magenta}$&${y.reset}`),c=c.replace(r,`${y.dim}$1${y.reset}`),c}function pc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${y.dim}$1${y.reset}`),i=i.replace(n,`${y.green}$&${y.reset}`),i=i.replace(e,`<${y.magenta}$1${y.reset}`),i=i.replace(s,` ${y.cyan}$1${y.reset}=`),i=i.replace(r,`${y.yellow}$1${y.reset}`),i}function fp(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,c)=>` ${y.bold}${i.padEnd(s[c])}${y.reset} `).join("\u2502"),r=[];r.push(`${y.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${y.reset}`),r.push(`${y.dim}\u2502${y.reset}${o}${y.dim}\u2502${y.reset}`),r.push(`${y.dim}\u251C${n}\u2524${y.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${y.dim}\u2502${y.reset}`);r.push(`${y.dim}\u2502${y.reset}${c}${y.dim}\u2502${y.reset}`)}return r.push(`${y.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${y.reset}`),r.join(`
|
|
330
|
+
`)}function mp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,c=o>=100?y.green:o>50?y.yellow:y.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${y.dim}${"\u2591".repeat(i)}${y.reset} ${o}% (${e}/${s})`}var Eo=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
331
331
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
332
332
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
333
333
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${y.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${y.reset}
|
|
334
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
334
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Co(e,this.codeBlockLang)}
|
|
335
335
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(4))}${y.reset}
|
|
336
336
|
`);return}if(e.startsWith("## ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(3))}${y.reset}
|
|
337
337
|
`);return}if(e.startsWith("# ")){this._safeWrite(`${y.bold}${y.cyan}${ft(e.substring(2))}${y.reset}
|
|
338
338
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${y.cyan}\u2022${y.reset} ${mt(n)}
|
|
339
339
|
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${y.cyan}${s[2]}.${y.reset} ${mt(s[3])}
|
|
340
340
|
`);return}}this._safeWrite(`${mt(e)}
|
|
341
|
-
`)}};
|
|
341
|
+
`)}};hc.exports={renderMarkdown:dp,renderInline:mt,stripHeadingMarkers:ft,highlightCode:Co,highlightJS:ac,highlightBash:cc,highlightJSON:lc,highlightPython:uc,highlightGo:dc,highlightRust:fc,highlightCSS:mc,highlightHTML:pc,renderTable:fp,renderProgress:mp,StreamRenderer:Eo}});var Ao=N((R$,bc)=>{var{execSync:pp}=require("child_process"),To=require("path"),un=require("fs"),Ro=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function $c(){return To.join(process.cwd(),".nex","hooks")}function hp(){return To.join(process.cwd(),".nex","config.json")}function yc(){let t=hp();if(!un.existsSync(t))return{};try{return JSON.parse(un.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function rs(t){if(!Ro.includes(t))return[];let e=[],s=$c(),n=To.join(s,t);un.existsSync(n)&&e.push(n);let o=yc();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function wc(t,e={},s=3e4){try{return{success:!0,output:pp(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function gp(t,e={}){let s=rs(t);if(s.length===0)return[];let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=wc(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function $p(t){return rs(t).length>0}function yp(){let t=[];for(let e of Ro){let s=rs(e);s.length>0&&t.push({event:e,commands:s})}return t}function wp(){let t=$c();return un.existsSync(t)||un.mkdirSync(t,{recursive:!0}),t}bc.exports={HOOK_EVENTS:Ro,loadHookConfig:yc,getHooksForEvent:rs,executeHook:wc,runHooks:gp,hasHooks:$p,listHooks:yp,initHooksDir:wp}});var ce=N((M$,Nc)=>{var{C:_,Spinner:Ot,TaskProgress:bp,formatToolCall:xp,formatResult:_p,formatToolSummary:Sc,formatSectionHeader:kp,setActiveTaskProgress:A$}=oe(),{callStream:vp}=ge(),{parseToolArgs:Sp}=Tn(),{executeTool:Ep}=Ue(),{gatherProjectContext:Cp}=$o(),{fitToContext:Tp,forceCompress:Oo,getUsage:Rp,estimateTokens:Ap}=Re(),{autoSave:pt}=lt(),{getMemoryContext:Op}=Qe(),{checkPermission:Mp,setPermission:Np,savePermissions:Pp}=ln(),{confirm:Ec,setAllowAlwaysHandler:Lp}=Me(),{isPlanMode:ls,getPlanModePrompt:Ip,PLAN_MODE_ALLOWED_TOOLS:Cc,setPlanContent:qp}=At(),{StreamRenderer:jp}=gc(),{runHooks:xc}=Ao(),{routeMCPCall:Dp,getMCPToolDefinitions:Fp}=Nn(),{getSkillInstructions:Up,getSkillToolDefinitions:Wp,routeSkillCall:Bp}=Ht(),{trackUsage:Hp}=xt(),{validateToolArgs:Gp}=Us(),{filterToolsForModel:_c,getModelTier:zp,PROVIDER_DEFAULT_TIER:O$}=Zs(),{getConfiguredProviders:Kp,getActiveProviderName:Do,getActiveModelId:Tc,setActiveModel:Jp,MODEL_EQUIVALENTS:Fo}=ge(),Bo=require("fs"),Ho=require("path"),kc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Yp(t){let e=[],s;for(kc.lastIndex=0;(s=kc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Ho.resolve(n);Bo.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Xp(t){let e=Bo.readFileSync(t),s=Ho.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Rc(t){let e=Yp(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=Xp(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Mo=null,No=null,Po=null;function Mt(){if(Mo===null){let{TOOL_DEFINITIONS:t}=Ue();Mo=t}return No===null&&(No=Wp()),Po===null&&(Po=Fp()),[...Mo,...No,...Po]}var Uo=50;function Vp(t){Number.isFinite(t)&&t>0&&(Uo=t)}var is=()=>null;function Qp(t){is=t}var dn=null,Wo=null,Nt=null,as=new Map,Zp=1e4,eh=6e3,th=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function nh(t){return!t||typeof t!="string"?t:t.replace(th,(e,s)=>`${s}=***REDACTED***`)}function sh(t){let e=nh(t);if(Ap(e)>Zp)try{let{compressToolResult:n}=Re();return n(e,eh)}catch{return e}return e}function Ac(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(as.has(n))return as.get(n);let o=_c(t);return as.set(n,o),o}catch{return _c(t)}}function oh(){as.clear()}async function Oc(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Qe(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Bo.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function rh(){dn=null,Wo=null,Nt=null}var ih=new Set(["spawn_agents"]),Lo=5,Io=3,qo=2,ah=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),ch=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function lh(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Lp(t=>{Np(t,"allow"),Pp(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function uh(t){let e=t.function.name,s=Sp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Mt().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${_.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${_.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
342
342
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
343
343
|
|
|
344
344
|
Expected JSON schema for "${e}":
|
|
345
345
|
${u}
|
|
346
346
|
|
|
347
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
348
|
-
`)[0]}${
|
|
347
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Gp(e,s);if(!o.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
348
|
+
`)[0]}${_.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let r=o.corrected||s;if(o.corrected){let c=Object.keys(s),l=Object.keys(o.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${_.dim} \u2713 ${e}: corrected args (${u.join(", ")})${_.reset}`)}if(ls()&&!Cc.has(e))return console.log(`${_.yellow} \u2717 ${e}: blocked in plan mode${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=Mp(e);if(i==="deny")return console.log(`${_.red} \u2717 ${e}: denied by permissions${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(i==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Ec(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 dh(t,e,s={}){let n=await Bp(t,e);if(n!==null)return n;let o=await Dp(t,e);return o!==null?o:Ep(t,e,s)}function fh(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 jo(t,e=!1){e||console.log(xp(t.fnName,t.args)),xc("pre-tool",{tool_name:t.fnName});let s=await dh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
349
349
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
350
|
-
`)[0],
|
|
351
|
-
`)}function
|
|
352
|
-
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let
|
|
350
|
+
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Sc(t.fnName,t.args,o,i);return e||(console.log(_p(o)),console.log(c)),xc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:sh(o),tool_call_id:t.callId},summary:c}}async function mh(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],m=fh(d.fnName,d.args);u=`\u23FA ${d.fnName}${m?`(${m})`:""}`}else{let d=l.map(m=>m.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Ot(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await jo(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>jo(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)n[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,o.push(Sc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(ih.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:m}=await jo(u,e);n[l]=d,o.push(m)}else r.push(l)}if(await c(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var ee=[],vc=300,cs=[];function ph(t){cs.push(t.trim())}function hh(){return cs.length===0?null:cs.splice(0,cs.length).join(`
|
|
351
|
+
`)}function gh(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
352
|
+
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||(n?"English":null);return i&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
|
|
353
353
|
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
|
|
354
354
|
`)+`
|
|
355
355
|
|
|
356
|
-
`}function
|
|
356
|
+
`}function $h(){if(Nt!==null)return Nt;try{let e=Kp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:zp(r.id,o.name),name:r.name})));if(e.length<2)return Nt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
357
357
|
# Sub-Agent Model Routing
|
|
358
358
|
|
|
359
359
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
360
360
|
|---|---|---|
|
|
361
361
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
362
|
-
`;return Nt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Nt="",""}}async function
|
|
362
|
+
`;return Nt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Nt="",""}}async function Mc(){let t=await Oc();if(dn!==null&&t===Wo)return dn;let e=await Cp(process.cwd()),s=Op(),n=Up(),o=ls()?Ip():"",r=gh();return dn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
363
363
|
|
|
364
364
|
WORKING DIRECTORY: ${process.cwd()}
|
|
365
365
|
All relative paths resolve from this directory.
|
|
@@ -480,7 +480,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
480
480
|
- Good for: reading multiple files, analyzing separate modules.
|
|
481
481
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
482
482
|
- Max 5 parallel agents.
|
|
483
|
-
${
|
|
483
|
+
${$h()}
|
|
484
484
|
|
|
485
485
|
# Edit Reliability (Critical)
|
|
486
486
|
|
|
@@ -531,19 +531,18 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
531
531
|
- Include tags in frontmatter for better retrieval
|
|
532
532
|
- The user reviews all brain writes via /brain review or git diff
|
|
533
533
|
|
|
534
|
-
`,
|
|
535
|
-
`):[]).filter(
|
|
536
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function ht(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),
|
|
537
|
-
${
|
|
534
|
+
`,Wo=t,dn}function yh(){ee=[]}function wh(){ee.length>vc&&ee.splice(0,ee.length-vc)}function bh(){return ee.length}function xh(){return ee}function _h(t){ee=t}async function kh(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(m,f)=>new Promise(h=>{t(m,f,{cwd:s,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
|
|
535
|
+
`):[]).filter(m=>{let f=m.split(".").pop();return r.has(f)});if(i.length<3)return null;let c={};for(let m of i){let f=m.split(".").pop();c[f]=(c[f]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((m,f)=>f[1]-m[1]).slice(0,4).map(([m,f])=>`${f} .${m}`).join(" \xB7 ")}`,d=Ho.join(s,"package.json");if(e.existsSync(d))try{let m=JSON.parse(e.readFileSync(d,"utf-8")),f=Object.keys({...m.dependencies||{},...m.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),p=f.length>5?` +${f.length-5}`:"";u+=`
|
|
536
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function ht(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),i=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(s.size>0&&(i+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);i+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}i+=" \u2500\u2500",console.log(`
|
|
537
|
+
${_.dim} ${i}${_.reset}`),s.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${_.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function vh(){if(!process.stdout.isTTY)return{action:"quit"};let t=Do(),e=Tc(),s=Fo.fast?.[t],n=Fo.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${_.dim}(${e})${_.reset}`}),o&&i.push({key:"f",label:`Switch to ${_.bold}${s}${_.reset} ${_.dim}\u2014 fast, low latency${_.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${_.bold}${n}${_.reset} ${_.dim}\u2014 reliable tool-calling, medium speed${_.reset}`,model:n}),i.push({key:"q",label:`${_.dim}Quit${_.reset}`}),console.log(),console.log(`${_.yellow} Stream stale \u2014 all retries exhausted.${_.reset} What would you like to do?`);for(let c of i)console.log(` ${_.cyan}[${c.key}]${_.reset} ${c.label}`);return new Promise(c=>{let u=require("readline").createInterface({input:process.stdin,output:process.stdout});u.question(` ${_.yellow}> ${_.reset}`,d=>{u.close();let m=d.trim().toLowerCase(),f=i.find(h=>h.key===m);!f||f.key==="q"||!f.model&&f.key!=="r"?c({action:"quit"}):f.key==="r"?c({action:"retry"}):c({action:"switch",model:f.model,provider:t})})})}async function Sh(t){let e=Rc(t);ee.push({role:"user",content:e}),wh();let{setOnChange:s}=Bn(),n=null,o=0;s((de,A)=>{de==="create"?(n&&n.stop(),n=new bp(A.name,A.tasks),n.setStats({tokens:o}),n.start()):de==="update"&&n?n.updateTask(A.id,A.status):de==="clear"&&n&&(n.stop(),n=null)});let r=await Mc(),i=r;try{let{getBrainContext:de}=nn(),A=await de(t);A&&(i=r+`
|
|
538
538
|
`+A+`
|
|
539
|
-
`)}catch(
|
|
540
|
-
${
|
|
541
|
-
${
|
|
542
|
-
`),await t(c,
|
|
543
|
-
`)
|
|
544
|
-
`);process.stdout.write(
|
|
545
|
-
`);process.
|
|
546
|
-
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<a.length-1&&(l++,h());return}if(x.name==="return"){let O=e[a[l]];g(),r(O?O.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function Xh(t){let e=Gh(),s=Kh(),n=Jh(),o=[];for(let a of e)if(a.models.length!==0){o.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===s&&c.id===n;o.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await Fc(t,o,{title:"Select Model"});return r?(Yh(r),console.log(`${J.green}Switched to ${r}${J.reset}`),!0):(console.log(`${J.dim}Cancelled${J.reset}`),!1)}Uc.exports={pickFromList:Fc,showModelPicker:Xh}});var Ko=M((M$,Yc)=>{var zo=require("fs"),Vh=require("path"),{callChat:Bc}=pe(),{remember:Qh,listMemories:N$,recall:Zh}=Ve(),Go=4,eg=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
539
|
+
`)}catch(de){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",de.message)}let c=[{role:"system",content:i},...ee],l=new Ot("Thinking...");l.start();let d=ee.length===1?kh().catch(()=>null):Promise.resolve(null),m=Mt(),[{messages:f,compressed:h,compacted:p,tokensRemoved:g},w]=await Promise.all([Tp(c,m),d]),$=Rp(c,m);if(l.stop(),w&&console.log(`${_.dim}${w}${_.reset}`),p)console.log(`${_.dim} [context compacted \u2014 summary (~${g} tokens freed)]${_.reset}`);else if(h){let de=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${_.dim} [context compressed \u2014 ~${g} tokens freed (${de}%)]${_.reset}`)}$.percentage>85&&console.log(`${_.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${_.reset}`);let x=f,O=0,k=0,v=0,C=0,S=0,T=new Map,F=new Set,I=new Set,V=Date.now(),D,ne=Uo,ie=0,ue=10;e:for(;;){for(D=0;D<ne&&!is()?.aborted;D++){let A=!0,L=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let E=S>0?`Thinking... (step ${S+1})`:"Thinking...";L=new Ot(E),L.start()}let se=!0,z="",q=new jp,U,H=Date.now(),ae=!1,je=new AbortController,gt=setInterval(()=>{let E=Date.now()-H;if(E>=ch)q._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${_.reset}`),je.abort();else if(E>=ah&&!ae){ae=!0,q._clearCursorLine();let j=Fo.fast?.[Do()];console.log(`${_.yellow} \u26A0 No tokens received for ${Math.round(E/1e3)}s \u2014 waiting...${_.reset}`),j&&console.log(`${_.dim} \u{1F4A1} Ctrl+C \u2192 /model ${j} to switch to a faster model${_.reset}`)}},5e3),me="",ke=null;try{let E=Ac(Mt()),j=ls()?E.filter(pe=>Cc.has(pe.function.name)):E,$t=is(),W=new AbortController;$t&&$t.addEventListener("abort",()=>W.abort(),{once:!0}),je.signal.addEventListener("abort",()=>W.abort(),{once:!0}),U=await vp(x,j,{signal:W.signal,onToken:pe=>{H=Date.now(),ae=!1,me+=pe,process.stdout.isTTY?ke||(ke=setTimeout(()=>{me&&q&&q.push(me),me="",ke=null},50)):(q.push(me),me=""),se&&(n&&!n._paused?n.pause():L&&L.stop(),A||(A=!0),q.startCursor(),se=!1),z+=pe}})}catch(E){if(clearInterval(gt),ke&&(clearTimeout(ke),ke=null),me&&q&&(q.push(me),me=""),n&&!n._paused&&n.pause(),L&&L.stop(),q.stopCursor(),je.signal.aborted&&!is()?.aborted){if(v++,v>qo){if(C<1){C++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let qt=Mt(),{messages:jt,tokensRemoved:kl}=Oo(x,qt);x=jt,console.log(`${_.dim} [force-compressed \u2014 ~${kl} tokens freed]${_.reset}`),v=0,D--;continue}n&&(n.stop(),n=null);let he=await vh();if(he.action==="quit"){s(null),ht(S,T,F,I,V),pt(ee);break}he.action==="switch"&&(Jp(`${he.provider}:${he.model}`),console.log(`${_.green} \u2713 Switched to ${he.provider}:${he.model}${_.reset}`)),v=0,C=0,D--;continue}let W=v===1?3e3:5e3;if(v>=2&&C<1){C++,console.log(`${_.yellow} \u26A0 Stale retry ${v}/${qo} \u2014 force-compressing before retry...${_.reset}`);let he=Mt(),{messages:qt,tokensRemoved:jt}=Oo(x,he);x=qt,console.log(`${_.dim} [force-compressed \u2014 ~${jt} tokens freed]${_.reset}`)}else console.log(`${_.yellow} \u26A0 Stale retry ${v}/${qo} \u2014 retrying in ${W/1e3}s...${_.reset}`);let pe=new Ot(`Waiting ${W/1e3}s before retry...`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop(),D--;continue}if(E.name==="AbortError"||E.name==="CanceledError"||E.message?.includes("canceled")||E.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}let j=E.message;if(E.code==="ECONNREFUSED"||E.message.includes("ECONNREFUSED"))j="Connection refused \u2014 please check your internet connection or API endpoint";else if(E.code==="ENOTFOUND"||E.message.includes("ENOTFOUND"))j="Network error \u2014 could not reach the API server. Please check your connection";else if(E.code==="ETIMEDOUT"||E.message.includes("timeout"))j="Request timed out \u2014 the API server took too long to respond. Please try again";else if(E.message.includes("401")||E.message.includes("Unauthorized"))j="Authentication failed \u2014 please check your API key in the .env file";else if(E.message.includes("403")||E.message.includes("Forbidden"))j="Access denied \u2014 your API key may not have permission for this model";else if(E.message.includes("400")){let W=(E.message||"").toLowerCase(),pe=W.includes("context")||W.includes("token")||W.includes("length")||W.includes("too long")||W.includes("too many")||W.includes("prompt")||W.includes("size")||W.includes("exceeds")||W.includes("num_ctx")||W.includes("input");if(pe&&C<1){C++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let he=Mt(),{messages:qt,tokensRemoved:jt}=Oo(x,he);x=qt,console.log(`${_.dim} [force-compressed \u2014 ~${jt} tokens freed]${_.reset}`),D--;continue}pe?j="Context too long \u2014 force compression exhausted. Use /clear to start fresh":j="Bad request \u2014 the conversation may be too long or contain unsupported content. Try /clear and retry"}else E.message.includes("500")||E.message.includes("502")||E.message.includes("503")||E.message.includes("504")?j="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(E.message.includes("fetch failed")||E.message.includes("fetch"))&&(j="Network request failed \u2014 please check your internet connection");if(console.log(`${_.red} \u2717 ${j}${_.reset}`),E.message.includes("429")){if(O++,O>Lo){console.log(`${_.red} Rate limit: max retries (${Lo}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}let W=Math.min(1e4*Math.pow(2,O-1),12e4),pe=new Ot(`Rate limit \u2014 waiting ${Math.round(W/1e3)}s (retry ${O}/${Lo})`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop();continue}if(E.message.includes("socket disconnected")||E.message.includes("TLS")||E.message.includes("ECONNRESET")||E.message.includes("ECONNABORTED")||E.message.includes("ETIMEDOUT")||E.code==="ECONNRESET"||E.code==="ECONNABORTED"){if(k++,k>Io){console.log(`${_.red} Network error: max retries (${Io}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}let W=Math.min(2e3*Math.pow(2,k-1),3e4),pe=new Ot(`Network error \u2014 retrying in ${Math.round(W/1e3)}s (${k}/${Io})`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop(),D--;continue}n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}clearInterval(gt),O=0,k=0,se&&(n&&!n._paused&&n.pause(),L&&L.stop()),ke&&(clearTimeout(ke),ke=null),me&&q&&(q.push(me),me=""),z&&q.flush(),k=0,v=0,U&&U.usage&&(Hp(Do(),Tc(),U.usage.prompt_tokens||0,U.usage.completion_tokens||0),o+=(U.usage.prompt_tokens||0)+(U.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:ps,tool_calls:nt}=U,hs={role:"assistant",content:ps||""};if(nt&&nt.length>0&&(hs.tool_calls=nt),ee.push(hs),x.push(hs),!nt||nt.length===0){let E=(ps||"").trim().length>0||z.trim().length>0;if(!E&&S>0&&D<Uo-1){let j={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};x.push(j),ee.push(j);continue}if(ls()&&E){let j=(ps||z||"").trim();qp(j),lh(j),console.log(`
|
|
540
|
+
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);return}S++,S>1&&(A=!1);for(let E of nt){let j=E.function.name;T.set(j,(T.get(j)||0)+1)}let hn=await Promise.all(nt.map(E=>uh(E))),gs=n?{skipSpinner:!0,skipSummaries:!0}:{},ur=!gs.skipSummaries&&!A;ur&&(A=!0),n&&n._paused&&n.resume();let{results:dr,summaries:gn}=await mh(hn,!0,{...gs,skipSummaries:!0});if(!gs.skipSummaries)if(ur){let E=kp(hn,S);if(gn.length===1)console.log(E+gn[0]);else{console.log(E);for(let j of gn)console.log(j)}}else for(let E of gn)console.log(E);for(let E=0;E<hn.length;E++){let j=hn[E];if(!j.canExecute)continue;let $t=dr[E].content,W=!$t.startsWith("ERROR")&&!$t.includes("CANCELLED");W&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&F.add(j.args.path),W&&j.fnName==="read_file"&&j.args&&j.args.path&&I.add(j.args.path)}for(let E of dr)ee.push(E),x.push(E);let fr=hh();if(fr){let E={role:"user",content:`[User note mid-run]: ${fr}`};ee.push(E),x.push(E),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(D>=ne){n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);let{getActiveProviderName:de}=ge();if(de()==="ollama"&&ie<ue){ie++,ne=20,console.log(`${_.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ie}/${ue}) \u2500\u2500${_.reset}`);continue e}if(console.log(`
|
|
541
|
+
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await Ec(" Continue for 20 more turns?")){ne=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}Nc.exports={processInput:Sh,clearConversation:yh,getConversationLength:bh,getConversationMessages:xh,setConversationMessages:_h,setAbortSignalGetter:Qp,setMaxIterations:Vp,invalidateSystemPromptCache:rh,clearToolFilterCache:oh,getCachedFilteredTools:Ac,buildSystemPrompt:Mc,getProjectContextHash:Oc,buildUserContent:Rc,injectMidRunNote:ph}});var ge=N((N$,jc)=>{var{OllamaProvider:Eh}=Ar(),{OpenAIProvider:Ch}=Kr(),{AnthropicProvider:Th}=Vr(),{GeminiProvider:Rh}=ti(),{LocalProvider:Ah}=oi(),{checkBudget:Oh}=xt(),Go={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"}},Pc={};for(let[t,e]of Object.entries(Go))for(let s of Object.values(e))Pc[s]=t;function Lc(t,e){let s=Pc[t];return s&&Go[s][e]||t}var fe={},_e=null,le=null,fn=[];function Te(){if(Object.keys(fe).length>0)return;Pt("ollama",new Eh),Pt("openai",new Ch),Pt("anthropic",new Th),Pt("gemini",new Rh),Pt("local",new Ah);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;fe[t]?(_e=t,le=e||fe[t].defaultModel):(_e="ollama",le="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(fn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Pt(t,e){fe[t]=e}function Mh(t){return Te(),fe[t]||null}function zo(){return Te(),fe[_e]||null}function Nh(){return Te(),_e}function Ph(){return Te(),le}function Lh(){Te();let t=zo();if(!t)return{id:le,name:le,provider:_e};let e=t.getModel(le);return e?{...e,provider:_e}:{id:le,name:le,provider:_e}}function Ic(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(fe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Ih(t){Te();let{provider:e,model:s}=Ic(t);if(e){let o=fe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(_e=e,le=s,us(),!0):!1}let n=zo();if(n&&n.getModel(s))return le=s,us(),!0;for(let[o,r]of Object.entries(fe))if(r.getModel(s))return _e=o,le=s,us(),!0;return!1}function us(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ce();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Re();t()}catch{}}function qh(){Te();let t=new Set;for(let e of Object.values(fe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function jh(){return Te(),Object.entries(fe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===_e&&s.id===le}))}))}function Dh(){Te();let t=[];for(let[e,s]of Object.entries(fe)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function Fh(t){fn=Array.isArray(t)?t:[]}function Uh(){return[...fn]}function Wh(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function qc(t){let e=[_e,...fn.filter(r=>r!==_e)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],c=fe[i];if(!c||!c.isConfigured())continue;o++;let l=Oh(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Lc(le,i):le;return u&&d!==le&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
542
|
+
`),await t(c,i,d)}catch(u){if(s=u,Wh(u)&&r<e.length-1)continue;throw u}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Bh(t,e,s={}){return Te(),qc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Hh(t,e,s={}){if(Te(),s.provider){let n=fe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||le,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return qc(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Gh(){Te();let t=[];for(let[e,s]of Object.entries(fe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function zh(){for(let t of Object.keys(fe))delete fe[t];_e=null,le=null,fn=[]}jc.exports={registerProvider:Pt,getProvider:Mh,getActiveProvider:zo,getActiveProviderName:Nh,getActiveModelId:Ph,getActiveModel:Lh,setActiveModel:Ih,getModelNames:qh,parseModelSpec:Ic,listProviders:jh,listAllModels:Dh,callStream:Bh,callChat:Hh,getConfiguredProviders:Gh,setFallbackChain:Fh,getFallbackChain:Uh,resolveModelForProvider:Lc,MODEL_EQUIVALENTS:Go,_reset:zh}});var Fc=N((P$,Dc)=>{"use strict";var Kh="\x1B[2m",Jh="\x1B[0m";function Yh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Ko=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._lastOutputRow=1}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,s=1){return`\x1B[${e};${s}H`}_statusLine(){return Kh+"\u2500".repeat(this._cols)+Jh}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(l,...u){if(s._active&&typeof l=="string"){if(s._cursorOnInputRow){let m=l.replace(/\n/g,"");return m?n(m,...u):!0}let d=(l.match(/\n/g)||[]).length;d>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+d,s._scrollEnd))}return n(l,...u)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(l,...u){if(!s._active)return s._origStderrWrite(l,...u);if(typeof l=="string"&&l.includes("\r")){let d=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(d))}return s._origStderrWrite(l,...u)},this._origLog=console.log,this._origError=console.error;function o(...l){if(!s._active){s._origLog(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...l),s.drawFooter()}function r(...l){if(!s._active){s._origError(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...l),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(l){s._origSetPr(l),s._active&&s.drawFooter(l)},this._origPrompt=e.prompt.bind(e),e.prompt=function(l){if(!s._active)return s._origPrompt(l);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(l),s._cursorOnInputRow=!0};let i=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=i,i&&(e._refreshLine=function(){if(!s._active)return i();let l=s._cols,u=Yh(e._prompt||""),d=l-u-1;if(e.line.length<=d)return i();let m=e.line,f=e.cursor,h=Math.max(1,d-1),g=Math.max(0,f-h),w=(g>0?"\xAB":"")+m.slice(g,g+h+(g>0?0:1));e.line=w,e.cursor=w.length,i(),e.line=m,e.cursor=f}),e.on("line",l=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let c=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",c),this._offResize=()=>process.stdout.off("resize",c)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Dc.exports={StickyFooter:Ko}});var Bc=N((L$,Wc)=>{var{C:J}=oe(),{listProviders:Xh,getActiveProviderName:Vh,getActiveModelId:Qh,setActiveModel:Zh}=ge();function Uc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let i=e.map(($,x)=>$.isHeader?-1:x).filter($=>$>=0);if(i.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function m(){let $=i[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let f=0;function h(){if(f>0){process.stdout.write(`\x1B[${f}A`);for(let v=0;v<f;v++)process.stdout.write(`\x1B[2K
|
|
543
|
+
`);process.stdout.write(`\x1B[${f}A`)}let $=[];$.push(` ${J.bold}${J.cyan}${n}${J.reset}`),$.push(` ${J.dim}${o}${J.reset}`),$.push("");let{start:x,end:O}=m();x>0&&$.push(` ${J.dim}\u2191 more${J.reset}`);for(let v=x;v<O;v++){let C=e[v];if(C.isHeader){$.push(` ${J.bold}${J.dim}${C.label}${J.reset}`);continue}let S=i[l]===v,T=S?`${J.cyan}> `:" ",F=C.isCurrent?` ${J.yellow}<current>${J.reset}`:"";S?$.push(`${T}${J.bold}${C.label}${J.reset}${F}`):$.push(`${T}${J.dim}${C.label}${J.reset}${F}`)}O<e.length&&$.push(` ${J.dim}\u2193 more${J.reset}`);let k=$.join(`
|
|
544
|
+
`);process.stdout.write(k+`
|
|
545
|
+
`),f=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<i.length-1&&(l++,h());return}if(x.name==="return"){let O=e[i[l]];g(),r(O?O.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function eg(t){let e=Xh(),s=Vh(),n=Qh(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===s&&c.id===n;o.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Uc(t,o,{title:"Select Model"});return r?(Zh(r),console.log(`${J.green}Switched to ${r}${J.reset}`),!0):(console.log(`${J.dim}Cancelled${J.reset}`),!1)}Wc.exports={pickFromList:Uc,showModelPicker:eg}});var Xo=N((q$,Xc)=>{var Jo=require("fs"),tg=require("path"),{callChat:Hc}=ge(),{remember:ng,listMemories:I$,recall:sg}=Qe(),Yo=4,og=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
547
546
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
548
547
|
|
|
549
548
|
Return ONLY valid JSON in this exact format:
|
|
@@ -569,15 +568,15 @@ Rules:
|
|
|
569
568
|
- value: concise actionable instruction, max 120 chars
|
|
570
569
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
571
570
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
572
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
571
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Gc(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
573
572
|
|
|
574
|
-
`)}async function zc(t){if(t.filter(o=>o.role==="user").length<
|
|
573
|
+
`)}async function zc(t){if(t.filter(o=>o.role==="user").length<Yo)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Gc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:og},{role:"user",content:`Conversation to analyze:
|
|
575
574
|
|
|
576
|
-
${s}`}];try{let
|
|
577
|
-
`)?o+
|
|
578
|
-
`+
|
|
575
|
+
${s}`}];try{let i=((await Hc(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Kc(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!o||!r)continue;let i=sg(o);i!==r&&(ng(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Jc(t){if(!t||t.length===0)return[];let e=tg.join(process.cwd(),"NEX.md"),s="";try{Jo.existsSync(e)&&(s=Jo.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(i),o=o?o.endsWith(`
|
|
576
|
+
`)?o+i:o+`
|
|
577
|
+
`+i:i)}return n.length>0&&(o.endsWith(`
|
|
579
578
|
`)||(o+=`
|
|
580
|
-
`),
|
|
579
|
+
`),Jo.writeFileSync(e,o,"utf-8")),n}async function rg(t){let e=await zc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Kc(e.memories),n=Jc(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var ig=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
581
580
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
582
581
|
|
|
583
582
|
Return ONLY valid JSON in this exact format:
|
|
@@ -611,139 +610,139 @@ Rules:
|
|
|
611
610
|
---
|
|
612
611
|
- Maximum 3 documents per session. Quality over quantity.
|
|
613
612
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
614
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
613
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Yc(t){if(t.filter(o=>o.role==="user").length<Yo)return{documents:[],skip_reason:"Session too short"};let s=Gc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:ig},{role:"user",content:`Conversation to analyze:
|
|
615
614
|
|
|
616
|
-
${s}`}];try{let
|
|
615
|
+
${s}`}];try{let i=((await Hc(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function ag(t){let e=await Yc(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:n}=nn(),o=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
|
|
617
616
|
|
|
618
617
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
619
618
|
|
|
620
|
-
${
|
|
619
|
+
${i.content}`;s(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}Xc.exports={learnFromSession:rg,learnBrainFromSession:ag,reflectOnSession:zc,reflectBrain:Yc,applyMemories:Kc,applyNexAdditions:Jc,LEARN_MIN_MESSAGES:Yo}});var tl=N((D$,el)=>{var ye=require("fs"),It=require("path"),j$=require("os"),cg=require("readline"),{C:R}=oe(),Vc=".nex",Vo=null;function lg(t){Vo=t}function Se(t,e=""){let s=e?` ${R.dim}[${e}]${R.reset}`:"",n=` ${R.cyan}${t}${s}${R.reset}: `;return new Promise(o=>{let r=i=>{let c=i.trim()||e;o(c)};if(Vo)Vo.question(n,r);else{let i=cg.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function Lt(t,e=!0){return Se(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function Qc(t,e,s){let n=e.map((c,l)=>`${R.dim}${l+1})${R.reset} ${c}`).join(" ");console.log(` ${R.cyan}${t}${R.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await Se("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function ug(){let t=It.join(process.cwd(),Vc),e=It.join(t,"servers.json"),s={};if(ye.existsSync(e))try{s=JSON.parse(ye.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
621
620
|
${R.bold}${R.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${R.reset}`),console.log(`${R.bold}${R.cyan}\u2551 nex-code Server Setup Wizard \u2551${R.reset}`),console.log(`${R.bold}${R.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${R.reset}
|
|
622
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await
|
|
621
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await Lt("Add or update a server profile?",!0))){console.log(`${R.dim}No changes made.${R.reset}
|
|
623
622
|
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
624
|
-
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await
|
|
625
|
-
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${
|
|
626
|
-
Add another server?`,!1)}
|
|
623
|
+
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await Se("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${R.red} Name is required.${R.reset}`);continue}let u=await Se("Host / IP address");if(!u){console.log(`${R.red} Host is required.${R.reset}`);continue}let d=await Se("SSH user","root"),m=await Se("SSH port","22"),f=parseInt(m,10)||22,h=await Se("SSH key path (leave empty for SSH agent)",""),p=await Qc("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Lt("Allow sudo commands?",!0),w={host:u,user:d};f!==22&&(w.port=f),h&&(w.key=h),p!=="other"&&(w.os=p),g&&(w.sudo=!0),o[l]=w,console.log(`
|
|
624
|
+
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${f!==22?`:${f}`:""}${p!=="other"?` [${p}]`:""}`),r=await Lt(`
|
|
625
|
+
Add another server?`,!1)}ye.existsSync(t)||ye.mkdirSync(t,{recursive:!0}),ye.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
627
626
|
`,"utf-8"),console.log(`
|
|
628
|
-
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let
|
|
627
|
+
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=It.join(process.cwd(),".gitignore");ye.existsSync(i)&&(ye.readFileSync(i,"utf-8").includes(".nex/")||await Lt("Add .nex/ to .gitignore?",!0)&&(ye.appendFileSync(i,`
|
|
629
628
|
# nex-code server profiles
|
|
630
629
|
.nex/
|
|
631
|
-
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await
|
|
632
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
630
|
+
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await Lt(`
|
|
631
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await Zc(o,t),console.log(`
|
|
633
632
|
${R.dim}Use /servers to list profiles, /servers ping to check connectivity.${R.reset}
|
|
634
|
-
`)}async function
|
|
633
|
+
`)}async function Zc(t,e){let s=e||It.join(process.cwd(),Vc),n=It.join(s,"deploy.json"),o={};if(ye.existsSync(n))try{o=JSON.parse(ye.readFileSync(n,"utf-8"))}catch{}if(!t){let u=It.join(s,"servers.json");if(ye.existsSync(u))try{t=JSON.parse(ye.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
635
634
|
${R.bold}${R.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${R.reset}`),console.log(`${R.bold}${R.cyan}\u2551 Deploy Config Wizard \u2551${R.reset}`),console.log(`${R.bold}${R.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${R.reset}
|
|
636
|
-
`);let
|
|
637
|
-
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await
|
|
638
|
-
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${
|
|
639
|
-
Add another deploy config?`,!1)}
|
|
635
|
+
`);let i=Object.keys(o);i.length>0&&console.log(`${R.dim}Existing deploy configs: ${i.join(", ")}${R.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
636
|
+
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await Se("Config name (e.g. prod, staging)");if(!u){console.log(`${R.red} Name is required.${R.reset}`);continue}let d;r.length>0?d=await Qc("Target server",r,r[0]):d=await Se("Target server (profile name or user@host)");let m=await Se("Local path to sync (e.g. dist/ or ./build)","dist/"),f=await Se("Remote destination path (e.g. /var/www/app)");if(!f){console.log(`${R.red} Remote path is required.${R.reset}`);continue}let h=await Se("Deploy script to run after sync (leave empty to skip)",""),p=await Se("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],w={server:d,local_path:m,remote_path:f};h&&(w.deploy_script=h),g.length>0&&(w.exclude=g),c[u]=w;let $=m.endsWith("/")?m:`${m}/`;console.log(`
|
|
637
|
+
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${f}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await Lt(`
|
|
638
|
+
Add another deploy config?`,!1)}ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
640
639
|
`,"utf-8"),console.log(`
|
|
641
640
|
${R.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${R.reset}`),console.log(`${R.dim}Use: deploy prod (or with explicit params)${R.reset}
|
|
642
|
-
`)}
|
|
643
|
-
${
|
|
644
|
-
`)}function
|
|
645
|
-
${
|
|
646
|
-
${
|
|
647
|
-
${
|
|
648
|
-
${
|
|
649
|
-
${
|
|
650
|
-
${
|
|
651
|
-
${
|
|
652
|
-
${
|
|
653
|
-
${
|
|
654
|
-
${
|
|
655
|
-
${
|
|
656
|
-
|
|
657
|
-
${
|
|
658
|
-
${
|
|
659
|
-
${
|
|
660
|
-
${
|
|
661
|
-
${
|
|
662
|
-
|
|
663
|
-
${
|
|
664
|
-
${
|
|
665
|
-
${
|
|
666
|
-
${
|
|
667
|
-
${
|
|
668
|
-
${
|
|
669
|
-
|
|
670
|
-
${
|
|
671
|
-
${
|
|
672
|
-
${
|
|
673
|
-
${
|
|
674
|
-
|
|
675
|
-
${
|
|
676
|
-
${
|
|
677
|
-
${
|
|
678
|
-
${
|
|
679
|
-
${
|
|
680
|
-
${
|
|
681
|
-
|
|
682
|
-
${
|
|
683
|
-
${
|
|
684
|
-
${
|
|
685
|
-
${
|
|
686
|
-
|
|
687
|
-
${
|
|
688
|
-
${
|
|
689
|
-
${
|
|
690
|
-
${
|
|
691
|
-
${
|
|
692
|
-
${
|
|
693
|
-
${
|
|
694
|
-
|
|
695
|
-
${
|
|
696
|
-
${
|
|
697
|
-
${
|
|
698
|
-
|
|
699
|
-
${
|
|
700
|
-
${
|
|
701
|
-
${
|
|
702
|
-
${
|
|
703
|
-
|
|
704
|
-
${
|
|
705
|
-
`)}function
|
|
706
|
-
${
|
|
707
|
-
${
|
|
708
|
-
${
|
|
641
|
+
`)}el.exports={runServerWizard:ug,runDeployWizard:Zc,setWizardRL:lg}});var ol=N((F$,sl)=>{var dg=require("axios"),mn=require("fs"),nl=require("path"),fg="nex-code",Qo=nl.join(process.cwd(),".nex"),Zo=nl.join(Qo,"last-version-check");mn.existsSync(Qo)||mn.mkdirSync(Qo,{recursive:!0});async function mg(){try{let t=hg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};gg(e);let s=pg(),o=(await dg.get(`https://registry.npmjs.org/${fg}/latest`,{timeout:5e3})).data.version,r=$g(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function pg(){return $n().version}function hg(){try{if(mn.existsSync(Zo)){let t=mn.readFileSync(Zo,"utf8");return parseInt(t,10)}}catch{}return null}function gg(t){try{mn.writeFileSync(Zo,t.toString())}catch{}}function $g(t,e){try{let s=t.split(".").map(Number),n=e.split(".").map(Number);return s[0]>n[0]?!0:s[0]<n[0]?!1:s[1]>n[1]?!0:s[1]<n[1]?!1:s[2]>n[2]}catch{return!1}}sl.exports={checkForNewVersion:mg}});var wl=N((W$,yl)=>{var yg=require("readline"),tt=require("fs"),qe=require("path"),{C:a,banner:wg,cleanupTerminal:rl}=oe(),{listProviders:tr,getActiveProviderName:Ze,listAllModels:U$,setFallbackChain:bg,getFallbackChain:xg,getProvider:_g}=ge(),{flushAutoSave:il}=lt(),{getActiveModel:et,setActiveModel:al}=Tn(),{printContext:cl}=$o(),{loadAllSkills:kg,getSkillCommands:nr,handleSkillCommand:vg}=Ht(),{setReadlineInterface:Sg,setAutoConfirm:Eg,getAutoConfirm:ll}=Me(),{StickyFooter:Cg}=Fc(),fs=process.cwd(),Ke=null;function ul(){return Ke?.signal??null}var ms=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function dl(){let t=nr(),e=[...ms,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of ms)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
642
|
+
${a.dim}Type /help for detailed usage${a.reset}
|
|
643
|
+
`)}function fl(t){try{let e,s;t.endsWith("/")||t.endsWith(qe.sep)?(e=t,s=""):(e=qe.dirname(t),s=qe.basename(t)),e.startsWith("~")&&(e=qe.join(require("os").homedir(),e.slice(1)));let n=qe.isAbsolute(e)?e:qe.resolve(fs,e);if(!tt.existsSync(n)||!tt.statSync(n).isDirectory())return[];let o=tt.readdirSync(n,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||s&&!i.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(qe.sep)?t:qe.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function ml(t){if(t.startsWith("/")){let n=[...ms,...nr()],o=n.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:n.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[fl(s),s]:[[],t]}function pl(){console.log(`
|
|
644
|
+
${a.bold}${a.cyan}Commands:${a.reset}
|
|
645
|
+
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
646
|
+
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
647
|
+
${a.cyan}/providers${a.reset} ${a.dim}Show available providers and models${a.reset}
|
|
648
|
+
${a.cyan}/fallback [chain]${a.reset} ${a.dim}Show/set fallback chain (e.g. anthropic,openai,local)${a.reset}
|
|
649
|
+
${a.cyan}/tokens${a.reset} ${a.dim}Show token usage and context budget${a.reset}
|
|
650
|
+
${a.cyan}/costs${a.reset} ${a.dim}Show session token costs${a.reset}
|
|
651
|
+
${a.cyan}/budget [prov] [n]${a.reset}${a.dim}Show/set cost limits per provider${a.reset}
|
|
652
|
+
${a.cyan}/clear${a.reset} ${a.dim}Clear conversation context${a.reset}
|
|
653
|
+
${a.cyan}/context${a.reset} ${a.dim}Show project context${a.reset}
|
|
654
|
+
${a.cyan}/autoconfirm${a.reset} ${a.dim}Toggle auto-confirm for file changes${a.reset}
|
|
655
|
+
|
|
656
|
+
${a.bold}${a.cyan}Sessions:${a.reset}
|
|
657
|
+
${a.cyan}/save [name]${a.reset} ${a.dim}Save current session${a.reset}
|
|
658
|
+
${a.cyan}/load <name>${a.reset} ${a.dim}Load a saved session${a.reset}
|
|
659
|
+
${a.cyan}/sessions${a.reset} ${a.dim}List all saved sessions${a.reset}
|
|
660
|
+
${a.cyan}/resume${a.reset} ${a.dim}Resume last session${a.reset}
|
|
661
|
+
|
|
662
|
+
${a.bold}${a.cyan}Memory:${a.reset}
|
|
663
|
+
${a.cyan}/remember <text>${a.reset} ${a.dim}Save a memory (key=value or freeform)${a.reset}
|
|
664
|
+
${a.cyan}/forget <key>${a.reset} ${a.dim}Delete a memory${a.reset}
|
|
665
|
+
${a.cyan}/memory${a.reset} ${a.dim}Show all memories${a.reset}
|
|
666
|
+
${a.cyan}/learn${a.reset} ${a.dim}Reflect on this session and auto-update memory + NEX.md${a.reset}
|
|
667
|
+
${a.cyan}/optimize${a.reset} ${a.dim}Show context, memory health, and optimization tips${a.reset}
|
|
668
|
+
|
|
669
|
+
${a.bold}${a.cyan}Permissions:${a.reset}
|
|
670
|
+
${a.cyan}/permissions${a.reset} ${a.dim}Show tool permissions${a.reset}
|
|
671
|
+
${a.cyan}/allow <tool>${a.reset} ${a.dim}Auto-allow a tool${a.reset}
|
|
672
|
+
${a.cyan}/deny <tool>${a.reset} ${a.dim}Block a tool${a.reset}
|
|
673
|
+
|
|
674
|
+
${a.bold}${a.cyan}Planning:${a.reset}
|
|
675
|
+
${a.cyan}/plan [task]${a.reset} ${a.dim}Enter plan mode (analyze, don't execute)${a.reset}
|
|
676
|
+
${a.cyan}/plan status${a.reset} ${a.dim}Show current plan progress${a.reset}
|
|
677
|
+
${a.cyan}/plan approve${a.reset} ${a.dim}Approve current plan${a.reset}
|
|
678
|
+
${a.cyan}/plans${a.reset} ${a.dim}List saved plans${a.reset}
|
|
679
|
+
${a.cyan}/auto [level]${a.reset} ${a.dim}Set autonomy: interactive/semi-auto/autonomous${a.reset}
|
|
680
|
+
|
|
681
|
+
${a.bold}${a.cyan}Git:${a.reset}
|
|
682
|
+
${a.cyan}/commit [msg]${a.reset} ${a.dim}Smart commit (analyze diff, suggest message)${a.reset}
|
|
683
|
+
${a.cyan}/diff${a.reset} ${a.dim}Show current diff summary${a.reset}
|
|
684
|
+
${a.cyan}/branch [name]${a.reset} ${a.dim}Create feature branch${a.reset}
|
|
685
|
+
|
|
686
|
+
${a.bold}${a.cyan}Extensibility:${a.reset}
|
|
687
|
+
${a.cyan}/mcp${a.reset} ${a.dim}Show MCP servers and tools${a.reset}
|
|
688
|
+
${a.cyan}/mcp connect${a.reset} ${a.dim}Connect all configured MCP servers${a.reset}
|
|
689
|
+
${a.cyan}/hooks${a.reset} ${a.dim}Show configured hooks${a.reset}
|
|
690
|
+
${a.cyan}/skills${a.reset} ${a.dim}List loaded skills${a.reset}
|
|
691
|
+
${a.cyan}/skills enable${a.reset} ${a.dim}Enable a skill by name${a.reset}
|
|
692
|
+
${a.cyan}/skills disable${a.reset} ${a.dim}Disable a skill by name${a.reset}
|
|
693
|
+
|
|
694
|
+
${a.bold}${a.cyan}Tasks:${a.reset}
|
|
695
|
+
${a.cyan}/tasks${a.reset} ${a.dim}Show current task list${a.reset}
|
|
696
|
+
${a.cyan}/tasks clear${a.reset} ${a.dim}Clear all tasks${a.reset}
|
|
697
|
+
|
|
698
|
+
${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
699
|
+
${a.cyan}/undo${a.reset} ${a.dim}Undo last file change${a.reset}
|
|
700
|
+
${a.cyan}/redo${a.reset} ${a.dim}Redo last undone change${a.reset}
|
|
701
|
+
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
702
|
+
|
|
703
|
+
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
704
|
+
`)}function hl(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function er(){let t=tr(),e=Ze(),s=et();console.log(`
|
|
705
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${n.provider}${a.reset}${i}`);for(let c of n.models){let l=c.id===s.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function gl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return pl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Bc();await r(e)}else{let r=et(),i=Ze();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(o==="list")return er(),!0;if(al(o)){let r=et(),i=Ze();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${o}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return er(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=xg();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=o.split(",").map(i=>i.trim()).filter(Boolean);return bg(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=ce(),{getUsage:r}=Re(),{TOOL_DEFINITIONS:i}=Ue(),c=o(),l=r(c,i),u=et(),d=Ze();console.log(`
|
|
706
|
+
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let m=hl(l.percentage);return console.log(` ${m}`),console.log(`
|
|
707
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=xt();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
709
708
|
${o()}
|
|
710
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:
|
|
711
|
-
${
|
|
712
|
-
`)}else process.stdout.write(`${
|
|
709
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=xt(),d=n[0];if(!d){let h=o(),p=tr();console.log(`
|
|
710
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let w of p){let $=r(w.provider),x=h[w.provider];if(x!==void 0){g=!0;let O=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(O/100*k),C=k-v,T=`${O>=100?a.red:O>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(C)}${a.reset}`;console.log(` ${a.bold}${w.provider}:${a.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${O}%) ${T}`)}else w.provider==="ollama"||w.provider==="local"?console.log(` ${a.bold}${w.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${w.provider}:${a.reset} $${$.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let m=n[1];if(!m){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(m==="off"||m==="remove"||m==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let f=parseFloat(m);return isNaN(f)||f<=0?(console.log(`${a.red}Invalid amount: ${m}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,f),l(),console.log(`${a.green}Set ${d} budget limit: $${f.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=ce(),{clearHistory:i}=kt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=Xo();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let m=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${m} learning(s) saved${a.reset}
|
|
711
|
+
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
713
712
|
`)}).catch(()=>process.stdout.write(`
|
|
714
|
-
`))}return o(),
|
|
715
|
-
${
|
|
716
|
-
${
|
|
717
|
-
|
|
718
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${
|
|
719
|
-
${
|
|
720
|
-
${
|
|
721
|
-
${
|
|
722
|
-
${
|
|
723
|
-
`),console.log(p.content),!0):(console.log(`${
|
|
724
|
-
${
|
|
725
|
-
${
|
|
726
|
-
`),console.log($)):console.log(`${
|
|
727
|
-
${
|
|
728
|
-
${
|
|
713
|
+
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await cl(fs),!0;case"/autoconfirm":{let o=!ll();return Eg(o),console.log(`${a.green}Auto-confirm: ${o?"ON":"OFF"}${a.reset}`),o&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:o}=lt(),{getConversationMessages:r}=ce(),i=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=et(),u=Ze();return o(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=lt(),{setConversationMessages:r}=ce(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=lt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
714
|
+
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=lt(),{setConversationMessages:r}=ce(),i=o();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:o}=Qe(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=Qe(),r=n.join(" ").trim();return r?(o(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=Qe(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
715
|
+
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:m}=nn(),f=n[0],h=n.slice(1).join(" ").trim();switch(f){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let p=h.indexOf(" ");if(p<0){i(h,`# ${h}
|
|
716
|
+
|
|
717
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),w=h.substring(p+1);i(g,w),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
718
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),w=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(w)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(w)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),O=Array.isArray(x.tags)?x.tags.join(", "):"",k=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,v=$.modified.toLocaleDateString();console.log(` ${a.cyan}${$.name.padEnd(g+2)}${a.reset}${a.dim}${O.substring(0,w-1).padEnd(w)}${k.padStart(7)} ${v}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await m(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
719
|
+
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let w=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
720
|
+
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${w})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
721
|
+
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
722
|
+
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=Me();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let w=c(h);return console.log(w?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),w=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${w} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),w=require("path"),$=w.join(process.cwd(),".nex","brain",".brain-index.json"),x=w.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
723
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let O=p.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${O<1024?O+"B":(O/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),w=g(p);try{let{stdout:$}=await w("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
724
|
+
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
725
|
+
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),w=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(w))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=$[0],{exec:O}=require("child_process"),{promisify:k}=require("util"),v=k(O);try{await v(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${x.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let p=o();if(p.length===0)console.log(`
|
|
726
|
+
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
727
|
+
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
729
728
|
`);else{console.log(`
|
|
730
|
-
${
|
|
731
|
-
${
|
|
732
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
733
|
-
${
|
|
734
|
-
`);let h=u.percentage>80?
|
|
735
|
-
${
|
|
736
|
-
${
|
|
737
|
-
${
|
|
738
|
-
${
|
|
739
|
-
${
|
|
740
|
-
${
|
|
741
|
-
${
|
|
742
|
-
${
|
|
743
|
-
${
|
|
744
|
-
${
|
|
745
|
-
${
|
|
746
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
729
|
+
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:w}=r(g.name),$=Array.isArray(w.tags)?` [${w.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
|
|
730
|
+
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
731
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Xo(),{getConversationMessages:i}=ce(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let m=u.applied&&u.applied.length>0,f=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!m&&!f&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(m){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:w}of u.applied){let $=w==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}${a.reset} = ${g}`)}}if(f){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:w}of d.written){let $=w==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=ce(),{getUsage:r}=Re(),{TOOL_DEFINITIONS:i}=Ue(),{listMemories:c}=Qe(),l=o(),u=r(l,i),d=et(),m=Ze(),f=c();console.log(`
|
|
732
|
+
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
733
|
+
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
734
|
+
${a.bold}Memory:${a.reset} ${f.length} entries`),f.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let O=[...f].sort((C,S)=>new Date(S.updatedAt)-new Date(C.updatedAt))[0],k=O?Math.round((Date.now()-new Date(O.updatedAt))/6e4):null,v=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${v}${a.reset}`),f.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${f.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
735
|
+
${a.bold}Active Model:${a.reset} ${m}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
736
|
+
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
737
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of w)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,formatPlan:u}=At(),{invalidateSystemPromptCache:d}=ce(),m=n.join(" ").trim();if(m==="status"){let f=o();return console.log(u(f)),!0}if(m==="approve"){if(r()){i(),c(!1),d();let f=!!l();console.log(`${a.green}${a.bold}Plan approved!${a.reset} ${f?"Executing the planned steps...":"Starting execution..."}`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`)}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),d(),console.log(`
|
|
738
|
+
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
739
|
+
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
740
|
+
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
741
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:o}=At(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
742
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=At(),c=n.join(" ").trim();return c?(r(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=ln(),r=o();console.log(`
|
|
743
|
+
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
|
|
744
|
+
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
745
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=ln(),i=n.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=ln(),i=n.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:c}=it(),{confirm:l}=Me();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let m=await c();if(console.log(m),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=it();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=it(),{processInput:i}=ce(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),m=`## Review Protocol
|
|
747
746
|
|
|
748
747
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
749
748
|
|
|
@@ -778,78 +777,78 @@ For each issue, include:
|
|
|
778
777
|
+ fixed code
|
|
779
778
|
\`\`\`${l?`
|
|
780
779
|
|
|
781
|
-
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,
|
|
780
|
+
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,f;if(u)f=`Do a thorough code review of \`${u}\`.
|
|
782
781
|
|
|
783
|
-
${
|
|
782
|
+
${m}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([r(!1),r(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;f=`Review the following code diff.
|
|
784
783
|
|
|
785
|
-
${
|
|
784
|
+
${m}
|
|
786
785
|
|
|
787
786
|
\`\`\`diff
|
|
788
787
|
${g.substring(0,2e4)}
|
|
789
|
-
\`\`\``}return await
|
|
790
|
-
${
|
|
791
|
-
${
|
|
792
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
793
|
-
${
|
|
794
|
-
${
|
|
795
|
-
${
|
|
796
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Bn();return n.join(" ").trim()==="clear"?(r(),console.log(`${
|
|
788
|
+
\`\`\``}return await i(f),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=it();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:i}=Nn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=o();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
789
|
+
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
790
|
+
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
791
|
+
`),!0}case"/hooks":{let{listHooks:o}=Ao(),r=o();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
792
|
+
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=Ht(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=o();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
793
|
+
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,m=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,f=[];u.commands>0&&f.push(`${u.commands} cmd`),u.tools>0&&f.push(`${u.tools} tools`);let h=f.length>0?` \u2014 ${f.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${m}${h}`)}return console.log(`
|
|
794
|
+
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
795
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Bn();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
797
796
|
`+o()+`
|
|
798
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
799
|
-
${
|
|
800
|
-
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${
|
|
801
|
-
${
|
|
802
|
-
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:
|
|
803
|
-
${
|
|
804
|
-
`);try{let{stdout:
|
|
805
|
-
`).filter(Boolean);console.log(`${
|
|
806
|
-
`),!0}try{let{stdout:
|
|
807
|
-
`).filter(Boolean),h=
|
|
808
|
-
`);let w=
|
|
809
|
-
`)}catch(
|
|
810
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:
|
|
811
|
-
${
|
|
812
|
-
`),!0;if(n[0]==="ping"){let
|
|
813
|
-
${
|
|
814
|
-
${
|
|
815
|
-
${
|
|
816
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
817
|
-
${
|
|
818
|
-
`).forEach(w=>console.log(` ${
|
|
819
|
-
${
|
|
820
|
-
${
|
|
797
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=kt(),i=o();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=kt(),i=o();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:i}=kt(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
798
|
+
${a.bold}File Change History${a.reset}
|
|
799
|
+
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
800
|
+
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
801
|
+
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=m=>l?`${u}"${m.replace(/"/g,'\\"')}"`:m;console.log(`
|
|
802
|
+
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
803
|
+
`);try{let{stdout:m}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),f=m.trim().split(`
|
|
804
|
+
`).filter(Boolean);console.log(`${a.bold}Namespaces (${f.length}):${a.reset}`);for(let h of f)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
805
|
+
`),!0}try{let{stdout:m}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),f=m.trim().split(`
|
|
806
|
+
`).filter(Boolean),h=f.filter($=>$.includes("Running")).length,p=f.filter($=>$.includes("Pending")).length,g=f.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${f.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
807
|
+
`);let w=f.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(w.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of w)console.log(` ${a.red}${$}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
808
|
+
`)}catch(m){console.log(`${a.dim}Could not list pods: ${m.message}${a.reset}
|
|
809
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Et(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
810
|
+
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
|
|
811
|
+
`),!0;if(n[0]==="ping"){let m=n[1]?[n[1]]:l;return console.log(`
|
|
812
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(m.map(async f=>{if(!c[f]){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 unknown profile`);return}try{let h={...c[f],_name:f},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${f} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${f} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Et();console.log(`
|
|
813
|
+
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let m of l)console.log(` ${a.green}${m}${a.reset} ${a.dim}${d(m,c[m])}${a.reset}`);return console.log(`
|
|
814
|
+
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
815
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Et(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=n[0]==="-a"||n[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),m=[["local",null],...Object.entries(d)];console.log(`
|
|
816
|
+
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[f,h]of m){let p=f==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${f}${a.reset}`;try{let g;if(f==="local"){let{stdout:w}=await l(u,{timeout:8e3});g=(w||"").trim()}else{let w=await r(h,u,{timeout:1e4});if(g=[w.stdout,w.stderr].filter(Boolean).join("").trim(),w.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${w.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
817
|
+
`).forEach(w=>console.log(` ${a.dim}${w}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Xs(),r=o(),i=Object.keys(r),c=n[0];if(c&&i.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=Ue();console.log(`
|
|
818
|
+
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let m=await d("deploy",{...u,dry_run:l});return console.log(m),!0}if(i.length===0)return console.log(`
|
|
819
|
+
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
821
820
|
`),!0;console.log(`
|
|
822
|
-
${
|
|
823
|
-
${
|
|
824
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:
|
|
825
|
-
${
|
|
826
|
-
`).filter(Boolean).slice(-
|
|
827
|
-
`)}catch{}}function
|
|
828
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=
|
|
829
|
-
${
|
|
830
|
-
`),process.exit(1));let
|
|
831
|
-
`),await
|
|
832
|
-
${
|
|
833
|
-
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{
|
|
834
|
-
${
|
|
835
|
-
${
|
|
836
|
-
`),
|
|
837
|
-
`).replace(/\r/g,"").trim();if(
|
|
838
|
-
`).length,
|
|
839
|
-
`)),F()}if(
|
|
840
|
-
`)),!0}if(U){let H=
|
|
841
|
-
`)),F()}if(
|
|
842
|
-
`)),!0}return A.call(process.stdin,L,...se)}}let
|
|
843
|
-
\x1B[2K ${
|
|
844
|
-
\x1B[2K ${
|
|
845
|
-
`)}return}if(
|
|
846
|
-
`).trim();if(
|
|
847
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
848
|
-
`).trim();if(
|
|
849
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
850
|
-
`)
|
|
851
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
852
|
-
${
|
|
821
|
+
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",m=`${u.server}:${u.remote_path}`,f=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${m}${a.reset}${f}`)}return console.log(`
|
|
822
|
+
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
823
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=tl();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":console.log(`
|
|
824
|
+
${a.dim}Bye!${a.reset}`),process.exit(0);default:return vg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var sr=1e3;function or(){return qe.join(process.cwd(),".nex","repl_history")}function $l(){try{let t=or();if(tt.existsSync(t))return tt.readFileSync(t,"utf-8").split(`
|
|
825
|
+
`).filter(Boolean).slice(-sr)}catch{}return[]}function ds(t){try{let e=or(),s=qe.dirname(e);tt.existsSync(s)||tt.mkdirSync(s,{recursive:!0}),tt.appendFileSync(e,t+`
|
|
826
|
+
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=At(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=Ze(),r=et(),i=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(i),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var rr="\x1B[200~",ir="\x1B[201~";function Tg(t){return typeof t=="string"&&t.includes(rr)}function Rg(t){return typeof t=="string"&&t.includes(ir)}function pn(t){return typeof t!="string"?t:t.split(rr).join("").split(ir).join("")}async function Ag(){if(!_g("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:s}=require("util");return await s(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),al("local:llama3"),!0}catch{return!1}}async function Og(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ce();t(ul);let o=tr().some(A=>A.configured),r=(async()=>{kg();let A=et(),L=Ze();return{model:A,providerName:L}})(),i=(async()=>o?!0:await Ag()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
827
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=ol();return await A()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
828
|
+
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
829
|
+
`),process.exit(1));let m=$l(),f=yg.createInterface({input:process.stdin,output:process.stdout,prompt:Ee(),completer:ml,history:m,historySize:sr});Sg(f);let h=new Cg;h.activate(f);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;wg(p,fs,{yolo:ll()}),d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
830
|
+
`),await cl(fs);let g=!1,w=0,$=!1,x=null;function O(){il(),h.deactivate(),rl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write(`
|
|
831
|
+
${a.dim}Bye!${a.reset}
|
|
832
|
+
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{il()}),f.on("SIGINT",()=>{if(rl(),g){if(w++,w>=2){O();return}Ke&&Ke.abort();let{cancelPendingAskUser:A}=Ue();A(),console.log(`
|
|
833
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),g=!1,f.setPrompt(Ee()),f.prompt();return}$?O():($=!0,process.stdout.write(`
|
|
834
|
+
${a.dim} (Press Ctrl+C again to exit)${a.reset}
|
|
835
|
+
`),f.setPrompt(Ee()),f.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||O()});let k=!1,v=[],C=0,S={},T=!1;function F(){let A=v.join(`
|
|
836
|
+
`).replace(/\r/g,"").trim();if(v=[],k=!1,!A)return!0;C++,T=!0;let L=C;S[L]=A;let se=A.split(`
|
|
837
|
+
`).length,z=se>1?`[Pasted content #${L} \u2014 ${se} lines]`:`[Pasted content #${L}]`,q=f.line||"",U=q&&!q.endsWith(" ")?" ":"",H=q+U+z;return f.setPrompt(Ee()),f.prompt(),f.line=H,f.cursor=H.length,f._refreshLine(),!0}function I(A){return A.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,se)=>S[Number(se)]||"")}function V(){C=0,S={},T=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let A=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(L,...se){if(L!=="data")return A.call(process.stdin,L,...se);let z=se[0];if(Buffer.isBuffer(z)&&(z=z.toString("utf8")),typeof z!="string")return A.call(process.stdin,L,...se);let q=z.includes(rr),U=z.includes(ir);if(q&&U){let H=pn(z);return H&&v.push(...H.split(`
|
|
838
|
+
`)),F()}if(q){k=!0,v=[];let H=pn(z);return H&&v.push(...H.split(`
|
|
839
|
+
`)),!0}if(U){let H=pn(z);return H&&v.push(...H.split(`
|
|
840
|
+
`)),F()}if(k){let H=pn(z);return H&&v.push(...H.split(`
|
|
841
|
+
`)),!0}return A.call(process.stdin,L,...se)}}let D=0;function ne(){if(D>0){let A="";for(let L=0;L<D;L++)A+="\x1B[1B\x1B[2K";A+=`\x1B[${D}A`,process.stdout.write(A),D=0}}function ie(A){let L=[...ms,...nr()].filter(ae=>ae.cmd.startsWith(A));if(!L.length||L.length===1&&L[0].cmd===A)return;let se=10,z=L.slice(0,se),q=Math.max(...z.map(ae=>ae.cmd.length)),U="";for(let{cmd:ae,desc:je}of z){let gt=ae.substring(0,A.length),me=ae.substring(A.length),ke=" ".repeat(Math.max(0,q-ae.length+2));U+=`
|
|
842
|
+
\x1B[2K ${a.cyan}${gt}${a.reset}${a.dim}${me}${ke}${je}${a.reset}`}D=z.length,L.length>se&&(U+=`
|
|
843
|
+
\x1B[2K ${a.dim}\u2026 +${L.length-se} more${a.reset}`,D++);let H=f._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;U+=`\x1B[${D}A\x1B[${H+f.cursor+1}G`,process.stdout.write(U)}process.stdin.isTTY&&process.stdin.on("keypress",(A,L)=>{ne(),!(L&&(L.name==="tab"||L.name==="return"))&&setImmediate(()=>{f.line&&f.line.startsWith("/")&&ie(f.line)})});let ue=null,de=`${a.dim}...${a.reset} `;f.setPrompt(Ee()),f.prompt(),f.on("line",async A=>{if(ne(),Object.keys(S).length>0&&(A=I(A),V(),f.setPrompt(Ee())),g){let q=A.trim();if(q){let{injectMidRunNote:U}=ce();U(q),process.stdout.write(`${a.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${a.reset}
|
|
844
|
+
`)}return}if(ue!==null){if(ue._mode==="triple"){if(A.trim()==='"""'){let q=ue.join(`
|
|
845
|
+
`).trim();if(ue=null,q){ds(q.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(q)}catch(H){if(!Ke?.signal?.aborted){let ae=H.message?.split(`
|
|
846
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ae}${a.reset}`)}}g=!1;let U=se();U>0&&process.stdout.write(`${a.gray}[${U} messages] ${a.reset}`)}f.setPrompt(Ee()),f.prompt();return}ue.push(A),f.setPrompt(de),f.prompt();return}if(A.endsWith("\\"))ue.push(A.slice(0,-1));else{ue.push(A);let q=ue.join(`
|
|
847
|
+
`).trim();if(ue=null,q){ds(q.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(q)}catch(ae){if(!Ke?.signal?.aborted){let je=ae.message?.split(`
|
|
848
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${je}${a.reset}`)}}let{getConversationLength:U}=ce();g=!1;let H=U();H>0&&process.stdout.write(`${a.gray}[${H} messages] ${a.reset}`)}f.setPrompt(Ee()),f.prompt();return}f.setPrompt(de),f.prompt();return}if(A.trim()==='"""'||A.trim().startsWith('"""')){let q=A.trim().substring(3);ue=q?[q]:[],ue._mode="triple",f.setPrompt(de),f.prompt();return}if(A.endsWith("\\")){ue=[A.slice(0,-1)],ue._mode="backslash",f.setPrompt(de),f.prompt();return}let L=A.trim();if(!L){f.setPrompt(Ee()),f.prompt();return}if(ds(L),L==="/"){dl(),f.setPrompt(Ee()),f.prompt();return}if(L.startsWith("/")){await gl(L,f),f.setPrompt(Ee()),f.prompt();return}{let q="\x1B[48;5;237m",U=process.stdout.columns||80;L.split(`
|
|
849
|
+
`).forEach((ae,je)=>{let gt=je===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",me=2+ae.length,ke=" ".repeat(Math.max(0,U-me));console.log(`${q}${gt} ${ae}${ke}\x1B[0m`)})}g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(L)}catch(q){if(!Ke?.signal?.aborted){let U=q.message?.split(`
|
|
850
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${U}${a.reset}`)}}g=!1;let{getConversationLength:se}=ce(),z=se();z>0&&process.stdout.write(`${a.gray}[${z} messages] ${a.reset}`),f.setPrompt(Ee()),f.prompt()}),f.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
851
|
+
${a.dim}Bye!${a.reset}`),process.exit(0)})}yl.exports={startREPL:Og,getPrompt:Ee,loadHistory:$l,appendHistory:ds,getHistoryPath:or,HISTORY_MAX:sr,showCommandList:dl,completer:ml,completeFilePath:fl,handleSlashCommand:gl,showProviders:er,showHelp:pl,renderBar:hl,hasPasteStart:Tg,hasPasteEnd:Rg,stripPasteSequences:pn,getAbortSignal:ul}});var _l=require("path");require("dotenv").config({path:_l.join(__dirname,"..",".env")});require("dotenv").config();var te=process.argv.slice(2);(te.includes("--help")||te.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
853
852
|
|
|
854
853
|
Options:
|
|
855
854
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -862,4 +861,4 @@ Options:
|
|
|
862
861
|
--json Output result as JSON (for CI parsing)
|
|
863
862
|
-h, --help Show this help
|
|
864
863
|
-v, --version Show version
|
|
865
|
-
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=$n();console.log(t.version),process.exit(0)}var
|
|
864
|
+
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=$n();console.log(t.version),process.exit(0)}var Mg=te.includes("--yolo")||te.includes("-yolo");if(Mg){let{setAutoConfirm:t}=Me();t(!0)}var ar=te.indexOf("--model");if(ar!==-1&&te[ar+1]){let{setActiveModel:t}=ge();t(te[ar+1])}var cr=te.indexOf("--max-turns");if(cr!==-1&&te[cr+1]){let t=parseInt(te[cr+1],10);if(t>0){let{setMaxIterations:e}=ce();e(t)}}else try{let t=require("fs"),e=_l.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(s.maxIterations,10);if(n>0){let{setMaxIterations:o}=ce();o(n)}}}catch{}function lr(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}function bl(t){if(te.includes("--auto")){let{setAutoConfirm:o}=Me();o(!0)}if(!te.includes("--model")){let{setActiveModel:o}=ge(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=ce();s(t).then(()=>{if(te.includes("--json")){let r=n().filter(i=>i.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{te.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var xl=te.indexOf("--prompt-file");if(xl!==-1){let t=te[xl+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),te.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}lr(),bl(s)}else{let t=te.indexOf("--task");if(t!==-1){let e=te[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),lr(),bl(e)}else{lr();let{startREPL:e}=wl();e()}}
|