nex-code 0.3.19 → 0.3.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/dist/nex-code.js +234 -232
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,125 +1,126 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var zt=O((
|
|
3
|
-
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,
|
|
5
|
-
`}process.stderr.write(
|
|
6
|
-
`;for(let
|
|
7
|
-
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
9
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,
|
|
11
|
-
`;for(let
|
|
12
|
-
`}process.stderr.write(a)}};function
|
|
13
|
-
`),n
|
|
14
|
-
`);return o>0&&(
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80)
|
|
17
|
-
|
|
18
|
-
`).length
|
|
19
|
-
`).
|
|
2
|
+
var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var zt=O(($p,Za)=>{Za.exports={name:"nex-code",version:"0.3.21",description:"The open-source agentic coding CLI. Free with Ollama Cloud \u2014 switch to OpenAI, Anthropic or Gemini anytime. Alternative to Claude Code & Gemini CLI.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright",test:"jest --coverage","test:watch":"jest --watch",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0"}}});var xo=O((yp,bo)=>{var R={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},$o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],yo=["\u273D","\u2726","\u2727","\u2726"],Bs=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=$o[this.frame%$o.length],n="";if(this.startTime){let s=Math.floor((Date.now()-this.startTime)/1e3);if(s>=60){let o=Math.floor(s/60),r=s%60;n=` ${R.dim}${o}m ${String(r).padStart(2,"0")}s${R.reset}`}else s>=1&&(n=` ${R.dim}${s}s${R.reset}`)}process.stderr.write(`\x1B[2K\r${R.cyan}${e}${R.reset} ${R.dim}${this.text}${R.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),80))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},wo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Hs=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 n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_render(){if(this._stopped)return;let e=wo[this.frame%wo.length],n=this._formatElapsed(),s=n?` ${R.dim}${n}${R.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let a,c;switch(this.statuses[r]){case"done":a=`${R.green}\u2713${R.reset}`,c=R.dim;break;case"error":a=`${R.red}\u2717${R.reset}`,c=R.dim;break;default:a=`${R.cyan}${e}${R.reset}`,c=""}let l=r===this.labels.length-1?s:"";o+=`\x1B[2K ${a} ${c}${this.labels[r]}${R.reset}${l}
|
|
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 n=0;n<this.lineCount;n++)e+=`
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${R.dim}${e}${R.reset}`:"",s="";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?n:"";s+=`\x1B[2K ${r} ${R.dim}${this.labels[o]}${R.reset}${a}
|
|
5
|
+
`}process.stderr.write(s)}},Kt={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Jt={done:R.green,in_progress:R.cyan,pending:R.dim,failed:R.red},Ie=null,Gs=class{constructor(e,n){this.name=e,this.tasks=n.map(s=>({id:s.id,description:s.description,status:s.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 n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=yo[this.frame%yo.length],n=this._formatElapsed(),s=this._formatTokens(),o=[n,s?`\u2193 ${s} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${R.dim}(${o})${R.reset}`:"",a=`\x1B[2K${R.cyan}${e}${R.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Kt[l.status]||Kt.pending,f=Jt[l.status]||Jt.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${m}
|
|
7
|
+
`}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 n=0;n<this.lineCount;n++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Ie=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Ie===this&&(Ie=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let s=this.tasks.find(o=>o.id===e);s&&(s.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(c=>c.status==="done").length,s=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=s>0?`${n}/${o} done, ${s} failed`:`${n}/${o} done`,a=`\x1B[2K${R.green}\u2714${R.reset} ${this.name} ${R.dim}(${e} \xB7 ${r})${R.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Kt[l.status]||Kt.pending,f=Jt[l.status]||Jt.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${R.dim}${u}${R.reset} ${f}${d}${R.reset} ${R.dim}${m}${R.reset}
|
|
12
|
+
`}process.stderr.write(a)}};function ec(t){Ie=t}function tc(){return Ie}function sc(){Ie&&(Ie.stop(),Ie=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}bo.exports={C:R,Spinner:Bs,MultiProgress:Hs,TaskProgress:Gs,setActiveTaskProgress:ec,getActiveTaskProgress:tc,cleanupTerminal:sc}});var _o=O((wp,ko)=>{var V={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function nc(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":n=(e.command||"").substring(0,80);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let s=n?`${V.dim}(${n})${V.reset}`:"";return`${V.cyan}\u23FA${V.reset} ${V.bold}${t}${V.reset}${s}`}function oc(t,e=8){let n=t.split(`
|
|
13
|
+
`),s=n.slice(0,e),o=n.length-e,r=`${V.dim} \u23BF ${V.reset}`,a=" ",c=s.map((l,u)=>`${u===0?r:a}${V.green}${l}${V.reset}`).join(`
|
|
14
|
+
`);return o>0&&(c+=`
|
|
15
|
+
${V.gray} \u2026+${o} more lines${V.reset}`),c}function rc(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 ic(t,e,n,s){let o=String(n||"");if(s){let a=o.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
+
${V.dim}${c[1].substring(0,100)}${V.reset}`:"";return` ${V.red}\u23BF ${a}${V.reset}${l}`}let r;switch(t){case"read_file":{let a=o.split(`
|
|
18
|
+
`).filter(Boolean),c=a.length,l=a[a.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let a=(e.content||"").split(`
|
|
19
|
+
`).length;r=`Wrote ${a} line${a!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let a=(e.patches||[]).length;r=`Applied ${a} patch${a!==1?"es":""}`;break}case"bash":{let a=o.match(/^EXIT (\d+)/);if(a){let c=o.match(/\nHINT: (.+)/);r=`Exit ${a[1]}${c?` \u2014 ${c[1].substring(0,60)}`:""}`}else{let c=o.split(`
|
|
20
|
+
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let a=o.split(`
|
|
20
21
|
`).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
22
|
`).filter(Boolean).length;r=`${a} file${a!==1?"s":""} found`}break}case"list_directory":{let a=o==="(empty)"?0:o.split(`
|
|
22
|
-
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),
|
|
23
|
-
`).filter(
|
|
24
|
-
`).filter(
|
|
23
|
+
`).filter(Boolean).length;r=`${a} entr${a!==1?"ies":"y"}`;break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
24
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
25
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=a>0?`${a} commit${a!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let a=o.split(`
|
|
25
26
|
|
|
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,
|
|
27
|
-
`),u=
|
|
28
|
-
${
|
|
27
|
+
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${V.dim}\u23BF ${r}${V.reset}`}ko.exports={C:V,formatToolCall:nc,formatResult:oc,getToolSpinnerText:rc,formatToolSummary:ic}});var Q=O((bp,vo)=>{var ot={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function ac(t,e){return[...t].map(n=>n===" "?n:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${n}`).join("")+ot.reset}function cc(t,e){let n=(t.length-1)*e,s=Math.min(Math.floor(n),t.length-2),o=n-s;return[Math.round(t[s][0]+(t[s+1][0]-t[s][0])*o),Math.round(t[s][1]+(t[s+1][1]-t[s][1])*o),Math.round(t[s][2]+(t[s+1][2]-t[s][2])*o)]}function lc(t,e,n={}){let s=ot.bold,o=ot.dim,r=ot.reset,a=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=a.map((d,f)=>{let m=f/(a.length-1||1);return ac(d,cc(c,m))}).join(`
|
|
28
|
+
`),u=n.yolo?` ${s}${ot.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
29
|
+
${l}
|
|
29
30
|
${o}Agentic Coding CLI v${zt().version}${r}
|
|
30
31
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
31
|
-
`)}var{Spinner:
|
|
32
|
-
`)};return o.length>0&&(r.images=o),r}return
|
|
33
|
-
`);h=x.pop()||"";for(let w of x){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(
|
|
32
|
+
`)}var{Spinner:uc,MultiProgress:dc,TaskProgress:fc,setActiveTaskProgress:mc,getActiveTaskProgress:pc,cleanupTerminal:hc}=xo(),{formatToolCall:gc,formatResult:$c,getToolSpinnerText:yc,formatToolSummary:wc}=_o();vo.exports={C:ot,banner:lc,Spinner:uc,MultiProgress:dc,TaskProgress:fc,setActiveTaskProgress:mc,getActiveTaskProgress:pc,cleanupTerminal:hc,formatToolCall:gc,formatResult:$c,getToolSpinnerText:yc,formatToolSummary:wc}});var Te=O((xp,Mo)=>{var bc=require("readline"),{C:Yt}=Q(),So=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/],zs=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function To(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let s=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(s.length===0)return!1;let o=r=>{let a=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(a))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):zs.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:zs.some(c=>c.test(a))};return s.every(o)}var Js=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Co=[/git\s+push/,/npm\s+publish/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],Eo=[...Js,...Co],Ys=!1,Ks=null;function xc(t){Ys=t}function kc(){return Ys}function _c(t){Ks=t}function vc(t){for(let e of So)if(e.test(t))return e;return null}function Sc(t){if(/ssh\s/.test(t)&&To(t))return!1;for(let e of Eo)if(e.test(t))return!0;return!1}function Tc(t){for(let e of Js)if(e.test(t))return!0;return!1}function Cc(t,e={}){if(Ys)return Promise.resolve(!0);let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(s=>{let o=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(Ao(e.toolName),s(!0)):s(a!=="n")};if(Ks)Ks.question(`${Yt.yellow}${t} ${n}${Yt.reset}`,o);else{let r=bc.createInterface({input:process.stdin,output:process.stdout});r.question(`${Yt.yellow}${t} ${n}${Yt.reset}`,a=>{r.close(),o(a)})}})}var Ao=()=>{};function Ec(t){Ao=t}Mo.exports={FORBIDDEN_PATTERNS:So,SSH_SAFE_PATTERNS:zs,isSSHReadOnly:To,DANGEROUS_BASH:Eo,CRITICAL_BASH:Js,NOTABLE_BASH:Co,isForbidden:vc,isDangerous:Sc,isCritical:Tc,confirm:Cc,setAutoConfirm:xc,getAutoConfirm:kc,setReadlineInterface:_c,setAllowAlwaysHandler:Ec}});var rt=O((kp,Ro)=>{var Vs=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,s={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,s={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Ro.exports={BaseProvider:Vs}});var Po=O((_p,Oo)=>{var Vt=require("axios"),Ac=require("http"),Mc=require("https"),{BaseProvider:Rc}=rt(),Xt=new Ac.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Qt=new Mc.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),No={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:131072},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:128e3},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Xs=class extends Rc{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||No,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Vt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xt,httpsAgent:Qt}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Vt.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xt,httpsAgent:Qt})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.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(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let a of n.content)a.type==="text"?s.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:s.join(`
|
|
33
|
+
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||16384,c=await Vt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:s.temperature??this.temperature,num_predict:a}},{timeout:s.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Xt,httpsAgent:Qt});return this.normalizeResponse(c.data)}async stream(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||16384,c=s.onToken||(()=>{}),l;try{l=await Vt.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!0,options:{temperature:s.temperature??this.temperature,num_predict:a}},{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal,httpAgent:Xt,httpsAgent:Qt})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";s.signal&&s.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let x=h.split(`
|
|
34
|
+
`);h=x.pop()||"";for(let w of x){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{s.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_normalizeToolCalls(e){return e.map((n,s)=>({id:n.id||`ollama-${Date.now()}-${s}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};Oo.exports={OllamaProvider:Xs,OLLAMA_MODELS:No}});var Fo=O((vp,Do)=>{var{callChat:Nc}=re(),{estimateTokens:Qs}=xe(),Io=process.env.NEX_COMPACTION!=="false",qo=6,Lo=500,Oc=`Summarize this conversation history concisely. Focus on:
|
|
34
35
|
- What files were read, created, or modified
|
|
35
36
|
- Key decisions made and their rationale
|
|
36
37
|
- Current state of the task (what's done, what's pending)
|
|
37
38
|
- Any errors encountered and how they were resolved
|
|
38
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
39
|
-
${
|
|
40
|
-
tools: ${o}`}return`[${
|
|
39
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Pc(t){if(!Io||t.length<qo)return null;let e=[{role:"system",content:Oc},{role:"user",content:jo(t)}];try{let s=((await Nc(e,[],{temperature:0,maxTokens:Lo})).content||"").trim();if(!s)return null;let o=t.reduce((a,c)=>a+Qs(c.content||"")+(c.tool_calls?Qs(JSON.stringify(c.tool_calls)):0),0),r=Qs(s);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
40
|
+
${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function jo(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,s=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${s}
|
|
41
|
+
tools: ${o}`}return`[${n}] ${s}`}).join(`
|
|
41
42
|
|
|
42
|
-
`)}Do.exports={compactMessages:
|
|
43
|
-
`);if(o.length<=10){let
|
|
43
|
+
`)}Do.exports={compactMessages:Pc,formatMessagesForSummary:jo,COMPACTION_ENABLED:Io,COMPACTION_MIN_MESSAGES:qo,COMPACTION_SUMMARY_BUDGET:Lo}});var xe=O((Sp,Yo)=>{function Bo(){return re().getActiveModel()}var Ic={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},_t=new Map,Uo=1e3,Zt=new WeakMap,it=new Map,Wo=500,vt=null;function qc(){if(vt!==null)return vt;try{let e=Bo()?.provider||"ollama";return vt=Ic[e]||4,vt}catch{return 4}}function Lc(){vt=null}function He(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)}`,n=_t.get(e);if(n!==void 0)return n;let s=Math.ceil(t.length/qc());if(_t.size>=Uo){let o=Uo>>1,r=_t.keys();for(let a=0;a<o;a++)_t.delete(r.next().value)}return _t.set(e,s),s}function jc(t){if(Zt.has(t))return Zt.get(t);let e=Ho(t);if(it.has(e)){let s=it.get(e);return Zt.set(t,s),s}let n=JSON.stringify(t);if(it.size>=Wo){let s=Wo>>1,o=it.keys();for(let r=0;r<s;r++)it.delete(o.next().value)}return it.set(e,n),Zt.set(t,n),n}function Ho(t){let e=t.role||"",n=typeof t.content=="string"?t.content.substring(0,100):"",s=t.tool_calls?t.tool_calls.length:0;return`${e}:${n.length}:${s}`}function at(t){let n=4;if(t.content&&(n+=He(t.content)),t.tool_calls)for(let s of t.tool_calls){n+=4,n+=He(s.function?.name||"");let o=s.function?.arguments;typeof o=="string"?n+=He(o):o&&(n+=He(JSON.stringify(o)))}return n}function $e(t){let e=0;for(let n of t)e+=at(n);return e}function Dc(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 n=t?t.length:0,s=e.length,o=0;for(let r=n;r<s;r++)o+=at(e[r]);return o}function es(t){return!t||t.length===0?0:He(JSON.stringify(t))}function ts(){return Bo()?.contextWindow||32768}function Fc(t,e){let n=$e(t),s=es(e),o=n+s,r=ts(),a=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=at(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:s},messageCount:t.length}}var Go=.75,zo=.1,Ko=10,Uc=200,Wc=500;function Jo(t,e){if(!t||t.length<=e)return t;let s=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=s)return t;let o=t.split(`
|
|
44
|
+
`);if(o.length<=10){let p=Math.floor(s*.6),x=Math.floor(s*.4),w=t.substring(0,p),$=t.substring(t.length-x);return w+`
|
|
44
45
|
...(${t.length} chars total)...
|
|
45
|
-
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),
|
|
46
|
+
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(s*.4);for(let p=0;p<r&&l<u;p++)c.push(o[p]),l+=o[p].length+1;let d=[],f=0,m=Math.floor(s*.4);for(let p=o.length-1;p>=o.length-a&&f<m;p--)d.unshift(o[p]),f+=o[p].length+1;let h=o.length-c.length-d.length;return c.join(`
|
|
46
47
|
`)+`
|
|
47
48
|
...(${h} lines omitted, ${o.length} total)...
|
|
48
49
|
`+d.join(`
|
|
49
|
-
`)}function
|
|
50
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function
|
|
51
|
-
`),r=Math.floor(
|
|
52
|
-
`:"")+h,
|
|
53
|
-
`:"")+u;if(
|
|
54
|
-
|
|
55
|
-
... (${o.length-
|
|
56
|
-
|
|
57
|
-
`;return
|
|
58
|
-
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(
|
|
59
|
-
|
|
60
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){
|
|
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
|
|
62
|
-
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(
|
|
63
|
-
`)};return o.length>0&&(r.images=o),r}return
|
|
64
|
-
`);f=h.pop()||"";for(let
|
|
65
|
-
`)}}function
|
|
66
|
-
`)}function
|
|
67
|
-
`),
|
|
68
|
-
`),
|
|
69
|
-
`),o=[],r=
|
|
70
|
-
${y.bold}${y.cyan} Diff: ${t}${y.reset}`);let o=
|
|
71
|
-
${y.bold}${y.cyan} File exists \u2014 showing changes: ${t}${y.reset}`);let
|
|
72
|
-
${y.bold}${y.cyan} New file: ${t}${y.reset}`);let
|
|
73
|
-
`),n
|
|
74
|
-
${y.bold}${y.cyan} Side-by-side: ${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${y.reset}`);let a=
|
|
75
|
-
`)}function
|
|
76
|
-
${y.cyan}\u23FA${y.reset} ${y.bold}${o}(${
|
|
77
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let b=a.filter(E=>E.severity==="error").length,S=a.filter(E=>E.severity==="warn").length,_=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=[];
|
|
78
|
-
`),r=
|
|
79
|
-
${y.cyan}\u23FA${y.reset} ${y.bold}Create(${
|
|
80
|
-
`).filter(Boolean).map(e=>{let
|
|
81
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",
|
|
82
|
-
${
|
|
83
|
-
${
|
|
84
|
-
${
|
|
50
|
+
`)}function St(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:Wc,s=e==="aggressive"?50:e==="medium"?100:Uc;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>s?{...t,content:Jo(o,s)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>n&&(o.content=o.content.substring(0,n)+`
|
|
51
|
+
...(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 Bc(t,e,n={}){let s=n.threshold??Go,o=n.safetyMargin??zo,r=n.keepRecent??Ko,a=ts(),c=es(e),l=Math.floor(a*(s-o)),u=l-c,d=$e(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let x=Math.max(p,t.length-r),w=t.slice(p,x),$=t.slice(x),k=w.filter(C=>!C._compacted);if(k.length>=6)try{let{compactMessages:C}=Fo(),E=await C(k);if(E){let q=[...w.filter(I=>I._compacted),E.message],M=Be(h,q,$),N=$e(M);if(N+c<=l)return{messages:M,compressed:!0,compacted:!0,tokensRemoved:m-N};w=q}}catch{}let T=(f-l)/l,b=w.map(C=>St(C,"light")),S=Be(h,b,$),_=$e(S);if(_+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};if(b=w.map(C=>St(C,"medium")),S=Be(h,b,$),_=$e(S),_+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};if(b=w.map(C=>St(C,"aggressive")),S=Be(h,b,$),_=$e(S),_+c<=l)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_};for(;b.length>0&&_+c>u;){let C=b.shift();_-=at(C)}return S=Be(h,b,$),_=$e(S),{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-_}}function Be(t,e,n){let s=[];return t&&s.push(t),s.push(...e,...n),s}function Hc(t,e){if(!t)return"";if(He(t)<=e)return t;let s=e*4,o=t.split(`
|
|
52
|
+
`),r=Math.floor(s*.6),a=Math.floor(s*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
53
|
+
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
54
|
+
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
55
|
+
|
|
56
|
+
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
57
|
+
|
|
58
|
+
`;return c+m+u}var Gc=6;function zc(t,e){let n=ts(),s=es(e),o=Math.floor(n*.5)-s,r=$e(t),a=null,c=0;t.length>0&&t[0].role==="system"&&(a=t[0],c=1);let l=Math.max(c,t.length-Gc),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>St(p,"aggressive")),m=Be(a,f,d),h=$e(m);for(;f.length>0&&h>o;){let p=f.shift();h-=at(p)}return m=Be(a,f,d),h=$e(m),{messages:m,tokensRemoved:r-h}}Yo.exports={estimateTokens:He,estimateMessageTokens:at,estimateMessagesTokens:$e,estimateDeltaTokens:Dc,estimateToolsTokens:es,serializeMessage:jc,getMessageCacheKey:Ho,getContextWindow:ts,getUsage:Fc,compressMessage:St,compressToolResult:Jo,fitToContext:Bc,forceCompress:zc,truncateFileContent:Hc,invalidateTokenRatioCache:Lc,COMPRESSION_THRESHOLD:Go,SAFETY_MARGIN:zo,KEEP_RECENT:Ko}});var Zo=O((Cp,Qo)=>{var Vo=require("axios"),{BaseProvider:Kc}=rt(),{serializeMessage:Tp}=xe(),Xo={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},Zs=class extends Kc{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Xo,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(s,a),n.push(a);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.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 n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:s.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u=await Vo.post(`${this.baseUrl}/chat/completions`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||16384,c=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:s.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await Vo.post(`${this.baseUrl}/chat/completions`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},x="";s.signal&&s.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(`
|
|
59
|
+
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let S;try{S=JSON.parse(b)}catch{continue}let _=S.choices?.[0]?.delta;if(_&&(_.content&&(c(_.content),h+=_.content),_.tool_calls))for(let C of _.tool_calls){let E=C.index??0;p[E]||(p[E]={id:C.id||"",name:"",arguments:""}),C.id&&(p[E].id=C.id),C.function?.name&&(p[E].name+=C.function.name),C.function?.arguments&&(p[E].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{s.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`openai-${Date.now()}`,function:{name:n.name,arguments:n.arguments}}))}};Qo.exports={OpenAIProvider:Zs,OPENAI_MODELS:Xo}});var nr=O((Ap,sr)=>{var er=require("axios"),{BaseProvider:Jc}=rt(),{serializeMessage:Ep}=xe(),tr={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},Yc="2023-06-01",en=class extends Jc{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||tr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Yc}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 n="",s=[];for(let o of e){if(o.role==="system"){n+=(n?`
|
|
60
|
+
|
|
61
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);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)}s.push(r)}}return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.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:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.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 s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=s.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:c,temperature:s.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(n);f.length>0&&(d.tools=f);let m=await er.post(`${this.baseUrl}/messages`,d,{timeout:s.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),a=this.getModel(o),c=s.maxTokens||a?.maxTokens||8192,l=s.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:c,temperature:s.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(n);m.length>0&&(f.tools=m);let h;try{h=await er.post(`${this.baseUrl}/messages`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let x=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${x}`)}return new Promise((p,x)=>{let w="",$=[],k=-1,T="";s.signal&&s.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(`
|
|
62
|
+
`);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 q=P.content_block;q?.type==="tool_use"&&(k=$.length,$.push({id:q.id,name:q.name,inputJson:""}));break}case"content_block_delta":{let q=P.delta;q?.type==="text_delta"&&q.text&&(l(q.text),w+=q.text),q?.type==="input_json_delta"&&q.partial_json!==void 0&&k>=0&&($[k].inputJson+=q.partial_json);break}case"content_block_stop":k=-1;break;case"message_stop":p({content:w,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",b=>{s.signal?.aborted||x(new Error(`Stream error: ${b.message}`))}),h.data.on("end",()=>{p({content:w,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let n="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}_buildToolCalls(e){return e.filter(n=>n.name).map(n=>{let s={};if(n.inputJson)try{s=JSON.parse(n.inputJson)}catch{s=n.inputJson}return{id:n.id||`anthropic-${Date.now()}`,function:{name:n.name,arguments:s}}})}};sr.exports={AnthropicProvider:en,ANTHROPIC_MODELS:tr}});var ar=O((Rp,ir)=>{var or=require("axios"),{BaseProvider:Vc}=rt(),{serializeMessage:Mp}=xe(),rr={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},tn=class extends Vc{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||rr,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let a=this._messageStringCache.get(o);this._messageFormatCache.set(s,a),n.push(a);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.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 n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:s.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u=await or.post(`${this.baseUrl}/chat/completions`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),a=s.maxTokens||r?.maxTokens||8192,c=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:s.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await or.post(`${this.baseUrl}/chat/completions`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},x="";s.signal&&s.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(`
|
|
63
|
+
`);x=$.pop()||"";for(let k of $){let T=k.trim();if(!T||!T.startsWith("data: "))continue;let b=T.slice(6);if(b==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let S;try{S=JSON.parse(b)}catch{continue}let _=S.choices?.[0]?.delta;if(_&&(_.content&&(c(_.content),h+=_.content),_.tool_calls))for(let C of _.tool_calls){let E=C.index??0;p[E]||(p[E]={id:C.id||"",name:"",arguments:""}),C.id&&(p[E].id=C.id),C.function?.name&&(p[E].name+=C.function.name),C.function?.arguments&&(p[E].arguments+=C.function.arguments)}}}),d.data.on("error",w=>{s.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:n.name,arguments:n.arguments}}))}};ir.exports={GeminiProvider:tn,GEMINI_MODELS:rr}});var ur=O((Np,lr)=>{var ss=require("axios"),{BaseProvider:Xc}=rt(),cr="http://localhost:11434",sn=class extends Xc{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||cr,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 n=(await ss.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),a=32768;try{let c=await ss.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};a=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:s.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(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let a of n.content)a.type==="text"?s.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:s.join(`
|
|
64
|
+
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await ss.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:s.temperature??this.temperature,num_predict:s.maxTokens||8192}},{timeout:s.timeout||this.timeout});return this.normalizeResponse(r.data)}async stream(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=s.onToken||(()=>{}),a;try{a=await ss.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!0,options:{temperature:s.temperature??this.temperature,num_predict:s.maxTokens||8192}},{timeout:s.timeout||this.timeout,responseType:"stream",signal:s.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";s.signal&&s.signal.addEventListener("abort",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
65
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let x;try{x=JSON.parse(p)}catch{continue}if(x.message?.content&&(r(x.message.content),u+=x.message.content),x.message?.tool_calls&&(d=d.concat(x.message.tool_calls)),x.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{s.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}_normalizeToolCalls(e){return e.map((n,s)=>({id:n.id||`local-${Date.now()}-${s}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};lr.exports={LocalProvider:sn,DEFAULT_LOCAL_URL:cr}});var ct=O((Op,$r)=>{var Ge=require("fs"),nn=require("path"),dr={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},ns=[],qe={};function Qc(t,e,n,s){if(ns.push({provider:t,model:e,input:n,output:s}),qe[t]!==void 0){let o=hr(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
66
|
+
`)}}function on(t,e){let n=dr[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function fr(t){let e=on(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function mr(){let t={};for(let r of ns){let a=`${r.provider}:${r.model}`;t[a]||(t[a]={provider:r.provider,model:r.model,input:0,output:0}),t[a].input+=r.input,t[a].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:fr(r)})),n=e.reduce((r,a)=>r+a.cost,0),s=e.reduce((r,a)=>r+a.input,0),o=e.reduce((r,a)=>r+a.output,0);return{totalCost:n,totalInput:s,totalOutput:o,breakdown:e}}function Zc(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:s}=mr();if(s.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of s){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 + ${n.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
67
|
+
`)}function el(t,e,n,s){let o=on(t,e),r=(n*o.input+s*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function tl(){ns=[]}function sl(t,e){qe[t]=e}function nl(t){delete qe[t]}function ol(){return{...qe}}function pr(t){let e=0;for(let n of ns)n.provider===t&&(e+=fr(n));return e}function hr(t){let e=pr(t),n=qe[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let s=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:s}}function gr(){let t=nn.join(process.cwd(),".nex","config.json");if(Ge.existsSync(t))try{let e=JSON.parse(Ge.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(qe={...e.costLimits})}catch{}}function rl(){let t=nn.join(process.cwd(),".nex"),e=nn.join(t,"config.json"),n={};if(Ge.existsSync(e))try{n=JSON.parse(Ge.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=qe,Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0}),Ge.writeFileSync(e,JSON.stringify(n,null,2),"utf-8")}function il(){qe={}}gr();$r.exports={PRICING:dr,trackUsage:Qc,getSessionCosts:mr,formatCosts:Zc,formatCostHint:el,resetCosts:tl,getPricing:on,setCostLimit:sl,removeCostLimit:nl,getCostLimits:ol,getProviderSpend:pr,checkBudget:hr,loadCostLimits:gr,saveCostLimits:rl,resetCostLimits:il}});var os=O((Pp,yr)=>{var Tt=re(),al={"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 cl(){return Tt.getActiveModel()}function ll(t){return Tt.setActiveModel(t)}function ul(){return Tt.getModelNames()}function dl(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let s=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(s)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let s=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(s)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function fl(t,e){let{C:n}=Q(),{Spinner:s}=Q(),o=new s("Thinking...");o.start();let r=!0,a="";try{let c=await Tt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?o.stop():process.stdout.write(`${n.reset}
|
|
68
|
+
`),c}catch(c){throw o.stop(),c}}async function ml(t,e){return Tt.callChat(t,e)}yr.exports={MODELS:al,getActiveModel:cl,setActiveModel:ll,getModelNames:ul,callOllamaStream:fl,callOllama:ml,parseToolArgs:dl}});var xr=O((Ip,br)=>{var rs=require("path"),{C:y}=Q(),{confirm:pl,getAutoConfirm:hl}=Te(),wr=2e3;function Ct(t,e){let n=t.split(`
|
|
69
|
+
`),s=e.split(`
|
|
70
|
+
`),o=[],r=n.length,a=s.length;if(r>wr||a>wr){for(let f of n)o.push({type:"remove",line:f});for(let f of s)o.push({type:"add",line:f});return o}let c=Array.from({length:r+1},()=>new Array(a+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=a;m++)n[f-1]===s[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=r,u=a,d=[];for(;l>0||u>0;)l>0&&u>0&&n[l-1]===s[u-1]?(d.unshift({type:"same",line:n[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:s[u-1]}),u--):(d.unshift({type:"remove",line:n[l-1]}),l--);return d}function gl(t,e,n,s=3){console.log(`
|
|
71
|
+
${y.bold}${y.cyan} Diff: ${t}${y.reset}`);let o=Ct(e,n),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${y.gray} (no changes)${y.reset}`);return}let a=Math.max(0,r[0]-s),c=Math.min(o.length,r[r.length-1]+s+1);a>0&&console.log(`${y.gray} ...${y.reset}`);for(let l=a;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${y.red} - ${u.line}${y.reset}`);break;case"add":console.log(`${y.green} + ${u.line}${y.reset}`);break;default:console.log(`${y.gray} ${u.line}${y.reset}`)}}c<o.length&&console.log(`${y.gray} ...${y.reset}`),console.log()}function $l(t,e,n){console.log(`
|
|
72
|
+
${y.bold}${y.cyan} File exists \u2014 showing changes: ${t}${y.reset}`);let s=Ct(e,n),o=0;for(let a of s)a.type!=="same"&&o++;if(o===0){console.log(`${y.gray} (identical content)${y.reset}`);return}let r=0;for(let a of s){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 yl(t,e){console.log(`
|
|
73
|
+
${y.bold}${y.cyan} New file: ${t}${y.reset}`);let n=e.split(`
|
|
74
|
+
`),s=n.slice(0,20);for(let o of s)console.log(`${y.green} + ${o}${y.reset}`);n.length>20&&console.log(`${y.gray} ...+${n.length-20} more lines${y.reset}`),console.log()}async function wl(t){return hl()?!0:pl(` ${t}?`)}function bl(t,e,n,s){let o=s||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
75
|
+
${y.bold}${y.cyan} Side-by-side: ${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${y.reset}`);let a=Ct(e,n),c=[],l=0;for(;l<a.length;)if(a[l].type==="same")c.push({left:a[l].line,right:a[l].line,type:"same"}),l++;else if(a[l].type==="remove"){let h=[];for(;l<a.length&&a[l].type==="remove";)h.push(a[l].line),l++;let p=[];for(;l<a.length&&a[l].type==="add";)p.push(a[l].line),l++;let x=Math.max(h.length,p.length);for(let w=0;w<x;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",type:"changed"})}else a[l].type==="add"&&(c.push({left:"",right:a[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${y.gray}(no changes)${y.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let x=h.replace(/\x1b\[[0-9;]*m/g,"");return x.length>=p?h.substring(0,p):h+" ".repeat(p-x.length)};d>0&&console.log(` ${y.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${y.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${y.gray}${m(p.left,r)}${y.reset}\u2502${y.gray}${m(p.right,r)}${y.reset}`);else{let x=p.left?`${y.red}${m(p.left,r)}${y.reset}`:`${m("",r)}`,w=p.right?`${y.green}${m(p.right,r)}${y.reset}`:`${m("",r)}`;console.log(` ${x}\u2502${w}`)}}f<c.length&&console.log(` ${y.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${y.reset}
|
|
76
|
+
`)}function xl(t,e,n,s={}){let o=s.label||"Update",r=s.context||3,a=s.annotations||[],c=rs.isAbsolute(t)?rs.relative(process.cwd(),t):t,l=Ct(e,n),u=1,d=1;for(let b of l)b.type==="same"?(b.oldLine=u++,b.newLine=d++):b.type==="remove"?(b.oldLine=u++,b.newLine=null):(b.oldLine=null,b.newLine=d++);let f=0,m=0;for(let b of l)b.type==="add"?f++:b.type==="remove"&&m++;if(console.log(`
|
|
77
|
+
${y.cyan}\u23FA${y.reset} ${y.bold}${o}(${c})${y.reset}`),f===0&&m===0){console.log(` ${y.dim}\u23BF (no changes)${y.reset}
|
|
78
|
+
`);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=[];l.forEach((b,S)=>{b.type!=="same"&&x.push(S)});let w=[],$=null,k=null;for(let b of x){let S=Math.max(0,b-r),_=Math.min(l.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=l[C],P=E.newLine!=null?E.newLine:E.oldLine,q=String(P).padStart(4),M=E.type!=="remove"?a.filter(N=>N.line===E.newLine):[];E.type==="remove"?console.log(`${T}${y.red}${q} -${E.line}${y.reset}`):E.type==="add"?console.log(`${T}${y.green}${q} +${E.line}${y.reset}`):console.log(`${T}${y.dim}${q}${y.reset} ${E.line}`);for(let N of M){let I=y.cyan,L="\u2139";N.severity==="error"?(I=y.red,L="\u2716"):N.severity==="warn"&&(I=y.yellow,L="\u26A0"),console.log(`${T} ${I}${L} ${N.message}${y.reset}`)}}}console.log()}function kl(t,e,n={}){let s=rs.isAbsolute(t)?rs.relative(process.cwd(),t):t,o=e.split(`
|
|
79
|
+
`),r=n.annotations||[];console.log(`
|
|
80
|
+
${y.cyan}\u23FA${y.reset} ${y.bold}Create(${s})${y.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${y.red}${d} error${d!==1?"s":""}${y.dim}`),f>0&&h.push(`${y.yellow}${f} warning${f!==1?"s":""}${y.dim}`),m>0&&h.push(`${y.cyan}${m} info${m!==1?"s":""}${y.dim}`),a.push(`found ${h.join(", ")}`)}console.log(` ${y.dim}\u23BF ${a.join(", ")}${y.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=r.filter(p=>p.line===m);console.log(`${l}${y.green}${f} +${o[d]}${y.reset}`);for(let p of h){let x=y.cyan,w="\u2139";p.severity==="error"?(x=y.red,w="\u2716"):p.severity==="warn"&&(x=y.yellow,w="\u26A0"),console.log(`${l} ${x}${w} ${p.message}${y.reset}`)}}o.length>20&&console.log(`${l}${y.dim} ...+${o.length-20} more lines${y.reset}`),console.log()}br.exports={diffLines:Ct,showEditDiff:gl,showWriteDiff:$l,showNewFilePreview:yl,confirmFileChange:wl,showSideBySideDiff:bl,showClaudeDiff:xl,showClaudeNewFile:kl}});var ze=O((qp,vr)=>{var kr=require("util").promisify(require("child_process").exec),_l=require("util").promisify(require("child_process").execFile),{C:J}=Q();async function rn(t){try{let{stdout:e}=await kr(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function is(...t){try{let{stdout:e}=await _l("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function vl(){return await rn("git rev-parse --is-inside-work-tree")==="true"}async function Sl(){return await rn("git branch --show-current")}async function an(){try{let{stdout:t}=await kr("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
81
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function as(t=!1){return await rn(`git diff ${t?"--cached":""}`)||""}async function cn(){return(await an()).map(e=>e.file)}async function _r(){let t=await cn();if(t.length===0)return null;let e=await as(),s=await as(!0)||e,o=0,r=0;if(s){let d=s.split(`
|
|
82
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function Tl(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await is("checkout","-b",n)!==null?n:null}async function Cl(t){return await is("add","-A"),await is("commit","-m",t)?await is("rev-parse","--short","HEAD"):null}async function El(){let t=await _r();if(!t)return`${J.dim}No changes${J.reset}`;let e=[];e.push(`
|
|
83
|
+
${J.bold}${J.cyan}Git Diff Summary:${J.reset}`),e.push(` ${J.green}+${t.stats.additions}${J.reset} ${J.red}-${t.stats.deletions}${J.reset} in ${t.files.length} file(s)`),e.push(`
|
|
84
|
+
${J.bold}${J.cyan}Files:${J.reset}`);for(let n of t.files.slice(0,20))e.push(` ${J.dim}${n}${J.reset}`);return t.files.length>20&&e.push(` ${J.dim}...+${t.files.length-20} more${J.reset}`),e.push(`
|
|
85
|
+
${J.bold}${J.cyan}Suggested message:${J.reset}`),e.push(` ${J.cyan}${t.summary}${J.reset}
|
|
85
86
|
`),e.join(`
|
|
86
|
-
`)}async function
|
|
87
|
-
...(truncated)`:
|
|
87
|
+
`)}async function Al(){return(await an()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Ml(){let t=await cn();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let s of t.slice(0,10))e.push(` ${s}`);let n=await as();if(n){let s=n.length>5e3?n.substring(0,5e3)+`
|
|
88
|
+
...(truncated)`:n;e.push(`
|
|
88
89
|
DIFF:
|
|
89
|
-
${
|
|
90
|
-
`)}vr.exports={isGitRepo:
|
|
91
|
-
${
|
|
92
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
90
|
+
${s}`)}return e.join(`
|
|
91
|
+
`)}vr.exports={isGitRepo:vl,getCurrentBranch:Sl,getStatus:an,getDiff:as,getChangedFiles:cn,analyzeDiff:_r,createBranch:Tl,commit:Cl,formatDiffSummary:El,getDiffContext:Ml,getMergeConflicts:Al}});var ut=O((Lp,Sr)=>{var ln=require("fs").promises,Rl=50,Ce=[],lt=[];function Nl(t,e,n,s){for(Ce.push({tool:t,filePath:e,oldContent:n,newContent:s,timestamp:Date.now()});Ce.length>Rl;)Ce.shift();lt.length=0}async function Ol(){if(Ce.length===0)return null;let t=Ce.pop();if(t.oldContent===null)try{await ln.unlink(t.filePath)}catch{}else await ln.writeFile(t.filePath,t.oldContent,"utf-8");return lt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Pl(){if(lt.length===0)return null;let t=lt.pop();return await ln.writeFile(t.filePath,t.newContent,"utf-8"),Ce.push(t),{tool:t.tool,filePath:t.filePath}}function Il(t=10){return Ce.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function ql(){return Ce.length}function Ll(){return lt.length}function jl(){Ce.length=0,lt.length=0}Sr.exports={recordChange:Nl,undo:Ol,redo:Pl,getHistory:Il,getUndoCount:ql,getRedoCount:Ll,clearHistory:jl}});var Et=O((jp,Rr)=>{var fe=require("fs"),dt=require("path"),ce=[];function un(){return dt.join(process.cwd(),".nex","skills")}function Tr(){return dt.join(process.cwd(),".nex","config.json")}function Dl(){let t=un();return fe.existsSync(t)||fe.mkdirSync(t,{recursive:!0}),t}function dn(){let t=Tr();if(!fe.existsSync(t))return[];try{let e=JSON.parse(fe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Cr(t){let e=Tr(),n={};if(fe.existsSync(e))try{n=JSON.parse(fe.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t;let s=dt.dirname(e);fe.existsSync(s)||fe.mkdirSync(s,{recursive:!0}),fe.writeFileSync(e,JSON.stringify(n,null,2),"utf-8")}function Er(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let s=0;s<t.commands.length;s++){let o=t.commands[s];(!o.cmd||typeof o.cmd!="string")&&n.push(`commands[${s}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&n.push(`commands[${s}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let s=0;s<t.tools.length;s++){let o=t.tools[s];(!o.function||!o.function.name||typeof o.function.name!="string")&&n.push(`tools[${s}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&n.push(`tools[${s}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Ar(t){try{let e=fe.readFileSync(t,"utf-8").trim();return e?{name:dt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Mr(t){try{let e=require(t),{valid:n,errors:s}=Er(e,t);return n?{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}
|
|
92
|
+
${s.join(`
|
|
93
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Fl(){ce=[];let t=un();if(!fe.existsSync(t))return ce;let e=dn(),n;try{n=fe.readdirSync(t)}catch{return ce}for(let s of n){let o=dt.join(t,s),r;try{r=fe.statSync(o)}catch{continue}if(!r.isFile())continue;let a=null;s.endsWith(".md")?a=Ar(o):s.endsWith(".js")&&(a=Mr(o)),a&&(a.enabled=!e.includes(a.name),ce.push(a))}return ce}function Ul(){let t=[];for(let e of ce)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
93
94
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
94
95
|
${t.join(`
|
|
95
96
|
|
|
96
|
-
`)}`}function
|
|
97
|
-
`,
|
|
98
|
-
`);for(let
|
|
99
|
-
`):JSON.stringify(o)}function
|
|
100
|
-
Available tools: ${d.join(", ")}`}}if(!
|
|
97
|
+
`)}`}function Wl(){let t=[];for(let e of ce)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function Bl(){let t=[];for(let e of ce)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function Hl(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let s of ce)if(s.enabled){for(let o of s.tools)if(o.function.name===n&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function Gl(t){let[e,...n]=t.split(/\s+/),s=n.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(s)}catch(a){console.error(`Skill command error (${e}): ${a.message}`)}return!0}}return!1}function zl(){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 Kl(t){let e=ce.find(s=>s.name===t);if(!e)return!1;e.enabled=!0;let n=dn().filter(s=>s!==t);return Cr(n),!0}function Jl(t){let e=ce.find(s=>s.name===t);if(!e)return!1;e.enabled=!1;let n=dn();return n.includes(t)||(n.push(t),Cr(n)),!0}function Yl(){return ce}Rr.exports={initSkillsDir:Dl,loadAllSkills:Fl,getSkillInstructions:Ul,getSkillCommands:Wl,getSkillToolDefinitions:Bl,routeSkillCall:Hl,handleSkillCommand:Gl,listSkills:zl,enableSkill:Kl,disableSkill:Jl,getLoadedSkills:Yl,_getSkillsDir:un,_validateScriptSkill:Er,_loadMarkdownSkill:Ar,_loadScriptSkill:Mr}});var ls=O((Dp,Lr)=>{var{spawn:Vl}=require("child_process"),Xl=require("path"),Nr=require("fs"),Ee=new Map;function Ql(){return Xl.join(process.cwd(),".nex","config.json")}function fn(){let t=Ql();if(!Nr.existsSync(t))return{};try{return JSON.parse(Nr.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function cs(t,e,n={},s=1e4){return new Promise((o,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:n})+`
|
|
98
|
+
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},s);function d(m){l+=m.toString();let h=l.split(`
|
|
99
|
+
`);for(let p of h)if(p.trim())try{let x=JSON.parse(p);if(x.id===a){f(),x.error?r(new Error(`MCP error: ${x.error.message||JSON.stringify(x.error)}`)):o(x.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Or(t,e){if(Ee.has(t))return Ee.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],s={};for(let a of n)process.env[a]&&(s[a]=process.env[a]);let o=Vl(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...s,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await cs(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await cs(o,"tools/list",{});return r.tools=a&&a.tools||[],Ee.set(t,r),r}catch(a){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function Pr(t){let e=Ee.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ee.delete(t),!0}function Zl(){for(let[t]of Ee)Pr(t)}async function Ir(t,e,n={}){let s=Ee.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await cs(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
100
|
+
`):JSON.stringify(o)}function qr(){let t=[];for(let[e,n]of Ee)for(let s of n.tools)t.push({server:e,name:s.name,description:s.description||"",inputSchema:s.inputSchema||{type:"object",properties:{}}});return t}function eu(){return qr().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function tu(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let s=n[0],o=n.slice(1).join("_");return Ir(s,o,e)}function su(){let t=fn();return Object.entries(t).map(([e,n])=>{let s=Ee.get(e);return{name:e,command:n.command,connected:!!s,toolCount:s?s.tools.length:0}})}async function nu(){let t=fn(),e=[];for(let[n,s]of Object.entries(t))try{let o=await Or(n,s);e.push({name:n,tools:o.tools.length})}catch(o){e.push({name:n,tools:0,error:o.message})}return e}Lr.exports={loadMCPConfig:fn,sendRequest:cs,connectServer:Or,disconnectServer:Pr,disconnectAll:Zl,callTool:Ir,getAllTools:qr,getMCPToolDefinitions:eu,routeMCPCall:tu,listServers:su,connectAll:nu}});var mn=O((Fp,Ur)=>{var{getSkillToolDefinitions:ou}=Et(),{getMCPToolDefinitions:ru}=ls(),us=new Map;function jr(){let{TOOL_DEFINITIONS:t}=Ke();return[...t,...ou(),...ru()]}function Dr(t){if(us.has(t))return us.get(t);let n=jr().find(o=>o.function.name===t);if(!n)return null;let s=n.function.parameters;return us.set(t,s),s}function iu(){us.clear()}function ds(t,e){if(!t||e.length===0)return null;let n=null,s=1/0;for(let o of e){let r=Fr(t.toLowerCase(),o.toLowerCase());r<s&&(s=r,n=o)}return s<=Math.ceil(t.length/2)?n:null}function Fr(t,e){let n=t.length,s=e.length,o=Array.from({length:n+1},()=>Array(s+1).fill(0));for(let r=0;r<=n;r++)o[r][0]=r;for(let r=0;r<=s;r++)o[0][r]=r;for(let r=1;r<=n;r++)for(let a=1;a<=s;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[n][s]}function au(t,e){let n=Dr(t);if(n===null){let d=jr().map(m=>m.function.name),f=ds(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
101
|
+
Available tools: ${d.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let s=n.required||[],o=Object.keys(n.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of s)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ds(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${n.properties[u]?.description||n.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=ds(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||a.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!n.properties[u])continue;let d=n.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return a.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
101
102
|
`+a.map(u=>` - ${u}`).join(`
|
|
102
103
|
`)+`
|
|
103
104
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(
|
|
105
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Ur.exports={validateToolArgs:au,closestMatch:ds,levenshtein:Fr,getCachedSchema:Dr,clearSchemaCache:iu}});var Gr=O((Up,Hr)=>{var{levenshtein:fs}=mn(),cu=200,lu=.3,uu=2;function pn(t){return t.replace(/\r\n/g,`
|
|
105
106
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
107
|
-
`).map(e=>{let
|
|
108
|
-
`)}function
|
|
109
|
-
`),r=
|
|
110
|
-
`),a=
|
|
111
|
-
`),
|
|
112
|
-
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(
|
|
107
|
+
`).replace(/\t/g," ".repeat(uu)).split(`
|
|
108
|
+
`).map(e=>{let n=e.replace(/\s+$/,""),s=n.match(/^(\s*)(.*)/);if(!s)return n;let[,o,r]=s;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
109
|
+
`)}function du(t,e){if(t.includes(e))return e;let n=pn(t),s=pn(e);if(!n.includes(s))return null;let o=t.split(`
|
|
110
|
+
`),r=n.split(`
|
|
111
|
+
`),a=s.split(`
|
|
112
|
+
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return o.slice(u,u+a.length).join(`
|
|
113
|
+
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(s)!==-1)return o[u]}return null}function fu(t,e){if(!t||!e)return null;let n=t.split(`
|
|
113
114
|
`),o=e.split(`
|
|
114
|
-
`).length;return
|
|
115
|
-
`),u=
|
|
116
|
-
`),h=
|
|
117
|
-
`),
|
|
118
|
-
`).filter(Boolean),
|
|
115
|
+
`).length;return n.length===0||o===0?null:o===1?mu(n,e):hu(n,e,o)}function Wr(t){return Math.max(1,Math.floor(t/cu))}function Br(t,e){return t<=Math.ceil(e*lu)}function mu(t,e){let n=e.trim(),s=Wr(t.length),o=null,r=1/0;for(let a=0;a<t.length;a+=s){let c=t[a];if(!c.trim())continue;let l=fs(c.trim(),n);l<r&&(r=l,o={text:c,distance:l,line:a+1})}return o&&s>1&&(o=pu(t,n,o,s)||o,r=o.distance),Br(r,e.length)?o:null}function pu(t,e,n,s){let o=n.line-1,r=Math.max(0,o-s),a=Math.min(t.length-1,o+s),c=n.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=fs(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function hu(t,e,n){let s=t.length-n+1;if(s<=0)return null;let o=Wr(s),r=null,a=1/0;for(let c=0;c<s;c+=o){let l=t.slice(c,c+n).join(`
|
|
116
|
+
`),u=fs(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=gu(t,e,r,o,n,s)||r,a=r.distance),Br(a,e.length)?r:null}function gu(t,e,n,s,o,r){let a=n.line-1,c=Math.max(0,a-s),l=Math.min(r-1,a+s),u=n.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
117
|
+
`),h=fs(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Hr.exports={normalizeWhitespace:pn,fuzzyFindText:du,findMostSimilar:fu}});var Kr=O((Bp,zr)=>{var{C:Wp}=Q(),$u=[{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}],yu=[{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 wu(t,e){let n=e.split(`
|
|
118
|
+
`),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let a=n[r],c=r+1;for(let l of $u)l.regex.test(a)&&s.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of yu)l.ext&&!l.ext.includes(o)||l.regex.test(a)&&s.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&s.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),s}zr.exports={runDiagnostics:wu}});var $n=O((Hp,Vr)=>{var bu=require("fs").promises,Jr=require("path"),{exec:xu}=require("util").promisify(require("child_process").exec),ft=[],gn=null,ms=!1,hn=0,ku=6e4;function Yr(t){return!(ft.length===0||gn!==t||Date.now()-hn>ku)}async function _u(t){if(!ms&&!Yr(t)){ms=!0,gn=t;try{try{let{stdout:s}=await xu("rg --files",{cwd:t,timeout:5e3});ft=s.split(`
|
|
119
|
+
`).filter(Boolean),hn=Date.now(),ms=!1;return}catch{}let e=[],n=async(s,o)=>{let r;try{r=await bu.readdir(s,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let c=o?`${o}/${a.name}`:a.name;a.isDirectory()?await n(Jr.join(s,a.name),c):e.push(c)}};await n(t,""),ft=e,hn=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{ms=!1}}}function vu(){return ft}function Su(){return gn}function Tu(t){return ft.filter(e=>Jr.basename(e)===t)}function Cu(t){let e=t.toLowerCase();return ft.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}Vr.exports={refreshIndex:_u,getFileIndex:vu,getIndexedCwd:Su,findFileInIndex:Tu,searchIndex:Cu,isIndexValid:Yr}});var Mt=O((Gp,Zr)=>{var yn=null,Ae=null,At=null,Xr=`Playwright is not installed. Install with:
|
|
119
120
|
npm install playwright && npx playwright install chromium
|
|
120
|
-
Then restart nex-code.`;function Qr(){if(
|
|
121
|
-
...(truncated)`:""),links:
|
|
122
|
-
`)}function
|
|
121
|
+
Then restart nex-code.`;function Qr(){if(At!==null)return At;try{require("playwright"),At=!0}catch{At=!1}return At}async function ps(){if(!Qr())throw new Error(Xr);return yn||(yn=require("playwright")),(!Ae||!Ae.isConnected())&&(Ae=await yn.chromium.launch({headless:!0})),Ae}async function Eu(){if(Ae){try{await Ae.close()}catch{}Ae=null}}process.on("exit",()=>{if(Ae)try{Ae.close()}catch{}});async function Au(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let o=await(await ps()).newPage();try{await o.goto(t,{waitUntil:n,timeout:e});let r=await o.title(),a=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
122
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function Mu(t,{width:e=1280,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let a=await(await ps()).newPage();try{await a.setViewportSize({width:e,height:n}),await a.goto(t,{waitUntil:"networkidle",timeout:o});let c=await a.screenshot({type:"png",fullPage:s}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await a.title(),url:a.url()}}finally{await a.close()}}async function Ru(t,{selector:e,text:n,timeout:s=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await ps()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),n?await r.getByText(n,{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 Nu(t,{selector:e,value:n,submit:s=!1,timeout:o=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let a=await(await ps()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await a.fill(e,String(n)),s&&(await a.keyboard.press("Enter"),await a.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${s?`Submitted \u2192 ${a.url()}`:"Not submitted."}`}finally{await a.close()}}Zr.exports={isPlaywrightAvailable:Qr,browserNavigate:Au,browserScreenshot:Mu,browserClick:Ru,browserFill:Nu,closeBrowser:Eu,INSTALL_MSG:Xr}});var hs=O((zp,ei)=>{var{C:B}=Q(),Nt="",ie=[],Rt=0,Je=null;function Ou(t){Je=t}function Pu(t,e){Nt=t,ie=[],Rt=0;for(let s of e){Rt++;let o=`t${Rt}`;ie.push({id:o,description:s.description||s.title||s.name||s.task||`Task ${Rt}`,status:"pending",dependsOn:s.depends_on||[],result:null})}let n=ie.map(s=>({...s}));return Je&&Je("create",{name:t,tasks:n}),n}function Iu(t,e,n){let s=ie.find(o=>o.id===t);return s?(s.status=e,n!==void 0&&(s.result=n),Je&&Je("update",{id:t,status:e,result:n}),{...s}):null}function qu(){return{name:Nt,tasks:ie.map(t=>({...t}))}}function Lu(){Nt="",ie=[],Rt=0,Je&&Je("clear",{})}function ju(){return ie.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=ie.find(s=>s.id===e);return n&&n.status==="done"}))}function Du(){if(ie.length===0)return`${B.dim}No active tasks${B.reset}`;let t=[];Nt&&(t.push(` ${B.bold}${B.cyan}Tasks: ${Nt}${B.reset}`),t.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`));for(let o of 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 c=o.dependsOn.length>0?` ${B.dim}(after: ${o.dependsOn.join(", ")})${B.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${a}${r}${B.reset} ${B.bold}${o.id}${B.reset} ${u.padEnd(40)} ${a}${l}${B.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${B.dim}\u2192 ${d}${B.reset}`)}}let e=ie.filter(o=>o.status==="done").length,n=ie.filter(o=>o.status==="failed").length,s=ie.length;return t.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`),t.push(` ${B.dim}${e}/${s} done${n>0?`, ${n} failed`:""}${B.reset}`),t.join(`
|
|
123
|
+
`)}function Fu(){return ie.length>0&&ie.some(t=>t.status==="pending"||t.status==="in_progress")}ei.exports={createTasks:Pu,updateTask:Iu,getTaskList:qu,clearTasks:Lu,getReadyTasks:ju,renderTaskList:Du,setOnChange:Ou,hasActiveTasks:Fu}});var bn=O((Kp,si)=>{var{getActiveModel:Uu,getActiveProviderName:Wu}=re(),Ot={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list"],full:null},Pt={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},It={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ke={};function ti(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(ke=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{ke={}}}ti();function wn(){let e=Uu()?.id,n=Wu();return e&&ke[e]?ke[e]:n&&ke[`${n}:*`]?ke[`${n}:*`]:e&&Pt[e]?Pt[e]:n&&It[n]?It[n]:"full"}function Bu(t,e){return t&&ke[t]?ke[t]:e&&ke[`${e}:*`]?ke[`${e}:*`]:t&&Pt[t]?Pt[t]:e&&It[e]?It[e]:"full"}function Hu(t,e){let n=e||wn();if(n==="full"||!Ot[n])return t;let s=new Set(Ot[n]);return t.filter(o=>s.has(o.function.name))}function Gu(){let t=wn(),e=Ot[t]?Ot[t].length:"all";return{tier:t,toolCount:e}}si.exports={filterToolsForModel:Hu,getActiveTier:wn,getModelTier:Bu,getTierInfo:Gu,TIERS:Ot,MODEL_TIERS:Pt,PROVIDER_DEFAULT_TIER:It,loadConfigOverrides:ti}});var pi=O((Yp,mi)=>{var{callStream:zu,getActiveProviderName:$s,getActiveModelId:Ku,getConfiguredProviders:Ju,getProvider:ni,getActiveProvider:oi,parseModelSpec:ri}=re(),{parseToolArgs:Yu}=os(),{filterToolsForModel:Vu,getModelTier:gs}=bn(),{trackUsage:Xu}=ct(),{MultiProgress:Qu,C:Jp}=Q(),Zu=15,ii=5,ai=3,ys=new Map;function ed(t,e){let n=ys.get(t);return n&&n!==e?!1:(ys.set(t,e),!0)}function xn(t){ys.delete(t)}function kn(){ys.clear()}function ci(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function li(t,e,n){let s;for(let o=0;o<=ai;o++)try{return await zu(t,e,n)}catch(r){if(s=r,o<ai&&ci(r)){let a=Math.min(2e3*Math.pow(2,o),15e3);await new Promise(c=>setTimeout(c,a).unref());continue}throw r}throw s}var td=new Set(["ask_user","task_list","spawn_agents"]),sd=new Set(["write_file","edit_file","patch_file"]),nd=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,od=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ui(t){return od.test(t)?"full":nd.test(t)?"essential":"standard"}function di(t){let e=Ju(),n=$s(),s=[...e].sort((o,r)=>(o.name===n?-1:1)-(r.name===n?-1:1));for(let o of s)for(let r of o.models)if(gs(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var rd={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function _n(t){if(t.model){let{provider:o,model:r}=ri(t.model),a=o?ni(o):oi(),c=o||$s();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=gs(r,c);return{provider:c,model:r,tier:l}}}let e=ui(t.task),n=rd[e];if(n){let{provider:o,model:r}=ri(n),a=o?ni(o):oi(),c=o||$s();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=gs(r,c);return{provider:c,model:r,tier:l}}}let s=di(e);if(s){let o=gs(s.model,s.provider);return{provider:s.provider,model:s.model,tier:o}}return{provider:null,model:null,tier:null}}async function fi(t,e={}){let n=Math.min(t.max_iterations||10,Zu),s=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},a=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
123
124
|
|
|
124
125
|
TASK: ${t.task}
|
|
125
126
|
${t.context?`
|
|
@@ -141,93 +142,95 @@ TOOL STRATEGY:
|
|
|
141
142
|
ERROR RECOVERY:
|
|
142
143
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
143
144
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
144
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
${
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
`)}function xi(t,e,s){let n=Cs(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var $i=!1;async function Ts(){if(!$i){$i=!0;try{let{stdout:t}=await Ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var yd=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function ue(t){let e=de.isAbsolute(t)?de.resolve(t):de.resolve(process.cwd(),t);for(let s of yd)if(s.test(e))return null;return e}var wd=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}}];async function yi(t,e,s={}){switch(t){case"bash":{let n=e.command,o=cd(n);if(o)return`BLOCKED: Command matches forbidden pattern: ${o}`;if(s.autoConfirm?pi(n):ud(n)){let l=pi(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
152
|
-
${H.yellow}${l}: ${n}${H.reset}`),!await dd(" Execute?"))return"CANCELLED: User declined to execute this command."}if($d.test(n.trim())){s.silent||console.log(`${H.dim} \u25B6 interactive: ${n}${H.reset}`);let l=ld("sh",["-c",n],{stdio:"inherit",cwd:process.cwd()});return l.error?`ERROR: ${l.error.message}`:l.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${l.status})`}let a=s.silent?null:new wi(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);a&&a.start();try{let{stdout:l,stderr:c}=await Ae(n,{cwd:process.cwd(),timeout:9e4,maxBuffer:5242880});return a&&a.stop(),l||c||"(no output)"}catch(l){a&&a.stop();let c=(l.stderr||l.stdout||l.message||"").toString().substring(0,5e3),u=bi(c,n);return`EXIT ${l.code||1}
|
|
153
|
-
${
|
|
154
|
-
|
|
145
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=_n(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ke(),x=Vu(h.filter($=>!td.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
146
|
+
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<n;$++){let k=await li(l,x,w);if(!k||typeof k!="object")throw new Error("Empty or invalid response from provider");if(k.usage){let E=k.usage.prompt_tokens||0,P=k.usage.completion_tokens||0;r.input+=E,r.output+=P;let q=d||$s(),M=f||Ku();Xu(q,M,E,P)}let T=k.content||"",b=k.tool_calls,S={role:"assistant",content:T||""};if(b&&b.length>0&&(S.tool_calls=b),l.push(S),!b||b.length===0){for(let E of a)xn(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,q=Yu(E.function.arguments),M=E.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!q)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${P}`,tool_call_id:M});if(sd.has(P)&&q.path){let N=require("path"),I=N.isAbsolute(q.path)?q.path:N.resolve(process.cwd(),q.path);if(!ed(I,s))return Promise.resolve({role:"tool",content:`ERROR: File '${q.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:M});a.add(I)}return o.push(P),p(P,q,{autoConfirm:!0,silent:!0}).then(N=>{let I=String(N??"");return{role:"tool",content:I.length>2e4?I.substring(0,2e4)+`
|
|
147
|
+
...(truncated)`:I,tool_call_id:M}}).catch(N=>({role:"tool",content:`ERROR: ${N.message}`,tool_call_id:M}))}),C=await Promise.all(_);l.push(...C),e.onUpdate&&e.onUpdate(`step ${$+1}/${n}`)}for(let $ of a)xn($);return{task:t.task,status:"done",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let k of a)xn(k);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function id(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ii)return`ERROR: Max ${ii} parallel agents allowed, got ${e.length}`;let n=e.map(r=>_n(r)),s=e.map((r,a)=>{let c=n[a],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${a+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new Qu(s);o.start();try{let r=e.map((d,f)=>{let m=n[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return fi(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="done"?"done":"error"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),a=await Promise.all(r);o.stop(),kn();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<a.length;d++){let f=a[d],m=f.status==="done"?"\u2713":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
148
|
+
`)}catch(r){return o.stop(),kn(),`ERROR: Sub-agent execution failed: ${r.message}`}}mi.exports={runSubAgent:fi,executeSpawnAgents:id,clearAllLocks:kn,classifyTask:ui,pickModelForTier:di,resolveSubAgentModel:_n,isRetryableError:ci,callWithRetry:li}});var Ke=O((Qp,vi)=>{var K=require("fs").promises,ad=require("fs"),ue=require("path"),Me=require("util").promisify(require("child_process").exec),hi=require("util").promisify(require("child_process").execFile),{spawnSync:cd}=require("child_process"),vn=require("axios"),{isForbidden:ld,isDangerous:ud,isCritical:gi,confirm:dd}=Te(),{showClaudeDiff:ws,showClaudeNewFile:fd,showEditDiff:Vp,confirmFileChange:qt}=xr(),{C:H,Spinner:xi,getToolSpinnerText:md}=Q(),{isGitRepo:Sn,getCurrentBranch:$i,getStatus:pd,getDiff:hd}=ze(),{recordChange:bs}=ut(),{fuzzyFindText:yi,findMostSimilar:Cn}=Gr(),{runDiagnostics:Lt}=Kr(),{findFileInIndex:gd,getFileIndex:Xp}=$n(),$d=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,yd=/^ssh\s/,wd=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function xs(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=le(e);if(n&&await K.access(n).then(()=>!0).catch(()=>!1))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let s=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=ue.extname(t);if(!o)for(let a of s){let c=le(t+a);if(c&&await K.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(o){let a=t.replace(/\.[^.]+$/,"");for(let c of s){if(c===o)continue;let l=le(a+c);if(l&&await K.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=ue.basename(t);if(r&&r.length>2)try{let a=gd(r).map(c=>le(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${ue.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
149
|
+
${a.map(l=>ue.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
150
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function bd(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function ki(t,e){let n=[];if(/command not found|not recognized/i.test(t)){let s=e.match(/^(\S+)/),o=s?s[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let s=t.match(/Cannot find module '([^']+)'/),o=s?s[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?n.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let s=t.match(/port (\d+)|:(\d+)/),o=s?s[1]||s[2]:"";n.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let s=t.match(/curl:\s*\((\d+)\)/),o=s?parseInt(s[1],10):null;o===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let s=t.match(/port (\d+)/),o=s?s[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),n.length===0?t:t+`
|
|
151
|
+
|
|
152
|
+
`+n.join(`
|
|
153
|
+
`)}function _i(t,e,n){let s=Cn(t,e);if(!s)return null;let o=Math.max(3,Math.ceil(e.length*.05));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var wi=!1;async function Tn(){if(!wi){wi=!0;try{let{stdout:t}=await Me("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Me('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Me("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Me("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var xd=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function le(t){let e=ue.isAbsolute(t)?ue.resolve(t):ue.resolve(process.cwd(),t);for(let n of xd)if(n.test(e))return null;return e}var kd=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}}];async function bi(t,e,n={}){switch(t){case"bash":{let s=e.command,o=ld(s);if(o){let l=bd(s);return`BLOCKED: Command matches forbidden pattern: ${o}${l?`
|
|
154
|
+
HINT: ${l}`:""}`}if(n.autoConfirm?gi(s):ud(s)){let l=gi(s)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
155
|
+
${H.yellow}${l}: ${s}${H.reset}`),!await dd(" Execute?"))return"CANCELLED: User declined to execute this command."}let a=yd.test(s.trim())&&!wd.test(s.trim());if($d.test(s.trim())||a){n.silent||console.log(`${H.dim} \u25B6 interactive: ${s}${H.reset}`);let l=cd("sh",["-c",s],{stdio:"inherit",cwd:process.cwd()});return l.error?`ERROR: ${l.error.message}`:l.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${l.status})`}let c=n.silent?null:new xi(`Running: ${s.substring(0,60)}${s.length>60?"...":""}`);c&&c.start();try{let{stdout:l,stderr:u}=await Me(s,{cwd:process.cwd(),timeout:9e4,maxBuffer:5242880});return c&&c.stop(),l||u||"(no output)"}catch(l){c&&c.stop();let u=(l.stderr||l.stdout||l.message||"").toString().substring(0,5e3),d=ki(u,s);return`EXIT ${l.code||1}
|
|
156
|
+
${d}`}}case"read_file":{let s=le(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(s).then(()=>!0).catch(()=>!1)){let m=await xs(e.path);if(m.fixedPath)s=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),s)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
157
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await ad.promises.open(s,"r"),{bytesRead:c}=await a.read(r,0,8192,0);await a.close();for(let m=0;m<c;m++)if(r[m]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let l=await K.readFile(s,"utf-8");if(!l&&(await K.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let u=l.split(`
|
|
155
158
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
|
|
156
|
-
`)}case"write_file":{await
|
|
157
|
-
`+d.message:""}`}let r=await
|
|
159
|
+
`)}case"write_file":{await Tn();let s=le(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await K.access(s).then(()=>!0).catch(()=>!1),r=null;if(n.autoConfirm)o&&(r=await K.readFile(s,"utf-8"));else if(o){r=await K.readFile(s,"utf-8");let l=await Lt(s,e.content);if(ws(s,r,e.content,{annotations:l}),!await qt("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await Lt(s,e.content);if(fd(s,e.content,{annotations:l}),!await qt("Create"))return"CANCELLED: User declined to create file."}let a=ue.dirname(s);return await K.access(a).then(()=>!0).catch(()=>!1)||await K.mkdir(a,{recursive:!0}),await K.writeFile(s,e.content,"utf-8"),bs("write_file",s,r,e.content),`Written: ${s} (${e.content.length} chars)`}case"edit_file":{await Tn();let s=le(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(s).then(()=>!0).catch(()=>!1)){let d=await xs(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),s)}${H.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
160
|
+
`+d.message:""}`}let r=await K.readFile(s,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=yi(r,e.old_text);if(d)a=d,c=!0,console.log(`${H.dim} \u2713 fuzzy whitespace match applied${H.reset}`);else{let f=_i(r,e.old_text,e.new_text);if(f){if(!n.autoConfirm){let p=await Lt(s,f.content);if(ws(s,r,f.content,{annotations:p}),!await qt(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await K.writeFile(s,f.content,"utf-8"),bs("edit_file",s,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: ${s} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=Cn(r,e.old_text);return m?`ERROR: old_text not found in ${s}
|
|
158
161
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
159
|
-
${m.text}`:`ERROR: old_text not found in ${
|
|
160
|
-
`)||"(empty)"}case"search_files":{let
|
|
162
|
+
${m.text}`:`ERROR: old_text not found in ${s}`}}if(!n.autoConfirm){let d=r.split(a).join(e.new_text),f=await Lt(s,d);if(ws(s,r,d,{annotations:f}),!await qt(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await K.writeFile(s,u,"utf-8"),bs("edit_file",s,r,u),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}case"list_directory":{let s=le(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(s).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=le(u),f=await K.access(d).then(()=>!0).catch(()=>!1);if(d&&f)s=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await K.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ue.join(u,h.name),d+1,f+" ")}};return await l(s,1,""),c.join(`
|
|
163
|
+
`)||"(empty)"}case"search_files":{let s=le(e.path);if(!s)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,s);try{let{stdout:r}=await hi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
161
164
|
`).slice(0,50).join(`
|
|
162
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
165
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?le(e.path):o,a=e.pattern,c=b=>{let S=b.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${S}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=$n(),x=f(),w=m();p(r)||(await h(r),x=f());let $=x.filter(b=>l.test(b)||d.test(ue.basename(b))).map(b=>ue.join(r,b));if($.length===0)return"(no matches)";let k=$.length>200,T=$.slice(0,200).join(`
|
|
163
166
|
`);return k?`${T}
|
|
164
167
|
|
|
165
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let
|
|
168
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let s=e.path?le(e.path):process.cwd(),o=["-rn","-E"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,s);try{let{stdout:r}=await hi("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
166
169
|
`).slice(0,100).join(`
|
|
167
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
168
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await
|
|
170
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Tn();let s=le(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await K.access(s).then(()=>!0).catch(()=>!1)){let m=await xs(e.path);if(m.fixedPath)s=m.fixedPath,console.log(`${H.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ue.relative(process.cwd(),s)}${H.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
171
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await K.readFile(s,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:h,new_text:p}=r[m];if(a.includes(h))c.push({old_text:h,new_text:p});else{let x=yi(a,h);if(x)c.push({old_text:x,new_text:p}),l=!0;else{let w=Cn(a,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${s}
|
|
169
172
|
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
170
|
-
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${
|
|
173
|
+
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${s}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!n.autoConfirm){let m=await Lt(s,d);if(ws(s,a,d,{annotations:m}),!await qt(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await K.writeFile(s,d,"utf-8"),bs("patch_file",s,a,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${s} (${r.length} replacements)${f}`}case"web_fetch":{let s=e.url,o=e.max_length||1e4;try{let r=await vn.get(s,{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 ${s}: ${r.message}`}}case"web_search":{let s=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await vn.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",a=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
171
174
|
|
|
172
|
-
${r}`;return a.length>0&&(
|
|
175
|
+
${r}`;return a.length>0&&(c+=`
|
|
173
176
|
|
|
174
177
|
Sources:
|
|
175
|
-
`+a.slice(0,
|
|
176
|
-
`)),
|
|
178
|
+
`+a.slice(0,s).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
179
|
+
`)),c}catch(o){console.error(`${H.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${H.reset}`)}try{let r=(await vn.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&a.length<s;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{a.push({title:d,url:decodeURIComponent(u)})}catch{a.push({title:d,url:u})}}return a.length===0?"(no results)":a.map((u,d)=>`${d+1}. ${u.title}
|
|
177
180
|
${u.url}`).join(`
|
|
178
181
|
|
|
179
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:
|
|
182
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:s}=Mt();try{let o=await s(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
180
183
|
|
|
181
184
|
Links:
|
|
182
185
|
`+o.links.map(a=>` ${a.text} \u2192 ${a.href}`).join(`
|
|
183
186
|
`):"";return`Title: ${o.title}
|
|
184
187
|
URL: ${o.url}
|
|
185
188
|
|
|
186
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:
|
|
189
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:s}=Mt();try{let o=await s(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
187
190
|
Title: ${o.title}
|
|
188
191
|
URL: ${o.url}
|
|
189
192
|
|
|
190
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:
|
|
191
|
-
${H.cyan}${H.bold} ? ${
|
|
192
|
-
Clean working tree (no changes)`;let r=[`Branch: ${
|
|
193
|
-
`)}case"git_diff":{if(!await
|
|
193
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:s}=Mt();try{return await s(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:s}=Mt();try{return await s(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let s=e.question;return new Promise(o=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});console.log(`
|
|
194
|
+
${H.cyan}${H.bold} ? ${s}${H.reset}`),r.question(`${H.cyan} > ${H.reset}`,a=>{r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await Sn())return"ERROR: Not a git repository";let s=await $i()||"(detached)",o=await pd();if(o.length===0)return`Branch: ${s}
|
|
195
|
+
Clean working tree (no changes)`;let r=[`Branch: ${s}`,`Changed files (${o.length}):`];for(let a of o){let c=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${c}: ${a.file}`)}return r.join(`
|
|
196
|
+
`)}case"git_diff":{if(!await Sn())return"ERROR: Not a git repository";let s;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{s=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{s=""}}else s=await hd(!!e.staged);return s||"(no diff)"}case"git_log":{if(!await Sn())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:s,updateTask:o,getTaskList:r,renderTaskList:a,hasActiveTasks:c}=hs(),{getActiveTaskProgress:l}=Q(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=s(e.name,e.tasks);return u||console.log(`
|
|
194
197
|
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
195
198
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
196
199
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
197
200
|
`+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:
|
|
201
|
+
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:s}=pi();return s(e)}case"switch_model":{let{setActiveModel:s,getActiveProviderName:o,getActiveModelId:r}=re();return s(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let s=Math.min(e.limit||10,30),o=["run","list","--limit",String(s),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Me(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
199
202
|
`)}catch(r){let a=(r.stderr||r.message||"").toString();return a.includes("not found")||a.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${a.split(`
|
|
200
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await
|
|
201
|
-
...(truncated)`:"")}let{stdout:
|
|
202
|
-
`)}catch(
|
|
203
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:
|
|
204
|
-
${H.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${H.reset}`),!await
|
|
205
|
-
`)[0]}`}}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
203
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await Me(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
204
|
+
...(truncated)`:"")}let{stdout:s}=await Me(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(s),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of o.jobs||[]){let c=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${a.name} (${a.conclusion||a.status})`);for(let l of a.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
205
|
+
`)}catch(s){return`ERROR: ${(s.stderr||s.message||"").toString().split(`
|
|
206
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:s}=Te(),o=e.branch||await $i()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
207
|
+
${H.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${H.reset}`),!await s(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Me(a,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
208
|
+
`)[0]}`}}default:return`ERROR: Unknown tool: ${t}`}}async function _d(t,e,n={}){let s=n.silent?null:md(t,e);if(!s)return bi(t,e,n);let o=new xi(s);o.start();try{let r=await bi(t,e,n);return o.stop(),r}catch(r){throw o.stop(),r}}vi.exports={TOOL_DEFINITIONS:kd,executeTool:_d,resolvePath:le,autoFixPath:xs,autoFixEdit:_i,enrichBashError:ki}});var An=O((Zp,Ti)=>{var ye=require("fs").promises,pe=require("path"),ks=require("util").promisify(require("child_process").exec),{C:_e}=Q(),{getMergeConflicts:Si}=ze(),En=new Map,mt=new Map,_s=null,vd=3e4;async function Le(t){try{return await t()}catch{return null}}async function Sd(){if(!_s||Date.now()>_s)return!1;let t=[pe.join(process.cwd(),"package.json"),pe.join(process.cwd(),"README.md"),pe.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await ye.stat(e),s=mt.get(e);if(!s||n.mtimeMs!==s)return!1}catch{if(mt.has(e))return!1}try{let e=pe.join(process.cwd(),".git","HEAD"),n=await ye.stat(e),s=mt.get(e);if(!s||n.mtimeMs!==s)return!1}catch{}return!0}async function Td(){let t=[pe.join(process.cwd(),"package.json"),pe.join(process.cwd(),"README.md"),pe.join(process.cwd(),".gitignore"),pe.join(process.cwd(),".git","HEAD")];for(let e of t)try{let n=await ye.stat(e);mt.set(e,n.mtimeMs)}catch{mt.delete(e)}}async function Cd(t){let e="fileContext",n=En.get(e),s=!1;if(n&&await Sd()&&(s=!0),!s){let u=[],d=pe.join(t,"package.json");if(await Le(()=>ye.access(d).then(()=>!0).catch(()=>!1)))try{let w=await ye.readFile(d,"utf-8"),$=JSON.parse(w),k={name:$.name,version:$.version};$.scripts&&(k.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(k.deps=Object.keys($.dependencies).length),$.devDependencies&&(k.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(k)}`)}catch{}let m=pe.join(t,"README.md");if(await Le(()=>ye.access(m).then(()=>!0).catch(()=>!1))){let $=(await ye.readFile(m,"utf-8")).split(`
|
|
206
209
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
207
210
|
${$.join(`
|
|
208
|
-
`)}`)}let
|
|
209
|
-
${w.trim()}`)}
|
|
211
|
+
`)}`)}let p=pe.join(t,".gitignore");if(await Le(()=>ye.access(p).then(()=>!0).catch(()=>!1))){let w=await ye.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
212
|
+
${w.trim()}`)}n=u.join(`
|
|
210
213
|
|
|
211
|
-
`),
|
|
212
|
-
${a}`),
|
|
213
|
-
${
|
|
214
|
+
`),En.set(e,n),_s=Date.now()+vd,await Td()}let o=[n],[r,a,c,l]=await Promise.all([Le(async()=>{let{stdout:u}=await ks("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Le(async()=>{let{stdout:u}=await ks("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Le(async()=>{let{stdout:u}=await ks("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Si()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
215
|
+
${a}`),c&&o.push(`RECENT COMMITS:
|
|
216
|
+
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
214
217
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
215
218
|
${u}`)}return o.join(`
|
|
216
219
|
|
|
217
|
-
`)}async function
|
|
218
|
-
${e}`);let
|
|
219
|
-
${
|
|
220
|
+
`)}async function Ed(t){let e=pe.join(t,"package.json"),n="";if(await Le(()=>ye.access(e).then(()=>!0).catch(()=>!1)))try{let a=await ye.readFile(e,"utf-8"),c=JSON.parse(a);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Le(async()=>{let{stdout:a}=await ks("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),Si()]);if(n&&console.log(`${_e.dim} project: ${n}${_e.reset}`),o&&console.log(`${_e.dim} branch: ${o}${_e.reset}`),r&&r.length>0){console.log(`${_e.red} \u26A0 ${r.length} unresolved merge conflict(s):${_e.reset}`);for(let a of r)console.log(`${_e.red} ${a.file}${_e.reset}`);console.log(`${_e.yellow} \u2192 Resolve conflicts before starting tasks${_e.reset}`)}console.log()}Ti.exports={gatherProjectContext:Cd,printContext:Ed,_clearContextCache:()=>{En.clear(),mt.clear(),_s=null}}});var Ve=O((eh,Mi)=>{var Ne=require("fs"),Mn=require("path");function vs(){return Mn.join(process.cwd(),".nex","sessions")}function Ci(){let t=vs();Ne.existsSync(t)||Ne.mkdirSync(t,{recursive:!0})}function Rn(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Mn.join(vs(),`${e}.json`)}function Nn(t,e,n={}){Ci();let s=Rn(t),o={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return Ne.writeFileSync(s,JSON.stringify(o,null,2),"utf-8"),{path:s,name:t}}function Ei(t){let e=Rn(t);if(!Ne.existsSync(e))return null;try{return JSON.parse(Ne.readFileSync(e,"utf-8"))}catch{return null}}function Ai(){Ci();let t=vs(),e=Ne.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(Ne.readFileSync(Mn.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function Ad(t){let e=Rn(t);return Ne.existsSync(e)?(Ne.unlinkSync(e),!0):!1}function Md(){let t=Ai();return t.length===0?null:Ei(t[0].name)}var Ye=null,Re=null,jt=null;function Rd(t,e={}){t.length!==0&&(Ye&&clearTimeout(Ye),Re=t,jt=e||{},Ye=setTimeout(()=>{Re&&Re.length>0&&Nn("_autosave",Re,jt),Ye=null,Re=null,jt=null},5e3))}function Nd(){Ye&&(clearTimeout(Ye),Ye=null),Re&&Re.length>0&&(Nn("_autosave",Re,jt),Re=null,jt=null)}Mi.exports={saveSession:Nn,loadSession:Ei,listSessions:Ai,deleteSession:Ad,getLastSession:Md,autoSave:Rd,flushAutoSave:Nd,_getSessionsDir:vs}});var je=O((th,qi)=>{var Oe=require("fs"),Ss=require("path"),Od=require("os");function On(){return Ss.join(process.cwd(),".nex","memory")}function Pn(){return Ss.join(On(),"memory.json")}function Pd(){return Ss.join(process.cwd(),"NEX.md")}function Ri(){return Ss.join(Od.homedir(),".nex","NEX.md")}function Id(){let t=On();Oe.existsSync(t)||Oe.mkdirSync(t,{recursive:!0})}function Ts(){let t=Pn();if(!Oe.existsSync(t))return{};try{return JSON.parse(Oe.readFileSync(t,"utf-8"))}catch{return{}}}function Ni(t){Id(),Oe.writeFileSync(Pn(),JSON.stringify(t,null,2),"utf-8")}function qd(t,e){let n=Ts();n[t]={value:e,updatedAt:new Date().toISOString()},Ni(n)}function Ld(t){let e=Ts();return e[t]?e[t].value:null}function jd(t){let e=Ts();return t in e?(delete e[t],Ni(e),!0):!1}function Oi(){let t=Ts();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Pi(){let t=Ri();if(!Oe.existsSync(t))return"";try{return Oe.readFileSync(t,"utf-8").trim()}catch{return""}}function Ii(){let t=Pd();if(!Oe.existsSync(t))return"";try{return Oe.readFileSync(t,"utf-8").trim()}catch{return""}}function Dd(){let t=[],e=Pi();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
221
|
+
${e}`);let n=Ii();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
222
|
+
${n}`);let s=Oi();if(s.length>0){let o=s.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
220
223
|
`);t.push(`PROJECT MEMORY:
|
|
221
224
|
${o}`)}return t.join(`
|
|
222
225
|
|
|
223
|
-
`)}
|
|
224
|
-
${F.bold}${F.cyan}Plan: ${t.task}${F.reset}`),
|
|
225
|
-
`);for(let
|
|
226
|
-
`)}function
|
|
226
|
+
`)}qi.exports={remember:qd,recall:Ld,forget:jd,listMemories:Oi,loadGlobalInstructions:Pi,loadProjectInstructions:Ii,getMemoryContext:Dd,_getMemoryDir:On,_getMemoryFile:Pn,_getGlobalNexMdPath:Ri}});var Dt=O((nh,Di)=>{var Xe=require("fs"),In=require("path"),{C:sh}=Q(),Cs={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={...Cs};function Li(){let t=In.join(process.cwd(),".nex","config.json");if(Xe.existsSync(t))try{let e=JSON.parse(Xe.readFileSync(t,"utf-8"));e.permissions&&(pt={...Cs,...e.permissions})}catch{}}function Fd(){let t=In.join(process.cwd(),".nex"),e=In.join(t,"config.json"),n={};if(Xe.existsSync(e))try{n=JSON.parse(Xe.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=pt,Xe.existsSync(t)||Xe.mkdirSync(t,{recursive:!0}),Xe.writeFileSync(e,JSON.stringify(n,null,2),"utf-8")}function ji(t){return pt[t]||"ask"}function Ud(t,e){return["allow","ask","deny"].includes(e)?(pt[t]=e,!0):!1}function Wd(t){return ji(t)}function Bd(){return Object.entries(pt).map(([t,e])=>({tool:t,mode:e}))}function Hd(){pt={...Cs}}Li();Di.exports={getPermission:ji,setPermission:Ud,checkPermission:Wd,listPermissions:Bd,loadPermissions:Li,savePermissions:Fd,resetPermissions:Hd,DEFAULT_PERMISSIONS:Cs}});var ht=O((rh,Hi)=>{var Qe=require("fs"),Es=require("path"),oh=require("readline"),{C:F}=Q(),X=null,qn=!1,Ln=null,Fi=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 As(){return Es.join(process.cwd(),".nex","plans")}function Ui(){let t=As();Qe.existsSync(t)||Qe.mkdirSync(t,{recursive:!0})}function Gd(t,e=[]){return X={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},X}function zd(){return X}function Kd(t){qn=t}function Jd(){return qn}function Yd(){return!X||X.status!=="draft"?!1:(X.status="approved",X.updatedAt=new Date().toISOString(),!0)}function Vd(){return!X||X.status!=="approved"?!1:(X.status="executing",!0)}function Xd(t,e){return!X||t<0||t>=X.steps.length?!1:(X.steps[t].status=e,X.updatedAt=new Date().toISOString(),X.steps.every(n=>n.status==="done"||n.status==="skipped")&&(X.status="completed"),!0)}function Qd(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}`},n=[];n.push(`
|
|
227
|
+
${F.bold}${F.cyan}Plan: ${t.task}${F.reset}`),n.push(`${F.dim}Status: ${e[t.status]||t.status}${F.reset}
|
|
228
|
+
`);for(let s=0;s<t.steps.length;s++){let o=t.steps[s],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}`}n.push(` ${r} ${F.bold}Step ${s+1}:${F.reset} ${o.description}`),o.files.length>0&&n.push(` ${F.dim}Files: ${o.files.join(", ")}${F.reset}`)}return n.push(""),n.join(`
|
|
229
|
+
`)}function Zd(t){if(t||(t=X),!t)return null;Ui();let e=Es.join(As(),`${t.name}.json`);return Qe.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function ef(t){let e=Es.join(As(),`${t}.json`);if(!Qe.existsSync(e))return null;try{let n=JSON.parse(Qe.readFileSync(e,"utf-8"));return X=n,n}catch{return null}}function tf(){Ui();let t=As(),e=Qe.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(Qe.readFileSync(Es.join(t,s),"utf-8"));n.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return n.sort((s,o)=>(o.createdAt||"").localeCompare(s.createdAt||""))}function sf(t){Ln=t}function nf(){return Ln}function of(){X=null,qn=!1,Ln=null}function rf(){return`
|
|
227
230
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
228
231
|
|
|
229
232
|
# Allowed Tools (read-only)
|
|
230
|
-
You may ONLY use these tools: ${[...
|
|
233
|
+
You may ONLY use these tools: ${[...Fi].join(", ")}
|
|
231
234
|
Any other tool call will be blocked and returned with an error.
|
|
232
235
|
|
|
233
236
|
# Analysis Phase
|
|
@@ -258,46 +261,46 @@ Bullet list of potential issues and mitigations.
|
|
|
258
261
|
# Important
|
|
259
262
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
260
263
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
261
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
262
|
-
`),
|
|
263
|
-
`)}function
|
|
264
|
-
`)}function
|
|
265
|
-
`))!==-1;){let
|
|
266
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${
|
|
267
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
268
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
269
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
270
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
271
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
272
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
273
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
274
|
-
`);return}}this._safeWrite(`${
|
|
275
|
-
`)}};
|
|
264
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Wi=["interactive","semi-auto","autonomous"],Bi="interactive";function af(t){return Wi.includes(t)?(Bi=t,!0):!1}function cf(){return Bi}Hi.exports={createPlan:Gd,getActivePlan:zd,setPlanMode:Kd,isPlanMode:Jd,approvePlan:Yd,startExecution:Vd,updateStep:Xd,formatPlan:Qd,savePlan:Zd,loadPlan:ef,listPlans:tf,clearPlan:of,getPlanModePrompt:rf,setPlanContent:sf,getPlanContent:nf,PLAN_MODE_ALLOWED_TOOLS:Fi,setAutonomyLevel:af,getAutonomyLevel:cf,AUTONOMY_LEVELS:Wi}});var ea=O((ih,Zi)=>{var{C:g}=Q();function lf(t){if(!t)return"";let e=t.split(`
|
|
265
|
+
`),n=[],s=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(s)n.push(`${g.dim}${"\u2500".repeat(40)}${g.reset}`),s=!1,o="";else{s=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";n.push(`${g.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${g.reset}`)}continue}if(s){n.push(` ${Dn(r,o)}`);continue}if(r.startsWith("### ")){n.push(`${g.bold}${g.cyan} ${Ze(r.substring(4))}${g.reset}`);continue}if(r.startsWith("## ")){n.push(`${g.bold}${g.cyan} ${Ze(r.substring(3))}${g.reset}`);continue}if(r.startsWith("# ")){n.push(`${g.bold}${g.cyan}${Ze(r.substring(2))}${g.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");n.push(`${a}${g.cyan}\u2022${g.reset} ${et(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){n.push(`${a[1]}${g.cyan}${a[2]}.${g.reset} ${et(a[3])}`);continue}}n.push(et(r))}return n.join(`
|
|
266
|
+
`)}function Ze(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function et(t){return t?t.replace(/`([^`]+)`/g,`${g.cyan}$1${g.reset}`).replace(/\*\*([^*]+)\*\*/g,`${g.bold}$1${g.reset}`).replace(/\*([^*]+)\*/g,`${g.dim}$1${g.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${g.cyan}$1${g.reset} ${g.dim}($2)${g.reset}`):""}function Dn(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Gi(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?zi(t):e==="json"||e==="jsonc"?Ki(t):e==="python"||e==="py"?Ji(t):e==="go"||e==="golang"?Yi(t):e==="rust"||e==="rs"?Vi(t):e==="css"||e==="scss"||e==="less"?Xi(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Qi(t):t:""}function Gi(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,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${g.yellow}$1${g.reset}`),r=r.replace(e,`${g.magenta}$1${g.reset}`),r=r.replace(n,`${g.green}$&${g.reset}`),r=r.replace(s,`${g.dim}$1${g.reset}`),r}function zi(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(n,`${g.cyan}$1${g.reset}`),r=r.replace(e,`$1${g.green}$2${g.reset}`),r=r.replace(s,`${g.yellow}$&${g.reset}`),r=r.replace(o,`${g.dim}$1${g.reset}`),r}function Ki(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,s=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${g.cyan}$1${g.reset}:`),r=r.replace(n,`: ${g.green}$1${g.reset}`),r=r.replace(s,`: ${g.yellow}$1${g.reset}`),r=r.replace(o,`: ${g.magenta}$1${g.reset}`),r}function Ji(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,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,s=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,a=t;return a=a.replace(o,`${g.yellow}$1${g.reset}`),a=a.replace(e,`${g.magenta}$1${g.reset}`),a=a.replace(r,`${g.cyan}$1${g.reset}`),a=a.replace(n,`${g.green}$&${g.reset}`),a=a.replace(s,`${g.dim}$1${g.reset}`),a}function Yi(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,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${g.yellow}$1${g.reset}`),a=a.replace(n,`${g.cyan}$1${g.reset}`),a=a.replace(e,`${g.magenta}$1${g.reset}`),a=a.replace(s,`${g.green}$&${g.reset}`),a=a.replace(o,`${g.dim}$1${g.reset}`),a}function Vi(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,n=/\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,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${g.yellow}$1${g.reset}`),c=c.replace(n,`${g.cyan}$1${g.reset}`),c=c.replace(e,`${g.magenta}$1${g.reset}`),c=c.replace(a,`${g.yellow}$1${g.reset}`),c=c.replace(s,`${g.green}$&${g.reset}`),c=c.replace(o,`${g.dim}$1${g.reset}`),c}function Xi(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,s=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,a=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(a,`${g.yellow}$1${g.reset}`),c=c.replace(o,`${g.yellow}$1${g.reset}`),c=c.replace(e,`$1${g.cyan}$2${g.reset}:`),c=c.replace(s,`$1${g.magenta}$&${g.reset}`),c=c.replace(r,`${g.dim}$1${g.reset}`),c}function Qi(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(o,`${g.dim}$1${g.reset}`),a=a.replace(s,`${g.green}$&${g.reset}`),a=a.replace(e,`<${g.magenta}$1${g.reset}`),a=a.replace(n,` ${g.cyan}$1${g.reset}=`),a=a.replace(r,`${g.yellow}$1${g.reset}`),a}function uf(t,e){if(!t||t.length===0)return"";let n=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),s=n.map(a=>"\u2500".repeat(a+2)).join("\u253C"),o=t.map((a,c)=>` ${g.bold}${a.padEnd(n[c])}${g.reset} `).join("\u2502"),r=[];r.push(`${g.dim}\u250C${s.replace(/┼/g,"\u252C")}\u2510${g.reset}`),r.push(`${g.dim}\u2502${g.reset}${o}${g.dim}\u2502${g.reset}`),r.push(`${g.dim}\u251C${s}\u2524${g.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(n[u])} `).join(`${g.dim}\u2502${g.reset}`);r.push(`${g.dim}\u2502${g.reset}${c}${g.dim}\u2502${g.reset}`)}return r.push(`${g.dim}\u2514${s.replace(/┼/g,"\u2534")}\u2518${g.reset}`),r.join(`
|
|
267
|
+
`)}function df(t,e,n,s=30){let o=n>0?Math.round(e/n*100):0,r=Math.round(o/100*s),a=s-r,c=o>=100?g.green:o>50?g.yellow:g.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${g.dim}${"\u2591".repeat(a)}${g.reset} ${o}% (${e}/${n})`}var jn=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(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}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"],n=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${n}\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 n;for(;(n=this.buffer.indexOf(`
|
|
268
|
+
`))!==-1;){let s=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(s)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${g.dim}${"\u2500".repeat(40)}${g.reset}
|
|
269
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${g.dim}${"\u2500".repeat(40)}${g.reset}
|
|
270
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let n=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${g.dim}${"\u2500".repeat(3)}${n}${"\u2500".repeat(Math.max(0,37-n.length))}${g.reset}
|
|
271
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Dn(e,this.codeBlockLang)}
|
|
272
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${g.bold}${g.cyan} ${Ze(e.substring(4))}${g.reset}
|
|
273
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${g.bold}${g.cyan} ${Ze(e.substring(3))}${g.reset}
|
|
274
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${g.bold}${g.cyan}${Ze(e.substring(2))}${g.reset}
|
|
275
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let n=e.match(/^(\s*)/)[1],s=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${n}${g.cyan}\u2022${g.reset} ${et(s)}
|
|
276
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let n=e.match(/^(\s*)(\d+)\.\s(.*)/);if(n){this._safeWrite(`${n[1]}${g.cyan}${n[2]}.${g.reset} ${et(n[3])}
|
|
277
|
+
`);return}}this._safeWrite(`${et(e)}
|
|
278
|
+
`)}};Zi.exports={renderMarkdown:lf,renderInline:et,stripHeadingMarkers:Ze,highlightCode:Dn,highlightJS:Gi,highlightBash:zi,highlightJSON:Ki,highlightPython:Ji,highlightGo:Yi,highlightRust:Vi,highlightCSS:Xi,highlightHTML:Qi,renderTable:uf,renderProgress:df,StreamRenderer:jn}});var Wn=O((ah,oa)=>{var{execSync:ff}=require("child_process"),Fn=require("path"),Ft=require("fs"),Un=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function ta(){return Fn.join(process.cwd(),".nex","hooks")}function mf(){return Fn.join(process.cwd(),".nex","config.json")}function sa(){let t=mf();if(!Ft.existsSync(t))return{};try{return JSON.parse(Ft.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Ms(t){if(!Un.includes(t))return[];let e=[],n=ta(),s=Fn.join(n,t);Ft.existsSync(s)&&e.push(s);let o=sa();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function na(t,e={},n=3e4){try{return{success:!0,output:ff(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){return{success:!1,error:s.stderr?s.stderr.trim():s.message}}}function pf(t,e={}){let n=Ms(t);if(n.length===0)return[];let s={};for(let[r,a]of Object.entries(e))s[`NEX_${r.toUpperCase()}`]=String(a);let o=[];for(let r of n){let a=na(r,s);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function hf(t){return Ms(t).length>0}function gf(){let t=[];for(let e of Un){let n=Ms(e);n.length>0&&t.push({event:e,commands:n})}return t}function $f(){let t=ta();return Ft.existsSync(t)||Ft.mkdirSync(t,{recursive:!0}),t}oa.exports={HOOK_EVENTS:Un,loadHookConfig:sa,getHooksForEvent:Ms,executeHook:na,runHooks:pf,hasHooks:hf,listHooks:gf,initHooksDir:$f}});var ee=O((uh,$a)=>{var{C:v,Spinner:gt,TaskProgress:yf,formatToolCall:wf,formatResult:bf,formatToolSummary:ca,setActiveTaskProgress:ch}=Q(),{callStream:xf}=re(),{parseToolArgs:kf}=os(),{executeTool:_f}=Ke(),{gatherProjectContext:vf}=An(),{fitToContext:Sf,forceCompress:Bn,getUsage:Tf,estimateTokens:Cf}=xe(),{autoSave:tt}=Ve(),{getMemoryContext:Ef}=je(),{checkPermission:Af,setPermission:Mf,savePermissions:Rf}=Dt(),{confirm:la,setAllowAlwaysHandler:Nf}=Te(),{isPlanMode:Ps,getPlanModePrompt:Of,PLAN_MODE_ALLOWED_TOOLS:ua,setPlanContent:Pf}=ht(),{StreamRenderer:If}=ea(),{runHooks:ra}=Wn(),{routeMCPCall:qf,getMCPToolDefinitions:Lf}=ls(),{getSkillInstructions:jf,getSkillToolDefinitions:Df,routeSkillCall:Ff}=Et(),{trackUsage:Uf}=ct(),{validateToolArgs:Wf}=mn(),{filterToolsForModel:ia,getModelTier:Bf,PROVIDER_DEFAULT_TIER:lh}=bn(),{getConfiguredProviders:Hf,getActiveProviderName:Gf,getActiveModelId:zf}=re(),da=require("fs"),fa=require("path"),aa=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Kf(t){let e=[],n;for(aa.lastIndex=0;(n=aa.exec(t))!==null;){let s=n[1].trim(),o=s.startsWith("~")?s.replace("~",process.env.HOME||""):fa.resolve(s);da.existsSync(o)&&e.push({raw:s,abs:o})}return e}function Jf(t){let e=da.readFileSync(t),n=fa.extname(t).toLowerCase().replace(".",""),s=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:s}}function ma(t){let e=Kf(t);if(e.length===0)return t;let n=[{type:"text",text:t}];for(let s of e)try{let{data:o,media_type:r}=Jf(s.abs);n.push({type:"image",media_type:r,data:o})}catch{}return n.length>1?n:t}var Hn=null,Gn=null,zn=null;function $t(){if(Hn===null){let{TOOL_DEFINITIONS:t}=Ke();Hn=t}return Gn===null&&(Gn=Df()),zn===null&&(zn=Lf()),[...Hn,...Gn,...zn]}var Vn=50;function Yf(t){Number.isFinite(t)&&t>0&&(Vn=t)}var Ns=()=>null;function Vf(t){Ns=t}var Ut=null,Xn=null,yt=null,Os=new Map,Xf=1e4,Qf=6e3;function Zf(t){if(Cf(t)>Xf)try{let{compressToolResult:n}=xe();return n(t,Qf)}catch{return t}return t}function pa(t){try{let{getActiveModel:e}=re(),n=e(),s=n?`${n.provider}:${n.id}`:"default";if(Os.has(s))return Os.get(s);let o=ia(t);return Os.set(s,o),o}catch{return ia(t)}}function em(){Os.clear()}async function ha(){try{let t=require("fs").promises,e=require("path"),n=[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(n.map(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=je(),a=r();a&&o.push(`memory:${a}`)}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function tm(){Ut=null,Xn=null,yt=null}var sm=new Set(["read_file","list_directory","search_files","glob","grep","web_fetch","web_search","git_status","git_diff","git_log","task_list","gh_run_list","gh_run_view"]),Kn=5,Jn=3,Rs=2,nm=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),om=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function rm(t){try{let e=require("fs"),n=require("path"),s=n.join(process.cwd(),".nex","plans");e.existsSync(s)||e.mkdirSync(s,{recursive:!0});let o=n.join(s,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Nf(t=>{Mf(t,"allow"),Rf(),console.log(`${v.green} \u2713 ${t}: always allow${v.reset}`)});async function im(t){let e=t.function.name,n=kf(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let l=$t().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${v.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${v.reset}`),{callId:s,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
276
279
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
277
280
|
|
|
278
281
|
Expected JSON schema for "${e}":
|
|
279
282
|
${u}
|
|
280
283
|
|
|
281
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:
|
|
282
|
-
`)[0]}${v.reset}`),{callId:
|
|
283
|
-
...(truncated ${
|
|
284
|
-
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),
|
|
284
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}let o=Wf(e,n);if(!o.valid)return console.log(`${v.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
285
|
+
`)[0]}${v.reset}`),{callId:s,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:s}};let r=o.corrected||n;if(o.corrected){let c=Object.keys(n),l=Object.keys(o.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${v.dim} \u2713 ${e}: corrected args (${u.join(", ")})${v.reset}`)}if(Ps()&&!ua.has(e))return console.log(`${v.yellow} \u2717 ${e}: blocked in plan mode${v.reset}`),{callId:s,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:s}};let a=Af(e);if(a==="deny")return console.log(`${v.red} \u2717 ${e}: denied by permissions${v.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:s}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await la(c,{toolName:e})?{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:s}}}return{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function am(t,e,n={}){let s=await Ff(t,e);if(s!==null)return s;let o=await qf(t,e);return o!==null?o:_f(t,e,n)}function cm(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 Yn(t,e=!1){e||console.log(wf(t.fnName,t.args)),ra("pre-tool",{tool_name:t.fnName});let n=await am(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),s=String(n??""),o=s.length>5e4?s.substring(0,5e4)+`
|
|
286
|
+
...(truncated ${s.length-5e4} chars)`:s,r=o.split(`
|
|
287
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=ca(t.fnName,t.args,o,a);return e||(console.log(bf(o)),console.log(c)),ra("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:Zf(o),tool_call_id:t.callId},summary:c}}async function lm(t,e=!1,n={}){let s=new Array(t.length),o=[],r=[],a=null;if(e&&!n.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=cm(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}a=new gt(u),a.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Yn(t[l],e);s[l]=u,o.push(d)}else{let l=r.map(d=>Yn(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)s[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),s[l]=u.errorResult,o.push(ca(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(sm.has(u.fnName))r.push(l);else{await c(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Yn(u,e);s[l]=d,o.push(f)}}if(await c(),a&&a.stop(),e&&o.length>0&&!n.skipSummaries)for(let l of o)console.log(l);return s}var ae=[];function um(){if(yt!==null)return yt;try{let e=Hf().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Bf(r.id,o.name),name:r.name})));if(e.length<2)return yt="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},s=`
|
|
285
288
|
# Sub-Agent Model Routing
|
|
286
289
|
|
|
287
|
-
`;
|
|
290
|
+
`;s+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',s+=`| Model | Tier | Auto-assigned for |
|
|
288
291
|
|---|---|---|
|
|
289
|
-
`;for(let o of e)
|
|
290
|
-
`;return yt=
|
|
292
|
+
`;for(let o of e)s+=`| ${o.spec} | ${o.tier} | ${n[o.tier]||o.tier} |
|
|
293
|
+
`;return yt=s,s}catch{return yt="",""}}async function ga(){let t=await ha();if(Ut!==null&&t===Xn)return Ut;let e=await vf(process.cwd()),n=Ef(),s=jf(),o=Ps()?Of():"";return Ut=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
291
294
|
|
|
292
295
|
WORKING DIRECTORY: ${process.cwd()}
|
|
293
296
|
All relative paths resolve from this directory.
|
|
294
297
|
|
|
295
298
|
PROJECT CONTEXT:
|
|
296
299
|
${e}
|
|
297
|
-
${
|
|
298
|
-
${s}
|
|
299
|
-
`:""}${n?`
|
|
300
|
+
${n?`
|
|
300
301
|
${n}
|
|
302
|
+
`:""}${s?`
|
|
303
|
+
${s}
|
|
301
304
|
`:""}${o?`
|
|
302
305
|
${o}
|
|
303
306
|
`:""}
|
|
@@ -359,7 +362,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
359
362
|
- Good for: reading multiple files, analyzing separate modules.
|
|
360
363
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
361
364
|
- Max 5 parallel agents.
|
|
362
|
-
${
|
|
365
|
+
${um()}
|
|
363
366
|
|
|
364
367
|
# Edit Reliability (Critical)
|
|
365
368
|
|
|
@@ -399,15 +402,14 @@ When a tool call returns ERROR:
|
|
|
399
402
|
- Prefer creating new git commits over amending. Never force-push without explicit permission.
|
|
400
403
|
- If you encounter unexpected state (unfamiliar files, branches), investigate before modifying.
|
|
401
404
|
|
|
402
|
-
`,
|
|
403
|
-
${v.dim} ${a}${v.reset}`),
|
|
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}`)}
|
|
405
|
-
${v.yellow}\u26A0 Max iterations (${P}) reached.${v.reset}`),await
|
|
406
|
-
`),await
|
|
407
|
-
`)
|
|
408
|
-
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${z.bold}${z.cyan}${n}${z.reset}`),$.push(` ${z.dim}${o}${z.reset}`),$.push("");let{start:k,end:T}=f();k>0&&$.push(` ${z.dim}\u2191 more${z.reset}`);for(let S=k;S<T;S++){let _=e[S];if(_.isHeader){$.push(` ${z.bold}${z.dim}${_.label}${z.reset}`);continue}let C=a[c]===S,E=C?`${z.cyan}> `:" ",P=_.isCurrent?` ${z.yellow}<current>${z.reset}`:"";C?$.push(`${E}${z.bold}${_.label}${z.reset}${P}`):$.push(`${E}${z.dim}${_.label}${z.reset}${P}`)}T<e.length&&$.push(` ${z.dim}\u2193 more${z.reset}`);let b=$.join(`
|
|
405
|
+
`,Xn=t,Ut}function dm(){ae=[]}function fm(){return ae.length}function mm(){return ae}function pm(t){ae=t}function st(t,e,n,s,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}a+=" \u2500\u2500",console.log(`
|
|
406
|
+
${v.dim} ${a}${v.reset}`),n.size>0?console.log(`${v.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${v.reset}`):s.size>0&&t>=2&&console.log(`${v.dim} \u{1F4A1} /save \xB7 /clear${v.reset}`)}async function hm(t){let e=ma(t);ae.push({role:"user",content:e});let{setOnChange:n}=hs(),s=null,o=0;n((I,L)=>{I==="create"?(s&&s.stop(),s=new yf(L.name,L.tasks),s.setStats({tokens:o}),s.start()):I==="update"&&s?s.updateTask(L.id,L.status):I==="clear"&&s&&(s.stop(),s=null)});let a=[{role:"system",content:await ga()},...ae],c=new gt("Thinking...");c.start();let l=$t(),{messages:u,compressed:d,compacted:f,tokensRemoved:m}=await Sf(a,l),h=Tf(a,l);if(c.stop(),f)console.log(`${v.dim} [context compacted \u2014 summary (~${m} tokens freed)]${v.reset}`);else if(d){let I=h.limit>0?Math.round(m/h.limit*100):0;console.log(`${v.dim} [context compressed \u2014 ~${m} tokens freed (${I}%)]${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 p=u,x=0,w=0,$=0,k=0,T=0,b=new Map,S=new Set,_=new Set,C=Date.now(),E,P=Vn,q=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(Ns()?.aborted)break;let L=!0,W=null;if(s&&s.isActive())s._paused&&s.resume();else if(!s){let A=T>0?`Thinking... (step ${T+1})`:"Thinking...";W=new gt(A),W.start()}let z=!0,se="",ne=new If,be,Gt=Date.now(),bt=!1,Ds=new AbortController,po=setInterval(()=>{let A=Date.now()-Gt;A>=om?(ne._clearCursorLine(),console.log(`${v.yellow} \u26A0 Stream stale for ${Math.round(A/1e3)}s \u2014 aborting and retrying${v.reset}`),Ds.abort()):A>=nm&&!bt&&(bt=!0,ne._clearCursorLine(),console.log(`${v.yellow} \u26A0 No tokens received for ${Math.round(A/1e3)}s \u2014 waiting...${v.reset}`))},5e3),me="",Se=null;try{let A=pa($t()),j=Ps()?A.filter(oe=>ua.has(oe.function.name)):A,nt=Ns(),D=new AbortController;nt&&nt.addEventListener("abort",()=>D.abort(),{once:!0}),Ds.signal.addEventListener("abort",()=>D.abort(),{once:!0}),be=await xf(p,j,{signal:D.signal,onToken:oe=>{Gt=Date.now(),bt=!1,me+=oe,process.stdout.isTTY?Se||(Se=setTimeout(()=>{me&&ne&&ne.push(me),me="",Se=null},50)):(ne.push(me),me=""),z&&(s&&!s._paused?s.pause():W&&W.stop(),U(),ne.startCursor(),z=!1),se+=oe}})}catch(A){if(clearInterval(po),Se&&(clearTimeout(Se),Se=null),me&&ne&&(ne.push(me),me=""),s&&!s._paused&&s.pause(),W&&W.stop(),ne.stopCursor(),Ds.signal.aborted&&!Ns()?.aborted){if($++,$>Rs){if(k<1){k++,console.log(`${v.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${v.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Bn(p,ge);p=xt,console.log(`${v.dim} [force-compressed \u2014 ~${kt} tokens freed]${v.reset}`),$=0,E--;continue}console.log(`${v.red} \u2717 Stream stale: max retries (${Rs}) exceeded. The model may be overloaded \u2014 try again or switch models.${v.reset}`),s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);break}let D=$===1?3e3:5e3;if($>=2&&k<1){k++,console.log(`${v.yellow} \u26A0 Stale retry ${$}/${Rs} \u2014 force-compressing before retry...${v.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Bn(p,ge);p=xt,console.log(`${v.dim} [force-compressed \u2014 ~${kt} tokens freed]${v.reset}`)}else console.log(`${v.yellow} \u26A0 Stale retry ${$}/${Rs} \u2014 retrying in ${D/1e3}s...${v.reset}`);let oe=new gt(`Waiting ${D/1e3}s before retry...`);oe.start(),await new Promise(ge=>setTimeout(ge,D)),oe.stop(),E--;continue}if(A.name==="AbortError"||A.name==="CanceledError"||A.message?.includes("canceled")||A.message?.includes("aborted")){s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(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(),oe=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(oe&&k<1){k++,console.log(`${v.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${v.reset}`);let ge=$t(),{messages:xt,tokensRemoved:kt}=Bn(p,ge);p=xt,console.log(`${v.dim} [force-compressed \u2014 ~${kt} tokens freed]${v.reset}`),E--;continue}oe?j="Context too long \u2014 force compression exhausted. Use /clear to start fresh":j="Bad request \u2014 the conversation may be too long or contain unsupported content. Try /clear and retry"}else A.message.includes("500")||A.message.includes("502")||A.message.includes("503")||A.message.includes("504")?j="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(A.message.includes("fetch failed")||A.message.includes("fetch"))&&(j="Network request failed \u2014 please check your internet connection");if(console.log(`${v.red} \u2717 ${j}${v.reset}`),A.message.includes("429")){if(x++,x>Kn){console.log(`${v.red} Rate limit: max retries (${Kn}) exceeded. Try again later or use /budget to check your limits.${v.reset}`),s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);break}let D=Math.min(1e4*Math.pow(2,x-1),12e4),oe=new gt(`Rate limit \u2014 waiting ${Math.round(D/1e3)}s (retry ${x}/${Kn})`);oe.start(),await new Promise(ge=>setTimeout(ge,D)),oe.stop();continue}if(A.message.includes("socket disconnected")||A.message.includes("TLS")||A.message.includes("ECONNRESET")||A.message.includes("ECONNABORTED")||A.message.includes("ETIMEDOUT")||A.code==="ECONNRESET"||A.code==="ECONNABORTED"){if(w++,w>Jn){console.log(`${v.red} Network error: max retries (${Jn}) exceeded. Check your connection and try again.${v.reset}`),s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);break}let D=Math.min(2e3*Math.pow(2,w-1),3e4),oe=new gt(`Network error \u2014 retrying in ${Math.round(D/1e3)}s (${w}/${Jn})`);oe.start(),await new Promise(ge=>setTimeout(ge,D)),oe.stop(),E--;continue}s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);break}clearInterval(po),z&&(s&&!s._paused&&s.pause(),W&&W.stop()),Se&&(clearTimeout(Se),Se=null),me&&ne&&(ne.push(me),me=""),se&&ne.flush(),w=0,$=0,be&&be.usage&&(Uf(Gf(),zf(),be.usage.prompt_tokens||0,be.usage.completion_tokens||0),o+=(be.usage.prompt_tokens||0)+(be.usage.completion_tokens||0),s&&s.setStats({tokens:o}));let{content:Fs,tool_calls:We}=be,Us={role:"assistant",content:Fs||""};if(We&&We.length>0&&(Us.tool_calls=We),ae.push(Us),p.push(Us),!We||We.length===0){let A=(Fs||"").trim().length>0||se.trim().length>0;if(!A&&T>0&&E<Vn-1){let j={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};p.push(j);continue}if(Ps()&&A){let j=(Fs||se||"").trim();Pf(j),rm(j),console.log(`
|
|
407
|
+
${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}`)}s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);return}T++,T>1&&(L=!1);for(let A of We){let j=A.function.name;b.set(j,(b.get(j)||0)+1)}let Ws=await Promise.all(We.map(A=>im(A))),ho=s?{skipSpinner:!0,skipSummaries:!0}:{};ho.skipSummaries||U(),s&&s._paused&&s.resume();let go=await lm(Ws,!0,ho);for(let A=0;A<Ws.length;A++){let j=Ws[A];if(!j.canExecute)continue;let nt=go[A].content,D=!nt.startsWith("ERROR")&&!nt.includes("CANCELLED");D&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&S.add(j.args.path),D&&j.fnName==="read_file"&&j.args&&j.args.path&&_.add(j.args.path)}for(let A of go)ae.push(A),p.push(A)}if(E>=P){s&&(s.stop(),s=null),n(null),st(T,b,S,_,C),tt(ae);let{getActiveProviderName:I}=re();if(I()==="ollama"&&q<M){q++,P+=20,console.log(`${v.dim} \u2500\u2500 auto-extending to ${P} turns \u2500\u2500${v.reset}`);continue e}if(console.log(`
|
|
408
|
+
${v.yellow}\u26A0 Max iterations (${P}) reached.${v.reset}`),await la(" 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}}$a.exports={processInput:hm,clearConversation:dm,getConversationLength:fm,getConversationMessages:mm,setConversationMessages:pm,setAbortSignalGetter:Vf,setMaxIterations:Yf,invalidateSystemPromptCache:tm,clearToolFilterCache:em,getCachedFilteredTools:pa,buildSystemPrompt:ga,getProjectContextHash:ha,buildUserContent:ma}});var re=O((dh,_a)=>{var{OllamaProvider:gm}=Po(),{OpenAIProvider:$m}=Zo(),{AnthropicProvider:ym}=nr(),{GeminiProvider:wm}=ar(),{LocalProvider:bm}=ur(),{checkBudget:xm}=ct(),ya={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},wa={};for(let[t,e]of Object.entries(ya))for(let n of Object.values(e))wa[n]=t;function ba(t,e){let n=wa[t];return n&&ya[n][e]||t}var te={},de=null,Z=null,Wt=[];function he(){if(Object.keys(te).length>0)return;wt("ollama",new gm),wt("openai",new $m),wt("anthropic",new ym),wt("gemini",new wm),wt("local",new bm);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;te[t]?(de=t,Z=e||te[t].defaultModel):(de="ollama",Z="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Wt=n.split(",").map(s=>s.trim()).filter(Boolean))}function wt(t,e){te[t]=e}function km(t){return he(),te[t]||null}function Qn(){return he(),te[de]||null}function _m(){return he(),de}function vm(){return he(),Z}function Sm(){he();let t=Qn();if(!t)return{id:Z,name:Z,provider:de};let e=t.getModel(Z);return e?{...e,provider:de}:{id:Z,name:Z,provider:de}}function xa(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(te[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function Tm(t){he();let{provider:e,model:n}=xa(t);if(e){let o=te[e];return o&&(o.getModel(n)||e==="local"||e==="ollama")?(de=e,Z=n,Is(),!0):!1}let s=Qn();if(s&&s.getModel(n))return Z=n,Is(),!0;for(let[o,r]of Object.entries(te))if(r.getModel(n))return de=o,Z=n,Is(),!0;return!1}function Is(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ee();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=xe();t()}catch{}}function Cm(){he();let t=new Set;for(let e of Object.values(te))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function Em(){return he(),Object.entries(te).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===de&&n.id===Z}))}))}function Am(){he();let t=[];for(let[e,n]of Object.entries(te)){let s=n.isConfigured();for(let o of Object.values(n.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:s})}return t}function Mm(t){Wt=Array.isArray(t)?t:[]}function Rm(){return[...Wt]}function Nm(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="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 ka(t){let e=[de,...Wt.filter(r=>r!==de)],n,s=0,o=0;for(let r=0;r<e.length;r++){let a=e[r],c=te[a];if(!c||!c.isConfigured())continue;o++;let l=xm(a);if(!l.allowed){s++,n=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?ba(Z,a):Z;return u&&d!==Z&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
409
|
+
`),await t(c,a,d)}catch(u){if(n=u,Nm(u)&&r<e.length-1)continue;throw u}}throw s>0&&s===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):n||new Error("No configured provider available")}async function Om(t,e,n={}){return he(),ka((s,o,r)=>s.stream(t,e,{model:r,signal:n.signal,...n}))}async function Pm(t,e,n={}){if(he(),n.provider){let s=te[n.provider];if(!s||!s.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let o={model:n.model||Z,...n};try{return await s.chat(t,e,o)}catch(r){if(typeof s.stream=="function")try{return await s.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return ka(async(s,o,r)=>{try{return await s.chat(t,e,{model:r,...n})}catch(a){if(typeof s.stream=="function")try{return await s.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw a}})}function Im(){he();let t=[];for(let[e,n]of Object.entries(te))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function qm(){for(let t of Object.keys(te))delete te[t];de=null,Z=null,Wt=[]}_a.exports={registerProvider:wt,getProvider:km,getActiveProvider:Qn,getActiveProviderName:_m,getActiveModelId:vm,getActiveModel:Sm,setActiveModel:Tm,getModelNames:Cm,parseModelSpec:xa,listProviders:Em,listAllModels:Am,callStream:Om,callChat:Pm,getConfiguredProviders:Im,setFallbackChain:Mm,getFallbackChain:Rm,resolveModelForProvider:ba,_reset:qm}});var Ta=O((fh,Sa)=>{var{C:G}=Q(),{listProviders:Lm,getActiveProviderName:jm,getActiveModelId:Dm,setActiveModel:Fm}=re();function va(t,e,n={}){let{title:s="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let a=e.map(($,k)=>$.isHeader?-1:k).filter($=>$>=0);if(a.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?a.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=a[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let S=0;S<m;S++)process.stdout.write(`\x1B[2K
|
|
410
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${G.bold}${G.cyan}${s}${G.reset}`),$.push(` ${G.dim}${o}${G.reset}`),$.push("");let{start:k,end:T}=f();k>0&&$.push(` ${G.dim}\u2191 more${G.reset}`);for(let S=k;S<T;S++){let _=e[S];if(_.isHeader){$.push(` ${G.bold}${G.dim}${_.label}${G.reset}`);continue}let C=a[l]===S,E=C?`${G.cyan}> `:" ",P=_.isCurrent?` ${G.yellow}<current>${G.reset}`:"";C?$.push(`${E}${G.bold}${_.label}${G.reset}${P}`):$.push(`${E}${G.dim}${_.label}${G.reset}${P}`)}T<e.length&&$.push(` ${G.dim}\u2193 more${G.reset}`);let b=$.join(`
|
|
409
411
|
`);process.stdout.write(b+`
|
|
410
|
-
`),m=$.length}t.pause();let
|
|
412
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function x(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){l>0&&(l--,h());return}if(k.name==="down"||k.ctrl&&k.name==="n"){l<a.length-1&&(l++,h());return}if(k.name==="return"){let T=e[a[l]];x(),r(T?T.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){x(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function Um(t){let e=Lm(),n=jm(),s=Dm(),o=[];for(let a of e)if(a.models.length!==0){o.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===n&&c.id===s;o.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await va(t,o,{title:"Select Model"});return r?(Fm(r),console.log(`${G.green}Switched to ${r}${G.reset}`),!0):(console.log(`${G.dim}Cancelled${G.reset}`),!1)}Sa.exports={pickFromList:va,showModelPicker:Um}});var eo=O((ph,Ra)=>{var Zn=require("fs"),Wm=require("path"),{callChat:Bm}=re(),{remember:Hm,listMemories:mh,recall:Gm}=je(),Ca=4,zm=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
411
413
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
412
414
|
|
|
413
415
|
Return ONLY valid JSON in this exact format:
|
|
@@ -433,17 +435,17 @@ Rules:
|
|
|
433
435
|
- value: concise actionable instruction, max 120 chars
|
|
434
436
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
435
437
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
436
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
438
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Km(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
439
|
|
|
438
|
-
`)}async function
|
|
440
|
+
`)}async function Ea(t){if(t.filter(o=>o.role==="user").length<Ca)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Km(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=[{role:"system",content:zm},{role:"user",content:`Conversation to analyze:
|
|
439
441
|
|
|
440
|
-
${
|
|
442
|
+
${n}`}];try{let a=((await Bm(s,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(a[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Aa(t){let e=[];for(let{key:n,value:s}of t||[]){if(!n||!s||typeof n!="string"||typeof s!="string")continue;let o=n.trim().replace(/\s+/g,"-").substring(0,60),r=s.trim().substring(0,200);if(!o||!r)continue;let a=Gm(o);a!==r&&(Hm(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Ma(t){if(!t||t.length===0)return[];let e=Wm.join(process.cwd(),"NEX.md"),n="";try{Zn.existsSync(e)&&(n=Zn.readFileSync(e,"utf-8"))}catch{}let s=[],o=n;for(let r of t){if(!r||typeof r!="string")continue;let a=r.trim();if(!a)continue;let c=a.substring(0,35).toLowerCase();n.toLowerCase().includes(c)||(s.push(a),o=o?o.endsWith(`
|
|
441
443
|
`)?o+a:o+`
|
|
442
|
-
`+a:a)}return
|
|
444
|
+
`+a:a)}return s.length>0&&(o.endsWith(`
|
|
443
445
|
`)||(o+=`
|
|
444
|
-
`),
|
|
446
|
+
`),Zn.writeFileSync(e,o,"utf-8")),s}async function Jm(t){let e=await Ea(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=Aa(e.memories),s=Ma(e.nex_additions);return{applied:n,nexAdded:s,summary:e.summary}}Ra.exports={learnFromSession:Jm,reflectOnSession:Ea,applyMemories:Aa,applyNexAdditions:Ma,LEARN_MIN_MESSAGES:Ca}});var Pa=O((hh,Oa)=>{var Ym=require("axios"),Bt=require("fs"),Na=require("path"),Vm="nex-code",to=Na.join(process.cwd(),".nex"),so=Na.join(to,"last-version-check");Bt.existsSync(to)||Bt.mkdirSync(to,{recursive:!0});async function Xm(){try{let t=Zm(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};ep(e);let n=Qm(),o=(await Ym.get(`https://registry.npmjs.org/${Vm}/latest`,{timeout:5e3})).data.version,r=tp(o,n);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function Qm(){return zt().version}function Zm(){try{if(Bt.existsSync(so)){let t=Bt.readFileSync(so,"utf8");return parseInt(t,10)}}catch{}return null}function ep(t){try{Bt.writeFileSync(so,t.toString())}catch{}}function tp(t,e){try{let n=t.split(".").map(Number),s=e.split(".").map(Number);return n[0]>s[0]?!0:n[0]<s[0]?!1:n[1]>s[1]?!0:n[1]<s[1]?!1:n[2]>s[2]}catch{return!1}}Oa.exports={checkForNewVersion:Xm}});var Ya=O(($h,Ja)=>{var sp=require("readline"),Ue=require("fs"),ve=require("path"),{C:i,banner:np,cleanupTerminal:Ia}=Q(),{listProviders:oo,getActiveProviderName:De,listAllModels:gh,setFallbackChain:op,getFallbackChain:rp,getProvider:ip}=re(),{flushAutoSave:qa}=Ve(),{getActiveModel:Fe,setActiveModel:La}=os(),{printContext:ja}=An(),{loadAllSkills:ap,getSkillCommands:ro,handleSkillCommand:cp}=Et(),{setReadlineInterface:lp,setAutoConfirm:up,getAutoConfirm:Da}=Te(),Ls=process.cwd(),Pe=null;function Fa(){return Pe?.signal??null}var js=[{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 Ua(){let t=ro(),e=[...js,...t],n=Math.max(...e.map(s=>s.cmd.length));console.log("");for(let{cmd:s,desc:o}of js)console.log(` ${i.cyan}${s.padEnd(n+2)}${i.reset}${i.dim}${o}${i.reset}`);for(let{cmd:s,desc:o}of t)console.log(` ${i.cyan}${s.padEnd(n+2)}${i.reset}${i.dim}${o} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
445
447
|
${i.dim}Type /help for detailed usage${i.reset}
|
|
446
|
-
`)}function
|
|
448
|
+
`)}function Wa(t){try{let e,n;t.endsWith("/")||t.endsWith(ve.sep)?(e=t,n=""):(e=ve.dirname(t),n=ve.basename(t)),e.startsWith("~")&&(e=ve.join(require("os").homedir(),e.slice(1)));let s=ve.isAbsolute(e)?e:ve.resolve(Ls,e);if(!Ue.existsSync(s)||!Ue.statSync(s).isDirectory())return[];let o=Ue.readdirSync(s,{withFileTypes:!0}),r=[];for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules"||n&&!a.name.startsWith(n))continue;let c=t.endsWith("/")||t.endsWith(ve.sep)?t:ve.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function Ba(t){if(t.startsWith("/")){let s=[...js,...ro()],o=s.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:s.map(r=>r.cmd),t]}let e=t.split(/\s+/),n=e[e.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[Wa(n),n]:[[],t]}function Ha(){console.log(`
|
|
447
449
|
${i.bold}${i.cyan}Commands:${i.reset}
|
|
448
450
|
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
449
451
|
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
@@ -504,75 +506,75 @@ ${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
|
504
506
|
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
505
507
|
|
|
506
508
|
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
507
|
-
`)}function
|
|
508
|
-
${i.bold}${i.cyan}Providers:${i.reset}`);for(let
|
|
509
|
-
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(
|
|
510
|
-
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${
|
|
509
|
+
`)}function Ga(t){let n=Math.round(t/100*30),s=30-n;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(n)}${i.dim}${"\u2591".repeat(s)}${i.reset} ${t}%`}function no(){let t=oo(),e=De(),n=Fe();console.log(`
|
|
510
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let s of t){let o=s.provider===e,r=s.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${s.provider}${i.reset}${a}`);for(let c of s.models){let l=c.id===n.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function za(t,e){let[n,...s]=t.split(/\s+/);switch(n){case"/help":return Ha(),!0;case"/model":{let o=s.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Ta();await r(e)}else{let r=Fe(),a=De();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 no(),!0;if(La(o)){let r=Fe(),a=De();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 no(),!0;case"/fallback":{let o=s.join(" ").trim();if(!o){let a=rp();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 op(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=ee(),{getUsage:r}=xe(),{TOOL_DEFINITIONS:a}=Ke(),c=o(),l=r(c,a),u=Fe(),d=De();console.log(`
|
|
511
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=Ga(l.percentage);return console.log(` ${f}`),console.log(`
|
|
512
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=ct();return s.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
511
513
|
${o()}
|
|
512
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:
|
|
513
|
-
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let x=!1;for(let w of
|
|
514
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=ct(),d=s[0];if(!d){let h=o(),p=oo();console.log(`
|
|
515
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let x=!1;for(let w of p){let $=r(w.provider),k=h[w.provider];if(k!==void 0){x=!0;let T=Math.min(100,Math.round($/k*100)),b=10,S=Math.round(T/100*b),_=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=s[1];if(!f){let h=a(d);return h.limit!==null?console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} ${i.dim}(no limit)${i.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${i.green}Removed cost limit for ${d}${i.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${i.red}Invalid amount: ${f}. Use a positive number or 'off'.${i.reset}`),!0):(u(d,m),l(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=ee(),{clearHistory:a}=ut(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=eo();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${i.green}${f} learning(s) saved${i.reset}
|
|
514
516
|
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
515
517
|
`)}).catch(()=>process.stdout.write(`
|
|
516
|
-
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await
|
|
517
|
-
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let
|
|
518
|
-
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/learn":{let{learnFromSession:o}=eo(),{getConversationMessages:r}=
|
|
518
|
+
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await ja(Ls),!0;case"/autoconfirm":{let o=!Da();return up(o),console.log(`${i.green}Auto-confirm: ${o?"ON":"OFF"}${i.reset}`),o&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:o}=Ve(),{getConversationMessages:r}=ee(),a=s.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let l=Fe(),u=De();return o(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:o}=Ve(),{setConversationMessages:r}=ee(),a=s.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=o(a);return c?(r(c.messages),console.log(`${i.green}Loaded session: ${c.name} (${c.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:o}=Ve(),r=o();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
519
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=Ve(),{setConversationMessages:r}=ee(),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}=je(),r=s.join(" ").trim();if(!r)return console.log(`${i.red}Usage: /remember <key>=<value> or /remember <text>${i.reset}`),!0;let a=r.indexOf("="),c,l;return a>0?(c=r.substring(0,a).trim(),l=r.substring(a+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:o}=je(),r=s.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}=je(),r=o();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
520
|
+
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/learn":{let{learnFromSession:o}=eo(),{getConversationMessages:r}=ee(),a=r(),c=a.filter(l=>l.role==="user").length;if(c<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${c})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let l=await o(a);if(l.skipped)return console.log(`${i.dim}Session too short${i.reset}`),!0;if(l.error)return console.log(`${i.red}Reflection error: ${l.error}${i.reset}`),!0;if(console.log(""),l.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${l.summary}${i.reset}`),console.log("")),l.applied.length===0&&l.nexAdded.length===0)console.log(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(l.applied.length>0){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:u,value:d,action:f}of l.applied){let m=f==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${m} ${i.bold}${u}${i.reset} = ${d}`)}}if(l.nexAdded.length>0){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let u of l.nexAdded)console.log(` ${i.green}+${i.reset} ${u}`)}}console.log("")}catch(l){console.log(`${i.red}Learn failed: ${l.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=ee(),{getUsage:r}=xe(),{TOOL_DEFINITIONS:a}=Ke(),{listMemories:c}=je(),l=o(),u=r(l,a),d=Fe(),f=De(),m=c();console.log(`
|
|
519
521
|
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
520
522
|
`);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
523
|
${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
|
|
523
|
-
${i.bold}Session:${i.reset} ${x} turns, ${
|
|
524
|
-
${i.bold}Quick Wins:${i.reset}`);for(let k of w)console.log(` ${i.cyan}\u2192${i.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:
|
|
524
|
+
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let x=l.filter(k=>k.role==="user").length;console.log(`
|
|
525
|
+
${i.bold}Session:${i.reset} ${x} turns, ${l.length} messages total`),x>=4&&x%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
526
|
+
${i.bold}Quick Wins:${i.reset}`);for(let k of w)console.log(` ${i.cyan}\u2192${i.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=ht(),{invalidateSystemPromptCache:d}=ee(),f=s.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){a(),c(!1),d();let m=!!l();console.log(`${i.green}${i.bold}Plan approved!${i.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${i.dim}Plan mode disabled \u2014 all tools now available.${i.reset}`)}else console.log(`${i.red}No plan to approve. Enter plan mode first with /plan${i.reset}`);return!0}return c(!0),d(),console.log(`
|
|
525
527
|
${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
528
|
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
527
529
|
${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
530
|
${i.cyan}${i.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:o}=ht(),r=o();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
529
|
-
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let
|
|
530
|
-
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let
|
|
531
|
+
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=ht(),c=s.join(" ").trim();return c?(r(c)?console.log(`${i.green}Autonomy: ${c}${i.reset}`):console.log(`${i.red}Unknown level: ${c}. Use: ${a.join(", ")}${i.reset}`),!0):(console.log(`${i.bold}${i.cyan}Autonomy:${i.reset} ${o()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:o}=Dt(),r=o();console.log(`
|
|
532
|
+
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let c=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${c} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
531
533
|
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
532
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
534
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=Dt(),a=s.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}=Dt(),a=s.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:c}=ze(),{confirm:l}=Te();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=s.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${i.green}Committed: ${p} \u2014 ${u}${i.reset}`:`${i.red}Commit failed${i.reset}`),!0}if(!a())return console.log(`${i.yellow}No changes to commit${i.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${i.green} \u2713 Committed: ${h}${i.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=ze();return o()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=ze(),{processInput:a}=ee(),c=s.join(" ").trim(),l;if(c)l=`Do a thorough code review of \`${c}\`. Check for bugs, security issues, code quality, correctness, and suggest concrete improvements. Format findings by severity (critical, warning, suggestion).`;else{if(!o())return console.log(`${i.red}Not a git repository \u2014 try /review <file>${i.reset}`),!0;let[u,d]=await Promise.all([r(!1),r(!0)]),f=d||u;if(!f||!f.trim())return console.log(`${i.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${i.reset}`),!0;l=`Review the following code diff for bugs, security issues, code quality, and improvements. Format findings by severity (critical, warning, suggestion):
|
|
533
535
|
|
|
534
536
|
\`\`\`diff
|
|
535
537
|
${f.substring(0,2e4)}
|
|
536
|
-
\`\`\``}return await a(
|
|
537
|
-
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of
|
|
538
|
+
\`\`\``}return await a(l),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:a}=ze();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let c=s.join(" ").trim();if(!c){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let l=a(c);return console.log(l?`${i.green}Created and switched to: ${l}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:a}=ls(),c=s.join(" ").trim();if(c==="connect")return console.log(`${i.dim}Connecting MCP servers...${i.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${i.red}\u2717${i.reset} ${d.name}: ${d.error}`):console.log(` ${i.green}\u2713${i.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${i.dim}No MCP servers configured in .nex/config.json${i.reset}`)}).catch(u=>{console.log(`${i.red}MCP connection error: ${u.message}${i.reset}`)}),!0;if(c==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let l=o();if(l.length===0)return console.log(`${i.dim}No MCP servers configured${i.reset}`),console.log(`${i.dim}Add servers to .nex/config.json under "mcpServers"${i.reset}`),!0;console.log(`
|
|
539
|
+
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of l){let d=u.connected?`${i.green}\u2713 connected${i.reset}`:`${i.dim}\u25CB disconnected${i.reset}`;console.log(` ${d} ${i.bold}${u.name}${i.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
538
540
|
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
539
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
540
|
-
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let
|
|
541
|
-
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of
|
|
541
|
+
`),!0}case"/hooks":{let{listHooks:o}=Wn(),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(`
|
|
542
|
+
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:a}=Et(),c=s.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${i.green}Skill enabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return a(u)?console.log(`${i.yellow}Skill disabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}let l=o();if(l.length===0)return console.log(`${i.dim}No skills loaded${i.reset}`),console.log(`${i.dim}Add .md or .js files to .nex/skills/${i.reset}`),!0;console.log(`
|
|
543
|
+
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of l){let d=u.enabled?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,f=u.type==="prompt"?`${i.dim}(prompt)${i.reset}`:`${i.dim}(script)${i.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${i.bold}${u.name}${i.reset} ${f}${h}`)}return console.log(`
|
|
542
544
|
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
543
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
545
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=hs();return s.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
544
546
|
`+o()+`
|
|
545
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let
|
|
547
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to undo${i.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=ut(),a=o();if(!a)return console.log(`${i.yellow}Nothing to redo${i.reset}`),!0;console.log(`${i.green}Redone: ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:a}=ut(),c=o(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
546
548
|
${i.bold}File Change History${i.reset}
|
|
547
|
-
`);for(let
|
|
549
|
+
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${l.tool}${i.reset} ${l.filePath}`)}return console.log(`
|
|
548
550
|
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
549
551
|
`),!0}case"/exit":case"/quit":console.log(`
|
|
550
|
-
${i.dim}Bye!${i.reset}`),process.exit(0);default:return
|
|
551
|
-
`).filter(Boolean).slice(-io)}catch{}return[]}function
|
|
552
|
-
`)}catch{}}function
|
|
553
|
-
`),!0):!1)(),
|
|
552
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return cp(t)||console.log(`${i.red}Unknown command: ${n}. Type /help${i.reset}`),!0}}var io=1e3;function ao(){return ve.join(process.cwd(),".nex","repl_history")}function Ka(){try{let t=ao();if(Ue.existsSync(t))return Ue.readFileSync(t,"utf-8").split(`
|
|
553
|
+
`).filter(Boolean).slice(-io)}catch{}return[]}function qs(t){try{let e=ao(),n=ve.dirname(e);Ue.existsSync(n)||Ue.mkdirSync(n,{recursive:!0}),Ue.appendFileSync(e,t+`
|
|
554
|
+
`)}catch{}}function we(){let{isPlanMode:t,getAutonomyLevel:e}=ht(),n=[];t()&&n.push("plan");let s=e();s!=="interactive"&&n.push(s);let o=De(),r=Fe();return n.push(`${o}:${r.id}`),`${n.length>0?`${i.dim}[${n.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var co="\x1B[200~",lo="\x1B[201~";function dp(t){return typeof t=="string"&&t.includes(co)}function fp(t){return typeof t=="string"&&t.includes(lo)}function Ht(t){return typeof t!="string"?t:t.split(co).join("").split(lo).join("")}async function mp(){if(!ip("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:n}=require("util");return await n(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),La("local:llama3"),!0}catch{return!1}}async function pp(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=ee();t(Fa);let o=oo().some(M=>M.configured),r=(async()=>{ap();let M=Fe(),N=De();return{model:M,providerName:N}})(),a=(async()=>o?!0:await mp()?(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}
|
|
555
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:M}=Pa();return await M()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!o&&(console.error(`
|
|
554
556
|
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
555
|
-
`),process.exit(1)),
|
|
556
|
-
`),await
|
|
557
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",$),process.on("exit",()=>{
|
|
558
|
-
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(
|
|
557
|
+
`),process.exit(1)),np(`${l.providerName}:${l.model.id}`,Ls,{yolo:Da()}),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}
|
|
558
|
+
`),await ja(Ls);let f=Ka(),m=sp.createInterface({input:process.stdin,output:process.stdout,prompt:we(),completer:Ba,history:f,historySize:io});lp(m);let h=!1,p=0,x=!1,w=null;function $(){qa(),Ia(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
559
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)}process.on("SIGTERM",$),process.on("exit",()=>{qa()}),m.on("SIGINT",()=>{if(Ia(),h){if(p++,p>=2){$();return}Pe&&Pe.abort(),console.log(`
|
|
560
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),h=!1,m.setPrompt(we()),m.prompt();return}x?$():(x=!0,process.stdout.write(`
|
|
559
561
|
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
560
|
-
`),m.setPrompt(
|
|
562
|
+
`),m.setPrompt(we()),m.prompt(),w&&clearTimeout(w),w=setTimeout(()=>{x=!1,w=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||$()});let k=!1,T=[],b=null;function S(){let M=T.join(`
|
|
561
563
|
`).trim();if(T=[],k=!1,!M)return!0;b=M;let N=M.split(`
|
|
562
|
-
`),
|
|
563
|
-
${i.dim} ${U}${i.reset}`),console.log(`${i.dim} \u23BF ${L}${i.reset}`),
|
|
564
|
-
`)),S()}if(U){k=!0,T=[];let
|
|
565
|
-
`)),!0}if(W){let
|
|
566
|
-
`)),S()}if(k){let
|
|
567
|
-
`)),!0}return M.call(process.stdin,N,...
|
|
568
|
-
\x1B[2K ${i.cyan}${
|
|
569
|
-
\x1B[2K ${i.dim}\u2026 +${N.length-
|
|
570
|
-
`).trim();if(P=null,U){
|
|
571
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
572
|
-
`).trim();if(P=null,U){
|
|
573
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
574
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${W}${i.reset}`)}}h=!1;let{getConversationLength:
|
|
575
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)})}
|
|
564
|
+
`),I=N.length,L=N[0].length>80?N[0].substring(0,77)+"...":N[0],U=I>1?`[Pasted content \u2014 ${I} lines]`:"[Pasted content]";return console.log(`
|
|
565
|
+
${i.dim} ${U}${i.reset}`),console.log(`${i.dim} \u23BF ${L}${i.reset}`),I>1&&console.log(`${i.dim} \u23BF \u2026 +${I-1} more lines${i.reset}`),console.log(`${i.dim} Press Enter to send${i.reset}`),!0}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let M=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(N,...I){if(N!=="data")return M.call(process.stdin,N,...I);let L=I[0];if(Buffer.isBuffer(L)&&(L=L.toString("utf8")),typeof L!="string")return M.call(process.stdin,N,...I);let U=L.includes(co),W=L.includes(lo);if(U&&W){let z=Ht(L);return z&&T.push(...z.split(`
|
|
566
|
+
`)),S()}if(U){k=!0,T=[];let z=Ht(L);return z&&T.push(...z.split(`
|
|
567
|
+
`)),!0}if(W){let z=Ht(L);return z&&T.push(...z.split(`
|
|
568
|
+
`)),S()}if(k){let z=Ht(L);return z&&T.push(...z.split(`
|
|
569
|
+
`)),!0}return M.call(process.stdin,N,...I)}}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=[...js,...ro()].filter(se=>se.cmd.startsWith(M));if(!N.length||N.length===1&&N[0].cmd===M)return;let I=10,L=N.slice(0,I),U=Math.max(...L.map(se=>se.cmd.length)),W="";for(let{cmd:se,desc:ne}of L){let be=se.substring(0,M.length),Gt=se.substring(M.length),bt=" ".repeat(Math.max(0,U-se.length+2));W+=`
|
|
570
|
+
\x1B[2K ${i.cyan}${be}${i.reset}${i.dim}${Gt}${bt}${ne}${i.reset}`}_=L.length,N.length>I&&(W+=`
|
|
571
|
+
\x1B[2K ${i.dim}\u2026 +${N.length-I} more${i.reset}`,_++);let z=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;W+=`\x1B[${_}A\x1B[${z+m.cursor+1}G`,process.stdout.write(W)}process.stdin.isTTY&&process.stdin.on("keypress",(M,N)=>{C(),!(N&&(N.name==="tab"||N.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&E(m.line)})});let P=null,q=`${i.dim}...${i.reset} `;m.setPrompt(we()),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(`
|
|
572
|
+
`).trim();if(P=null,U){qs(U.replace(/\n/g,"\\n")),h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await n(U)}catch(z){if(!Pe?.signal?.aborted){let se=z.message?.split(`
|
|
573
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${se}${i.reset}`)}}h=!1;let W=I();W>0&&process.stdout.write(`${i.gray}[${W} messages] ${i.reset}`)}m.setPrompt(we()),m.prompt();return}P.push(M),m.setPrompt(q),m.prompt();return}if(M.endsWith("\\"))P.push(M.slice(0,-1));else{P.push(M);let U=P.join(`
|
|
574
|
+
`).trim();if(P=null,U){qs(U.replace(/\n/g,"\\n")),h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await n(U)}catch(se){if(!Pe?.signal?.aborted){let ne=se.message?.split(`
|
|
575
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${ne}${i.reset}`)}}let{getConversationLength:W}=ee();h=!1;let z=W();z>0&&process.stdout.write(`${i.gray}[${z} messages] ${i.reset}`)}m.setPrompt(we()),m.prompt();return}m.setPrompt(q),m.prompt();return}if(M.trim()==='"""'||M.trim().startsWith('"""')){let U=M.trim().substring(3);P=U?[U]:[],P._mode="triple",m.setPrompt(q),m.prompt();return}if(M.endsWith("\\")){P=[M.slice(0,-1)],P._mode="backslash",m.setPrompt(q),m.prompt();return}let N=M.trim();if(!N){m.setPrompt(we()),m.prompt();return}if(qs(N),N==="/"){Ua(),m.setPrompt(we()),m.prompt();return}if(N.startsWith("/")){await za(N,m),m.setPrompt(we()),m.prompt();return}h=!0,p=0,x=!1,w&&(clearTimeout(w),w=null),Pe=new AbortController;try{await n(N)}catch(U){if(!Pe?.signal?.aborted){let W=U.message?.split(`
|
|
576
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${W}${i.reset}`)}}h=!1;let{getConversationLength:I}=ee(),L=I();L>0&&process.stdout.write(`${i.gray}[${L} messages] ${i.reset}`),m.setPrompt(we()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
577
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}Ja.exports={startREPL:pp,getPrompt:we,loadHistory:Ka,appendHistory:qs,getHistoryPath:ao,HISTORY_MAX:io,showCommandList:Ua,completer:Ba,completeFilePath:Wa,handleSlashCommand:za,showProviders:no,showHelp:Ha,renderBar:Ga,hasPasteStart:dp,hasPasteEnd:fp,stripPasteSequences:Ht,getAbortSignal:Fa}});var Qa=require("path");require("dotenv").config({path:Qa.join(__dirname,"..",".env")});require("dotenv").config();var Y=process.argv.slice(2);(Y.includes("--help")||Y.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
576
578
|
|
|
577
579
|
Options:
|
|
578
580
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -585,4 +587,4 @@ Options:
|
|
|
585
587
|
--json Output result as JSON (for CI parsing)
|
|
586
588
|
-h, --help Show this help
|
|
587
589
|
-v, --version Show version
|
|
588
|
-
`),process.exit(0));if(
|
|
590
|
+
`),process.exit(0));if(Y.includes("-v")||Y.includes("--version")){let t=zt();console.log(t.version),process.exit(0)}var hp=Y.includes("--yolo")||Y.includes("-yolo");if(hp){let{setAutoConfirm:t}=Te();t(!0)}var uo=Y.indexOf("--model");if(uo!==-1&&Y[uo+1]){let{setActiveModel:t}=re();t(Y[uo+1])}var fo=Y.indexOf("--max-turns");if(fo!==-1&&Y[fo+1]){let t=parseInt(Y[fo+1],10);if(t>0){let{setMaxIterations:e}=ee();e(t)}}else try{let t=require("fs"),e=Qa.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),s=parseInt(n.maxIterations,10);if(s>0){let{setMaxIterations:o}=ee();o(s)}}}catch{}function mo(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let n=()=>{try{e.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}function Va(t){if(Y.includes("--auto")){let{setAutoConfirm:o}=Te();o(!0)}if(!Y.includes("--model")){let{setActiveModel:o}=re(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:n,getConversationMessages:s}=ee();n(t).then(()=>{if(Y.includes("--json")){let r=s().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{Y.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var Xa=Y.indexOf("--prompt-file");if(Xa!==-1){let t=Y[Xa+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),n;try{n=e.readFileSync(t,"utf-8").trim()}catch(s){console.error(`--prompt-file: cannot read file: ${s.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),Y.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}mo(),Va(n)}else{let t=Y.indexOf("--task");if(t!==-1){let e=Y[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),mo(),Va(e)}else{mo();let{startREPL:e}=Ya();e()}}
|