nex-code 0.3.19 → 0.3.22
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 +8 -1
- package/dist/nex-code.js +220 -210
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,125 +1,127 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
2
|
+
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Kt=O((vp,nc)=>{nc.exports={name:"nex-code",version:"0.3.22",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 vo=O((Sp,_o)=>{var R={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"},bo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xo=["\u273D","\u2726","\u2727","\u2726"],zn=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=bo[this.frame%bo.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=` ${R.dim}${o}m ${String(r).padStart(2,"0")}s${R.reset}`}else n>=1&&(s=` ${R.dim}${n}s${R.reset}`)}process.stderr.write(`\x1B[2K\r${R.cyan}${e}${R.reset} ${R.dim}${this.text}${R.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}},ko=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Kn=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=ko[this.frame%ko.length],s=this._formatElapsed(),n=s?` ${R.dim}${s}${R.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let a,c;switch(this.statuses[r]){case"done":a=`${R.green}\u2713${R.reset}`,c=R.dim;break;case"error":a=`${R.red}\u2717${R.reset}`,c=R.dim;break;default:a=`${R.cyan}${e}${R.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${a} ${c}${this.labels[r]}${R.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
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?` ${R.dim}${e}${R.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${R.green}\u2713${R.reset}`;break;case"error":r=`${R.red}\u2717${R.reset}`;break;default:r=`${R.yellow}\u25CB${R.reset}`}let a=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${R.dim}${this.labels[o]}${R.reset}${a}
|
|
5
|
-
`}process.stderr.write(n)}},
|
|
6
|
-
`;for(let
|
|
5
|
+
`}process.stderr.write(n)}},Jt={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Yt={done:R.green,in_progress:R.cyan,pending:R.dim,failed:R.red},Ie=null,Jn=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=xo[this.frame%xo.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${R.dim}(${o})${R.reset}`:"",a=`\x1B[2K${R.cyan}${e}${R.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=Jt[l.status]||Jt.pending,f=Yt[l.status]||Yt.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${m}
|
|
7
7
|
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Ie=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,Ie===this&&(Ie=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(
|
|
11
|
-
`;for(let
|
|
12
|
-
`}process.stderr.write(a)}};function
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
14
|
-
`);return o>0&&(
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80)
|
|
17
|
-
|
|
18
|
-
`).length
|
|
19
|
-
`).
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,a=`\x1B[2K${R.green}\u2714${R.reset} ${this.name} ${R.dim}(${e} \xB7 ${r})${R.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Jt[l.status]||Jt.pending,f=Yt[l.status]||Yt.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${R.dim}${m}${R.reset}
|
|
12
|
+
`}process.stderr.write(a)}};function sc(t){Ie=t}function oc(){return Ie}function rc(){Ie&&(Ie.stop(),Ie=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}_o.exports={C:R,Spinner:zn,MultiProgress:Kn,TaskProgress:Jn,setActiveTaskProgress:sc,getActiveTaskProgress:oc,cleanupTerminal:rc}});var To=O((Tp,So)=>{var V={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 ic(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=s?`${V.dim}(${s})${V.reset}`:"";return`${V.cyan}\u23FA${V.reset} ${V.bold}${t}${V.reset}${n}`}function ac(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${V.dim} \u23BF ${V.reset}`,a=" ",c=n.map((l,u)=>`${u===0?r:a}${V.green}${l}${V.reset}`).join(`
|
|
14
|
+
`);return o>0&&(c+=`
|
|
15
|
+
${V.gray} \u2026+${o} more lines${V.reset}`),c}function cc(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 lc(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
+
${V.dim}${c[1].substring(0,100)}${V.reset}`:"";return` ${V.red}\u23BF ${a}${V.reset}${l}`}let r;switch(t){case"read_file":{let a=o.split(`
|
|
18
|
+
`).filter(Boolean),c=a.length,l=a[a.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let a=(e.content||"").split(`
|
|
19
|
+
`).length;r=`Wrote ${a} line${a!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let a=(e.patches||[]).length;r=`Applied ${a} patch${a!==1?"es":""}`;break}case"bash":{let a=o.match(/^EXIT (\d+)/);if(a){let c=a[1],l=o.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=o.split(`
|
|
20
|
+
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=o.split(`
|
|
21
|
+
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let a=o.split(`
|
|
20
22
|
`).filter(Boolean).length;r=`${a} match${a!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let a=o.split(`
|
|
21
23
|
`).filter(Boolean).length;r=`${a} file${a!==1?"s":""} found`}break}case"list_directory":{let a=o==="(empty)"?0:o.split(`
|
|
22
|
-
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),
|
|
23
|
-
`).filter(
|
|
24
|
-
`).filter(
|
|
24
|
+
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
25
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
26
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=a>0?`${a} commit${a!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let a=o.split(`
|
|
25
27
|
|
|
26
|
-
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,
|
|
28
|
+
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${V.dim}\u23BF ${r}${V.reset}`}So.exports={C:V,formatToolCall:ic,formatResult:ac,getToolSpinnerText:cc,formatToolSummary:lc}});var Q=O((Cp,Co)=>{var ot={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 uc(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+ot.reset}function dc(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 fc(t,e,s={}){let n=ot.bold,o=ot.dim,r=ot.reset,a=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=a.map((d,f)=>{let m=f/(a.length-1||1);return uc(d,dc(c,m))}).join(`
|
|
27
29
|
`),u=s.yolo?` ${n}${ot.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
28
|
-
${
|
|
29
|
-
${o}Agentic Coding CLI v${
|
|
30
|
+
${l}
|
|
31
|
+
${o}Agentic Coding CLI v${Kt().version}${r}
|
|
30
32
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
31
|
-
`)}var{Spinner:
|
|
32
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,
|
|
33
|
-
`);h=x.pop()||"";for(let w of x){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(
|
|
33
|
+
`)}var{Spinner:mc,MultiProgress:pc,TaskProgress:hc,setActiveTaskProgress:gc,getActiveTaskProgress:$c,cleanupTerminal:yc}=vo(),{formatToolCall:wc,formatResult:bc,getToolSpinnerText:xc,formatToolSummary:kc}=To();Co.exports={C:ot,banner:fc,Spinner:mc,MultiProgress:pc,TaskProgress:hc,setActiveTaskProgress:gc,getActiveTaskProgress:$c,cleanupTerminal:yc,formatToolCall:wc,formatResult:bc,getToolSpinnerText:xc,formatToolSummary:kc}});var Te=O((Ep,Oo)=>{var _c=require("readline"),{C:Vt}=Q(),Eo=[/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/],Yn=[/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 Ao(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let a=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(a))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):Yn.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:Yn.some(c=>c.test(a))};return n.every(o)}var Xn=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Mo=[/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/],Ro=[...Xn,...Mo],Qn=!1,Vn=null;function vc(t){Qn=t}function Sc(){return Qn}function Tc(t){Vn=t}function Cc(t){for(let e of Eo)if(e.test(t))return e;return null}function Ec(t){if(/ssh\s/.test(t)&&Ao(t))return!1;for(let e of Ro)if(e.test(t))return!0;return!1}function Ac(t){for(let e of Xn)if(e.test(t))return!0;return!1}function Mc(t,e={}){if(Qn)return Promise.resolve(!0);let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(No(e.toolName),n(!0)):n(a!=="n")};if(Vn)Vn.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,o);else{let r=_c.createInterface({input:process.stdin,output:process.stdout});r.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,a=>{r.close(),o(a)})}})}var No=()=>{};function Rc(t){No=t}Oo.exports={FORBIDDEN_PATTERNS:Eo,SSH_SAFE_PATTERNS:Yn,isSSHReadOnly:Ao,DANGEROUS_BASH:Ro,CRITICAL_BASH:Xn,NOTABLE_BASH:Mo,isForbidden:Cc,isDangerous:Ec,isCritical:Ac,confirm:Mc,setAutoConfirm:vc,getAutoConfirm:Sc,setReadlineInterface:Tc,setAllowAlwaysHandler:Rc}});var rt=O((Ap,Po)=>{var Zn=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`)}};Po.exports={BaseProvider:Zn}});var qo=O((Mp,Lo)=>{var Xt=require("axios"),Nc=require("http"),Oc=require("https"),{BaseProvider:Pc}=rt(),Qt=new Nc.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Zt=new Oc.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Io={"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}},es=class extends Pc{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Io,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){Xt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Qt,httpsAgent:Zt}).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 Xt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Qt,httpsAgent:Zt})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
34
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=await Xt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Qt,httpsAgent:Zt});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await Xt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Qt,httpsAgent:Zt})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let x=h.split(`
|
|
35
|
+
`);h=x.pop()||"";for(let w of x){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Lo.exports={OllamaProvider:es,OLLAMA_MODELS:Io}});var Bo=O((Rp,Wo)=>{var{callChat:Ic}=re(),{estimateTokens:ts}=xe(),jo=process.env.NEX_COMPACTION!=="false",Do=6,Fo=500,Lc=`Summarize this conversation history concisely. Focus on:
|
|
34
36
|
- What files were read, created, or modified
|
|
35
37
|
- Key decisions made and their rationale
|
|
36
38
|
- Current state of the task (what's done, what's pending)
|
|
37
39
|
- Any errors encountered and how they were resolved
|
|
38
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
39
|
-
${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 qc(t){if(!jo||t.length<Do)return null;let e=[{role:"system",content:Lc},{role:"user",content:Uo(t)}];try{let n=((await Ic(e,[],{temperature:0,maxTokens:Fo})).content||"").trim();if(!n)return null;let o=t.reduce((a,c)=>a+ts(c.content||"")+(c.tool_calls?ts(JSON.stringify(c.tool_calls)):0),0),r=ts(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 Uo(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}
|
|
40
42
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
41
43
|
|
|
42
|
-
`)}
|
|
43
|
-
`);if(o.length<=10){let
|
|
44
|
+
`)}Wo.exports={compactMessages:qc,formatMessagesForSummary:Uo,COMPACTION_ENABLED:jo,COMPACTION_MIN_MESSAGES:Do,COMPACTION_SUMMARY_BUDGET:Fo}});var xe=O((Np,Qo)=>{function zo(){return re().getActiveModel()}var jc={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},_t=new Map,Ho=1e3,en=new WeakMap,it=new Map,Go=500,vt=null;function Dc(){if(vt!==null)return vt;try{let e=zo()?.provider||"ollama";return vt=jc[e]||4,vt}catch{return 4}}function Fc(){vt=null}function Ge(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=_t.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/Dc());if(_t.size>=Ho){let o=Ho>>1,r=_t.keys();for(let a=0;a<o;a++)_t.delete(r.next().value)}return _t.set(e,n),n}function Uc(t){if(en.has(t))return en.get(t);let e=Ko(t);if(it.has(e)){let n=it.get(e);return en.set(t,n),n}let s=JSON.stringify(t);if(it.size>=Go){let n=Go>>1,o=it.keys();for(let r=0;r<n;r++)it.delete(o.next().value)}return it.set(e,s),en.set(t,s),s}function Ko(t){let e=t.role||"",s=typeof t.content=="string"?t.content.substring(0,100):"",n=t.tool_calls?t.tool_calls.length:0;return`${e}:${s.length}:${n}`}function at(t){let s=4;if(t.content&&(s+=Ge(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Ge(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Ge(o):o&&(s+=Ge(JSON.stringify(o)))}return s}function $e(t){let e=0;for(let s of t)e+=at(s);return e}function Wc(t,e){if(t&&t.length===e.length){let r=!1;for(let a=0;a<e.length;a++)if(t[a]!==e[a]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=at(e[r]);return o}function tn(t){return!t||t.length===0?0:Ge(JSON.stringify(t))}function nn(){return zo()?.contextWindow||32768}function Bc(t,e){let s=$e(t),n=tn(e),o=s+n,r=nn(),a=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=at(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Jo=.75,Yo=.1,Vo=10,Hc=200,Gc=500;function Xo(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
45
|
+
`);if(o.length<=10){let p=Math.floor(n*.6),x=Math.floor(n*.4),w=t.substring(0,p),$=t.substring(t.length-x);return w+`
|
|
44
46
|
...(${t.length} chars total)...
|
|
45
|
-
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),
|
|
47
|
+
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<r&&l<u;p++)c.push(o[p]),l+=o[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=o.length-1;p>=o.length-a&&f<m;p--)d.unshift(o[p]),f+=o[p].length+1;let h=o.length-c.length-d.length;return c.join(`
|
|
46
48
|
`)+`
|
|
47
49
|
...(${h} lines omitted, ${o.length} total)...
|
|
48
50
|
`+d.join(`
|
|
49
|
-
`)}function
|
|
50
|
-
...(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
|
|
51
|
-
`),r=Math.floor(n*.6),a=Math.floor(n*.4),
|
|
52
|
-
`:"")+h,
|
|
53
|
-
`:"")+u;if(
|
|
54
|
-
|
|
55
|
-
... (${o.length-
|
|
56
|
-
|
|
57
|
-
`;return
|
|
58
|
-
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(
|
|
59
|
-
|
|
60
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(o);this._messageStringCache.set(a,r),this._messageFormatCache.set(o,r)}n.push(r)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),
|
|
61
|
-
`);T=S.pop()||"";for(let
|
|
62
|
-
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(
|
|
63
|
-
`)};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
|
|
64
|
-
`);f=h.pop()||"";for(let
|
|
65
|
-
`)}}function
|
|
66
|
-
`)}function
|
|
67
|
-
`),
|
|
51
|
+
`)}function St(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Gc,n=e==="aggressive"?50:e==="medium"?100:Hc;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Xo(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 zc(t,e,s={}){let n=s.threshold??Jo,o=s.safetyMargin??Yo,r=s.keepRecent??Vo,a=nn(),c=tn(e),l=Math.floor(a*(n-o)),u=l-c,d=$e(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let x=Math.max(p,t.length-r),w=t.slice(p,x),$=t.slice(x),k=w.filter(C=>!C._compacted);if(k.length>=6)try{let{compactMessages:C}=Bo(),E=await C(k);if(E){let L=[...w.filter(I=>I._compacted),E.message],M=He(h,L,$),N=$e(M);if(N+c<=l)return{messages:M,compressed:!0,compacted:!0,tokensRemoved:m-N};w=L}}catch{}let T=(f-l)/l,b=w.map(C=>St(C,"light")),S=He(h,b,$),v=$e(S);if(v+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-v};if(b=w.map(C=>St(C,"medium")),S=He(h,b,$),v=$e(S),v+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-v};if(b=w.map(C=>St(C,"aggressive")),S=He(h,b,$),v=$e(S),v+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-v};for(;b.length>0&&v+c>u;){let C=b.shift();v-=at(C)}return S=He(h,b,$),v=$e(S),{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-v}}function He(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Kc(t,e){if(!t)return"";if(Ge(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
|
+
`),r=Math.floor(n*.6),a=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
|
+
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
|
+
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
56
|
+
|
|
57
|
+
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
|
+
|
|
59
|
+
`;return c+m+u}var Jc=6;function Yc(t,e){let s=nn(),n=tn(e),o=Math.floor(s*.5)-n,r=$e(t),a=null,c=0;t.length>0&&t[0].role==="system"&&(a=t[0],c=1);let l=Math.max(c,t.length-Jc),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>St(p,"aggressive")),m=He(a,f,d),h=$e(m);for(;f.length>0&&h>o;){let p=f.shift();h-=at(p)}return m=He(a,f,d),h=$e(m),{messages:m,tokensRemoved:r-h}}Qo.exports={estimateTokens:Ge,estimateMessageTokens:at,estimateMessagesTokens:$e,estimateDeltaTokens:Wc,estimateToolsTokens:tn,serializeMessage:Uc,getMessageCacheKey:Ko,getContextWindow:nn,getUsage:Bc,compressMessage:St,compressToolResult:Xo,fitToContext:zc,forceCompress:Yc,truncateFileContent:Kc,invalidateTokenRatioCache:Fc,COMPRESSION_THRESHOLD:Jo,SAFETY_MARGIN:Yo,KEEP_RECENT:Vo}});var nr=O((Pp,tr)=>{var Zo=require("axios"),{BaseProvider:Vc}=rt(),{serializeMessage:Op}=xe(),er={"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}},ns=class extends Vc{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||er,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Zo.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Zo.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},x="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{x+=w.toString();let $=x.split(`
|
|
60
|
+
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let S;try{S=JSON.parse(b)}catch{continue}let v=S.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let C of v.tool_calls){let E=C.index??0;p[E]||(p[E]={id:C.id||"",name:"",arguments:""}),C.id&&(p[E].id=C.id),C.function?.name&&(p[E].name+=C.function.name),C.function?.arguments&&(p[E].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};tr.exports={OpenAIProvider:ns,OPENAI_MODELS:er}});var ir=O((Lp,rr)=>{var sr=require("axios"),{BaseProvider:Xc}=rt(),{serializeMessage:Ip}=xe(),or={"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}},Qc="2023-06-01",ss=class extends Xc{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||or,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Qc}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 a=this._getMessageCacheKey(o);this._messageStringCache.set(a,r),this._messageFormatCache.set(o,r)}n.push(r)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await sr.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(s);m.length>0&&(f.tools=m);let h;try{h=await sr.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let x=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${x}`)}return new Promise((p,x)=>{let w="",$=[],k=-1,T="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),x(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",b=>{T+=b.toString();let S=T.split(`
|
|
63
|
+
`);T=S.pop()||"";for(let v of S){let C=v.trim();if(C.startsWith("data: ")){let E=C.slice(6),P;try{P=JSON.parse(E)}catch{continue}switch(P.type){case"content_block_start":{let L=P.content_block;L?.type==="tool_use"&&(k=$.length,$.push({id:L.id,name:L.name,inputJson:""}));break}case"content_block_delta":{let L=P.delta;L?.type==="text_delta"&&L.text&&(l(L.text),w+=L.text),L?.type==="input_json_delta"&&L.partial_json!==void 0&&k>=0&&($[k].inputJson+=L.partial_json);break}case"content_block_stop":k=-1;break;case"message_stop":p({content:w,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",b=>{n.signal?.aborted||x(new Error(`Stream error: ${b.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}}})}};rr.exports={AnthropicProvider:ss,ANTHROPIC_MODELS:or}});var ur=O((jp,lr)=>{var ar=require("axios"),{BaseProvider:Zc}=rt(),{serializeMessage:qp}=xe(),cr={"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}},os=class extends Zc{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||cr,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await ar.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await ar.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},x="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",w=>{x+=w.toString();let $=x.split(`
|
|
64
|
+
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let S;try{S=JSON.parse(b)}catch{continue}let v=S.choices?.[0]?.delta;if(v&&(v.content&&(c(v.content),h+=v.content),v.tool_calls))for(let C of v.tool_calls){let E=C.index??0;p[E]||(p[E]={id:C.id||"",name:"",arguments:""}),C.id&&(p[E].id=C.id),C.function?.name&&(p[E].name+=C.function.name),C.function?.arguments&&(p[E].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};lr.exports={GeminiProvider:os,GEMINI_MODELS:cr}});var mr=O((Dp,fr)=>{var sn=require("axios"),{BaseProvider:el}=rt(),dr="http://localhost:11434",rs=class extends el{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||dr,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 sn.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),a=32768;try{let c=await sn.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};a=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(a*.1)),contextWindow:a}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
65
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await sn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),a;try{a=await sn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
66
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let x;try{x=JSON.parse(p)}catch{continue}if(x.message?.content&&(r(x.message.content),u+=x.message.content),x.message?.tool_calls&&(d=d.concat(x.message.tool_calls)),x.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};fr.exports={LocalProvider:rs,DEFAULT_LOCAL_URL:dr}});var ct=O((Fp,br)=>{var ze=require("fs"),is=require("path"),pr={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:{}},on=[],Le={};function tl(t,e,s,n){if(on.push({provider:t,model:e,input:s,output:n}),Le[t]!==void 0){let o=yr(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 as(t,e){let s=pr[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function hr(t){let e=as(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function gr(){let t={};for(let r of on){let a=`${r.provider}:${r.model}`;t[a]||(t[a]={provider:r.provider,model:r.model,input:0,output:0}),t[a].input+=r.input,t[a].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:hr(r)})),s=e.reduce((r,a)=>r+a.cost,0),n=e.reduce((r,a)=>r+a.input,0),o=e.reduce((r,a)=>r+a.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function nl(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=gr();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let a=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${a}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
68
|
+
`)}function sl(t,e,s,n){let o=as(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function ol(){on=[]}function rl(t,e){Le[t]=e}function il(t){delete Le[t]}function al(){return{...Le}}function $r(t){let e=0;for(let s of on)s.provider===t&&(e+=hr(s));return e}function yr(t){let e=$r(t),s=Le[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 wr(){let t=is.join(process.cwd(),".nex","config.json");if(ze.existsSync(t))try{let e=JSON.parse(ze.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Le={...e.costLimits})}catch{}}function cl(){let t=is.join(process.cwd(),".nex"),e=is.join(t,"config.json"),s={};if(ze.existsSync(e))try{s=JSON.parse(ze.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Le,ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0}),ze.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function ll(){Le={}}wr();br.exports={PRICING:pr,trackUsage:tl,getSessionCosts:gr,formatCosts:nl,formatCostHint:sl,resetCosts:ol,getPricing:as,setCostLimit:rl,removeCostLimit:il,getCostLimits:al,getProviderSpend:$r,checkBudget:yr,loadCostLimits:wr,saveCostLimits:cl,resetCostLimits:ll}});var rn=O((Up,xr)=>{var Tt=re(),ul={"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 dl(){return Tt.getActiveModel()}function fl(t){return Tt.setActiveModel(t)}function ml(){return Tt.getModelNames()}function pl(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 hl(t,e){let{C:s}=Q(),{Spinner:n}=Q(),o=new n("Thinking...");o.start();let r=!0,a="";try{let c=await Tt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
69
|
+
`),c}catch(c){throw o.stop(),c}}async function gl(t,e){return Tt.callChat(t,e)}xr.exports={MODELS:ul,getActiveModel:dl,setActiveModel:fl,getModelNames:ml,callOllamaStream:hl,callOllama:gl,parseToolArgs:pl}});var vr=O((Wp,_r)=>{var an=require("path"),{C:y}=Q(),{confirm:$l,getAutoConfirm:yl}=Te(),kr=2e3;function Ct(t,e){let s=t.split(`
|
|
68
70
|
`),n=e.split(`
|
|
69
|
-
`),o=[],r=s.length,a=n.length;if(r>
|
|
70
|
-
${y.bold}${y.cyan} Diff: ${t}${y.reset}`);let o=
|
|
71
|
-
${y.bold}${y.cyan} File exists \u2014 showing changes: ${t}${y.reset}`);let n=
|
|
71
|
+
`),o=[],r=s.length,a=n.length;if(r>kr||a>kr){for(let f of s)o.push({type:"remove",line:f});for(let f of n)o.push({type:"add",line:f});return o}let c=Array.from({length:r+1},()=>new Array(a+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=a;m++)s[f-1]===n[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=a,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===n[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function wl(t,e,s,n=3){console.log(`
|
|
72
|
+
${y.bold}${y.cyan} Diff: ${t}${y.reset}`);let o=Ct(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${y.gray} (no changes)${y.reset}`);return}let a=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);a>0&&console.log(`${y.gray} ...${y.reset}`);for(let l=a;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${y.red} - ${u.line}${y.reset}`);break;case"add":console.log(`${y.green} + ${u.line}${y.reset}`);break;default:console.log(`${y.gray} ${u.line}${y.reset}`)}}c<o.length&&console.log(`${y.gray} ...${y.reset}`),console.log()}function bl(t,e,s){console.log(`
|
|
73
|
+
${y.bold}${y.cyan} File exists \u2014 showing changes: ${t}${y.reset}`);let n=Ct(e,s),o=0;for(let a of n)a.type!=="same"&&o++;if(o===0){console.log(`${y.gray} (identical content)${y.reset}`);return}let r=0;for(let a of n){if(r>=30){console.log(`${y.gray} ...(${o-r} more changes)${y.reset}`);break}switch(a.type){case"remove":console.log(`${y.red} - ${a.line}${y.reset}`),r++;break;case"add":console.log(`${y.green} + ${a.line}${y.reset}`),r++;break;default:r>0&&console.log(`${y.gray} ${a.line}${y.reset}`)}}console.log()}function xl(t,e){console.log(`
|
|
72
74
|
${y.bold}${y.cyan} New file: ${t}${y.reset}`);let s=e.split(`
|
|
73
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${y.green} + ${o}${y.reset}`);s.length>20&&console.log(`${y.gray} ...+${s.length-20} more lines${y.reset}`),console.log()}async function
|
|
74
|
-
${y.bold}${y.cyan} Side-by-side: ${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${y.reset}`);let a=
|
|
75
|
-
`)}function
|
|
76
|
-
${y.cyan}\u23FA${y.reset} ${y.bold}${o}(${
|
|
77
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let b=a.filter(E=>E.severity==="error").length,S=a.filter(E=>E.severity==="warn").length,
|
|
75
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${y.green} + ${o}${y.reset}`);s.length>20&&console.log(`${y.gray} ...+${s.length-20} more lines${y.reset}`),console.log()}async function kl(t){return yl()?!0:$l(` ${t}?`)}function _l(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
76
|
+
${y.bold}${y.cyan} Side-by-side: ${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${y.reset}`);let a=Ct(e,s),c=[],l=0;for(;l<a.length;)if(a[l].type==="same")c.push({left:a[l].line,right:a[l].line,type:"same"}),l++;else if(a[l].type==="remove"){let h=[];for(;l<a.length&&a[l].type==="remove";)h.push(a[l].line),l++;let p=[];for(;l<a.length&&a[l].type==="add";)p.push(a[l].line),l++;let x=Math.max(h.length,p.length);for(let w=0;w<x;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",type:"changed"})}else a[l].type==="add"&&(c.push({left:"",right:a[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${y.gray}(no changes)${y.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let x=h.replace(/\x1b\[[0-9;]*m/g,"");return x.length>=p?h.substring(0,p):h+" ".repeat(p-x.length)};d>0&&console.log(` ${y.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${y.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${y.gray}${m(p.left,r)}${y.reset}\u2502${y.gray}${m(p.right,r)}${y.reset}`);else{let x=p.left?`${y.red}${m(p.left,r)}${y.reset}`:`${m("",r)}`,w=p.right?`${y.green}${m(p.right,r)}${y.reset}`:`${m("",r)}`;console.log(` ${x}\u2502${w}`)}}f<c.length&&console.log(` ${y.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${y.reset}
|
|
77
|
+
`)}function vl(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,a=n.annotations||[],c=an.isAbsolute(t)?an.relative(process.cwd(),t):t,l=Ct(e,s),u=1,d=1;for(let b of l)b.type==="same"?(b.oldLine=u++,b.newLine=d++):b.type==="remove"?(b.oldLine=u++,b.newLine=null):(b.oldLine=null,b.newLine=d++);let f=0,m=0;for(let b of l)b.type==="add"?f++:b.type==="remove"&&m++;if(console.log(`
|
|
78
|
+
${y.cyan}\u23FA${y.reset} ${y.bold}${o}(${c})${y.reset}`),f===0&&m===0){console.log(` ${y.dim}\u23BF (no changes)${y.reset}
|
|
79
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let b=a.filter(E=>E.severity==="error").length,S=a.filter(E=>E.severity==="warn").length,v=a.filter(E=>E.severity==="info").length,C=[];b>0&&C.push(`${y.red}${b} error${b!==1?"s":""}${y.dim}`),S>0&&C.push(`${y.yellow}${S} warning${S!==1?"s":""}${y.dim}`),v>0&&C.push(`${y.cyan}${v} info${v!==1?"s":""}${y.dim}`),h.push(`found ${C.join(", ")}`)}console.log(` ${y.dim}\u23BF ${h.join(", ")}${y.reset}`);let x=[];l.forEach((b,S)=>{b.type!=="same"&&x.push(S)});let w=[],$=null,k=null;for(let b of x){let S=Math.max(0,b-r),v=Math.min(l.length-1,b+r);$===null?($=S,k=v):(S<=k+1||(w.push([$,k]),$=S),k=v)}$!==null&&w.push([$,k]);let T=" ";for(let b=0;b<w.length;b++){b>0&&console.log(`${T}${y.dim}\xB7\xB7\xB7${y.reset}`);let[S,v]=w[b];for(let C=S;C<=v;C++){let E=l[C],P=E.newLine!=null?E.newLine:E.oldLine,L=String(P).padStart(4),M=E.type!=="remove"?a.filter(N=>N.line===E.newLine):[];E.type==="remove"?console.log(`${T}${y.red}${L} -${E.line}${y.reset}`):E.type==="add"?console.log(`${T}${y.green}${L} +${E.line}${y.reset}`):console.log(`${T}${y.dim}${L}${y.reset} ${E.line}`);for(let N of M){let I=y.cyan,q="\u2139";N.severity==="error"?(I=y.red,q="\u2716"):N.severity==="warn"&&(I=y.yellow,q="\u26A0"),console.log(`${T} ${I}${q} ${N.message}${y.reset}`)}}}console.log()}function Sl(t,e,s={}){let n=an.isAbsolute(t)?an.relative(process.cwd(),t):t,o=e.split(`
|
|
78
80
|
`),r=s.annotations||[];console.log(`
|
|
79
|
-
${y.cyan}\u23FA${y.reset} ${y.bold}Create(${n})${y.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(
|
|
80
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function ln(t=!1){return await
|
|
81
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",
|
|
82
|
-
${
|
|
83
|
-
${
|
|
84
|
-
${
|
|
81
|
+
${y.cyan}\u23FA${y.reset} ${y.bold}Create(${n})${y.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${y.red}${d} error${d!==1?"s":""}${y.dim}`),f>0&&h.push(`${y.yellow}${f} warning${f!==1?"s":""}${y.dim}`),m>0&&h.push(`${y.cyan}${m} info${m!==1?"s":""}${y.dim}`),a.push(`found ${h.join(", ")}`)}console.log(` ${y.dim}\u23BF ${a.join(", ")}${y.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=r.filter(p=>p.line===m);console.log(`${l}${y.green}${f} +${o[d]}${y.reset}`);for(let p of h){let x=y.cyan,w="\u2139";p.severity==="error"?(x=y.red,w="\u2716"):p.severity==="warn"&&(x=y.yellow,w="\u26A0"),console.log(`${l} ${x}${w} ${p.message}${y.reset}`)}}o.length>20&&console.log(`${l}${y.dim} ...+${o.length-20} more lines${y.reset}`),console.log()}_r.exports={diffLines:Ct,showEditDiff:wl,showWriteDiff:bl,showNewFilePreview:xl,confirmFileChange:kl,showSideBySideDiff:_l,showClaudeDiff:vl,showClaudeNewFile:Sl}});var Ke=O((Bp,Cr)=>{var Sr=require("util").promisify(require("child_process").exec),Tl=require("util").promisify(require("child_process").execFile),{C:J}=Q();async function cs(t){try{let{stdout:e}=await Sr(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function cn(...t){try{let{stdout:e}=await Tl("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Cl(){return await cs("git rev-parse --is-inside-work-tree")==="true"}async function El(){return await cs("git branch --show-current")}async function ls(){try{let{stdout:t}=await Sr("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 ln(t=!1){return await cs(`git diff ${t?"--cached":""}`)||""}async function us(){return(await ls()).map(e=>e.file)}async function Tr(){let t=await us();if(t.length===0)return null;let e=await ln(),n=await ln(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function Al(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await cn("checkout","-b",s)!==null?s:null}async function Ml(t){return await cn("add","-A"),await cn("commit","-m",t)?await cn("rev-parse","--short","HEAD"):null}async function Rl(){let t=await Tr();if(!t)return`${J.dim}No changes${J.reset}`;let e=[];e.push(`
|
|
84
|
+
${J.bold}${J.cyan}Git Diff Summary:${J.reset}`),e.push(` ${J.green}+${t.stats.additions}${J.reset} ${J.red}-${t.stats.deletions}${J.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
|
+
${J.bold}${J.cyan}Files:${J.reset}`);for(let s of t.files.slice(0,20))e.push(` ${J.dim}${s}${J.reset}`);return t.files.length>20&&e.push(` ${J.dim}...+${t.files.length-20} more${J.reset}`),e.push(`
|
|
86
|
+
${J.bold}${J.cyan}Suggested message:${J.reset}`),e.push(` ${J.cyan}${t.summary}${J.reset}
|
|
85
87
|
`),e.join(`
|
|
86
|
-
`)}async function
|
|
88
|
+
`)}async function Nl(){return(await ls()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Ol(){let t=await us();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 ln();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
87
89
|
...(truncated)`:s;e.push(`
|
|
88
90
|
DIFF:
|
|
89
91
|
${n}`)}return e.join(`
|
|
90
|
-
`)}
|
|
92
|
+
`)}Cr.exports={isGitRepo:Cl,getCurrentBranch:El,getStatus:ls,getDiff:ln,getChangedFiles:us,analyzeDiff:Tr,createBranch:Al,commit:Ml,formatDiffSummary:Rl,getDiffContext:Ol,getMergeConflicts:Nl}});var ut=O((Hp,Er)=>{var ds=require("fs").promises,Pl=50,Ce=[],lt=[];function Il(t,e,s,n){for(Ce.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Ce.length>Pl;)Ce.shift();lt.length=0}async function Ll(){if(Ce.length===0)return null;let t=Ce.pop();if(t.oldContent===null)try{await ds.unlink(t.filePath)}catch{}else await ds.writeFile(t.filePath,t.oldContent,"utf-8");return lt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ql(){if(lt.length===0)return null;let t=lt.pop();return await ds.writeFile(t.filePath,t.newContent,"utf-8"),Ce.push(t),{tool:t.tool,filePath:t.filePath}}function jl(t=10){return Ce.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Dl(){return Ce.length}function Fl(){return lt.length}function Ul(){Ce.length=0,lt.length=0}Er.exports={recordChange:Il,undo:Ll,redo:ql,getHistory:jl,getUndoCount:Dl,getRedoCount:Fl,clearHistory:Ul}});var Et=O((Gp,Pr)=>{var fe=require("fs"),dt=require("path"),ce=[];function fs(){return dt.join(process.cwd(),".nex","skills")}function Ar(){return dt.join(process.cwd(),".nex","config.json")}function Wl(){let t=fs();return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function ms(){let t=Ar();if(!fe.existsSync(t))return[];try{let e=JSON.parse(fe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Mr(t){let e=Ar(),s={};if(fe.existsSync(e))try{s=JSON.parse(fe.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=dt.dirname(e);fe.existsSync(n)||fe.mkdirSync(n,{recursive:!0}),fe.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Rr(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 Nr(t){try{let e=fe.readFileSync(t,"utf-8").trim();return e?{name:dt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Or(t){try{let e=require(t),{valid:s,errors:n}=Rr(e,t);return s?{name:e.name||dt.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}
|
|
91
93
|
${n.join(`
|
|
92
|
-
`)}`),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 Bl(){ce=[];let t=fs();if(!fe.existsSync(t))return ce;let e=ms(),s;try{s=fe.readdirSync(t)}catch{return ce}for(let n of s){let o=dt.join(t,n),r;try{r=fe.statSync(o)}catch{continue}if(!r.isFile())continue;let a=null;n.endsWith(".md")?a=Nr(o):n.endsWith(".js")&&(a=Or(o)),a&&(a.enabled=!e.includes(a.name),ce.push(a))}return ce}function Hl(){let t=[];for(let e of ce)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
93
95
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
94
96
|
${t.join(`
|
|
95
97
|
|
|
96
|
-
`)}`}function
|
|
97
|
-
`,
|
|
98
|
-
`);for(let
|
|
99
|
-
`):JSON.stringify(o)}function
|
|
100
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),a=[],
|
|
98
|
+
`)}`}function Gl(){let t=[];for(let e of ce)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function zl(){let t=[];for(let e of ce)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 Kl(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ce)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 Jl(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ce)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(a){console.error(`Skill command error (${e}): ${a.message}`)}return!0}}return!1}function Yl(){return ce.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 Vl(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=ms().filter(n=>n!==t);return Mr(s),!0}function Xl(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=ms();return s.includes(t)||(s.push(t),Mr(s)),!0}function Ql(){return ce}Pr.exports={initSkillsDir:Wl,loadAllSkills:Bl,getSkillInstructions:Hl,getSkillCommands:Gl,getSkillToolDefinitions:zl,routeSkillCall:Kl,handleSkillCommand:Jl,listSkills:Yl,enableSkill:Vl,disableSkill:Xl,getLoadedSkills:Ql,_getSkillsDir:fs,_validateScriptSkill:Rr,_loadMarkdownSkill:Nr,_loadScriptSkill:Or}});var dn=O((zp,Fr)=>{var{spawn:Zl}=require("child_process"),eu=require("path"),Ir=require("fs"),Ee=new Map;function tu(){return eu.join(process.cwd(),".nex","config.json")}function ps(){let t=tu();if(!Ir.existsSync(t))return{};try{return JSON.parse(Ir.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function un(t,e,s={},n=1e4){return new Promise((o,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:s})+`
|
|
99
|
+
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
|
|
100
|
+
`);for(let p of h)if(p.trim())try{let x=JSON.parse(p);if(x.id===a){f(),x.error?r(new Error(`MCP error: ${x.error.message||JSON.stringify(x.error)}`)):o(x.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Lr(t,e){if(Ee.has(t))return Ee.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let a of s)process.env[a]&&(n[a]=process.env[a]);let o=Zl(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await un(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await un(o,"tools/list",{});return r.tools=a&&a.tools||[],Ee.set(t,r),r}catch(a){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function qr(t){let e=Ee.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ee.delete(t),!0}function nu(){for(let[t]of Ee)qr(t)}async function jr(t,e,s={}){let n=Ee.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await un(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 Dr(){let t=[];for(let[e,s]of Ee)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 su(){return Dr().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function ou(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 jr(n,o,e)}function ru(){let t=ps();return Object.entries(t).map(([e,s])=>{let n=Ee.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function iu(){let t=ps(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Lr(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Fr.exports={loadMCPConfig:ps,sendRequest:un,connectServer:Lr,disconnectServer:qr,disconnectAll:nu,callTool:jr,getAllTools:Dr,getMCPToolDefinitions:su,routeMCPCall:ou,listServers:ru,connectAll:iu}});var hs=O((Kp,Hr)=>{var{getSkillToolDefinitions:au}=Et(),{getMCPToolDefinitions:cu}=dn(),fn=new Map;function Ur(){let{TOOL_DEFINITIONS:t}=qe();return[...t,...au(),...cu()]}function Wr(t){if(fn.has(t))return fn.get(t);let s=Ur().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return fn.set(t,n),n}function lu(){fn.clear()}function mn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Br(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Br(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let a=1;a<=n;a++)o[r][a]=t[r-1]===e[a-1]?o[r-1][a-1]:1+Math.min(o[r-1][a],o[r][a-1],o[r-1][a-1]);return o[s][n]}function uu(t,e){let s=Wr(t);if(s===null){let d=Ur().map(m=>m.function.name),f=mn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=mn(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=mn(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||a.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return a.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
101
103
|
`+a.map(u=>` - ${u}`).join(`
|
|
102
104
|
`)+`
|
|
103
105
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c
|
|
106
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Hr.exports={validateToolArgs:uu,closestMatch:mn,levenshtein:Br,getCachedSchema:Wr,clearSchemaCache:lu}});var Jr=O((Jp,Kr)=>{var{levenshtein:pn}=hs(),du=200,fu=.3,mu=2;function gs(t){return t.replace(/\r\n/g,`
|
|
105
107
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
108
|
+
`).replace(/\t/g," ".repeat(mu)).split(`
|
|
107
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(`
|
|
108
|
-
`)}function
|
|
110
|
+
`)}function pu(t,e){if(t.includes(e))return e;let s=gs(t),n=gs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
109
111
|
`),r=s.split(`
|
|
110
112
|
`),a=n.split(`
|
|
111
|
-
`),
|
|
112
|
-
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function
|
|
113
|
+
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return o.slice(u,u+a.length).join(`
|
|
114
|
+
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function hu(t,e){if(!t||!e)return null;let s=t.split(`
|
|
113
115
|
`),o=e.split(`
|
|
114
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
115
|
-
`),u=
|
|
116
|
-
`),h=
|
|
117
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],
|
|
118
|
-
`).filter(Boolean)
|
|
116
|
+
`).length;return s.length===0||o===0?null:o===1?gu(s,e):yu(s,e,o)}function Gr(t){return Math.max(1,Math.floor(t/du))}function zr(t,e){return t<=Math.ceil(e*fu)}function gu(t,e){let s=e.trim(),n=Gr(t.length),o=null,r=1/0;for(let a=0;a<t.length;a+=n){let c=t[a];if(!c.trim())continue;let l=pn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:a+1})}return o&&n>1&&(o=$u(t,s,o,n)||o,r=o.distance),zr(r,e.length)?o:null}function $u(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),a=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=pn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function yu(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Gr(n),r=null,a=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
117
|
+
`),u=pn(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=wu(t,e,r,o,s,n)||r,a=r.distance),zr(a,e.length)?r:null}function wu(t,e,s,n,o,r){let a=s.line-1,c=Math.max(0,a-n),l=Math.min(r-1,a+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
118
|
+
`),h=pn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Kr.exports={normalizeWhitespace:gs,fuzzyFindText:pu,findMostSimilar:hu}});var Vr=O((Vp,Yr)=>{var{C:Yp}=Q(),bu=[{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}],xu=[{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 ku(t,e){let s=e.split(`
|
|
119
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],c=r+1;for(let l of bu)l.regex.test(a)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of xu)l.ext&&!l.ext.includes(o)||l.regex.test(a)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}Yr.exports={runDiagnostics:ku}});var ws=O((Xp,Zr)=>{var _u=require("fs").promises,Xr=require("path"),{exec:vu}=require("util").promisify(require("child_process").exec),ft=[],ys=null,hn=!1,$s=0,Su=6e4;function Qr(t){return!(ft.length===0||ys!==t||Date.now()-$s>Su)}async function Tu(t){if(!hn&&!Qr(t)){hn=!0,ys=t;try{try{let{stdout:n}=await vu("rg --files",{cwd:t,timeout:5e3});ft=n.split(`
|
|
120
|
+
`).filter(Boolean),$s=Date.now(),hn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await _u.readdir(n,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let c=o?`${o}/${a.name}`:a.name;a.isDirectory()?await s(Xr.join(n,a.name),c):e.push(c)}};await s(t,""),ft=e,$s=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{hn=!1}}}function Cu(){return ft}function Eu(){return ys}function Au(t){return ft.filter(e=>Xr.basename(e)===t)}function Mu(t){let e=t.toLowerCase();return ft.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Zr.exports={refreshIndex:Tu,getFileIndex:Cu,getIndexedCwd:Eu,findFileInIndex:Au,searchIndex:Mu,isIndexValid:Qr}});var Mt=O((Qp,ni)=>{var bs=null,Ae=null,At=null,ei=`Playwright is not installed. Install with:
|
|
119
121
|
npm install playwright && npx playwright install chromium
|
|
120
|
-
Then restart nex-code.`;function
|
|
121
|
-
...(truncated)`:""),links:
|
|
122
|
-
`)}function
|
|
122
|
+
Then restart nex-code.`;function ti(){if(At!==null)return At;try{require("playwright"),At=!0}catch{At=!1}return At}async function gn(){if(!ti())throw new Error(ei);return bs||(bs=require("playwright")),(!Ae||!Ae.isConnected())&&(Ae=await bs.chromium.launch({headless:!0})),Ae}async function Ru(){if(Ae){try{await Ae.close()}catch{}Ae=null}}process.on("exit",()=>{if(Ae)try{Ae.close()}catch{}});async function Nu(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await gn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),a=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
123
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function Ou(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let a=await(await gn()).newPage();try{await a.setViewportSize({width:e,height:s}),await a.goto(t,{waitUntil:"networkidle",timeout:o});let c=await a.screenshot({type:"png",fullPage:n}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await a.title(),url:a.url()}}finally{await a.close()}}async function Pu(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await gn()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let a=await r.title();return`Clicked \u2014 now at: ${r.url()} (${a})`}finally{await r.close()}}async function Iu(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let a=await(await gn()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await a.fill(e,String(s)),n&&(await a.keyboard.press("Enter"),await a.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${a.url()}`:"Not submitted."}`}finally{await a.close()}}ni.exports={isPlaywrightAvailable:ti,browserNavigate:Nu,browserScreenshot:Ou,browserClick:Pu,browserFill:Iu,closeBrowser:Ru,INSTALL_MSG:ei}});var $n=O((Zp,si)=>{var{C:B}=Q(),Nt="",ae=[],Rt=0,Je=null;function Lu(t){Je=t}function qu(t,e){Nt=t,ae=[],Rt=0;for(let n of e){Rt++;let o=`t${Rt}`;ae.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Rt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ae.map(n=>({...n}));return Je&&Je("create",{name:t,tasks:s}),s}function ju(t,e,s){let n=ae.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Je&&Je("update",{id:t,status:e,result:s}),{...n}):null}function Du(){return{name:Nt,tasks:ae.map(t=>({...t}))}}function Fu(){Nt="",ae=[],Rt=0,Je&&Je("clear",{})}function Uu(){return ae.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ae.find(n=>n.id===e);return s&&s.status==="done"}))}function Wu(){if(ae.length===0)return`${B.dim}No active tasks${B.reset}`;let t=[];Nt&&(t.push(` ${B.bold}${B.cyan}Tasks: ${Nt}${B.reset}`),t.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`));for(let o of ae){let r,a;switch(o.status){case"done":r="\u2713",a=B.green;break;case"in_progress":r="\u2192",a=B.cyan;break;case"failed":r="\u2717",a=B.red;break;default:r="\xB7",a=B.dim}let c=o.dependsOn.length>0?` ${B.dim}(after: ${o.dependsOn.join(", ")})${B.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${a}${r}${B.reset} ${B.bold}${o.id}${B.reset} ${u.padEnd(40)} ${a}${l}${B.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${B.dim}\u2192 ${d}${B.reset}`)}}let e=ae.filter(o=>o.status==="done").length,s=ae.filter(o=>o.status==="failed").length,n=ae.length;return t.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`),t.push(` ${B.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${B.reset}`),t.join(`
|
|
124
|
+
`)}function Bu(){return ae.length>0&&ae.some(t=>t.status==="pending"||t.status==="in_progress")}si.exports={createTasks:qu,updateTask:ju,getTaskList:Du,clearTasks:Fu,getReadyTasks:Uu,renderTaskList:Wu,setOnChange:Lu,hasActiveTasks:Bu}});var ks=O((eh,ri)=>{var{getActiveModel:Hu,getActiveProviderName:Gu}=re(),Ot={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"],full:null},Pt={"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"},It={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ke={};function oi(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(ke=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{ke={}}}oi();function xs(){let e=Hu()?.id,s=Gu();return e&&ke[e]?ke[e]:s&&ke[`${s}:*`]?ke[`${s}:*`]:e&&Pt[e]?Pt[e]:s&&It[s]?It[s]:"full"}function zu(t,e){return t&&ke[t]?ke[t]:e&&ke[`${e}:*`]?ke[`${e}:*`]:t&&Pt[t]?Pt[t]:e&&It[e]?It[e]:"full"}function Ku(t,e){let s=e||xs();if(s==="full"||!Ot[s])return t;let n=new Set(Ot[s]);return t.filter(o=>n.has(o.function.name))}function Ju(){let t=xs(),e=Ot[t]?Ot[t].length:"all";return{tier:t,toolCount:e}}ri.exports={filterToolsForModel:Ku,getActiveTier:xs,getModelTier:zu,getTierInfo:Ju,TIERS:Ot,MODEL_TIERS:Pt,PROVIDER_DEFAULT_TIER:It,loadConfigOverrides:oi}});var $i=O((nh,gi)=>{var{callStream:Yu,getActiveProviderName:wn,getActiveModelId:Vu,getConfiguredProviders:Xu,getProvider:ii,getActiveProvider:ai,parseModelSpec:ci}=re(),{parseToolArgs:Qu}=rn(),{filterToolsForModel:Zu,getModelTier:yn}=ks(),{trackUsage:ed}=ct(),{MultiProgress:td,C:th}=Q(),nd=15,li=5,ui=3,bn=new Map;function sd(t,e){let s=bn.get(t);return s&&s!==e?!1:(bn.set(t,e),!0)}function _s(t){bn.delete(t)}function vs(){bn.clear()}function di(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 fi(t,e,s){let n;for(let o=0;o<=ui;o++)try{return await Yu(t,e,s)}catch(r){if(n=r,o<ui&&di(r)){let a=Math.min(2e3*Math.pow(2,o),15e3);await new Promise(c=>setTimeout(c,a).unref());continue}throw r}throw n}var od=new Set(["ask_user","task_list","spawn_agents"]),rd=new Set(["write_file","edit_file","patch_file"]),id=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,ad=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function mi(t){return ad.test(t)?"full":id.test(t)?"essential":"standard"}function pi(t){let e=Xu(),s=wn(),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(yn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var cd={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ss(t){if(t.model){let{provider:o,model:r}=ci(t.model),a=o?ii(o):ai(),c=o||wn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=yn(r,c);return{provider:c,model:r,tier:l}}}let e=mi(t.task),s=cd[e];if(s){let{provider:o,model:r}=ci(s),a=o?ii(o):ai(),c=o||wn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=yn(r,c);return{provider:c,model:r,tier:l}}}let n=pi(e);if(n){let o=yn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function hi(t,e={}){let s=Math.min(t.max_iterations||10,nd),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},a=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
123
125
|
|
|
124
126
|
TASK: ${t.task}
|
|
125
127
|
${t.context?`
|
|
@@ -141,93 +143,95 @@ TOOL STRATEGY:
|
|
|
141
143
|
ERROR RECOVERY:
|
|
142
144
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
143
145
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
144
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
${
|
|
148
|
-
|
|
146
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=Ss(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=qe(),x=Zu(h.filter($=>!od.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
147
|
+
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let k=await fi(l,x,w);if(!k||typeof k!="object")throw new Error("Empty or invalid response from provider");if(k.usage){let E=k.usage.prompt_tokens||0,P=k.usage.completion_tokens||0;r.input+=E,r.output+=P;let L=d||wn(),M=f||Vu();ed(L,M,E,P)}let T=k.content||"",b=k.tool_calls,S={role:"assistant",content:T||""};if(b&&b.length>0&&(S.tool_calls=b),l.push(S),!b||b.length===0){for(let E of a)_s(E);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let v=b.map(E=>{let P=E.function.name,L=Qu(E.function.arguments),M=E.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!L)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${P}`,tool_call_id:M});if(rd.has(P)&&L.path){let N=require("path"),I=N.isAbsolute(L.path)?L.path:N.resolve(process.cwd(),L.path);if(!sd(I,n))return Promise.resolve({role:"tool",content:`ERROR: File '${L.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:M});a.add(I)}return o.push(P),p(P,L,{autoConfirm:!0,silent:!0}).then(N=>{let I=String(N??"");return{role:"tool",content:I.length>2e4?I.substring(0,2e4)+`
|
|
148
|
+
...(truncated)`:I,tool_call_id:M}}).catch(N=>({role:"tool",content:`ERROR: ${N.message}`,tool_call_id:M}))}),C=await Promise.all(v);l.push(...C),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of a)_s($);return{task:t.task,status:"done",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let k of a)_s(k);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function ld(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>li)return`ERROR: Max ${li} parallel agents allowed, got ${e.length}`;let s=e.map(r=>Ss(r)),n=e.map((r,a)=>{let c=s[a],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${a+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new td(n);o.start();try{let r=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return hi(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="done"?"done":"error"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),a=await Promise.all(r);o.stop(),vs();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<a.length;d++){let f=a[d],m=f.status==="done"?"\u2713":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
149
|
+
`)}catch(r){return o.stop(),vs(),`ERROR: Sub-agent execution failed: ${r.message}`}}gi.exports={runSubAgent:hi,executeSpawnAgents:ld,clearAllLocks:vs,classifyTask:mi,pickModelForTier:pi,resolveSubAgentModel:Ss,isRetryableError:di,callWithRetry:fi}});var qe=O((rh,Ci)=>{var K=require("fs").promises,ud=require("fs"),ue=require("path"),Me=require("util").promisify(require("child_process").exec),yi=require("util").promisify(require("child_process").execFile),{spawnSync:dd}=require("child_process"),Ts=require("axios"),{isForbidden:fd,isDangerous:md,isCritical:wi,confirm:pd}=Te(),{showClaudeDiff:xn,showClaudeNewFile:hd,showEditDiff:sh,confirmFileChange:Lt}=vr(),{C:H,Spinner:vi,getToolSpinnerText:gd}=Q(),{isGitRepo:Cs,getCurrentBranch:bi,getStatus:$d,getDiff:yd}=Ke(),{recordChange:kn}=ut(),{fuzzyFindText:xi,findMostSimilar:As}=Jr(),{runDiagnostics:qt}=Vr(),{findFileInIndex:wd,getFileIndex:oh}=ws(),bd=/^(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/,xd=/^ssh\s/,kd=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function _n(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=le(e);if(s&&await K.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=ue.extname(t);if(!o)for(let a of n){let c=le(t+a);if(c&&await K.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(o){let a=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=le(a+c);if(l&&await K.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=ue.basename(t);if(r&&r.length>2)try{let a=wd(r).map(c=>le(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${ue.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
150
|
+
${a.map(l=>ue.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
151
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function _d(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 Si(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+`
|
|
149
152
|
|
|
150
153
|
`+s.join(`
|
|
151
|
-
`)}function xi(t,e,s){let n=Cs(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 $i=!1;async function Ts(){if(!$i){$i=!0;try{let{stdout:t}=await Ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var yd=[/\.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 ue(t){let e=de.isAbsolute(t)?de.resolve(t):de.resolve(process.cwd(),t);for(let s of yd)if(s.test(e))return null;return e}var wd=[{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"]}}}];async function yi(t,e,s={}){switch(t){case"bash":{let n=e.command,o=cd(n);if(o)return`BLOCKED: Command matches forbidden pattern: ${o}`;if(s.autoConfirm?pi(n):ud(n)){let l=pi(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
152
|
-
|
|
153
|
-
${
|
|
154
|
-
|
|
154
|
+
`)}function Ti(t,e,s){let n=As(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var ki=!1,jt=null;function vd(){jt&&(jt(),jt=null)}async function Es(){if(!ki){ki=!0;try{let{stdout:t}=await Me("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Me('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Me("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Me("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Sd=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function le(t){let e=ue.isAbsolute(t)?ue.resolve(t):ue.resolve(process.cwd(),t);for(let s of Sd)if(s.test(e))return null;return e}var Td=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}}];async function _i(t,e,s={}){switch(t){case"bash":{let n=e.command,o=fd(n);if(o){let l=_d(n);return`BLOCKED: Command matches forbidden pattern: ${o}${l?`
|
|
155
|
+
HINT: ${l}`:""}`}if(s.autoConfirm?wi(n):md(n)){let l=wi(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
156
|
+
${H.yellow}${l}: ${n}${H.reset}`),!await pd(" Execute?"))return"CANCELLED: User declined to execute this command."}let a=xd.test(n.trim())&&!kd.test(n.trim());if(bd.test(n.trim())||a){s.silent||console.log(`${H.dim} \u25B6 interactive: ${n}${H.reset}`);let l=dd("sh",["-c",n],{stdio:"inherit",cwd:process.cwd()});return l.error?`ERROR: ${l.error.message}`:l.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${l.status})`}let c=s.silent?null:new vi(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);c&&c.start();try{let{stdout:l,stderr:u}=await Me(n,{cwd:process.cwd(),timeout:9e4,maxBuffer:5242880});return c&&c.stop(),l||u||"(no output)"}catch(l){c&&c.stop();let u=(l.stderr||l.stdout||l.message||"").toString().substring(0,5e3),d=Si(u,n);return`EXIT ${l.code||1}
|
|
157
|
+
${d}`}}case"read_file":{let n=le(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(n).then(()=>!0).catch(()=>!1)){let m=await _n(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
158
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await ud.promises.open(n,"r"),{bytesRead:c}=await a.read(r,0,8192,0);await a.close();for(let m=0;m<c;m++)if(r[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await K.readFile(n,"utf-8");if(!l&&(await K.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
155
159
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
|
|
156
|
-
`)}case"write_file":{await
|
|
157
|
-
`+d.message:""}`}let r=await
|
|
160
|
+
`)}case"write_file":{await Es();let n=le(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await K.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await K.readFile(n,"utf-8"));else if(o){r=await K.readFile(n,"utf-8");let l=await qt(n,e.content);if(xn(n,r,e.content,{annotations:l}),!await Lt("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await qt(n,e.content);if(hd(n,e.content,{annotations:l}),!await Lt("Create"))return"CANCELLED: User declined to create file."}let a=ue.dirname(n);return await K.access(a).then(()=>!0).catch(()=>!1)||await K.mkdir(a,{recursive:!0}),await K.writeFile(n,e.content,"utf-8"),kn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Es();let n=le(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(n).then(()=>!0).catch(()=>!1)){let d=await _n(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
161
|
+
`+d.message:""}`}let r=await K.readFile(n,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=xi(r,e.old_text);if(d)a=d,c=!0,console.log(`${H.dim} \u2713 fuzzy whitespace match applied${H.reset}`);else{let f=Ti(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await qt(n,f.content);if(xn(n,r,f.content,{annotations:p}),!await Lt(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await K.writeFile(n,f.content,"utf-8"),kn("edit_file",n,r,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${H.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${H.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=As(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
158
162
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
159
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await
|
|
160
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
163
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await qt(n,d);if(xn(n,r,d,{annotations:f}),!await Lt(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await K.writeFile(n,u,"utf-8"),kn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=le(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=le(u),f=await K.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await K.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ue.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
164
|
+
`)||"(empty)"}case"search_files":{let n=le(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 yi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
161
165
|
`).slice(0,50).join(`
|
|
162
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
166
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?le(e.path):o,a=e.pattern,c=b=>{let S=b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${S}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=ws(),x=f(),w=m();p(r)||(await h(r),x=f());let $=x.filter(b=>l.test(b)||d.test(ue.basename(b))).map(b=>ue.join(r,b));if($.length===0)return"(no matches)";let k=$.length>200,T=$.slice(0,200).join(`
|
|
163
167
|
`);return k?`${T}
|
|
164
168
|
|
|
165
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?
|
|
169
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?le(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 yi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
166
170
|
`).slice(0,100).join(`
|
|
167
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
168
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await
|
|
171
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Es();let n=le(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(n).then(()=>!0).catch(()=>!1)){let m=await _n(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
172
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await K.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:h,new_text:p}=r[m];if(a.includes(h))c.push({old_text:h,new_text:p});else{let x=xi(a,h);if(x)c.push({old_text:x,new_text:p}),l=!0;else{let w=As(a,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
169
173
|
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
170
|
-
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of
|
|
174
|
+
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await qt(n,d);if(xn(n,a,d,{annotations:m}),!await Lt(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await K.writeFile(n,d,"utf-8"),kn("patch_file",n,a,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${f}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Ts.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 Ts.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",a=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
171
175
|
|
|
172
|
-
${r}`;return a.length>0&&(
|
|
176
|
+
${r}`;return a.length>0&&(c+=`
|
|
173
177
|
|
|
174
178
|
Sources:
|
|
175
|
-
`+a.slice(0,n).map((
|
|
176
|
-
`)),
|
|
179
|
+
`+a.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
180
|
+
`)),c}catch(o){console.error(`${H.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${H.reset}`)}try{let r=(await Ts.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&a.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{a.push({title:d,url:decodeURIComponent(u)})}catch{a.push({title:d,url:u})}}return a.length===0?"(no results)":a.map((u,d)=>`${d+1}. ${u.title}
|
|
177
181
|
${u.url}`).join(`
|
|
178
182
|
|
|
179
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
183
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Mt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
180
184
|
|
|
181
185
|
Links:
|
|
182
186
|
`+o.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
183
187
|
`):"";return`Title: ${o.title}
|
|
184
188
|
URL: ${o.url}
|
|
185
189
|
|
|
186
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
190
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Mt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
187
191
|
Title: ${o.title}
|
|
188
192
|
URL: ${o.url}
|
|
189
193
|
|
|
190
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=
|
|
191
|
-
${H.cyan}${H.bold} ? ${n}${H.reset}`),r.question(`${H.cyan} > ${H.reset}`,a=>{r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await
|
|
192
|
-
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let a of o){let
|
|
193
|
-
`)}case"git_diff":{if(!await
|
|
194
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Mt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Mt();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});jt=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
195
|
+
${H.cyan}${H.bold} ? ${n}${H.reset}`),r.question(`${H.cyan} > ${H.reset}`,a=>{jt=null,r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await Cs())return"ERROR: Not a git repository";let n=await bi()||"(detached)",o=await $d();if(o.length===0)return`Branch: ${n}
|
|
196
|
+
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let a of o){let c=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${c}: ${a.file}`)}return r.join(`
|
|
197
|
+
`)}case"git_diff":{if(!await Cs())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 yd(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Cs())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:a,hasActiveTasks:c}=$n(),{getActiveTaskProgress:l}=Q(),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(`
|
|
194
198
|
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
195
199
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
196
200
|
`)}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(`
|
|
197
201
|
`+a()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
198
|
-
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=
|
|
202
|
+
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=$i();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=re();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 Me(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
199
203
|
`)}catch(r){let a=(r.stderr||r.message||"").toString();return a.includes("not found")||a.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${a.split(`
|
|
200
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await
|
|
201
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
204
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await Me(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
205
|
+
...(truncated)`:"")}let{stdout:n}=await Me(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of o.jobs||[]){let c=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${a.name} (${a.conclusion||a.status})`);for(let l of a.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
202
206
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
203
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
204
|
-
${H.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${H.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await
|
|
205
|
-
`)[0]}`}}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
207
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Te(),o=e.branch||await bi()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
208
|
+
${H.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${H.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Me(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
209
|
+
`)[0]}`}}default:return`ERROR: Unknown tool: ${t}`}}async function Cd(t,e,s={}){let n=s.silent?null:gd(t,e);if(!n)return _i(t,e,s);let o=new vi(n);o.start();try{let r=await _i(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}Ci.exports={TOOL_DEFINITIONS:Td,executeTool:Cd,resolvePath:le,autoFixPath:_n,autoFixEdit:Ti,enrichBashError:Si,cancelPendingAskUser:vd}});var Rs=O((ih,Ai)=>{var ye=require("fs").promises,pe=require("path"),vn=require("util").promisify(require("child_process").exec),{C:_e}=Q(),{getMergeConflicts:Ei}=Ke(),Ms=new Map,mt=new Map,Sn=null,Ed=3e4;async function je(t){try{return await t()}catch{return null}}async function Ad(){if(!Sn||Date.now()>Sn)return!1;let t=[pe.join(process.cwd(),"package.json"),pe.join(process.cwd(),"README.md"),pe.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await ye.stat(e),n=mt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(mt.has(e))return!1}try{let e=pe.join(process.cwd(),".git","HEAD"),s=await ye.stat(e),n=mt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Md(){let t=[pe.join(process.cwd(),"package.json"),pe.join(process.cwd(),"README.md"),pe.join(process.cwd(),".gitignore"),pe.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await ye.stat(e);mt.set(e,s.mtimeMs)}catch{mt.delete(e)}}async function Rd(t){let e="fileContext",s=Ms.get(e),n=!1;if(s&&await Ad()&&(n=!0),!n){let u=[],d=pe.join(t,"package.json");if(await je(()=>ye.access(d).then(()=>!0).catch(()=>!1)))try{let w=await ye.readFile(d,"utf-8"),$=JSON.parse(w),k={name:$.name,version:$.version};$.scripts&&(k.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(k.deps=Object.keys($.dependencies).length),$.devDependencies&&(k.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(k)}`)}catch{}let m=pe.join(t,"README.md");if(await je(()=>ye.access(m).then(()=>!0).catch(()=>!1))){let $=(await ye.readFile(m,"utf-8")).split(`
|
|
206
210
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
207
211
|
${$.join(`
|
|
208
|
-
`)}`)}let
|
|
212
|
+
`)}`)}let p=pe.join(t,".gitignore");if(await je(()=>ye.access(p).then(()=>!0).catch(()=>!1))){let w=await ye.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
209
213
|
${w.trim()}`)}s=u.join(`
|
|
210
214
|
|
|
211
|
-
`),
|
|
212
|
-
${a}`),
|
|
213
|
-
${
|
|
215
|
+
`),Ms.set(e,s),Sn=Date.now()+Ed,await Md()}let o=[s],[r,a,c,l]=await Promise.all([je(async()=>{let{stdout:u}=await vn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),je(async()=>{let{stdout:u}=await vn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),je(async()=>{let{stdout:u}=await vn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ei()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
216
|
+
${a}`),c&&o.push(`RECENT COMMITS:
|
|
217
|
+
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
214
218
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
215
219
|
${u}`)}return o.join(`
|
|
216
220
|
|
|
217
|
-
`)}async function
|
|
218
|
-
${e}`);let s=
|
|
219
|
-
${s}`);let n=
|
|
221
|
+
`)}async function Nd(t){let e=pe.join(t,"package.json"),s="";if(await je(()=>ye.access(e).then(()=>!0).catch(()=>!1)))try{let a=await ye.readFile(e,"utf-8"),c=JSON.parse(a);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([je(async()=>{let{stdout:a}=await vn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),Ei()]);if(s&&console.log(`${_e.dim} project: ${s}${_e.reset}`),o&&console.log(`${_e.dim} branch: ${o}${_e.reset}`),r&&r.length>0){console.log(`${_e.red} \u26A0 ${r.length} unresolved merge conflict(s):${_e.reset}`);for(let a of r)console.log(`${_e.red} ${a.file}${_e.reset}`);console.log(`${_e.yellow} \u2192 Resolve conflicts before starting tasks${_e.reset}`)}console.log()}Ai.exports={gatherProjectContext:Rd,printContext:Nd,_clearContextCache:()=>{Ms.clear(),mt.clear(),Sn=null}}});var Ve=O((ah,Oi)=>{var Ne=require("fs"),Ns=require("path");function Tn(){return Ns.join(process.cwd(),".nex","sessions")}function Mi(){let t=Tn();Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0})}function Os(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ns.join(Tn(),`${e}.json`)}function Ps(t,e,s={}){Mi();let n=Os(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 Ne.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Ri(t){let e=Os(t);if(!Ne.existsSync(e))return null;try{return JSON.parse(Ne.readFileSync(e,"utf-8"))}catch{return null}}function Ni(){Mi();let t=Tn(),e=Ne.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Ne.readFileSync(Ns.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 Od(t){let e=Os(t);return Ne.existsSync(e)?(Ne.unlinkSync(e),!0):!1}function Pd(){let t=Ni();return t.length===0?null:Ri(t[0].name)}var Ye=null,Re=null,Dt=null;function Id(t,e={}){t.length!==0&&(Ye&&clearTimeout(Ye),Re=t,Dt=e||{},Ye=setTimeout(()=>{Re&&Re.length>0&&Ps("_autosave",Re,Dt),Ye=null,Re=null,Dt=null},5e3))}function Ld(){Ye&&(clearTimeout(Ye),Ye=null),Re&&Re.length>0&&(Ps("_autosave",Re,Dt),Re=null,Dt=null)}Oi.exports={saveSession:Ps,loadSession:Ri,listSessions:Ni,deleteSession:Od,getLastSession:Pd,autoSave:Id,flushAutoSave:Ld,_getSessionsDir:Tn}});var De=O((ch,Di)=>{var Oe=require("fs"),Cn=require("path"),qd=require("os");function Is(){return Cn.join(process.cwd(),".nex","memory")}function Ls(){return Cn.join(Is(),"memory.json")}function jd(){return Cn.join(process.cwd(),"NEX.md")}function Pi(){return Cn.join(qd.homedir(),".nex","NEX.md")}function Dd(){let t=Is();Oe.existsSync(t)||Oe.mkdirSync(t,{recursive:!0})}function En(){let t=Ls();if(!Oe.existsSync(t))return{};try{return JSON.parse(Oe.readFileSync(t,"utf-8"))}catch{return{}}}function Ii(t){Dd(),Oe.writeFileSync(Ls(),JSON.stringify(t,null,2),"utf-8")}function Fd(t,e){let s=En();s[t]={value:e,updatedAt:new Date().toISOString()},Ii(s)}function Ud(t){let e=En();return e[t]?e[t].value:null}function Wd(t){let e=En();return t in e?(delete e[t],Ii(e),!0):!1}function Li(){let t=En();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function qi(){let t=Pi();if(!Oe.existsSync(t))return"";try{return Oe.readFileSync(t,"utf-8").trim()}catch{return""}}function ji(){let t=jd();if(!Oe.existsSync(t))return"";try{return Oe.readFileSync(t,"utf-8").trim()}catch{return""}}function Bd(){let t=[],e=qi();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
222
|
+
${e}`);let s=ji();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
223
|
+
${s}`);let n=Li();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
220
224
|
`);t.push(`PROJECT MEMORY:
|
|
221
225
|
${o}`)}return t.join(`
|
|
222
226
|
|
|
223
|
-
`)}
|
|
224
|
-
${
|
|
225
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
226
|
-
`)}function
|
|
227
|
+
`)}Di.exports={remember:Fd,recall:Ud,forget:Wd,listMemories:Li,loadGlobalInstructions:qi,loadProjectInstructions:ji,getMemoryContext:Bd,_getMemoryDir:Is,_getMemoryFile:Ls,_getGlobalNexMdPath:Pi}});var Ft=O((uh,Wi)=>{var Xe=require("fs"),qs=require("path"),{C:lh}=Q(),An={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"},pt={...An};function Fi(){let t=qs.join(process.cwd(),".nex","config.json");if(Xe.existsSync(t))try{let e=JSON.parse(Xe.readFileSync(t,"utf-8"));e.permissions&&(pt={...An,...e.permissions})}catch{}}function Hd(){let t=qs.join(process.cwd(),".nex"),e=qs.join(t,"config.json"),s={};if(Xe.existsSync(e))try{s=JSON.parse(Xe.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=pt,Xe.existsSync(t)||Xe.mkdirSync(t,{recursive:!0}),Xe.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Ui(t){return pt[t]||"ask"}function Gd(t,e){return["allow","ask","deny"].includes(e)?(pt[t]=e,!0):!1}function zd(t){return Ui(t)}function Kd(){return Object.entries(pt).map(([t,e])=>({tool:t,mode:e}))}function Jd(){pt={...An}}Fi();Wi.exports={getPermission:Ui,setPermission:Gd,checkPermission:zd,listPermissions:Kd,loadPermissions:Fi,savePermissions:Hd,resetPermissions:Jd,DEFAULT_PERMISSIONS:An}});var ht=O((fh,Ki)=>{var Qe=require("fs"),Mn=require("path"),dh=require("readline"),{C:U}=Q(),X=null,js=!1,Ds=null,Bi=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 Rn(){return Mn.join(process.cwd(),".nex","plans")}function Hi(){let t=Rn();Qe.existsSync(t)||Qe.mkdirSync(t,{recursive:!0})}function Yd(t,e=[]){return X={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()},X}function Vd(){return X}function Xd(t){js=t}function Qd(){return js}function Zd(){return!X||X.status!=="draft"?!1:(X.status="approved",X.updatedAt=new Date().toISOString(),!0)}function ef(){return!X||X.status!=="approved"?!1:(X.status="executing",!0)}function tf(t,e){return!X||t<0||t>=X.steps.length?!1:(X.steps[t].status=e,X.updatedAt=new Date().toISOString(),X.steps.every(s=>s.status==="done"||s.status==="skipped")&&(X.status="completed"),!0)}function nf(t){if(!t)return`${U.dim}No active plan${U.reset}`;let e={draft:`${U.yellow}DRAFT${U.reset}`,approved:`${U.green}APPROVED${U.reset}`,executing:`${U.blue}EXECUTING${U.reset}`,completed:`${U.green}COMPLETED${U.reset}`},s=[];s.push(`
|
|
228
|
+
${U.bold}${U.cyan}Plan: ${t.task}${U.reset}`),s.push(`${U.dim}Status: ${e[t.status]||t.status}${U.reset}
|
|
229
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${U.green}\u2713${U.reset}`;break;case"in_progress":r=`${U.blue}\u2192${U.reset}`;break;case"skipped":r=`${U.dim}\u25CB${U.reset}`;break;default:r=`${U.dim} ${U.reset}`}s.push(` ${r} ${U.bold}Step ${n+1}:${U.reset} ${o.description}`),o.files.length>0&&s.push(` ${U.dim}Files: ${o.files.join(", ")}${U.reset}`)}return s.push(""),s.join(`
|
|
230
|
+
`)}function sf(t){if(t||(t=X),!t)return null;Hi();let e=Mn.join(Rn(),`${t.name}.json`);return Qe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function of(t){let e=Mn.join(Rn(),`${t}.json`);if(!Qe.existsSync(e))return null;try{let s=JSON.parse(Qe.readFileSync(e,"utf-8"));return X=s,s}catch{return null}}function rf(){Hi();let t=Rn(),e=Qe.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Qe.readFileSync(Mn.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 af(t){Ds=t}function cf(){return Ds}function lf(){X=null,js=!1,Ds=null}function uf(){return`
|
|
227
231
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
228
232
|
|
|
229
233
|
# Allowed Tools (read-only)
|
|
230
|
-
You may ONLY use these tools: ${[...
|
|
234
|
+
You may ONLY use these tools: ${[...Bi].join(", ")}
|
|
231
235
|
Any other tool call will be blocked and returned with an error.
|
|
232
236
|
|
|
233
237
|
# Analysis Phase
|
|
@@ -258,41 +262,47 @@ Bullet list of potential issues and mitigations.
|
|
|
258
262
|
# Important
|
|
259
263
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
260
264
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
261
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
262
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${
|
|
263
|
-
`)}function
|
|
264
|
-
`)}function
|
|
265
|
-
`))!==-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(`${
|
|
266
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${
|
|
267
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${
|
|
268
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
269
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
270
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
271
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
272
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${
|
|
273
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${
|
|
274
|
-
`);return}}this._safeWrite(`${
|
|
275
|
-
`)}};
|
|
265
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Gi=["interactive","semi-auto","autonomous"],zi="interactive";function df(t){return Gi.includes(t)?(zi=t,!0):!1}function ff(){return zi}Ki.exports={createPlan:Yd,getActivePlan:Vd,setPlanMode:Xd,isPlanMode:Qd,approvePlan:Zd,startExecution:ef,updateStep:tf,formatPlan:nf,savePlan:sf,loadPlan:of,listPlans:rf,clearPlan:lf,getPlanModePrompt:uf,setPlanContent:af,getPlanContent:cf,PLAN_MODE_ALLOWED_TOOLS:Bi,setAutonomyLevel:df,getAutonomyLevel:ff,AUTONOMY_LEVELS:Gi}});var sa=O((mh,na)=>{var{C:g}=Q();function mf(t){if(!t)return"";let e=t.split(`
|
|
266
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${g.dim}${"\u2500".repeat(40)}${g.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${g.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${g.reset}`)}continue}if(n){s.push(` ${Us(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${g.bold}${g.cyan} ${Ze(r.substring(4))}${g.reset}`);continue}if(r.startsWith("## ")){s.push(`${g.bold}${g.cyan} ${Ze(r.substring(3))}${g.reset}`);continue}if(r.startsWith("# ")){s.push(`${g.bold}${g.cyan}${Ze(r.substring(2))}${g.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${a}${g.cyan}\u2022${g.reset} ${et(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){s.push(`${a[1]}${g.cyan}${a[2]}.${g.reset} ${et(a[3])}`);continue}}s.push(et(r))}return s.join(`
|
|
267
|
+
`)}function Ze(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function et(t){return t?t.replace(/`([^`]+)`/g,`${g.cyan}$1${g.reset}`).replace(/\*\*([^*]+)\*\*/g,`${g.bold}$1${g.reset}`).replace(/\*([^*]+)\*/g,`${g.dim}$1${g.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${g.cyan}$1${g.reset} ${g.dim}($2)${g.reset}`):""}function Us(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ji(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Yi(t):e==="json"||e==="jsonc"?Vi(t):e==="python"||e==="py"?Xi(t):e==="go"||e==="golang"?Qi(t):e==="rust"||e==="rs"?Zi(t):e==="css"||e==="scss"||e==="less"?ea(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?ta(t):t:""}function Ji(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,`${g.yellow}$1${g.reset}`),r=r.replace(e,`${g.magenta}$1${g.reset}`),r=r.replace(s,`${g.green}$&${g.reset}`),r=r.replace(n,`${g.dim}$1${g.reset}`),r}function Yi(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${g.cyan}$1${g.reset}`),r=r.replace(e,`$1${g.green}$2${g.reset}`),r=r.replace(n,`${g.yellow}$&${g.reset}`),r=r.replace(o,`${g.dim}$1${g.reset}`),r}function Vi(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,`${g.cyan}$1${g.reset}:`),r=r.replace(s,`: ${g.green}$1${g.reset}`),r=r.replace(n,`: ${g.yellow}$1${g.reset}`),r=r.replace(o,`: ${g.magenta}$1${g.reset}`),r}function Xi(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,a=t;return a=a.replace(o,`${g.yellow}$1${g.reset}`),a=a.replace(e,`${g.magenta}$1${g.reset}`),a=a.replace(r,`${g.cyan}$1${g.reset}`),a=a.replace(s,`${g.green}$&${g.reset}`),a=a.replace(n,`${g.dim}$1${g.reset}`),a}function Qi(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${g.yellow}$1${g.reset}`),a=a.replace(s,`${g.cyan}$1${g.reset}`),a=a.replace(e,`${g.magenta}$1${g.reset}`),a=a.replace(n,`${g.green}$&${g.reset}`),a=a.replace(o,`${g.dim}$1${g.reset}`),a}function Zi(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${g.yellow}$1${g.reset}`),c=c.replace(s,`${g.cyan}$1${g.reset}`),c=c.replace(e,`${g.magenta}$1${g.reset}`),c=c.replace(a,`${g.yellow}$1${g.reset}`),c=c.replace(n,`${g.green}$&${g.reset}`),c=c.replace(o,`${g.dim}$1${g.reset}`),c}function ea(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,a=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(a,`${g.yellow}$1${g.reset}`),c=c.replace(o,`${g.yellow}$1${g.reset}`),c=c.replace(e,`$1${g.cyan}$2${g.reset}:`),c=c.replace(n,`$1${g.magenta}$&${g.reset}`),c=c.replace(r,`${g.dim}$1${g.reset}`),c}function ta(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(o,`${g.dim}$1${g.reset}`),a=a.replace(n,`${g.green}$&${g.reset}`),a=a.replace(e,`<${g.magenta}$1${g.reset}`),a=a.replace(s,` ${g.cyan}$1${g.reset}=`),a=a.replace(r,`${g.yellow}$1${g.reset}`),a}function pf(t,e){if(!t||t.length===0)return"";let s=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),n=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),o=t.map((a,c)=>` ${g.bold}${a.padEnd(s[c])}${g.reset} `).join("\u2502"),r=[];r.push(`${g.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${g.reset}`),r.push(`${g.dim}\u2502${g.reset}${o}${g.dim}\u2502${g.reset}`),r.push(`${g.dim}\u251C${n}\u2524${g.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(s[u])} `).join(`${g.dim}\u2502${g.reset}`);r.push(`${g.dim}\u2502${g.reset}${c}${g.dim}\u2502${g.reset}`)}return r.push(`${g.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${g.reset}`),r.join(`
|
|
268
|
+
`)}function hf(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),a=n-r,c=o>=100?g.green:o>50?g.yellow:g.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${g.dim}${"\u2591".repeat(a)}${g.reset} ${o}% (${e}/${s})`}var Fs=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(`
|
|
269
|
+
`))!==-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(`${g.dim}${"\u2500".repeat(40)}${g.reset}
|
|
270
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${g.dim}${"\u2500".repeat(40)}${g.reset}
|
|
271
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${g.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${g.reset}
|
|
272
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Us(e,this.codeBlockLang)}
|
|
273
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${g.bold}${g.cyan} ${Ze(e.substring(4))}${g.reset}
|
|
274
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${g.bold}${g.cyan} ${Ze(e.substring(3))}${g.reset}
|
|
275
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${g.bold}${g.cyan}${Ze(e.substring(2))}${g.reset}
|
|
276
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${g.cyan}\u2022${g.reset} ${et(n)}
|
|
277
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${g.cyan}${s[2]}.${g.reset} ${et(s[3])}
|
|
278
|
+
`);return}}this._safeWrite(`${et(e)}
|
|
279
|
+
`)}};na.exports={renderMarkdown:mf,renderInline:et,stripHeadingMarkers:Ze,highlightCode:Us,highlightJS:Ji,highlightBash:Yi,highlightJSON:Vi,highlightPython:Xi,highlightGo:Qi,highlightRust:Zi,highlightCSS:ea,highlightHTML:ta,renderTable:pf,renderProgress:hf,StreamRenderer:Fs}});var Hs=O((ph,aa)=>{var{execSync:gf}=require("child_process"),Ws=require("path"),Ut=require("fs"),Bs=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function oa(){return Ws.join(process.cwd(),".nex","hooks")}function $f(){return Ws.join(process.cwd(),".nex","config.json")}function ra(){let t=$f();if(!Ut.existsSync(t))return{};try{return JSON.parse(Ut.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Nn(t){if(!Bs.includes(t))return[];let e=[],s=oa(),n=Ws.join(s,t);Ut.existsSync(n)&&e.push(n);let o=ra();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function ia(t,e={},s=3e4){try{return{success:!0,output:gf(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 yf(t,e={}){let s=Nn(t);if(s.length===0)return[];let n={};for(let[r,a]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(a);let o=[];for(let r of s){let a=ia(r,n);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function wf(t){return Nn(t).length>0}function bf(){let t=[];for(let e of Bs){let s=Nn(e);s.length>0&&t.push({event:e,commands:s})}return t}function xf(){let t=oa();return Ut.existsSync(t)||Ut.mkdirSync(t,{recursive:!0}),t}aa.exports={HOOK_EVENTS:Bs,loadHookConfig:ra,getHooksForEvent:Nn,executeHook:ia,runHooks:yf,hasHooks:wf,listHooks:bf,initHooksDir:xf}});var Z=O(($h,ba)=>{var{C:_,Spinner:gt,TaskProgress:kf,formatToolCall:_f,formatResult:vf,formatToolSummary:da,setActiveTaskProgress:hh}=Q(),{callStream:Sf}=re(),{parseToolArgs:Tf}=rn(),{executeTool:Cf}=qe(),{gatherProjectContext:Ef}=Rs(),{fitToContext:Af,forceCompress:Gs,getUsage:Mf,estimateTokens:Rf}=xe(),{autoSave:tt}=Ve(),{getMemoryContext:Nf}=De(),{checkPermission:Of,setPermission:Pf,savePermissions:If}=Ft(),{confirm:fa,setAllowAlwaysHandler:Lf}=Te(),{isPlanMode:qn,getPlanModePrompt:qf,PLAN_MODE_ALLOWED_TOOLS:ma,setPlanContent:jf}=ht(),{StreamRenderer:Df}=sa(),{runHooks:ca}=Hs(),{routeMCPCall:Ff,getMCPToolDefinitions:Uf}=dn(),{getSkillInstructions:Wf,getSkillToolDefinitions:Bf,routeSkillCall:Hf}=Et(),{trackUsage:Gf}=ct(),{validateToolArgs:zf}=hs(),{filterToolsForModel:la,getModelTier:Kf,PROVIDER_DEFAULT_TIER:gh}=ks(),{getConfiguredProviders:Jf,getActiveProviderName:Yf,getActiveModelId:Vf}=re(),pa=require("fs"),ha=require("path"),ua=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Xf(t){let e=[],s;for(ua.lastIndex=0;(s=ua.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):ha.resolve(n);pa.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Qf(t){let e=pa.readFileSync(t),s=ha.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 ga(t){let e=Xf(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}=Qf(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var zs=null,Ks=null,Js=null;function $t(){if(zs===null){let{TOOL_DEFINITIONS:t}=qe();zs=t}return Ks===null&&(Ks=Bf()),Js===null&&(Js=Uf()),[...zs,...Ks,...Js]}var Qs=50;function Zf(t){Number.isFinite(t)&&t>0&&(Qs=t)}var Pn=()=>null;function em(t){Pn=t}var Wt=null,Zs=null,yt=null,In=new Map,tm=1e4,nm=6e3;function sm(t){if(Rf(t)>tm)try{let{compressToolResult:s}=xe();return s(t,nm)}catch{return t}return t}function $a(t){try{let{getActiveModel:e}=re(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(In.has(n))return In.get(n);let o=la(t);return In.set(n,o),o}catch{return la(t)}}function om(){In.clear()}async function ya(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=De(),a=r();a&&o.push(`memory:${a}`)}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function rm(){Wt=null,Zs=null,yt=null}var im=new Set(["read_file","list_directory","search_files","glob","grep","web_fetch","web_search","git_status","git_diff","git_log","task_list","gh_run_list","gh_run_view"]),Ys=5,Vs=3,On=2,am=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),cm=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function lm(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{}}Lf(t=>{Pf(t,"allow"),If(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function um(t){let e=t.function.name,s=Tf(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=$t().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.
|
|
276
280
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
277
281
|
|
|
278
282
|
Expected JSON schema for "${e}":
|
|
279
283
|
${u}
|
|
280
284
|
|
|
281
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
282
|
-
`)[0]}${
|
|
285
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=zf(e,s);if(!o.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
286
|
+
`)[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(qn()&&!ma.has(e))return console.log(`${_.yellow} \u2717 ${e}: blocked in plan mode${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let a=Of(e);if(a==="deny")return console.log(`${_.red} \u2717 ${e}: denied by permissions${_.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await fa(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 dm(t,e,s={}){let n=await Hf(t,e);if(n!==null)return n;let o=await Ff(t,e);return o!==null?o:Cf(t,e,s)}function fm(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 Xs(t,e=!1){e||console.log(_f(t.fnName,t.args)),ca("pre-tool",{tool_name:t.fnName});let s=await dm(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
283
287
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
284
|
-
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),
|
|
288
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=da(t.fnName,t.args,o,a);return e||(console.log(vf(o)),console.log(c)),ca("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:sm(o),tool_call_id:t.callId},summary:c}}async function mm(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],a=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=fm(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}a=new gt(u),a.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Xs(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>Xs(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(da(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(im.has(u.fnName))r.push(l);else{await c(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Xs(u,e);n[l]=d,o.push(f)}}if(await c(),a&&a.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return n}var ie=[],Ln=[];function pm(t){Ln.push(t.trim())}function hm(){return Ln.length===0?null:Ln.splice(0,Ln.length).join(`
|
|
289
|
+
`)}function gm(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE;if(!t&&!e&&!s)return"";let n=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
290
|
+
`];t&&n.push(`RESPONSE LANGUAGE: You MUST always respond in ${t}. 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. ${t} only.`);let o=e||(t?"English":null);o&&n.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${o}.`);let r=s||(t?"English":null);return r&&n.push(`COMMIT MESSAGES: Write all git commit messages in ${r}.`),t&&n.push(`
|
|
291
|
+
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),n.join(`
|
|
292
|
+
`)+`
|
|
293
|
+
|
|
294
|
+
`}function $m(){if(yt!==null)return yt;try{let e=Jf().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Kf(r.id,o.name),name:r.name})));if(e.length<2)return yt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
285
295
|
# Sub-Agent Model Routing
|
|
286
296
|
|
|
287
297
|
`;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 |
|
|
288
298
|
|---|---|---|
|
|
289
299
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
290
|
-
`;return yt=n,n}catch{return yt="",""}}async function
|
|
300
|
+
`;return yt=n,n}catch{return yt="",""}}async function wa(){let t=await ya();if(Wt!==null&&t===Zs)return Wt;let e=await Ef(process.cwd()),s=Nf(),n=Wf(),o=qn()?qf():"",r=gm();return Wt=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
291
301
|
|
|
292
302
|
WORKING DIRECTORY: ${process.cwd()}
|
|
293
303
|
All relative paths resolve from this directory.
|
|
294
|
-
|
|
295
|
-
PROJECT CONTEXT:
|
|
304
|
+
${r?`
|
|
305
|
+
${r}`:""}PROJECT CONTEXT:
|
|
296
306
|
${e}
|
|
297
307
|
${s?`
|
|
298
308
|
${s}
|
|
@@ -359,7 +369,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
359
369
|
- Good for: reading multiple files, analyzing separate modules.
|
|
360
370
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
361
371
|
- Max 5 parallel agents.
|
|
362
|
-
${
|
|
372
|
+
${$m()}
|
|
363
373
|
|
|
364
374
|
# Edit Reliability (Critical)
|
|
365
375
|
|
|
@@ -399,15 +409,14 @@ When a tool call returns ERROR:
|
|
|
399
409
|
- Prefer creating new git commits over amending. Never force-push without explicit permission.
|
|
400
410
|
- If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
|
|
401
411
|
|
|
402
|
-
`,
|
|
403
|
-
${
|
|
404
|
-
${
|
|
405
|
-
${
|
|
406
|
-
`),await
|
|
407
|
-
`)
|
|
408
|
-
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${z.bold}${z.cyan}${n}${z.reset}`),$.push(` ${z.dim}${o}${z.reset}`),$.push("");let{start:k,end:T}=f();k>0&&$.push(` ${z.dim}\u2191 more${z.reset}`);for(let S=k;S<T;S++){let _=e[S];if(_.isHeader){$.push(` ${z.bold}${z.dim}${_.label}${z.reset}`);continue}let C=a[c]===S,E=C?`${z.cyan}> `:" ",P=_.isCurrent?` ${z.yellow}<current>${z.reset}`:"";C?$.push(`${E}${z.bold}${_.label}${z.reset}${P}`):$.push(`${E}${z.dim}${_.label}${z.reset}${P}`)}T<e.length&&$.push(` ${z.dim}\u2193 more${z.reset}`);let b=$.join(`
|
|
412
|
+
`,Zs=t,Wt}function ym(){ie=[]}function wm(){return ie.length}function bm(){return ie}function xm(t){ie=t}function nt(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}a+=" \u2500\u2500",console.log(`
|
|
413
|
+
${_.dim} ${a}${_.reset}`),s.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function km(t){let e=ga(t);ie.push({role:"user",content:e});let{setOnChange:s}=$n(),n=null,o=0;s((I,q)=>{I==="create"?(n&&n.stop(),n=new kf(q.name,q.tasks),n.setStats({tokens:o}),n.start()):I==="update"&&n?n.updateTask(q.id,q.status):I==="clear"&&n&&(n.stop(),n=null)});let a=[{role:"system",content:await wa()},...ie],c=new gt("Thinking...");c.start();let l=$t(),{messages:u,compressed:d,compacted:f,tokensRemoved:m}=await Af(a,l),h=Mf(a,l);if(c.stop(),f)console.log(`${_.dim} [context compacted \u2014 summary (~${m} tokens freed)]${_.reset}`);else if(d){let I=h.limit>0?Math.round(m/h.limit*100):0;console.log(`${_.dim} [context compressed \u2014 ~${m} tokens freed (${I}%)]${_.reset}`)}h.percentage>85&&console.log(`${_.yellow} \u26A0 Context ${Math.round(h.percentage)}% full \u2014 consider /clear or /save + start fresh${_.reset}`);let p=u,x=0,w=0,$=0,k=0,T=0,b=new Map,S=new Set,v=new Set,C=Date.now(),E,P=Qs,L=0,M=10;e:for(;;){for(E=0;E<P;E++){let D=function(){q||(console.log(`${_.cyan} \u25C6 Step ${T}${_.reset}`),q=!0)};var N=D;if(Pn()?.aborted)break;let q=!0,W=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let A=T>0?`Thinking... (step ${T+1})`:"Thinking...";W=new gt(A),W.start()}let z=!0,ne="",se=new Df,be,zt=Date.now(),bt=!1,Wn=new AbortController,go=setInterval(()=>{let A=Date.now()-zt;A>=cm?(se._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(A/1e3)}s \u2014 aborting and retrying${_.reset}`),Wn.abort()):A>=am&&!bt&&(bt=!0,se._clearCursorLine(),console.log(`${_.yellow} \u26A0 No tokens received for ${Math.round(A/1e3)}s \u2014 waiting...${_.reset}`))},5e3),me="",Se=null;try{let A=$a($t()),j=qn()?A.filter(oe=>ma.has(oe.function.name)):A,st=Pn(),F=new AbortController;st&&st.addEventListener("abort",()=>F.abort(),{once:!0}),Wn.signal.addEventListener("abort",()=>F.abort(),{once:!0}),be=await Sf(p,j,{signal:F.signal,onToken:oe=>{zt=Date.now(),bt=!1,me+=oe,process.stdout.isTTY?Se||(Se=setTimeout(()=>{me&&se&&se.push(me),me="",Se=null},50)):(se.push(me),me=""),z&&(n&&!n._paused?n.pause():W&&W.stop(),D(),se.startCursor(),z=!1),ne+=oe}})}catch(A){if(clearInterval(go),Se&&(clearTimeout(Se),Se=null),me&&se&&(se.push(me),me=""),n&&!n._paused&&n.pause(),W&&W.stop(),se.stopCursor(),Wn.signal.aborted&&!Pn()?.aborted){if($++,$>On){if(k<1){k++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Gs(p,ge);p=xt,console.log(`${_.dim} [force-compressed \u2014 ~${kt} tokens freed]${_.reset}`),$=0,E--;continue}console.log(`${_.red} \u2717 Stream stale: max retries (${On}) exceeded. The model may be overloaded \u2014 try again or switch models.${_.reset}`),n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);break}let F=$===1?3e3:5e3;if($>=2&&k<1){k++,console.log(`${_.yellow} \u26A0 Stale retry ${$}/${On} \u2014 force-compressing before retry...${_.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Gs(p,ge);p=xt,console.log(`${_.dim} [force-compressed \u2014 ~${kt} tokens freed]${_.reset}`)}else console.log(`${_.yellow} \u26A0 Stale retry ${$}/${On} \u2014 retrying in ${F/1e3}s...${_.reset}`);let oe=new gt(`Waiting ${F/1e3}s before retry...`);oe.start(),await new Promise(ge=>setTimeout(ge,F)),oe.stop(),E--;continue}if(A.name==="AbortError"||A.name==="CanceledError"||A.message?.includes("canceled")||A.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);break}let j=A.message;if(A.code==="ECONNREFUSED"||A.message.includes("ECONNREFUSED"))j="Connection refused \u2014 please check your internet connection or API endpoint";else if(A.code==="ENOTFOUND"||A.message.includes("ENOTFOUND"))j="Network error \u2014 could not reach the API server. Please check your connection";else if(A.code==="ETIMEDOUT"||A.message.includes("timeout"))j="Request timed out \u2014 the API server took too long to respond. Please try again";else if(A.message.includes("401")||A.message.includes("Unauthorized"))j="Authentication failed \u2014 please check your API key in the .env file";else if(A.message.includes("403")||A.message.includes("Forbidden"))j="Access denied \u2014 your API key may not have permission for this model";else if(A.message.includes("400")){let F=(A.message||"").toLowerCase(),oe=F.includes("context")||F.includes("token")||F.includes("length")||F.includes("too long")||F.includes("too many")||F.includes("prompt")||F.includes("size")||F.includes("exceeds")||F.includes("num_ctx")||F.includes("input");if(oe&&k<1){k++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Gs(p,ge);p=xt,console.log(`${_.dim} [force-compressed \u2014 ~${kt} tokens freed]${_.reset}`),E--;continue}oe?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 A.message.includes("500")||A.message.includes("502")||A.message.includes("503")||A.message.includes("504")?j="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(A.message.includes("fetch failed")||A.message.includes("fetch"))&&(j="Network request failed \u2014 please check your internet connection");if(console.log(`${_.red} \u2717 ${j}${_.reset}`),A.message.includes("429")){if(x++,x>Ys){console.log(`${_.red} Rate limit: max retries (${Ys}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);break}let F=Math.min(1e4*Math.pow(2,x-1),12e4),oe=new gt(`Rate limit \u2014 waiting ${Math.round(F/1e3)}s (retry ${x}/${Ys})`);oe.start(),await new Promise(ge=>setTimeout(ge,F)),oe.stop();continue}if(A.message.includes("socket disconnected")||A.message.includes("TLS")||A.message.includes("ECONNRESET")||A.message.includes("ECONNABORTED")||A.message.includes("ETIMEDOUT")||A.code==="ECONNRESET"||A.code==="ECONNABORTED"){if(w++,w>Vs){console.log(`${_.red} Network error: max retries (${Vs}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);break}let F=Math.min(2e3*Math.pow(2,w-1),3e4),oe=new gt(`Network error \u2014 retrying in ${Math.round(F/1e3)}s (${w}/${Vs})`);oe.start(),await new Promise(ge=>setTimeout(ge,F)),oe.stop(),E--;continue}n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);break}clearInterval(go),z&&(n&&!n._paused&&n.pause(),W&&W.stop()),Se&&(clearTimeout(Se),Se=null),me&&se&&(se.push(me),me=""),ne&&se.flush(),w=0,$=0,be&&be.usage&&(Gf(Yf(),Vf(),be.usage.prompt_tokens||0,be.usage.completion_tokens||0),o+=(be.usage.prompt_tokens||0)+(be.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:Bn,tool_calls:Be}=be,Hn={role:"assistant",content:Bn||""};if(Be&&Be.length>0&&(Hn.tool_calls=Be),ie.push(Hn),p.push(Hn),!Be||Be.length===0){let A=(Bn||"").trim().length>0||ne.trim().length>0;if(!A&&T>0&&E<Qs-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."};p.push(j);continue}if(qn()&&A){let j=(Bn||ne||"").trim();jf(j),lm(j),console.log(`
|
|
414
|
+
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);return}T++,T>1&&(q=!1);for(let A of Be){let j=A.function.name;b.set(j,(b.get(j)||0)+1)}let Gn=await Promise.all(Be.map(A=>um(A))),$o=n?{skipSpinner:!0,skipSummaries:!0}:{};$o.skipSummaries||D(),n&&n._paused&&n.resume();let yo=await mm(Gn,!0,$o);for(let A=0;A<Gn.length;A++){let j=Gn[A];if(!j.canExecute)continue;let st=yo[A].content,F=!st.startsWith("ERROR")&&!st.includes("CANCELLED");F&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&S.add(j.args.path),F&&j.fnName==="read_file"&&j.args&&j.args.path&&v.add(j.args.path)}for(let A of yo)ie.push(A),p.push(A);let wo=hm();if(wo){let A={role:"user",content:`[User note mid-run]: ${wo}`};ie.push(A),p.push(A),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(E>=P){n&&(n.stop(),n=null),s(null),nt(T,b,S,v,C),tt(ie);let{getActiveProviderName:I}=re();if(I()==="ollama"&&L<M){L++,P+=20,console.log(`${_.dim} \u2500\u2500 auto-extending to ${P} turns \u2500\u2500${_.reset}`);continue e}if(console.log(`
|
|
415
|
+
${_.yellow}\u26A0 Max iterations (${P}) reached.${_.reset}`),await fa(" Continue for 20 more turns?")){P+=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}ba.exports={processInput:km,clearConversation:ym,getConversationLength:wm,getConversationMessages:bm,setConversationMessages:xm,setAbortSignalGetter:em,setMaxIterations:Zf,invalidateSystemPromptCache:rm,clearToolFilterCache:om,getCachedFilteredTools:$a,buildSystemPrompt:wa,getProjectContextHash:ya,buildUserContent:ga,injectMidRunNote:pm}});var re=O((yh,Ta)=>{var{OllamaProvider:_m}=qo(),{OpenAIProvider:vm}=nr(),{AnthropicProvider:Sm}=ir(),{GeminiProvider:Tm}=ur(),{LocalProvider:Cm}=mr(),{checkBudget:Em}=ct(),xa={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"}},ka={};for(let[t,e]of Object.entries(xa))for(let s of Object.values(e))ka[s]=t;function _a(t,e){let s=ka[t];return s&&xa[s][e]||t}var te={},de=null,ee=null,Bt=[];function he(){if(Object.keys(te).length>0)return;wt("ollama",new _m),wt("openai",new vm),wt("anthropic",new Sm),wt("gemini",new Tm),wt("local",new Cm);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;te[t]?(de=t,ee=e||te[t].defaultModel):(de="ollama",ee="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Bt=s.split(",").map(n=>n.trim()).filter(Boolean))}function wt(t,e){te[t]=e}function Am(t){return he(),te[t]||null}function eo(){return he(),te[de]||null}function Mm(){return he(),de}function Rm(){return he(),ee}function Nm(){he();let t=eo();if(!t)return{id:ee,name:ee,provider:de};let e=t.getModel(ee);return e?{...e,provider:de}:{id:ee,name:ee,provider:de}}function va(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(te[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Om(t){he();let{provider:e,model:s}=va(t);if(e){let o=te[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(de=e,ee=s,jn(),!0):!1}let n=eo();if(n&&n.getModel(s))return ee=s,jn(),!0;for(let[o,r]of Object.entries(te))if(r.getModel(s))return de=o,ee=s,jn(),!0;return!1}function jn(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Z();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=xe();t()}catch{}}function Pm(){he();let t=new Set;for(let e of Object.values(te))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Im(){return he(),Object.entries(te).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===de&&s.id===ee}))}))}function Lm(){he();let t=[];for(let[e,s]of Object.entries(te)){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 qm(t){Bt=Array.isArray(t)?t:[]}function jm(){return[...Bt]}function Dm(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 Sa(t){let e=[de,...Bt.filter(r=>r!==de)],s,n=0,o=0;for(let r=0;r<e.length;r++){let a=e[r],c=te[a];if(!c||!c.isConfigured())continue;o++;let l=Em(a);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?_a(ee,a):ee;return u&&d!==ee&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
416
|
+
`),await t(c,a,d)}catch(u){if(s=u,Dm(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."):s||new Error("No configured provider available")}async function Fm(t,e,s={}){return he(),Sa((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Um(t,e,s={}){if(he(),s.provider){let n=te[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||ee,...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 Sa(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(a){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw a}})}function Wm(){he();let t=[];for(let[e,s]of Object.entries(te))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Bm(){for(let t of Object.keys(te))delete te[t];de=null,ee=null,Bt=[]}Ta.exports={registerProvider:wt,getProvider:Am,getActiveProvider:eo,getActiveProviderName:Mm,getActiveModelId:Rm,getActiveModel:Nm,setActiveModel:Om,getModelNames:Pm,parseModelSpec:va,listProviders:Im,listAllModels:Lm,callStream:Fm,callChat:Um,getConfiguredProviders:Wm,setFallbackChain:qm,getFallbackChain:jm,resolveModelForProvider:_a,_reset:Bm}});var Aa=O((wh,Ea)=>{var{C:G}=Q(),{listProviders:Hm,getActiveProviderName:Gm,getActiveModelId:zm,setActiveModel:Km}=re();function Ca(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let a=e.map(($,k)=>$.isHeader?-1:k).filter($=>$>=0);if(a.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?a.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=a[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let S=0;S<m;S++)process.stdout.write(`\x1B[2K
|
|
417
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${G.bold}${G.cyan}${n}${G.reset}`),$.push(` ${G.dim}${o}${G.reset}`),$.push("");let{start:k,end:T}=f();k>0&&$.push(` ${G.dim}\u2191 more${G.reset}`);for(let S=k;S<T;S++){let v=e[S];if(v.isHeader){$.push(` ${G.bold}${G.dim}${v.label}${G.reset}`);continue}let C=a[l]===S,E=C?`${G.cyan}> `:" ",P=v.isCurrent?` ${G.yellow}<current>${G.reset}`:"";C?$.push(`${E}${G.bold}${v.label}${G.reset}${P}`):$.push(`${E}${G.dim}${v.label}${G.reset}${P}`)}T<e.length&&$.push(` ${G.dim}\u2193 more${G.reset}`);let b=$.join(`
|
|
409
418
|
`);process.stdout.write(b+`
|
|
410
|
-
`),m=$.length}t.pause();let
|
|
419
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function x(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){l>0&&(l--,h());return}if(k.name==="down"||k.ctrl&&k.name==="n"){l<a.length-1&&(l++,h());return}if(k.name==="return"){let T=e[a[l]];x(),r(T?T.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){x(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function Jm(t){let e=Hm(),s=Gm(),n=zm(),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 Ca(t,o,{title:"Select Model"});return r?(Km(r),console.log(`${G.green}Switched to ${r}${G.reset}`),!0):(console.log(`${G.dim}Cancelled${G.reset}`),!1)}Ea.exports={pickFromList:Ca,showModelPicker:Jm}});var no=O((xh,Pa)=>{var to=require("fs"),Ym=require("path"),{callChat:Vm}=re(),{remember:Xm,listMemories:bh,recall:Qm}=De(),Ma=4,Zm=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
411
420
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
412
421
|
|
|
413
422
|
Return ONLY valid JSON in this exact format:
|
|
@@ -433,17 +442,17 @@ Rules:
|
|
|
433
442
|
- value: concise actionable instruction, max 120 chars
|
|
434
443
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
435
444
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
436
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
445
|
+
- Return ONLY the JSON, no markdown, no explanation`;function ep(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(`
|
|
437
446
|
|
|
438
|
-
`)}async function
|
|
447
|
+
`)}async function Ra(t){if(t.filter(o=>o.role==="user").length<Ma)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=ep(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:Zm},{role:"user",content:`Conversation to analyze:
|
|
439
448
|
|
|
440
|
-
${s}`}];try{let a=((await
|
|
449
|
+
${s}`}];try{let a=((await Vm(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(a[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Na(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!o||!r)continue;let a=Qm(o);a!==r&&(Xm(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Oa(t){if(!t||t.length===0)return[];let e=Ym.join(process.cwd(),"NEX.md"),s="";try{to.existsSync(e)&&(s=to.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let a=r.trim();if(!a)continue;let c=a.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(a),o=o?o.endsWith(`
|
|
441
450
|
`)?o+a:o+`
|
|
442
451
|
`+a:a)}return n.length>0&&(o.endsWith(`
|
|
443
452
|
`)||(o+=`
|
|
444
|
-
`),
|
|
453
|
+
`),to.writeFileSync(e,o,"utf-8")),n}async function tp(t){let e=await Ra(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Na(e.memories),n=Oa(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}Pa.exports={learnFromSession:tp,reflectOnSession:Ra,applyMemories:Na,applyNexAdditions:Oa,LEARN_MIN_MESSAGES:Ma}});var qa=O((kh,La)=>{var np=require("axios"),Ht=require("fs"),Ia=require("path"),sp="nex-code",so=Ia.join(process.cwd(),".nex"),oo=Ia.join(so,"last-version-check");Ht.existsSync(so)||Ht.mkdirSync(so,{recursive:!0});async function op(){try{let t=ip(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};ap(e);let s=rp(),o=(await np.get(`https://registry.npmjs.org/${sp}/latest`,{timeout:5e3})).data.version,r=cp(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function rp(){return Kt().version}function ip(){try{if(Ht.existsSync(oo)){let t=Ht.readFileSync(oo,"utf8");return parseInt(t,10)}}catch{}return null}function ap(t){try{Ht.writeFileSync(oo,t.toString())}catch{}}function cp(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}}La.exports={checkForNewVersion:op}});var Qa=O((vh,Xa)=>{var lp=require("readline"),We=require("fs"),ve=require("path"),{C:i,banner:up,cleanupTerminal:ja}=Q(),{listProviders:io,getActiveProviderName:Fe,listAllModels:_h,setFallbackChain:dp,getFallbackChain:fp,getProvider:mp}=re(),{flushAutoSave:Da}=Ve(),{getActiveModel:Ue,setActiveModel:Fa}=rn(),{printContext:Ua}=Rs(),{loadAllSkills:pp,getSkillCommands:ao,handleSkillCommand:hp}=Et(),{setReadlineInterface:gp,setAutoConfirm:$p,getAutoConfirm:Wa}=Te(),Fn=process.cwd(),Pe=null;function Ba(){return Pe?.signal??null}var Un=[{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:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review",desc:"Code review on current diff or file"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/exit",desc:"Quit"}];function Ha(){let t=ao(),e=[...Un,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of Un)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o}${i.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
445
454
|
${i.dim}Type /help for detailed usage${i.reset}
|
|
446
|
-
`)}function
|
|
455
|
+
`)}function Ga(t){try{let e,s;t.endsWith("/")||t.endsWith(ve.sep)?(e=t,s=""):(e=ve.dirname(t),s=ve.basename(t)),e.startsWith("~")&&(e=ve.join(require("os").homedir(),e.slice(1)));let n=ve.isAbsolute(e)?e:ve.resolve(Fn,e);if(!We.existsSync(n)||!We.statSync(n).isDirectory())return[];let o=We.readdirSync(n,{withFileTypes:!0}),r=[];for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules"||s&&!a.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(ve.sep)?t:ve.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function za(t){if(t.startsWith("/")){let n=[...Un,...ao()],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("~"))?[Ga(s),s]:[[],t]}function Ka(){console.log(`
|
|
447
456
|
${i.bold}${i.cyan}Commands:${i.reset}
|
|
448
457
|
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
449
458
|
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
@@ -504,75 +513,76 @@ ${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
|
504
513
|
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
505
514
|
|
|
506
515
|
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
507
|
-
`)}function
|
|
508
|
-
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${n.provider}${i.reset}${a}`);for(let
|
|
509
|
-
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(
|
|
510
|
-
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${
|
|
516
|
+
`)}function Ja(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(s)}${i.dim}${"\u2591".repeat(n)}${i.reset} ${t}%`}function ro(){let t=io(),e=Fe(),s=Ue();console.log(`
|
|
517
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${n.provider}${i.reset}${a}`);for(let c of n.models){let l=c.id===s.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function Ya(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return Ka(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Aa();await r(e)}else{let r=Ue(),a=Fe();console.log(`${i.bold}${i.cyan}Active model:${i.reset} ${i.dim}${a}:${r.id} (${r.name})${i.reset}`),console.log(`${i.gray}Use /model <provider:model> to switch. /providers to see all.${i.reset}`)}return!0}if(o==="list")return ro(),!0;if(Fa(o)){let r=Ue(),a=Fe();console.log(`${i.green}Switched to ${a}:${r.id} (${r.name})${i.reset}`)}else console.log(`${i.red}Unknown model: ${o}${i.reset}`),console.log(`${i.gray}Use /providers to see available models${i.reset}`);return!0}case"/providers":return ro(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let a=fp();return a.length===0?(console.log(`${i.dim}No fallback chain configured${i.reset}`),console.log(`${i.dim}Use /fallback anthropic,openai,local to set${i.reset}`)):console.log(`${i.bold}${i.cyan}Fallback chain:${i.reset} ${a.join(" \u2192 ")}`),!0}let r=o.split(",").map(a=>a.trim()).filter(Boolean);return dp(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=Z(),{getUsage:r}=xe(),{TOOL_DEFINITIONS:a}=qe(),c=o(),l=r(c,a),u=Ue(),d=Fe();console.log(`
|
|
518
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=Ja(l.percentage);return console.log(` ${f}`),console.log(`
|
|
519
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=ct();return n.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
511
520
|
${o()}
|
|
512
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:
|
|
513
|
-
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let x=!1;for(let w of
|
|
521
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=ct(),d=n[0];if(!d){let h=o(),p=io();console.log(`
|
|
522
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let x=!1;for(let w of p){let $=r(w.provider),k=h[w.provider];if(k!==void 0){x=!0;let T=Math.min(100,Math.round($/k*100)),b=10,S=Math.round(T/100*b),v=b-S,E=`${T>=100?i.red:T>=80?i.yellow:i.green}${"\u2588".repeat(S)}${i.dim}${"\u2591".repeat(v)}${i.reset}`;console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} / $${k.toFixed(2)} (${T}%) ${E}`)}else w.provider==="ollama"||w.provider==="local"?console.log(` ${i.bold}${w.provider}:${i.reset} ${i.dim}free (no limit)${i.reset}`):$>0&&console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} ${i.dim}(no limit)${i.reset}`)}return x||console.log(` ${i.dim}No limits set. Use /budget <provider> <amount> to set one.${i.reset}`),console.log(),!0}let f=n[1];if(!f){let h=a(d);return h.limit!==null?console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} ${i.dim}(no limit)${i.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${i.green}Removed cost limit for ${d}${i.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${i.red}Invalid amount: ${f}. Use a positive number or 'off'.${i.reset}`),!0):(u(d,m),l(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=Z(),{clearHistory:a}=ut(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=no();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${i.green}${f} learning(s) saved${i.reset}
|
|
514
523
|
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
515
524
|
`)}).catch(()=>process.stdout.write(`
|
|
516
|
-
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await
|
|
517
|
-
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let
|
|
518
|
-
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/learn":{let{learnFromSession:o}=
|
|
525
|
+
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await Ua(Fn),!0;case"/autoconfirm":{let o=!Wa();return $p(o),console.log(`${i.green}Auto-confirm: ${o?"ON":"OFF"}${i.reset}`),o&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:o}=Ve(),{getConversationMessages:r}=Z(),a=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let l=Ue(),u=Fe();return o(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:o}=Ve(),{setConversationMessages:r}=Z(),a=n.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=o(a);return c?(r(c.messages),console.log(`${i.green}Loaded session: ${c.name} (${c.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:o}=Ve(),r=o();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
526
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=Ve(),{setConversationMessages:r}=Z(),a=o();return a?(r(a.messages),console.log(`${i.green}Resumed: ${a.name} (${a.messageCount} messages)${i.reset}`),!0):(console.log(`${i.yellow}No session to resume${i.reset}`),!0)}case"/remember":{let{remember:o}=De(),r=n.join(" ").trim();if(!r)return console.log(`${i.red}Usage: /remember <key>=<value> or /remember <text>${i.reset}`),!0;let a=r.indexOf("="),c,l;return a>0?(c=r.substring(0,a).trim(),l=r.substring(a+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:o}=De(),r=n.join(" ").trim();return r?(o(r)?console.log(`${i.green}Forgotten: ${r}${i.reset}`):console.log(`${i.red}Memory not found: ${r}${i.reset}`),!0):(console.log(`${i.red}Usage: /forget <key>${i.reset}`),!0)}case"/memory":{let{listMemories:o}=De(),r=o();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
527
|
+
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/learn":{let{learnFromSession:o}=no(),{getConversationMessages:r}=Z(),a=r(),c=a.filter(l=>l.role==="user").length;if(c<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${c})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let l=await o(a);if(l.skipped)return console.log(`${i.dim}Session too short${i.reset}`),!0;if(l.error)return console.log(`${i.red}Reflection error: ${l.error}${i.reset}`),!0;if(console.log(""),l.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${l.summary}${i.reset}`),console.log("")),l.applied.length===0&&l.nexAdded.length===0)console.log(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(l.applied.length>0){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:u,value:d,action:f}of l.applied){let m=f==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${m} ${i.bold}${u}${i.reset} = ${d}`)}}if(l.nexAdded.length>0){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let u of l.nexAdded)console.log(` ${i.green}+${i.reset} ${u}`)}}console.log("")}catch(l){console.log(`${i.red}Learn failed: ${l.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=Z(),{getUsage:r}=xe(),{TOOL_DEFINITIONS:a}=qe(),{listMemories:c}=De(),l=o(),u=r(l,a),d=Ue(),f=Fe(),m=c();console.log(`
|
|
519
528
|
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
520
529
|
`);let h=u.percentage>80?i.red:u.percentage>50?i.yellow:i.green;if(console.log(`${i.bold}Context Window:${i.reset} ${h}${u.percentage}%${i.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${i.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${i.reset}`):u.percentage>50?console.log(` ${i.dim}\u2192 Context is filling up, consider /clear soon${i.reset}`):console.log(` ${i.green}\u2192 Context healthy${i.reset}`),console.log(`
|
|
521
|
-
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let T=[...m].sort((
|
|
522
|
-
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let
|
|
523
|
-
${i.bold}Session:${i.reset} ${x} turns, ${
|
|
524
|
-
${i.bold}Quick Wins:${i.reset}`);for(let k of w)console.log(` ${i.cyan}\u2192${i.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:
|
|
530
|
+
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let T=[...m].sort((v,C)=>new Date(C.updatedAt)-new Date(v.updatedAt))[0],b=T?Math.round((Date.now()-new Date(T.updatedAt))/6e4):null,S=b!==null?b<60?`${b}m ago`:`${Math.round(b/60)}h ago`:"?";console.log(` ${i.dim}Latest update: ${S}${i.reset}`),m.length>30&&console.log(` ${i.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${i.reset}`)}console.log(`
|
|
531
|
+
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let x=l.filter(k=>k.role==="user").length;console.log(`
|
|
532
|
+
${i.bold}Session:${i.reset} ${x} turns, ${l.length} messages total`),x>=4&&x%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
533
|
+
${i.bold}Quick Wins:${i.reset}`);for(let k of w)console.log(` ${i.cyan}\u2192${i.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=ht(),{invalidateSystemPromptCache:d}=Z(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){a(),c(!1),d();let m=!!l();console.log(`${i.green}${i.bold}Plan approved!${i.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${i.dim}Plan mode disabled \u2014 all tools now available.${i.reset}`)}else console.log(`${i.red}No plan to approve. Enter plan mode first with /plan${i.reset}`);return!0}return c(!0),d(),console.log(`
|
|
525
534
|
${i.cyan}${i.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${i.reset}
|
|
526
535
|
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
527
536
|
${i.cyan}${i.bold}\u2502${i.reset} ${i.dim}Read-only tools only \xB7 /plan approve to execute${i.reset} ${i.cyan}${i.bold}\u2502${i.reset}
|
|
528
537
|
${i.cyan}${i.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:o}=ht(),r=o();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
529
|
-
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let
|
|
530
|
-
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let
|
|
538
|
+
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=ht(),c=n.join(" ").trim();return c?(r(c)?console.log(`${i.green}Autonomy: ${c}${i.reset}`):console.log(`${i.red}Unknown level: ${c}. Use: ${a.join(", ")}${i.reset}`),!0):(console.log(`${i.bold}${i.cyan}Autonomy:${i.reset} ${o()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:o}=Ft(),r=o();console.log(`
|
|
539
|
+
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let c=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${c} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
531
540
|
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
532
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=Ft(),a=n.join(" ").trim();return a?(o(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=Ft(),a=n.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:
|
|
541
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=Ft(),a=n.join(" ").trim();return a?(o(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=Ft(),a=n.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:c}=Ke(),{confirm:l}=Te();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${i.green}Committed: ${p} \u2014 ${u}${i.reset}`:`${i.red}Commit failed${i.reset}`),!0}if(!a())return console.log(`${i.yellow}No changes to commit${i.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${i.green} \u2713 Committed: ${h}${i.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=Ke();return o()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=Ke(),{processInput:a}=Z(),c=n.join(" ").trim(),l;if(c)l=`Do a thorough code review of \`${c}\`. Check for bugs, security issues, code quality, correctness, and suggest concrete improvements. Format findings by severity (critical, warning, suggestion).`;else{if(!o())return console.log(`${i.red}Not a git repository \u2014 try /review <file>${i.reset}`),!0;let[u,d]=await Promise.all([r(!1),r(!0)]),f=d||u;if(!f||!f.trim())return console.log(`${i.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${i.reset}`),!0;l=`Review the following code diff for bugs, security issues, code quality, and improvements. Format findings by severity (critical, warning, suggestion):
|
|
533
542
|
|
|
534
543
|
\`\`\`diff
|
|
535
544
|
${f.substring(0,2e4)}
|
|
536
|
-
\`\`\``}return await a(
|
|
537
|
-
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of
|
|
545
|
+
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:a}=Ke();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let l=a(c);return console.log(l?`${i.green}Created and switched to: ${l}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:a}=dn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${i.dim}Connecting MCP servers...${i.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${i.red}\u2717${i.reset} ${d.name}: ${d.error}`):console.log(` ${i.green}\u2713${i.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${i.dim}No MCP servers configured in .nex/config.json${i.reset}`)}).catch(u=>{console.log(`${i.red}MCP connection error: ${u.message}${i.reset}`)}),!0;if(c==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let l=o();if(l.length===0)return console.log(`${i.dim}No MCP servers configured${i.reset}`),console.log(`${i.dim}Add servers to .nex/config.json under "mcpServers"${i.reset}`),!0;console.log(`
|
|
546
|
+
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of l){let d=u.connected?`${i.green}\u2713 connected${i.reset}`:`${i.dim}\u25CB disconnected${i.reset}`;console.log(` ${d} ${i.bold}${u.name}${i.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
538
547
|
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
539
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
540
|
-
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let
|
|
541
|
-
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of
|
|
548
|
+
`),!0}case"/hooks":{let{listHooks:o}=Hs(),r=o();if(r.length===0)return console.log(`${i.dim}No hooks configured${i.reset}`),console.log(`${i.dim}Add hooks to .nex/config.json or .nex/hooks/${i.reset}`),!0;console.log(`
|
|
549
|
+
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:a}=Et(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${i.green}Skill enabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return a(u)?console.log(`${i.yellow}Skill disabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}let l=o();if(l.length===0)return console.log(`${i.dim}No skills loaded${i.reset}`),console.log(`${i.dim}Add .md or .js files to .nex/skills/${i.reset}`),!0;console.log(`
|
|
550
|
+
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of l){let d=u.enabled?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,f=u.type==="prompt"?`${i.dim}(prompt)${i.reset}`:`${i.dim}(script)${i.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${i.bold}${u.name}${i.reset} ${f}${h}`)}return console.log(`
|
|
542
551
|
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
543
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}
|
|
552
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=$n();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
544
553
|
`+o()+`
|
|
545
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let
|
|
554
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to undo${i.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to redo${i.reset}`),!0;console.log(`${i.green}Redone: ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:a}=ut(),c=o(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
546
555
|
${i.bold}File Change History${i.reset}
|
|
547
|
-
`);for(let
|
|
556
|
+
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${l.tool}${i.reset} ${l.filePath}`)}return console.log(`
|
|
548
557
|
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
549
558
|
`),!0}case"/exit":case"/quit":console.log(`
|
|
550
|
-
${i.dim}Bye!${i.reset}`),process.exit(0);default:return
|
|
551
|
-
`).filter(Boolean).slice(-
|
|
552
|
-
`)}catch{}}function
|
|
553
|
-
`),!0):!1)(),
|
|
559
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return hp(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var co=1e3;function lo(){return ve.join(process.cwd(),".nex","repl_history")}function Va(){try{let t=lo();if(We.existsSync(t))return We.readFileSync(t,"utf-8").split(`
|
|
560
|
+
`).filter(Boolean).slice(-co)}catch{}return[]}function Dn(t){try{let e=lo(),s=ve.dirname(e);We.existsSync(s)||We.mkdirSync(s,{recursive:!0}),We.appendFileSync(e,t+`
|
|
561
|
+
`)}catch{}}function we(){let{isPlanMode:t,getAutonomyLevel:e}=ht(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=Fe(),r=Ue();return s.push(`${o}:${r.id}`),`${s.length>0?`${i.dim}[${s.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var uo="\x1B[200~",fo="\x1B[201~";function yp(t){return typeof t=="string"&&t.includes(uo)}function wp(t){return typeof t=="string"&&t.includes(fo)}function Gt(t){return typeof t!="string"?t:t.split(uo).join("").split(fo).join("")}async function bp(){if(!mp("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"),Fa("local:llama3"),!0}catch{return!1}}async function xp(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=Z();t(Ba);let o=io().some(M=>M.configured),r=(async()=>{pp();let M=Ue(),N=Fe();return{model:M,providerName:N}})(),a=(async()=>o?!0:await bp()?(console.log(`${i.green}\u2713 Local Ollama detected \u2014 using local models${i.reset}`),console.log(`${i.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${i.reset}
|
|
562
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:M}=qa();return await M()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!o&&(console.error(`
|
|
554
563
|
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
555
|
-
`),process.exit(1)),
|
|
556
|
-
`),await
|
|
557
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",$),process.on("exit",()=>{
|
|
558
|
-
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(
|
|
564
|
+
`),process.exit(1)),up(`${l.providerName}:${l.model.id}`,Fn,{yolo:Wa()}),d.hasNewVersion&&console.log(`${i.yellow}\u{1F4A1} New version available!${i.reset} Run ${i.cyan}npm update -g nex-code${i.reset} to upgrade from ${i.dim}${d.currentVersion}${i.reset} to ${i.green}${d.latestVersion}${i.reset}
|
|
565
|
+
`),await Ua(Fn);let f=Va(),m=lp.createInterface({input:process.stdin,output:process.stdout,prompt:we(),completer:za,history:f,historySize:co});gp(m);let h=!1,p=0,x=!1,w=null;function $(){Da(),ja(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
566
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",$),process.on("exit",()=>{Da()}),m.on("SIGINT",()=>{if(ja(),h){if(p++,p>=2){$();return}Pe&&Pe.abort();let{cancelPendingAskUser:M}=qe();M(),console.log(`
|
|
567
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(we()),m.prompt();return}x?$():(x=!0,process.stdout.write(`
|
|
559
568
|
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
560
|
-
`),m.setPrompt(
|
|
569
|
+
`),m.setPrompt(we()),m.prompt(),w&&clearTimeout(w),w=setTimeout(()=>{x=!1,w=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||$()});let k=!1,T=[],b=null;function S(){let M=T.join(`
|
|
561
570
|
`).trim();if(T=[],k=!1,!M)return!0;b=M;let N=M.split(`
|
|
562
|
-
`),
|
|
563
|
-
${i.dim} ${
|
|
564
|
-
`)),S()}if(
|
|
565
|
-
`)),!0}if(W){let
|
|
566
|
-
`)),S()}if(k){let
|
|
567
|
-
`)),!0}return M.call(process.stdin,N,...
|
|
568
|
-
\x1B[2K ${i.cyan}${
|
|
569
|
-
\x1B[2K ${i.dim}\u2026 +${N.length-
|
|
570
|
-
`)
|
|
571
|
-
`)
|
|
572
|
-
`).
|
|
573
|
-
`)
|
|
574
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
575
|
-
|
|
571
|
+
`),I=N.length,q=N[0].length>80?N[0].substring(0,77)+"...":N[0],D=I>1?`[Pasted content \u2014 ${I} lines]`:"[Pasted content]";return console.log(`
|
|
572
|
+
${i.dim} ${D}${i.reset}`),console.log(`${i.dim} \u23BF ${q}${i.reset}`),I>1&&console.log(`${i.dim} \u23BF \u2026 +${I-1} more lines${i.reset}`),console.log(`${i.dim} Press Enter to send${i.reset}`),!0}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let M=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(N,...I){if(N!=="data")return M.call(process.stdin,N,...I);let q=I[0];if(Buffer.isBuffer(q)&&(q=q.toString("utf8")),typeof q!="string")return M.call(process.stdin,N,...I);let D=q.includes(uo),W=q.includes(fo);if(D&&W){let z=Gt(q);return z&&T.push(...z.split(`
|
|
573
|
+
`)),S()}if(D){k=!0,T=[];let z=Gt(q);return z&&T.push(...z.split(`
|
|
574
|
+
`)),!0}if(W){let z=Gt(q);return z&&T.push(...z.split(`
|
|
575
|
+
`)),S()}if(k){let z=Gt(q);return z&&T.push(...z.split(`
|
|
576
|
+
`)),!0}return M.call(process.stdin,N,...I)}}let v=0;function C(){if(v>0){let M="";for(let N=0;N<v;N++)M+="\x1B[1B\x1B[2K";M+=`\x1B[${v}A`,process.stdout.write(M),v=0}}function E(M){let N=[...Un,...ao()].filter(ne=>ne.cmd.startsWith(M));if(!N.length||N.length===1&&N[0].cmd===M)return;let I=10,q=N.slice(0,I),D=Math.max(...q.map(ne=>ne.cmd.length)),W="";for(let{cmd:ne,desc:se}of q){let be=ne.substring(0,M.length),zt=ne.substring(M.length),bt=" ".repeat(Math.max(0,D-ne.length+2));W+=`
|
|
577
|
+
\x1B[2K ${i.cyan}${be}${i.reset}${i.dim}${zt}${bt}${se}${i.reset}`}v=q.length,N.length>I&&(W+=`
|
|
578
|
+
\x1B[2K ${i.dim}\u2026 +${N.length-I} more${i.reset}`,v++);let z=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;W+=`\x1B[${v}A\x1B[${z+m.cursor+1}G`,process.stdout.write(W)}process.stdin.isTTY&&process.stdin.on("keypress",(M,N)=>{C(),!(N&&(N.name==="tab"||N.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&E(m.line)})});let P=null,L=`${i.dim}...${i.reset} `;m.setPrompt(we()),m.prompt(),m.on("line",async M=>{if(C(),h){let D=(b!==null?b:M).trim();if(b=null,D){let{injectMidRunNote:W}=Z();W(D),process.stdout.write(`${i.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${i.reset}
|
|
579
|
+
`)}return}if(b!==null&&(M=b,b=null),P!==null){if(P._mode==="triple"){if(M.trim()==='"""'){let D=P.join(`
|
|
580
|
+
`).trim();if(P=null,D){Dn(D.replace(/\n/g,"\\n")),h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await s(D)}catch(z){if(!Pe?.signal?.aborted){let ne=z.message?.split(`
|
|
581
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${ne}${i.reset}`)}}h=!1;let W=I();W>0&&process.stdout.write(`${i.gray}[${W} messages] ${i.reset}`)}m.setPrompt(we()),m.prompt();return}P.push(M),m.setPrompt(L),m.prompt();return}if(M.endsWith("\\"))P.push(M.slice(0,-1));else{P.push(M);let D=P.join(`
|
|
582
|
+
`).trim();if(P=null,D){Dn(D.replace(/\n/g,"\\n")),h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await s(D)}catch(ne){if(!Pe?.signal?.aborted){let se=ne.message?.split(`
|
|
583
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${se}${i.reset}`)}}let{getConversationLength:W}=Z();h=!1;let z=W();z>0&&process.stdout.write(`${i.gray}[${z} messages] ${i.reset}`)}m.setPrompt(we()),m.prompt();return}m.setPrompt(L),m.prompt();return}if(M.trim()==='"""'||M.trim().startsWith('"""')){let D=M.trim().substring(3);P=D?[D]:[],P._mode="triple",m.setPrompt(L),m.prompt();return}if(M.endsWith("\\")){P=[M.slice(0,-1)],P._mode="backslash",m.setPrompt(L),m.prompt();return}let N=M.trim();if(!N){m.setPrompt(we()),m.prompt();return}if(Dn(N),N==="/"){Ha(),m.setPrompt(we()),m.prompt();return}if(N.startsWith("/")){await Ya(N,m),m.setPrompt(we()),m.prompt();return}h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await s(N)}catch(D){if(!Pe?.signal?.aborted){let W=D.message?.split(`
|
|
584
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${W}${i.reset}`)}}h=!1;let{getConversationLength:I}=Z(),q=I();q>0&&process.stdout.write(`${i.gray}[${q} messages] ${i.reset}`),m.setPrompt(we()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
585
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}Xa.exports={startREPL:xp,getPrompt:we,loadHistory:Va,appendHistory:Dn,getHistoryPath:lo,HISTORY_MAX:co,showCommandList:Ha,completer:za,completeFilePath:Ga,handleSlashCommand:Ya,showProviders:ro,showHelp:Ka,renderBar:Ja,hasPasteStart:yp,hasPasteEnd:wp,stripPasteSequences:Gt,getAbortSignal:Ba}});var tc=require("path");require("dotenv").config({path:tc.join(__dirname,"..",".env")});require("dotenv").config();var Y=process.argv.slice(2);(Y.includes("--help")||Y.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
576
586
|
|
|
577
587
|
Options:
|
|
578
588
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -585,4 +595,4 @@ Options:
|
|
|
585
595
|
--json Output result as JSON (for CI parsing)
|
|
586
596
|
-h, --help Show this help
|
|
587
597
|
-v, --version Show version
|
|
588
|
-
`),process.exit(0));if(
|
|
598
|
+
`),process.exit(0));if(Y.includes("-v")||Y.includes("--version")){let t=Kt();console.log(t.version),process.exit(0)}var kp=Y.includes("--yolo")||Y.includes("-yolo");if(kp){let{setAutoConfirm:t}=Te();t(!0)}var mo=Y.indexOf("--model");if(mo!==-1&&Y[mo+1]){let{setActiveModel:t}=re();t(Y[mo+1])}var po=Y.indexOf("--max-turns");if(po!==-1&&Y[po+1]){let t=parseInt(Y[po+1],10);if(t>0){let{setMaxIterations:e}=Z();e(t)}}else try{let t=require("fs"),e=tc.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}=Z();o(n)}}}catch{}function ho(){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 Za(t){if(Y.includes("--auto")){let{setAutoConfirm:o}=Te();o(!0)}if(!Y.includes("--model")){let{setActiveModel:o}=re(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=Z();s(t).then(()=>{if(Y.includes("--json")){let r=n().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{Y.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var ec=Y.indexOf("--prompt-file");if(ec!==-1){let t=Y[ec+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)),Y.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}ho(),Za(s)}else{let t=Y.indexOf("--task");if(t!==-1){let e=Y[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),ho(),Za(e)}else{ho();let{startREPL:e}=Qa();e()}}
|