nex-code 0.3.14 → 0.3.19
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 +47 -4
- package/dist/nex-code.js +372 -298
- package/package.json +2 -2
package/dist/nex-code.js
CHANGED
|
@@ -1,122 +1,125 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
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
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,
|
|
5
|
-
`}process.stderr.write(
|
|
6
|
-
`;for(let
|
|
7
|
-
`}
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
9
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,
|
|
11
|
-
`;for(let
|
|
12
|
-
`}process.stderr.write(
|
|
13
|
-
`),s
|
|
14
|
-
`);return o>0&&(
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80);return` ${
|
|
17
|
-
`).filter(Boolean),
|
|
18
|
-
`).length;r=`Wrote ${
|
|
19
|
-
`).filter(Boolean);r=
|
|
20
|
-
`).filter(Boolean).length;r=`${
|
|
21
|
-
`).filter(Boolean).length;r=`${
|
|
22
|
-
`).filter(Boolean).length;r=`${
|
|
23
|
-
`).filter(
|
|
24
|
-
`).filter(
|
|
25
|
-
|
|
26
|
-
`).filter(Boolean).length;r=`${
|
|
27
|
-
`),u=
|
|
28
|
-
${
|
|
29
|
-
${o}Agentic Coding CLI v${
|
|
2
|
+
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var zt=O((up,Xa)=>{Xa.exports={name:"nex-code",version:"0.3.19",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 xo=O((dp,bo)=>{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"},$o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],yo=["\u273D","\u2726","\u2727","\u2726"],Bn=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=$o[this.frame%$o.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}},wo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Hn=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=wo[this.frame%wo.length],s=this._formatElapsed(),n=s?` ${R.dim}${s}${R.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let a,l;switch(this.statuses[r]){case"done":a=`${R.green}\u2713${R.reset}`,l=R.dim;break;case"error":a=`${R.red}\u2717${R.reset}`,l=R.dim;break;default:a=`${R.cyan}${e}${R.reset}`,l=""}let c=r===this.labels.length-1?n:"";o+=`\x1B[2K ${a} ${l}${this.labels[r]}${R.reset}${c}
|
|
3
|
+
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${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)}},Kt={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Jt={done:R.green,in_progress:R.cyan,pending:R.dim,failed:R.red},Pe=null,Gn=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=yo[this.frame%yo.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 l=0;l<this.tasks.length;l++){let c=this.tasks[l],u=l===0?"\u23BF":" ",d=Kt[c.status]||Kt.pending,f=Jt[c.status]||Jt.pending,m=c.description.length>55?c.description.substring(0,52)+"...":c.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${m}
|
|
7
|
+
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Pe=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,Pe===this&&(Pe=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(l=>l.status==="done").length,n=this.tasks.filter(l=>l.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 l=0;l<this.tasks.length;l++){let c=this.tasks[l],u=l===0?"\u23BF":" ",d=Kt[c.status]||Kt.pending,f=Jt[c.status]||Jt.pending,m=c.description.length>55?c.description.substring(0,52)+"...":c.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${R.dim}${m}${R.reset}
|
|
12
|
+
`}process.stderr.write(a)}};function Qa(t){Pe=t}function Za(){return Pe}function el(){Pe&&(Pe.stop(),Pe=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}bo.exports={C:R,Spinner:Bn,MultiProgress:Hn,TaskProgress:Gn,setActiveTaskProgress:Qa,getActiveTaskProgress:Za,cleanupTerminal:el}});var _o=O((fp,ko)=>{var ee={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 tl(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=s?`${ee.dim}(${s})${ee.reset}`:"";return`${ee.cyan}\u23FA${ee.reset} ${ee.bold}${t}${ee.reset}${n}`}function nl(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${ee.dim} \u23BF ${ee.reset}`,a=" ",l=n.map((c,u)=>`${u===0?r:a}${ee.green}${c}${ee.reset}`).join(`
|
|
14
|
+
`);return o>0&&(l+=`
|
|
15
|
+
${ee.gray} \u2026+${o} more lines${ee.reset}`),l}function sl(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;default:return`Running: ${t}`}}function ol(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80);return` ${ee.red}\u23BF ${a}${ee.reset}`}let r;switch(t){case"read_file":{let a=o.split(`
|
|
17
|
+
`).filter(Boolean),l=a.length,c=a[a.length-1],u=c?parseInt(c.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>l?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${l} line${l!==1?"s":""}`;break}case"write_file":{let a=(e.content||"").split(`
|
|
18
|
+
`).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)r=`Exit ${a[1]}`;else{let l=o.split(`
|
|
19
|
+
`).filter(Boolean);r=l.length>1?`${l.length} lines output`:(l[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
|
+
`).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
|
+
`).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+)/),l=o.split(`
|
|
23
|
+
`).filter(c=>/^\s*[MADRCU?!]/.test(c)).length;r=a?`${a[1]} \xB7 ${l} change${l!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,l=(o.match(/^-[^-]/gm)||[]).length;r=a||l?`+${a} \u2212${l} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
24
|
+
`).filter(l=>/^commit\s+[0-9a-f]{7}/.test(l)).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
|
+
|
|
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,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} failed`:`${a} agent${a!==1?"s":""} done`;break}default:r="Done"}return` ${ee.dim}\u23BF ${r}${ee.reset}`}ko.exports={C:ee,formatToolCall:tl,formatResult:nl,getToolSpinnerText:sl,formatToolSummary:ol}});var Q=O((mp,vo)=>{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 rl(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+ot.reset}function il(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function al(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"],l=[[220,240,255],[80,200,255],[40,100,220]],c=a.map((d,f)=>{let m=f/(a.length-1||1);return rl(d,il(l,m))}).join(`
|
|
27
|
+
`),u=s.yolo?` ${n}${ot.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
28
|
+
${c}
|
|
29
|
+
${o}Agentic Coding CLI v${zt().version}${r}
|
|
30
30
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
31
|
-
`)}var{Spinner:
|
|
32
|
-
`)};return o.length>0&&(r.images=o),r}return
|
|
33
|
-
`);h=x.pop()||"";for(let
|
|
31
|
+
`)}var{Spinner:ll,MultiProgress:cl,TaskProgress:ul,setActiveTaskProgress:dl,getActiveTaskProgress:fl,cleanupTerminal:ml}=xo(),{formatToolCall:pl,formatResult:hl,getToolSpinnerText:gl,formatToolSummary:$l}=_o();vo.exports={C:ot,banner:al,Spinner:ll,MultiProgress:cl,TaskProgress:ul,setActiveTaskProgress:dl,getActiveTaskProgress:fl,cleanupTerminal:ml,formatToolCall:pl,formatResult:hl,getToolSpinnerText:gl,formatToolSummary:$l}});var Se=O((pp,Mo)=>{var yl=require("readline"),{C:Yt}=Q(),So=[/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/],zn=[/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 To(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 l=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return l?l.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):zn.some(c=>c.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:zn.some(l=>l.test(a))};return n.every(o)}var Jn=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Co=[/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/],Eo=[...Jn,...Co],Yn=!1,Kn=null;function wl(t){Yn=t}function bl(){return Yn}function xl(t){Kn=t}function kl(t){for(let e of So)if(e.test(t))return e;return null}function _l(t){if(/ssh\s/.test(t)&&To(t))return!1;for(let e of Eo)if(e.test(t))return!0;return!1}function vl(t){for(let e of Jn)if(e.test(t))return!0;return!1}function Sl(t,e={}){if(Yn)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?(Ao(e.toolName),n(!0)):n(a!=="n")};if(Kn)Kn.question(`${Yt.yellow}${t} ${s}${Yt.reset}`,o);else{let r=yl.createInterface({input:process.stdin,output:process.stdout});r.question(`${Yt.yellow}${t} ${s}${Yt.reset}`,a=>{r.close(),o(a)})}})}var Ao=()=>{};function Tl(t){Ao=t}Mo.exports={FORBIDDEN_PATTERNS:So,SSH_SAFE_PATTERNS:zn,isSSHReadOnly:To,DANGEROUS_BASH:Eo,CRITICAL_BASH:Jn,NOTABLE_BASH:Co,isForbidden:kl,isDangerous:_l,isCritical:vl,confirm:Sl,setAutoConfirm:wl,getAutoConfirm:bl,setReadlineInterface:xl,setAllowAlwaysHandler:Tl}});var rt=O((hp,Ro)=>{var Vn=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`)}};Ro.exports={BaseProvider:Vn}});var Po=O((gp,Oo)=>{var Vt=require("axios"),Cl=require("http"),El=require("https"),{BaseProvider:Al}=rt(),Xt=new Cl.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Qt=new El.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),No={"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}},Xn=class extends Al{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||No,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){Vt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xt,httpsAgent:Qt}).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 Vt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xt,httpsAgent:Qt})).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(`
|
|
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,l=await Vt.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:Xt,httpsAgent:Qt});return this.normalizeResponse(l.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,l=n.onToken||(()=>{}),c;try{c=await Vt.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:Xt,httpsAgent:Qt})}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",()=>{c.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",g=>{h+=g.toString();let x=h.split(`
|
|
33
|
+
`);h=x.pop()||"";for(let w of x){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(l($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),c.data.on("error",g=>{n.signal?.aborted||d(new Error(`Stream error: ${g.message}`))}),c.data.on("end",()=>{if(h.trim())try{let g=JSON.parse(h);g.message?.content&&(l(g.message.content),f+=g.message.content),g.message?.tool_calls&&(m=m.concat(g.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||{}}}))}};Oo.exports={OllamaProvider:Xn,OLLAMA_MODELS:No}});var Fo=O(($p,Do)=>{var{callChat:Ml}=oe(),{estimateTokens:Qn}=be(),qo=process.env.NEX_COMPACTION!=="false",Io=6,Lo=500,Rl=`Summarize this conversation history concisely. Focus on:
|
|
34
34
|
- What files were read, created, or modified
|
|
35
35
|
- Key decisions made and their rationale
|
|
36
36
|
- Current state of the task (what's done, what's pending)
|
|
37
37
|
- Any errors encountered and how they were resolved
|
|
38
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
39
|
-
${
|
|
40
|
-
tools: ${o}`}return`[${
|
|
38
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Nl(t){if(!qo||t.length<Io)return null;let e=[{role:"system",content:Rl},{role:"user",content:jo(t)}];try{let n=((await Ml(e,[],{temperature:0,maxTokens:Lo})).content||"").trim();if(!n)return null;let o=t.reduce((a,l)=>a+Qn(l.content||"")+(l.tool_calls?Qn(JSON.stringify(l.tool_calls)):0),0),r=Qn(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
39
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function jo(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
|
+
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
41
41
|
|
|
42
|
-
`)}
|
|
43
|
-
`);if(o.length<=10){let g=Math.floor(
|
|
42
|
+
`)}Do.exports={compactMessages:Nl,formatMessagesForSummary:jo,COMPACTION_ENABLED:qo,COMPACTION_MIN_MESSAGES:Io,COMPACTION_SUMMARY_BUDGET:Lo}});var be=O((yp,Yo)=>{function Bo(){return oe().getActiveModel()}var Ol={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},vt=new Map,Uo=1e3,Zt=new WeakMap,it=new Map,Wo=500,St=null;function Pl(){if(St!==null)return St;try{let e=Bo()?.provider||"ollama";return St=Ol[e]||4,St}catch{return 4}}function ql(){St=null}function Be(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=vt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/Pl());if(vt.size>=Uo){let o=Uo>>1,r=vt.keys();for(let a=0;a<o;a++)vt.delete(r.next().value)}return vt.set(e,n),n}function Il(t){if(Zt.has(t))return Zt.get(t);let e=Ho(t);if(it.has(e)){let n=it.get(e);return Zt.set(t,n),n}let s=JSON.stringify(t);if(it.size>=Wo){let n=Wo>>1,o=it.keys();for(let r=0;r<n;r++)it.delete(o.next().value)}return it.set(e,s),Zt.set(t,s),s}function Ho(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+=Be(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=Be(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=Be(o):o&&(s+=Be(JSON.stringify(o)))}return s}function ge(t){let e=0;for(let s of t)e+=at(s);return e}function Ll(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 en(t){return!t||t.length===0?0:Be(JSON.stringify(t))}function tn(){return Bo()?.contextWindow||32768}function jl(t,e){let s=ge(t),n=en(e),o=s+n,r=tn(),a=r>0?o/r*100:0,l=0,c=0,u=0;for(let d of t){let f=at(d);d.role==="system"?l+=f:d.role==="tool"?u+=f:c+=f}return{used:o,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:l,conversation:c,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Go=.75,zo=.1,Ko=10,Dl=200,Fl=500;function Jo(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(`
|
|
43
|
+
`);if(o.length<=10){let g=Math.floor(n*.6),x=Math.floor(n*.4),w=t.substring(0,g),$=t.substring(t.length-x);return w+`
|
|
44
44
|
...(${t.length} chars total)...
|
|
45
|
-
`+$}let r=Math.floor(o.length*.4),
|
|
45
|
+
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),l=[],c=0,u=Math.floor(n*.4);for(let g=0;g<r&&c<u;g++)l.push(o[g]),c+=o[g].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let g=o.length-1;g>=o.length-a&&f<m;g--)d.unshift(o[g]),f+=o[g].length+1;let h=o.length-l.length-d.length;return l.join(`
|
|
46
46
|
`)+`
|
|
47
47
|
...(${h} lines omitted, ${o.length} total)...
|
|
48
48
|
`+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(
|
|
52
|
-
`:"")+h,
|
|
53
|
-
`:"")+u;if(g.length>
|
|
54
|
-
|
|
55
|
-
... (${o.length-
|
|
56
|
-
|
|
57
|
-
`;return
|
|
58
|
-
`);x=$.pop()||"";for(let k of $){let
|
|
59
|
-
|
|
60
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){
|
|
61
|
-
`);
|
|
62
|
-
`);x=$.pop()||"";for(let k of $){let
|
|
63
|
-
`)};return o.length>0&&(r.images=o),r}return
|
|
64
|
-
`);f=h.pop()||"";for(let g of h){if(!g.trim())continue;let x;try{x=JSON.parse(g)}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){
|
|
65
|
-
`)}}function
|
|
66
|
-
`)}function
|
|
67
|
-
`),
|
|
68
|
-
`),
|
|
69
|
-
`),o=[],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
|
|
72
|
-
${y.bold}${y.cyan} New file: ${t}${y.reset}`);let
|
|
73
|
-
`),s
|
|
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
|
|
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":""}`),
|
|
78
|
-
`),r=
|
|
79
|
-
${y.cyan}\u23FA${y.reset} ${y.bold}Create(${
|
|
80
|
-
`).filter(Boolean).map(e=>{let
|
|
81
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let
|
|
82
|
-
${
|
|
83
|
-
${
|
|
84
|
-
${
|
|
49
|
+
`)}function Tt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Fl,n=e==="aggressive"?50:e==="medium"?100:Dl;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Jo(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
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 Ul(t,e,s={}){let n=s.threshold??Go,o=s.safetyMargin??zo,r=s.keepRecent??Ko,a=tn(),l=en(e),c=Math.floor(a*(n-o)),u=c-l,d=ge(t),f=d+l;if(f<=c)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let x=Math.max(g,t.length-r),w=t.slice(g,x),$=t.slice(x),k=w.filter(C=>!C._compacted);if(k.length>=6)try{let{compactMessages:C}=Fo(),E=await C(k);if(E){let I=[...w.filter(q=>q._compacted),E.message],M=We(h,I,$),N=ge(M);if(N+l<=c)return{messages:M,compressed:!0,compacted:!0,tokensRemoved:m-N};w=I}}catch{}let T=(f-c)/c,b=w.map(C=>Tt(C,"light")),S=We(h,b,$),_=ge(S);if(_+l<=c)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};if(b=w.map(C=>Tt(C,"medium")),S=We(h,b,$),_=ge(S),_+l<=c)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};if(b=w.map(C=>Tt(C,"aggressive")),S=We(h,b,$),_=ge(S),_+l<=c)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};for(;b.length>0&&_+l>u;){let C=b.shift();_-=at(C)}return S=We(h,b,$),_=ge(S),{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_}}function We(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Wl(t,e){if(!t)return"";if(Be(t)<=e)return t;let n=e*4,o=t.split(`
|
|
51
|
+
`),r=Math.floor(n*.6),a=Math.floor(n*.4),l="",c=0;for(let h of o){if(l.length+h.length+1>r)break;l+=(l?`
|
|
52
|
+
`:"")+h,c++}let u="",d=0;for(let h=o.length-1;h>=c;h--){let g=o[h]+(u?`
|
|
53
|
+
`:"")+u;if(g.length>a)break;u=g,d++}let m=`
|
|
54
|
+
|
|
55
|
+
... (${o.length-c-d} lines omitted, ${o.length} total) ...
|
|
56
|
+
|
|
57
|
+
`;return l+m+u}var Bl=6;function Hl(t,e){let s=tn(),n=en(e),o=Math.floor(s*.5)-n,r=ge(t),a=null,l=0;t.length>0&&t[0].role==="system"&&(a=t[0],l=1);let c=Math.max(l,t.length-Bl),u=t.slice(l,c),d=t.slice(c),f=u.map(g=>Tt(g,"aggressive")),m=We(a,f,d),h=ge(m);for(;f.length>0&&h>o;){let g=f.shift();h-=at(g)}return m=We(a,f,d),h=ge(m),{messages:m,tokensRemoved:r-h}}Yo.exports={estimateTokens:Be,estimateMessageTokens:at,estimateMessagesTokens:ge,estimateDeltaTokens:Ll,estimateToolsTokens:en,serializeMessage:Il,getMessageCacheKey:Ho,getContextWindow:tn,getUsage:jl,compressMessage:Tt,compressToolResult:Jo,fitToContext:Ul,forceCompress:Hl,truncateFileContent:Wl,invalidateTokenRatioCache:ql,COMPRESSION_THRESHOLD:Go,SAFETY_MARGIN:zo,KEEP_RECENT:Ko}});var Zo=O((bp,Qo)=>{var Vo=require("axios"),{BaseProvider:Gl}=rt(),{serializeMessage:wp}=be(),Xo={"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}},Zn=class extends Gl{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Xo,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:l}=this.formatMessages(e),c={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(c.tools=s);let u=await Vo.post(`${this.baseUrl}/chat/completions`,c,{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,l=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Vo.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="",g={},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(`
|
|
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(g)});return}let S;try{S=JSON.parse(b)}catch{continue}let _=S.choices?.[0]?.delta;if(_&&(_.content&&(l(_.content),h+=_.content),_.tool_calls))for(let C of _.tool_calls){let E=C.index??0;g[E]||(g[E]={id:C.id||"",name:"",arguments:""}),C.id&&(g[E].id=C.id),C.function?.name&&(g[E].name+=C.function.name),C.function?.arguments&&(g[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(g)})})})}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}}))}};Qo.exports={OpenAIProvider:Zn,OPENAI_MODELS:Xo}});var sr=O((kp,nr)=>{var er=require("axios"),{BaseProvider:zl}=rt(),{serializeMessage:xp}=be(),tr={"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}},Kl="2023-06-01",es=class extends zl{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||tr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Kl}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?`
|
|
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),l=n.maxTokens||a?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),d={model:r,messages:c,max_tokens:l,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await er.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),l=n.maxTokens||a?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:l,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 er.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let x=g.response?.data?.error?.message||g.message;throw new Error(`API Error: ${x}`)}return new Promise((g,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(`
|
|
61
|
+
`);T=S.pop()||"";for(let _ of S){let C=_.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 I=P.content_block;I?.type==="tool_use"&&(k=$.length,$.push({id:I.id,name:I.name,inputJson:""}));break}case"content_block_delta":{let I=P.delta;I?.type==="text_delta"&&I.text&&(c(I.text),w+=I.text),I?.type==="input_json_delta"&&I.partial_json!==void 0&&k>=0&&($[k].inputJson+=I.partial_json);break}case"content_block_stop":k=-1;break;case"message_stop":g({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",()=>{g({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}}})}};nr.exports={AnthropicProvider:es,ANTHROPIC_MODELS:tr}});var ar=O((vp,ir)=>{var or=require("axios"),{BaseProvider:Jl}=rt(),{serializeMessage:_p}=be(),rr={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},ts=class extends Jl{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||rr,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:l}=this.formatMessages(e),c={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(c.tools=s);let u=await or.post(`${this.baseUrl}/chat/completions`,c,{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,l=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await or.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="",g={},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(`
|
|
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(g)});return}let S;try{S=JSON.parse(b)}catch{continue}let _=S.choices?.[0]?.delta;if(_&&(_.content&&(l(_.content),h+=_.content),_.tool_calls))for(let C of _.tool_calls){let E=C.index??0;g[E]||(g[E]={id:C.id||"",name:"",arguments:""}),C.id&&(g[E].id=C.id),C.function?.name&&(g[E].name+=C.function.name),C.function?.arguments&&(g[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(g)})})})}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}}))}};ir.exports={GeminiProvider:ts,GEMINI_MODELS:rr}});var ur=O((Sp,cr)=>{var nn=require("axios"),{BaseProvider:Yl}=rt(),lr="http://localhost:11434",ns=class extends Yl{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||lr,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 nn.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 l=await nn.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=l.data?.model_info||l.data?.details||{};a=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(l.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(`
|
|
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 nn.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 nn.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(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let c=l.response?.data?.error||l.message;throw new Error(`API Error: ${c}`)}return new Promise((l,c)=>{let u="",d=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),c(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
64
|
+
`);f=h.pop()||"";for(let g of h){if(!g.trim())continue;let x;try{x=JSON.parse(g)}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){l({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||c(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{}l({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||{}}}))}};cr.exports={LocalProvider:ns,DEFAULT_LOCAL_URL:lr}});var lt=O((Tp,$r)=>{var He=require("fs"),ss=require("path"),dr={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:{}},sn=[],qe={};function Vl(t,e,s,n){if(sn.push({provider:t,model:e,input:s,output:n}),qe[t]!==void 0){let o=hr(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
65
|
+
`)}}function os(t,e){let s=dr[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function fr(t){let e=os(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function mr(){let t={};for(let r of sn){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:fr(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 Xl(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=mr();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(`
|
|
66
|
+
`)}function Ql(t,e,s,n){let o=os(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Zl(){sn=[]}function ec(t,e){qe[t]=e}function tc(t){delete qe[t]}function nc(){return{...qe}}function pr(t){let e=0;for(let s of sn)s.provider===t&&(e+=fr(s));return e}function hr(t){let e=pr(t),s=qe[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 gr(){let t=ss.join(process.cwd(),".nex","config.json");if(He.existsSync(t))try{let e=JSON.parse(He.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(qe={...e.costLimits})}catch{}}function sc(){let t=ss.join(process.cwd(),".nex"),e=ss.join(t,"config.json"),s={};if(He.existsSync(e))try{s=JSON.parse(He.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=qe,He.existsSync(t)||He.mkdirSync(t,{recursive:!0}),He.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function oc(){qe={}}gr();$r.exports={PRICING:dr,trackUsage:Vl,getSessionCosts:mr,formatCosts:Xl,formatCostHint:Ql,resetCosts:Zl,getPricing:os,setCostLimit:ec,removeCostLimit:tc,getCostLimits:nc,getProviderSpend:pr,checkBudget:hr,loadCostLimits:gr,saveCostLimits:sc,resetCostLimits:oc}});var on=O((Cp,yr)=>{var Ct=oe(),rc={"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 ic(){return Ct.getActiveModel()}function ac(t){return Ct.setActiveModel(t)}function lc(){return Ct.getModelNames()}function cc(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 uc(t,e){let{C:s}=Q(),{Spinner:n}=Q(),o=new n("Thinking...");o.start();let r=!0,a="";try{let l=await Ct.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),a+=c}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
67
|
+
`),l}catch(l){throw o.stop(),l}}async function dc(t,e){return Ct.callChat(t,e)}yr.exports={MODELS:rc,getActiveModel:ic,setActiveModel:ac,getModelNames:lc,callOllamaStream:uc,callOllama:dc,parseToolArgs:cc}});var xr=O((Ep,br)=>{var rn=require("path"),{C:y}=Q(),{confirm:fc,getAutoConfirm:mc}=Se(),wr=2e3;function Et(t,e){let s=t.split(`
|
|
68
|
+
`),n=e.split(`
|
|
69
|
+
`),o=[],r=s.length,a=n.length;if(r>wr||a>wr){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 l=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]?l[f][m]=l[f-1][m-1]+1:l[f][m]=Math.max(l[f-1][m],l[f][m-1]);let c=r,u=a,d=[];for(;c>0||u>0;)c>0&&u>0&&s[c-1]===n[u-1]?(d.unshift({type:"same",line:s[c-1]}),c--,u--):u>0&&(c===0||l[c][u-1]>=l[c-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[c-1]}),c--);return d}function pc(t,e,s,n=3){console.log(`
|
|
70
|
+
${y.bold}${y.cyan} Diff: ${t}${y.reset}`);let o=Et(e,s),r=[];if(o.forEach((c,u)=>{c.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),l=Math.min(o.length,r[r.length-1]+n+1);a>0&&console.log(`${y.gray} ...${y.reset}`);for(let c=a;c<l;c++){let u=o[c];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}`)}}l<o.length&&console.log(`${y.gray} ...${y.reset}`),console.log()}function hc(t,e,s){console.log(`
|
|
71
|
+
${y.bold}${y.cyan} File exists \u2014 showing changes: ${t}${y.reset}`);let n=Et(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 gc(t,e){console.log(`
|
|
72
|
+
${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 $c(t){return mc()?!0:fc(` ${t}?`)}function yc(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
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=Et(e,s),l=[],c=0;for(;c<a.length;)if(a[c].type==="same")l.push({left:a[c].line,right:a[c].line,type:"same"}),c++;else if(a[c].type==="remove"){let h=[];for(;c<a.length&&a[c].type==="remove";)h.push(a[c].line),c++;let g=[];for(;c<a.length&&a[c].type==="add";)g.push(a[c].line),c++;let x=Math.max(h.length,g.length);for(let w=0;w<x;w++)l.push({left:w<h.length?h[w]:"",right:w<g.length?g[w]:"",type:"changed"})}else a[c].type==="add"&&(l.push({left:"",right:a[c].line,type:"changed"}),c++);let u=l.map((h,g)=>h.type!=="same"?g:-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(l.length,u[u.length-1]+3),m=(h,g)=>{let x=h.replace(/\x1b\[[0-9;]*m/g,"");return x.length>=g?h.substring(0,g):h+" ".repeat(g-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 g=l[h];if(g.type==="same")console.log(` ${y.gray}${m(g.left,r)}${y.reset}\u2502${y.gray}${m(g.right,r)}${y.reset}`);else{let x=g.left?`${y.red}${m(g.left,r)}${y.reset}`:`${m("",r)}`,w=g.right?`${y.green}${m(g.right,r)}${y.reset}`:`${m("",r)}`;console.log(` ${x}\u2502${w}`)}}f<l.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}
|
|
75
|
+
`)}function wc(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,a=n.annotations||[],l=rn.isAbsolute(t)?rn.relative(process.cwd(),t):t,c=Et(e,s),u=1,d=1;for(let b of c)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 c)b.type==="add"?f++:b.type==="remove"&&m++;if(console.log(`
|
|
76
|
+
${y.cyan}\u23FA${y.reset} ${y.bold}${o}(${l})${y.reset}`),f===0&&m===0){console.log(` ${y.dim}\u23BF (no changes)${y.reset}
|
|
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,_=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}`),_>0&&C.push(`${y.cyan}${_} info${_!==1?"s":""}${y.dim}`),h.push(`found ${C.join(", ")}`)}console.log(` ${y.dim}\u23BF ${h.join(", ")}${y.reset}`);let x=[];c.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),_=Math.min(c.length-1,b+r);$===null?($=S,k=_):(S<=k+1||(w.push([$,k]),$=S),k=_)}$!==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,_]=w[b];for(let C=S;C<=_;C++){let E=c[C],P=E.newLine!=null?E.newLine:E.oldLine,I=String(P).padStart(4),M=E.type!=="remove"?a.filter(N=>N.line===E.newLine):[];E.type==="remove"?console.log(`${T}${y.red}${I} -${E.line}${y.reset}`):E.type==="add"?console.log(`${T}${y.green}${I} +${E.line}${y.reset}`):console.log(`${T}${y.dim}${I}${y.reset} ${E.line}`);for(let N of M){let q=y.cyan,L="\u2139";N.severity==="error"?(q=y.red,L="\u2716"):N.severity==="warn"&&(q=y.yellow,L="\u26A0"),console.log(`${T} ${q}${L} ${N.message}${y.reset}`)}}}console.log()}function bc(t,e,s={}){let n=rn.isAbsolute(t)?rn.relative(process.cwd(),t):t,o=e.split(`
|
|
78
|
+
`),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(g=>g.severity==="error").length,f=r.filter(g=>g.severity==="warn").length,m=r.filter(g=>g.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 c=" ",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(g=>g.line===m);console.log(`${c}${y.green}${f} +${o[d]}${y.reset}`);for(let g of h){let x=y.cyan,w="\u2139";g.severity==="error"?(x=y.red,w="\u2716"):g.severity==="warn"&&(x=y.yellow,w="\u26A0"),console.log(`${c} ${x}${w} ${g.message}${y.reset}`)}}o.length>20&&console.log(`${c}${y.dim} ...+${o.length-20} more lines${y.reset}`),console.log()}br.exports={diffLines:Et,showEditDiff:pc,showWriteDiff:hc,showNewFilePreview:gc,confirmFileChange:$c,showSideBySideDiff:yc,showClaudeDiff:wc,showClaudeNewFile:bc}});var Ge=O((Ap,vr)=>{var kr=require("util").promisify(require("child_process").exec),xc=require("util").promisify(require("child_process").execFile),{C:Y}=Q();async function rs(t){try{let{stdout:e}=await kr(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function an(...t){try{let{stdout:e}=await xc("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function kc(){return await rs("git rev-parse --is-inside-work-tree")==="true"}async function _c(){return await rs("git branch --show-current")}async function is(){try{let{stdout:t}=await kr("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
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 rs(`git diff ${t?"--cached":""}`)||""}async function as(){return(await is()).map(e=>e.file)}async function _r(){let t=await as();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(`
|
|
81
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",l=t.join(" ").toLowerCase();l.includes("test")?a="test":l.includes("readme")||l.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let c=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function vc(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await an("checkout","-b",s)!==null?s:null}async function Sc(t){return await an("add","-A"),await an("commit","-m",t)?await an("rev-parse","--short","HEAD"):null}async function Tc(){let t=await _r();if(!t)return`${Y.dim}No changes${Y.reset}`;let e=[];e.push(`
|
|
82
|
+
${Y.bold}${Y.cyan}Git Diff Summary:${Y.reset}`),e.push(` ${Y.green}+${t.stats.additions}${Y.reset} ${Y.red}-${t.stats.deletions}${Y.reset} in ${t.files.length} file(s)`),e.push(`
|
|
83
|
+
${Y.bold}${Y.cyan}Files:${Y.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Y.dim}${s}${Y.reset}`);return t.files.length>20&&e.push(` ${Y.dim}...+${t.files.length-20} more${Y.reset}`),e.push(`
|
|
84
|
+
${Y.bold}${Y.cyan}Suggested message:${Y.reset}`),e.push(` ${Y.cyan}${t.summary}${Y.reset}
|
|
85
85
|
`),e.join(`
|
|
86
|
-
`)}async function
|
|
87
|
-
...(truncated)`:
|
|
86
|
+
`)}async function Cc(){return(await is()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Ec(){let t=await as();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
|
+
...(truncated)`:s;e.push(`
|
|
88
88
|
DIFF:
|
|
89
|
-
${
|
|
90
|
-
`)}
|
|
91
|
-
${
|
|
92
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
89
|
+
${n}`)}return e.join(`
|
|
90
|
+
`)}vr.exports={isGitRepo:kc,getCurrentBranch:_c,getStatus:is,getDiff:ln,getChangedFiles:as,analyzeDiff:_r,createBranch:vc,commit:Sc,formatDiffSummary:Tc,getDiffContext:Ec,getMergeConflicts:Cc}});var ut=O((Mp,Sr)=>{var ls=require("fs").promises,Ac=50,Te=[],ct=[];function Mc(t,e,s,n){for(Te.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Te.length>Ac;)Te.shift();ct.length=0}async function Rc(){if(Te.length===0)return null;let t=Te.pop();if(t.oldContent===null)try{await ls.unlink(t.filePath)}catch{}else await ls.writeFile(t.filePath,t.oldContent,"utf-8");return ct.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Nc(){if(ct.length===0)return null;let t=ct.pop();return await ls.writeFile(t.filePath,t.newContent,"utf-8"),Te.push(t),{tool:t.tool,filePath:t.filePath}}function Oc(t=10){return Te.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Pc(){return Te.length}function qc(){return ct.length}function Ic(){Te.length=0,ct.length=0}Sr.exports={recordChange:Mc,undo:Rc,redo:Nc,getHistory:Oc,getUndoCount:Pc,getRedoCount:qc,clearHistory:Ic}});var At=O((Rp,Rr)=>{var fe=require("fs"),dt=require("path"),ce=[];function cs(){return dt.join(process.cwd(),".nex","skills")}function Tr(){return dt.join(process.cwd(),".nex","config.json")}function Lc(){let t=cs();return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function us(){let t=Tr();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 Cr(t){let e=Tr(),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 Er(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 Ar(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 Mr(t){try{let e=require(t),{valid:s,errors:n}=Er(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
|
+
${n.join(`
|
|
92
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function jc(){ce=[];let t=cs();if(!fe.existsSync(t))return ce;let e=us(),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=Ar(o):n.endsWith(".js")&&(a=Mr(o)),a&&(a.enabled=!e.includes(a.name),ce.push(a))}return ce}function Dc(){let t=[];for(let e of ce)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
93
93
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
94
94
|
${t.join(`
|
|
95
95
|
|
|
96
|
-
`)}`}function
|
|
97
|
-
`,
|
|
98
|
-
`);for(let g of h)if(g.trim())try{let x=JSON.parse(g);if(x.id===
|
|
99
|
-
`):JSON.stringify(o)}function
|
|
100
|
-
Available tools: ${d.join(", ")}`}}if(!
|
|
101
|
-
`+
|
|
96
|
+
`)}`}function Fc(){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 Uc(){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 Wc(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 Bc(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 Hc(){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 Gc(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=us().filter(n=>n!==t);return Cr(s),!0}function zc(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=us();return s.includes(t)||(s.push(t),Cr(s)),!0}function Kc(){return ce}Rr.exports={initSkillsDir:Lc,loadAllSkills:jc,getSkillInstructions:Dc,getSkillCommands:Fc,getSkillToolDefinitions:Uc,routeSkillCall:Wc,handleSkillCommand:Bc,listSkills:Hc,enableSkill:Gc,disableSkill:zc,getLoadedSkills:Kc,_getSkillsDir:cs,_validateScriptSkill:Er,_loadMarkdownSkill:Ar,_loadScriptSkill:Mr}});var un=O((Np,Lr)=>{var{spawn:Jc}=require("child_process"),Yc=require("path"),Nr=require("fs"),Ce=new Map;function Vc(){return Yc.join(process.cwd(),".nex","config.json")}function ds(){let t=Vc();if(!Nr.existsSync(t))return{};try{return JSON.parse(Nr.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function cn(t,e,s={},n=1e4){return new Promise((o,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,l=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:s})+`
|
|
97
|
+
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){c+=m.toString();let h=c.split(`
|
|
98
|
+
`);for(let g of h)if(g.trim())try{let x=JSON.parse(g);if(x.id===a){f(),x.error?r(new Error(`MCP error: ${x.error.message||JSON.stringify(x.error)}`)):o(x.result);return}}catch{}c=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(l)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Or(t,e){if(Ce.has(t))return Ce.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=Jc(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await cn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await cn(o,"tools/list",{});return r.tools=a&&a.tools||[],Ce.set(t,r),r}catch(a){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function Pr(t){let e=Ce.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ce.delete(t),!0}function Xc(){for(let[t]of Ce)Pr(t)}async function qr(t,e,s={}){let n=Ce.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await cn(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(`
|
|
99
|
+
`):JSON.stringify(o)}function Ir(){let t=[];for(let[e,s]of Ce)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 Qc(){return Ir().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Zc(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 qr(n,o,e)}function eu(){let t=ds();return Object.entries(t).map(([e,s])=>{let n=Ce.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function tu(){let t=ds(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Or(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Lr.exports={loadMCPConfig:ds,sendRequest:cn,connectServer:Or,disconnectServer:Pr,disconnectAll:Xc,callTool:qr,getAllTools:Ir,getMCPToolDefinitions:Qc,routeMCPCall:Zc,listServers:eu,connectAll:tu}});var fs=O((Op,Ur)=>{var{getSkillToolDefinitions:nu}=At(),{getMCPToolDefinitions:su}=un(),dn=new Map;function jr(){let{TOOL_DEFINITIONS:t}=ze();return[...t,...nu(),...su()]}function Dr(t){if(dn.has(t))return dn.get(t);let s=jr().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return dn.set(t,n),n}function ou(){dn.clear()}function fn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Fr(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Fr(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 ru(t,e){let s=Dr(t);if(s===null){let d=jr().map(m=>m.function.name),f=fn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
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=[],l={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=fn(u,r);d&&!o.includes(d)?(l[u]=e[d],delete l[d],c=!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=fn(u,o);d&&!(d in l)?(l[d]=e[u],delete l[u],c=!0):c||a.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(l)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof l[u];d==="string"&&f==="number"?(l[u]=String(l[u]),c=!0):d==="number"&&f==="string"&&!isNaN(l[u])?(l[u]=Number(l[u]),c=!0):d==="boolean"&&f==="string"&&(l[u]=l[u]==="true",c=!0)}return a.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
|
|
101
|
+
`+a.map(u=>` - ${u}`).join(`
|
|
102
102
|
`)+`
|
|
103
103
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(
|
|
104
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?l:null}}Ur.exports={validateToolArgs:ru,closestMatch:fn,levenshtein:Fr,getCachedSchema:Dr,clearSchemaCache:ou}});var Gr=O((Pp,Hr)=>{var{levenshtein:mn}=fs(),iu=200,au=.3,lu=2;function ms(t){return t.replace(/\r\n/g,`
|
|
105
105
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
107
|
-
`).map(e=>{let
|
|
108
|
-
`)}function
|
|
109
|
-
`),r=
|
|
110
|
-
`),
|
|
111
|
-
`),
|
|
112
|
-
`)}if(
|
|
106
|
+
`).replace(/\t/g," ".repeat(lu)).split(`
|
|
107
|
+
`).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 cu(t,e){if(t.includes(e))return e;let s=ms(t),n=ms(e);if(!s.includes(n))return null;let o=t.split(`
|
|
109
|
+
`),r=s.split(`
|
|
110
|
+
`),a=n.split(`
|
|
111
|
+
`),l=a[0],c=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(`
|
|
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 uu(t,e){if(!t||!e)return null;let s=t.split(`
|
|
113
113
|
`),o=e.split(`
|
|
114
|
-
`).length;return
|
|
115
|
-
`),u=
|
|
116
|
-
`),h=
|
|
117
|
-
`),
|
|
118
|
-
`).filter(Boolean),
|
|
119
|
-
|
|
114
|
+
`).length;return s.length===0||o===0?null:o===1?du(s,e):mu(s,e,o)}function Wr(t){return Math.max(1,Math.floor(t/iu))}function Br(t,e){return t<=Math.ceil(e*au)}function du(t,e){let s=e.trim(),n=Wr(t.length),o=null,r=1/0;for(let a=0;a<t.length;a+=n){let l=t[a];if(!l.trim())continue;let c=mn(l.trim(),s);c<r&&(r=c,o={text:l,distance:c,line:a+1})}return o&&n>1&&(o=fu(t,s,o,n)||o,r=o.distance),Br(r,e.length)?o:null}function fu(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),a=Math.min(t.length-1,o+n),l=s.distance,c=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=mn(d.trim(),e);f<l&&(l=f,c={text:d,distance:f,line:u+1})}return c}function mu(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Wr(n),r=null,a=1/0;for(let l=0;l<n;l+=o){let c=t.slice(l,l+s).join(`
|
|
115
|
+
`),u=mn(c,e);u<a&&(a=u,r={text:c,distance:u,line:l+1})}return r&&o>1&&(r=pu(t,e,r,o,s,n)||r,a=r.distance),Br(a,e.length)?r:null}function pu(t,e,s,n,o,r){let a=s.line-1,l=Math.max(0,a-n),c=Math.min(r-1,a+n),u=s.distance,d=null;for(let f=l;f<=c;f++){let m=t.slice(f,f+o).join(`
|
|
116
|
+
`),h=mn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Hr.exports={normalizeWhitespace:ms,fuzzyFindText:cu,findMostSimilar:uu}});var Kr=O((Ip,zr)=>{var{C:qp}=Q(),hu=[{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}],gu=[{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 $u(t,e){let s=e.split(`
|
|
117
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],l=r+1;for(let c of hu)c.regex.test(a)&&n.push({line:l,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of gu)c.ext&&!c.ext.includes(o)||c.regex.test(a)&&n.push({line:l,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}zr.exports={runDiagnostics:$u}});var gs=O((Lp,Vr)=>{var yu=require("fs").promises,Jr=require("path"),{exec:wu}=require("util").promisify(require("child_process").exec),ft=[],hs=null,pn=!1,ps=0,bu=6e4;function Yr(t){return!(ft.length===0||hs!==t||Date.now()-ps>bu)}async function xu(t){if(!pn&&!Yr(t)){pn=!0,hs=t;try{try{let{stdout:n}=await wu("rg --files",{cwd:t,timeout:5e3});ft=n.split(`
|
|
118
|
+
`).filter(Boolean),ps=Date.now(),pn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await yu.readdir(n,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let l=o?`${o}/${a.name}`:a.name;a.isDirectory()?await s(Jr.join(n,a.name),l):e.push(l)}};await s(t,""),ft=e,ps=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{pn=!1}}}function ku(){return ft}function _u(){return hs}function vu(t){return ft.filter(e=>Jr.basename(e)===t)}function Su(t){let e=t.toLowerCase();return ft.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Vr.exports={refreshIndex:xu,getFileIndex:ku,getIndexedCwd:_u,findFileInIndex:vu,searchIndex:Su,isIndexValid:Yr}});var Rt=O((jp,Zr)=>{var $s=null,Ee=null,Mt=null,Xr=`Playwright is not installed. Install with:
|
|
119
|
+
npm install playwright && npx playwright install chromium
|
|
120
|
+
Then restart nex-code.`;function Qr(){if(Mt!==null)return Mt;try{require("playwright"),Mt=!0}catch{Mt=!1}return Mt}async function hn(){if(!Qr())throw new Error(Xr);return $s||($s=require("playwright")),(!Ee||!Ee.isConnected())&&(Ee=await $s.chromium.launch({headless:!0})),Ee}async function Tu(){if(Ee){try{await Ee.close()}catch{}Ee=null}}process.on("exit",()=>{if(Ee)try{Ee.close()}catch{}});async function Cu(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await hn()).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||"")),l=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
121
|
+
...(truncated)`:""),links:l.slice(0,20)}}finally{await o.close()}}async function Eu(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let a=await(await hn()).newPage();try{await a.setViewportSize({width:e,height:s}),await a.goto(t,{waitUntil:"networkidle",timeout:o});let l=await a.screenshot({type:"png",fullPage:n}),c=require("os"),u=require("path"),d=require("fs"),f=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,l),{path:f,base64:l.toString("base64"),media_type:"image/png",title:await a.title(),url:a.url()}}finally{await a.close()}}async function Au(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await hn()).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 Mu(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 hn()).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()}}Zr.exports={isPlaywrightAvailable:Qr,browserNavigate:Cu,browserScreenshot:Eu,browserClick:Au,browserFill:Mu,closeBrowser:Tu,INSTALL_MSG:Xr}});var gn=O((Dp,ei)=>{var{C:B}=Q(),Ot="",ie=[],Nt=0,Ke=null;function Ru(t){Ke=t}function Nu(t,e){Ot=t,ie=[],Nt=0;for(let n of e){Nt++;let o=`t${Nt}`;ie.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Nt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ie.map(n=>({...n}));return Ke&&Ke("create",{name:t,tasks:s}),s}function Ou(t,e,s){let n=ie.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Ke&&Ke("update",{id:t,status:e,result:s}),{...n}):null}function Pu(){return{name:Ot,tasks:ie.map(t=>({...t}))}}function qu(){Ot="",ie=[],Nt=0,Ke&&Ke("clear",{})}function Iu(){return ie.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ie.find(n=>n.id===e);return s&&s.status==="done"}))}function Lu(){if(ie.length===0)return`${B.dim}No active tasks${B.reset}`;let t=[];Ot&&(t.push(` ${B.bold}${B.cyan}Tasks: ${Ot}${B.reset}`),t.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`));for(let o of ie){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 l=o.dependsOn.length>0?` ${B.dim}(after: ${o.dependsOn.join(", ")})${B.reset}`:"",c=`[${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}${c}${B.reset}${l}`),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=ie.filter(o=>o.status==="done").length,s=ie.filter(o=>o.status==="failed").length,n=ie.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(`
|
|
122
|
+
`)}function ju(){return ie.length>0&&ie.some(t=>t.status==="pending"||t.status==="in_progress")}ei.exports={createTasks:Nu,updateTask:Ou,getTaskList:Pu,clearTasks:qu,getReadyTasks:Iu,renderTaskList:Lu,setOnChange:Ru,hasActiveTasks:ju}});var ws=O((Fp,ni)=>{var{getActiveModel:Du,getActiveProviderName:Fu}=oe(),Pt={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},qt={"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"},xe={};function ti(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(xe=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{xe={}}}ti();function ys(){let e=Du()?.id,s=Fu();return e&&xe[e]?xe[e]:s&&xe[`${s}:*`]?xe[`${s}:*`]:e&&qt[e]?qt[e]:s&&It[s]?It[s]:"full"}function Uu(t,e){return t&&xe[t]?xe[t]:e&&xe[`${e}:*`]?xe[`${e}:*`]:t&&qt[t]?qt[t]:e&&It[e]?It[e]:"full"}function Wu(t,e){let s=e||ys();if(s==="full"||!Pt[s])return t;let n=new Set(Pt[s]);return t.filter(o=>n.has(o.function.name))}function Bu(){let t=ys(),e=Pt[t]?Pt[t].length:"all";return{tier:t,toolCount:e}}ni.exports={filterToolsForModel:Wu,getActiveTier:ys,getModelTier:Uu,getTierInfo:Bu,TIERS:Pt,MODEL_TIERS:qt,PROVIDER_DEFAULT_TIER:It,loadConfigOverrides:ti}});var fi=O((Wp,di)=>{var{callStream:Hu,getActiveProviderName:_s,getActiveModelId:Gu,getConfiguredProviders:zu,getProvider:Ku,getActiveProvider:Ju,parseModelSpec:Yu}=oe(),{parseToolArgs:Vu}=on(),{filterToolsForModel:Xu,getModelTier:xs}=ws(),{trackUsage:Qu}=lt(),{MultiProgress:Zu,C:Up}=Q(),ed=15,si=5,oi=3,$n=new Map;function td(t,e){let s=$n.get(t);return s&&s!==e?!1:($n.set(t,e),!0)}function bs(t){$n.delete(t)}function ks(){$n.clear()}function ri(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 ii(t,e,s){let n;for(let o=0;o<=oi;o++)try{return await Hu(t,e,s)}catch(r){if(n=r,o<oi&&ri(r)){let a=Math.min(2e3*Math.pow(2,o),15e3);await new Promise(l=>setTimeout(l,a).unref());continue}throw r}throw n}var nd=new Set(["ask_user","task_list","spawn_agents"]),sd=new Set(["write_file","edit_file","patch_file"]),od=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,rd=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ai(t){return rd.test(t)?"full":od.test(t)?"essential":"standard"}function li(t){let e=zu(),s=_s(),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(xs(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}function ci(t){if(t.model){let{provider:n,model:o}=Yu(t.model),r=n?Ku(n):Ju(),a=n||_s();if(r&&r.isConfigured()&&(r.getModel(o)||a==="local")){let l=xs(o,a);return{provider:a,model:o,tier:l}}}let e=ai(t.task),s=li(e);if(s){let n=xs(s.model,s.provider);return{provider:s.provider,model:s.model,tier:n}}return{provider:null,model:null,tier:null}}async function ui(t,e={}){let s=Math.min(t.max_iterations||10,ed),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},a=new Set,c=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
120
123
|
|
|
121
124
|
TASK: ${t.task}
|
|
122
125
|
${t.context?`
|
|
@@ -138,69 +141,93 @@ TOOL STRATEGY:
|
|
|
138
141
|
ERROR RECOVERY:
|
|
139
142
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
140
143
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
141
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];
|
|
142
|
-
...(truncated)`:
|
|
143
|
-
`)}catch(o){return
|
|
144
|
-
${
|
|
145
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
146
|
-
|
|
147
|
-
`+
|
|
148
|
-
`)}function oi(t,e,n){let s=yn(t,e);if(!s)return null;let o=Math.max(3,Math.ceil(e.length*.05));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var ei=!1;async function $n(){if(!ei){ei=!0;try{let{stdout:t}=await It("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await It('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await It("git stash pop",{cwd:process.cwd(),timeout:1e4}),await It("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Uu=[/\.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 n of Uu)if(n.test(e))return null;return e}var Wu=[{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 using DuckDuckGo. Returns titles and URLs. 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:"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:"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 ti(t,e,n={}){switch(t){case"bash":{let s=e.command,o=Ru(s);if(o)return`BLOCKED: Command matches forbidden pattern: ${o}`;if(Nu(s)&&!n.autoConfirm&&(console.log(`
|
|
149
|
-
${
|
|
150
|
-
${
|
|
151
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),
|
|
144
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];c.push({role:"user",content:t.task});let u=ci(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:g}=ze(),x=Xu(h.filter($=>!nd.has($.function.name)),m),w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let k=await ii(c,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 I=d||_s(),M=f||Gu();Qu(I,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),c.push(S),!b||b.length===0){for(let E of a)bs(E);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let _=b.map(E=>{let P=E.function.name,I=Vu(E.function.arguments),M=E.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!I)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${P}`,tool_call_id:M});if(sd.has(P)&&I.path){let N=require("path"),q=N.isAbsolute(I.path)?I.path:N.resolve(process.cwd(),I.path);if(!td(q,n))return Promise.resolve({role:"tool",content:`ERROR: File '${I.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:M});a.add(q)}return o.push(P),g(P,I,{autoConfirm:!0,silent:!0}).then(N=>{let q=String(N??"");return{role:"tool",content:q.length>2e4?q.substring(0,2e4)+`
|
|
145
|
+
...(truncated)`:q,tool_call_id:M}}).catch(N=>({role:"tool",content:`ERROR: ${N.message}`,tool_call_id:M}))}),C=await Promise.all(_);c.push(...C),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of a)bs($);return{task:t.task,status:"done",result:c[c.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let k of a)bs(k);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function id(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>si)return`ERROR: Max ${si} parallel agents allowed, got ${e.length}`;let s=e.map((o,r)=>`Agent ${r+1}: ${o.task.substring(0,50)}${o.task.length>50?"...":""}`),n=new Zu(s);n.start();try{let o=e.map((u,d)=>ui(u,{onUpdate:()=>{}}).then(f=>(n.update(d,f.status==="done"?"done":"error"),f)).catch(f=>(n.update(d,"error"),{task:u.task,status:"failed",result:`Error: ${f.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))),r=await Promise.all(o);n.stop(),ks();let a=["Sub-agent results:",""],l=0,c=0;for(let u=0;u<r.length;u++){let d=r[u],f=d.status==="done"?"\u2713":"\u2717",m=d.modelSpec?` [${d.modelSpec}]`:"";a.push(`${f} Agent ${u+1}${m}: ${d.task}`),a.push(` Status: ${d.status}`),a.push(` Tools used: ${d.toolsUsed.length>0?d.toolsUsed.join(", "):"none"}`),a.push(` Result: ${d.result}`),a.push(""),l+=d.tokensUsed.input,c+=d.tokensUsed.output}return a.push(`Total sub-agent tokens: ${l} input + ${c} output`),a.join(`
|
|
146
|
+
`)}catch(o){return n.stop(),ks(),`ERROR: Sub-agent execution failed: ${o.message}`}}di.exports={runSubAgent:ui,executeSpawnAgents:id,clearAllLocks:ks,classifyTask:ai,pickModelForTier:li,resolveSubAgentModel:ci,isRetryableError:ri,callWithRetry:ii}});var ze=O((Gp,ki)=>{var J=require("fs").promises,ad=require("fs"),de=require("path"),Ae=require("util").promisify(require("child_process").exec),mi=require("util").promisify(require("child_process").execFile),{spawnSync:ld}=require("child_process"),vs=require("axios"),{isForbidden:cd,isDangerous:ud,isCritical:pi,confirm:dd}=Se(),{showClaudeDiff:yn,showClaudeNewFile:fd,showEditDiff:Bp,confirmFileChange:Lt}=xr(),{C:H,Spinner:wi,getToolSpinnerText:md}=Q(),{isGitRepo:Ss,getCurrentBranch:hi,getStatus:pd,getDiff:hd}=Ge(),{recordChange:wn}=ut(),{fuzzyFindText:gi,findMostSimilar:Cs}=Gr(),{runDiagnostics:jt}=Kr(),{findFileInIndex:gd,getFileIndex:Hp}=gs(),$d=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|ssh\s|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/;async function bn(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=ue(e);if(s&&await J.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=de.extname(t);if(!o)for(let a of n){let l=ue(t+a);if(l&&await J.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: added ${a} extension)`}}if(o){let a=t.replace(/\.[^.]+$/,"");for(let l of n){if(l===o)continue;let c=ue(a+l);if(c&&await J.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${l})`}}}let r=de.basename(t);if(r&&r.length>2)try{let a=gd(r).map(l=>ue(l));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${de.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
147
|
+
${a.map(c=>de.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
|
|
148
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function bi(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.`)}return/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."),s.length===0?t:t+`
|
|
149
|
+
|
|
150
|
+
`+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
|
+
${H.yellow}${l}: ${n}${H.reset}`),!await dd(" Execute?"))return"CANCELLED: User declined to execute this command."}if($d.test(n.trim())){s.silent||console.log(`${H.dim} \u25B6 interactive: ${n}${H.reset}`);let l=ld("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 a=s.silent?null:new wi(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);a&&a.start();try{let{stdout:l,stderr:c}=await Ae(n,{cwd:process.cwd(),timeout:9e4,maxBuffer:5242880});return a&&a.stop(),l||c||"(no output)"}catch(l){a&&a.stop();let c=(l.stderr||l.stdout||l.message||"").toString().substring(0,5e3),u=bi(c,n);return`EXIT ${l.code||1}
|
|
153
|
+
${u}`}}case"read_file":{let n=ue(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let m=await bn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${de.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
154
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await ad.promises.open(n,"r"),{bytesRead:l}=await a.read(r,0,8192,0);await a.close();for(let m=0;m<l;m++)if(r[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await J.readFile(n,"utf-8");if(!c&&(await J.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=c.split(`
|
|
152
155
|
`),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(`
|
|
153
|
-
`)}case"write_file":{await
|
|
154
|
-
`+d.message:""}`}let r=await
|
|
156
|
+
`)}case"write_file":{await Ts();let n=ue(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await J.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await J.readFile(n,"utf-8"));else if(o){r=await J.readFile(n,"utf-8");let c=await jt(n,e.content);if(yn(n,r,e.content,{annotations:c}),!await Lt("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let c=await jt(n,e.content);if(fd(n,e.content,{annotations:c}),!await Lt("Create"))return"CANCELLED: User declined to create file."}let a=de.dirname(n);return await J.access(a).then(()=>!0).catch(()=>!1)||await J.mkdir(a,{recursive:!0}),await J.writeFile(n,e.content,"utf-8"),wn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Ts();let n=ue(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let d=await bn(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${de.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
157
|
+
`+d.message:""}`}let r=await J.readFile(n,"utf-8"),a=e.old_text,l=!1,c=!1;if(!r.includes(e.old_text)){let d=gi(r,e.old_text);if(d)a=d,l=!0,console.log(`${H.dim} \u2713 fuzzy whitespace match applied${H.reset}`);else{let f=xi(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let g=await jt(n,f.content);if(yn(n,r,f.content,{annotations:g}),!await Lt(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await J.writeFile(n,f.content,"utf-8"),wn("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=Cs(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
155
158
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
156
|
-
${m.text}`:`ERROR: old_text not found in ${
|
|
157
|
-
`)||"(empty)"}case"search_files":{let
|
|
159
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await jt(n,d);if(yn(n,r,d,{annotations:f}),!await Lt(l?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await J.writeFile(n,u,"utf-8"),wn("edit_file",n,r,u),l?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=ue(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ue(u),f=await J.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let l=[],c=async(u,d,f)=>{if(d>r)return;let m;try{m=await J.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let g=h.isDirectory()?"/":"";l.push(`${f}${h.name}${g}`),h.isDirectory()&&await c(de.join(u,h.name),d+1,f+" ")}};return await c(n,1,""),l.join(`
|
|
160
|
+
`)||"(empty)"}case"search_files":{let n=ue(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 mi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
158
161
|
`).slice(0,50).join(`
|
|
159
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
160
|
-
`);return k?`${
|
|
162
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?ue(e.path):o,a=e.pattern,l=b=>{let S=b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${S}$`)},c=l(a),u=a.split("/").pop(),d=l(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:g}=gs(),x=f(),w=m();g(r)||(await h(r),x=f());let $=x.filter(b=>c.test(b)||d.test(de.basename(b))).map(b=>de.join(r,b));if($.length===0)return"(no matches)";let k=$.length>200,T=$.slice(0,200).join(`
|
|
163
|
+
`);return k?`${T}
|
|
161
164
|
|
|
162
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
165
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?ue(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 mi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
163
166
|
`).slice(0,100).join(`
|
|
164
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
165
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let
|
|
166
|
-
Most similar text (line ${
|
|
167
|
-
${
|
|
167
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Ts();let n=ue(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await J.access(n).then(()=>!0).catch(()=>!1)){let m=await bn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${de.relative(process.cwd(),n)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
168
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await J.readFile(n,"utf-8"),l=[],c=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:h,new_text:g}=r[m];if(a.includes(h))l.push({old_text:h,new_text:g});else{let x=gi(a,h);if(x)l.push({old_text:x,new_text:g}),c=!0;else{let w=Cs(a,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)l.push({old_text:w.text,new_text:g}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
169
|
+
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 l)d=d.split(m).join(h);if(!s.autoConfirm){let m=await jt(n,d);if(yn(n,a,d,{annotations:m}),!await Lt(c?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await J.writeFile(n,d,"utf-8"),wn("patch_file",n,a,d);let f=u?" (auto-fixed)":c?" (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 vs.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 vs.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||[],l=`[Perplexity grounded search]
|
|
171
|
+
|
|
172
|
+
${r}`;return a.length>0&&(l+=`
|
|
173
|
+
|
|
174
|
+
Sources:
|
|
175
|
+
`+a.slice(0,n).map((c,u)=>`${u+1}. ${c}`).join(`
|
|
176
|
+
`)),l}catch(o){console.error(`${H.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${H.reset}`)}try{let r=(await vs.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],l=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=l.exec(r))!==null&&a.length<n;){let u=c[1].replace(/.*uddg=/,"").split("&")[0],d=c[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}
|
|
168
177
|
${u.url}`).join(`
|
|
169
178
|
|
|
170
|
-
`)}catch{return"ERROR: Web search failed"}}case"
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
179
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Rt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
180
|
+
|
|
181
|
+
Links:
|
|
182
|
+
`+o.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
183
|
+
`):"";return`Title: ${o.title}
|
|
184
|
+
URL: ${o.url}
|
|
185
|
+
|
|
186
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Rt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
187
|
+
Title: ${o.title}
|
|
188
|
+
URL: ${o.url}
|
|
189
|
+
|
|
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}=Rt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Rt();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});console.log(`
|
|
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 Ss())return"ERROR: Not a git repository";let n=await hi()||"(detached)",o=await pd();if(o.length===0)return`Branch: ${n}
|
|
192
|
+
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let a of o){let l=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${l}: ${a.file}`)}return r.join(`
|
|
193
|
+
`)}case"git_diff":{if(!await Ss())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 hd(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Ss())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:l}=gn(),{getActiveTaskProgress:c}=Q(),u=c();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
|
+
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
175
195
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
176
196
|
`)}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(`
|
|
177
|
-
`+
|
|
178
|
-
`+
|
|
197
|
+
`+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}=fi();return n(e)}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Ae(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.map(c=>{let u=c.conclusion||c.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
199
|
+
`)}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 Ae(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
201
|
+
...(truncated)`:"")}let{stdout:n}=await Ae(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of o.jobs||[]){let l=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${l} ${a.name} (${a.conclusion||a.status})`);for(let c of a.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let u=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${c.name}`)}}return r.join(`
|
|
202
|
+
`)}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}=Se(),o=e.branch||await hi()||"main",r=e.inputs?Object.entries(e.inputs).map(([c,u])=>`-f ${c}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
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 Ae(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
205
|
+
`)[0]}`}}default:return`ERROR: Unknown tool: ${t}`}}async function bd(t,e,s={}){let n=s.silent?null:md(t,e);if(!n)return yi(t,e,s);let o=new wi(n);o.start();try{let r=await yi(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}ki.exports={TOOL_DEFINITIONS:wd,executeTool:bd,resolvePath:ue,autoFixPath:bn,autoFixEdit:xi,enrichBashError:bi}});var As=O((zp,vi)=>{var $e=require("fs").promises,me=require("path"),xn=require("util").promisify(require("child_process").exec),{C:ke}=Q(),{getMergeConflicts:_i}=Ge(),Es=new Map,mt=new Map,kn=null,xd=3e4;async function Ie(t){try{return await t()}catch{return null}}async function kd(){if(!kn||Date.now()>kn)return!1;let t=[me.join(process.cwd(),"package.json"),me.join(process.cwd(),"README.md"),me.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await $e.stat(e),n=mt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(mt.has(e))return!1}try{let e=me.join(process.cwd(),".git","HEAD"),s=await $e.stat(e),n=mt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function _d(){let t=[me.join(process.cwd(),"package.json"),me.join(process.cwd(),"README.md"),me.join(process.cwd(),".gitignore"),me.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await $e.stat(e);mt.set(e,s.mtimeMs)}catch{mt.delete(e)}}async function vd(t){let e="fileContext",s=Es.get(e),n=!1;if(s&&await kd()&&(n=!0),!n){let u=[],d=me.join(t,"package.json");if(await Ie(()=>$e.access(d).then(()=>!0).catch(()=>!1)))try{let w=await $e.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=me.join(t,"README.md");if(await Ie(()=>$e.access(m).then(()=>!0).catch(()=>!1))){let $=(await $e.readFile(m,"utf-8")).split(`
|
|
179
206
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
180
207
|
${$.join(`
|
|
181
|
-
`)}`)}let g=me.join(t,".gitignore");if(await
|
|
182
|
-
${
|
|
208
|
+
`)}`)}let g=me.join(t,".gitignore");if(await Ie(()=>$e.access(g).then(()=>!0).catch(()=>!1))){let w=await $e.readFile(g,"utf-8");u.push(`GITIGNORE:
|
|
209
|
+
${w.trim()}`)}s=u.join(`
|
|
183
210
|
|
|
184
|
-
`),
|
|
185
|
-
${
|
|
186
|
-
${
|
|
211
|
+
`),Es.set(e,s),kn=Date.now()+xd,await _d()}let o=[s],[r,a,l,c]=await Promise.all([Ie(async()=>{let{stdout:u}=await xn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ie(async()=>{let{stdout:u}=await xn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ie(async()=>{let{stdout:u}=await xn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),_i()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
212
|
+
${a}`),l&&o.push(`RECENT COMMITS:
|
|
213
|
+
${l}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
|
|
187
214
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
188
215
|
${u}`)}return o.join(`
|
|
189
216
|
|
|
190
|
-
`)}async function
|
|
191
|
-
${e}`);let
|
|
192
|
-
${
|
|
217
|
+
`)}async function Sd(t){let e=me.join(t,"package.json"),s="";if(await Ie(()=>$e.access(e).then(()=>!0).catch(()=>!1)))try{let a=await $e.readFile(e,"utf-8"),l=JSON.parse(a);s=`${l.name||"?"} v${l.version||"?"}`}catch{}let[o,r]=await Promise.all([Ie(async()=>{let{stdout:a}=await xn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),_i()]);if(s&&console.log(`${ke.dim} project: ${s}${ke.reset}`),o&&console.log(`${ke.dim} branch: ${o}${ke.reset}`),r&&r.length>0){console.log(`${ke.red} \u26A0 ${r.length} unresolved merge conflict(s):${ke.reset}`);for(let a of r)console.log(`${ke.red} ${a.file}${ke.reset}`);console.log(`${ke.yellow} \u2192 Resolve conflicts before starting tasks${ke.reset}`)}console.log()}vi.exports={gatherProjectContext:vd,printContext:Sd,_clearContextCache:()=>{Es.clear(),mt.clear(),kn=null}}});var Ye=O((Kp,Ei)=>{var Re=require("fs"),Ms=require("path");function _n(){return Ms.join(process.cwd(),".nex","sessions")}function Si(){let t=_n();Re.existsSync(t)||Re.mkdirSync(t,{recursive:!0})}function Rs(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ms.join(_n(),`${e}.json`)}function Ns(t,e,s={}){Si();let n=Rs(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 Re.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Ti(t){let e=Rs(t);if(!Re.existsSync(e))return null;try{return JSON.parse(Re.readFileSync(e,"utf-8"))}catch{return null}}function Ci(){Si();let t=_n(),e=Re.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Re.readFileSync(Ms.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 Td(t){let e=Rs(t);return Re.existsSync(e)?(Re.unlinkSync(e),!0):!1}function Cd(){let t=Ci();return t.length===0?null:Ti(t[0].name)}var Je=null,Me=null,Dt=null;function Ed(t,e={}){t.length!==0&&(Je&&clearTimeout(Je),Me=t,Dt=e||{},Je=setTimeout(()=>{Me&&Me.length>0&&Ns("_autosave",Me,Dt),Je=null,Me=null,Dt=null},5e3))}function Ad(){Je&&(clearTimeout(Je),Je=null),Me&&Me.length>0&&(Ns("_autosave",Me,Dt),Me=null,Dt=null)}Ei.exports={saveSession:Ns,loadSession:Ti,listSessions:Ci,deleteSession:Td,getLastSession:Cd,autoSave:Ed,flushAutoSave:Ad,_getSessionsDir:_n}});var Le=O((Jp,Pi)=>{var Ne=require("fs"),vn=require("path"),Md=require("os");function Os(){return vn.join(process.cwd(),".nex","memory")}function Ps(){return vn.join(Os(),"memory.json")}function Rd(){return vn.join(process.cwd(),"NEX.md")}function Ai(){return vn.join(Md.homedir(),".nex","NEX.md")}function Nd(){let t=Os();Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0})}function Sn(){let t=Ps();if(!Ne.existsSync(t))return{};try{return JSON.parse(Ne.readFileSync(t,"utf-8"))}catch{return{}}}function Mi(t){Nd(),Ne.writeFileSync(Ps(),JSON.stringify(t,null,2),"utf-8")}function Od(t,e){let s=Sn();s[t]={value:e,updatedAt:new Date().toISOString()},Mi(s)}function Pd(t){let e=Sn();return e[t]?e[t].value:null}function qd(t){let e=Sn();return t in e?(delete e[t],Mi(e),!0):!1}function Ri(){let t=Sn();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Ni(){let t=Ai();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function Oi(){let t=Rd();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function Id(){let t=[],e=Ni();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
218
|
+
${e}`);let s=Oi();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
219
|
+
${s}`);let n=Ri();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
193
220
|
`);t.push(`PROJECT MEMORY:
|
|
194
221
|
${o}`)}return t.join(`
|
|
195
222
|
|
|
196
|
-
`)}
|
|
197
|
-
${F.bold}${F.cyan}Plan: ${t.task}${F.reset}`),
|
|
198
|
-
`);for(let
|
|
199
|
-
`)}function
|
|
223
|
+
`)}Pi.exports={remember:Od,recall:Pd,forget:qd,listMemories:Ri,loadGlobalInstructions:Ni,loadProjectInstructions:Oi,getMemoryContext:Id,_getMemoryDir:Os,_getMemoryFile:Ps,_getGlobalNexMdPath:Ai}});var Ft=O((Vp,Li)=>{var Ve=require("fs"),qs=require("path"),{C:Yp}=Q(),Tn={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={...Tn};function qi(){let t=qs.join(process.cwd(),".nex","config.json");if(Ve.existsSync(t))try{let e=JSON.parse(Ve.readFileSync(t,"utf-8"));e.permissions&&(pt={...Tn,...e.permissions})}catch{}}function Ld(){let t=qs.join(process.cwd(),".nex"),e=qs.join(t,"config.json"),s={};if(Ve.existsSync(e))try{s=JSON.parse(Ve.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=pt,Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0}),Ve.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Ii(t){return pt[t]||"ask"}function jd(t,e){return["allow","ask","deny"].includes(e)?(pt[t]=e,!0):!1}function Dd(t){return Ii(t)}function Fd(){return Object.entries(pt).map(([t,e])=>({tool:t,mode:e}))}function Ud(){pt={...Tn}}qi();Li.exports={getPermission:Ii,setPermission:jd,checkPermission:Dd,listPermissions:Fd,loadPermissions:qi,savePermissions:Ld,resetPermissions:Ud,DEFAULT_PERMISSIONS:Tn}});var ht=O((Qp,Wi)=>{var Xe=require("fs"),Cn=require("path"),Xp=require("readline"),{C:F}=Q(),X=null,Is=!1,Ls=null,ji=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 En(){return Cn.join(process.cwd(),".nex","plans")}function Di(){let t=En();Xe.existsSync(t)||Xe.mkdirSync(t,{recursive:!0})}function Wd(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 Bd(){return X}function Hd(t){Is=t}function Gd(){return Is}function zd(){return!X||X.status!=="draft"?!1:(X.status="approved",X.updatedAt=new Date().toISOString(),!0)}function Kd(){return!X||X.status!=="approved"?!1:(X.status="executing",!0)}function Jd(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 Yd(t){if(!t)return`${F.dim}No active plan${F.reset}`;let e={draft:`${F.yellow}DRAFT${F.reset}`,approved:`${F.green}APPROVED${F.reset}`,executing:`${F.blue}EXECUTING${F.reset}`,completed:`${F.green}COMPLETED${F.reset}`},s=[];s.push(`
|
|
224
|
+
${F.bold}${F.cyan}Plan: ${t.task}${F.reset}`),s.push(`${F.dim}Status: ${e[t.status]||t.status}${F.reset}
|
|
225
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${F.green}\u2713${F.reset}`;break;case"in_progress":r=`${F.blue}\u2192${F.reset}`;break;case"skipped":r=`${F.dim}\u25CB${F.reset}`;break;default:r=`${F.dim} ${F.reset}`}s.push(` ${r} ${F.bold}Step ${n+1}:${F.reset} ${o.description}`),o.files.length>0&&s.push(` ${F.dim}Files: ${o.files.join(", ")}${F.reset}`)}return s.push(""),s.join(`
|
|
226
|
+
`)}function Vd(t){if(t||(t=X),!t)return null;Di();let e=Cn.join(En(),`${t.name}.json`);return Xe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Xd(t){let e=Cn.join(En(),`${t}.json`);if(!Xe.existsSync(e))return null;try{let s=JSON.parse(Xe.readFileSync(e,"utf-8"));return X=s,s}catch{return null}}function Qd(){Di();let t=En(),e=Xe.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Xe.readFileSync(Cn.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 Zd(t){Ls=t}function ef(){return Ls}function tf(){X=null,Is=!1,Ls=null}function nf(){return`
|
|
200
227
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
201
228
|
|
|
202
229
|
# Allowed Tools (read-only)
|
|
203
|
-
You may ONLY use these tools: ${[...
|
|
230
|
+
You may ONLY use these tools: ${[...ji].join(", ")}
|
|
204
231
|
Any other tool call will be blocked and returned with an error.
|
|
205
232
|
|
|
206
233
|
# Analysis Phase
|
|
@@ -231,46 +258,46 @@ Bullet list of potential issues and mitigations.
|
|
|
231
258
|
# Important
|
|
232
259
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
233
260
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
234
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
235
|
-
`),
|
|
236
|
-
`)}function
|
|
237
|
-
`)}function
|
|
238
|
-
`))!==-1;){let
|
|
261
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Fi=["interactive","semi-auto","autonomous"],Ui="interactive";function sf(t){return Fi.includes(t)?(Ui=t,!0):!1}function of(){return Ui}Wi.exports={createPlan:Wd,getActivePlan:Bd,setPlanMode:Hd,isPlanMode:Gd,approvePlan:zd,startExecution:Kd,updateStep:Jd,formatPlan:Yd,savePlan:Vd,loadPlan:Xd,listPlans:Qd,clearPlan:tf,getPlanModePrompt:nf,setPlanContent:Zd,getPlanContent:ef,PLAN_MODE_ALLOWED_TOOLS:ji,setAutonomyLevel:sf,getAutonomyLevel:of,AUTONOMY_LEVELS:Fi}});var Qi=O((Zp,Xi)=>{var{C:p}=Q();function rf(t){if(!t)return"";let e=t.split(`
|
|
262
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${p.dim}${"\u2500".repeat(40)}${p.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${p.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${p.reset}`)}continue}if(n){s.push(` ${Ds(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${p.bold}${p.cyan} ${Qe(r.substring(4))}${p.reset}`);continue}if(r.startsWith("## ")){s.push(`${p.bold}${p.cyan} ${Qe(r.substring(3))}${p.reset}`);continue}if(r.startsWith("# ")){s.push(`${p.bold}${p.cyan}${Qe(r.substring(2))}${p.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,"");s.push(`${a}${p.cyan}\u2022${p.reset} ${Ze(l)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){s.push(`${a[1]}${p.cyan}${a[2]}.${p.reset} ${Ze(a[3])}`);continue}}s.push(Ze(r))}return s.join(`
|
|
263
|
+
`)}function Qe(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Ze(t){return t?t.replace(/`([^`]+)`/g,`${p.cyan}$1${p.reset}`).replace(/\*\*([^*]+)\*\*/g,`${p.bold}$1${p.reset}`).replace(/\*([^*]+)\*/g,`${p.dim}$1${p.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${p.cyan}$1${p.reset} ${p.dim}($2)${p.reset}`):""}function Ds(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Bi(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Hi(t):e==="json"||e==="jsonc"?Gi(t):e==="python"||e==="py"?zi(t):e==="go"||e==="golang"?Ki(t):e==="rust"||e==="rs"?Ji(t):e==="css"||e==="scss"||e==="less"?Yi(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Vi(t):t:""}function Bi(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,`${p.yellow}$1${p.reset}`),r=r.replace(e,`${p.magenta}$1${p.reset}`),r=r.replace(s,`${p.green}$&${p.reset}`),r=r.replace(n,`${p.dim}$1${p.reset}`),r}function Hi(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${p.cyan}$1${p.reset}`),r=r.replace(e,`$1${p.green}$2${p.reset}`),r=r.replace(n,`${p.yellow}$&${p.reset}`),r=r.replace(o,`${p.dim}$1${p.reset}`),r}function Gi(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,`${p.cyan}$1${p.reset}:`),r=r.replace(s,`: ${p.green}$1${p.reset}`),r=r.replace(n,`: ${p.yellow}$1${p.reset}`),r=r.replace(o,`: ${p.magenta}$1${p.reset}`),r}function zi(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,`${p.yellow}$1${p.reset}`),a=a.replace(e,`${p.magenta}$1${p.reset}`),a=a.replace(r,`${p.cyan}$1${p.reset}`),a=a.replace(s,`${p.green}$&${p.reset}`),a=a.replace(n,`${p.dim}$1${p.reset}`),a}function Ki(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,`${p.yellow}$1${p.reset}`),a=a.replace(s,`${p.cyan}$1${p.reset}`),a=a.replace(e,`${p.magenta}$1${p.reset}`),a=a.replace(n,`${p.green}$&${p.reset}`),a=a.replace(o,`${p.dim}$1${p.reset}`),a}function Ji(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,l=t;return l=l.replace(r,`${p.yellow}$1${p.reset}`),l=l.replace(s,`${p.cyan}$1${p.reset}`),l=l.replace(e,`${p.magenta}$1${p.reset}`),l=l.replace(a,`${p.yellow}$1${p.reset}`),l=l.replace(n,`${p.green}$&${p.reset}`),l=l.replace(o,`${p.dim}$1${p.reset}`),l}function Yi(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,l=t;return l=l.replace(a,`${p.yellow}$1${p.reset}`),l=l.replace(o,`${p.yellow}$1${p.reset}`),l=l.replace(e,`$1${p.cyan}$2${p.reset}:`),l=l.replace(n,`$1${p.magenta}$&${p.reset}`),l=l.replace(r,`${p.dim}$1${p.reset}`),l}function Vi(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,`${p.dim}$1${p.reset}`),a=a.replace(n,`${p.green}$&${p.reset}`),a=a.replace(e,`<${p.magenta}$1${p.reset}`),a=a.replace(s,` ${p.cyan}$1${p.reset}=`),a=a.replace(r,`${p.yellow}$1${p.reset}`),a}function af(t,e){if(!t||t.length===0)return"";let s=t.map((a,l)=>{let c=e.reduce((u,d)=>Math.max(u,(d[l]||"").length),0);return Math.max(a.length,c)}),n=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),o=t.map((a,l)=>` ${p.bold}${a.padEnd(s[l])}${p.reset} `).join("\u2502"),r=[];r.push(`${p.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${p.reset}`),r.push(`${p.dim}\u2502${p.reset}${o}${p.dim}\u2502${p.reset}`),r.push(`${p.dim}\u251C${n}\u2524${p.reset}`);for(let a of e){let l=t.map((c,u)=>` ${(a[u]||"").padEnd(s[u])} `).join(`${p.dim}\u2502${p.reset}`);r.push(`${p.dim}\u2502${p.reset}${l}${p.dim}\u2502${p.reset}`)}return r.push(`${p.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${p.reset}`),r.join(`
|
|
264
|
+
`)}function lf(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),a=n-r,l=o>=100?p.green:o>50?p.yellow:p.cyan;return` ${t} ${l}${"\u2588".repeat(r)}${p.dim}${"\u2591".repeat(a)}${p.reset} ${o}% (${e}/${s})`}var js=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(`
|
|
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(`${p.dim}${"\u2500".repeat(40)}${p.reset}
|
|
239
266
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${p.dim}${"\u2500".repeat(40)}${p.reset}
|
|
240
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
241
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
242
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${p.bold}${p.cyan} ${
|
|
243
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${p.bold}${p.cyan} ${
|
|
244
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${p.bold}${p.cyan}${
|
|
245
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
246
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
247
|
-
`);return}}this._safeWrite(`${
|
|
248
|
-
`)}};
|
|
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(`${p.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${p.reset}
|
|
268
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Ds(e,this.codeBlockLang)}
|
|
269
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${p.bold}${p.cyan} ${Qe(e.substring(4))}${p.reset}
|
|
270
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${p.bold}${p.cyan} ${Qe(e.substring(3))}${p.reset}
|
|
271
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${p.bold}${p.cyan}${Qe(e.substring(2))}${p.reset}
|
|
272
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${p.cyan}\u2022${p.reset} ${Ze(n)}
|
|
273
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${p.cyan}${s[2]}.${p.reset} ${Ze(s[3])}
|
|
274
|
+
`);return}}this._safeWrite(`${Ze(e)}
|
|
275
|
+
`)}};Xi.exports={renderMarkdown:rf,renderInline:Ze,stripHeadingMarkers:Qe,highlightCode:Ds,highlightJS:Bi,highlightBash:Hi,highlightJSON:Gi,highlightPython:zi,highlightGo:Ki,highlightRust:Ji,highlightCSS:Yi,highlightHTML:Vi,renderTable:af,renderProgress:lf,StreamRenderer:js}});var Ws=O((eh,na)=>{var{execSync:cf}=require("child_process"),Fs=require("path"),Ut=require("fs"),Us=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Zi(){return Fs.join(process.cwd(),".nex","hooks")}function uf(){return Fs.join(process.cwd(),".nex","config.json")}function ea(){let t=uf();if(!Ut.existsSync(t))return{};try{return JSON.parse(Ut.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function An(t){if(!Us.includes(t))return[];let e=[],s=Zi(),n=Fs.join(s,t);Ut.existsSync(n)&&e.push(n);let o=ea();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function ta(t,e={},s=3e4){try{return{success:!0,output:cf(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 df(t,e={}){let s=An(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=ta(r,n);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function ff(t){return An(t).length>0}function mf(){let t=[];for(let e of Us){let s=An(e);s.length>0&&t.push({event:e,commands:s})}return t}function pf(){let t=Zi();return Ut.existsSync(t)||Ut.mkdirSync(t,{recursive:!0}),t}na.exports={HOOK_EVENTS:Us,loadHookConfig:ea,getHooksForEvent:An,executeHook:ta,runHooks:df,hasHooks:ff,listHooks:mf,initHooksDir:pf}});var te=O((sh,ha)=>{var{C:v,Spinner:gt,TaskProgress:hf,formatToolCall:gf,formatResult:$f,formatToolSummary:ia,setActiveTaskProgress:th}=Q(),{callStream:yf}=oe(),{parseToolArgs:wf}=on(),{executeTool:bf}=ze(),{gatherProjectContext:xf}=As(),{fitToContext:kf,forceCompress:Bs,getUsage:_f,estimateTokens:vf}=be(),{autoSave:et}=Ye(),{getMemoryContext:Sf}=Le(),{checkPermission:Tf,setPermission:Cf,savePermissions:Ef}=Ft(),{confirm:aa,setAllowAlwaysHandler:Af}=Se(),{isPlanMode:On,getPlanModePrompt:Mf,PLAN_MODE_ALLOWED_TOOLS:la,setPlanContent:Rf}=ht(),{StreamRenderer:Nf}=Qi(),{runHooks:sa}=Ws(),{routeMCPCall:Of,getMCPToolDefinitions:Pf}=un(),{getSkillInstructions:qf,getSkillToolDefinitions:If,routeSkillCall:Lf}=At(),{trackUsage:jf}=lt(),{validateToolArgs:Df}=fs(),{filterToolsForModel:oa,getModelTier:Ff,PROVIDER_DEFAULT_TIER:nh}=ws(),{getConfiguredProviders:Uf}=oe(),ca=require("fs"),ua=require("path"),ra=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Wf(t){let e=[],s;for(ra.lastIndex=0;(s=ra.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):ua.resolve(n);ca.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Bf(t){let e=ca.readFileSync(t),s=ua.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 da(t){let e=Wf(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}=Bf(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Hs=null,Gs=null,zs=null;function $t(){if(Hs===null){let{TOOL_DEFINITIONS:t}=ze();Hs=t}return Gs===null&&(Gs=If()),zs===null&&(zs=Pf()),[...Hs,...Gs,...zs]}var Vs=50;function Hf(t){Number.isFinite(t)&&t>0&&(Vs=t)}var Rn=()=>null;function Gf(t){Rn=t}var Wt=null,Xs=null,yt=null,Nn=new Map,zf=1e4,Kf=6e3;function Jf(t){if(vf(t)>zf)try{let{compressToolResult:s}=be();return s(t,Kf)}catch{return t}return t}function fa(t){try{let{getActiveModel:e}=oe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Nn.has(n))return Nn.get(n);let o=oa(t);return Nn.set(n,o),o}catch{return oa(t)}}function Yf(){Nn.clear()}async function ma(){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}=Le(),a=r();a&&o.push(`memory:${a}`)}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function Vf(){Wt=null,Xs=null,yt=null}var Xf=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"]),Ks=5,Js=3,Mn=2,Qf=6e4,Zf=12e4;function em(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{}}Af(t=>{Cf(t,"allow"),Ef(),console.log(`${v.green} \u2713 ${t}: always allow${v.reset}`)});async function tm(t){let e=t.function.name,s=wf(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let c=$t().find(d=>d.function.name===e),u=c?JSON.stringify(c.function.parameters,null,2):"unknown";return console.log(`${v.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${v.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
249
276
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
250
277
|
|
|
251
278
|
Expected JSON schema for "${e}":
|
|
252
279
|
${u}
|
|
253
280
|
|
|
254
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:
|
|
255
|
-
`)[0]}${
|
|
256
|
-
...(truncated ${
|
|
257
|
-
`)[0],
|
|
281
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Df(e,s);if(!o.valid)return console.log(`${v.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
282
|
+
`)[0]}${v.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),c=Object.keys(o.corrected),u=l.filter(d=>!c.includes(d));u.length&&console.log(`${v.dim} \u2713 ${e}: corrected args (${u.join(", ")})${v.reset}`)}if(On()&&!la.has(e))return console.log(`${v.yellow} \u2717 ${e}: blocked in plan mode${v.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let a=Tf(e);if(a==="deny")return console.log(`${v.red} \u2717 ${e}: denied by permissions${v.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(a==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await aa(l,{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 nm(t,e,s={}){let n=await Lf(t,e);if(n!==null)return n;let o=await Of(t,e);return o!==null?o:bf(t,e,s)}function sm(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 Ys(t,e=!1){e||console.log(gf(t.fnName,t.args)),sa("pre-tool",{tool_name:t.fnName});let s=await nm(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
283
|
+
...(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),l=ia(t.fnName,t.args,o,a);return e||(console.log($f(o)),console.log(l)),sa("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:Jf(o),tool_call_id:t.callId},summary:l}}async function om(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],a=null;if(e&&!s.skipSpinner){let c=t.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let d=c[0],f=sm(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=c.map(f=>f.fnName).join(", ");u=`\u23FA ${c.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}a=new gt(u),a.start()}}async function l(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await Ys(t[c],e);n[c]=u,o.push(d)}else{let c=r.map(d=>Ys(t[d],e)),u=await Promise.all(c);for(let d=0;d<r.length;d++)n[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await l(),n[c]=u.errorResult,o.push(ia(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Xf.has(u.fnName))r.push(c);else{await l(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Ys(u,e);n[c]=d,o.push(f)}}if(await l(),a&&a.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return n}var ae=[];function rm(){if(yt!==null)return yt;try{let e=Uf().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Ff(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=`
|
|
258
285
|
# Sub-Agent Model Routing
|
|
259
286
|
|
|
260
|
-
`;
|
|
287
|
+
`;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 |
|
|
261
288
|
|---|---|---|
|
|
262
|
-
`;for(let o of e)
|
|
263
|
-
`;return
|
|
289
|
+
`;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 pa(){let t=await ma();if(Wt!==null&&t===Xs)return Wt;let e=await xf(process.cwd()),s=Sf(),n=qf(),o=On()?Mf():"";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.
|
|
264
291
|
|
|
265
292
|
WORKING DIRECTORY: ${process.cwd()}
|
|
266
293
|
All relative paths resolve from this directory.
|
|
267
294
|
|
|
268
295
|
PROJECT CONTEXT:
|
|
269
296
|
${e}
|
|
270
|
-
${
|
|
271
|
-
${n}
|
|
272
|
-
`:""}${s?`
|
|
297
|
+
${s?`
|
|
273
298
|
${s}
|
|
299
|
+
`:""}${n?`
|
|
300
|
+
${n}
|
|
274
301
|
`:""}${o?`
|
|
275
302
|
${o}
|
|
276
303
|
`:""}
|
|
@@ -332,7 +359,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
332
359
|
- Good for: reading multiple files, analyzing separate modules.
|
|
333
360
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
334
361
|
- Max 5 parallel agents.
|
|
335
|
-
${
|
|
362
|
+
${rm()}
|
|
336
363
|
|
|
337
364
|
# Edit Reliability (Critical)
|
|
338
365
|
|
|
@@ -372,143 +399,190 @@ When a tool call returns ERROR:
|
|
|
372
399
|
- Prefer creating new git commits over amending. Never force-push without explicit permission.
|
|
373
400
|
- If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
|
|
374
401
|
|
|
375
|
-
`,
|
|
376
|
-
${
|
|
377
|
-
${
|
|
378
|
-
${
|
|
379
|
-
`),await u.stream(t,e,{model:m,signal:
|
|
380
|
-
`),await u.chat(t,e,{model:m,...
|
|
381
|
-
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${
|
|
382
|
-
`);process.stdout.write(
|
|
383
|
-
`),m=$.length}t.pause();let g=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function x(){process.stdin.removeListener("keypress",
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
${
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
${
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
${
|
|
422
|
-
${
|
|
423
|
-
${
|
|
424
|
-
${
|
|
425
|
-
|
|
426
|
-
${
|
|
427
|
-
${
|
|
428
|
-
${
|
|
429
|
-
${
|
|
430
|
-
${
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
${
|
|
435
|
-
${
|
|
436
|
-
${
|
|
437
|
-
|
|
438
|
-
${
|
|
439
|
-
${
|
|
440
|
-
${
|
|
441
|
-
${
|
|
442
|
-
|
|
443
|
-
${
|
|
444
|
-
|
|
445
|
-
${
|
|
446
|
-
${
|
|
447
|
-
${
|
|
402
|
+
`,Xs=t,Wt}function im(){ae=[]}function am(){return ae.length}function lm(){return ae}function cm(t){ae=t}function tt(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((l,c)=>l+c,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 l=Date.now()-o,c=Math.round(l/1e3);a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}a+=" \u2500\u2500",console.log(`
|
|
403
|
+
${v.dim} ${a}${v.reset}`),s.size>0?console.log(`${v.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${v.reset}`):n.size>0&&t>=2&&console.log(`${v.dim} \u{1F4A1} /save \xB7 /clear${v.reset}`)}async function um(t){let e=da(t);ae.push({role:"user",content:e});let{setOnChange:s}=gn(),n=null,o=0;s((q,L)=>{q==="create"?(n&&n.stop(),n=new hf(L.name,L.tasks),n.setStats({tokens:o}),n.start()):q==="update"&&n?n.updateTask(L.id,L.status):q==="clear"&&n&&(n.stop(),n=null)});let a=[{role:"system",content:await pa()},...ae],l=new gt("Thinking...");l.start();let c=$t(),{messages:u,compressed:d,compacted:f,tokensRemoved:m}=await kf(a,c),h=_f(a,c);if(l.stop(),f)console.log(`${v.dim} [context compacted \u2014 summary (~${m} tokens freed)]${v.reset}`);else if(d){let q=h.limit>0?Math.round(m/h.limit*100):0;console.log(`${v.dim} [context compressed \u2014 ~${m} tokens freed (${q}%)]${v.reset}`)}h.percentage>85&&console.log(`${v.yellow} \u26A0 Context ${Math.round(h.percentage)}% full \u2014 consider /clear or /save + start fresh${v.reset}`);let g=u,x=0,w=0,$=0,k=0,T=0,b=new Map,S=new Set,_=new Set,C=Date.now(),E,P=Vs,I=0,M=10;e:for(;;){for(E=0;E<P;E++){let U=function(){L||(console.log(`${v.dim} \u2500\u2500 step ${T} \u2500\u2500${v.reset}`),L=!0)};var N=U;if(Rn()?.aborted)break;let L=!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 K=!0,ne="",le=new Nf,we,Gt=Date.now(),xt=!1,Dn=new AbortController,po=setInterval(()=>{let A=Date.now()-Gt;A>=Zf?(le._clearCursorLine(),console.log(`${v.yellow} \u26A0 Stream stale for ${Math.round(A/1e3)}s \u2014 aborting and retrying${v.reset}`),Dn.abort()):A>=Qf&&!xt&&(xt=!0,le._clearCursorLine(),console.log(`${v.yellow} \u26A0 No tokens received for ${Math.round(A/1e3)}s \u2014 waiting...${v.reset}`))},5e3),ve="",nt=null;try{let A=fa($t()),j=On()?A.filter(se=>la.has(se.function.name)):A,st=Rn(),D=new AbortController;st&&st.addEventListener("abort",()=>D.abort(),{once:!0}),Dn.signal.addEventListener("abort",()=>D.abort(),{once:!0}),we=await yf(g,j,{signal:D.signal,onToken:se=>{Gt=Date.now(),xt=!1,ve+=se,process.stdout.isTTY?nt||(nt=setTimeout(()=>{ve&&le&&le.push(ve),ve="",nt=null},50)):(le.push(ve),ve=""),K&&(n&&!n._paused?n.pause():W&&W.stop(),U(),le.startCursor(),K=!1),ne+=se}})}catch(A){if(clearInterval(po),n&&!n._paused&&n.pause(),W&&W.stop(),le.stopCursor(),Dn.signal.aborted&&!Rn()?.aborted){if($++,$>Mn){if(k<1){k++,console.log(`${v.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${v.reset}`);let he=$t(),{messages:kt,tokensRemoved:_t}=Bs(g,he);g=kt,console.log(`${v.dim} [force-compressed \u2014 ~${_t} tokens freed]${v.reset}`),$=0,E--;continue}console.log(`${v.red} \u2717 Stream stale: max retries (${Mn}) exceeded. The model may be overloaded \u2014 try again or switch models.${v.reset}`),n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);break}let D=$===1?3e3:5e3;if($>=2&&k<1){k++,console.log(`${v.yellow} \u26A0 Stale retry ${$}/${Mn} \u2014 force-compressing before retry...${v.reset}`);let he=$t(),{messages:kt,tokensRemoved:_t}=Bs(g,he);g=kt,console.log(`${v.dim} [force-compressed \u2014 ~${_t} tokens freed]${v.reset}`)}else console.log(`${v.yellow} \u26A0 Stale retry ${$}/${Mn} \u2014 retrying in ${D/1e3}s...${v.reset}`);let se=new gt(`Waiting ${D/1e3}s before retry...`);se.start(),await new Promise(he=>setTimeout(he,D)),se.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),tt(T,b,S,_,C),et(ae);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 D=(A.message||"").toLowerCase(),se=D.includes("context")||D.includes("token")||D.includes("length")||D.includes("too long")||D.includes("too many")||D.includes("prompt")||D.includes("size")||D.includes("exceeds")||D.includes("num_ctx")||D.includes("input");if(se&&k<1){k++,console.log(`${v.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${v.reset}`);let he=$t(),{messages:kt,tokensRemoved:_t}=Bs(g,he);g=kt,console.log(`${v.dim} [force-compressed \u2014 ~${_t} tokens freed]${v.reset}`),E--;continue}se?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(`${v.red} \u2717 ${j}${v.reset}`),A.message.includes("429")){if(x++,x>Ks){console.log(`${v.red} Rate limit: max retries (${Ks}) exceeded. Try again later or use /budget to check your limits.${v.reset}`),n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);break}let D=Math.min(1e4*Math.pow(2,x-1),12e4),se=new gt(`Rate limit \u2014 waiting ${Math.round(D/1e3)}s (retry ${x}/${Ks})`);se.start(),await new Promise(he=>setTimeout(he,D)),se.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>Js){console.log(`${v.red} Network error: max retries (${Js}) exceeded. Check your connection and try again.${v.reset}`),n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);break}let D=Math.min(2e3*Math.pow(2,w-1),3e4),se=new gt(`Network error \u2014 retrying in ${Math.round(D/1e3)}s (${w}/${Js})`);se.start(),await new Promise(he=>setTimeout(he,D)),se.stop(),E--;continue}n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);break}if(clearInterval(po),K&&(n&&!n._paused&&n.pause(),W&&W.stop()),nt&&(clearTimeout(nt),nt=null),ve&&le&&(le.push(ve),ve=""),ne&&le.flush(),w=0,$=0,we&&we.usage){let{getActiveProviderName:A,getActiveModelId:j}=oe();jf(A(),j(),we.usage.prompt_tokens||0,we.usage.completion_tokens||0),o+=(we.usage.prompt_tokens||0)+(we.usage.completion_tokens||0),n&&n.setStats({tokens:o})}let{content:Fn,tool_calls:Ue}=we,Un={role:"assistant",content:Fn||""};if(Ue&&Ue.length>0&&(Un.tool_calls=Ue),ae.push(Un),g.push(Un),!Ue||Ue.length===0){let A=(Fn||"").trim().length>0||ne.trim().length>0;if(!A&&T>0&&E<Vs-1){let j={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};g.push(j);continue}if(On()&&A){let j=(Fn||ne||"").trim();Rf(j),em(j),console.log(`
|
|
404
|
+
${v.cyan}${v.bold}Plan ready.${v.reset} ${v.dim}Type ${v.reset}${v.cyan}/plan approve${v.reset}${v.dim} to execute, or ask follow-up questions to refine.${v.reset}`)}n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);return}T++,T>1&&(L=!1);for(let A of Ue){let j=A.function.name;b.set(j,(b.get(j)||0)+1)}let Wn=await Promise.all(Ue.map(A=>tm(A))),ho=n?{skipSpinner:!0,skipSummaries:!0}:{};ho.skipSummaries||U(),n&&n._paused&&n.resume();let go=await om(Wn,!0,ho);for(let A=0;A<Wn.length;A++){let j=Wn[A];if(!j.canExecute)continue;let st=go[A].content,D=!st.startsWith("ERROR")&&!st.includes("CANCELLED");D&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&S.add(j.args.path),D&&j.fnName==="read_file"&&j.args&&j.args.path&&_.add(j.args.path)}for(let A of go)ae.push(A),g.push(A)}if(E>=P){n&&(n.stop(),n=null),s(null),tt(T,b,S,_,C),et(ae);let{getActiveProviderName:q}=oe();if(q()==="ollama"&&I<M){I++,P+=20,console.log(`${v.dim} \u2500\u2500 auto-extending to ${P} turns \u2500\u2500${v.reset}`);continue e}if(console.log(`
|
|
405
|
+
${v.yellow}\u26A0 Max iterations (${P}) reached.${v.reset}`),await aa(" Continue for 20 more turns?")){P+=20;continue e}console.log(`${v.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${v.reset}`)}break e}}ha.exports={processInput:um,clearConversation:im,getConversationLength:am,getConversationMessages:lm,setConversationMessages:cm,setAbortSignalGetter:Gf,setMaxIterations:Hf,invalidateSystemPromptCache:Vf,clearToolFilterCache:Yf,getCachedFilteredTools:fa,buildSystemPrompt:pa,getProjectContextHash:ma,buildUserContent:da}});var oe=O((oh,xa)=>{var{OllamaProvider:dm}=Po(),{OpenAIProvider:fm}=Zo(),{AnthropicProvider:mm}=sr(),{GeminiProvider:pm}=ar(),{LocalProvider:hm}=ur(),{checkBudget:ga}=lt(),$a={top:{ollama:"kimi-k2.5",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"}},ya={};for(let[t,e]of Object.entries($a))for(let s of Object.values(e))ya[s]=t;function qn(t,e){let s=ya[t];return s&&$a[s][e]||t}var Z={},re=null,G=null,bt=[];function pe(){if(Object.keys(Z).length>0)return;wt("ollama",new dm),wt("openai",new fm),wt("anthropic",new mm),wt("gemini",new pm),wt("local",new hm);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Z[t]?(re=t,G=e||Z[t].defaultModel):(re="ollama",G="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(bt=s.split(",").map(n=>n.trim()).filter(Boolean))}function wt(t,e){Z[t]=e}function gm(t){return pe(),Z[t]||null}function Qs(){return pe(),Z[re]||null}function $m(){return pe(),re}function ym(){return pe(),G}function wm(){pe();let t=Qs();if(!t)return{id:G,name:G,provider:re};let e=t.getModel(G);return e?{...e,provider:re}:{id:G,name:G,provider:re}}function wa(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Z[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function bm(t){pe();let{provider:e,model:s}=wa(t);if(e){let o=Z[e];return o&&(o.getModel(s)||e==="local")?(re=e,G=s,Pn(),!0):!1}let n=Qs();if(n&&n.getModel(s))return G=s,Pn(),!0;for(let[o,r]of Object.entries(Z))if(r.getModel(s))return re=o,G=s,Pn(),!0;return!1}function Pn(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=te();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=be();t()}catch{}}function xm(){pe();let t=new Set;for(let e of Object.values(Z))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function km(){return pe(),Object.entries(Z).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===re&&s.id===G}))}))}function _m(){pe();let t=[];for(let[e,s]of Object.entries(Z)){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 vm(t){bt=Array.isArray(t)?t:[]}function Sm(){return[...bt]}function ba(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 Tm(t,e,s={}){pe();let n=[re,...bt.filter(l=>l!==re)],o,r=0,a=0;for(let l=0;l<n.length;l++){let c=n[l],u=Z[c];if(!u||!u.isConfigured())continue;a++;let d=ga(c);if(!d.allowed){r++,o=new Error(`Budget limit reached for ${c}: $${d.spent.toFixed(2)} / $${d.limit.toFixed(2)}`);continue}try{let f=l>0,m=f?qn(G,c):G;return f&&m!==G&&process.stderr.write(` [fallback: ${c}:${m}]
|
|
406
|
+
`),await u.stream(t,e,{model:m,signal:s.signal,...s})}catch(f){if(o=f,ba(f)&&l<n.length-1)continue;throw f}}throw r>0&&r===a?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o||new Error("No configured provider available")}async function Cm(t,e,s={}){if(pe(),s.provider){let l=Z[s.provider];if(!l||!l.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let c={model:s.model||G,...s};try{return await l.chat(t,e,c)}catch(u){if(typeof l.stream=="function")try{return await l.stream(t,e,{...c,onToken:()=>{}})}catch{}throw u}}let n=[re,...bt.filter(l=>l!==re)],o,r=0,a=0;for(let l=0;l<n.length;l++){let c=n[l],u=Z[c];if(!u||!u.isConfigured())continue;a++;let d=ga(c);if(!d.allowed){r++,o=new Error(`Budget limit reached for ${c}: $${d.spent.toFixed(2)} / $${d.limit.toFixed(2)}`);continue}try{let f=l>0,m=f?qn(G,c):G;return f&&m!==G&&process.stderr.write(` [fallback: ${c}:${m}]
|
|
407
|
+
`),await u.chat(t,e,{model:m,...s})}catch(f){let m=l>0?qn(G,c):G;if(typeof u.stream=="function")try{return await u.stream(t,e,{model:m,...s,onToken:()=>{}})}catch{}if(o=f,ba(f)&&l<n.length-1)continue;throw f}}throw r>0&&r===a?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o||new Error("No configured provider available")}function Em(){pe();let t=[];for(let[e,s]of Object.entries(Z))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Am(){for(let t of Object.keys(Z))delete Z[t];re=null,G=null,bt=[]}xa.exports={registerProvider:wt,getProvider:gm,getActiveProvider:Qs,getActiveProviderName:$m,getActiveModelId:ym,getActiveModel:wm,setActiveModel:bm,getModelNames:xm,parseModelSpec:wa,listProviders:km,listAllModels:_m,callStream:Tm,callChat:Cm,getConfiguredProviders:Em,setFallbackChain:vm,getFallbackChain:Sm,resolveModelForProvider:qn,_reset:Am}});var va=O((rh,_a)=>{var{C:z}=Q(),{listProviders:Mm,getActiveProviderName:Rm,getActiveModelId:Nm,setActiveModel:Om}=oe();function ka(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 l=e.findIndex($=>$.isCurrent),c=l>=0?a.indexOf(l):0;c<0&&(c=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=a[c];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
|
|
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(`
|
|
409
|
+
`);process.stdout.write(b+`
|
|
410
|
+
`),m=$.length}t.pause();let g=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function x(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&g!==void 0&&process.stdin.setRawMode(g),t.resume()}function w($,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){c>0&&(c--,h());return}if(k.name==="down"||k.ctrl&&k.name==="n"){c<a.length-1&&(c++,h());return}if(k.name==="return"){let T=e[a[c]];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 Pm(t){let e=Mm(),s=Rm(),n=Nm(),o=[];for(let a of e)if(a.models.length!==0){o.push({label:a.provider,value:null,isHeader:!0});for(let l of a.models){let c=a.provider===s&&l.id===n;o.push({label:` ${l.name} (${a.provider}:${l.id})`,value:`${a.provider}:${l.id}`,isCurrent:c})}}let r=await ka(t,o,{title:"Select Model"});return r?(Om(r),console.log(`${z.green}Switched to ${r}${z.reset}`),!0):(console.log(`${z.dim}Cancelled${z.reset}`),!1)}_a.exports={pickFromList:ka,showModelPicker:Pm}});var eo=O((ah,Aa)=>{var Zs=require("fs"),qm=require("path"),{callChat:Im}=oe(),{remember:Lm,listMemories:ih,recall:jm}=Le(),Sa=4,Dm=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
411
|
+
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
412
|
+
|
|
413
|
+
Return ONLY valid JSON in this exact format:
|
|
414
|
+
{
|
|
415
|
+
"memories": [
|
|
416
|
+
{ "key": "snake_case_key", "value": "concise actionable value" }
|
|
417
|
+
],
|
|
418
|
+
"nex_additions": [
|
|
419
|
+
"- Instruction line to add to project NEX.md"
|
|
420
|
+
],
|
|
421
|
+
"summary": "1-2 sentence description of what was done this session"
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
Focus on extracting:
|
|
425
|
+
1. CORRECTIONS: User corrected the AI ("no, not like that", "always use X", "never do Y", "stop doing Z")
|
|
426
|
+
2. PREFERENCES: Explicit style/tool/workflow preferences stated ("I prefer X", "use Y for Z", "always do W")
|
|
427
|
+
3. PROJECT CONVENTIONS: Discovered project-specific rules, file patterns, naming conventions
|
|
428
|
+
4. TECH STACK FACTS: Specific versions, frameworks, patterns used in this project
|
|
429
|
+
|
|
430
|
+
Rules:
|
|
431
|
+
- ONLY extract HIGH-CONFIDENCE learnings (user was explicit, not guessed)
|
|
432
|
+
- key: snake_case, max 30 chars, unique and descriptive
|
|
433
|
+
- value: concise actionable instruction, max 120 chars
|
|
434
|
+
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
435
|
+
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
436
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Fm(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
|
+
|
|
438
|
+
`)}async function Ta(t){if(t.filter(o=>o.role==="user").length<Sa)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Fm(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:Dm},{role:"user",content:`Conversation to analyze:
|
|
439
|
+
|
|
440
|
+
${s}`}];try{let a=((await Im(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let l=JSON.parse(a[0]);return{memories:Array.isArray(l.memories)?l.memories:[],nex_additions:Array.isArray(l.nex_additions)?l.nex_additions:[],summary:typeof l.summary=="string"?l.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Ca(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=jm(o);a!==r&&(Lm(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Ea(t){if(!t||t.length===0)return[];let e=qm.join(process.cwd(),"NEX.md"),s="";try{Zs.existsSync(e)&&(s=Zs.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 l=a.substring(0,35).toLowerCase();s.toLowerCase().includes(l)||(n.push(a),o=o?o.endsWith(`
|
|
441
|
+
`)?o+a:o+`
|
|
442
|
+
`+a:a)}return n.length>0&&(o.endsWith(`
|
|
443
|
+
`)||(o+=`
|
|
444
|
+
`),Zs.writeFileSync(e,o,"utf-8")),n}async function Um(t){let e=await Ta(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Ca(e.memories),n=Ea(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}Aa.exports={learnFromSession:Um,reflectOnSession:Ta,applyMemories:Ca,applyNexAdditions:Ea,LEARN_MIN_MESSAGES:Sa}});var Na=O((lh,Ra)=>{var Wm=require("axios"),Bt=require("fs"),Ma=require("path"),Bm="nex-code",to=Ma.join(process.cwd(),".nex"),no=Ma.join(to,"last-version-check");Bt.existsSync(to)||Bt.mkdirSync(to,{recursive:!0});async function Hm(){try{let t=zm(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Km(e);let s=Gm(),o=(await Wm.get(`https://registry.npmjs.org/${Bm}/latest`,{timeout:5e3})).data.version,r=Jm(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function Gm(){return zt().version}function zm(){try{if(Bt.existsSync(no)){let t=Bt.readFileSync(no,"utf8");return parseInt(t,10)}}catch{}return null}function Km(t){try{Bt.writeFileSync(no,t.toString())}catch{}}function Jm(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}}Ra.exports={checkForNewVersion:Hm}});var Ka=O((uh,za)=>{var Ym=require("readline"),Fe=require("fs"),_e=require("path"),{C:i,banner:Vm,cleanupTerminal:Oa}=Q(),{listProviders:oo,getActiveProviderName:je,listAllModels:ch,setFallbackChain:Xm,getFallbackChain:Qm,getProvider:Zm}=oe(),{flushAutoSave:Pa}=Ye(),{getActiveModel:De,setActiveModel:qa}=on(),{printContext:Ia}=As(),{loadAllSkills:ep,getSkillCommands:ro,handleSkillCommand:tp}=At(),{setReadlineInterface:np,setAutoConfirm:sp,getAutoConfirm:La}=Se(),Ln=process.cwd(),Oe=null;function ja(){return Oe?.signal??null}var jn=[{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 Da(){let t=ro(),e=[...jn,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of jn)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
|
+
${i.dim}Type /help for detailed usage${i.reset}
|
|
446
|
+
`)}function Fa(t){try{let e,s;t.endsWith("/")||t.endsWith(_e.sep)?(e=t,s=""):(e=_e.dirname(t),s=_e.basename(t)),e.startsWith("~")&&(e=_e.join(require("os").homedir(),e.slice(1)));let n=_e.isAbsolute(e)?e:_e.resolve(Ln,e);if(!Fe.existsSync(n)||!Fe.statSync(n).isDirectory())return[];let o=Fe.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 l=t.endsWith("/")||t.endsWith(_e.sep)?t:_e.dirname(t)+"/",c=l==="./"&&!t.startsWith("./")?a.name:l+a.name;r.push(a.isDirectory()?c+"/":c)}return r}catch{return[]}}function Ua(t){if(t.startsWith("/")){let n=[...jn,...ro()],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("~"))?[Fa(s),s]:[[],t]}function Wa(){console.log(`
|
|
447
|
+
${i.bold}${i.cyan}Commands:${i.reset}
|
|
448
|
+
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
449
|
+
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
450
|
+
${i.cyan}/providers${i.reset} ${i.dim}Show available providers and models${i.reset}
|
|
451
|
+
${i.cyan}/fallback [chain]${i.reset} ${i.dim}Show/set fallback chain (e.g. anthropic,openai,local)${i.reset}
|
|
452
|
+
${i.cyan}/tokens${i.reset} ${i.dim}Show token usage and context budget${i.reset}
|
|
453
|
+
${i.cyan}/costs${i.reset} ${i.dim}Show session token costs${i.reset}
|
|
454
|
+
${i.cyan}/budget [prov] [n]${i.reset}${i.dim}Show/set cost limits per provider${i.reset}
|
|
455
|
+
${i.cyan}/clear${i.reset} ${i.dim}Clear conversation context${i.reset}
|
|
456
|
+
${i.cyan}/context${i.reset} ${i.dim}Show project context${i.reset}
|
|
457
|
+
${i.cyan}/autoconfirm${i.reset} ${i.dim}Toggle auto-confirm for file changes${i.reset}
|
|
458
|
+
|
|
459
|
+
${i.bold}${i.cyan}Sessions:${i.reset}
|
|
460
|
+
${i.cyan}/save [name]${i.reset} ${i.dim}Save current session${i.reset}
|
|
461
|
+
${i.cyan}/load <name>${i.reset} ${i.dim}Load a saved session${i.reset}
|
|
462
|
+
${i.cyan}/sessions${i.reset} ${i.dim}List all saved sessions${i.reset}
|
|
463
|
+
${i.cyan}/resume${i.reset} ${i.dim}Resume last session${i.reset}
|
|
464
|
+
|
|
465
|
+
${i.bold}${i.cyan}Memory:${i.reset}
|
|
466
|
+
${i.cyan}/remember <text>${i.reset} ${i.dim}Save a memory (key=value or freeform)${i.reset}
|
|
467
|
+
${i.cyan}/forget <key>${i.reset} ${i.dim}Delete a memory${i.reset}
|
|
468
|
+
${i.cyan}/memory${i.reset} ${i.dim}Show all memories${i.reset}
|
|
469
|
+
${i.cyan}/learn${i.reset} ${i.dim}Reflect on this session and auto-update memory + NEX.md${i.reset}
|
|
470
|
+
${i.cyan}/optimize${i.reset} ${i.dim}Show context, memory health, and optimization tips${i.reset}
|
|
471
|
+
|
|
472
|
+
${i.bold}${i.cyan}Permissions:${i.reset}
|
|
473
|
+
${i.cyan}/permissions${i.reset} ${i.dim}Show tool permissions${i.reset}
|
|
474
|
+
${i.cyan}/allow <tool>${i.reset} ${i.dim}Auto-allow a tool${i.reset}
|
|
475
|
+
${i.cyan}/deny <tool>${i.reset} ${i.dim}Block a tool${i.reset}
|
|
476
|
+
|
|
477
|
+
${i.bold}${i.cyan}Planning:${i.reset}
|
|
478
|
+
${i.cyan}/plan [task]${i.reset} ${i.dim}Enter plan mode (analyze, don't execute)${i.reset}
|
|
479
|
+
${i.cyan}/plan status${i.reset} ${i.dim}Show current plan progress${i.reset}
|
|
480
|
+
${i.cyan}/plan approve${i.reset} ${i.dim}Approve current plan${i.reset}
|
|
481
|
+
${i.cyan}/plans${i.reset} ${i.dim}List saved plans${i.reset}
|
|
482
|
+
${i.cyan}/auto [level]${i.reset} ${i.dim}Set autonomy: interactive/semi-auto/autonomous${i.reset}
|
|
483
|
+
|
|
484
|
+
${i.bold}${i.cyan}Git:${i.reset}
|
|
485
|
+
${i.cyan}/commit [msg]${i.reset} ${i.dim}Smart commit (analyze diff, suggest message)${i.reset}
|
|
486
|
+
${i.cyan}/diff${i.reset} ${i.dim}Show current diff summary${i.reset}
|
|
487
|
+
${i.cyan}/branch [name]${i.reset} ${i.dim}Create feature branch${i.reset}
|
|
488
|
+
|
|
489
|
+
${i.bold}${i.cyan}Extensibility:${i.reset}
|
|
490
|
+
${i.cyan}/mcp${i.reset} ${i.dim}Show MCP servers and tools${i.reset}
|
|
491
|
+
${i.cyan}/mcp connect${i.reset} ${i.dim}Connect all configured MCP servers${i.reset}
|
|
492
|
+
${i.cyan}/hooks${i.reset} ${i.dim}Show configured hooks${i.reset}
|
|
493
|
+
${i.cyan}/skills${i.reset} ${i.dim}List loaded skills${i.reset}
|
|
494
|
+
${i.cyan}/skills enable${i.reset} ${i.dim}Enable a skill by name${i.reset}
|
|
495
|
+
${i.cyan}/skills disable${i.reset} ${i.dim}Disable a skill by name${i.reset}
|
|
496
|
+
|
|
497
|
+
${i.bold}${i.cyan}Tasks:${i.reset}
|
|
498
|
+
${i.cyan}/tasks${i.reset} ${i.dim}Show current task list${i.reset}
|
|
499
|
+
${i.cyan}/tasks clear${i.reset} ${i.dim}Clear all tasks${i.reset}
|
|
500
|
+
|
|
501
|
+
${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
502
|
+
${i.cyan}/undo${i.reset} ${i.dim}Undo last file change${i.reset}
|
|
503
|
+
${i.cyan}/redo${i.reset} ${i.dim}Redo last undone change${i.reset}
|
|
504
|
+
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
505
|
+
|
|
506
|
+
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
507
|
+
`)}function Ba(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 so(){let t=oo(),e=je(),s=De();console.log(`
|
|
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 l of n.models){let c=l.id===s.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${l.id}${i.reset} \u2014 ${l.name}${c}`)}}console.log()}async function Ha(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return Wa(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=va();await r(e)}else{let r=De(),a=je();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 so(),!0;if(qa(o)){let r=De(),a=je();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 so(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let a=Qm();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 Xm(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=te(),{getUsage:r}=be(),{TOOL_DEFINITIONS:a}=ze(),l=o(),c=r(l,a),u=De(),d=je();console.log(`
|
|
509
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(c.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${c.used.toLocaleString()} / ${c.limit.toLocaleString()} (${c.percentage}%)`);let f=Ba(c.percentage);return console.log(` ${f}`),console.log(`
|
|
510
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${c.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${c.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${c.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${c.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${c.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=lt();return n.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
448
511
|
${o()}
|
|
449
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:
|
|
450
|
-
${
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
${a.
|
|
454
|
-
${a.cyan}${a.
|
|
455
|
-
${a.cyan}${a.
|
|
456
|
-
${
|
|
457
|
-
|
|
458
|
-
${
|
|
459
|
-
${
|
|
460
|
-
|
|
512
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:l,saveCostLimits:c,setCostLimit:u}=lt(),d=n[0];if(!d){let h=o(),g=oo();console.log(`
|
|
513
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let x=!1;for(let w of g){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),_=b-S,E=`${T>=100?i.red:T>=80?i.yellow:i.green}${"\u2588".repeat(S)}${i.dim}${"\u2591".repeat(_)}${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 l(d),c(),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),c(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=te(),{clearHistory:a}=ut(),l=r();if(l.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=eo();u(l).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
|
+
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
515
|
+
`)}).catch(()=>process.stdout.write(`
|
|
516
|
+
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await Ia(Ln),!0;case"/autoconfirm":{let o=!La();return sp(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}=Ye(),{getConversationMessages:r}=te(),a=n.join(" ").trim()||`session-${Date.now()}`,l=r();if(l.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let c=De(),u=je();return o(a,l,{model:c.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${l.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:o}=Ye(),{setConversationMessages:r}=te(),a=n.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let l=o(a);return l?(r(l.messages),console.log(`${i.green}Loaded session: ${l.name} (${l.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:o}=Ye(),r=o();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
517
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let l=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",c=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${c} \u2014 ${a.messageCount} msgs, ${l}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=Ye(),{setConversationMessages:r}=te(),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}=Le(),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("="),l,c;return a>0?(l=r.substring(0,a).trim(),c=r.substring(a+1).trim()):(l=r.substring(0,40).replace(/\s+/g,"-"),c=r),o(l,c),console.log(`${i.green}Remembered: ${l}${i.reset}`),!0}case"/forget":{let{forget:o}=Le(),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}=Le(),r=o();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
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}=eo(),{getConversationMessages:r}=te(),a=r(),l=a.filter(c=>c.role==="user").length;if(l<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${l})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let c=await o(a);if(c.skipped)return console.log(`${i.dim}Session too short${i.reset}`),!0;if(c.error)return console.log(`${i.red}Reflection error: ${c.error}${i.reset}`),!0;if(console.log(""),c.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${c.summary}${i.reset}`),console.log("")),c.applied.length===0&&c.nexAdded.length===0)console.log(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(c.applied.length>0){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:u,value:d,action:f}of c.applied){let m=f==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${m} ${i.bold}${u}${i.reset} = ${d}`)}}if(c.nexAdded.length>0){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let u of c.nexAdded)console.log(` ${i.green}+${i.reset} ${u}`)}}console.log("")}catch(c){console.log(`${i.red}Learn failed: ${c.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=te(),{getUsage:r}=be(),{TOOL_DEFINITIONS:a}=ze(),{listMemories:l}=Le(),c=o(),u=r(c,a),d=De(),f=je(),m=l();console.log(`
|
|
519
|
+
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
520
|
+
`);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((_,C)=>new Date(C.updatedAt)-new Date(_.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(`
|
|
522
|
+
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let g=d.contextWindow||d.maxTokens||0;g>0&&g<32e3&&c.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(g/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):g>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(g/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let x=c.filter(k=>k.role==="user").length;console.log(`
|
|
523
|
+
${i.bold}Session:${i.reset} ${x} turns, ${c.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(`
|
|
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:l,getPlanContent:c,formatPlan:u}=ht(),{invalidateSystemPromptCache:d}=te(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){a(),l(!1),d();let m=!!c();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 l(!0),d(),console.log(`
|
|
525
|
+
${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
|
+
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
527
|
+
${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
|
+
${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 l=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${l} ${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(),l=n.join(" ").trim();return l?(r(l)?console.log(`${i.green}Autonomy: ${l}${i.reset}`):console.log(`${i.red}Unknown level: ${l}. 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(`
|
|
530
|
+
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let l=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${l} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
531
|
+
${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:l}=Ge(),{confirm:c}=Se();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=n.join(" ").trim();if(u){let g=await r(u);return console.log(g?`${i.green}Committed: ${g} \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 l();if(console.log(f),!await c(" 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}=Ge();return o()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=Ge(),{processInput:a}=te(),l=n.join(" ").trim(),c;if(l)c=`Do a thorough code review of \`${l}\`. 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;c=`Review the following code diff for bugs, security issues, code quality, and improvements. Format findings by severity (critical, warning, suggestion):
|
|
461
533
|
|
|
462
534
|
\`\`\`diff
|
|
463
535
|
${f.substring(0,2e4)}
|
|
464
|
-
\`\`\``}return await
|
|
465
|
-
${
|
|
466
|
-
${
|
|
467
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
468
|
-
${
|
|
469
|
-
${
|
|
470
|
-
${
|
|
471
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
536
|
+
\`\`\``}return await a(c),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:a}=Ge();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let l=n.join(" ").trim();if(!l){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let c=a(l);return console.log(c?`${i.green}Created and switched to: ${c}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:a}=un(),l=n.join(" ").trim();if(l==="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(l==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let c=o();if(c.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(`
|
|
537
|
+
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of c){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
|
+
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
539
|
+
`),!0}case"/hooks":{let{listHooks:o}=Ws(),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(`
|
|
540
|
+
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let l of a.commands)console.log(` ${i.dim}\u2192 ${l}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:a}=At(),l=n.join(" ").trim();if(l.startsWith("enable ")){let u=l.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(l.startsWith("disable ")){let u=l.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 c=o();if(c.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(`
|
|
541
|
+
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of c){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
|
+
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
543
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=gn();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
472
544
|
`+o()+`
|
|
473
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
474
|
-
${
|
|
475
|
-
`);for(let
|
|
476
|
-
${
|
|
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 l=r();return l>0&&console.log(`${i.dim}${l} 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 l=r();return l>0&&console.log(`${i.dim}${l} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:a}=ut(),l=o(20);if(l.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
546
|
+
${i.bold}File Change History${i.reset}
|
|
547
|
+
`);for(let c of l){let u=new Date(c.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${c.tool}${i.reset} ${c.filePath}`)}return console.log(`
|
|
548
|
+
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
477
549
|
`),!0}case"/exit":case"/quit":console.log(`
|
|
478
|
-
${
|
|
479
|
-
`).filter(Boolean).slice(-
|
|
480
|
-
`)}catch{}}function ye(){let{isPlanMode:t,getAutonomyLevel:e}=
|
|
481
|
-
`),!0):!1)(),
|
|
482
|
-
${
|
|
483
|
-
`),process.exit(1)),
|
|
484
|
-
`),await
|
|
485
|
-
${
|
|
486
|
-
${
|
|
487
|
-
${
|
|
488
|
-
`),m.setPrompt(ye()),m.prompt(),
|
|
489
|
-
`).trim();if(
|
|
490
|
-
`),
|
|
491
|
-
${
|
|
492
|
-
`)),S()}if(U){k=!0,
|
|
493
|
-
`)),!0}if(W){let
|
|
494
|
-
`)),S()}if(k){let
|
|
495
|
-
`)),!0}return M.call(process.stdin,N,...
|
|
496
|
-
\x1B[2K ${
|
|
497
|
-
\x1B[2K ${
|
|
498
|
-
`).trim();if(P=null,U){
|
|
499
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
500
|
-
`).trim();if(P=null,U){
|
|
501
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
502
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
503
|
-
${
|
|
550
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return tp(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var io=1e3;function ao(){return _e.join(process.cwd(),".nex","repl_history")}function Ga(){try{let t=ao();if(Fe.existsSync(t))return Fe.readFileSync(t,"utf-8").split(`
|
|
551
|
+
`).filter(Boolean).slice(-io)}catch{}return[]}function In(t){try{let e=ao(),s=_e.dirname(e);Fe.existsSync(s)||Fe.mkdirSync(s,{recursive:!0}),Fe.appendFileSync(e,t+`
|
|
552
|
+
`)}catch{}}function ye(){let{isPlanMode:t,getAutonomyLevel:e}=ht(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=je(),r=De();return s.push(`${o}:${r.id}`),`${s.length>0?`${i.dim}[${s.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var lo="\x1B[200~",co="\x1B[201~";function op(t){return typeof t=="string"&&t.includes(lo)}function rp(t){return typeof t=="string"&&t.includes(co)}function Ht(t){return typeof t!="string"?t:t.split(lo).join("").split(co).join("")}async function ip(){if(!Zm("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"),qa("local:llama3"),!0}catch{return!1}}async function ap(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=te();t(ja);let o=oo().some(M=>M.configured),r=(async()=>{ep();let M=De(),N=je();return{model:M,providerName:N}})(),a=(async()=>o?!0:await ip()?(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}
|
|
553
|
+
`),!0):!1)(),l=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:M}=Na();return await M()}catch{return{hasNewVersion:!1}}})(),[c,u,d]=await Promise.all([r,a,l]);!u&&!o&&(console.error(`
|
|
554
|
+
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
555
|
+
`),process.exit(1)),Vm(`${c.providerName}:${c.model.id}`,Ln,{yolo:La()}),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}
|
|
556
|
+
`),await Ia(Ln);let f=Ga(),m=Ym.createInterface({input:process.stdin,output:process.stdout,prompt:ye(),completer:Ua,history:f,historySize:io});np(m);let h=!1,g=0,x=!1,w=null;function $(){Pa(),Oa(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
557
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",$),process.on("exit",()=>{Pa()}),m.on("SIGINT",()=>{if(Oa(),h){if(g++,g>=2){$();return}Oe&&Oe.abort(),console.log(`
|
|
558
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(ye()),m.prompt();return}x?$():(x=!0,process.stdout.write(`
|
|
559
|
+
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
560
|
+
`),m.setPrompt(ye()),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
|
+
`).trim();if(T=[],k=!1,!M)return!0;b=M;let N=M.split(`
|
|
562
|
+
`),q=N.length,L=N[0].length>80?N[0].substring(0,77)+"...":N[0],U=q>1?`[Pasted content \u2014 ${q} lines]`:"[Pasted content]";return console.log(`
|
|
563
|
+
${i.dim} ${U}${i.reset}`),console.log(`${i.dim} \u23BF ${L}${i.reset}`),q>1&&console.log(`${i.dim} \u23BF \u2026 +${q-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,...q){if(N!=="data")return M.call(process.stdin,N,...q);let L=q[0];if(Buffer.isBuffer(L)&&(L=L.toString("utf8")),typeof L!="string")return M.call(process.stdin,N,...q);let U=L.includes(lo),W=L.includes(co);if(U&&W){let K=Ht(L);return K&&T.push(...K.split(`
|
|
564
|
+
`)),S()}if(U){k=!0,T=[];let K=Ht(L);return K&&T.push(...K.split(`
|
|
565
|
+
`)),!0}if(W){let K=Ht(L);return K&&T.push(...K.split(`
|
|
566
|
+
`)),S()}if(k){let K=Ht(L);return K&&T.push(...K.split(`
|
|
567
|
+
`)),!0}return M.call(process.stdin,N,...q)}}let _=0;function C(){if(_>0){let M="";for(let N=0;N<_;N++)M+="\x1B[1B\x1B[2K";M+=`\x1B[${_}A`,process.stdout.write(M),_=0}}function E(M){let N=[...jn,...ro()].filter(ne=>ne.cmd.startsWith(M));if(!N.length||N.length===1&&N[0].cmd===M)return;let q=10,L=N.slice(0,q),U=Math.max(...L.map(ne=>ne.cmd.length)),W="";for(let{cmd:ne,desc:le}of L){let we=ne.substring(0,M.length),Gt=ne.substring(M.length),xt=" ".repeat(Math.max(0,U-ne.length+2));W+=`
|
|
568
|
+
\x1B[2K ${i.cyan}${we}${i.reset}${i.dim}${Gt}${xt}${le}${i.reset}`}_=L.length,N.length>q&&(W+=`
|
|
569
|
+
\x1B[2K ${i.dim}\u2026 +${N.length-q} more${i.reset}`,_++);let K=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;W+=`\x1B[${_}A\x1B[${K+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,I=`${i.dim}...${i.reset} `;m.setPrompt(ye()),m.prompt(),m.on("line",async M=>{if(C(),h){b=null;return}if(b!==null&&(M=b,b=null),P!==null){if(P._mode==="triple"){if(M.trim()==='"""'){let U=P.join(`
|
|
570
|
+
`).trim();if(P=null,U){In(U.replace(/\n/g,"\\n")),h=!0,g=0,x=!1,w&&(clearTimeout(w),w=null),Oe=new AbortController;try{await s(U)}catch(K){if(!Oe?.signal?.aborted){let ne=K.message?.split(`
|
|
571
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${ne}${i.reset}`)}}h=!1;let W=q();W>0&&process.stdout.write(`${i.gray}[${W} messages] ${i.reset}`)}m.setPrompt(ye()),m.prompt();return}P.push(M),m.setPrompt(I),m.prompt();return}if(M.endsWith("\\"))P.push(M.slice(0,-1));else{P.push(M);let U=P.join(`
|
|
572
|
+
`).trim();if(P=null,U){In(U.replace(/\n/g,"\\n")),h=!0,g=0,x=!1,w&&(clearTimeout(w),w=null),Oe=new AbortController;try{await s(U)}catch(ne){if(!Oe?.signal?.aborted){let le=ne.message?.split(`
|
|
573
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${le}${i.reset}`)}}let{getConversationLength:W}=te();h=!1;let K=W();K>0&&process.stdout.write(`${i.gray}[${K} messages] ${i.reset}`)}m.setPrompt(ye()),m.prompt();return}m.setPrompt(I),m.prompt();return}if(M.trim()==='"""'||M.trim().startsWith('"""')){let U=M.trim().substring(3);P=U?[U]:[],P._mode="triple",m.setPrompt(I),m.prompt();return}if(M.endsWith("\\")){P=[M.slice(0,-1)],P._mode="backslash",m.setPrompt(I),m.prompt();return}let N=M.trim();if(!N){m.setPrompt(ye()),m.prompt();return}if(In(N),N==="/"){Da(),m.setPrompt(ye()),m.prompt();return}if(N.startsWith("/")){await Ha(N,m),m.setPrompt(ye()),m.prompt();return}h=!0,g=0,x=!1,w&&(clearTimeout(w),w=null),Oe=new AbortController;try{await s(N)}catch(U){if(!Oe?.signal?.aborted){let W=U.message?.split(`
|
|
574
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${W}${i.reset}`)}}h=!1;let{getConversationLength:q}=te(),L=q();L>0&&process.stdout.write(`${i.gray}[${L} messages] ${i.reset}`),m.setPrompt(ye()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
575
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}za.exports={startREPL:ap,getPrompt:ye,loadHistory:Ga,appendHistory:In,getHistoryPath:ao,HISTORY_MAX:io,showCommandList:Da,completer:Ua,completeFilePath:Fa,handleSlashCommand:Ha,showProviders:so,showHelp:Wa,renderBar:Ba,hasPasteStart:op,hasPasteEnd:rp,stripPasteSequences:Ht,getAbortSignal:ja}});var Va=require("path");require("dotenv").config({path:Va.join(__dirname,"..",".env")});require("dotenv").config();var V=process.argv.slice(2);(V.includes("--help")||V.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
504
576
|
|
|
505
577
|
Options:
|
|
506
|
-
--task <prompt>
|
|
507
|
-
--
|
|
508
|
-
--
|
|
509
|
-
--
|
|
510
|
-
--
|
|
511
|
-
--
|
|
512
|
-
-
|
|
513
|
-
|
|
514
|
-
|
|
578
|
+
--task <prompt> Run a single task and exit (headless mode)
|
|
579
|
+
--prompt-file <path> Read prompt from file and run headless (avoids shell escaping)
|
|
580
|
+
--delete-prompt-file Delete the prompt file after reading (use with --prompt-file)
|
|
581
|
+
--auto Skip all confirmations (implies --task / --prompt-file)
|
|
582
|
+
--yolo, -yolo Skip all confirmations (interactive YOLO mode)
|
|
583
|
+
--model <spec> Set model (e.g. openai:gpt-4o)
|
|
584
|
+
--max-turns <n> Max agentic loop iterations (default: 50)
|
|
585
|
+
--json Output result as JSON (for CI parsing)
|
|
586
|
+
-h, --help Show this help
|
|
587
|
+
-v, --version Show version
|
|
588
|
+
`),process.exit(0));if(V.includes("-v")||V.includes("--version")){let t=zt();console.log(t.version),process.exit(0)}var lp=V.includes("--yolo")||V.includes("-yolo");if(lp){let{setAutoConfirm:t}=Se();t(!0)}var uo=V.indexOf("--model");if(uo!==-1&&V[uo+1]){let{setActiveModel:t}=oe();t(V[uo+1])}var fo=V.indexOf("--max-turns");if(fo!==-1&&V[fo+1]){let t=parseInt(V[fo+1],10);if(t>0){let{setMaxIterations:e}=te();e(t)}}else try{let t=require("fs"),e=Va.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}=te();o(n)}}}catch{}function mo(){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 Ja(t){if(V.includes("--auto")){let{setAutoConfirm:o}=Se();o(!0)}if(!V.includes("--model")){let{setActiveModel:o}=oe(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=te();s(t).then(()=>{if(V.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=>{V.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var Ya=V.indexOf("--prompt-file");if(Ya!==-1){let t=V[Ya+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)),V.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}mo(),Ja(s)}else{let t=V.indexOf("--task");if(t!==-1){let e=V[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),mo(),Ja(e)}else{mo();let{startREPL:e}=Ka();e()}}
|