nex-code 0.3.13 → 0.3.18
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 +104 -14
- package/dist/nex-code.js +355 -275
- package/package.json +24 -8
package/dist/nex-code.js
CHANGED
|
@@ -1,120 +1,125 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
2
|
+
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Kt=O((ip,Ya)=>{Ya.exports={name:"nex-code",version:"0.3.18",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 wo=O((ap,yo)=>{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"},ho=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],go=["\u273D","\u2726","\u2727","\u2726"],Un=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=ho[this.frame%ho.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}},$o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Wn=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=$o[this.frame%$o.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
3
|
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
5
|
-
`}process.stderr.write(n)}},
|
|
6
|
-
`;for(let l=0;l<this.tasks.length;l++){let c=this.tasks[l],u=l===0?"\u23BF":" ",d=
|
|
7
|
-
`}
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${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)}},Jt={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Yt={done:R.green,in_progress:R.cyan,pending:R.dim,failed:R.red},Pe=null,Bn=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=go[this.frame%go.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=Jt[c.status]||Jt.pending,f=Yt[c.status]||Yt.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
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`,
|
|
11
|
-
`;for(let l=0;l<this.tasks.length;l++){let c=this.tasks[l],u=l===0?"\u23BF":" ",d=
|
|
12
|
-
`}process.stderr.write(
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(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=Jt[c.status]||Jt.pending,f=Yt[c.status]||Yt.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 Va(t){Pe=t}function Xa(){return Pe}function Qa(){Pe&&(Pe.stop(),Pe=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}yo.exports={C:R,Spinner:Un,MultiProgress:Wn,TaskProgress:Bn,setActiveTaskProgress:Va,getActiveTaskProgress:Xa,cleanupTerminal:Qa}});var xo=O((lp,bo)=>{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 Za(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 el(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
14
|
`);return o>0&&(l+=`
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80);return` ${
|
|
17
|
-
`).filter(Boolean),l=
|
|
18
|
-
`).length;r=`Wrote ${
|
|
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
|
|
20
|
-
`).filter(Boolean).length;r=`${
|
|
21
|
-
`).filter(Boolean).length;r=`${
|
|
22
|
-
`).filter(Boolean).length;r=`${
|
|
23
|
-
`).filter(c=>/^\s*[MADRCU?!]/.test(c)).length;r=
|
|
24
|
-
`).filter(l=>/^commit\s+[0-9a-f]{7}/.test(l)).length;r=
|
|
25
|
-
|
|
26
|
-
`).filter(Boolean).length;r=`${
|
|
27
|
-
`),u=s.yolo?` ${n}${
|
|
15
|
+
${ee.gray} \u2026+${o} more lines${ee.reset}`),l}function tl(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 nl(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}`}bo.exports={C:ee,formatToolCall:Za,formatResult:el,getToolSpinnerText:tl,formatToolSummary:nl}});var Q=O((cp,ko)=>{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 sl(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+ot.reset}function ol(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 rl(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 sl(d,ol(l,m))}).join(`
|
|
27
|
+
`),u=s.yolo?` ${n}${ot.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
28
28
|
${c}
|
|
29
|
-
${o}Agentic Coding CLI v${
|
|
29
|
+
${o}Agentic Coding CLI v${Kt().version}${r}
|
|
30
30
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
31
|
-
`)}var{Spinner:
|
|
32
|
-
`);
|
|
31
|
+
`)}var{Spinner:il,MultiProgress:al,TaskProgress:ll,setActiveTaskProgress:cl,getActiveTaskProgress:ul,cleanupTerminal:dl}=wo(),{formatToolCall:fl,formatResult:ml,getToolSpinnerText:pl,formatToolSummary:hl}=xo();ko.exports={C:ot,banner:rl,Spinner:il,MultiProgress:al,TaskProgress:ll,setActiveTaskProgress:cl,getActiveTaskProgress:ul,cleanupTerminal:dl,formatToolCall:fl,formatResult:ml,getToolSpinnerText:pl,formatToolSummary:hl}});var Se=O((up,Eo)=>{var gl=require("readline"),{C:Vt}=Q(),_o=[/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/],Hn=[/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 vo(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)):Hn.some(c=>c.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:Hn.some(l=>l.test(a))};return n.every(o)}var zn=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],So=[/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/],To=[...zn,...So],Kn=!1,Gn=null;function $l(t){Kn=t}function yl(){return Kn}function wl(t){Gn=t}function bl(t){for(let e of _o)if(e.test(t))return e;return null}function xl(t){if(/ssh\s/.test(t)&&vo(t))return!1;for(let e of To)if(e.test(t))return!0;return!1}function kl(t){for(let e of zn)if(e.test(t))return!0;return!1}function _l(t,e={}){if(Kn)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?(Co(e.toolName),n(!0)):n(a!=="n")};if(Gn)Gn.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,o);else{let r=gl.createInterface({input:process.stdin,output:process.stdout});r.question(`${Vt.yellow}${t} ${s}${Vt.reset}`,a=>{r.close(),o(a)})}})}var Co=()=>{};function vl(t){Co=t}Eo.exports={FORBIDDEN_PATTERNS:_o,SSH_SAFE_PATTERNS:Hn,isSSHReadOnly:vo,DANGEROUS_BASH:To,CRITICAL_BASH:zn,NOTABLE_BASH:So,isForbidden:bl,isDangerous:xl,isCritical:kl,confirm:_l,setAutoConfirm:$l,getAutoConfirm:yl,setReadlineInterface:wl,setAllowAlwaysHandler:vl}});var rt=O((dp,Ao)=>{var Jn=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`)}};Ao.exports={BaseProvider:Jn}});var No=O((fp,Ro)=>{var Xt=require("axios"),{BaseProvider:Sl}=rt(),Mo={"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}},Yn=class extends Sl{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Mo,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Xt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders()}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Xt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders()})).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 Xt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders()});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 Xt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}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||{}}}))}};Ro.exports={OllamaProvider:Yn,OLLAMA_MODELS:Mo}});var jo=O((mp,Lo)=>{var{callChat:Tl}=oe(),{estimateTokens:Vn}=be(),Oo=process.env.NEX_COMPACTION!=="false",Po=6,qo=500,Cl=`Summarize this conversation history concisely. Focus on:
|
|
33
34
|
- What files were read, created, or modified
|
|
34
35
|
- Key decisions made and their rationale
|
|
35
36
|
- Current state of the task (what's done, what's pending)
|
|
36
37
|
- Any errors encountered and how they were resolved
|
|
37
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
38
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function
|
|
38
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function El(t){if(!Oo||t.length<Po)return null;let e=[{role:"system",content:Cl},{role:"user",content:Io(t)}];try{let n=((await Tl(e,[],{temperature:0,maxTokens:qo})).content||"").trim();if(!n)return null;let o=t.reduce((a,l)=>a+Vn(l.content||"")+(l.tool_calls?Vn(JSON.stringify(l.tool_calls)):0),0),r=Vn(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 Io(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}
|
|
39
40
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
40
41
|
|
|
41
|
-
`)}
|
|
42
|
-
`);if(o.length<=10){let g=Math.floor(n*.6),x=Math.floor(n*.4),
|
|
42
|
+
`)}Lo.exports={compactMessages:El,formatMessagesForSummary:Io,COMPACTION_ENABLED:Oo,COMPACTION_MIN_MESSAGES:Po,COMPACTION_SUMMARY_BUDGET:qo}});var be=O((pp,Ko)=>{function Uo(){return oe().getActiveModel()}var Al={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},vt=new Map,Do=1e3,Qt=new WeakMap,it=new Map,Fo=500,St=null;function Ml(){if(St!==null)return St;try{let e=Uo()?.provider||"ollama";return St=Al[e]||4,St}catch{return 4}}function Rl(){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/Ml());if(vt.size>=Do){let o=Do>>1,r=vt.keys();for(let a=0;a<o;a++)vt.delete(r.next().value)}return vt.set(e,n),n}function Nl(t){if(Qt.has(t))return Qt.get(t);let e=Wo(t);if(it.has(e)){let n=it.get(e);return Qt.set(t,n),n}let s=JSON.stringify(t);if(it.size>=Fo){let n=Fo>>1,o=it.keys();for(let r=0;r<n;r++)it.delete(o.next().value)}return it.set(e,s),Qt.set(t,s),s}function Wo(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 Ol(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 Zt(t){return!t||t.length===0?0:Be(JSON.stringify(t))}function en(){return Uo()?.contextWindow||32768}function Pl(t,e){let s=ge(t),n=Zt(e),o=s+n,r=en(),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 Bo=.75,Ho=.1,Go=10,ql=200,Il=500;function zo(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+`
|
|
43
44
|
...(${t.length} chars total)...
|
|
44
|
-
|
|
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(`
|
|
45
46
|
`)+`
|
|
46
|
-
...(${
|
|
47
|
+
...(${h} lines omitted, ${o.length} total)...
|
|
47
48
|
`+d.join(`
|
|
48
|
-
`)}function
|
|
49
|
-
...(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
|
|
50
|
-
`),r=Math.floor(n*.6),
|
|
51
|
-
`:"")+
|
|
52
|
-
`:"")+u;if(g.length>
|
|
49
|
+
`)}function Tt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Il,n=e==="aggressive"?50:e==="medium"?100:ql;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:zo(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 Ll(t,e,s={}){let n=s.threshold??Bo,o=s.safetyMargin??Ho,r=s.keepRecent??Go,a=en(),l=Zt(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}=jo(),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 jl(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=`
|
|
53
54
|
|
|
54
55
|
... (${o.length-c-d} lines omitted, ${o.length} total) ...
|
|
55
56
|
|
|
56
|
-
`;return l+m+u}var
|
|
57
|
-
`);x
|
|
58
|
-
|
|
59
|
-
`:"")+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
|
|
60
|
-
`);
|
|
61
|
-
`);x
|
|
62
|
-
`);
|
|
63
|
-
`)
|
|
64
|
-
`)}function
|
|
65
|
-
`)
|
|
57
|
+
`;return l+m+u}var Dl=6;function Fl(t,e){let s=en(),n=Zt(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-Dl),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}}Ko.exports={estimateTokens:Be,estimateMessageTokens:at,estimateMessagesTokens:ge,estimateDeltaTokens:Ol,estimateToolsTokens:Zt,serializeMessage:Nl,getMessageCacheKey:Wo,getContextWindow:en,getUsage:Pl,compressMessage:Tt,compressToolResult:zo,fitToContext:Ll,forceCompress:Fl,truncateFileContent:jl,invalidateTokenRatioCache:Rl,COMPRESSION_THRESHOLD:Bo,SAFETY_MARGIN:Ho,KEEP_RECENT:Go}});var Xo=O((gp,Vo)=>{var Jo=require("axios"),{BaseProvider:Ul}=rt(),{serializeMessage:hp}=be(),Yo={"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}},Xn=class extends Ul{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Yo,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 Jo.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 Jo.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}}))}};Vo.exports={OpenAIProvider:Xn,OPENAI_MODELS:Yo}});var tr=O((yp,er)=>{var Qo=require("axios"),{BaseProvider:Wl}=rt(),{serializeMessage:$p}=be(),Zo={"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}},Bl="2023-06-01",Qn=class extends Wl{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Zo,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Bl}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 Qo.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 Qo.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}}})}};er.exports={AnthropicProvider:Qn,ANTHROPIC_MODELS:Zo}});var rr=O((bp,or)=>{var nr=require("axios"),{BaseProvider:Hl}=rt(),{serializeMessage:wp}=be(),sr={"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}},Zn=class extends Hl{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||sr,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 nr.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 nr.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}}))}};or.exports={GeminiProvider:Zn,GEMINI_MODELS:sr}});var lr=O((xp,ar)=>{var tn=require("axios"),{BaseProvider:Gl}=rt(),ir="http://localhost:11434",es=class extends Gl{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ir,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 tn.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 tn.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 tn.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 tn.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||{}}}))}};ar.exports={LocalProvider:es,DEFAULT_LOCAL_URL:ir}});var lt=O((kp,hr)=>{var He=require("fs"),ts=require("path"),cr={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:{}},nn=[],qe={};function zl(t,e,s,n){if(nn.push({provider:t,model:e,input:s,output:n}),qe[t]!==void 0){let o=mr(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 ns(t,e){let s=cr[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ur(t){let e=ns(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function dr(){let t={};for(let r of nn){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:ur(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 Kl(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=dr();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 Jl(t,e,s,n){let o=ns(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Yl(){nn=[]}function Vl(t,e){qe[t]=e}function Xl(t){delete qe[t]}function Ql(){return{...qe}}function fr(t){let e=0;for(let s of nn)s.provider===t&&(e+=ur(s));return e}function mr(t){let e=fr(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 pr(){let t=ts.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 Zl(){let t=ts.join(process.cwd(),".nex"),e=ts.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 ec(){qe={}}pr();hr.exports={PRICING:cr,trackUsage:zl,getSessionCosts:dr,formatCosts:Kl,formatCostHint:Jl,resetCosts:Yl,getPricing:ns,setCostLimit:Vl,removeCostLimit:Xl,getCostLimits:Ql,getProviderSpend:fr,checkBudget:mr,loadCostLimits:pr,saveCostLimits:Zl,resetCostLimits:ec}});var sn=O((_p,gr)=>{var Ct=oe(),tc={"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 nc(){return Ct.getActiveModel()}function sc(t){return Ct.setActiveModel(t)}function oc(){return Ct.getModelNames()}function rc(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 ic(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 ac(t,e){return Ct.callChat(t,e)}gr.exports={MODELS:tc,getActiveModel:nc,setActiveModel:sc,getModelNames:oc,callOllamaStream:ic,callOllama:ac,parseToolArgs:rc}});var wr=O((vp,yr)=>{var on=require("path"),{C:y}=Q(),{confirm:lc,getAutoConfirm:cc}=Se(),$r=2e3;function Et(t,e){let s=t.split(`
|
|
66
68
|
`),n=e.split(`
|
|
67
|
-
`),o=[],r=s.length,
|
|
68
|
-
${
|
|
69
|
-
${
|
|
70
|
-
${
|
|
71
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${
|
|
72
|
-
${
|
|
73
|
-
`)}function
|
|
74
|
-
${
|
|
75
|
-
`);return}let
|
|
69
|
+
`),o=[],r=s.length,a=n.length;if(r>$r||a>$r){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 uc(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 dc(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 fc(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 mc(t){return cc()?!0:lc(` ${t}?`)}function pc(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 hc(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,a=n.annotations||[],l=on.isAbsolute(t)?on.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 gc(t,e,s={}){let n=on.isAbsolute(t)?on.relative(process.cwd(),t):t,o=e.split(`
|
|
76
78
|
`),r=s.annotations||[];console.log(`
|
|
77
|
-
${
|
|
78
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
79
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let
|
|
80
|
-
${
|
|
81
|
-
${
|
|
82
|
-
${
|
|
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()}yr.exports={diffLines:Et,showEditDiff:uc,showWriteDiff:dc,showNewFilePreview:fc,confirmFileChange:mc,showSideBySideDiff:pc,showClaudeDiff:hc,showClaudeNewFile:gc}});var Ge=O((Sp,kr)=>{var br=require("util").promisify(require("child_process").exec),$c=require("util").promisify(require("child_process").execFile),{C:Y}=Q();async function ss(t){try{let{stdout:e}=await br(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function rn(...t){try{let{stdout:e}=await $c("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function yc(){return await ss("git rev-parse --is-inside-work-tree")==="true"}async function wc(){return await ss("git branch --show-current")}async function os(){try{let{stdout:t}=await br("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 an(t=!1){return await ss(`git diff ${t?"--cached":""}`)||""}async function rs(){return(await os()).map(e=>e.file)}async function xr(){let t=await rs();if(t.length===0)return null;let e=await an(),n=await an(!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 bc(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await rn("checkout","-b",s)!==null?s:null}async function xc(t){return await rn("add","-A"),await rn("commit","-m",t)?await rn("rev-parse","--short","HEAD"):null}async function kc(){let t=await xr();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}
|
|
83
85
|
`),e.join(`
|
|
84
|
-
`)}async function
|
|
86
|
+
`)}async function _c(){return(await os()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function vc(){let t=await rs();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 an();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
85
87
|
...(truncated)`:s;e.push(`
|
|
86
88
|
DIFF:
|
|
87
89
|
${n}`)}return e.join(`
|
|
88
|
-
`)}
|
|
90
|
+
`)}kr.exports={isGitRepo:yc,getCurrentBranch:wc,getStatus:os,getDiff:an,getChangedFiles:rs,analyzeDiff:xr,createBranch:bc,commit:xc,formatDiffSummary:kc,getDiffContext:vc,getMergeConflicts:_c}});var ut=O((Tp,_r)=>{var is=require("fs").promises,Sc=50,Te=[],ct=[];function Tc(t,e,s,n){for(Te.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Te.length>Sc;)Te.shift();ct.length=0}async function Cc(){if(Te.length===0)return null;let t=Te.pop();if(t.oldContent===null)try{await is.unlink(t.filePath)}catch{}else await is.writeFile(t.filePath,t.oldContent,"utf-8");return ct.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Ec(){if(ct.length===0)return null;let t=ct.pop();return await is.writeFile(t.filePath,t.newContent,"utf-8"),Te.push(t),{tool:t.tool,filePath:t.filePath}}function Ac(t=10){return Te.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Mc(){return Te.length}function Rc(){return ct.length}function Nc(){Te.length=0,ct.length=0}_r.exports={recordChange:Tc,undo:Cc,redo:Ec,getHistory:Ac,getUndoCount:Mc,getRedoCount:Rc,clearHistory:Nc}});var At=O((Cp,Ar)=>{var fe=require("fs"),dt=require("path"),ce=[];function as(){return dt.join(process.cwd(),".nex","skills")}function vr(){return dt.join(process.cwd(),".nex","config.json")}function Oc(){let t=as();return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function ls(){let t=vr();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 Sr(t){let e=vr(),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 Tr(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 Cr(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 Er(t){try{let e=require(t),{valid:s,errors:n}=Tr(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}
|
|
89
91
|
${n.join(`
|
|
90
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
92
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Pc(){ce=[];let t=as();if(!fe.existsSync(t))return ce;let e=ls(),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=Cr(o):n.endsWith(".js")&&(a=Er(o)),a&&(a.enabled=!e.includes(a.name),ce.push(a))}return ce}function qc(){let t=[];for(let e of ce)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
91
93
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
92
94
|
${t.join(`
|
|
93
95
|
|
|
94
|
-
`)}`}function
|
|
95
|
-
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){c+=m.toString();let
|
|
96
|
-
`);for(let g of
|
|
97
|
-
`):JSON.stringify(o)}function
|
|
98
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),
|
|
99
|
-
`+
|
|
96
|
+
`)}`}function Ic(){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 Lc(){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 jc(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 Dc(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 Fc(){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 Uc(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=ls().filter(n=>n!==t);return Sr(s),!0}function Wc(t){let e=ce.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=ls();return s.includes(t)||(s.push(t),Sr(s)),!0}function Bc(){return ce}Ar.exports={initSkillsDir:Oc,loadAllSkills:Pc,getSkillInstructions:qc,getSkillCommands:Ic,getSkillToolDefinitions:Lc,routeSkillCall:jc,handleSkillCommand:Dc,listSkills:Fc,enableSkill:Uc,disableSkill:Wc,getLoadedSkills:Bc,_getSkillsDir:as,_validateScriptSkill:Tr,_loadMarkdownSkill:Cr,_loadScriptSkill:Er}});var cn=O((Ep,qr)=>{var{spawn:Hc}=require("child_process"),Gc=require("path"),Mr=require("fs"),Ce=new Map;function zc(){return Gc.join(process.cwd(),".nex","config.json")}function cs(){let t=zc();if(!Mr.existsSync(t))return{};try{return JSON.parse(Mr.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ln(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 Rr(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=Hc(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await ln(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await ln(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 Nr(t){let e=Ce.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ce.delete(t),!0}function Kc(){for(let[t]of Ce)Nr(t)}async function Or(t,e,s={}){let n=Ce.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await ln(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 Pr(){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 Jc(){return Pr().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Yc(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 Or(n,o,e)}function Vc(){let t=cs();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 Xc(){let t=cs(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Rr(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}qr.exports={loadMCPConfig:cs,sendRequest:ln,connectServer:Rr,disconnectServer:Nr,disconnectAll:Kc,callTool:Or,getAllTools:Pr,getMCPToolDefinitions:Jc,routeMCPCall:Yc,listServers:Vc,connectAll:Xc}});var us=O((Ap,Dr)=>{var{getSkillToolDefinitions:Qc}=At(),{getMCPToolDefinitions:Zc}=cn(),un=new Map;function Ir(){let{TOOL_DEFINITIONS:t}=ze();return[...t,...Qc(),...Zc()]}function Lr(t){if(un.has(t))return un.get(t);let s=Ir().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return un.set(t,n),n}function eu(){un.clear()}function dn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=jr(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function jr(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 tu(t,e){let s=Lr(t);if(s===null){let d=Ir().map(m=>m.function.name),f=dn(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=dn(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=dn(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(`
|
|
100
102
|
`)+`
|
|
101
103
|
|
|
102
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?l:null}}
|
|
104
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?l:null}}Dr.exports={validateToolArgs:tu,closestMatch:dn,levenshtein:jr,getCachedSchema:Lr,clearSchemaCache:eu}});var Br=O((Mp,Wr)=>{var{levenshtein:fn}=us(),nu=200,su=.3,ou=2;function ds(t){return t.replace(/\r\n/g,`
|
|
103
105
|
`).replace(/\r/g,`
|
|
104
|
-
`).replace(/\t/g," ".repeat(
|
|
106
|
+
`).replace(/\t/g," ".repeat(ou)).split(`
|
|
105
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(`
|
|
106
|
-
`)}function
|
|
108
|
+
`)}function ru(t,e){if(t.includes(e))return e;let s=ds(t),n=ds(e);if(!s.includes(n))return null;let o=t.split(`
|
|
107
109
|
`),r=s.split(`
|
|
108
|
-
`),
|
|
109
|
-
`),l=
|
|
110
|
-
`)}if(
|
|
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 iu(t,e){if(!t||!e)return null;let s=t.split(`
|
|
111
113
|
`),o=e.split(`
|
|
112
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
113
|
-
`),u=
|
|
114
|
-
`),
|
|
115
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let
|
|
116
|
-
`).filter(Boolean),
|
|
117
|
-
|
|
114
|
+
`).length;return s.length===0||o===0?null:o===1?au(s,e):cu(s,e,o)}function Fr(t){return Math.max(1,Math.floor(t/nu))}function Ur(t,e){return t<=Math.ceil(e*su)}function au(t,e){let s=e.trim(),n=Fr(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=fn(l.trim(),s);c<r&&(r=c,o={text:l,distance:c,line:a+1})}return o&&n>1&&(o=lu(t,s,o,n)||o,r=o.distance),Ur(r,e.length)?o:null}function lu(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=fn(d.trim(),e);f<l&&(l=f,c={text:d,distance:f,line:u+1})}return c}function cu(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Fr(n),r=null,a=1/0;for(let l=0;l<n;l+=o){let c=t.slice(l,l+s).join(`
|
|
115
|
+
`),u=fn(c,e);u<a&&(a=u,r={text:c,distance:u,line:l+1})}return r&&o>1&&(r=uu(t,e,r,o,s,n)||r,a=r.distance),Ur(a,e.length)?r:null}function uu(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=fn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Wr.exports={normalizeWhitespace:ds,fuzzyFindText:ru,findMostSimilar:iu}});var Gr=O((Np,Hr)=>{var{C:Rp}=Q(),du=[{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}],fu=[{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 mu(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 du)c.regex.test(a)&&n.push({line:l,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of fu)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}Hr.exports={runDiagnostics:mu}});var ps=O((Op,Jr)=>{var pu=require("fs").promises,zr=require("path"),{exec:hu}=require("util").promisify(require("child_process").exec),ft=[],ms=null,mn=!1,fs=0,gu=6e4;function Kr(t){return!(ft.length===0||ms!==t||Date.now()-fs>gu)}async function $u(t){if(!mn&&!Kr(t)){mn=!0,ms=t;try{try{let{stdout:n}=await hu("rg --files",{cwd:t,timeout:5e3});ft=n.split(`
|
|
118
|
+
`).filter(Boolean),fs=Date.now(),mn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await pu.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(zr.join(n,a.name),l):e.push(l)}};await s(t,""),ft=e,fs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{mn=!1}}}function yu(){return ft}function wu(){return ms}function bu(t){return ft.filter(e=>zr.basename(e)===t)}function xu(t){let e=t.toLowerCase();return ft.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Jr.exports={refreshIndex:$u,getFileIndex:yu,getIndexedCwd:wu,findFileInIndex:bu,searchIndex:xu,isIndexValid:Kr}});var Rt=O((Pp,Xr)=>{var hs=null,Ee=null,Mt=null,Yr=`Playwright is not installed. Install with:
|
|
119
|
+
npm install playwright && npx playwright install chromium
|
|
120
|
+
Then restart nex-code.`;function Vr(){if(Mt!==null)return Mt;try{require("playwright"),Mt=!0}catch{Mt=!1}return Mt}async function pn(){if(!Vr())throw new Error(Yr);return hs||(hs=require("playwright")),(!Ee||!Ee.isConnected())&&(Ee=await hs.chromium.launch({headless:!0})),Ee}async function ku(){if(Ee){try{await Ee.close()}catch{}Ee=null}}process.on("exit",()=>{if(Ee)try{Ee.close()}catch{}});async function _u(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await pn()).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 vu(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let a=await(await pn()).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 Su(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await pn()).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 Tu(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 pn()).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()}}Xr.exports={isPlaywrightAvailable:Vr,browserNavigate:_u,browserScreenshot:vu,browserClick:Su,browserFill:Tu,closeBrowser:ku,INSTALL_MSG:Yr}});var hn=O((qp,Qr)=>{var{C:B}=Q(),Ot="",ie=[],Nt=0,Ke=null;function Cu(t){Ke=t}function Eu(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 Au(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 Mu(){return{name:Ot,tasks:ie.map(t=>({...t}))}}function Ru(){Ot="",ie=[],Nt=0,Ke&&Ke("clear",{})}function Nu(){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 Ou(){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 Pu(){return ie.length>0&&ie.some(t=>t.status==="pending"||t.status==="in_progress")}Qr.exports={createTasks:Eu,updateTask:Au,getTaskList:Mu,clearTasks:Ru,getReadyTasks:Nu,renderTaskList:Ou,setOnChange:Cu,hasActiveTasks:Pu}});var $s=O((Ip,ei)=>{var{getActiveModel:qu,getActiveProviderName:Iu}=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 Zr(){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={}}}Zr();function gs(){let e=qu()?.id,s=Iu();return e&&xe[e]?xe[e]:s&&xe[`${s}:*`]?xe[`${s}:*`]:e&&qt[e]?qt[e]:s&&It[s]?It[s]:"full"}function Lu(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 ju(t,e){let s=e||gs();if(s==="full"||!Pt[s])return t;let n=new Set(Pt[s]);return t.filter(o=>n.has(o.function.name))}function Du(){let t=gs(),e=Pt[t]?Pt[t].length:"all";return{tier:t,toolCount:e}}ei.exports={filterToolsForModel:ju,getActiveTier:gs,getModelTier:Lu,getTierInfo:Du,TIERS:Pt,MODEL_TIERS:qt,PROVIDER_DEFAULT_TIER:It,loadConfigOverrides:Zr}});var ui=O((jp,ci)=>{var{callStream:Fu,getActiveProviderName:xs,getActiveModelId:Uu,getConfiguredProviders:Wu,getProvider:Bu,getActiveProvider:Hu,parseModelSpec:Gu}=oe(),{parseToolArgs:zu}=sn(),{filterToolsForModel:Ku,getModelTier:ws}=$s(),{trackUsage:Ju}=lt(),{MultiProgress:Yu,C:Lp}=Q(),Vu=15,ti=5,ni=3,gn=new Map;function Xu(t,e){let s=gn.get(t);return s&&s!==e?!1:(gn.set(t,e),!0)}function ys(t){gn.delete(t)}function bs(){gn.clear()}function si(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 oi(t,e,s){let n;for(let o=0;o<=ni;o++)try{return await Fu(t,e,s)}catch(r){if(n=r,o<ni&&si(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 Qu=new Set(["ask_user","task_list","spawn_agents"]),Zu=new Set(["write_file","edit_file","patch_file"]),ed=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,td=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ri(t){return td.test(t)?"full":ed.test(t)?"essential":"standard"}function ii(t){let e=Wu(),s=xs(),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(ws(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}function ai(t){if(t.model){let{provider:n,model:o}=Gu(t.model),r=n?Bu(n):Hu(),a=n||xs();if(r&&r.isConfigured()&&(r.getModel(o)||a==="local")){let l=ws(o,a);return{provider:a,model:o,tier:l}}}let e=ri(t.task),s=ii(e);if(s){let n=ws(s.model,s.provider);return{provider:s.provider,model:s.model,tier:n}}return{provider:null,model:null,tier:null}}async function li(t,e={}){let s=Math.min(t.max_iterations||10,Vu),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.
|
|
118
123
|
|
|
119
124
|
TASK: ${t.task}
|
|
120
125
|
${t.context?`
|
|
@@ -136,69 +141,93 @@ TOOL STRATEGY:
|
|
|
136
141
|
ERROR RECOVERY:
|
|
137
142
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
138
143
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
139
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];c.push({role:"user",content:t.task});let u=
|
|
140
|
-
...(truncated)`:
|
|
141
|
-
`)}catch(o){return n.stop(),
|
|
142
|
-
${
|
|
143
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
144
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];c.push({role:"user",content:t.task});let u=ai(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:g}=ze(),x=Ku(h.filter($=>!Qu.has($.function.name)),m),w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let k=await oi(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||xs(),M=f||Uu();Ju(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)ys(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=zu(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(Zu.has(P)&&I.path){let N=require("path"),q=N.isAbsolute(I.path)?I.path:N.resolve(process.cwd(),I.path);if(!Xu(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)ys($);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)ys(k);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function nd(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ti)return`ERROR: Max ${ti} 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 Yu(s);n.start();try{let o=e.map((u,d)=>li(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(),bs();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(),bs(),`ERROR: Sub-agent execution failed: ${o.message}`}}ci.exports={runSubAgent:li,executeSpawnAgents:nd,clearAllLocks:bs,classifyTask:ri,pickModelForTier:ii,resolveSubAgentModel:ai,isRetryableError:si,callWithRetry:oi}});var ze=O((Up,bi)=>{var J=require("fs").promises,sd=require("fs"),de=require("path"),Ae=require("util").promisify(require("child_process").exec),di=require("util").promisify(require("child_process").execFile),{spawnSync:od}=require("child_process"),ks=require("axios"),{isForbidden:rd,isDangerous:id,isCritical:fi,confirm:ad}=Se(),{showClaudeDiff:$n,showClaudeNewFile:ld,showEditDiff:Dp,confirmFileChange:Lt}=wr(),{C:H,Spinner:$i,getToolSpinnerText:cd}=Q(),{isGitRepo:_s,getCurrentBranch:mi,getStatus:ud,getDiff:dd}=Ge(),{recordChange:yn}=ut(),{fuzzyFindText:pi,findMostSimilar:Ss}=Br(),{runDiagnostics:jt}=Gr(),{findFileInIndex:fd,getFileIndex:Fp}=ps(),md=/^(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 wn(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=fd(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 yi(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+`
|
|
144
149
|
|
|
145
150
|
`+s.join(`
|
|
146
|
-
`)}function ni(t,e,s){let n=$n(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 Zr=!1;async function gn(){if(!Zr){Zr=!0;try{let{stdout:t}=await Lt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Lt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Lt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Lt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Lu=[/\.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=ce.isAbsolute(t)?ce.resolve(t):ce.resolve(process.cwd(),t);for(let s of Lu)if(s.test(e))return null;return e}var Iu=[{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 ei(t,e,s={}){switch(t){case"bash":{let n=e.command,o=Tu(n);if(o)return`BLOCKED: Command matches forbidden pattern: ${o}`;if(Cu(n)&&!s.autoConfirm&&(console.log(`
|
|
147
|
-
${
|
|
148
|
-
${
|
|
149
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),
|
|
150
|
-
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,
|
|
151
|
-
`)}case"write_file":{await
|
|
152
|
-
`+d.message:""}`}let r=await
|
|
151
|
+
`)}function wi(t,e,s){let n=Ss(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 hi=!1;async function vs(){if(!hi){hi=!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 pd=[/\.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 pd)if(s.test(e))return null;return e}var hd=[{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 gi(t,e,s={}){switch(t){case"bash":{let n=e.command,o=rd(n);if(o)return`BLOCKED: Command matches forbidden pattern: ${o}`;if(s.autoConfirm?fi(n):id(n)){let l=fi(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
152
|
+
${H.yellow}${l}: ${n}${H.reset}`),!await ad(" Execute?"))return"CANCELLED: User declined to execute this command."}if(md.test(n.trim())){s.silent||console.log(`${H.dim} \u25B6 interactive: ${n}${H.reset}`);let l=od("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 $i(`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=yi(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 wn(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 sd.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(`
|
|
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(`
|
|
156
|
+
`)}case"write_file":{await vs();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($n(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(ld(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"),yn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await vs();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 wn(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=pi(r,e.old_text);if(d)a=d,l=!0,console.log(`${H.dim} \u2713 fuzzy whitespace match applied${H.reset}`);else{let f=wi(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let g=await jt(n,f.content);if($n(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"),yn("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=Ss(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
153
158
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
154
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(
|
|
155
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
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($n(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"),yn("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 di("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
156
161
|
`).slice(0,50).join(`
|
|
157
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
158
|
-
`);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}=ps(),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}
|
|
159
164
|
|
|
160
|
-
\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 di("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
161
166
|
`).slice(0,100).join(`
|
|
162
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
163
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let
|
|
164
|
-
Most similar text (line ${
|
|
165
|
-
${
|
|
167
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await vs();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 wn(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=pi(a,h);if(x)l.push({old_text:x,new_text:g}),c=!0;else{let w=Ss(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($n(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"),yn("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 ks.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 ks.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 ks.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}
|
|
166
177
|
${u.url}`).join(`
|
|
167
178
|
|
|
168
|
-
`)}catch{return"ERROR: Web search failed"}}case"
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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 _s())return"ERROR: Not a git repository";let n=await mi()||"(detached)",o=await ud();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 _s())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 dd(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await _s())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}=hn(),{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:
|
|
173
195
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
174
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(`
|
|
175
|
-
`+
|
|
176
|
-
`+
|
|
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}=ui();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 mi()||"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 gd(t,e,s={}){let n=s.silent?null:cd(t,e);if(!n)return gi(t,e,s);let o=new $i(n);o.start();try{let r=await gi(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}bi.exports={TOOL_DEFINITIONS:hd,executeTool:gd,resolvePath:ue,autoFixPath:wn,autoFixEdit:wi,enrichBashError:yi}});var Cs=O((Wp,ki)=>{var $e=require("fs").promises,me=require("path"),bn=require("util").promisify(require("child_process").exec),{C:ke}=Q(),{getMergeConflicts:xi}=Ge(),Ts=new Map,mt=new Map,xn=null,$d=3e4;async function Ie(t){try{return await t()}catch{return null}}async function yd(){if(!xn||Date.now()>xn)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 wd(){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 bd(t){let e="fileContext",s=Ts.get(e),n=!1;if(s&&await yd()&&(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(`
|
|
177
206
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
178
|
-
${
|
|
179
|
-
`)}`)}let g=me.join(t,".gitignore");if(await
|
|
180
|
-
${
|
|
207
|
+
${$.join(`
|
|
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(`
|
|
181
210
|
|
|
182
|
-
`),
|
|
183
|
-
${
|
|
211
|
+
`),Ts.set(e,s),xn=Date.now()+$d,await wd()}let o=[s],[r,a,l,c]=await Promise.all([Ie(async()=>{let{stdout:u}=await bn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ie(async()=>{let{stdout:u}=await bn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ie(async()=>{let{stdout:u}=await bn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),xi()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
212
|
+
${a}`),l&&o.push(`RECENT COMMITS:
|
|
184
213
|
${l}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
|
|
185
214
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
186
215
|
${u}`)}return o.join(`
|
|
187
216
|
|
|
188
|
-
`)}async function
|
|
189
|
-
${e}`);let s=
|
|
190
|
-
${s}`);let n=
|
|
217
|
+
`)}async function xd(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 bn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),xi()]);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()}ki.exports={gatherProjectContext:bd,printContext:xd,_clearContextCache:()=>{Ts.clear(),mt.clear(),xn=null}}});var Ye=O((Bp,Ti)=>{var Re=require("fs"),Es=require("path");function kn(){return Es.join(process.cwd(),".nex","sessions")}function _i(){let t=kn();Re.existsSync(t)||Re.mkdirSync(t,{recursive:!0})}function As(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Es.join(kn(),`${e}.json`)}function Ms(t,e,s={}){_i();let n=As(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 vi(t){let e=As(t);if(!Re.existsSync(e))return null;try{return JSON.parse(Re.readFileSync(e,"utf-8"))}catch{return null}}function Si(){_i();let t=kn(),e=Re.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Re.readFileSync(Es.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 kd(t){let e=As(t);return Re.existsSync(e)?(Re.unlinkSync(e),!0):!1}function _d(){let t=Si();return t.length===0?null:vi(t[0].name)}var Je=null,Me=null,Dt=null;function vd(t,e={}){t.length!==0&&(Je&&clearTimeout(Je),Me=t,Dt=e||{},Je=setTimeout(()=>{Me&&Me.length>0&&Ms("_autosave",Me,Dt),Je=null,Me=null,Dt=null},5e3))}function Sd(){Je&&(clearTimeout(Je),Je=null),Me&&Me.length>0&&(Ms("_autosave",Me,Dt),Me=null,Dt=null)}Ti.exports={saveSession:Ms,loadSession:vi,listSessions:Si,deleteSession:kd,getLastSession:_d,autoSave:vd,flushAutoSave:Sd,_getSessionsDir:kn}});var Le=O((Hp,Ni)=>{var Ne=require("fs"),_n=require("path"),Td=require("os");function Rs(){return _n.join(process.cwd(),".nex","memory")}function Ns(){return _n.join(Rs(),"memory.json")}function Cd(){return _n.join(process.cwd(),"NEX.md")}function Ci(){return _n.join(Td.homedir(),".nex","NEX.md")}function Ed(){let t=Rs();Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0})}function vn(){let t=Ns();if(!Ne.existsSync(t))return{};try{return JSON.parse(Ne.readFileSync(t,"utf-8"))}catch{return{}}}function Ei(t){Ed(),Ne.writeFileSync(Ns(),JSON.stringify(t,null,2),"utf-8")}function Ad(t,e){let s=vn();s[t]={value:e,updatedAt:new Date().toISOString()},Ei(s)}function Md(t){let e=vn();return e[t]?e[t].value:null}function Rd(t){let e=vn();return t in e?(delete e[t],Ei(e),!0):!1}function Ai(){let t=vn();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Mi(){let t=Ci();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function Ri(){let t=Cd();if(!Ne.existsSync(t))return"";try{return Ne.readFileSync(t,"utf-8").trim()}catch{return""}}function Nd(){let t=[],e=Mi();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
218
|
+
${e}`);let s=Ri();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
219
|
+
${s}`);let n=Ai();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
191
220
|
`);t.push(`PROJECT MEMORY:
|
|
192
221
|
${o}`)}return t.join(`
|
|
193
222
|
|
|
194
|
-
`)}
|
|
195
|
-
${
|
|
196
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
197
|
-
`)}function
|
|
223
|
+
`)}Ni.exports={remember:Ad,recall:Md,forget:Rd,listMemories:Ai,loadGlobalInstructions:Mi,loadProjectInstructions:Ri,getMemoryContext:Nd,_getMemoryDir:Rs,_getMemoryFile:Ns,_getGlobalNexMdPath:Ci}});var Ft=O((zp,qi)=>{var Ve=require("fs"),Os=require("path"),{C:Gp}=Q(),Sn={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={...Sn};function Oi(){let t=Os.join(process.cwd(),".nex","config.json");if(Ve.existsSync(t))try{let e=JSON.parse(Ve.readFileSync(t,"utf-8"));e.permissions&&(pt={...Sn,...e.permissions})}catch{}}function Od(){let t=Os.join(process.cwd(),".nex"),e=Os.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 Pi(t){return pt[t]||"ask"}function Pd(t,e){return["allow","ask","deny"].includes(e)?(pt[t]=e,!0):!1}function qd(t){return Pi(t)}function Id(){return Object.entries(pt).map(([t,e])=>({tool:t,mode:e}))}function Ld(){pt={...Sn}}Oi();qi.exports={getPermission:Pi,setPermission:Pd,checkPermission:qd,listPermissions:Id,loadPermissions:Oi,savePermissions:Od,resetPermissions:Ld,DEFAULT_PERMISSIONS:Sn}});var ht=O((Jp,Fi)=>{var Xe=require("fs"),Tn=require("path"),Kp=require("readline"),{C:F}=Q(),X=null,Ps=!1,qs=null,Ii=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 Cn(){return Tn.join(process.cwd(),".nex","plans")}function Li(){let t=Cn();Xe.existsSync(t)||Xe.mkdirSync(t,{recursive:!0})}function jd(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 Dd(){return X}function Fd(t){Ps=t}function Ud(){return Ps}function Wd(){return!X||X.status!=="draft"?!1:(X.status="approved",X.updatedAt=new Date().toISOString(),!0)}function Bd(){return!X||X.status!=="approved"?!1:(X.status="executing",!0)}function Hd(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 Gd(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 zd(t){if(t||(t=X),!t)return null;Li();let e=Tn.join(Cn(),`${t.name}.json`);return Xe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Kd(t){let e=Tn.join(Cn(),`${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 Jd(){Li();let t=Cn(),e=Xe.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Xe.readFileSync(Tn.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 Yd(t){qs=t}function Vd(){return qs}function Xd(){X=null,Ps=!1,qs=null}function Qd(){return`
|
|
198
227
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
199
228
|
|
|
200
229
|
# Allowed Tools (read-only)
|
|
201
|
-
You may ONLY use these tools: ${[...
|
|
230
|
+
You may ONLY use these tools: ${[...Ii].join(", ")}
|
|
202
231
|
Any other tool call will be blocked and returned with an error.
|
|
203
232
|
|
|
204
233
|
# Analysis Phase
|
|
@@ -229,36 +258,36 @@ Bullet list of potential issues and mitigations.
|
|
|
229
258
|
# Important
|
|
230
259
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
231
260
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
232
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
233
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${
|
|
234
|
-
`)}function
|
|
235
|
-
`)}function
|
|
236
|
-
`))!==-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(`${
|
|
237
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${
|
|
238
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${
|
|
239
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
240
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
241
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
242
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
243
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${
|
|
244
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${
|
|
245
|
-
`);return}}this._safeWrite(`${
|
|
246
|
-
`)}};
|
|
261
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var ji=["interactive","semi-auto","autonomous"],Di="interactive";function Zd(t){return ji.includes(t)?(Di=t,!0):!1}function ef(){return Di}Fi.exports={createPlan:jd,getActivePlan:Dd,setPlanMode:Fd,isPlanMode:Ud,approvePlan:Wd,startExecution:Bd,updateStep:Hd,formatPlan:Gd,savePlan:zd,loadPlan:Kd,listPlans:Jd,clearPlan:Xd,getPlanModePrompt:Qd,setPlanContent:Yd,getPlanContent:Vd,PLAN_MODE_ALLOWED_TOOLS:Ii,setAutonomyLevel:Zd,getAutonomyLevel:ef,AUTONOMY_LEVELS:ji}});var Vi=O((Yp,Yi)=>{var{C:p}=Q();function tf(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(` ${Ls(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 Ls(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ui(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Wi(t):e==="json"||e==="jsonc"?Bi(t):e==="python"||e==="py"?Hi(t):e==="go"||e==="golang"?Gi(t):e==="rust"||e==="rs"?zi(t):e==="css"||e==="scss"||e==="less"?Ki(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Ji(t):t:""}function Ui(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 Wi(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 Bi(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 Hi(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 Gi(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 zi(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,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 Ki(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 Ji(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 nf(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 sf(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 Is=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}
|
|
266
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${p.dim}${"\u2500".repeat(40)}${p.reset}
|
|
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(` ${Ls(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
|
+
`)}};Yi.exports={renderMarkdown:tf,renderInline:Ze,stripHeadingMarkers:Qe,highlightCode:Ls,highlightJS:Ui,highlightBash:Wi,highlightJSON:Bi,highlightPython:Hi,highlightGo:Gi,highlightRust:zi,highlightCSS:Ki,highlightHTML:Ji,renderTable:nf,renderProgress:sf,StreamRenderer:Is}});var Fs=O((Vp,ea)=>{var{execSync:of}=require("child_process"),js=require("path"),Ut=require("fs"),Ds=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Xi(){return js.join(process.cwd(),".nex","hooks")}function rf(){return js.join(process.cwd(),".nex","config.json")}function Qi(){let t=rf();if(!Ut.existsSync(t))return{};try{return JSON.parse(Ut.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function En(t){if(!Ds.includes(t))return[];let e=[],s=Xi(),n=js.join(s,t);Ut.existsSync(n)&&e.push(n);let o=Qi();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Zi(t,e={},s=3e4){try{return{success:!0,output:of(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 af(t,e={}){let s=En(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=Zi(r,n);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function lf(t){return En(t).length>0}function cf(){let t=[];for(let e of Ds){let s=En(e);s.length>0&&t.push({event:e,commands:s})}return t}function uf(){let t=Xi();return Ut.existsSync(t)||Ut.mkdirSync(t,{recursive:!0}),t}ea.exports={HOOK_EVENTS:Ds,loadHookConfig:Qi,getHooksForEvent:En,executeHook:Zi,runHooks:af,hasHooks:lf,listHooks:cf,initHooksDir:uf}});var te=O((Zp,ma)=>{var{C:v,Spinner:gt,TaskProgress:df,formatToolCall:ff,formatResult:mf,formatToolSummary:oa,setActiveTaskProgress:Xp}=Q(),{callStream:pf}=oe(),{parseToolArgs:hf}=sn(),{executeTool:gf}=ze(),{gatherProjectContext:$f}=Cs(),{fitToContext:yf,forceCompress:Us,getUsage:wf,estimateTokens:bf}=be(),{autoSave:et}=Ye(),{getMemoryContext:xf}=Le(),{checkPermission:kf,setPermission:_f,savePermissions:vf}=Ft(),{confirm:ra,setAllowAlwaysHandler:Sf}=Se(),{isPlanMode:Nn,getPlanModePrompt:Tf,PLAN_MODE_ALLOWED_TOOLS:ia,setPlanContent:Cf}=ht(),{StreamRenderer:Ef}=Vi(),{runHooks:ta}=Fs(),{routeMCPCall:Af,getMCPToolDefinitions:Mf}=cn(),{getSkillInstructions:Rf,getSkillToolDefinitions:Nf,routeSkillCall:Of}=At(),{trackUsage:Pf}=lt(),{validateToolArgs:qf}=us(),{filterToolsForModel:na,getModelTier:If,PROVIDER_DEFAULT_TIER:Qp}=$s(),{getConfiguredProviders:Lf}=oe(),aa=require("fs"),la=require("path"),sa=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function jf(t){let e=[],s;for(sa.lastIndex=0;(s=sa.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):la.resolve(n);aa.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Df(t){let e=aa.readFileSync(t),s=la.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 ca(t){let e=jf(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}=Df(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Ws=null,Bs=null,Hs=null;function $t(){if(Ws===null){let{TOOL_DEFINITIONS:t}=ze();Ws=t}return Bs===null&&(Bs=Nf()),Hs===null&&(Hs=Mf()),[...Ws,...Bs,...Hs]}var Js=50;function Ff(t){Number.isFinite(t)&&t>0&&(Js=t)}var Mn=()=>null;function Uf(t){Mn=t}var Wt=null,Ys=null,yt=null,Rn=new Map,Wf=5e3,Bf=3e3;function Hf(t){if(bf(t)>Wf)try{let{compressToolResult:s}=be();return s(t,Bf)}catch{return t}return t}function ua(t){try{let{getActiveModel:e}=oe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Rn.has(n))return Rn.get(n);let o=na(t);return Rn.set(n,o),o}catch{return na(t)}}function Gf(){Rn.clear()}async function da(){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 zf(){Wt=null,Ys=null,yt=null}var Kf=new Set(["read_file","list_directory","search_files","glob","grep","web_fetch","web_search","git_status","git_diff","git_log"]),Gs=5,zs=3,An=2,Jf=6e4,Yf=12e4;function Vf(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{}}Sf(t=>{_f(t,"allow"),vf(),console.log(`${v.green} \u2713 ${t}: always allow${v.reset}`)});async function Xf(t){let e=t.function.name,s=hf(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.
|
|
247
276
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
248
277
|
|
|
249
278
|
Expected JSON schema for "${e}":
|
|
250
279
|
${u}
|
|
251
280
|
|
|
252
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
253
|
-
`)[0]}${
|
|
281
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=qf(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(Nn()&&!ia.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=kf(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 ra(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 Qf(t,e,s={}){let n=await Of(t,e);if(n!==null)return n;let o=await Af(t,e);return o!==null?o:gf(t,e,s)}function Zf(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 Ks(t,e=!1){e||console.log(ff(t.fnName,t.args)),ta("pre-tool",{tool_name:t.fnName});let s=await Qf(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
254
283
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
255
|
-
`)[0],
|
|
284
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),l=oa(t.fnName,t.args,o,a);return e||(console.log(mf(o)),console.log(l)),ta("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:Hf(o),tool_call_id:t.callId},summary:l}}async function em(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=Zf(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 Ks(t[c],e);n[c]=u,o.push(d)}else{let c=r.map(d=>Ks(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(oa(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Kf.has(u.fnName))r.push(c);else{await l(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Ks(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 tm(){if(yt!==null)return yt;try{let e=Lf().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:If(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=`
|
|
256
285
|
# Sub-Agent Model Routing
|
|
257
286
|
|
|
258
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 |
|
|
259
288
|
|---|---|---|
|
|
260
289
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
261
|
-
`;return
|
|
290
|
+
`;return yt=n,n}catch{return yt="",""}}async function fa(){let t=await da();if(Wt!==null&&t===Ys)return Wt;let e=await $f(process.cwd()),s=xf(),n=Rf(),o=Nn()?Tf():"";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.
|
|
262
291
|
|
|
263
292
|
WORKING DIRECTORY: ${process.cwd()}
|
|
264
293
|
All relative paths resolve from this directory.
|
|
@@ -330,7 +359,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
330
359
|
- Good for: reading multiple files, analyzing separate modules.
|
|
331
360
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
332
361
|
- Max 5 parallel agents.
|
|
333
|
-
${
|
|
362
|
+
${tm()}
|
|
334
363
|
|
|
335
364
|
# Edit Reliability (Critical)
|
|
336
365
|
|
|
@@ -370,139 +399,190 @@ When a tool call returns ERROR:
|
|
|
370
399
|
- Prefer creating new git commits over amending. Never force-push without explicit permission.
|
|
371
400
|
- If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
|
|
372
401
|
|
|
373
|
-
`,
|
|
374
|
-
${
|
|
375
|
-
${
|
|
376
|
-
${
|
|
377
|
-
`),await u.stream(t,e,{model:m,signal:s.signal,...s})}catch(f){if(o=f,
|
|
378
|
-
`),await u.chat(t,e,{model:m,...s})}catch(f){let m=l>0?
|
|
379
|
-
`);process.stdout.write(`\x1B[${m}A`)}let
|
|
380
|
-
`);process.stdout.write(
|
|
381
|
-
`),m
|
|
382
|
-
|
|
383
|
-
|
|
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
|
-
${
|
|
402
|
+
`,Ys=t,Wt}function nm(){ae=[]}function sm(){return ae.length}function om(){return ae}function rm(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 im(t){let e=ca(t);ae.push({role:"user",content:e});let{setOnChange:s}=hn(),n=null,o=0;s((q,L)=>{q==="create"?(n&&n.stop(),n=new df(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 fa()},...ae],l=new gt("Thinking...");l.start();let c=$t(),{messages:u,compressed:d,compacted:f,tokensRemoved:m}=await yf(a,c),h=wf(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=Js,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(Mn()?.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 Ef,we,Gt=Date.now(),xt=!1,jn=new AbortController,fo=setInterval(()=>{let A=Date.now()-Gt;A>=Yf?(le._clearCursorLine(),console.log(`${v.yellow} \u26A0 Stream stale for ${Math.round(A/1e3)}s \u2014 aborting and retrying${v.reset}`),jn.abort()):A>=Jf&&!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=ua($t()),j=Nn()?A.filter(se=>ia.has(se.function.name)):A,st=Mn(),D=new AbortController;st&&st.addEventListener("abort",()=>D.abort(),{once:!0}),jn.signal.addEventListener("abort",()=>D.abort(),{once:!0}),we=await pf(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},100)):(le.push(ve),ve=""),K&&(n&&!n._paused?n.pause():W&&W.stop(),U(),le.startCursor(),K=!1),ne+=se}})}catch(A){if(clearInterval(fo),n&&!n._paused&&n.pause(),W&&W.stop(),le.stopCursor(),jn.signal.aborted&&!Mn()?.aborted){if($++,$>An){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}=Us(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 (${An}) 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 ${$}/${An} \u2014 force-compressing before retry...${v.reset}`);let he=$t(),{messages:kt,tokensRemoved:_t}=Us(g,he);g=kt,console.log(`${v.dim} [force-compressed \u2014 ~${_t} tokens freed]${v.reset}`)}else console.log(`${v.yellow} \u26A0 Stale retry ${$}/${An} \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}=Us(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>Gs){console.log(`${v.red} Rate limit: max retries (${Gs}) 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}/${Gs})`);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>zs){console.log(`${v.red} Network error: max retries (${zs}) 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}/${zs})`);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(fo),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();Pf(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:Dn,tool_calls:Ue}=we,Fn={role:"assistant",content:Dn||""};if(Ue&&Ue.length>0&&(Fn.tool_calls=Ue),ae.push(Fn),g.push(Fn),!Ue||Ue.length===0){let A=(Dn||"").trim().length>0||ne.trim().length>0;if(!A&&T>0&&E<Js-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(Nn()&&A){let j=(Dn||ne||"").trim();Cf(j),Vf(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 zt=[];for(let A of Ue)zt.push(await Xf(A));let mo=n?{skipSpinner:!0,skipSummaries:!0}:{};mo.skipSummaries||U(),n&&n._paused&&n.resume();let po=await em(zt,!0,mo);for(let A=0;A<zt.length;A++){let j=zt[A];if(!j.canExecute)continue;let st=po[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 po)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 ra(" 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}}ma.exports={processInput:im,clearConversation:nm,getConversationLength:sm,getConversationMessages:om,setConversationMessages:rm,setAbortSignalGetter:Uf,setMaxIterations:Ff,invalidateSystemPromptCache:zf,clearToolFilterCache:Gf,getCachedFilteredTools:ua,buildSystemPrompt:fa,getProjectContextHash:da,buildUserContent:ca}});var oe=O((eh,wa)=>{var{OllamaProvider:am}=No(),{OpenAIProvider:lm}=Xo(),{AnthropicProvider:cm}=tr(),{GeminiProvider:um}=rr(),{LocalProvider:dm}=lr(),{checkBudget:pa}=lt(),ha={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"}},ga={};for(let[t,e]of Object.entries(ha))for(let s of Object.values(e))ga[s]=t;function Pn(t,e){let s=ga[t];return s&&ha[s][e]||t}var Z={},re=null,G=null,bt=[];function pe(){if(Object.keys(Z).length>0)return;wt("ollama",new am),wt("openai",new lm),wt("anthropic",new cm),wt("gemini",new um),wt("local",new dm);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 fm(t){return pe(),Z[t]||null}function Vs(){return pe(),Z[re]||null}function mm(){return pe(),re}function pm(){return pe(),G}function hm(){pe();let t=Vs();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 $a(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 gm(t){pe();let{provider:e,model:s}=$a(t);if(e){let o=Z[e];return o&&(o.getModel(s)||e==="local")?(re=e,G=s,On(),!0):!1}let n=Vs();if(n&&n.getModel(s))return G=s,On(),!0;for(let[o,r]of Object.entries(Z))if(r.getModel(s))return re=o,G=s,On(),!0;return!1}function On(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=te();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=be();t()}catch{}}function $m(){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 ym(){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 wm(){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 bm(t){bt=Array.isArray(t)?t:[]}function xm(){return[...bt]}function ya(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 km(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=pa(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?Pn(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,ya(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 _m(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=pa(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?Pn(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?Pn(G,c):G;if(typeof u.stream=="function")try{return await u.stream(t,e,{model:m,...s,onToken:()=>{}})}catch{}if(o=f,ya(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 vm(){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 Sm(){for(let t of Object.keys(Z))delete Z[t];re=null,G=null,bt=[]}wa.exports={registerProvider:wt,getProvider:fm,getActiveProvider:Vs,getActiveProviderName:mm,getActiveModelId:pm,getActiveModel:hm,setActiveModel:gm,getModelNames:$m,parseModelSpec:$a,listProviders:ym,listAllModels:wm,callStream:km,callChat:_m,getConfiguredProviders:vm,setFallbackChain:bm,getFallbackChain:xm,resolveModelForProvider:Pn,_reset:Sm}});var ka=O((th,xa)=>{var{C:z}=Q(),{listProviders:Tm,getActiveProviderName:Cm,getActiveModelId:Em,setActiveModel:Am}=oe();function ba(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 Mm(t){let e=Tm(),s=Cm(),n=Em(),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 ba(t,o,{title:"Select Model"});return r?(Am(r),console.log(`${z.green}Switched to ${r}${z.reset}`),!0):(console.log(`${z.dim}Cancelled${z.reset}`),!1)}xa.exports={pickFromList:ba,showModelPicker:Mm}});var Qs=O((sh,Ca)=>{var Xs=require("fs"),Rm=require("path"),{callChat:Nm}=oe(),{remember:Om,listMemories:nh,recall:Pm}=Le(),_a=4,qm=`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 Im(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 va(t){if(t.filter(o=>o.role==="user").length<_a)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Im(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:qm},{role:"user",content:`Conversation to analyze:
|
|
439
|
+
|
|
440
|
+
${s}`}];try{let a=((await Nm(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 Sa(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=Pm(o);a!==r&&(Om(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Ta(t){if(!t||t.length===0)return[];let e=Rm.join(process.cwd(),"NEX.md"),s="";try{Xs.existsSync(e)&&(s=Xs.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
|
+
`),Xs.writeFileSync(e,o,"utf-8")),n}async function Lm(t){let e=await va(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Sa(e.memories),n=Ta(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}Ca.exports={learnFromSession:Lm,reflectOnSession:va,applyMemories:Sa,applyNexAdditions:Ta,LEARN_MIN_MESSAGES:_a}});var Ma=O((oh,Aa)=>{var jm=require("axios"),Bt=require("fs"),Ea=require("path"),Dm="nex-code",Zs=Ea.join(process.cwd(),".nex"),eo=Ea.join(Zs,"last-version-check");Bt.existsSync(Zs)||Bt.mkdirSync(Zs,{recursive:!0});async function Fm(){try{let t=Wm(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Bm(e);let s=Um(),o=(await jm.get(`https://registry.npmjs.org/${Dm}/latest`,{timeout:5e3})).data.version,r=Hm(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function Um(){return Kt().version}function Wm(){try{if(Bt.existsSync(eo)){let t=Bt.readFileSync(eo,"utf8");return parseInt(t,10)}}catch{}return null}function Bm(t){try{Bt.writeFileSync(eo,t.toString())}catch{}}function Hm(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}}Aa.exports={checkForNewVersion:Fm}});var Ga=O((ih,Ha)=>{var Gm=require("readline"),Fe=require("fs"),_e=require("path"),{C:i,banner:zm,cleanupTerminal:Ra}=Q(),{listProviders:no,getActiveProviderName:je,listAllModels:rh,setFallbackChain:Km,getFallbackChain:Jm,getProvider:Ym}=oe(),{flushAutoSave:Na}=Ye(),{getActiveModel:De,setActiveModel:Oa}=sn(),{printContext:Pa}=Cs(),{loadAllSkills:Vm,getSkillCommands:so,handleSkillCommand:Xm}=At(),{setReadlineInterface:Qm,setAutoConfirm:Zm,getAutoConfirm:qa}=Se(),In=process.cwd(),Oe=null;function Ia(){return Oe?.signal??null}var Ln=[{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 La(){let t=so(),e=[...Ln,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of Ln)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 ja(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(In,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 Da(t){if(t.startsWith("/")){let n=[...Ln,...so()],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("~"))?[ja(s),s]:[[],t]}function Fa(){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 Ua(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 to(){let t=no(),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 Wa(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return Fa(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=ka();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 to(),!0;if(Oa(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 to(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let a=Jm();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 Km(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=Ua(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(`
|
|
446
511
|
${o()}
|
|
447
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:
|
|
448
|
-
${
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
${a.
|
|
452
|
-
${a.cyan}${a.
|
|
453
|
-
${a.cyan}${a.
|
|
454
|
-
${
|
|
455
|
-
|
|
456
|
-
${
|
|
457
|
-
${
|
|
458
|
-
|
|
459
|
-
${
|
|
460
|
-
${
|
|
461
|
-
|
|
462
|
-
${
|
|
463
|
-
${
|
|
464
|
-
${a.dim}
|
|
465
|
-
|
|
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=no();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}=Qs();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 Pa(In),!0;case"/autoconfirm":{let o=!qa();return Zm(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}=Qs(),{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):
|
|
533
|
+
|
|
534
|
+
\`\`\`diff
|
|
535
|
+
${f.substring(0,2e4)}
|
|
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}=cn(),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}=Fs(),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}=hn();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
466
544
|
`+o()+`
|
|
467
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
468
|
-
${
|
|
469
|
-
`);for(let c of l){let u=new Date(c.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${
|
|
470
|
-
${
|
|
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}
|
|
471
549
|
`),!0}case"/exit":case"/quit":console.log(`
|
|
472
|
-
${
|
|
473
|
-
`).filter(Boolean).slice(-
|
|
474
|
-
`)}catch{}}function ye(){let{isPlanMode:t,getAutonomyLevel:e}=
|
|
475
|
-
`),!0):!1)(),l=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
476
|
-
${
|
|
477
|
-
`),process.exit(1)),
|
|
478
|
-
`),await
|
|
479
|
-
${
|
|
480
|
-
${
|
|
481
|
-
${
|
|
482
|
-
`),m.setPrompt(ye()),m.prompt(),
|
|
483
|
-
`).trim();if(
|
|
484
|
-
`),
|
|
485
|
-
${
|
|
486
|
-
`)),S()}if(
|
|
487
|
-
`)),!0}if(
|
|
488
|
-
`)),S()}if(k){let
|
|
489
|
-
`)),!0}return
|
|
490
|
-
\x1B[2K ${
|
|
491
|
-
\x1B[2K ${
|
|
492
|
-
`).trim();if(
|
|
493
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
494
|
-
`).trim();if(
|
|
495
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
496
|
-
`)[0]||"An unexpected error occurred";console.log(`${
|
|
497
|
-
${
|
|
550
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return Xm(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var oo=1e3;function ro(){return _e.join(process.cwd(),".nex","repl_history")}function Ba(){try{let t=ro();if(Fe.existsSync(t))return Fe.readFileSync(t,"utf-8").split(`
|
|
551
|
+
`).filter(Boolean).slice(-oo)}catch{}return[]}function qn(t){try{let e=ro(),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 io="\x1B[200~",ao="\x1B[201~";function ep(t){return typeof t=="string"&&t.includes(io)}function tp(t){return typeof t=="string"&&t.includes(ao)}function Ht(t){return typeof t!="string"?t:t.split(io).join("").split(ao).join("")}async function np(){if(!Ym("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"),Oa("local:llama3"),!0}catch{return!1}}async function sp(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=te();t(Ia);let o=no().some(M=>M.configured),r=(async()=>{Vm();let M=De(),N=je();return{model:M,providerName:N}})(),a=(async()=>o?!0:await np()?(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}=Ma();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)),zm(`${c.providerName}:${c.model.id}`,In,{yolo:qa()}),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 Pa(In);let f=Ba(),m=Gm.createInterface({input:process.stdin,output:process.stdout,prompt:ye(),completer:Da,history:f,historySize:oo});Qm(m);let h=!1,g=0,x=!1,w=null;function $(){Na(),Ra(),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",()=>{Na()}),m.on("SIGINT",()=>{if(Ra(),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(io),W=L.includes(ao);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=[...Ln,...so()].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){qn(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){qn(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(qn(N),N==="/"){La(),m.setPrompt(ye()),m.prompt();return}if(N.startsWith("/")){await Wa(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)})}Ha.exports={startREPL:sp,getPrompt:ye,loadHistory:Ba,appendHistory:qn,getHistoryPath:ro,HISTORY_MAX:oo,showCommandList:La,completer:Da,completeFilePath:ja,handleSlashCommand:Wa,showProviders:to,showHelp:Fa,renderBar:Ua,hasPasteStart:ep,hasPasteEnd:tp,stripPasteSequences:Ht,getAbortSignal:Ia}});var Ja=require("path");require("dotenv").config({path:Ja.join(__dirname,"..",".env")});require("dotenv").config();var V=process.argv.slice(2);(V.includes("--help")||V.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
498
576
|
|
|
499
577
|
Options:
|
|
500
|
-
--task <prompt>
|
|
501
|
-
--
|
|
502
|
-
--
|
|
503
|
-
--
|
|
504
|
-
--
|
|
505
|
-
--
|
|
506
|
-
-
|
|
507
|
-
|
|
508
|
-
|
|
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=Kt();console.log(t.version),process.exit(0)}var op=V.includes("--yolo")||V.includes("-yolo");if(op){let{setAutoConfirm:t}=Se();t(!0)}var lo=V.indexOf("--model");if(lo!==-1&&V[lo+1]){let{setActiveModel:t}=oe();t(V[lo+1])}var co=V.indexOf("--max-turns");if(co!==-1&&V[co+1]){let t=parseInt(V[co+1],10);if(t>0){let{setMaxIterations:e}=te();e(t)}}else try{let t=require("fs"),e=Ja.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 uo(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}function za(t){if(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 Ka=V.indexOf("--prompt-file");if(Ka!==-1){let t=V[Ka+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{}uo(),za(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)),uo(),za(e)}else{uo();let{startREPL:e}=Ga();e()}}
|