@mk-co/neox-cli 2.0.7

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.
@@ -0,0 +1,1891 @@
1
+ #!/usr/bin/env node
2
+ import*as an from'fs';import an__default,{readFileSync,createReadStream,realpathSync,existsSync,mkdirSync,writeFileSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync}from'fs';import*as te from'path';import te__default,{dirname,join,win32,posix}from'path';import*as ti from'os';import ti__default,{homedir,platform}from'os';import*as he from'fs/promises';import he__default,{readFile,realpath,readlink,readdir,lstat}from'fs/promises';import*as jo from'crypto';import {randomBytes,createHash,randomUUID}from'crypto';import {EventEmitter}from'events';import Td,{Stream}from'stream';import {StringDecoder}from'string_decoder';import {fileURLToPath}from'url';import {execa,execaSync}from'execa';import gv from'puppeteer-core';import*as Kp from'net';import {spawn,fork}from'child_process';import om from'fast-glob';import {performance as performance$1}from'perf_hooks';import*as zo from'readline';import zo__default from'readline';import kn from'prompts';import j from'chalk';import Mg from'ajv';import qb from'axios';import*as Dm from'tty';import Z,{createContext,forwardRef,useContext,useState,useEffect,useRef,useMemo,useLayoutEffect,PureComponent}from'react';import Oo,{cwd}from'process';import {throttle}from'es-toolkit/compat';import Ft from'ansi-escapes';import Ts from'is-in-ci';import t_ from'auto-bind';import {onExit}from'signal-exit';import s_ from'patch-console';import {NoEventPriority,DefaultEventPriority,LegacyRoot}from'react-reconciler/constants.js';import ae from'yoga-layout';import zx from'wrap-ansi';import lS from'react-reconciler';import Hx from'widest-line';import _n from'slice-ansi';import vo from'string-width';import {styledCharsFromTokens,tokenize,styledCharsToString}from'@alcalzone/ansi-tokenize';import Ro from'cli-cursor';import mh from'stack-utils';import {Buffer as Buffer$1}from'buffer';import E_ from'ink-spinner';var dg=Object.create;var ai=Object.defineProperty;var pg=Object.getOwnPropertyDescriptor;var mg=Object.getOwnPropertyNames;var hg=Object.getPrototypeOf,fg=Object.prototype.hasOwnProperty;var fu=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var K=(s,e)=>()=>(s&&(e=s(s=0)),e);var Us=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Fs=(s,e)=>{for(var t in e)ai(s,t,{get:e[t],enumerable:true});},gu=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mg(e))!fg.call(s,r)&&r!==t&&ai(s,r,{get:()=>e[r],enumerable:!(n=pg(e,r))||n.enumerable});return s};var yu=(s,e,t)=>(t=s!=null?dg(hg(s)):{},gu(ai(t,"default",{value:s,enumerable:true}),s)),gg=s=>gu(ai({},"__esModule",{value:true}),s);var $e={};Fs($e,{cliHealthMonitor:()=>Je,cliLogger:()=>f,debugLog:()=>vg,generateCurlCommand:()=>jn,installCrashHandler:()=>ma,logCurlCommand:()=>pa});function jn(s,e,t,n=true){let r=["curl -X POST \\"];r.push(` '${s}' \\`);for(let[o,a]of Object.entries(e)){let l=a;if(n){let c=o.toLowerCase();if(c==="authorization"||c==="x-api-key"||c==="anthropic-api-key")if(l.startsWith("Bearer ")){let u=l.slice(7);l=`Bearer ${u.slice(0,8)}...${u.slice(-4)}`;}else l.length>12&&(l=`${l.slice(0,8)}...${l.slice(-4)}`);}r.push(` -H '${o}: ${l}' \\`);}let i=JSON.stringify(t);return r.push(` -d '${bg(i)}'`),r.join(`
3
+ `)}function bg(s){return s.replace(/'/g,"'\\''")}function pa(s,e,t){if(process.env.CLI_DEBUG!=="1")return;let n=jn(s,e,t);f.info("CURL","=== LLM Request CURL Command ==="),f.info("CURL",n),f.info("CURL","=== End CURL Command ==="),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
4
+ [CURL] === LLM Request CURL Command ===`),console.log(n),console.log(`[CURL] === End CURL Command ===
5
+ `));}function vg(s,e,t){if(process.env.CLI_DEBUG==="1"&&(f.debug(s,e,t),process.env.CLI_DEBUG_CONSOLE==="1")){let n=s?`[${s}]`:"";t!==void 0?console.log(n,e,t):console.log(n,e);}}function ma(){process.on("uncaughtException",s=>{f.error("CRASH","Uncaught Exception",{name:s.name,message:s.message,stack:s.stack}),setTimeout(()=>process.exit(1),100);}),process.on("unhandledRejection",s=>{f.error("CRASH","Unhandled Rejection",{reason:s instanceof Error?{name:s.name,message:s.message,stack:s.stack}:s});});try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),f.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) initialized in crashHandler");}catch{}process.on("exit",()=>{f.close();});}var ua,f,da,Je,le=K(()=>{ua=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=te__default.join(ti__default.homedir(),".neox","logs");}init(){if(!this.initialized)try{an__default.existsSync(this.logDir)||an__default.mkdirSync(this.logDir,{recursive:!0}),this.initialized=!0;}catch{this.enabled=false;}}getLogFilePath(){let e=new Date().toISOString().split("T")[0];return te__default.join(this.logDir,`cli-${e}.log`)}ensureStream(){if(!this.enabled||(this.init(),!this.initialized))return null;let e=this.getLogFilePath();return this.currentLogFile!==e&&(this.writeStream&&this.writeStream.end(),this.writeStream=an__default.createWriteStream(e,{flags:"a"}),this.currentLogFile=e),this.writeStream}formatLocalTime(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return `${t}-${n}-${r} ${i}:${o}:${a}.${l}`}formatMessage(e,t,n,r){let i=this.formatLocalTime(),o=e.toUpperCase().padEnd(5),a=t?`[${t}]`:"",l=`${i} ${o} ${a} ${n}`;if(r!==void 0)try{let c=this.safeStringify(r);l+=` ${c}`;}catch{l+=" [Serialization Error]";}return l+`
6
+ `}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return "[Circular]";t.add(r);}return n==="parser"||n==="socket"||n==="_httpMessage"||n==="req"||n==="res"?"[Omitted]":r&&r.type==="Buffer"&&Array.isArray(r.data)?"[Buffer]":typeof r=="function"?"[Function]":r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:r})}write(e,t,n,r){if(!this.enabled)return;let i=this.ensureStream();if(!i||this.backpressured&&e==="debug")return;let o=this.formatMessage(e,t,n,r);!i.write(o)&&!this.backpressured&&(this.backpressured=true,i.once("drain",()=>{this.backpressured=false;}));}debug(e,t,n){this.write("debug",e,t,n);}info(e,t,n){this.write("info",e,t,n);}warn(e,t,n){this.write("warn",e,t,n);}error(e,t,n){this.write("error",e,t,n);}log(e,...t){let n=t.map(r=>{if(typeof r=="string")return r;try{return this.safeStringify(r)}catch{return String(r)}}).join(" ");this.write("info",e,n);}setEnabled(e){this.enabled=e;}getLogDir(){return this.logDir}getCurrentLogFile(){return this.currentLogFile}close(){this.writeStream&&(this.writeStream.end(),this.writeStream=null,this.currentLogFile=null);}},f=new ua;da=class{intervalId=null;lastHeartbeat=Date.now();heartbeatCount=0;stdinPausedCount=0;enabled=false;pid=process.pid;start(e=5e3){if(!(this.intervalId||process.env.CLI_DEBUG!=="1")){if(!process.stdin.isTTY){f.debug("HEALTH",`Skipping health monitor in non-TTY process (pid=${this.pid})`);return}this.enabled=true,this.lastHeartbeat=Date.now(),this.heartbeatCount=0,this.stdinPausedCount=0,f.info("HEALTH",`Health monitor started (interval: ${e}ms, pid=${this.pid})`),this.intervalId=setInterval(()=>{this.checkHealth();},e),this.intervalId.unref();}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,this.enabled=false,f.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let n=this.getStdinState();if(n.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,n.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){f.warn("HEALTH",`[pid=${this.pid}] stdin destroyed for ${this.stdinDestroyedCount} checks, exiting to avoid zombie process`),this.stop(),setTimeout(()=>{process.exit(0);},100);return}}else this.stdinDestroyedCount=0;f.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:n,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&f.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:n}),t>1e4&&f.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F Event loop delay detected: ${t}ms (expected ~5000ms)`);}getStdinState(){let e=process.stdin;return {isPaused:typeof e.isPaused=="function"?e.isPaused():false,isTTY:!!e.isTTY,isRaw:!!e.isRaw,readable:e.readable,destroyed:e.destroyed}}logStdinState(e){if(process.env.CLI_DEBUG!=="1")return;let t=this.getStdinState();f.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&f.debug("INK",`[${e}]`,t);}},Je=new da;});var Ou=Us((L0,Lu)=>{var Au=fu("fs"),ya=fu("path"),Mu=ya.join(__dirname,"path.txt");function Eg(){let s;if(Au.existsSync(Mu)&&(s=Au.readFileSync(Mu,"utf-8")),process.env.ELECTRON_OVERRIDE_DIST_PATH)return ya.join(process.env.ELECTRON_OVERRIDE_DIST_PATH,s||"electron");if(s)return ya.join(__dirname,"dist",s);throw new Error("Electron failed to install correctly, please delete node_modules/electron and try installing again")}Lu.exports=Eg();});var Nu,zs,fi,gi,zn,qs=K(()=>{Nu={enabled:false,autoPrompt:true,languages:["typescript","javascript","python","java","go","rust"],include:["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py","**/*.java","**/*.go","**/*.rs"],exclude:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/__pycache__/**","**/target/**","**/vendor/**"],cacheDir:".neox/index",maxFileSize:5},zs=200,fi=10,gi=4e3,zn=700;});function Uu(s){return createHash("md5").update(s).digest("hex")}async function Fu(s){try{return await he.access(s),!0}catch{return false}}async function Ks(s){try{await he.mkdir(s,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async function Ta(s,e,t){let r=(await he.readFile(s,"utf-8")).split(`
7
+ `),i=r.length,o=Math.max(0,e-1),a=Math.min(r.length,t);return {lines:r.slice(o,a),totalLines:i}}function Ke(s,e){return s.map((t,n)=>`${String(e+n).padStart(6)} \u2502 ${t}`).join(`
8
+ `)}function Vn(s,e){let n=te.relative(e,s).split(te.sep),r=n.findIndex(i=>["src","lib","app","core","packages","modules"].includes(i));return r>=0&&r+1<n.length?n[r+1]:n[0]||"root"}function wa(s){let e=te.extname(s).toLowerCase();return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".vue":"vue",".svelte":"svelte"}[e]||null}function mn(s,e,t="{([",n="})]"){let r=[],i=false;for(let o=e;o<s.length;o++){let a=s[o];for(let l of a){let c=t.indexOf(l),u=n.indexOf(l);c!==-1?(r.push(n[c]),i=true):u!==-1&&r.length>0&&r[r.length-1]===l&&r.pop();}if(i&&r.length===0)return o+1}return Math.min(e+500,s.length)}function Bu(s,e,t=["^\\s*(export\\s+)?(async\\s+)?function\\s+","^\\s*(export\\s+)?class\\s+","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?\\(","^\\s*(export\\s+)?(const|let|var)\\s+\\w+\\s*=\\s*(async\\s+)?function","^\\s*(public|private|protected|static|async)*\\s*\\w+\\s*\\(","^\\s*def\\s+","^\\s*class\\s+","^\\s*func\\s+","^\\s*fn\\s+"]){let n=t.map(r=>new RegExp(r));for(let r=e;r>=0;r--){let i=s[r];for(let o of n)if(o.test(i))return r;if(r<e&&i.trim()===""){let o=s.slice(0,r).reverse().findIndex(a=>a.trim()!=="");if(o>=0){let a=s[r-1-o];if(!a.trim().startsWith("@")&&!a.trim().startsWith("#")&&!a.trim().startsWith("//")&&!a.trim().startsWith("/*"))break}}}return Math.max(0,e-5)}function ka(s,e){let t=s.length>e.length?s:e,n=s.length>e.length?e:s;if(t.length===0)return 1;let r=qg(t,n);return (t.length-r)/t.length}function qg(s,e){let t=s.length,n=e.length,r=Array(t+1).fill(null).map(()=>Array(n+1).fill(0));for(let i=0;i<=t;i++)r[i][0]=i;for(let i=0;i<=n;i++)r[0][i]=i;for(let i=1;i<=t;i++)for(let o=1;o<=n;o++)s[i-1]===e[o-1]?r[i][o]=r[i-1][o-1]:r[i][o]=Math.min(r[i-1][o]+1,r[i][o-1]+1,r[i-1][o-1]+1);return r[t][n]}function Yn(s){return s.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var Rn=K(()=>{});function Ca(s){return new yi(s)}var yi,Ea=K(()=>{qs();Rn();yi=class{workspacePath;indexManager=null;constructor(e){this.workspacePath=e;}setIndexManager(e){this.indexManager=e;}async read(e){let{path:t,locator:n,mode:r="smart",autoFullThreshold:i,chunkSize:o=zs,expandContext:a=fi,maxLines:l=gi,useIndex:c=true}=e;try{let u=this.resolvePath(t);if((await he.stat(u)).isDirectory())return this.errorResult(t,"\u8FD9\u662F\u4E00\u4E2A\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6");switch(r){case "full":return this.readFull(u,t,l);case "chunk":return !n||n.type!=="line"?this.readChunk(u,t,1,o):this.readChunk(u,t,n.start,n.end?n.end-n.start+1:o);case "smart":default:return this.smartRead(u,t,n,{autoFullThreshold:i,chunkSize:o,expandContext:a,maxLines:l,useIndex:c})}}catch(u){return u.code==="ENOENT"?this.errorResult(t,"\u6587\u4EF6\u4E0D\u5B58\u5728"):this.errorResult(t,u.message)}}async smartRead(e,t,n,r){let{autoFullThreshold:i,chunkSize:o,expandContext:a,maxLines:l,useIndex:c}=r;if(!n){if(typeof i=="number"&&i>0){let u=await he.readFile(e,"utf-8"),d=Yn(u).split(`
9
+ `),p=d.length;if(p<=i){let g=Math.min(p,l),y=d.slice(0,g);return {success:true,path:t,totalLines:p,startLine:1,endLine:g,content:Ke(y,1),truncated:g<p,strategy:"full"}}let m=Math.min(o,p),h=d.slice(0,m);return {success:true,path:t,totalLines:p,startLine:1,endLine:m,content:Ke(h,1),truncated:m<p,strategy:"chunk"}}return this.readChunk(e,t,1,o)}switch(n.type){case "line":return this.readByLine(e,t,n.start,n.end,o);case "pattern":return this.readByPattern(e,t,n.regex,{matchIndex:n.matchIndex||1,context:n.context||a,chunkSize:o});case "symbol":return this.readBySymbol(e,t,n.name,{kind:n.kind,fuzzy:n.fuzzy,chunkSize:o,useIndex:c});case "function":return this.readBySymbol(e,t,n.name,{kind:"function",className:n.className,chunkSize:o,useIndex:c});case "class":return this.readBySymbol(e,t,n.name,{kind:"class",chunkSize:o,useIndex:c});case "range":return this.readByRange(e,t,n.startPattern,n.endPattern,o);default:return this.readChunk(e,t,1,o)}}async readByLine(e,t,n,r,i){let o=r||n+i-1,{lines:a,totalLines:l}=await Ta(e,n,o);return {success:true,path:t,totalLines:l,startLine:n,endLine:Math.min(o,l),content:Ke(a,n),truncated:o<l,strategy:"chunk"}}async readByPattern(e,t,n,r){let{matchIndex:i,context:o,chunkSize:a}=r,c=(await he.readFile(e,"utf-8")).split(`
10
+ `),u=c.length,d;try{d=new RegExp(n,"gi");}catch(x){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${x.message}`)}let p=[];if(c.forEach((x,S)=>{d.test(x)&&p.push(S+1),d.lastIndex=0;}),p.length===0)return {success:true,path:t,totalLines:u,startLine:1,endLine:Math.min(a,u),content:`\u672A\u627E\u5230\u5339\u914D: "${n}"
11
+
12
+ `+Ke(c.slice(0,Math.min(50,u)),1),truncated:false,strategy:"grep",metadata:{module:Vn(e,this.workspacePath)}};let m=p[Math.min(i-1,p.length-1)],h=Math.max(1,m-o),g=Math.min(u,m+a-o),y=c.slice(h-1,g);return {success:true,path:t,totalLines:u,startLine:h,endLine:g,content:Ke(y,h),truncated:g<u,strategy:"grep",metadata:{matchedLine:m,module:Vn(e,this.workspacePath)}}}async readBySymbol(e,t,n,r){let{kind:i,className:o,fuzzy:a,chunkSize:l,useIndex:c}=r;if(c&&this.indexManager){let d=await this.readBySymbolFromIndex(e,t,n,i,o);if(d)return d}let u=this.buildSymbolPattern(n,i,o);return this.readSymbolBlock(e,t,u,n,l)}async readBySymbolFromIndex(e,t,n,r,i){if(!this.indexManager)return null;try{let o=await this.indexManager.getFileIndex(e);if(!o)return null;let a;if(i){let u=o.symbols.find(d=>d.kind==="class"&&d.name===i);u?.children&&(a=u.children.find(d=>d.name===n));}else a=o.symbols.find(u=>r&&u.kind!==r?!1:u.name===n);if(!a)return null;let{lines:l,totalLines:c}=await Ta(e,a.startLine,a.endLine);return {success:!0,path:t,totalLines:c,startLine:a.startLine,endLine:a.endLine,content:Ke(l,a.startLine),truncated:!1,strategy:"index",metadata:{symbol:a,module:Vn(e,this.workspacePath)}}}catch{return null}}async readSymbolBlock(e,t,n,r,i){let a=(await he.readFile(e,"utf-8")).split(`
13
+ `),l=a.length,c;try{c=new RegExp(n,"i");}catch{c=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");}let u=-1;for(let g=0;g<a.length;g++)if(c.test(a[g])){u=g;break}if(u===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(i,l),content:`\u672A\u627E\u5230\u7B26\u53F7: "${r}"
14
+
15
+ `+Ke(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};let d=Bu(a,u),p=mn(a,d),m=Math.min(p,d+i),h=a.slice(d,m);return {success:true,path:t,totalLines:l,startLine:d+1,endLine:m,content:Ke(h,d+1),truncated:m<p,strategy:"grep",metadata:{matchedLine:u+1,module:Vn(e,this.workspacePath)}}}async readByRange(e,t,n,r,i){let a=(await he.readFile(e,"utf-8")).split(`
16
+ `),l=a.length,c,u;try{c=new RegExp(n,"i"),u=new RegExp(r,"i");}catch(g){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${g.message}`)}let d=-1,p=-1;for(let g=0;g<a.length;g++)if(d===-1&&c.test(a[g])&&(d=g),d!==-1&&u.test(a[g])){p=g;break}if(d===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(i,l),content:`\u672A\u627E\u5230\u8D77\u59CB\u6A21\u5F0F: "${n}"
17
+
18
+ `+Ke(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};p===-1&&(p=Math.min(d+i-1,l-1));let m=Math.min(p+1,d+i),h=a.slice(d,m);return {success:true,path:t,totalLines:l,startLine:d+1,endLine:m,content:Ke(h,d+1),truncated:m<p+1,strategy:"grep",metadata:{module:Vn(e,this.workspacePath)}}}async readChunk(e,t,n,r){let i=await he.readFile(e,"utf-8"),o=Yn(i).split(`
19
+ `),a=o.length,l=Math.max(1,n),c=Math.min(l+r-1,a),u=o.slice(l-1,c);return {success:true,path:t,totalLines:a,startLine:l,endLine:c,content:Ke(u,l),truncated:c<a,strategy:"chunk"}}async readFull(e,t,n){let r=await he.readFile(e,"utf-8"),i=Yn(r).split(`
20
+ `),o=i.length,a=Math.min(o,n),l=i.slice(0,a);return {success:true,path:t,totalLines:o,startLine:1,endLine:a,content:Ke(l,1),truncated:a<o,strategy:"full"}}buildSymbolPattern(e,t,n){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i={function:`(function|async\\s+function|const|let|var)\\s+${r}\\s*[=(<]`,class:`class\\s+${r}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${r}(\\s+extends|\\s*\\{|\\s*$)`,method:n?`(${r}|${n}\\.${r})\\s*\\(`:`${r}\\s*\\(`,variable:`(const|let|var)\\s+${r}\\s*[=:]`,type:`type\\s+${r}\\s*[=<]`,enum:`enum\\s+${r}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${r}`};return t&&i[t]?i[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${r}|${r}\\s*(=|\\()`}resolvePath(e){return te.isAbsolute(e)?e:te.resolve(this.workspacePath,e)}errorResult(e,t){return {success:false,path:e,totalLines:0,startLine:0,endLine:0,content:"",truncated:false,strategy:"chunk",error:t}}};});var Ju=Us((mw,Hu)=>{Hu.exports=Gu;function Gu(s,e,t){s instanceof RegExp&&(s=ju(s,t)),e instanceof RegExp&&(e=ju(e,t));var n=Wu(s,e,t);return n&&{start:n[0],end:n[1],pre:t.slice(0,n[0]),body:t.slice(n[0]+s.length,n[1]),post:t.slice(n[1]+e.length)}}function ju(s,e){var t=e.match(s);return t?t[0]:null}Gu.range=Wu;function Wu(s,e,t){var n,r,i,o,a,l=t.indexOf(s),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(s===e)return [l,c];for(n=[],i=t.length;u>=0&&!a;)u==l?(n.push(u),l=t.indexOf(s,u+1)):n.length==1?a=[n.pop(),c]:(r=n.pop(),r<i&&(i=r,o=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;n.length&&(a=[i,o]);}return a}});var Qu=Us((hw,Zu)=>{var zu=Ju();Zu.exports=Yg;var qu="\0SLASH"+Math.random()+"\0",Ku="\0OPEN"+Math.random()+"\0",Ra="\0CLOSE"+Math.random()+"\0",Vu="\0COMMA"+Math.random()+"\0",Yu="\0PERIOD"+Math.random()+"\0";function Ia(s){return parseInt(s,10)==s?parseInt(s,10):s.charCodeAt(0)}function Kg(s){return s.split("\\\\").join(qu).split("\\{").join(Ku).split("\\}").join(Ra).split("\\,").join(Vu).split("\\.").join(Yu)}function Vg(s){return s.split(qu).join("\\").split(Ku).join("{").split(Ra).join("}").split(Vu).join(",").split(Yu).join(".")}function Xu(s){if(!s)return [""];var e=[],t=zu("{","}",s);if(!t)return s.split(",");var n=t.pre,r=t.body,i=t.post,o=n.split(",");o[o.length-1]+="{"+r+"}";var a=Xu(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function Yg(s){return s?(s.substr(0,2)==="{}"&&(s="\\{\\}"+s.substr(2)),Vs(Kg(s),true).map(Vg)):[]}function Xg(s){return "{"+s+"}"}function Zg(s){return /^-?0\d/.test(s)}function Qg(s,e){return s<=e}function ey(s,e){return s>=e}function Vs(s,e){var t=[],n=zu("{","}",s);if(!n)return [s];var r=n.pre,i=n.post.length?Vs(n.post,false):[""];if(/\$$/.test(n.pre))for(var o=0;o<i.length;o++){var a=r+"{"+n.body+"}"+i[o];t.push(a);}else {var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),u=l||c,d=n.body.indexOf(",")>=0;if(!u&&!d)return n.post.match(/,(?!,).*\}/)?(s=n.pre+"{"+n.body+Ra+n.post,Vs(s)):[s];var p;if(u)p=n.body.split(/\.\./);else if(p=Xu(n.body),p.length===1&&(p=Vs(p[0],false).map(Xg),p.length===1))return i.map(function(E){return n.pre+p[0]+E});var m;if(u){var h=Ia(p[0]),g=Ia(p[1]),y=Math.max(p[0].length,p[1].length),x=p.length==3?Math.abs(Ia(p[2])):1,S=Qg,T=g<h;T&&(x*=-1,S=ey);var w=p.some(Zg);m=[];for(var L=h;S(L,g);L+=x){var B;if(c)B=String.fromCharCode(L),B==="\\"&&(B="");else if(B=String(L),w){var I=y-B.length;if(I>0){var k=new Array(I+1).join("0");L<0?B="-"+k+B.slice(1):B=k+B;}}m.push(B);}}else {m=[];for(var R=0;R<p.length;R++)m.push.apply(m,Vs(p[R],false));}for(var R=0;R<m.length;R++)for(var o=0;o<i.length;o++){var a=r+m[R]+i[o];(!e||u||a)&&t.push(a);}}return t}});var Ys,ed=K(()=>{Ys=s=>{if(typeof s!="string")throw new TypeError("invalid pattern");if(s.length>65536)throw new TypeError("pattern is too long")};});var ty,Xs,ny,td,nd,sd=K(()=>{ty={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",true],"[:alpha:]":["\\p{L}\\p{Nl}",true],"[:ascii:]":["\\x00-\\x7f",false],"[:blank:]":["\\p{Zs}\\t",true],"[:cntrl:]":["\\p{Cc}",true],"[:digit:]":["\\p{Nd}",true],"[:graph:]":["\\p{Z}\\p{C}",true,true],"[:lower:]":["\\p{Ll}",true],"[:print:]":["\\p{C}",true],"[:punct:]":["\\p{P}",true],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",true],"[:upper:]":["\\p{Lu}",true],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",true],"[:xdigit:]":["A-Fa-f0-9",false]},Xs=s=>s.replace(/[[\]\\-]/g,"\\$&"),ny=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),td=s=>s.join(""),nd=(s,e)=>{let t=e;if(s.charAt(t)!=="[")throw new Error("not in a brace expression");let n=[],r=[],i=t+1,o=false,a=false,l=false,c=false,u=t,d="";e:for(;i<s.length;){let g=s.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=true,i++;continue}if(g==="]"&&o&&!l){u=i+1;break}if(o=true,g==="\\"&&!l){l=true,i++;continue}if(g==="["&&!l){for(let[y,[x,S,T]]of Object.entries(ty))if(s.startsWith(y,i)){if(d)return ["$.",false,s.length-t,true];i+=y.length,T?r.push(x):n.push(x),a=a||S;continue e}}if(l=false,d){g>d?n.push(Xs(d)+"-"+Xs(g)):g===d&&n.push(Xs(g)),d="",i++;continue}if(s.startsWith("-]",i+1)){n.push(Xs(g+"-")),i+=2;continue}if(s.startsWith("-",i+1)){d=g,i+=2;continue}n.push(Xs(g)),i++;}if(u<i)return ["",false,0,false];if(!n.length&&!r.length)return ["$.",false,s.length-t,true];if(r.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let g=n[0].length===2?n[0].slice(-1):n[0];return [ny(g),false,u-t,false]}let p="["+(c?"^":"")+td(n)+"]",m="["+(c?"":"^")+td(r)+"]";return [n.length&&r.length?"("+p+"|"+m+")":n.length?p:m,a,u-t,true]};});var wt,vi=K(()=>{wt=(s,{windowsPathsNoEscape:e=false}={})=>e?s.replace(/\[([^\/\\])\]/g,"$1"):s.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");});var sy,rd,ry,xi,iy,oy,ay,ly,Pa,id,od,Xn,Aa=K(()=>{sd();vi();sy=new Set(["!","?","+","*","@"]),rd=s=>sy.has(s),ry="(?!(?:^|/)\\.\\.?(?:$|/))",xi="(?!\\.)",iy=new Set(["[","."]),oy=new Set(["..","."]),ay=new Set("().*{}+?[]^$\\!"),ly=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Pa="[^/]",id=Pa+"*?",od=Pa+"+?",Xn=class s{type;#e;#t;#i=false;#s=[];#o;#x;#c;#d=false;#a;#l;#r=false;constructor(e,t,n={}){this.type=e,e&&(this.#t=true),this.#o=t,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#d&&this.#c.push(this),this.#x=this.#o?this.#o.#s.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#s)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=true;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#s.map(e=>String(e)).join("|")+")":this.#l=this.#s.map(e=>String(e)).join("")}#g(){if(this!==this.#e)throw new Error("should only call on root");if(this.#d)return this;this.toString(),this.#d=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,n=t.#o;for(;n;){for(let r=t.#x+1;!n.type&&r<n.#s.length;r++)for(let i of e.#s){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(n.#s[r]);}t=n,n=t.#o;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof s&&t.#o===this))throw new Error("invalid part: "+t);this.#s.push(t);}}toJSON(){let e=this.type===null?this.#s.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#s.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#d&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#o?.isStart())return false;if(this.#x===0)return true;let e=this.#o;for(let t=0;t<this.#x;t++){let n=e.#s[t];if(!(n instanceof s&&n.type==="!"))return false}return true}isEnd(){if(this.#e===this||this.#o?.type==="!")return true;if(!this.#o?.isEnd())return false;if(!this.type)return this.#o?.isEnd();let e=this.#o?this.#o.#s.length:0;return this.#x===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new s(this.type,e);for(let n of this.#s)t.copyIn(n);return t}static#y(e,t,n,r){let i=false,o=false,a=-1,l=false;if(t.type===null){let m=n,h="";for(;m<e.length;){let g=e.charAt(m++);if(i||g==="\\"){i=!i,h+=g;continue}if(o){m===a+1?(g==="^"||g==="!")&&(l=true):g==="]"&&!(m===a+2&&l)&&(o=false),h+=g;continue}else if(g==="["){o=true,a=m,l=false,h+=g;continue}if(!r.noext&&rd(g)&&e.charAt(m)==="("){t.push(h),h="";let y=new s(g,t);m=s.#y(e,y,m,r),t.push(y);continue}h+=g;}return t.push(h),m}let c=n+1,u=new s(null,t),d=[],p="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,p+=m;continue}if(o){c===a+1?(m==="^"||m==="!")&&(l=true):m==="]"&&!(c===a+2&&l)&&(o=false),p+=m;continue}else if(m==="["){o=true,a=c,l=false,p+=m;continue}if(rd(m)&&e.charAt(c)==="("){u.push(p),p="";let h=new s(m,u);u.push(h),c=s.#y(e,h,c,r);continue}if(m==="|"){u.push(p),p="",d.push(u),u=new s(null,t);continue}if(m===")")return p===""&&t.#s.length===0&&(t.#r=true),u.push(p),p="",t.push(...d,u),c;p+=m;}return t.type=null,t.#t=void 0,t.#s=[e.substring(n-1)],c}static fromGlob(e,t={}){let n=new s(null,void 0,t);return s.#y(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,r,i]=this.toRegExpSource();if(!(r||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#g(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#s.map(m=>{let[h,g,y,x]=typeof m=="string"?s.#p(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||y,this.#i=this.#i||x,h}).join(""),u="";if(this.isStart()&&typeof this.#s[0]=="string"&&!(this.#s.length===1&&oy.has(this.#s[0]))){let h=iy,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),y=!t&&!e&&h.has(c.charAt(0));u=g?ry:y?xi:"";}let d="";return this.isEnd()&&this.#e.#d&&this.#o?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,wt(c),this.#t=!!this.#t,this.#i]}let n=this.type==="*"||this.type==="+",r=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#s=[l],this.type=null,this.#t=void 0,[l,wt(this.toString()),false,false]}let o=!n||e||t||!xi?"":this.#m(true);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let a="";if(this.type==="!"&&this.#r)a=(this.isStart()&&!t?xi:"")+od;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?xi:"")+id+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=r+i+l;}return [a,wt(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#s.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[n,r,i,o]=t.toRegExpSource(e);return this.#i=this.#i||o,n}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#p(e,t,n=false){let r=false,i="",o=false;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(r){r=false,i+=(ay.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":r=true;continue}if(l==="["){let[c,u,d,p]=nd(e,a);if(d){i+=c,o=o||u,a+=d-1,t=t||p;continue}}if(l==="*"){n&&e==="*"?i+=od:i+=id,t=true;continue}if(l==="?"){i+=Pa,t=true;continue}i+=ly(l);}return [i,wt(e),!!t,o]}};});var Zn,Ma=K(()=>{Zn=(s,{windowsPathsNoEscape:e=false}={})=>e?s.replace(/[?*()[\]]/g,"[$&]"):s.replace(/[?*()[\]\\]/g,"\\$&");});var cd,Ze,cy,uy,dy,py,my,hy,fy,gy,yy,by,vy,xy,Sy,_y,Ty,wy,ky,Cy,ud,dd,pd,ad,Ey,ze,Iy,Ry,Py,Ay,My,gt,Ly,md,Oy,Dy,ld,$y,it,hn=K(()=>{cd=yu(Qu());ed();Aa();Ma();vi();Aa();Ma();vi();Ze=(s,e,t={})=>(Ys(e),!t.nocomment&&e.charAt(0)==="#"?false:new it(e,t).match(s)),cy=/^\*+([^+@!?\*\[\(]*)$/,uy=s=>e=>!e.startsWith(".")&&e.endsWith(s),dy=s=>e=>e.endsWith(s),py=s=>(s=s.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(s)),my=s=>(s=s.toLowerCase(),e=>e.toLowerCase().endsWith(s)),hy=/^\*+\.\*+$/,fy=s=>!s.startsWith(".")&&s.includes("."),gy=s=>s!=="."&&s!==".."&&s.includes("."),yy=/^\.\*+$/,by=s=>s!=="."&&s!==".."&&s.startsWith("."),vy=/^\*+$/,xy=s=>s.length!==0&&!s.startsWith("."),Sy=s=>s.length!==0&&s!=="."&&s!=="..",_y=/^\?+([^+@!?\*\[\(]*)?$/,Ty=([s,e=""])=>{let t=ud([s]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},wy=([s,e=""])=>{let t=dd([s]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},ky=([s,e=""])=>{let t=dd([s]);return e?n=>t(n)&&n.endsWith(e):t},Cy=([s,e=""])=>{let t=ud([s]);return e?n=>t(n)&&n.endsWith(e):t},ud=([s])=>{let e=s.length;return t=>t.length===e&&!t.startsWith(".")},dd=([s])=>{let e=s.length;return t=>t.length===e&&t!=="."&&t!==".."},pd=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ad={win32:{sep:"\\"},posix:{sep:"/"}},Ey=pd==="win32"?ad.win32.sep:ad.posix.sep;Ze.sep=Ey;ze=Symbol("globstar **");Ze.GLOBSTAR=ze;Iy="[^/]",Ry=Iy+"*?",Py="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Ay="(?:(?!(?:\\/|^)\\.).)*?",My=(s,e={})=>t=>Ze(t,s,e);Ze.filter=My;gt=(s,e={})=>Object.assign({},s,e),Ly=s=>{if(!s||typeof s!="object"||!Object.keys(s).length)return Ze;let e=Ze;return Object.assign((n,r,i={})=>e(n,r,gt(s,i)),{Minimatch:class extends e.Minimatch{constructor(r,i={}){super(r,gt(s,i));}static defaults(r){return e.defaults(gt(s,r)).Minimatch}},AST:class extends e.AST{constructor(r,i,o={}){super(r,i,gt(s,o));}static fromGlob(r,i={}){return e.AST.fromGlob(r,gt(s,i))}},unescape:(n,r={})=>e.unescape(n,gt(s,r)),escape:(n,r={})=>e.escape(n,gt(s,r)),filter:(n,r={})=>e.filter(n,gt(s,r)),defaults:n=>e.defaults(gt(s,n)),makeRe:(n,r={})=>e.makeRe(n,gt(s,r)),braceExpand:(n,r={})=>e.braceExpand(n,gt(s,r)),match:(n,r,i={})=>e.match(n,r,gt(s,i)),sep:e.sep,GLOBSTAR:ze})};Ze.defaults=Ly;md=(s,e={})=>(Ys(s),e.nobrace||!/\{(?:(?!\{).)*\}/.test(s)?[s]:(0, cd.default)(s));Ze.braceExpand=md;Oy=(s,e={})=>new it(s,e).makeRe();Ze.makeRe=Oy;Dy=(s,e,t={})=>{let n=new it(e,t);return s=s.filter(r=>n.match(r)),n.options.nonull&&!s.length&&s.push(e),s};Ze.match=Dy;ld=/[?*]|[+@!]\(.*?\)|\[|\]/,$y=s=>s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),it=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Ys(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||pd,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let r=this.globParts.map((i,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!ld.test(i[2]))&&!ld.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return [...i.slice(0,4),...i.slice(4).map(u=>this.parse(u))];if(c)return [i[0],...i.slice(1).map(u=>this.parse(u))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,r),this.set=r.filter(i=>i.indexOf(false)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let o=this.set[i];o[0]===""&&o[1]===""&&this.globParts[i][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let r=0;r<e[n].length;r++)e[n][r]==="**"&&(e[n][r]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let n=-1;for(;(n=t.indexOf("**",n+1))!==-1;){let r=n;for(;t[r+1]==="**";)r++;r!==n&&t.splice(n,r-n);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((n,r)=>{let i=n[n.length-1];return r==="**"&&i==="**"?n:r===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(n.pop(),n):(n.push(r),n)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let r=1;r<e.length-1;r++){let i=e[r];r===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=true,e.splice(r,1),r--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let r=e[n-1];r&&r!=="."&&r!==".."&&r!=="**"&&(t=true,e.splice(n-1,2),n-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let n of e){let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let o=r;for(;n[o+1]==="**";)o++;o>r&&n.splice(r+1,o-r);let a=n[r+1],l=n[r+2],c=n[r+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,n.splice(r,1);let u=n.slice(0);u[r]="**",e.push(u),r--;}if(!this.preserveMultipleSlashes){for(let o=1;o<n.length-1;o++){let a=n[o];o===1&&a===""&&n[0]===""||(a==="."||a==="")&&(t=true,n.splice(o,1),o--);}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(t=true,n.pop());}let i=0;for(;(i=n.indexOf("..",i+1))!==-1;){let o=n[i-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=true;let l=i===1&&n[i+1]==="**"?["."]:[];n.splice(i-1,2,...l),n.length===0&&n.push(""),i-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let r=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(r){e[t]=[],e[n]=r;break}}return e.filter(t=>t.length)}partsMatch(e,t,n=false){let r=0,i=0,o=[],a="";for(;r<e.length&&i<t.length;)if(e[r]===t[i])o.push(a==="b"?t[i]:e[r]),r++,i++;else if(n&&e[r]==="**"&&t[i]===e[r+1])o.push(e[r]),r++;else if(n&&t[i]==="**"&&e[r]===t[i+1])o.push(t[i]),i++;else if(e[r]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return false;a="a",o.push(e[r]),r++,i++;}else if(t[i]==="*"&&e[r]&&(this.options.dot||!e[r].startsWith("."))&&e[r]!=="**"){if(a==="a")return false;a="b",o.push(t[i]),r++,i++;}else return false;return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,n=0;for(let r=0;r<e.length&&e.charAt(r)==="!";r++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t;}matchOne(e,t,n=false){let r=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),x=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!x&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),T=y?3:g?0:void 0,w=S?3:x?0:void 0;if(typeof T=="number"&&typeof w=="number"){let[L,B]=[e[T],t[w]];L.toLowerCase()===B.toLowerCase()&&(t[w]=L,w>T?t=t.slice(w):T>w&&(e=e.slice(T)));}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var o=0,a=0,l=e.length,c=t.length;o<l&&a<c;o++,a++){this.debug("matchOne loop");var u=t[a],d=e[o];if(this.debug(t,u,d),u===false)return false;if(u===ze){this.debug("GLOBSTAR",[t,u,d]);var p=o,m=a+1;if(m===c){for(this.debug("** at the end");o<l;o++)if(e[o]==="."||e[o]===".."||!r.dot&&e[o].charAt(0)===".")return false;return true}for(;p<l;){var h=e[p];if(this.debug(`
21
+ globstar while`,e,p,t,m,h),this.matchOne(e.slice(p),t.slice(m),n))return this.debug("globstar found match!",p,l,h),true;if(h==="."||h===".."||!r.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,p,t,m);break}this.debug("globstar swallow a segment, and continue"),p++;}return !!(n&&(this.debug(`
22
+ >>> no match, partial?`,e,p,t,m),p===l))}let g;if(typeof u=="string"?(g=d===u,this.debug("string match",u,d,g)):(g=u.test(d),this.debug("pattern match",u,d,g)),!g)return false}if(o===l&&a===c)return true;if(o===l)return n;if(a===c)return o===l-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return md(this.pattern,this.options)}parse(e){Ys(e);let t=this.options;if(e==="**")return ze;if(e==="")return "";let n,r=null;(n=e.match(vy))?r=t.dot?Sy:xy:(n=e.match(cy))?r=(t.nocase?t.dot?my:py:t.dot?dy:uy)(n[1]):(n=e.match(_y))?r=(t.nocase?t.dot?wy:Ty:t.dot?ky:Cy)(n):(n=e.match(hy))?r=t.dot?gy:fy:(n=e.match(yy))&&(r=by);let i=Xn.fromGlob(e,this.options).toMMPattern();return r&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:r}),i}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,n=t.noglobstar?Ry:t.dot?Py:Ay,r=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))r.add(d);return typeof u=="string"?$y(u):u===ze?ze:u._src});return c.forEach((u,d)=>{let p=c[d+1],m=c[d-1];u!==ze||m===ze||(m===void 0?p!==void 0&&p!==ze?c[d+1]="(?:\\/|"+n+"\\/)?"+p:c[d]=n:p===void 0?c[d-1]=m+"(?:\\/|"+n+")?":p!==ze&&(c[d-1]=m+"(?:\\/|\\/"+n+"\\/)"+p,c[d+1]=ze));}),c.filter(u=>u!==ze).join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...r].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let r=this.slashSplit(e);this.debug(this.pattern,"split",r);let i=this.set;this.debug(this.pattern,"set",i);let o=r[r.length-1];if(!o)for(let a=r.length-2;!o&&a>=0;a--)o=r[a];for(let a=0;a<i.length;a++){let l=i[a],c=r;if(n.matchBase&&l.length===1&&(c=[o]),this.matchOne(c,l,t))return n.flipNegate?true:!this.negate}return n.flipNegate?false:this.negate}static defaults(e){return Ze.defaults(e).Minimatch}};Ze.AST=Xn;Ze.Minimatch=it;Ze.escape=Zn;Ze.unescape=wt;});var Qn,fd,La,gd,Si,hd,Ny,fn,yd,es,Oa,Zs,bd=K(()=>{Qn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,fd=new Set,La=typeof process=="object"&&process?process:{},gd=(s,e,t,n)=>{typeof La.emitWarning=="function"?La.emitWarning(s,e,t,n):console.error(`[${t}] ${e}: ${s}`);},Si=globalThis.AbortController,hd=globalThis.AbortSignal;if(typeof Si>"u"){hd=class{onabort;_onabort=[];reason;aborted=false;addEventListener(n,r){this._onabort.push(r);}},Si=class{constructor(){e();}signal=new hd;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=true;for(let r of this.signal._onabort)r(n);this.signal.onabort?.(n);}}};let s=La.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{s&&(s=false,gd("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e));};}Ny=s=>!fd.has(s),fn=s=>s&&s===Math.floor(s)&&s>0&&isFinite(s),yd=s=>fn(s)?s<=Math.pow(2,8)?Uint8Array:s<=Math.pow(2,16)?Uint16Array:s<=Math.pow(2,32)?Uint32Array:s<=Number.MAX_SAFE_INTEGER?es:null:null,es=class extends Array{constructor(e){super(e),this.fill(0);}},Oa=class s{heap;length;static#e=false;static create(e){let t=yd(e);if(!t)return [];s.#e=true;let n=new s(e,t);return s.#e=false,n}constructor(e,t){if(!s.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0;}push(e){this.heap[this.length++]=e;}pop(){return this.heap[--this.length]}},Zs=class s{#e;#t;#i;#s;#o;#x;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#d;#a;#l;#r;#g;#y;#m;#p;#T;#f;#w;#k;#v;#S;#_;#h;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#v,sizes:e.#w,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#g,prev:e.#y,get head(){return e.#m},get tail(){return e.#p},free:e.#T,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,n,r,i)=>e.#U(t,n,r,i),moveToTail:t=>e.#B(t),indexes:t=>e.#E(t),rindexes:t=>e.#I(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#d}get size(){return this.#c}get fetchMethod(){return this.#o}get memoMethod(){return this.#x}get dispose(){return this.#i}get disposeAfter(){return this.#s}constructor(e){let{max:t=0,ttl:n,ttlResolution:r=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:p,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:y,memoMethod:x,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:T,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:L,ignoreFetchAbort:B}=e;if(t!==0&&!fn(t))throw new TypeError("max option must be a nonnegative integer");let I=t?yd(t):Array;if(!I)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(x!==void 0&&typeof x!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#x=x,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#o=y,this.#_=!!y,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#g=new I(t),this.#y=new I(t),this.#m=0,this.#p=0,this.#T=Oa.create(t),this.#c=0,this.#d=0,typeof c=="function"&&(this.#i=c),typeof u=="function"?(this.#s=u,this.#f=[]):(this.#s=void 0,this.#f=void 0),this.#S=!!this.#i,this.#h=!!this.#s,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!p,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!w,this.allowStaleOnFetchAbort=!!L,this.ignoreFetchAbort=!!B,this.maxEntrySize!==0){if(this.#t!==0&&!fn(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!fn(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#P();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!T,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=fn(r)||r===0?r:1,this.ttlAutopurge=!!i,this.ttl=n||0,this.ttl){if(!fn(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#R();}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let k="LRU_CACHE_UNBOUNDED";Ny(k)&&(fd.add(k),gd("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",k,s));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#R(){let e=new es(this.#e),t=new es(this.#e);this.#v=e,this.#k=t,this.#M=(i,o,a=Qn.now())=>{if(t[i]=o!==0?a:0,e[i]=o,o!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(i)&&this.#A(this.#l[i],"expire");},o+1);l.unref&&l.unref();}},this.#C=i=>{t[i]=e[i]!==0?Qn.now():0;},this.#n=(i,o)=>{if(e[o]){let a=e[o],l=t[o];if(!a||!l)return;i.ttl=a,i.start=l,i.now=n||r();let c=i.now-l;i.remainingTTL=a-c;}};let n=0,r=()=>{let i=Qn.now();if(this.ttlResolution>0){n=i;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref();}return i};this.getRemainingTTL=i=>{let o=this.#a.get(i);if(o===void 0)return 0;let a=e[o],l=t[o];if(!a||!l)return 1/0;let c=(n||r())-l;return a-c},this.#b=i=>{let o=t[i],a=e[i];return !!a&&!!o&&(n||r())-o>a};}#C=()=>{};#n=()=>{};#M=()=>{};#b=()=>false;#P(){let e=new es(this.#e);this.#d=0,this.#w=e,this.#L=t=>{this.#d-=e[t],e[t]=0;},this.#D=(t,n,r,i)=>{if(this.#u(n))return 0;if(!fn(r))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(r=i(n,t),!fn(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r},this.#O=(t,n,r)=>{if(e[t]=n,this.#t){let i=this.#t-e[t];for(;this.#d>i;)this.#N(true);}this.#d+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#d);};}#L=e=>{};#O=(e,t,n)=>{};#D=(e,t,n,r)=>{if(n||r)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#E({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#p));)t=this.#g[t];}#$(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#E())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*rentries(){for(let e of this.#I())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*keys(){for(let e of this.#E()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*values(){for(let e of this.#E())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}*rvalues(){for(let e of this.#I())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let n of this.#E()){let r=this.#r[n],i=this.#u(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#E()){let r=this.#r[n],i=this.#u(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this);}}rforEach(e,t=this){for(let n of this.#I()){let r=this.#r[n],i=this.#u(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this);}}purgeStale(){let e=false;for(let t of this.#I({allowStale:true}))this.#b(t)&&(this.#A(this.#l[t],"expire"),e=true);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#r[t],r=this.#u(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#v&&this.#k){let o=this.#v[t],a=this.#k[t];if(o&&a){let l=o-(Qn.now()-a);i.ttl=l,i.start=Date.now();}}return this.#w&&(i.size=this.#w[t]),i}dump(){let e=[];for(let t of this.#E({allowStale:true})){let n=this.#l[t],r=this.#r[t],i=this.#u(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let o={value:i};if(this.#v&&this.#k){o.ttl=this.#v[t];let a=Qn.now()-this.#k[t];o.start=Math.floor(Date.now()-a);}this.#w&&(o.size=this.#w[t]),e.unshift([n,o]);}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let r=Date.now()-n.start;n.start=Qn.now()-r;}this.set(t,n.value,n);}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,u=this.#D(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#A(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#p:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#N(false):this.#c,this.#l[d]=e,this.#r[d]=t,this.#a.set(e,d),this.#g[this.#p]=d,this.#y[d]=this.#p,this.#p=d,this.#c++,this.#O(d,u,l),l&&(l.set="add"),c=false;else {this.#B(d);let p=this.#r[d];if(t!==p){if(this.#_&&this.#u(p)){p.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=p;m!==void 0&&!o&&(this.#S&&this.#i?.(m,e,"set"),this.#h&&this.#f?.push([m,e,"set"]));}else o||(this.#S&&this.#i?.(p,e,"set"),this.#h&&this.#f?.push([p,e,"set"]));if(this.#L(d),this.#O(d,u,l),this.#r[d]=t,l){l.set="replace";let m=p&&this.#u(p)?p.__staleWhileFetching:p;m!==void 0&&(l.oldValue=m);}}else l&&(l.set="update");}if(r!==0&&!this.#v&&this.#R(),this.#v&&(c||this.#M(d,r,i),l&&this.#n(l,d)),!o&&this.#h&&this.#f){let p=this.#f,m;for(;m=p?.shift();)this.#s?.(...m);}return this}pop(){try{for(;this.#c;){let e=this.#r[this.#m];if(this.#N(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#f){let e=this.#f,t;for(;t=e?.shift();)this.#s?.(...t);}}}#N(e){let t=this.#m,n=this.#l[t],r=this.#r[t];return this.#_&&this.#u(r)?r.__abortController.abort(new Error("evicted")):(this.#S||this.#h)&&(this.#S&&this.#i?.(r,n,"evict"),this.#h&&this.#f?.push([r,n,"evict"])),this.#L(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#p=0,this.#T.length=0):this.#m=this.#g[t],this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#a.get(e);if(i!==void 0){let o=this.#r[i];if(this.#u(o)&&o.__staleWhileFetching===void 0)return false;if(this.#b(i))r&&(r.has="stale",this.#n(r,i));else return n&&this.#C(i),r&&(r.has="hit",this.#n(r,i)),true}else r&&(r.has="miss");return false}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#a.get(e);if(r===void 0||!n&&this.#b(r))return;let i=this.#r[r];return this.#u(i)?i.__staleWhileFetching:i}#U(e,t,n,r){let i=t===void 0?void 0:this.#r[t];if(this.#u(i))return i;let o=new Si,{signal:a}=n;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:n,context:r},c=(g,y=false)=>{let{aborted:x}=o.signal,S=n.ignoreFetchAbort&&g!==void 0;if(n.status&&(x&&!y?(n.status.fetchAborted=true,n.status.fetchError=o.signal.reason,S&&(n.status.fetchAbortIgnored=true)):n.status.fetchResolved=true),x&&!S&&!y)return d(o.signal.reason);let T=m;return this.#r[t]===m&&(g===void 0?T.__staleWhileFetching?this.#r[t]=T.__staleWhileFetching:this.#A(e,"fetch"):(n.status&&(n.status.fetchUpdated=true),this.set(e,g,l.options))),g},u=g=>(n.status&&(n.status.fetchRejected=true,n.status.fetchError=g),d(g)),d=g=>{let{aborted:y}=o.signal,x=y&&n.allowStaleOnFetchAbort,S=x||n.allowStaleOnFetchRejection,T=S||n.noDeleteOnFetchRejection,w=m;if(this.#r[t]===m&&(!T||w.__staleWhileFetching===void 0?this.#A(e,"fetch"):x||(this.#r[t]=w.__staleWhileFetching)),S)return n.status&&w.__staleWhileFetching!==void 0&&(n.status.returnedStale=true),w.__staleWhileFetching;if(w.__returned===w)throw g},p=(g,y)=>{let x=this.#o?.(e,i,l);x&&x instanceof Promise&&x.then(S=>g(S===void 0?void 0:S),y),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(g(void 0),n.allowStaleOnFetchAbort&&(g=S=>c(S,true)));});};n.status&&(n.status.fetchDispatched=true);let m=new Promise(p).then(c,u),h=Object.assign(m,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#r[t]=h,h}#u(e){if(!this.#_)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Si}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:p=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:y=false,status:x,signal:S}=t;if(!this.#_)return x&&(x.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:x});let T={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:p,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:x,signal:S},w=this.#a.get(e);if(w===void 0){x&&(x.fetch="miss");let L=this.#U(e,w,T,g);return L.__returned=L}else {let L=this.#r[w];if(this.#u(L)){let E=n&&L.__staleWhileFetching!==void 0;return x&&(x.fetch="inflight",E&&(x.returnedStale=true)),E?L.__staleWhileFetching:L.__returned=L}let B=this.#b(w);if(!y&&!B)return x&&(x.fetch="hit"),this.#B(w),r&&this.#C(w),x&&this.#n(x,w),L;let I=this.#U(e,w,T,g),R=I.__staleWhileFetching!==void 0&&n;return x&&(x.fetch=B?"stale":"refresh",R&&B&&(x.returnedStale=true)),R?I.__staleWhileFetching:I.__returned=I}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#x;if(!n)throw new Error("no memoMethod provided to constructor");let{context:r,forceRefresh:i,...o}=t,a=this.get(e,o);if(!i&&a!==void 0)return a;let l=n(e,a,{options:o,context:r});return this.set(e,l,o),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#r[a],c=this.#u(l);return o&&this.#n(o,a),this.#b(a)?(o&&(o.get="stale"),c?(o&&n&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),n?l.__staleWhileFetching:void 0):(i||this.#A(e,"expire"),o&&n&&(o.returnedStale=true),n?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#B(a),r&&this.#C(a),l))}else o&&(o.get="miss");}#F(e,t){this.#y[t]=e,this.#g[e]=t;}#B(e){e!==this.#p&&(e===this.#m?this.#m=this.#g[e]:this.#F(this.#y[e],this.#g[e]),this.#F(this.#p,e),this.#p=e);}delete(e){return this.#A(e,"delete")}#A(e,t){let n=false;if(this.#c!==0){let r=this.#a.get(e);if(r!==void 0)if(n=true,this.#c===1)this.#j(t);else {this.#L(r);let i=this.#r[r];if(this.#u(i)?i.__abortController.abort(new Error("deleted")):(this.#S||this.#h)&&(this.#S&&this.#i?.(i,e,t),this.#h&&this.#f?.push([i,e,t])),this.#a.delete(e),this.#l[r]=void 0,this.#r[r]=void 0,r===this.#p)this.#p=this.#y[r];else if(r===this.#m)this.#m=this.#g[r];else {let o=this.#y[r];this.#g[o]=this.#g[r];let a=this.#g[r];this.#y[a]=this.#y[r];}this.#c--,this.#T.push(r);}}if(this.#h&&this.#f?.length){let r=this.#f,i;for(;i=r?.shift();)this.#s?.(...i);}return n}clear(){return this.#j("delete")}#j(e){for(let t of this.#I({allowStale:true})){let n=this.#r[t];if(this.#u(n))n.__abortController.abort(new Error("deleted"));else {let r=this.#l[t];this.#S&&this.#i?.(n,r,e),this.#h&&this.#f?.push([n,r,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#v&&this.#k&&(this.#v.fill(0),this.#k.fill(0)),this.#w&&this.#w.fill(0),this.#m=0,this.#p=0,this.#T.length=0,this.#d=0,this.#c=0,this.#h&&this.#f){let t=this.#f,n;for(;n=t?.shift();)this.#s?.(...n);}}};});var vd,Fy,By,jy,Kt,Vt,gn,_i,Qs,Ti,xd,wi,Sd,kt,ts,je,er,ns,Ge,Qe,We,Da,ki,Ve,Le,$a,Na,_d,Ua,Dt,Fa,Ci,tr,Pn,ot,nr,Gy,Wy,Hy,Jy,Ei,Ba,zy,qy,yn,Ga=K(()=>{vd=typeof process=="object"&&process?process:{stdout:null,stderr:null},Fy=s=>!!s&&typeof s=="object"&&(s instanceof yn||s instanceof Td||By(s)||jy(s)),By=s=>!!s&&typeof s=="object"&&s instanceof EventEmitter&&typeof s.pipe=="function"&&s.pipe!==Td.Writable.prototype.pipe,jy=s=>!!s&&typeof s=="object"&&s instanceof EventEmitter&&typeof s.write=="function"&&typeof s.end=="function",Kt=Symbol("EOF"),Vt=Symbol("maybeEmitEnd"),gn=Symbol("emittedEnd"),_i=Symbol("emittingEnd"),Qs=Symbol("emittedError"),Ti=Symbol("closed"),xd=Symbol("read"),wi=Symbol("flush"),Sd=Symbol("flushChunk"),kt=Symbol("encoding"),ts=Symbol("decoder"),je=Symbol("flowing"),er=Symbol("paused"),ns=Symbol("resume"),Ge=Symbol("buffer"),Qe=Symbol("pipes"),We=Symbol("bufferLength"),Da=Symbol("bufferPush"),ki=Symbol("bufferShift"),Ve=Symbol("objectMode"),Le=Symbol("destroyed"),$a=Symbol("error"),Na=Symbol("emitData"),_d=Symbol("emitEnd"),Ua=Symbol("emitEnd2"),Dt=Symbol("async"),Fa=Symbol("abort"),Ci=Symbol("aborted"),tr=Symbol("signal"),Pn=Symbol("dataListeners"),ot=Symbol("discarded"),nr=s=>Promise.resolve().then(s),Gy=s=>s(),Wy=s=>s==="end"||s==="finish"||s==="prefinish",Hy=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,Jy=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Ei=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[ns](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Ba=class extends Ei{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,n){super(e,t,n),this.proxyErrors=r=>t.emit("error",r),e.on("error",this.proxyErrors);}},zy=s=>!!s.objectMode,qy=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",yn=class extends EventEmitter{[je]=false;[er]=false;[Qe]=[];[Ge]=[];[Ve];[kt];[Dt];[ts];[Kt]=false;[gn]=false;[_i]=false;[Ti]=false;[Qs]=null;[We]=0;[Le]=false;[tr];[Ci]=false;[Pn]=0;[ot]=false;writable=true;readable=true;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");zy(t)?(this[Ve]=true,this[kt]=null):qy(t)?(this[kt]=t.encoding,this[Ve]=false):(this[Ve]=false,this[kt]=null),this[Dt]=!!t.async,this[ts]=this[kt]?new StringDecoder(this[kt]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[Ge]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[Qe]});let{signal:n}=t;n&&(this[tr]=n,n.aborted?this[Fa]():n.addEventListener("abort",()=>this[Fa]()));}get bufferLength(){return this[We]}get encoding(){return this[kt]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ve]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Dt]}set async(e){this[Dt]=this[Dt]||!!e;}[Fa](){this[Ci]=true,this.emit("abort",this[tr]?.reason),this.destroy(this[tr]?.reason);}get aborted(){return this[Ci]}set aborted(e){}write(e,t,n){if(this[Ci])return false;if(this[Kt])throw new Error("write after end");if(this[Le])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let r=this[Dt]?nr:Gy;if(!this[Ve]&&!Buffer.isBuffer(e)){if(Jy(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(Hy(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ve]?(this[je]&&this[We]!==0&&this[wi](true),this[je]?this.emit("data",e):this[Da](e),this[We]!==0&&this.emit("readable"),n&&r(n),this[je]):e.length?(typeof e=="string"&&!(t===this[kt]&&!this[ts]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[kt]&&(e=this[ts].write(e)),this[je]&&this[We]!==0&&this[wi](true),this[je]?this.emit("data",e):this[Da](e),this[We]!==0&&this.emit("readable"),n&&r(n),this[je]):(this[We]!==0&&this.emit("readable"),n&&r(n),this[je])}read(e){if(this[Le])return null;if(this[ot]=false,this[We]===0||e===0||e&&e>this[We])return this[Vt](),null;this[Ve]&&(e=null),this[Ge].length>1&&!this[Ve]&&(this[Ge]=[this[kt]?this[Ge].join(""):Buffer.concat(this[Ge],this[We])]);let t=this[xd](e||null,this[Ge][0]);return this[Vt](),t}[xd](e,t){if(this[Ve])this[ki]();else {let n=t;e===n.length||e===null?this[ki]():typeof n=="string"?(this[Ge][0]=n.slice(e),t=n.slice(0,e),this[We]-=e):(this[Ge][0]=n.subarray(e),t=n.subarray(0,e),this[We]-=e);}return this.emit("data",t),!this[Ge].length&&!this[Kt]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Kt]=true,this.writable=false,(this[je]||!this[er])&&this[Vt](),this}[ns](){this[Le]||(!this[Pn]&&!this[Qe].length&&(this[ot]=true),this[er]=false,this[je]=true,this.emit("resume"),this[Ge].length?this[wi]():this[Kt]?this[Vt]():this.emit("drain"));}resume(){return this[ns]()}pause(){this[je]=false,this[er]=true,this[ot]=false;}get destroyed(){return this[Le]}get flowing(){return this[je]}get paused(){return this[er]}[Da](e){this[Ve]?this[We]+=1:this[We]+=e.length,this[Ge].push(e);}[ki](){return this[Ve]?this[We]-=1:this[We]-=this[Ge][0].length,this[Ge].shift()}[wi](e=false){do;while(this[Sd](this[ki]())&&this[Ge].length);!e&&!this[Ge].length&&!this[Kt]&&this.emit("drain");}[Sd](e){return this.emit("data",e),this[je]}pipe(e,t){if(this[Le])return e;this[ot]=false;let n=this[gn];return t=t||{},e===vd.stdout||e===vd.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Qe].push(t.proxyErrors?new Ba(this,e,t):new Ei(this,e,t)),this[Dt]?nr(()=>this[ns]()):this[ns]()),e}unpipe(e){let t=this[Qe].find(n=>n.dest===e);t&&(this[Qe].length===1?(this[je]&&this[Pn]===0&&(this[je]=false),this[Qe]=[]):this[Qe].splice(this[Qe].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[ot]=false,this[Pn]++,!this[Qe].length&&!this[je]&&this[ns]();else if(e==="readable"&&this[We]!==0)super.emit("readable");else if(Wy(e)&&this[gn])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Qs]){let r=t;this[Dt]?nr(()=>r.call(this,this[Qs])):r.call(this,this[Qs]);}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Pn]=this.listeners("data").length,this[Pn]===0&&!this[ot]&&!this[Qe].length&&(this[je]=false)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Pn]=0,!this[ot]&&!this[Qe].length&&(this[je]=false)),t}get emittedEnd(){return this[gn]}[Vt](){!this[_i]&&!this[gn]&&!this[Le]&&this[Ge].length===0&&this[Kt]&&(this[_i]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ti]&&this.emit("close"),this[_i]=false);}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==Le&&this[Le])return false;if(e==="data")return !this[Ve]&&!n?false:this[Dt]?(nr(()=>this[Na](n)),true):this[Na](n);if(e==="end")return this[_d]();if(e==="close"){if(this[Ti]=true,!this[gn]&&!this[Le])return false;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Qs]=n,super.emit($a,n);let i=!this[tr]||this.listeners("error").length?super.emit("error",n):false;return this[Vt](),i}else if(e==="resume"){let i=super.emit("resume");return this[Vt](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let r=super.emit(e,...t);return this[Vt](),r}[Na](e){for(let n of this[Qe])n.dest.write(e)===false&&this.pause();let t=this[ot]?false:super.emit("data",e);return this[Vt](),t}[_d](){return this[gn]?false:(this[gn]=true,this.readable=false,this[Dt]?(nr(()=>this[Ua]()),true):this[Ua]())}[Ua](){if(this[ts]){let t=this[ts].end();if(t){for(let n of this[Qe])n.dest.write(t);this[ot]||super.emit("data",t);}}for(let t of this[Qe])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[Ve]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[Ve]||(e.dataLength+=n.length);}),await t,e}async concat(){if(this[Ve])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[kt]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Le,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[ot]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let r=this.read();if(r!==null)return Promise.resolve({done:false,value:r});if(this[Kt])return t();let i,o,a=d=>{this.off("data",l),this.off("end",c),this.off(Le,u),t(),o(d);},l=d=>{this.off("error",a),this.off("end",c),this.off(Le,u),this.pause(),i({value:d,done:!!this[Kt]});},c=()=>{this.off("error",a),this.off("data",l),this.off(Le,u),t(),i({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((d,p)=>{o=p,i=d,this.once(Le,u),this.once("error",a),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[ot]=false;let e=false,t=()=>(this.pause(),this.off($a,t),this.off(Le,t),this.off("end",t),e=true,{done:true,value:void 0}),n=()=>{if(e)return t();let r=this.read();return r===null?t():{done:false,value:r}};return this.once("end",t),this.once($a,t),this.once(Le,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Le])return e?this.emit("error",e):this.emit(Le),this;this[Le]=true,this[ot]=true,this[Ge].length=0,this[We]=0;let t=this;return typeof t.close=="function"&&!this[Ti]&&t.close(),e?this.emit("error",e):this.emit(Le),this}static get isStream(){return Fy}};});var nb,rr,Id,Rd,ab,lb,bt,Pd,Ad,$t,Md,Ld,An,Od,yt,sr,Wa,wd,ir,Ct,Ii,Pi,kd,cb,Ha,Cd,or,Ed,Ri,Ai,za,Dd,Ye,Mi,Li,Oi,ss,rs,ar,$d,Nd=K(()=>{bd();Ga();nb=realpathSync.native,rr={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:nb,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Id=s=>!s||s===rr||s===an?rr:{...rr,...s,promises:{...rr.promises,...s.promises||{}}},Rd=/^\\\\\?\\([a-z]:)\\?$/i,ab=s=>s.replace(/\//g,"\\").replace(Rd,"$1\\"),lb=/[\\\/]/,bt=0,Pd=1,Ad=2,$t=4,Md=6,Ld=8,An=10,Od=12,yt=15,sr=~yt,Wa=16,wd=32,ir=64,Ct=128,Ii=256,Pi=512,kd=ir|Ct|Pi,cb=1023,Ha=s=>s.isFile()?Ld:s.isDirectory()?$t:s.isSymbolicLink()?An:s.isCharacterDevice()?Ad:s.isBlockDevice()?Md:s.isSocket()?Od:s.isFIFO()?Pd:bt,Cd=new Map,or=s=>{let e=Cd.get(s);if(e)return e;let t=s.normalize("NFKD");return Cd.set(s,t),t},Ed=new Map,Ri=s=>{let e=Ed.get(s);if(e)return e;let t=or(s.toLowerCase());return Ed.set(s,t),t},Ai=class extends Zs{constructor(){super({max:256});}},za=class extends Zs{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Dd=Symbol("PathScurry setAsCwd"),Ye=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#s;get nlink(){return this.#s}#o;get uid(){return this.#o}#x;get gid(){return this.#x}#c;get rdev(){return this.#c}#d;get blksize(){return this.#d}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#g;get atimeMs(){return this.#g}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#p;get birthtimeMs(){return this.#p}#T;get atime(){return this.#T}#f;get mtime(){return this.#f}#w;get ctime(){return this.#w}#k;get birthtime(){return this.#k}#v;#S;#_;#h;#R;#C;#n;#M;#b;#P;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=bt,n,r,i,o,a){this.name=e,this.#v=i?Ri(e):or(e),this.#n=t&cb,this.nocase=i,this.roots=r,this.root=n||this,this.#M=o,this.#_=a.fullpath,this.#R=a.relative,this.#C=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Id(a.fs);}depth(){return this.#S!==void 0?this.#S:this.parent?this.#S=this.parent.depth()+1:this.#S=0}childrenCache(){return this.#M}resolve(e){if(!e)return this;let t=this.getRootString(e),r=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#L(r):this.#L(r)}#L(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#M.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#M.set(this,t),this.#n&=~Wa,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),r=this.nocase?Ri(e):or(e);for(let l of n)if(l.#v===r)return l;let i=this.parent?this.sep:"",o=this.#_?this.#_+i+e:void 0,a=this.newChild(e,bt,{...t,parent:this,fullpath:o});return this.canReaddir()||(a.#n|=Ct),n.push(a),a}relative(){if(this.isCWD)return "";if(this.#R!==void 0)return this.#R;let e=this.name,t=this.parent;if(!t)return this.#R=this.name;let n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(this.#C!==void 0)return this.#C;let e=this.name,t=this.parent;if(!t)return this.#C=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#_!==void 0)return this.#_;let e=this.name,t=this.parent;if(!t)return this.#_=this.name;let r=t.fullpath()+(t.parent?this.sep:"")+e;return this.#_=r}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let r=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(r)?this.#h=`//?/${r}`:this.#h=r}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#h=n}isUnknown(){return (this.#n&yt)===bt}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#n&yt)===Ld}isDirectory(){return (this.#n&yt)===$t}isCharacterDevice(){return (this.#n&yt)===Ad}isBlockDevice(){return (this.#n&yt)===Md}isFIFO(){return (this.#n&yt)===Pd}isSocket(){return (this.#n&yt)===Od}isSymbolicLink(){return (this.#n&An)===An}lstatCached(){return this.#n&wd?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#P}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#b)return true;if(!this.parent)return false;let e=this.#n&yt;return !(e!==bt&&e!==An||this.#n&Ii||this.#n&Ct)}calledReaddir(){return !!(this.#n&Wa)}isENOENT(){return !!(this.#n&Ct)}isNamed(e){return this.nocase?this.#v===Ri(e):this.#v===or(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}#O(e){this.#n|=Wa;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#D();}}#D(){this.#n&Ct||(this.#n=(this.#n|Ct)&sr,this.#E());}#E(){let e=this.children();e.provisional=0;for(let t of e)t.#D();}#I(){this.#n|=Pi,this.#$();}#$(){if(this.#n&ir)return;let e=this.#n;(e&yt)===$t&&(e&=sr),this.#n=e|ir,this.#E();}#N(e=""){e==="ENOTDIR"||e==="EPERM"?this.#$():e==="ENOENT"?this.#D():this.children().provisional=0;}#U(e=""){e==="ENOTDIR"?this.parent.#$():e==="ENOENT"&&this.#D();}#u(e=""){let t=this.#n;t|=Ii,e==="ENOENT"&&(t|=Ct),(e==="EINVAL"||e==="UNKNOWN")&&(t&=sr),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#$();}#F(e,t){return this.#A(e,t)||this.#B(e,t)}#B(e,t){let n=Ha(e),r=this.newChild(e.name,n,{parent:this}),i=r.#n&yt;return i!==$t&&i!==An&&i!==bt&&(r.#n|=ir),t.unshift(r),t.provisional++,r}#A(e,t){for(let n=t.provisional;n<t.length;n++){let r=t[n];if((this.nocase?Ri(e.name):or(e.name))===r.#v)return this.#j(e,r,n,t)}}#j(e,t,n,r){let i=t.name;return t.#n=t.#n&sr|Ha(e),i!==e.name&&(t.name=e.name),n!==r.provisional&&(n===r.length-1?r.pop():r.splice(n,1),r.unshift(t)),r.provisional++,t}async lstat(){if((this.#n&Ct)===0)try{return this.#J(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code);}}lstatSync(){if((this.#n&Ct)===0)try{return this.#J(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code);}}#J(e){let{atime:t,atimeMs:n,birthtime:r,birthtimeMs:i,blksize:o,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:d,ino:p,mode:m,mtime:h,mtimeMs:g,nlink:y,rdev:x,size:S,uid:T}=e;this.#T=t,this.#g=n,this.#k=r,this.#p=i,this.#d=o,this.#r=a,this.#w=l,this.#m=c,this.#t=u,this.#x=d,this.#a=p,this.#i=m,this.#f=h,this.#y=g,this.#s=y,this.#c=x,this.#l=S,this.#o=T;let w=Ha(e);this.#n=this.#n&sr|w|wd,w!==bt&&w!==$t&&w!==An&&(this.#n|=ir);}#W=[];#H=false;#z(e){this.#H=false;let t=this.#W.slice();this.#W.length=0,t.forEach(n=>n(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let i=n.slice(0,n.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#W.push(e),this.#H)return;this.#H=true;let r=this.fullpath();this.#e.readdir(r,{withFileTypes:true},(i,o)=>{if(i)this.#N(i.code),n.provisional=0;else {for(let a of o)this.#F(a,n);this.#O(n);}this.#z(n.slice(0,n.provisional));});}#G;async readdir(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#G)await this.#G;else {let n=()=>{};this.#G=new Promise(r=>n=r);try{for(let r of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#F(r,e);this.#O(e);}catch(r){this.#N(r.code),e.provisional=0;}this.#G=void 0,n();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#F(n,e);this.#O(e);}catch(n){this.#N(n.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&kd)return false;let e=yt&this.#n;return e===bt||e===$t||e===An}shouldWalk(e,t){return (this.#n&$t)===$t&&!(this.#n&kd)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#P)return this.#P;if(!((Pi|Ii|Ct)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#P=this.resolve(e)}catch{this.#I();}}realpathSync(){if(this.#P)return this.#P;if(!((Pi|Ii|Ct)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#P=this.resolve(e)}catch{this.#I();}}[Dd](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),n=[],r=this;for(;r&&r.parent;)t.add(r),r.#R=n.join(this.sep),r.#C=n.join("/"),r=r.parent,n.push("..");for(r=e;r&&r.parent&&!t.has(r);)r.#R=void 0,r.#C=void 0,r=r.parent;}},Mi=class s extends Ye{sep="\\";splitSep=lb;constructor(e,t=bt,n,r,i,o,a){super(e,t,n,r,i,o,a);}newChild(e,t=bt,n={}){return new s(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=ab(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new ss(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Rd,"$1\\"),e===t}},Li=class s extends Ye{splitSep="/";sep="/";constructor(e,t=bt,n,r,i,o,a){super(e,t,n,r,i,o,a);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=bt,n={}){return new s(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},Oi=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#s;constructor(e=process.cwd(),t,n,{nocase:r,childrenCacheSize:i=16*1024,fs:o=rr}={}){this.#s=Id(o),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new Ai,this.#t=new Ai,this.#i=new za(i);let l=a.substring(this.rootPath.length).split(n);if(l.length===1&&!l[0]&&l.pop(),r===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=r,this.root=this.newRoot(this.#s),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,p=this.rootPath,m=false;for(let h of l){let g=u--;c=c.child(h,{relative:new Array(g).fill("..").join(d),relativePosix:new Array(g).fill("..").join("/"),fullpath:p+=(m?"":d)+h}),m=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let o=e[i];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let n=this.#e.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpath();return this.#e.set(t,r),r}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let o=e[i];if(!(!o||o===".")&&(t=t?`${o}/${t}`:o,this.isAbsolute(o)))break}let n=this.#t.get(t);if(n!==void 0)return n;let r=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,r),r}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let r=await e.readdir();return n?r:r.map(i=>i.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(r=>r.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:r=false,filter:i,walkFilter:o}=t,a=[];(!i||i(e))&&a.push(n?e:e.fullpath());let l=new Set,c=(d,p)=>{l.add(d),d.readdirCB((m,h)=>{if(m)return p(m);let g=h.length;if(!g)return p();let y=()=>{--g===0&&p();};for(let x of h)(!i||i(x))&&a.push(n?x:x.fullpath()),r&&x.isSymbolicLink()?x.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(l,o)?c(S,y):y()):x.shouldWalk(l,o)?c(x,y):y();},true);},u=e;return new Promise((d,p)=>{c(u,m=>{if(m)return p(m);d(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:r=false,filter:i,walkFilter:o}=t,a=[];(!i||i(e))&&a.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!i||i(d))&&a.push(n?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(r&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(l,o)&&l.add(p);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:r=false,filter:i,walkFilter:o}=t;(!i||i(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!i||i(u))&&(yield n?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(r&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(a,o)&&a.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:r=false,filter:i,walkFilter:o}=t,a=new yn({objectMode:true});(!i||i(e))&&a.write(n?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let p=false;for(;!p;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=(y,x,S=false)=>{if(y)return a.emit("error",y);if(r&&!S){let T=[];for(let w of x)w.isSymbolicLink()&&T.push(w.realpath().then(L=>L?.isUnknown()?L.lstat():L));if(T.length){Promise.all(T).then(()=>h(null,x,true));return}}for(let T of x)T&&(!i||i(T))&&(a.write(n?T:T.fullpath())||(p=true));u--;for(let T of x){let w=T.realpathCached()||T;w.shouldWalk(l,o)&&c.push(w);}p&&!a.flowing?a.once("drain",d):g||d();},g=true;m.readdirCB(h,true),g=false;}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Ye||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:r=false,filter:i,walkFilter:o}=t,a=new yn({objectMode:true}),l=new Set;(!i||i(e))&&a.write(n?e:e.fullpath());let c=[e],u=0,d=()=>{let p=false;for(;!p;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(a.write(n?g:g.fullpath())||(p=true));u--;for(let g of h){let y=g;if(g.isSymbolicLink()){if(!(r&&(y=g.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(l,o)&&c.push(y);}}p&&!a.flowing&&a.once("drain",d);};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Dd](t);}},ss=class extends Oi{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,win32,"\\",{...t,nocase:n}),this.nocase=n;for(let r=this.cwd;r;r=r.parent)r.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new Mi(this.rootPath,$t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},rs=class extends Oi{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=false}=t;super(e,posix,"/",{...t,nocase:n}),this.nocase=n;}parseRootPath(e){return "/"}newRoot(e){return new Li(this.rootPath,$t,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},ar=class extends rs{constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,{...t,nocase:n});}},process.platform==="win32"?Mi:Li,$d=process.platform==="win32"?ss:process.platform==="darwin"?ar:rs;});var ub,db,is,qa=K(()=>{hn();ub=s=>s.length>=1,db=s=>s.length>=1,is=class s{#e;#t;#i;length;#s;#o;#x;#c;#d;#a;#l=true;constructor(e,t,n,r){if(!ub(e))throw new TypeError("empty pattern list");if(!db(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=n,this.#s=r,this.#i===0){if(this.isUNC()){let[i,o,a,l,...c]=this.#e,[u,d,p,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,o,a,l,""].join("/"),y=[u,d,p,m,""].join("/");this.#e=[g,...c],this.#t=[y,...h],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[i,...o]=this.#e,[a,...l]=this.#t;o[0]===""&&(o.shift(),l.shift());let c=i+"/",u=a+"/";this.#e=[c,...o],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===ze}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#x=this.#x||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#o!==void 0?this.#o:this.hasMore()?(this.#o=new s(this.#e,this.#t,this.#i+1,this.#s),this.#o.#a=this.#a,this.#o.#d=this.#d,this.#o.#c=this.#c,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#d!==void 0?this.#d:this.#d=this.#s==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#s==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return !(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};});var pb,os,Ka=K(()=>{hn();qa();pb=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",os=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:r,noglobstar:i,platform:o=pb}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:true,nobrace:t,nocase:n,noext:r,noglobstar:i,optimizationLevel:2,platform:o,nocomment:true,nonegate:true};for(let a of e)this.add(a);}add(e){let t=new it(e,this.mmopts);for(let n=0;n<t.set.length;n++){let r=t.set[n],i=t.globParts[n];if(!r||!i)throw new Error("invalid pattern object");for(;r[0]==="."&&i[0]===".";)r.shift(),i.shift();let o=new is(r,i,0,this.platform),a=new it(o.globString(),this.mmopts),l=i[i.length-1]==="**",c=o.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(e){let t=e.fullpath(),n=`${t}/`,r=e.relative()||".",i=`${r}/`;for(let o of this.relative)if(o.match(r)||o.match(i))return true;for(let o of this.absolute)if(o.match(t)||o.match(n))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let r of this.relativeChildren)if(r.match(n))return true;for(let r of this.absoluteChildren)if(r.match(t))return true;return false}};});var Va,Ya,Xa,lr,Ud=K(()=>{hn();Va=class s{store;constructor(e=new Map){this.store=e;}copy(){return new s(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),r=this.store.get(n);r?r.add(t.globString()):this.store.set(n,new Set([t.globString()]));}},Ya=class{store=new Map;add(e,t,n){let r=(t?2:0)|(n?1:0),i=this.store.get(e);this.store.set(e,i===void 0?r:r&i);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Xa=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(r=>r.globString()===t.globString())||n.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},lr=class s{hasWalkedCache;matches=new Ya;subwalks=new Xa;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Va;}processPatterns(e,t){this.patterns=t;let n=t.map(r=>[e,r]);for(let[r,i]of n){this.hasWalkedCache.storeWalked(r,i);let o=i.root(),a=i.isAbsolute()&&this.opts.absolute!==false;if(o){r=r.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let d=i.rest();if(d)i=d;else {this.matches.add(r,true,false);continue}}if(r.isENOENT())continue;let l,c,u=false;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)r=r.resolve(l),i=c,u=true;if(l=i.pattern(),c=i.rest(),u){if(this.hasWalkedCache.hasWalked(r,i))continue;this.hasWalkedCache.storeWalked(r,i);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(r.resolve(l),a,d);continue}else if(l===ze){(!r.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(r,i);let d=c?.pattern(),p=c?.rest();if(!c||(d===""||d===".")&&!p)this.matches.add(r,a,d===""||d===".");else if(d===".."){let m=r.parent||r;p?this.hasWalkedCache.hasWalked(m,p)||this.subwalks.add(m,p):this.matches.add(m,a,true);}}else l instanceof RegExp&&this.subwalks.add(r,i);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new s(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),r=this.child();for(let i of t)for(let o of n){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===ze?r.testGlobstar(i,o,c,a):l instanceof RegExp?r.testRegExp(i,l,c,a):r.testString(i,l,c,a);}return r}testGlobstar(e,t,n,r){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,r,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let i=n.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,n.rest(),r);else if(i===".."){let o=e.parent||e;this.subwalks.add(o,n);}else i instanceof RegExp&&this.testRegExp(e,i,n.rest(),r);}}testRegExp(e,t,n,r){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,false));}testString(e,t,n,r){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,r,false));}};});var mb,Di,cr,ur,Fd=K(()=>{Ga();Ka();Ud();mb=(s,e)=>typeof s=="string"?new os([s],e):Array.isArray(s)?new os(s,e):s,Di=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#i=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==false,(n.ignore||!this.includeChildMatches)&&(this.#t=mb(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let r="cannot ignore child matches, ignore lacks add() method.";throw new Error(r)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#s(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#o(e){return !!this.#t?.childrenIgnored?.(e)}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=this.#e.shift());)e();}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n;}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let o=await i.realpath();o&&(o.isUnknown()||this.opts.stat)&&await o.lstat();}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#s(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n;}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let o=i.realpathSync();o&&(o?.isUnknown()||this.opts.stat)&&o.lstatSync();}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#s(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i);}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let r=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+r);}else {let i=this.opts.posix?e.relativePosix():e.relative(),o=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?o+i+r:"."+r);}}async match(e,t,n){let r=await this.matchCheck(e,n);r&&this.matchFinish(r,t);}matchSync(e,t,n){let r=this.matchCheckSync(e,n);r&&this.matchFinish(r,t);}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new lr(this.opts),n);}walkCB2(e,t,n,r){if(this.#o(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,r));return}n.processPatterns(e,t);let i=1,o=()=>{--i===0&&r();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(i++,this.match(a,l,c).then(()=>o()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,n,o):a.readdirCB((c,u)=>this.walkCB3(a,u,n,o),true);}o();}walkCB3(e,t,n,r){n=n.filterEntries(e,t);let i=1,o=()=>{--i===0&&r();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(i++,this.match(a,l,c).then(()=>o()));for(let[a,l]of n.subwalks.entries())i++,this.walkCB2(a,l,n.child(),o);o();}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new lr(this.opts),n);}walkCB2Sync(e,t,n,r){if(this.#o(e))return r();if(this.signal?.aborted&&r(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,r));return}n.processPatterns(e,t);let i=1,o=()=>{--i===0&&r();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirSync();this.walkCB3Sync(a,l,n,o);}o();}walkCB3Sync(e,t,n,r){n=n.filterEntries(e,t);let i=1,o=()=>{--i===0&&r();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let[a,l]of n.subwalks.entries())i++,this.walkCB2Sync(a,l,n.child(),o);o();}},cr=class extends Di{matches=new Set;constructor(e,t,n){super(e,t,n);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},ur=class extends Di{results;constructor(e,t,n){super(e,t,n),this.results=new yn({signal:this.signal,objectMode:true}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume());}matchEmit(e){this.results.write(e),this.results.flowing||this.pause();}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end());}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};});var fb,Et,Za=K(()=>{hn();Nd();qa();Fd();fb=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Et=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=fileURLToPath(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==false,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`);}if(this.pattern=e,this.platform=t.platform||fb,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else {let l=t.platform==="win32"?ss:t.platform==="darwin"?ar:t.platform?rs:$d;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",r={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new it(l,r)),[o,a]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=o.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new is(l,u,0,this.platform)});}async walk(){return [...await new cr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return [...new cr(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new ur(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new ur(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};});var Qa,el=K(()=>{hn();Qa=(s,e={})=>{Array.isArray(s)||(s=[s]);for(let t of s)if(new it(t,e).hasMagic())return true;return false};});function $i(s,e={}){return new Et(s,e).streamSync()}function jd(s,e={}){return new Et(s,e).stream()}function Gd(s,e={}){return new Et(s,e).walkSync()}async function Bd(s,e={}){return new Et(s,e).walk()}function Ni(s,e={}){return new Et(s,e).iterateSync()}function Wd(s,e={}){return new Et(s,e).iterate()}var gb,yb,bb,vb,xb,as,tl=K(()=>{hn();Za();el();hn();Za();el();Ka();gb=$i,yb=Object.assign(jd,{sync:$i}),bb=Ni,vb=Object.assign(Wd,{sync:Ni}),xb=Object.assign(Gd,{stream:$i,iterate:Ni}),as=Object.assign(Bd,{glob:Bd,globSync:Gd,sync:xb,globStream:jd,stream:yb,globStreamSync:$i,streamSync:gb,globIterate:Wd,iterate:vb,globIterateSync:Ni,iterateSync:bb,Glob:Et,hasMagic:Qa,escape:Zn,unescape:wt});as.glob=as;});var dr,nl=K(()=>{Rn();dr=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let n=e.split(`
23
+ `),r=[],i={class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[\w,\s]+)?/,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s+extends\s+[\w,\s]+)?/,type:/^(\s*)(export\s+)?type\s+(\w+)\s*[=<]/,enum:/^(\s*)(export\s+)?enum\s+(\w+)/,function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*[<(]/,constFunction:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]\s*(async\s+)?(\([^)]*\)|[a-zA-Z_]\w*)\s*(=>|:.*=>)/,variable:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]/,method:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(\w+)\s*[<(]/,property:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(readonly\s+)?(\w+)\s*[=:?]/},o=null,a=0;for(let l=0;l<n.length;l++){let c=n[l],u=l+1;if(o){let g=c.match(/^(\s*)/)?.[1].length||0;c.trim()&&g<=a&&!c.match(/^\s*[})\]]/)&&(o.endLine=l,r.push(o),o=null);}if(c.trim().startsWith("//")||c.trim().startsWith("/*")||!c.trim())continue;let d=c.match(i.class);if(d){if(o&&(o.endLine=l,r.push(o)),a=d[1].length,o={name:d[4],kind:"class",startLine:u,endLine:this.findSymbolEnd(n,l),children:[]},l>0){let g=n[l-1].trim();g.startsWith("/**")||g.startsWith("/*")?o.docstring=this.extractDocstring(n,l-1):g.startsWith("//")&&(o.docstring=g.replace(/^\/\/\s*/,""));}continue}let p=c.match(i.interface);if(p){r.push({name:p[3],kind:"interface",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let m=c.match(i.type);if(m){r.push({name:m[3],kind:"type",startLine:u,endLine:this.findTypeEnd(n,l)});continue}let h=c.match(i.enum);if(h){r.push({name:h[3],kind:"enum",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}if(!o){let g=c.match(i.function);if(g){r.push({name:g[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let y=c.match(i.constFunction);if(y){r.push({name:y[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let x=c.match(i.variable);if(x&&!i.constFunction.test(c)){r.push({name:x[4],kind:"variable",startLine:u,endLine:u});continue}}if(o){let g=c.match(i.method);if(g&&!["if","for","while","switch","catch","constructor"].includes(g[5])){let x={name:g[5],kind:(g[5]==="constructor","method"),startLine:u,endLine:this.findSymbolEnd(n,l),parent:o.name};o.children.push(x);continue}let y=c.match(i.property);if(y&&!["if","for","while","switch","catch","return","const","let","var"].includes(y[5])){let x={name:y[5],kind:"variable",startLine:u,endLine:u,parent:o.name};o.children.push(x);}}}return o&&(o.endLine=n.length,r.push(o)),r}findSymbolEnd(e,t){return mn(e,t)}findTypeEnd(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r.includes(";")||n>t&&/^(export|type|interface|class|function|const|let|var)/.test(r.trim()))return n+1}return t+1}extractDocstring(e,t){let n=[],r=t;for(;r>=0;){let i=e[r].trim();if(i.startsWith("/**")||i.startsWith("/*"))break;r--;}for(let i=r;i<=t;i++){let o=e[i].trim();o=o.replace(/^\/\*\*?\s*/,"").replace(/\*\/\s*$/,"").replace(/^\*\s?/,""),o&&n.push(o);}return n.join(`
24
+ `)}buildSymbolPattern(e,t){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`;case "class":return `class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{)`;case "interface":return `interface\\s+${n}(\\s+extends|\\s*\\{)`;case "type":return `type\\s+${n}\\s*[=<]`;case "enum":return `enum\\s+${n}\\s*\\{`;case "method":return `(async\\s+)?${n}\\s*\\(`;case "variable":return `(const|let|var)\\s+${n}\\s*[=:]`;default:return `(function|class|interface|type|enum|const|let|var)\\s+${n}|${n}\\s*(=|\\()`}}};});var pr,sl=K(()=>{pr=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let n=e.split(`
25
+ `),r=[],i={class:/^(\s*)class\s+(\w+)(\s*\([^)]*\))?\s*:/,function:/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,variable:/^([A-Z][A-Z0-9_]*)\s*[=:]/},o=null,a=-1;for(let l=0;l<n.length;l++){let c=n[l],u=l+1,d=c.match(/^(\s*)/)?.[1].length||0;if(o&&c.trim()&&d<=a&&(o.endLine=l,r.push(o),o=null,a=-1),c.trim().startsWith("#")||!c.trim())continue;let p=c.match(i.class);if(p){o&&(o.endLine=l,r.push(o)),a=p[1].length,o={name:p[2],kind:"class",startLine:u,endLine:this.findClassEnd(n,l,a),children:[],docstring:this.extractDocstring(n,l+1)};continue}let m=c.match(i.function);if(m){let h=m[1].length,g=m[3],y=o&&h>a,x={name:g,kind:y?"method":"function",startLine:u,endLine:this.findFunctionEnd(n,l,h),docstring:this.extractDocstring(n,l+1)};y&&o?(x.parent=o.name,o.children.push(x)):r.push(x);continue}if(!o&&c.match(i.variable)){let h=c.match(i.variable);h&&r.push({name:h[1],kind:"constant",startLine:u,endLine:u});}}return o&&(o.endLine=n.length,r.push(o)),r}findClassEnd(e,t,n){for(let r=t+1;r<e.length;r++){let i=e[r];if(!i.trim())continue;if((i.match(/^(\s*)/)?.[1].length||0)<=n)return r}return e.length}findFunctionEnd(e,t,n){let r=false;for(let i=t+1;i<e.length;i++){let o=e[i];if(!o.trim())continue;let a=o.match(/^(\s*)/)?.[1].length||0;if(a>n){r=true;continue}if(r&&a<=n)return i}return e.length}extractDocstring(e,t){if(t>=e.length)return;let n=e[t].trim();if(n.startsWith('"""')||n.startsWith("'''")){let r=n.startsWith('"""')?'"""':"'''";if(n.endsWith(r)&&n.length>6)return n.slice(3,-3);let i=[n.slice(3)];for(let o=t+1;o<e.length;o++){let a=e[o].trim();if(a.endsWith(r)){i.push(a.slice(0,-3));break}i.push(a);}return i.join(`
26
+ `).trim()}}buildSymbolPattern(e,t){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":case "method":return `(async\\s+)?def\\s+${n}\\s*\\(`;case "class":return `class\\s+${n}(\\s*\\(|\\s*:)`;case "variable":case "constant":return `^${n}\\s*[=:]`;default:return `(def|class)\\s+${n}|^${n}\\s*[=:]`}}};});var mr,rl=K(()=>{Rn();mr=class{languageId="generic";extensions=["*"];async parse(e,t){let n=e.split(`
27
+ `),r=[],i={function:[/^(\s*)(export\s+)?(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(function\s+)?(\w+)\s*\([^)]*\)\s*[:{]/,/^(\s*)func\s+(\w+)\s*\(/,/^(\s*)(pub\s+)?fn\s+(\w+)\s*[<(]/,/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,/^(\s*)def\s+(\w+)/],class:[/^(\s*)(export\s+)?(public\s+|abstract\s+)?(class|struct)\s+(\w+)/,/^(\s*)type\s+(\w+)\s+struct/,/^(\s*)(pub\s+)?struct\s+(\w+)/,/^(\s*)impl\s+(\w+)/],interface:[/^(\s*)(export\s+)?interface\s+(\w+)/,/^(\s*)type\s+(\w+)\s+interface/,/^(\s*)(pub\s+)?trait\s+(\w+)/],constant:[/^(\s*)(export\s+)?(const|final|static\s+final)\s+([A-Z_][A-Z0-9_]*)\s*[=:]/]};for(let o=0;o<n.length;o++){let a=n[o],l=o+1;if(!this.isComment(a)){for(let c of i.function){let u=a.match(c);if(u){let d=this.extractName(u);d&&!this.isKeyword(d)&&r.push({name:d,kind:"function",startLine:l,endLine:mn(n,o)});break}}for(let c of i.class){let u=a.match(c);if(u){let d=this.extractName(u);d&&r.push({name:d,kind:"class",startLine:l,endLine:mn(n,o)});break}}for(let c of i.interface){let u=a.match(c);if(u){let d=this.extractName(u);d&&r.push({name:d,kind:"interface",startLine:l,endLine:mn(n,o)});break}}for(let c of i.constant){let u=a.match(c);if(u){let d=this.extractName(u);d&&r.push({name:d,kind:"constant",startLine:l,endLine:l});break}}}}return r}extractName(e){for(let t=e.length-1;t>0;t--){let n=e[t];if(n&&/^\w+$/.test(n)&&!this.isModifier(n))return n}return null}isModifier(e){return ["public","private","protected","static","final","abstract","async","export","const","let","var","function","class","interface","type","enum","struct","impl","fn","func","def","pub","trait"].includes(e.toLowerCase())}isKeyword(e){return ["if","else","for","while","do","switch","case","break","continue","return","try","catch","finally","throw","new","this","super","null","undefined","true","false","import","from","as","default","with","in","of","get","set","constructor"].includes(e)}isComment(e){let t=e.trim();return t.startsWith("//")||t.startsWith("#")||t.startsWith("/*")||t.startsWith("*")||t.startsWith("--")}buildSymbolPattern(e,t){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|func|fn|def)\\s+${n}|${n}\\s*\\(`;case "class":return `(class|struct|type)\\s+${n}`;case "interface":return `(interface|trait)\\s+${n}`;default:return `(function|class|interface|struct|type|func|fn|def)\\s+${n}|${n}\\s*[=(]`}}};});var hr,il=K(()=>{nl();sl();rl();hr=class{parsers=new Map;constructor(){this.register(new dr),this.register(new pr),this.register(new mr);}register(e){this.parsers.set(e.languageId,e);for(let t of e.extensions){let n=this.getLanguageFromExtension(t);n&&this.parsers.has(n);}}getParser(e){return this.parsers.has(e)?this.parsers.get(e):e==="javascript"?this.parsers.get("typescript")||null:this.parsers.get("generic")||null}getLanguageFromExtension(e){return {".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".py":"python",".java":"java",".go":"go",".rs":"rust"}[e]||null}getSupportedLanguages(){return Array.from(this.parsers.keys()).filter(e=>e!=="generic")}};});function fr(s,e){return new Ui(s,e)}var Sb,Ui,ol=K(()=>{tl();qs();Rn();il();Sb="1.0.0",Ui=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Nu,...t},this.parserRegistry=new hr;}get indexDir(){return te.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=te.join(this.indexDir,"meta.json");return Fu(e)}async loadMetadata(){if(this.metadata)return this.metadata;let e=te.join(this.indexDir,"meta.json");try{let t=await he.readFile(e,"utf-8");return this.metadata=JSON.parse(t),this.metadata}catch{return null}}async saveMetadata(){if(!this.metadata)return;await Ks(this.indexDir);let e=te.join(this.indexDir,"meta.json");await he.writeFile(e,JSON.stringify(this.metadata,null,2));}async buildIndex(e={}){let t=Date.now(),n=[],{paths:r=this.config.include,languages:i=this.config.languages,force:o=false,onProgress:a}=e;await Ks(this.indexDir),await Ks(te.join(this.indexDir,"files"));let l=[];for(let d of r){let p=await as(d,{cwd:this.workspacePath,absolute:true,ignore:this.config.exclude});for(let m of p){let h=wa(m);h&&i.includes(h)&&l.push(m);}}let c=0,u=0;for(let d=0;d<l.length;d++){let p=l[d];a?.(d+1,l.length,p);try{if(!o){let h=await this.getFileIndex(p);if(h){let g=await he.stat(p);if(h.mtime>=g.mtimeMs){u+=h.symbols.length,c++;continue}}}let m=await this.indexFile(p);m&&(await this.saveFileIndex(m),this.fileIndexCache.set(p,m),u+=m.symbols.length,c++);}catch(m){n.push({file:p,error:m.message});}}return this.metadata={version:Sb,createdAt:this.metadata?.createdAt||Date.now(),updatedAt:Date.now(),fileCount:c,symbolCount:u,languages:i,indexDir:this.config.cacheDir},await this.saveMetadata(),{success:n.length===0,filesIndexed:c,symbolsFound:u,timeMs:Date.now()-t,errors:n}}async indexFile(e){let t=wa(e);if(!t)return null;let n=this.parserRegistry.getParser(t);if(!n)return null;try{let r=await he.readFile(e,"utf-8"),i=await he.stat(e),o=await n.parse(r,e),a=this.extractImports(r,t),l=this.extractExports(r,t);return {path:e,hash:Uu(r),mtime:i.mtimeMs,totalLines:r.split(`
28
+ `).length,symbols:o,imports:a,exports:l}}catch{return null}}extractImports(e,t){let n=[],r=e.split(`
29
+ `);if(["typescript","javascript"].includes(t)){let i=/^import\s+(?:(?:\{([^}]+)\}|(\w+))\s+from\s+)?['"]([^'"]+)['"]/;r.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[1]?.split(",").map(u=>u.trim())||(l[2]?[l[2]]:[]);n.push({module:l[3],line:a+1,names:c.filter(Boolean)});}});}if(t==="python"){let i=/^(?:from\s+(\S+)\s+import\s+(.+)|import\s+(\S+))/;r.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[1]||l[3],u=l[2]?.split(",").map(d=>d.trim())||[];n.push({module:c,line:a+1,names:u});}});}return n}extractExports(e,t){let n=[],r=e.split(`
30
+ `);if(["typescript","javascript"].includes(t)){let i=/^export\s+(?:(default)\s+)?(?:(class|function|const|let|var|interface|type|enum)\s+)?(\w+)?/;r.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[2],u=l[3]||(l[1]?"default":"");u&&n.push({name:u,line:a+1,kind:c});}});}return n}async getFileIndex(e){if(this.fileIndexCache.has(e))return this.fileIndexCache.get(e);let t=this.getFileIndexPath(e);try{let n=await he.readFile(t,"utf-8"),r=JSON.parse(n);return this.fileIndexCache.set(e,r),r}catch{return null}}async saveFileIndex(e){let t=this.getFileIndexPath(e.path);await Ks(te.dirname(t)),await he.writeFile(t,JSON.stringify(e,null,2));}getFileIndexPath(e){let n=te.relative(this.workspacePath,e).replace(/[/\\]/g,"_").replace(/\./g,"_");return te.join(this.indexDir,"files",`${n}.json`)}async searchSymbol(e){let{query:t,kind:n,fuzzy:r=false,limit:i=20}=e,o=[],a=te.join(this.indexDir,"files");try{let l=await he.readdir(a);for(let c of l)if(c.endsWith(".json"))try{let u=await he.readFile(te.join(a,c),"utf-8"),d=JSON.parse(u);for(let p of d.symbols){if(n&&p.kind!==n)continue;let m=0;if(r){if(m=ka(t.toLowerCase(),p.name.toLowerCase()),m<.5)continue}else {if(!p.name.toLowerCase().includes(t.toLowerCase()))continue;m=p.name.toLowerCase()===t.toLowerCase()?1:.8;}if(o.push({symbol:p,file:d.path,score:m}),p.children)for(let h of p.children){if(n&&h.kind!==n)continue;let g=0;if(r){if(g=ka(t.toLowerCase(),h.name.toLowerCase()),g<.5)continue}else {if(!h.name.toLowerCase().includes(t.toLowerCase()))continue;g=h.name.toLowerCase()===t.toLowerCase()?1:.8;}o.push({symbol:{...h,parent:p.name},file:d.path,score:g});}}}catch{continue}}catch{}return o.sort((l,c)=>c.score-l.score).slice(0,i)}async invalidate(e){this.fileIndexCache.delete(e);let t=this.getFileIndexPath(e);try{await he.unlink(t);}catch{}}async clear(){this.fileIndexCache.clear(),this.metadata=null;try{await he.rm(this.indexDir,{recursive:!0,force:!0});}catch{}}async getStats(){let e=await this.loadMetadata();if(!e)return {hasIndex:false,fileCount:0,symbolCount:0,lastUpdated:null,size:0};let t=0;try{let n=te.join(this.indexDir,"files"),r=await he.readdir(n);for(let i of r){let o=await he.stat(te.join(n,i));t+=o.size;}}catch{}return {hasIndex:true,fileCount:e.fileCount,symbolCount:e.symbolCount,lastUpdated:new Date(e.updatedAt),size:t}}};});var Hd=K(()=>{il();nl();sl();rl();});var vt=K(()=>{});function kb(s){return (!ls||Bi!==s)&&(ls=Ca(s),Bi=s,cs&&ls.setIndexManager(cs)),ls}function gr(s){return (!cs||Bi!==s)&&(cs=fr(s),Bi=s,ls&&ls.setIndexManager(cs)),cs}function Cb(s){return process.cwd()}function Nt(s){let e=Cb();return te.relative(e,s)||s}function zd(s,e){let t=te.relative(s,e);return t===""?true:!t.startsWith("..")&&!te.isAbsolute(t)}function Eb(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function cl(s){let e=s||process.cwd(),n=await gr(e).getStats();return {hasIndex:n.hasIndex,fileCount:n.fileCount,symbolCount:n.symbolCount,lastUpdated:n.lastUpdated}}async function qd(s){let e=await cl(s);return e.hasIndex?`
31
+ \u{1F4D6} readfile \u7B56\u7565\u63D0\u793A (\u7D22\u5F15\u5DF2\u542F\u7528, ${e.symbolCount} \u7B26\u53F7):
32
+ - \u5C0F\u6587\u4EF6 (\u2264${Mn.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
33
+ - \u5927\u6587\u4EF6 (>${Mn.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
34
+ \u2713 readfile(path="big.ts", function="handleClick") - \u7CBE\u51C6\u5B9A\u4F4D\u51FD\u6570
35
+ \u2713 readfile(path="big.ts", class="UserService") - \u7CBE\u51C6\u5B9A\u4F4D\u7C7B
36
+ - \u4E2D\u7B49\u6587\u4EF6: pattern \u548C symbol \u5747\u53EF\uFF0C\u6309\u9700\u9009\u62E9`:`
37
+ \u{1F4D6} readfile \u7B56\u7565\u63D0\u793A:
38
+ - \u7D22\u5F15\u672A\u6784\u5EFA\uFF0C\u4F7F\u7528 pattern/grep \u5B9A\u4F4D
39
+ - \u5C0F\u6587\u4EF6 (\u2264${Mn.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
40
+ - \u5927\u6587\u4EF6: \u5148\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
41
+ - \u{1F4A1} \u8FD0\u884C build_index() \u53EF\u4EE5\u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD`}async function ul(s){let e=await cl(s);await qd(s);let n=["## readfile \u6587\u4EF6\u8BFB\u53D6\u7B56\u7565",""];return e.hasIndex?(n.push(`\u2705 \u4EE3\u7801\u7D22\u5F15\u5DF2\u542F\u7528 (${e.fileCount} \u6587\u4EF6, ${e.symbolCount} \u7B26\u53F7)`),n.push(""),n.push("### \u6309\u6587\u4EF6\u5927\u5C0F\u9009\u62E9\u7B56\u7565:"),n.push(""),n.push("| \u6587\u4EF6\u5927\u5C0F | \u63A8\u8350\u7B56\u7565 | \u793A\u4F8B |"),n.push("|---------|---------|------|"),n.push(`| \u2264${Mn.small}\u884C | full \u81EA\u52A8\u8BFB\u53D6 | \`readfile(path)\` |`),n.push(`| ${Mn.small}-${Mn.large}\u884C | \u5747\u53EF | \u6309\u9700\u9009\u62E9 |`),n.push(`| >${Mn.large}\u884C | **symbol/function** | \`readfile(path, function="xxx")\` |`)):(n.push("\u26A0\uFE0F \u4EE3\u7801\u7D22\u5F15\u672A\u6784\u5EFA"),n.push(""),n.push("\u5F53\u524D\u53EF\u7528\u7B56\u7565:"),n.push("- `start_line`: \u6309\u884C\u53F7\u8BFB\u53D6"),n.push("- `pattern`: \u6B63\u5219\u5339\u914D\u5B9A\u4F4D\uFF08\u53EF\u914D\u5408 list_matches\uFF09"),n.push("- `range_start/end`: \u8303\u56F4\u8BFB\u53D6"),n.push(""),n.push("\u{1F4A1} \u8FD0\u884C `build_index()` \u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD")),n.join(`
42
+ `)}function dl(s){let e=()=>s||process.cwd(),t={name:"readfile",description:`\u3010\u667A\u80FD\u6587\u4EF6\u8BFB\u53D6\u3011\u7CBE\u51C6\u5B9A\u4F4D\u4EE3\u7801\u4F4D\u7F6E\uFF0C\u652F\u6301\u591A\u79CD\u5B9A\u4F4D\u65B9\u5F0F\u3002
43
+
44
+ \u{1F525} \u57FA\u7840\u7528\u6CD5:
45
+ readfile(path="src/main.ts") \u2192 \u8BFB\u53D6\u6587\u4EF6\u5F00\u5934 200 \u884C
46
+ readfile(path="src/main.ts", start_line=100) \u2192 \u4ECE\u7B2C 100 \u884C\u5F00\u59CB\u8BFB\u53D6
47
+ readfile(path="src/main.ts", start_line=100, end_line=500) \u2192 \u8BFB\u53D6 100-500 \u884C
48
+ readfile(path="src/main.ts", num_lines=2000) \u2192 \u8BFB\u53D6\u524D 2000 \u884C
49
+
50
+ \u{1F9E0} \u81EA\u9002\u5E94:
51
+ - \u2264${zn} \u884C\u9ED8\u8BA4 full
52
+ - >${zn} \u884C\u5EFA\u8BAE pattern/list_matches \u518D\u6309\u884C\u6279\u91CF\u8BFB\u53D6
53
+
54
+ \u{1F3AF} \u667A\u80FD\u5B9A\u4F4D (\u65E0\u9700\u77E5\u9053\u884C\u53F7):
55
+ readfile(path="src/main.ts", symbol="handleClick") \u2192 \u5B9A\u4F4D\u5230 handleClick \u51FD\u6570
56
+ readfile(path="src/main.ts", function="processData") \u2192 \u5B9A\u4F4D\u5230 processData \u51FD\u6570
57
+ readfile(path="src/main.ts", class="UserService") \u2192 \u5B9A\u4F4D\u5230 UserService \u7C7B
58
+ readfile(path="src/main.ts", pattern="TODO|FIXME") \u2192 \u5B9A\u4F4D\u5230\u5339\u914D\u7684\u4F4D\u7F6E
59
+
60
+ \u{1F50E} \u5339\u914D\u6458\u8981:
61
+ readfile(path="src/main.ts", pattern="TODO|FIXME", list_matches=true)
62
+ \u2192 \u5148\u5217\u51FA\u5339\u914D\u884C\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
63
+
64
+ \u{1F4E6} \u6279\u91CF\u8BFB\u53D6:
65
+ readfile(path="src/main.ts", anchor_lines=[120,480], num_lines=200)
66
+ \u2192 \u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u6279\u91CF\u8BFB\u53D6\u591A\u4E2A\u533A\u5757
67
+
68
+ readfile(path="src/main.ts", ranges=[{"start":100,"end":260},{"start":500,"end":800}])
69
+ \u2192 \u6309\u8303\u56F4\u6279\u91CF\u8BFB\u53D6\u591A\u4E2A\u533A\u5757
70
+
71
+ \u{1F4E6} \u9AD8\u7EA7\u5B9A\u4F4D:
72
+ readfile(path="src/main.ts", symbol="render", symbol_kind="method", class_name="Component")
73
+ \u2192 \u5B9A\u4F4D\u5230 Component \u7C7B\u7684 render \u65B9\u6CD5
74
+
75
+ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CONFIG")
76
+ \u2192 \u8BFB\u53D6\u4E24\u4E2A\u6807\u8BB0\u4E4B\u95F4\u7684\u5185\u5BB9
77
+
78
+ \u26A1 \u7279\u6027:
79
+ - \u9ED8\u8BA4\u8BFB\u53D6 200 \u884C\uFF0C\u6700\u5927\u652F\u6301 4000 \u884C
80
+ - \u81EA\u52A8\u8BC6\u522B\u4EE3\u7801\u5757\u8FB9\u754C (\u51FD\u6570/\u7C7B\u7684\u5B8C\u6574\u5B9A\u4E49)
81
+ - \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
82
+ - for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
83
+ - max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
84
+ - \u652F\u6301 TypeScript/JavaScript/Python/Java \u7B49\u591A\u79CD\u8BED\u8A00`,parameters:{type:"object",properties:{path:{type:"string",description:"\u6587\u4EF6\u8DEF\u5F84 (\u5FC5\u9700)"},start_line:{type:"number",description:"\u8D77\u59CB\u884C\u53F7 (1-indexed)"},end_line:{type:"number",description:"\u7ED3\u675F\u884C\u53F7"},num_lines:{type:"number",description:`\u8BFB\u53D6\u884C\u6570 (\u9ED8\u8BA4: ${zs})`},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u51FD\u6570\u540D\u3001\u7C7B\u540D\u3001\u53D8\u91CF\u540D\u7B49)"},symbol_kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},class_name:{type:"string",description:"\u6240\u5C5E\u7C7B\u540D (\u7528\u4E8E\u5B9A\u4F4D\u7C7B\u7684\u65B9\u6CD5)"},function:{type:"string",description:"\u51FD\u6570\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=function)"},class:{type:"string",description:"\u7C7B\u540D (\u5FEB\u6377\u65B9\u5F0F\uFF0C\u7B49\u540C\u4E8E symbol + symbol_kind=class)"},pattern:{type:"string",description:"\u641C\u7D22\u6A21\u5F0F (\u6B63\u5219\u8868\u8FBE\u5F0F)"},match_index:{type:"number",description:"\u5339\u914D\u7B2C\u51E0\u4E2A\u7ED3\u679C (\u9ED8\u8BA4: 1)"},list_matches:{type:"boolean",description:"\u4EC5\u5217\u51FA\u5339\u914D\u884C\u6458\u8981 (\u9ED8\u8BA4: false, \u9700\u914D\u5408 pattern)"},range_start:{type:"string",description:"\u8303\u56F4\u5F00\u59CB\u6A21\u5F0F"},range_end:{type:"string",description:"\u8303\u56F4\u7ED3\u675F\u6A21\u5F0F"},ranges:{type:"array",items:{type:"object",properties:{start:{type:"number"},end:{type:"number"}},required:["start"]},description:'\u591A\u4E2A\u884C\u8303\u56F4\u6279\u91CF\u8BFB\u53D6 (e.g., [{"start":10,"end":120},{"start":300,"end":480}])'},anchor_lines:{type:"array",items:{type:"number"},description:"\u6309\u884C\u53F7\u6279\u91CF\u8BFB\u53D6 (\u4F1A\u4EE5\u884C\u53F7\u4E3A\u4E2D\u5FC3\u5C55\u5F00 num_lines \u6216 context)"},context:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 10)"},use_index:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528\u7D22\u5F15 (\u9ED8\u8BA4: true, \u5982\u679C\u7D22\u5F15\u53EF\u7528)"},for_edit:{type:"boolean",description:"\u662F\u5426\u5305\u542B edit_file \u53EF\u590D\u5236\u7684\u539F\u59CB\u5185\u5BB9\u5757 (\u9ED8\u8BA4: false)"},max_output_chars:{type:"number",description:`\u6700\u5927\u8F93\u51FA\u5B57\u7B26\u6570 (\u9ED8\u8BA4: ${Jd})`}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:d,num_lines:p,symbol:m,symbol_kind:h,class_name:g,function:y,class:x,pattern:S,match_index:T,list_matches:w,range_start:L,range_end:B,ranges:I,anchor_lines:k,context:R,use_index:E=true,for_edit:M,max_output_chars:_}=l,W=e(),$=kb(W),A=M===true,G=typeof R=="number"?Math.max(0,R):fi,N=typeof _=="number"&&_>0?Math.floor(_):Jd,U=p||(A?_b:zs);U=Math.min(U,gi),!p&&S&&(U=Math.max(Fi,G*2+1));let H=Array.isArray(I)&&I.length>0,Ie=Array.isArray(k)&&k.length>0,J=w===true;if(A&&(H||Ie||J))return "\u2717 for_edit=true \u6682\u4E0D\u652F\u6301 list_matches / ranges / anchor_lines\uFF0C\u8BF7\u4F7F\u7528\u5355\u6B21 readfile \u83B7\u53D6\u53EF\u7F16\u8F91\u7247\u6BB5\u3002";let ye=()=>te.isAbsolute(c)?c:te.resolve(W,c),pe=async()=>{let O=ye(),q=await he.readFile(O,"utf-8"),de=Yn(q).split(`
85
+ `);return {absPath:O,lines:de,totalLines:de.length}},ce=(O,q,X)=>{let de=Math.max(1,Math.floor(O)),V=typeof q=="number"?Math.floor(q):de+U-1,re=Math.min(X,Math.max(V,de));return {start:de,end:re}},Oe=O=>{let q=O.filter(de=>Number.isFinite(de.start)&&Number.isFinite(de.end)).sort((de,V)=>de.start-V.start),X=[];for(let de of q){let V=X[X.length-1];!V||de.start>V.end+1?X.push({...de}):V.end=Math.max(V.end,de.end);}return X};if(J){if(!S)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:O,lines:q,totalLines:X}=await pe(),de;try{de=new RegExp(S,"gi");}catch(ue){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${ue.message}`}let V=[];q.forEach((ue,De)=>{de.test(ue)&&V.push({line:De+1,text:ue}),de.lastIndex=0;});let re=Nt(O);if(V.length===0){let ue=Ke(q.slice(0,Math.min(50,X)),1);return [`\u2713 \u6587\u4EF6: ${re}`,`\u603B\u884C\u6570: ${X} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${S}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",ue].join(`
86
+ `)}let D=al+12,ie=Math.max(5,Math.min(wb,Math.floor(N/D))),se=V.slice(0,ie),fe=se.map(ue=>{let De=ue.text.length>al?`${ue.text.slice(0,al)}...`:ue.text;return `${String(ue.line).padStart(6)} \u2502 ${De}`}),xe=[`\u2713 \u6587\u4EF6: ${re}`,`\u603B\u884C\u6570: ${X} | \u5339\u914D: ${V.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${fe.length}/${V.length}\uFF09---`,...fe];fe.length<V.length&&xe.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let Re=se.slice(0,5).map(ue=>ue.line).join(", ");return xe.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${re}", anchor_lines=[${Re}], num_lines=${Math.min(200,U)})`),xe.join(`
87
+ `)}catch(O){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${O.message}`}}if(H||Ie)try{let{absPath:O,lines:q,totalLines:X}=await pe(),de=[];if(H)for(let fe of I)!fe||typeof fe.start!="number"||de.push(ce(fe.start,fe.end,X));else if(Ie){let fe=Math.max(1,p||G*2+1);for(let xe of k){if(typeof xe!="number"||Number.isNaN(xe))continue;let Re=Math.max(1,Math.floor(xe-Math.floor(fe/2))),ue=Math.min(X,Re+fe-1);de.push({start:Re,end:ue});}}if(de.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let V=Oe(de),D=[`\u2713 \u6587\u4EF6: ${Nt(O)}`,`\u603B\u884C\u6570: ${X} | \u533A\u5757: ${V.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],ie=D.join(`
88
+ `).length,se=0;for(let[fe,xe]of V.entries()){let Re=Ke(q.slice(xe.start-1,xe.end),xe.start),De=`${`# \u533A\u5757 ${fe+1}: ${xe.start}-${xe.end}`}
89
+ ${Re}`;if(ie+De.length+2>N&&se>0)break;D.push(De,""),ie+=De.length+2,se+=1;}return se<V.length&&D.push(`\u26A0\uFE0F \u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4EC5\u663E\u793A\u524D ${se} \u4E2A\u533A\u5757`),D.join(`
90
+ `).trimEnd()}catch(O){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${O.message}`}let _e;u?_e={type:"line",start:u,end:d}:y?_e={type:"function",name:y,className:g}:x?_e={type:"class",name:x}:m?_e={type:"symbol",name:m,kind:h}:S?_e={type:"pattern",regex:S,matchIndex:T,context:G}:L&&B&&(_e={type:"range",startPattern:L,endPattern:B});let Q=O=>{let X=[`\u2713 \u6587\u4EF6: ${Nt(O.path)}`,`\u603B\u884C\u6570: ${O.totalLines} | \u663E\u793A: \u7B2C ${O.startLine}-${O.endLine} \u884C`,`\u7B56\u7565: ${O.strategy}${O.metadata?.matchedLine?` | \u5339\u914D\u884C: ${O.metadata.matchedLine}`:""}`];if(O.metadata?.symbol&&X.push(`\u7B26\u53F7: ${O.metadata.symbol.name} (${O.metadata.symbol.kind})`),O.truncated&&(X.push(""),X.push(`\u26A0\uFE0F \u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528 start_line=${O.endLine+1} \u7EE7\u7EED\u8BFB\u53D6`)),X.push(""),X.push("--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"),X.push(O.content),A){let re=O.content.split(`
91
+ `).map(D=>{let ie=D.match(/^\s*\d+\s*│\s?(.*)$/);return ie?ie[1]:D}).join(`
92
+ `);X.push(""),X.push("--- \u{1F525} COPY THIS FOR edit_file old_string (\u4E0D\u5E26\u884C\u53F7) ---"),X.push(re),X.push("--- END ---");}return X.join(`
93
+ `)},be=0,Te="",P=!p;for(;;){let O=await $.read({path:c,locator:_e,mode:"smart",autoFullThreshold:P?zn:void 0,chunkSize:U,expandContext:G,useIndex:E});if(!O.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${O.error}
94
+
95
+ \u{1F4A1} \u63D0\u793A:
96
+ - \u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E
97
+ - \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(Te=Q(O),!_e&&O.totalLines>zn&&O.strategy==="chunk"&&(Te+=`
98
+
99
+ \u{1F4A1} \u5EFA\u8BAE:
100
+ - \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
101
+ - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),P&&O.strategy==="full"&&Te.length>N){P=false;let de=Math.max(.1,Math.min(.9,N/Te.length));U=Math.max(Fi,Math.floor(U*de)),be+=1;continue}if(p||Te.length<=N||be>=Tb||U<=Fi)return Te;let q=Math.max(.1,Math.min(.9,N/Te.length)),X=Math.max(Fi,Math.floor(U*q));if(X>=U)return Te;U=X,be+=1;}}},n={name:"build_index",description:`\u3010\u6784\u5EFA\u4EE3\u7801\u7D22\u5F15\u3011\u4E3A\u9879\u76EE\u6784\u5EFA AST \u7D22\u5F15\uFF0C\u63D0\u5347\u4EE3\u7801\u5BFC\u822A\u901F\u5EA6\u3002
102
+
103
+ \u26A1 \u7279\u6027:
104
+ - \u89E3\u6790 TypeScript/JavaScript/Python \u4EE3\u7801\u7ED3\u6784
105
+ - \u63D0\u53D6\u51FD\u6570\u3001\u7C7B\u3001\u63A5\u53E3\u3001\u7C7B\u578B\u5B9A\u4E49
106
+ - \u589E\u91CF\u66F4\u65B0 (\u53EA\u91CD\u65B0\u7D22\u5F15\u53D8\u5316\u7684\u6587\u4EF6)
107
+ - \u6301\u4E45\u5316\u5B58\u50A8\u5728 .neox/index/
108
+
109
+ \u{1F527} \u7528\u6CD5:
110
+ build_index() \u2192 \u7D22\u5F15\u5F53\u524D\u9879\u76EE
111
+ build_index(force=true) \u2192 \u5F3A\u5236\u91CD\u5EFA\u7D22\u5F15
112
+ build_index(paths=["src/**/*.ts"]) \u2192 \u53EA\u7D22\u5F15\u6307\u5B9A\u8DEF\u5F84
113
+
114
+ \u{1F4CA} \u7D22\u5F15\u540E\u53EF\u4EE5\u4F7F\u7528:
115
+ - readfile \u7684\u7B26\u53F7\u5B9A\u4F4D\u4F1A\u66F4\u5FEB\u66F4\u51C6\u786E
116
+ - search_symbol \u53EF\u4EE5\u5FEB\u901F\u641C\u7D22\u7B26\u53F7`,parameters:{type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"\u8981\u7D22\u5F15\u7684\u8DEF\u5F84\u6A21\u5F0F (\u9ED8\u8BA4: \u9879\u76EE\u4E2D\u7684\u6240\u6709\u4EE3\u7801\u6587\u4EF6)"},languages:{type:"array",items:{type:"string"},description:"\u8BED\u8A00\u5217\u8868 (\u9ED8\u8BA4: typescript, javascript, python)"},force:{type:"boolean",description:"\u5F3A\u5236\u91CD\u5EFA\u7D22\u5F15 (\u5FFD\u7565\u7F13\u5B58)"}}},async function(l){let{paths:c,languages:u,force:d=false}=l,p=e(),h=await gr(p).buildIndex({paths:c,languages:u,force:d,onProgress:(y,x,S)=>{}}),g=[h.success?"\u2713 \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210":"\u26A0\uFE0F \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210 (\u6709\u9519\u8BEF)","","\u{1F4CA} \u7EDF\u8BA1:",` \u6587\u4EF6\u6570: ${h.filesIndexed}`,` \u7B26\u53F7\u6570: ${h.symbolsFound}`,` \u8017\u65F6: ${(h.timeMs/1e3).toFixed(2)}s`];if(h.errors.length>0){g.push(""),g.push("\u274C \u9519\u8BEF:");for(let y of h.errors.slice(0,5))g.push(` ${Nt(y.file)}: ${y.error}`);h.errors.length>5&&g.push(` ... \u8FD8\u6709 ${h.errors.length-5} \u4E2A\u9519\u8BEF`);}return g.push(""),g.push("\u{1F4A1} \u73B0\u5728\u53EF\u4EE5\u4F7F\u7528 readfile \u7684\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD\uFF0C\u6216\u4F7F\u7528 search_symbol \u641C\u7D22\u7B26\u53F7"),g.join(`
117
+ `)}},r={name:"search_symbol",description:`\u3010\u641C\u7D22\u7B26\u53F7\u3011\u5728\u7D22\u5F15\u4E2D\u641C\u7D22\u51FD\u6570\u3001\u7C7B\u3001\u63A5\u53E3\u7B49\u7B26\u53F7\u3002
118
+
119
+ \u26A0\uFE0F \u9700\u8981\u5148\u8FD0\u884C build_index \u6784\u5EFA\u7D22\u5F15
120
+
121
+ \u{1F50D} \u7528\u6CD5:
122
+ search_symbol(query="User") \u2192 \u641C\u7D22\u5305\u542B "User" \u7684\u7B26\u53F7
123
+ search_symbol(query="handle", kind="function") \u2192 \u53EA\u641C\u7D22\u51FD\u6570
124
+ search_symbol(query="Service", kind="class") \u2192 \u53EA\u641C\u7D22\u7C7B
125
+ search_symbol(query="usr", fuzzy=true) \u2192 \u6A21\u7CCA\u641C\u7D22
126
+
127
+ \u{1F4CB} \u8FD4\u56DE:
128
+ - \u7B26\u53F7\u540D\u79F0\u548C\u7C7B\u578B
129
+ - \u6240\u5728\u6587\u4EF6\u548C\u884C\u53F7
130
+ - \u53EF\u76F4\u63A5\u7528\u4E8E readfile \u5B9A\u4F4D`,parameters:{type:"object",properties:{query:{type:"string",description:"\u641C\u7D22\u5173\u952E\u8BCD"},kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},fuzzy:{type:"boolean",description:"\u6A21\u7CCA\u5339\u914D (\u9ED8\u8BA4: false)"},limit:{type:"number",description:"\u6700\u5927\u7ED3\u679C\u6570 (\u9ED8\u8BA4: 20)"}},required:["query"]},async function(l){let{query:c,kind:u,fuzzy:d=false,limit:p=20}=l,m=e(),h=gr(m);if(!await h.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
131
+
132
+ \u{1F4A1} \u8BF7\u5148\u8FD0\u884C build_index() \u6784\u5EFA\u7D22\u5F15:
133
+ build_index() \u2192 \u7D22\u5F15\u6574\u4E2A\u9879\u76EE
134
+ build_index(paths=["src/**/*.ts"]) \u2192 \u53EA\u7D22\u5F15\u6307\u5B9A\u8DEF\u5F84`;let y=await h.searchSymbol({query:c,kind:u,fuzzy:d,limit:p});if(y.length===0)return `\u2713 \u641C\u7D22: "${c}"
135
+
136
+ \u672A\u627E\u5230\u5339\u914D\u7684\u7B26\u53F7
137
+
138
+ \u{1F4A1} \u5EFA\u8BAE:
139
+ - \u5C1D\u8BD5 fuzzy=true \u8FDB\u884C\u6A21\u7CCA\u641C\u7D22
140
+ - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199
141
+ - \u8FD0\u884C build_index(force=true) \u91CD\u5EFA\u7D22\u5F15`;let x=[`\u2713 \u641C\u7D22: "${c}"${u?` (\u7C7B\u578B: ${u})`:""}${d?" (\u6A21\u7CCA\u5339\u914D)":""}`,`\u627E\u5230 ${y.length} \u4E2A\u7ED3\u679C:`,""];for(let S of y){let T=Nt(S.file),w=S.symbol.parent?`${S.symbol.parent}.`:"";x.push(`\u25B8 ${w}${S.symbol.name} (${S.symbol.kind})`,` \u{1F4C4} ${T}:${S.symbol.startLine}`,"");}if(x.push("\u{1F4A1} \u4F7F\u7528 readfile \u67E5\u770B\u8BE6\u60C5:"),y.length>0){let S=y[0];x.push(` readfile(path="${Nt(S.file)}", symbol="${S.symbol.name}")`);}return x.join(`
142
+ `)}},i={name:"get_definitions",description:`\u3010\u7B26\u53F7\u5B9A\u4E49\u3011\u5728\u7D22\u5F15\u4E2D\u67E5\u627E\u7B26\u53F7\u5B9A\u4E49\u4F4D\u7F6E\u3002
143
+
144
+ \u26A0\uFE0F \u9700\u8981\u5148\u8FD0\u884C build_index \u6784\u5EFA\u7D22\u5F15
145
+
146
+ \u793A\u4F8B:
147
+ get_definitions(query="UserService") \u2192 \u67E5\u627E\u5B9A\u4E49
148
+ get_definitions(symbol="handleLogin", kind="function")
149
+ get_definitions(query="User", path="src/auth") \u2192 \u9650\u5B9A\u76EE\u5F55`,parameters:{type:"object",properties:{query:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u4F18\u5148)"},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (query \u7684\u522B\u540D)"},kind:{type:"string",description:"\u7B26\u53F7\u7C7B\u578B: function, class, interface, method, variable, type, enum",enum:["function","class","interface","method","variable","type","enum"]},path:{type:"string",description:"\u9650\u5B9A\u641C\u7D22\u76EE\u5F55 (\u76F8\u5BF9\u5DE5\u4F5C\u533A)"},fuzzy:{type:"boolean",description:"\u6A21\u7CCA\u5339\u914D (\u9ED8\u8BA4: false)"},limit:{type:"number",description:"\u6700\u5927\u7ED3\u679C\u6570 (\u9ED8\u8BA4: 20)"}}},permission:{category:"read",allowInAskMode:true},async function(l){let c=typeof l.query=="string"?l.query:typeof l.symbol=="string"?l.symbol:"";if(!c.trim())return "\u2717 \u7F3A\u5C11\u53C2\u6570: query (\u6216 symbol)";let u=e(),d=gr(u);if(!await d.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
150
+
151
+ \u{1F4A1} \u8BF7\u5148\u8FD0\u884C build_index() \u6784\u5EFA\u7D22\u5F15`;let m=typeof l.limit=="number"&&l.limit>0?Math.min(l.limit,100):20,h=l.kind,g=!!l.fuzzy,y=await d.searchSymbol({query:c,kind:h,fuzzy:g,limit:m});if(l.path){let S=te.resolve(u,l.path);if(!zd(u,S))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";y=y.filter(T=>{let w=te.resolve(T.file);return w===S||w.startsWith(S+te.sep)});}if(y.length===0)return `\u2713 \u67E5\u627E: "${c}"
152
+
153
+ \u672A\u627E\u5230\u5B9A\u4E49
154
+
155
+ \u{1F4A1} \u5EFA\u8BAE:
156
+ - \u5C1D\u8BD5 fuzzy=true \u8FDB\u884C\u6A21\u7CCA\u641C\u7D22
157
+ - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199
158
+ - \u8FD0\u884C build_index(force=true) \u91CD\u5EFA\u7D22\u5F15`;let x=[`\u2713 \u5B9A\u4E49: "${c}"${h?` (\u7C7B\u578B: ${h})`:""}${g?" (\u6A21\u7CCA\u5339\u914D)":""}`,`\u627E\u5230 ${y.length} \u4E2A\u7ED3\u679C:`,""];for(let S of y){let T=Nt(S.file),w=S.symbol.parent?`${S.symbol.parent}.`:"";x.push(`\u25B8 ${w}${S.symbol.name} (${S.symbol.kind})`,` \u{1F4C4} ${T}:${S.symbol.startLine}`,"");}if(x.push("\u{1F4A1} \u4F7F\u7528 readfile \u67E5\u770B\u8BE6\u60C5:"),y.length>0){let S=y[0];x.push(` readfile(path="${Nt(S.file)}", symbol="${S.symbol.name}")`);}return x.join(`
159
+ `)}},o={name:"get_references",description:`\u3010\u7B26\u53F7\u5F15\u7528\u3011\u5728\u5DE5\u4F5C\u533A\u4E2D\u67E5\u627E\u7B26\u53F7\u5F15\u7528\u4F4D\u7F6E\u3002
160
+
161
+ \u793A\u4F8B:
162
+ get_references(query="UserService")
163
+ get_references(symbol="handleLogin", path="src/auth")
164
+ get_references(query="FeatureFlag", file_pattern="*.ts")`,parameters:{type:"object",properties:{query:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (\u4F18\u5148)"},symbol:{type:"string",description:"\u7B26\u53F7\u540D\u79F0 (query \u7684\u522B\u540D)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u76F8\u5BF9\u5DE5\u4F5C\u533A\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u533A)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,ts}")'},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: false)"},regex:{type:"boolean",description:"\u5C06 query \u4F5C\u4E3A\u6B63\u5219 (\u9ED8\u8BA4: false)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"}}},permission:{category:"read",allowInAskMode:true},async function(l){let c=typeof l.query=="string"?l.query:typeof l.symbol=="string"?l.symbol:"";if(!c.trim())return "\u2717 \u7F3A\u5C11\u53C2\u6570: query (\u6216 symbol)";let u=e(),d=te.resolve(u,l.path||".");if(!zd(u,d))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";let p;try{p=await he.stat(d);}catch{return "\u2717 \u8DEF\u5F84\u4E0D\u5B58\u5728"}let m=typeof l.context_lines=="number"&&l.context_lines>=0?Math.min(l.context_lines,10):2,h=typeof l.max_matches=="number"&&l.max_matches>0?Math.min(l.max_matches,1e3):200,g=!!l.case_insensitive,y=!!l.regex,x;try{let R=y?c:Eb(c);x=new RegExp(R,g?"gi":"g");}catch(R){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${R.message}`}let S=[];if(p.isDirectory()){let R=l.file_pattern||"**/*";S=await as(R,{cwd:d,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else S=[d];if(S.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let T=[],w=0,L=0,B=0;for(let R of S){if(w>=h)break;try{let E=await he.readFile(R,"utf-8");if(E.includes("\0"))continue;let M=E.split(`
165
+ `),_=new Set,W=new Map;for(let $=0;$<M.length&&!(w>=h);$++){let A=M[$],G=x.test(A);if(x.lastIndex=0,G){_.add($),w++;let N=Math.max(0,$-m),U=Math.min(M.length-1,$+m);for(let H=N;H<=U;H++){let Ie=W.get(H);W.set(H,{line:M[H],isMatch:Ie?.isMatch||H===$});}}}if(L++,_.size>0){B++;let A=Array.from(W.keys()).sort((G,N)=>G-N).map(G=>({lineNum:G+1,line:W.get(G)?.line||"",isMatch:W.get(G)?.isMatch||!1}));T.push({file:R,matches:A,matchCount:_.size});}}catch{continue}}let I=Nt(d),k=[`\u2713 \u5F15\u7528: "${c}"`,`\u25B8 \u8DEF\u5F84: ${I}`,l.file_pattern?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l.file_pattern}`:"",g?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",y?"\u25B8 \u6A21\u5F0F: \u6B63\u5219":"","",`\u6587\u4EF6: ${L} \u5DF2\u641C\u7D22, ${B} \u6709\u5339\u914D`,`\u5339\u914D: ${w}${w>=h?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(R=>R!=="");for(let R of T){let E=Nt(R.file);k.push(`
166
+ \u25B8 ${E} (${R.matchCount} \u5904)`),k.push("\u2500".repeat(50));let M=-10;for(let _ of R.matches){_.lineNum>M+1&&M>0&&k.push(" \u2504\u2504\u2504");let W=_.isMatch?"\u25B6":" ";k.push(`${W}${String(_.lineNum).padStart(5)} \u2502 ${_.line}`),M=_.lineNum;}}return T.length===0&&(k.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),k.push(""),k.push("\u{1F4A1} \u5EFA\u8BAE:"),k.push(" - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199"),k.push(" - \u4F7F\u7528 regex=true \u8FDB\u884C\u66F4\u7CBE\u786E\u5339\u914D"),k.push(" - \u7F29\u5C0F\u6216\u6269\u5927 path/file_pattern \u8303\u56F4")),k.join(`
167
+ `)}};return [t,n,r,i,o,{name:"index_stats",description:"\u3010\u7D22\u5F15\u7EDF\u8BA1\u3011\u67E5\u770B\u5F53\u524D\u9879\u76EE\u7684\u7D22\u5F15\u72B6\u6001\u548C\u7EDF\u8BA1\u4FE1\u606F\u3002",parameters:{type:"object",properties:{}},async function(){let l=e(),u=await gr(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
168
+
169
+ \u{1F4A1} \u8FD0\u884C build_index() \u6784\u5EFA\u7D22\u5F15\u4EE5\u83B7\u5F97\u66F4\u597D\u7684\u4EE3\u7801\u5BFC\u822A\u4F53\u9A8C`;let d=(u.size/1024).toFixed(1),p=(u.size/(1024*1024)).toFixed(2),m=u.size>1024*1024?`${p}MB`:`${d}KB`;return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u5DF2\u6784\u5EFA
170
+
171
+ \u7EDF\u8BA1:
172
+ \u6587\u4EF6\u6570: ${u.fileCount}
173
+ \u7B26\u53F7\u6570: ${u.symbolCount}
174
+ \u7D22\u5F15\u5927\u5C0F: ${m}
175
+ \u6700\u540E\u66F4\u65B0: ${u.lastUpdated?.toLocaleString()||"N/A"}
176
+
177
+ \u{1F4A1} \u4F7F\u7528 build_index(force=true) \u53EF\u4EE5\u91CD\u5EFA\u7D22\u5F15`}}]}var ls,cs,Bi,Mn,Jd,_b,Fi,Tb,wb,al,pl=K(()=>{tl();vt();Ea();ol();qs();Rn();ls=null,cs=null,Bi=null,Mn={small:zn,large:1e3},Jd=12e3,_b=120,Fi=20,Tb=3,wb=200,al=200;});var ji=K(()=>{qs();Ea();ol();Rn();Hd();pl();pl();});function Y(s,e,t,n){return {type:"ephemeral",status:e,tool:s,summary:t,final:e==="success"||e==="already_done",...n}}function ke(s,e,t,n,r){return {type:"contextual",status:e,tool:s,summary:t,content:n,...r}}function bn(s,e,t,n){return {type:"summarized",status:e,tool:s,summary:t,...n}}function tp(s){f.info("TOOL_RESULT",`\u{1F504} getResultForLLM input: ${s.tool}`,{type:s.type,status:s.status,tool:s.tool,hasContent:!!s.content,contentLength:s.content?.length||0,summary:s.summary?.substring(0,100)});let e;if(s.type==="ephemeral")if(s.status==="error")s.tool==="edit_file"?e=JSON.stringify({status:s.status,tool:s.tool,summary:s.summary,error:s.error,verify_hint:s.verify_hint,file_path:s.file_path,actual_content:s.actual_content,expected_start_line:s.expected_start_line,similar_matches:s.metadata?.similar_matches,suggestions:s.metadata?.suggestions}):e=JSON.stringify({status:s.status,tool:s.tool,summary:s.summary,error:s.error,verify_hint:s.verify_hint,file_path:s.file_path,similar_matches:s.metadata?.similar_matches,suggestions:s.metadata?.suggestions});else {let t=s.metadata?.edit_info;if(s.tool==="edit_file"&&t){let n=t.old_string?t.old_string.length>1e3?t.old_string.substring(0,1e3)+"...":t.old_string:void 0,r=t.new_string?t.new_string.length>1e3?t.new_string.substring(0,1e3)+"...":t.new_string:void 0;e=JSON.stringify({status:s.status,tool:s.tool,summary:s.summary,final:s.final,file_path:s.file_path,old_string_preview:n,new_string_preview:r,start_line:t.start_line});}else e=JSON.stringify({status:s.status,tool:s.tool,summary:s.summary,final:s.final,file_path:s.file_path});}else s.type==="summarized"?e=JSON.stringify({status:s.status,tool:s.tool,summary:s.summary,error:s.error}):e=JSON.stringify(s);return f.info("TOOL_RESULT",`\u2705 getResultForLLM output: ${s.tool}`,{type:s.type,tool:s.tool,llmResultLength:e.length,llmResultPreview:e.substring(0,500)}),e}var Hi=K(()=>{le();});async function kr(s,e,t){return (t?new It(t):xp).execute(s,e)}var lv,cv,It,xp,kl=K(()=>{lv={python:{command:"python3",args:["{file}"],extension:".py",useTempFile:true},javascript:{command:"node",args:["{file}"],extension:".js",useTempFile:true},typescript:{command:"npx",args:["tsx","{file}"],extension:".ts",useTempFile:true},bash:{command:"bash",args:["{file}"],extension:".sh",useTempFile:true},shell:{command:"sh",args:["{file}"],extension:".sh",useTempFile:true}},cv={timeout:3e4,maxMemoryMB:512,maxCPUPercent:50,allowNetwork:true,allowFileSystem:true,workingDirectory:process.cwd(),env:{},captureImages:false,maxOutputSize:1e4},It=class{config;constructor(e={}){this.config={...cv,...e};}async execute(e,t){let n=Date.now(),r=lv[t];if(!r)return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Unsupported language: ${t}`};if(!await this.checkRuntimeAvailable(r.command))return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Runtime not found: ${r.command}. Please install it first.`};let o=null;try{r.useTempFile&&(o=await this.createTempFile(e,r.extension));let a=r.args.map(h=>h.replace("{file}",o||"")),l=o?te__default.dirname(o):this.config.workingDirectory,c=[r.command,...a].join(" "),u={...Object.fromEntries(Object.entries(process.env).filter(([h,g])=>g!==void 0)),...this.config.env};t==="python"&&this.config.captureImages&&(u.MPLBACKEND="Agg");let d=await this.executeCommand(r.command,a,u,l),p=[];this.config.captureImages&&o&&(p=await this.captureGeneratedImages(te__default.dirname(o)));let m=Date.now()-n;return {...d,executionTime:m,command:c,workingDirectory:l,images:p&&p.length>0?p:void 0}}catch(a){let l=Date.now()-n;return {success:false,stdout:a.stdout||"",stderr:a.stderr||"",exitCode:a.exitCode||1,executionTime:l,error:a.message,timedOut:a.timedOut||false}}finally{o&&await this.cleanupTempFile(o);}}async checkRuntimeAvailable(e){try{return await execa(e,["--version"],{timeout:5e3}),!0}catch{return false}}async createTempFile(e,t){let n=await he__default.mkdtemp(te__default.join(ti__default.tmpdir(),"neox-code-")),r=te__default.join(n,`script${t}`);return await he__default.writeFile(r,e,"utf-8"),r}async executeCommand(e,t,n,r){try{let{stdout:i,stderr:o,exitCode:a}=await execa(e,t,{timeout:this.config.timeout,cwd:r,env:n,all:!0,reject:!1}),l=this.truncateOutput(i),c=this.truncateOutput(o);return {success:a===0,stdout:l,stderr:c,exitCode:a||0}}catch(i){throw i.timedOut?{stdout:i.stdout||"",stderr:i.stderr||"",exitCode:-1,message:`Execution timed out after ${this.config.timeout}ms`,timedOut:true}:{stdout:i.stdout||"",stderr:i.stderr||"",exitCode:i.exitCode||1,message:i.message}}}truncateOutput(e){if(e.length<=this.config.maxOutputSize)return e;let t=Math.floor(this.config.maxOutputSize/2);return e.slice(0,t)+`
178
+
179
+ ... [Truncated ${e.length-this.config.maxOutputSize} characters] ...
180
+
181
+ `+e.slice(-t)}async captureGeneratedImages(e){try{let n=(await he__default.readdir(e)).filter(i=>/\.(png|jpg|jpeg|svg)$/i.test(i)),r=[];for(let i of n){let o=te__default.join(e,i),l=(await he__default.readFile(o)).toString("base64");r.push({type:"base64",data:l,filename:i});}return r}catch{return []}}async cleanupTempFile(e){try{let t=te__default.dirname(e);await he__default.rm(t,{recursive:!0,force:!0});}catch{}}static formatResult(e){let t=[];return e.success?t.push(`\u2705 Code executed successfully
182
+ `):t.push(`\u274C Code execution failed
183
+ `),t.push(`\u23F1\uFE0F Execution time: ${e.executionTime}ms`),t.push(`\u{1F522} Exit code: ${e.exitCode}`),(e.command||e.workingDirectory)&&(t.push(`
184
+ \u{1F6E0}\uFE0F Command:`),e.command&&t.push(`$ ${e.command}`),e.workingDirectory&&t.push(`CWD: ${e.workingDirectory}`)),e.timedOut&&t.push("\u23F0 Execution timed out"),e.stdout&&(t.push(`
185
+ \u{1F4E4} Output:`),t.push("```"),t.push(e.stdout),t.push("```")),e.stderr&&(t.push(`
186
+ \u26A0\uFE0F Errors/Warnings:`),t.push("```"),t.push(e.stderr),t.push("```")),e.error&&(t.push(`
187
+ \u274C Error:`),t.push(e.error)),e.images&&e.images.length>0&&(t.push(`
188
+ \u{1F5BC}\uFE0F Generated ${e.images.length} image(s):`),e.images.forEach((n,r)=>{t.push(` ${r+1}. ${n.filename||"image"} (${n.type})`);})),t.join(`
189
+ `)}},xp=new It;});function Cl(s){let e=new It(s);return {name:"execute_code",description:`Execute code in multiple languages (Python, JavaScript, TypeScript, Bash/Shell).
190
+ Supports data analysis, calculations, file operations, and more.
191
+ Can capture generated images (matplotlib plots, etc.) if configured.
192
+
193
+ Configuration:
194
+ - Timeout: ${s?.timeout||3e4}ms
195
+ - Network access: ${s?.allowNetwork!==false?"Enabled":"Disabled"}
196
+ - File system access: ${s?.allowFileSystem!==false?"Enabled":"Disabled"}
197
+ - Image capture: ${s?.captureImages?"Enabled":"Disabled"}`,parameters:{type:"object",properties:{code:{type:"string",description:"The code to execute"},language:{type:"string",enum:["python","javascript","typescript","bash","shell"],description:"Programming language to use"}},required:["code","language"]},async function({code:t,language:n}){let r=await e.execute(t,n);return It.formatResult(r)}}}var El,Il,Rl,Sp=K(()=>{kl();El={name:"execute_python",description:`Execute Python code for calculations, data analysis, and scripting.
198
+ Useful for: math calculations, data processing, file operations, web scraping, etc.
199
+ Libraries commonly available: numpy, pandas, matplotlib, requests, etc.`,parameters:{type:"object",properties:{code:{type:"string",description:"Python code to execute"},capture_images:{type:"boolean",description:"Capture matplotlib plots and other images"}},required:["code"]},async function({code:s,capture_images:e=false}){let t=await kr(s,"python",{captureImages:e});return It.formatResult(t)}},Il={name:"execute_javascript",description:`Execute JavaScript (Node.js) code for calculations, data processing, and scripting.
200
+ Useful for: JSON processing, string manipulation, async operations, etc.
201
+ Has access to Node.js built-in modules.`,parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute"}},required:["code"]},async function({code:s}){let e=await kr(s,"javascript");return It.formatResult(e)}},Rl={name:"execute_bash",description:`Execute Bash/Shell scripts for system operations and file management.
202
+ Useful for: file operations, text processing, system commands, git operations, etc.
203
+ Has full access to system commands and utilities.`,parameters:{type:"object",properties:{code:{type:"string",description:"Bash script to execute"}},required:["code"]},async function({code:s}){let e=await kr(s,"bash");return It.formatResult(e)}},Cl({timeout:3e4,allowNetwork:true,allowFileSystem:true,captureImages:true,maxOutputSize:1e4}),Cl({timeout:1e4,allowNetwork:false,allowFileSystem:false,captureImages:false,maxOutputSize:5e3});});var Qi,_p=K(()=>{Qi={name:"debug_in_browser",description:`\u5728\u771F\u5B9E\u6D4F\u89C8\u5668\u73AF\u5883\u4E2D\u6253\u5F00\u6307\u5B9A URL \u5E76\u6536\u96C6\u8C03\u8BD5\u4FE1\u606F\u3002
204
+
205
+ \u8FD9\u4E2A\u5DE5\u5177\u4F1A\uFF1A
206
+ 1. \u81EA\u52A8\u542F\u52A8 Chrome \u6D4F\u89C8\u5668\uFF08headless \u6A21\u5F0F\uFF09
207
+ 2. \u6253\u5F00\u6307\u5B9A\u7684 URL\uFF08\u5982\u679C\u672A\u63D0\u4F9B\uFF0C\u81EA\u52A8\u68C0\u6D4B\u5F00\u53D1\u670D\u52A1\u5668\uFF09
208
+ 3. \u7B49\u5F85\u9875\u9762\u52A0\u8F7D\u5B8C\u6210
209
+ 4. **\u81EA\u52A8\u68C0\u6D4B\u767B\u5F55\u91CD\u5B9A\u5411**\uFF08\u5982\u679C\u9875\u9762\u88AB\u91CD\u5B9A\u5411\u5230\u767B\u5F55\u9875\u9762\uFF0C\u4F1A\u8FD4\u56DE needs_login: true\uFF09
210
+ 5. \u6536\u96C6 Console \u65E5\u5FD7\uFF08log/warn/error\uFF09
211
+ 6. \u6355\u83B7 JavaScript \u5F02\u5E38\u548C\u5806\u6808\u8DDF\u8E2A
212
+ 7. **\u76D1\u63A7 XHR/Fetch \u7F51\u7EDC\u8BF7\u6C42**\uFF08\u9ED8\u8BA4\u53EA\u6536\u96C6 API \u8BF7\u6C42\uFF0C\u652F\u6301\u8FC7\u6EE4\u548C\u54CD\u5E94\u4F53\u6536\u96C6\uFF09
213
+ 8. \u6536\u96C6\u6027\u80FD\u6307\u6807
214
+ 9. \uFF08\u53EF\u9009\uFF09\u622A\u53D6\u9875\u9762\u622A\u56FE
215
+ 10. \u5173\u95ED\u6D4F\u89C8\u5668\u5E76\u8FD4\u56DE\u6240\u6709\u6570\u636E
216
+
217
+ ## \u{1F310} \u7F51\u7EDC\u8BF7\u6C42\u76D1\u63A7\uFF08\u91CD\u8981\uFF01\uFF09
218
+
219
+ \u9ED8\u8BA4\u53EA\u6536\u96C6 **XHR/Fetch \u8BF7\u6C42**\uFF08API \u8C03\u7528\uFF09\uFF0C\u4E0D\u6536\u96C6\u9759\u6001\u8D44\u6E90\u3002
220
+
221
+ ### \u7F51\u7EDC\u8BF7\u6C42\u8FC7\u6EE4\u9009\u9879\uFF1A
222
+ - \`network_xhr_only\`: \u53EA\u6536\u96C6 XHR/Fetch\uFF08\u9ED8\u8BA4 true\uFF09
223
+ - \`network_url_pattern\`: URL \u6B63\u5219\u8FC7\u6EE4\uFF0C\u5982 \`"/api/"\` \u53EA\u770B API \u8BF7\u6C42
224
+ - \`network_status_filter\`: \u72B6\u6001\u7801\u8FC7\u6EE4
225
+ - \`"error"\`: \u6240\u6709 4xx \u548C 5xx
226
+ - \`"4xx"\`: \u53EA\u770B 400-499
227
+ - \`"5xx"\`: \u53EA\u770B 500-599
228
+ - \`"401,403"\`: \u6307\u5B9A\u72B6\u6001\u7801
229
+ - \`network_include_body\`: \u6536\u96C6\u54CD\u5E94\u4F53\uFF08\u9ED8\u8BA4\u5BF9\u9519\u8BEF\u8BF7\u6C42\u6536\u96C6\uFF09
230
+ - \`network_max_results\`: \u6700\u5927\u8FD4\u56DE\u6570\u91CF\uFF08\u9ED8\u8BA4 20\uFF09
231
+
232
+ ### \u5178\u578B\u4F7F\u7528\u573A\u666F\uFF1A
233
+
234
+ \`\`\`
235
+ // 1. \u53EA\u770B API \u9519\u8BEF\uFF08401\u3001403\u3001500 \u7B49\uFF09
236
+ debug_in_browser({ url: "...", network_status_filter: "error" })
237
+
238
+ // 2. \u53EA\u770B\u7279\u5B9A API
239
+ debug_in_browser({ url: "...", network_url_pattern: "/api/user" })
240
+
241
+ // 3. \u53EA\u770B 401 \u672A\u6388\u6743
242
+ debug_in_browser({ url: "...", network_status_filter: "401" })
243
+ \`\`\`
244
+
245
+ ### \u8FD4\u56DE\u7684\u7F51\u7EDC\u8BF7\u6C42\u4FE1\u606F\u5305\u542B\uFF1A
246
+ - URL\u3001Method\u3001\u72B6\u6001\u7801
247
+ - \u8BF7\u6C42\u4F53\uFF08POST/PUT\uFF09
248
+ - **\u54CD\u5E94\u4F53**\uFF08\u5BF9\u4E8E\u9519\u8BEF\u8BF7\u6C42\uFF0C\u5E2E\u52A9\u8BCA\u65AD\u95EE\u9898\uFF09
249
+ - \u8017\u65F6\u7EDF\u8BA1
250
+
251
+ ## \u{1F510} \u767B\u5F55\u72B6\u6001\u5904\u7406
252
+
253
+ \u672C\u5DE5\u5177\u4F7F\u7528**\u6301\u4E45\u5316\u6D4F\u89C8\u5668\u914D\u7F6E\u76EE\u5F55**\uFF08~/.neox/browser-profile\uFF09\uFF0C\u8FD9\u610F\u5473\u7740\uFF1A
254
+ - \u7528\u6237\u767B\u5F55\u4E00\u6B21\u540E\uFF0C\u767B\u5F55\u72B6\u6001\u4F1A\u81EA\u52A8\u4FDD\u5B58
255
+ - \u540E\u7EED\u8C03\u7528\u4F1A\u81EA\u52A8\u7EE7\u627F\u767B\u5F55\u72B6\u6001\uFF08cookies\u3001localStorage \u7B49\uFF09
256
+
257
+ ### \u5F53\u8FD4\u56DE needs_login: true \u65F6\uFF0C\u4F60\u5E94\u8BE5\uFF1A
258
+
259
+ 1. **\u544A\u77E5\u7528\u6237**\u9875\u9762\u9700\u8981\u767B\u5F55\u624D\u80FD\u8BBF\u95EE
260
+ 2. **\u4E3B\u52A8\u8C03\u7528\u672C\u5DE5\u5177**\u5E76\u8BBE\u7F6E \`open_for_login: true\`\uFF0C\u8FD9\u4F1A\uFF1A
261
+ - \u6253\u5F00**\u975E headless \u6D4F\u89C8\u5668\u7A97\u53E3**
262
+ - \u8BA9\u7528\u6237\u5728\u6D4F\u89C8\u5668\u4E2D\u624B\u52A8\u5B8C\u6210\u767B\u5F55
263
+ - \u767B\u5F55\u6210\u529F\u540E\u81EA\u52A8\u4FDD\u5B58\u72B6\u6001
264
+ 3. \u767B\u5F55\u6210\u529F\u540E\uFF0C\u518D\u6B21\u6B63\u5E38\u8C03\u7528\u5373\u53EF\u8BBF\u95EE\u9875\u9762
265
+
266
+ ## \u4F7F\u7528\u573A\u666F\uFF1A
267
+ - \u7528\u6237\u62A5\u544A\u9875\u9762\u9519\u8BEF\uFF0C\u9700\u8981\u5B9E\u9645\u67E5\u770B Console
268
+ - **\u8C03\u8BD5 API \u8BF7\u6C42\u95EE\u9898\uFF08401\u3001403\u3001500 \u7B49\uFF09**
269
+ - \u9700\u8981\u9A8C\u8BC1\u9875\u9762\u662F\u5426\u6B63\u5E38\u52A0\u8F7D
270
+ - \u8C03\u8BD5\u7F51\u7EDC\u8BF7\u6C42\u95EE\u9898\uFF08CORS\u3001404\u3001500\uFF09
271
+ - \u5206\u6790\u9875\u9762\u6027\u80FD
272
+ - \u83B7\u53D6\u771F\u5B9E\u8FD0\u884C\u65F6\u7684\u9519\u8BEF\u4FE1\u606F
273
+ - \u8C03\u8BD5\u9700\u8981\u767B\u5F55\u7684\u9875\u9762
274
+
275
+ ## \u6CE8\u610F\u4E8B\u9879\uFF1A
276
+ - \u6B64\u5DE5\u5177\u4F1A\u77ED\u6682\u542F\u52A8\u6D4F\u89C8\u5668\u8FDB\u7A0B\uFF08\u901A\u5E38 < 10 \u79D2\uFF09
277
+ - \u9ED8\u8BA4\u4F7F\u7528 headless \u6A21\u5F0F\uFF0C\u9664\u975E\u8BBE\u7F6E open_for_login: true
278
+ - \u9700\u8981\u76EE\u6807 URL \u53EF\u8BBF\u95EE
279
+ - \u7F51\u7EDC\u8BF7\u6C42\u6570\u91CF\u6709\u9650\u5236\uFF08\u9ED8\u8BA4\u6700\u591A 20 \u4E2A\uFF09\uFF0C\u9519\u8BEF\u8BF7\u6C42\u4F18\u5148\u8FD4\u56DE`,parameters:{type:"object",properties:{url:{type:"string",description:`\u8981\u8C03\u8BD5\u7684 URL\u3002
280
+ \u793A\u4F8B\uFF1A
281
+ - "http://localhost:5173"
282
+ - "http://localhost:3000/dashboard"
283
+ - "auto"\uFF08\u81EA\u52A8\u68C0\u6D4B\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u5F00\u53D1\u670D\u52A1\u5668\uFF09
284
+
285
+ \u5982\u679C\u4E0D\u63D0\u4F9B\uFF0C\u9ED8\u8BA4\u4E3A "auto"`},open_for_login:{type:"boolean",description:`\u{1F511} \u6253\u5F00\u6D4F\u89C8\u5668\u8BA9\u7528\u6237\u624B\u52A8\u767B\u5F55\u3002
286
+
287
+ \u5F53\u4E0A\u6B21\u8C03\u7528\u8FD4\u56DE needs_login: true \u65F6\uFF0C\u4F7F\u7528\u6B64\u53C2\u6570\uFF1A
288
+ - \u8BBE\u7F6E\u4E3A true \u4F1A\u6253\u5F00**\u53EF\u89C1\u7684\u6D4F\u89C8\u5668\u7A97\u53E3**\uFF08\u975E headless\uFF09
289
+ - \u7528\u6237\u53EF\u4EE5\u5728\u6D4F\u89C8\u5668\u4E2D\u624B\u52A8\u5B8C\u6210\u767B\u5F55
290
+ - \u767B\u5F55\u540E\u4F1A\u81EA\u52A8\u7B49\u5F85\u5E76\u68C0\u6D4B\u767B\u5F55\u72B6\u6001
291
+ - \u767B\u5F55\u4FE1\u606F\u4F1A\u4FDD\u5B58\u5230\u6301\u4E45\u5316\u914D\u7F6E\u76EE\u5F55\uFF0C\u540E\u7EED\u65E0\u9700\u518D\u767B\u5F55
292
+
293
+ **\u4F55\u65F6\u4F7F\u7528\uFF1A**
294
+ \u5F53\u7528\u6237\u4E0D\u60F3\u63D0\u4F9B\u8D26\u53F7\u5BC6\u7801\uFF0C\u6216\u7F51\u7AD9\u6709\u590D\u6742\u9A8C\u8BC1\u7801\u65F6`,default:false},auto_login:{type:"object",description:`\u{1F916} AI \u81EA\u52A8\u767B\u5F55\uFF08\u63A8\u8350\uFF09\u3002
295
+
296
+ \u5F53\u8FD4\u56DE needs_login: true \u65F6\uFF0C\u8BE2\u95EE\u7528\u6237\u8D26\u53F7\u5BC6\u7801\uFF0C\u7136\u540E\u4F7F\u7528\u6B64\u53C2\u6570\u81EA\u52A8\u767B\u5F55\uFF1A
297
+ - AI \u4F1A\u81EA\u52A8\u627E\u5230\u767B\u5F55\u8868\u5355\u5E76\u586B\u5199
298
+ - \u767B\u5F55\u6210\u529F\u540E\u81EA\u52A8\u4FDD\u5B58 cookies\uFF0C\u540E\u7EED\u65E0\u9700\u518D\u767B\u5F55
299
+
300
+ **\u4F7F\u7528\u6D41\u7A0B\uFF1A**
301
+ 1. \u8C03\u7528\u5DE5\u5177\uFF0C\u53D1\u73B0 needs_login: true
302
+ 2. \u8BE2\u95EE\u7528\u6237\uFF1A"\u9700\u8981\u767B\u5F55\uFF0C\u8BF7\u63D0\u4F9B\u8D26\u53F7\u548C\u5BC6\u7801"
303
+ 3. \u7528\u6237\u56DE\u590D\u8D26\u53F7\u5BC6\u7801\u540E\uFF0C\u518D\u6B21\u8C03\u7528\u5E76\u4F20\u5165 auto_login
304
+
305
+ **\u793A\u4F8B\uFF1A**
306
+ auto_login: { username: "admin", password: "123456" }`,properties:{username:{type:"string",description:"\u7528\u6237\u540D/\u90AE\u7BB1/\u624B\u673A\u53F7"},password:{type:"string",description:"\u5BC6\u7801"},username_selector:{type:"string",description:'\uFF08\u53EF\u9009\uFF09\u7528\u6237\u540D\u8F93\u5165\u6846\u7684 CSS \u9009\u62E9\u5668\uFF0C\u5982 #username\u3001input[name="email"]\u3002\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u68C0\u6D4B'},password_selector:{type:"string",description:"\uFF08\u53EF\u9009\uFF09\u5BC6\u7801\u8F93\u5165\u6846\u7684 CSS \u9009\u62E9\u5668\uFF0C\u5982 #password\u3002\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u68C0\u6D4B"},submit_selector:{type:"string",description:'\uFF08\u53EF\u9009\uFF09\u63D0\u4EA4\u6309\u94AE\u7684 CSS \u9009\u62E9\u5668\uFF0C\u5982 button[type="submit"]\u3002\u4E0D\u63D0\u4F9B\u5219\u81EA\u52A8\u68C0\u6D4B'}},required:["username","password"]},login_wait_time:{type:"number",description:"\u767B\u5F55\u6A21\u5F0F\u4E0B\u7B49\u5F85\u7528\u6237\u5B8C\u6210\u767B\u5F55\u7684\u6700\u5927\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\u3002\u9ED8\u8BA4 120000ms\uFF082\u5206\u949F\uFF09",default:12e4},use_profile:{type:"boolean",description:`\u662F\u5426\u4F7F\u7528\u6301\u4E45\u5316\u6D4F\u89C8\u5668\u914D\u7F6E\u76EE\u5F55\uFF08\u4FDD\u6301\u767B\u5F55\u72B6\u6001\uFF09\u3002
307
+ \u9ED8\u8BA4 true\u3002\u8BBE\u7F6E\u4E3A false \u4F1A\u4F7F\u7528\u5168\u65B0\u7684\u6D4F\u89C8\u5668\u4F1A\u8BDD\uFF08\u65E0\u4EFB\u4F55\u767B\u5F55\u72B6\u6001\uFF09`,default:true},wait_time:{type:"number",description:"\u9875\u9762\u52A0\u8F7D\u540E\u7B49\u5F85\u7684\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\uFF0C\u7528\u4E8E\u6536\u96C6\u5F02\u6B65\u65E5\u5FD7\u548C\u7F51\u7EDC\u8BF7\u6C42\u3002\u9ED8\u8BA4 3000ms\uFF083\u79D2\uFF09",default:3e3},collect_console:{type:"boolean",description:"\u662F\u5426\u6536\u96C6 console \u65E5\u5FD7\uFF08log/info/warn/error/debug\uFF09\u3002\u9ED8\u8BA4 true",default:true},collect_errors:{type:"boolean",description:"\u662F\u5426\u6536\u96C6 JavaScript \u5F02\u5E38\u548C\u672A\u6355\u83B7\u7684 Promise rejection\u3002\u9ED8\u8BA4 true",default:true},collect_network:{type:"boolean",description:"\u662F\u5426\u6536\u96C6\u7F51\u7EDC\u8BF7\u6C42\uFF08\u9ED8\u8BA4\u53EA\u6536\u96C6 XHR/Fetch\uFF09\u3002\u9ED8\u8BA4 true",default:true},network_xhr_only:{type:"boolean",description:`\u53EA\u6536\u96C6 XHR/Fetch \u8BF7\u6C42\uFF08API \u8C03\u7528\uFF09\u3002
308
+ \u9ED8\u8BA4 true\u3002\u8BBE\u7F6E\u4E3A false \u4F1A\u6536\u96C6\u6240\u6709\u8BF7\u6C42\uFF08\u4F46\u4ECD\u8FC7\u6EE4\u9759\u6001\u8D44\u6E90\u5982\u56FE\u7247\u3001\u5B57\u4F53\uFF09`,default:true},network_url_pattern:{type:"string",description:`URL \u6B63\u5219\u8FC7\u6EE4\u6A21\u5F0F\u3002\u53EA\u6709\u5339\u914D\u7684\u8BF7\u6C42\u4F1A\u88AB\u6536\u96C6\u3002
309
+ \u793A\u4F8B\uFF1A
310
+ - "/api/" - \u53EA\u6536\u96C6\u5305\u542B /api/ \u7684\u8BF7\u6C42
311
+ - "user|auth" - \u6536\u96C6\u5305\u542B user \u6216 auth \u7684\u8BF7\u6C42
312
+ - "^https://api\\.example\\.com" - \u53EA\u6536\u96C6\u7279\u5B9A\u57DF\u540D`},network_status_filter:{type:"string",description:`\u6309 HTTP \u72B6\u6001\u7801\u8FC7\u6EE4\u8BF7\u6C42\u3002
313
+ \u53EF\u9009\u503C\uFF1A
314
+ - "error" - \u6240\u6709 4xx \u548C 5xx \u9519\u8BEF
315
+ - "4xx" - \u53EA\u770B\u5BA2\u6237\u7AEF\u9519\u8BEF\uFF08400-499\uFF09
316
+ - "5xx" - \u53EA\u770B\u670D\u52A1\u7AEF\u9519\u8BEF\uFF08500-599\uFF09
317
+ - "401,403,500" - \u6307\u5B9A\u5177\u4F53\u72B6\u6001\u7801\uFF08\u9017\u53F7\u5206\u9694\uFF09
318
+
319
+ **\u63A8\u8350\u4F7F\u7528\u573A\u666F\uFF1A**
320
+ - \u8C03\u8BD5\u767B\u5F55\u95EE\u9898\u7528 "401"
321
+ - \u8C03\u8BD5\u6743\u9650\u95EE\u9898\u7528 "403"
322
+ - \u8C03\u8BD5\u670D\u52A1\u5668\u9519\u8BEF\u7528 "5xx"
323
+ - \u67E5\u770B\u6240\u6709\u9519\u8BEF\u7528 "error"`},network_include_body:{type:"boolean",description:`\u662F\u5426\u6536\u96C6\u54CD\u5E94\u4F53\u5185\u5BB9\u3002
324
+ \u9ED8\u8BA4 true\uFF08\u53EA\u5BF9\u9519\u8BEF\u8BF7\u6C42\u6536\u96C6\uFF09\u3002\u54CD\u5E94\u4F53\u5BF9\u4E8E\u8BCA\u65AD 401\u3001500 \u7B49\u9519\u8BEF\u975E\u5E38\u6709\u7528\u3002`,default:true},network_body_max_length:{type:"number",description:"\u54CD\u5E94\u4F53\u6700\u5927\u957F\u5EA6\uFF08\u5B57\u8282\uFF09\u3002\u8D85\u51FA\u4F1A\u88AB\u622A\u65AD\u3002\u9ED8\u8BA4 5000",default:5e3},network_max_results:{type:"number",description:`\u6700\u5927\u8FD4\u56DE\u7684\u7F51\u7EDC\u8BF7\u6C42\u6570\u91CF\u3002
325
+ \u9ED8\u8BA4 20\u3002\u9519\u8BEF\u8BF7\u6C42\u4F1A\u4F18\u5148\u8FD4\u56DE\u3002\u5982\u679C\u8BF7\u6C42\u5F88\u591A\u4F46\u4F60\u53EA\u5173\u5FC3\u9519\u8BEF\uFF0C\u5EFA\u8BAE\u540C\u65F6\u4F7F\u7528 network_status_filter: "error"`,default:20},collect_performance:{type:"boolean",description:"\u662F\u5426\u6536\u96C6\u6027\u80FD\u6307\u6807\uFF08\u52A0\u8F7D\u65F6\u95F4\u3001DOM \u8282\u70B9\u6570\u3001\u5185\u5B58\u4F7F\u7528\u7B49\uFF09\u3002\u9ED8\u8BA4 true",default:true},take_screenshot:{type:"boolean",description:`\u662F\u5426\u622A\u53D6\u9875\u9762\u622A\u56FE\uFF08base64 \u683C\u5F0F\uFF09\u3002
326
+
327
+ \u4F55\u65F6\u4F7F\u7528\u622A\u56FE\uFF1A
328
+ - \u5F53 Console \u65E5\u5FD7\u548C\u9519\u8BEF\u4FE1\u606F\u4E0D\u8DB3\u4EE5\u5224\u65AD\u95EE\u9898\u65F6
329
+ - \u9700\u8981\u67E5\u770B\u9875\u9762\u5B9E\u9645\u6E32\u67D3\u6548\u679C\uFF08\u5E03\u5C40\u3001\u6837\u5F0F\u3001\u5185\u5BB9\uFF09
330
+ - \u7528\u6237\u62A5\u544A UI \u663E\u793A\u95EE\u9898\u4F46\u6CA1\u6709\u63D0\u4F9B\u622A\u56FE
331
+
332
+ \u9ED8\u8BA4 false\uFF0C\u56E0\u4E3A\u622A\u56FE\u4F1A\u589E\u52A0\u54CD\u5E94\u5927\u5C0F\u3002`,default:false},headless:{type:"boolean",description:"\u662F\u5426\u4F7F\u7528 headless \u6A21\u5F0F\uFF08\u4E0D\u663E\u793A\u6D4F\u89C8\u5668\u7A97\u53E3\uFF09\u3002\u9ED8\u8BA4 true\u3002\u6CE8\u610F\uFF1A\u5982\u679C\u8BBE\u7F6E\u4E86 open_for_login: true\uFF0C\u6B64\u53C2\u6570\u4F1A\u88AB\u5FFD\u7565",default:true}},required:[]},async function(s){throw new Error("debug_in_browser tool must be created via createDebugInBrowserTool(workspacePath) to provide workspace context")}};});function Pl(){return Cr}function eo(){return existsSync(Cr)||(mkdirSync(Cr,{recursive:true}),f.info("CHROME",`Created browser profile directory: ${Cr}`)),Cr}async function wp(){let s=platform(),t={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium"],win32:["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",(process.env.LOCALAPPDATA||"")+"\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files\\Google\\Chrome Beta\\Application\\chrome.exe"],linux:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"]}[s]||[];for(let n of t)if(existsSync(n))return f.info("CHROME",`Found Chrome at: ${n}`),{path:n,version:"unknown",available:true};return f.warn("CHROME","No Chrome installation found"),null}async function Al(s={}){let{headless:e=true,useProfile:t=true}=s,n=await wp();if(!n)throw new Error("Chrome not found. Please install Google Chrome from https://www.google.com/chrome/");f.info("CHROME",`Launching Chrome (headless: ${e}, useProfile: ${t})...`);let r={executablePath:n.path,headless:e,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage","--disable-accelerated-2d-canvas","--no-first-run","--no-zygote","--disable-gpu"],defaultViewport:{width:1280,height:720}};if(t){let o=eo();r.userDataDir=o,f.info("CHROME",`Using profile directory: ${o}`);}let i=await gv.launch(r);return f.info("CHROME","Chrome launched successfully"),i}var Cr,to=K(()=>{le();Cr=join(homedir(),".neox","browser-profile");});function vv(s,e){return s?e==="error"?s>=400:e==="4xx"?s>=400&&s<500:e==="5xx"?s>=500:e.split(",").map(n=>parseInt(n.trim(),10)).includes(s):false}async function no(s,e,t){let n=Date.now(),r={xhr_only:true,include_body:true,body_max_length:5e3,max_results:20,...t.network_filter},i=[],o=[],l=new Map,c=`
333
+ (function() {
334
+ if (window.__NEOX_INJECTED__) return;
335
+ window.__NEOX_CONSOLE_LOGS__ = window.__NEOX_CONSOLE_LOGS__ || [];
336
+ window.__NEOX_ERRORS__ = window.__NEOX_ERRORS__ || [];
337
+
338
+ var originalLog = console.log;
339
+ var originalDebug = console.debug;
340
+ var originalInfo = console.info;
341
+ var originalWarn = console.warn;
342
+ var originalError = console.error;
343
+ var originalTrace = console.trace;
344
+
345
+ function captureLog(type, original) {
346
+ return function() {
347
+ var args = Array.prototype.slice.call(arguments);
348
+ var message = args.map(function(arg) {
349
+ if (typeof arg === 'object') {
350
+ try { return JSON.stringify(arg); } catch(e) { return String(arg); }
351
+ }
352
+ return String(arg);
353
+ }).join(' ');
354
+ window.__NEOX_CONSOLE_LOGS__.push({ type: type, message: message, timestamp: Date.now() });
355
+ return original.apply(console, args);
356
+ };
357
+ }
358
+
359
+ console.log = captureLog('log', originalLog);
360
+ console.debug = captureLog('debug', originalDebug);
361
+ console.info = captureLog('info', originalInfo);
362
+ console.warn = captureLog('warn', originalWarn);
363
+ console.error = captureLog('error', originalError);
364
+ console.trace = captureLog('trace', originalTrace);
365
+
366
+ window.addEventListener('error', function(event) {
367
+ window.__NEOX_ERRORS__.push({
368
+ type: 'exception',
369
+ message: event.message,
370
+ file: event.filename,
371
+ line: event.lineno,
372
+ column: event.colno,
373
+ stack: event.error ? event.error.stack : '',
374
+ timestamp: Date.now()
375
+ });
376
+ });
377
+
378
+ window.addEventListener('unhandledrejection', function(event) {
379
+ window.__NEOX_ERRORS__.push({
380
+ type: 'unhandled_rejection',
381
+ message: event.reason ? (event.reason.message || String(event.reason)) : 'Unknown',
382
+ stack: event.reason ? event.reason.stack : '',
383
+ timestamp: Date.now()
384
+ });
385
+ });
386
+
387
+ window.__NEOX_INJECTED__ = true;
388
+ })();
389
+ `;(t.collect_console!==false||t.collect_errors!==false)&&(await s.evaluateOnNewDocument(c),s.on("framenavigated",async I=>{if(I===s.mainFrame())try{await I.evaluate(c),f.debug("BROWSER",`Re-injected script after navigation to ${I.url()}`);}catch{}}));let u=await s.createCDPSession();await u.send("Runtime.enable"),await u.send("Log.enable");let d=I=>{let{type:k,args:R,timestamp:E}=I,_={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[k]||"log",W=R.map($=>$.value!==void 0?String($.value):$.description?$.description:$.preview?.properties?JSON.stringify($.preview.properties.reduce((A,G)=>(A[G.name]=G.value,A),{})):String($.type)).join(" ");i.push({type:_,timestamp:E?Math.floor(E):Date.now(),message:W}),f.debug("BROWSER",`[CDP] ${_}: ${W.substring(0,100)}`);},p=I=>{let{exceptionDetails:k}=I,R=k.exception?.description||k.text||"Unknown error";o.push({type:"exception",message:R,stack:k.stackTrace?.callFrames?.map(E=>` at ${E.functionName||"(anonymous)"} (${E.url}:${E.lineNumber}:${E.columnNumber})`).join(`
390
+ `)||"",file:k.url,line:k.lineNumber,column:k.columnNumber,timestamp:Date.now()}),f.debug("BROWSER",`[CDP Exception] ${R}`);},m=I=>{let{entry:k}=I,R=k.level;R==="error"?k.text&&(k.text.includes("Uncaught")||k.text.includes("Error"))?(o.push({type:"exception",message:k.text,stack:k.stackTrace?.callFrames?.map(E=>` at ${E.functionName||"(anonymous)"} (${E.url}:${E.lineNumber}:${E.columnNumber})`).join(`
391
+ `)||"",file:k.url,line:k.lineNumber,timestamp:Date.now()}),f.debug("BROWSER",`[CDP Log Error] ${k.text}`)):(i.push({type:"error",timestamp:Date.now(),message:k.text}),f.debug("BROWSER",`[CDP Log] error: ${k.text}`)):R==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:k.text});};if(t.collect_console!==false&&u.on("Runtime.consoleAPICalled",d),t.collect_errors!==false&&(u.on("Runtime.exceptionThrown",p),u.on("Log.entryAdded",m),s.on("pageerror",I=>{let k=I;o.push({type:"exception",message:k.message,stack:k.stack||"",timestamp:Date.now()}),f.debug("BROWSER",`[Puppeteer pageerror] ${k.message}`);}),s.on("requestfailed",I=>{let k=I.failure();o.push({type:"browser_error",message:`Request failed: ${k?.errorText||"Unknown error"}`,stack:"",file:I.url(),timestamp:Date.now()});})),t.collect_console!==false&&s.on("console",I=>{let k=I.type();i.push({type:k,timestamp:Date.now(),message:I.text(),args:I.args().map(R=>R.toString())}),f.debug("BROWSER",`[Puppeteer console] ${k}: ${I.text().substring(0,100)}`);}),t.collect_network!==false){let I=null;if(r.url_pattern)try{I=new RegExp(r.url_pattern,"i");}catch{f.warn("BROWSER",`Invalid URL pattern: ${r.url_pattern}`);}s.on("request",k=>{let R=k.url(),E=k.resourceType();if(r.xhr_only&&!yv.includes(E)||!r.xhr_only&&bv.includes(E)||I&&!I.test(R))return;`${k.method()}-${R}-${Date.now()}`;let _={url:R,method:k.method(),resource_type:E,request_headers:k.headers(),timing:{start:Date.now(),end:0,duration:0}},W=k.postData();if(W){let $=r.body_max_length||5e3;W.length>$?_.request_body=W.substring(0,$)+"...[truncated]":_.request_body=W;}l.set(R,_),f.debug("BROWSER",`[Network] ${E.toUpperCase()} ${k.method()} ${R}`);}),s.on("response",async k=>{let R=k.url(),E=l.get(R);if(!E||!E.timing)return;E.status=k.status(),E.status_text=k.statusText(),E.response_headers=k.headers(),E.timing.end=Date.now(),E.timing.duration=E.timing.end-E.timing.start;let M=E.status>=400;if(r.include_body&&(M||r.status_filter))try{let W=k.headers()["content-type"]||"";if(W.includes("json")||W.includes("text")||W.includes("html")){let $=await k.text(),A=r.body_max_length||5e3;$.length>A?(E.response_body=$.substring(0,A),E.response_truncated=!0):E.response_body=$;}}catch(W){f.debug("BROWSER",`Failed to get response body for ${R}: ${W}`);}f.debug("BROWSER",`[Network] Response ${E.status} ${R} (${E.timing.duration}ms)`);}),s.on("requestfailed",k=>{let R=k.url(),E=l.get(R),M=k.failure();E&&(E.error=M?.errorText||"Request failed",E.timing&&(E.timing.end=Date.now(),E.timing.duration=E.timing.end-E.timing.start)),o.push({type:"browser_error",message:`Request failed: ${M?.errorText||"Unknown error"}`,stack:"",file:R,timestamp:Date.now()});});}f.info("BROWSER",`Navigating to: ${e}`),await s.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await u.send("Runtime.enable"),await u.send("Log.enable"),f.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{f.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await s.evaluate(c),f.debug("BROWSER","Ensured script injection after page.goto");}catch{f.debug("BROWSER","Script already injected or page not ready");}let h=t.wait_time||3e3;if(f.info("BROWSER",`Waiting ${h}ms for async content...`),await new Promise(I=>setTimeout(I,h)),f.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{f.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let I=await s.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));f.debug("BROWSER",`Extracted ${I.consoleLogs.length} console logs and ${I.errors.length} errors from injected script`);for(let E of I.consoleLogs)f.debug("BROWSER",` [${E.type}] ${E.message?.substring(0,100)}`);let k=new Map;for(let E of I.consoleLogs){let M=`${E.type}:${E.message}`;k.has(M)||k.set(M,{type:E.type,timestamp:E.timestamp,message:E.message});}for(let E of i){let M=`${E.type}:${E.message}`;k.has(M)||k.set(M,E);}i.length=0,i.push(...Array.from(k.values()));let R=new Map;for(let E of I.errors){let M=`${E.type}:${E.message}`;R.has(M)||R.set(M,{type:E.type,message:E.message,stack:E.stack||"",file:E.file,line:E.line,column:E.column,timestamp:E.timestamp});}for(let E of o){let M=`${E.type}:${E.message}`;R.has(M)||R.set(M,E);}o.length=0,o.push(...Array.from(R.values())),f.info("BROWSER",`Final: ${i.length} console logs, ${o.length} errors`);}catch(I){f.error("BROWSER","Failed to extract injected logs",{error:I});}let g;if(t.collect_performance!==false)try{let I=await s.metrics(),k=await s.evaluate(()=>{let E=window.performance.timing;return {domContentLoaded:E.domContentLoadedEventEnd-E.navigationStart,loadComplete:E.loadEventEnd-E.navigationStart}});g={dom_content_loaded:k.domContentLoaded,load_complete:k.loadComplete,dom_nodes:I.Nodes||0,js_heap_size:I.JSHeapUsedSize||0,event_listeners:I.JSEventListeners||0};}catch(I){f.error("BROWSER","Failed to collect performance metrics",{error:I});}let y;if(t.take_screenshot===true)try{y=await s.screenshot({encoding:"base64"});}catch(I){f.error("BROWSER","Failed to capture screenshot",{error:I});}try{await u.detach();}catch{}let x=Array.from(l.values()),S=x.length;r.status_filter&&(x=x.filter(I=>vv(I.status,r.status_filter)));let T=x.filter(I=>I.error||I.status&&I.status>=400).length;x.sort((I,k)=>{let R=I.error||I.status&&I.status>=400,E=k.error||k.status&&k.status>=400;return R&&!E?-1:!R&&E?1:(I.timing?.start||0)-(k.timing?.start||0)});let w=r.max_results||20;x.length>w&&(x=x.slice(0,w));let L={total_captured:S,filtered_count:x.length,error_count:T};f.info("BROWSER",`Network: ${S} captured, ${x.length} returned, ${T} errors`);let B=Date.now()-n;return {console_logs:i,errors:o,network_requests:x,network_stats:L,performance:g,screenshot:y,load_time:B}}function so(s){let e=[];s.errors&&s.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${s.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),s.errors.slice(0,5).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`),o.file&&e.push(` \u4F4D\u7F6E\uFF1A${o.file}:${o.line||""}`);}),e.push(""));let t=s.console_logs?.filter(o=>o.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`);}),e.push(""));let n=s.console_logs?.filter(o=>o.type==="warn")||[];n.length>0&&(e.push(`\u26A0\uFE0F ${n.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),n.slice(0,3).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`);}),e.push(""));let r=s.console_logs?.filter(o=>o.type==="debug")||[];if(r.length>0&&(e.push(`\u{1F50D} ${r.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),r.slice(0,3).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`);}),e.push("")),s.errors?.length===0&&t.length===0&&n.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),s.network_stats){let o=s.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${o.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${o.filtered_count} \u4E2A\uFF0C${o.error_count} \u4E2A\u9519\u8BEF`);}let i=s.network_requests?.filter(o=>o.error||o.status&&o.status>=400)||[];return i.length>0&&(e.push(`\u{1F534} ${i.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),i.slice(0,5).forEach((o,a)=>{if(e.push(` ${a+1}. [${o.status||"Failed"}] ${o.method} ${o.url}`),o.response_body){let l=o.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${o.response_body.length>200?"...":""}`);}o.error&&e.push(` \u9519\u8BEF: ${o.error}`);}),e.push("")),s.performance&&(s.performance.dom_nodes>5e3&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${s.performance.dom_nodes})`),s.performance.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(s.performance.js_heap_size/1024/1024).toFixed(1)}MB)`)),e.join(`
392
+ `)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}var yv,bv,Ml=K(()=>{le();yv=["xhr","fetch"],bv=["stylesheet","script","image","font","media"];});async function kp(s){let e=await xv(s);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Sv(s);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let n=await _v(s);if(n)return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"env"};let r=await Tv(s);return {url:`http://localhost:${r}`,port:r,protocol:"http",source:"default"}}async function xv(s){try{let e=join(s,"vite.config.js"),n=(await readFile(e,"utf-8")).match(/server\s*:\s*\{[^}]*port\s*:\s*(\d+)/);return n?parseInt(n[1]):null}catch{return null}}async function Sv(s){try{let e=join(s,"package.json"),t=await readFile(e,"utf-8"),r=JSON.parse(t).scripts?.dev||"",i=r.match(/--port\s+(\d+)/);if(i)return parseInt(i[1]);let o=r.match(/PORT=(\d+)/);return o?parseInt(o[1]):null}catch{return null}}async function _v(s){try{let e=join(s,".env"),n=(await readFile(e,"utf-8")).match(/(?:VITE_)?PORT\s*=\s*(\d+)/);return n?parseInt(n[1]):null}catch{return null}}async function Tv(s){try{let e=join(s,"package.json"),t=await readFile(e,"utf-8"),n=JSON.parse(t),r={...n.dependencies,...n.devDependencies};return r.vite?5173:r.next||r["react-scripts"]?3e3:r.vue?8080:r.nuxt?3e3:r.svelte?5e3:3e3}catch{return 3e3}}async function Ll(s,e=3e3){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),r=await fetch(s,{method:"HEAD",signal:t.signal});return clearTimeout(n),r.ok}catch{return false}}async function Ol(s){let e=await kp(s);if(await Ll(e.url))return e;let n=[5173,3e3,8080,5e3,4200,8e3];for(let r of n){let i=`http://localhost:${r}`;if(await Ll(i))return {url:i,port:r,protocol:"http",source:"default"}}return null}var Dl=K(()=>{});function Cp(s){try{return new URL(s).hostname}catch{return s}}function Ep(){let s=eo();return join(s,Iv)}function Ip(){let s=Ep();if(!existsSync(s))return {};try{let e=readFileSync(s,"utf-8");return JSON.parse(e)}catch(e){return f.warn("HEADERS","Failed to read headers config",{error:e}),{}}}function Rp(s){let e=Ep();try{let t=JSON.stringify(s,null,2);writeFileSync(e,t,"utf-8"),f.info("HEADERS","Headers config saved",{path:e});}catch(t){f.error("HEADERS","Failed to save headers config",{error:t});}}function oo(s,e){let t=Cp(s),n=Ip(),r=Rv(e);if(Object.keys(r).length===0){f.info("HEADERS","No headers to save for domain",{domain:t});return}n[t]={headers:r,lastUsed:Date.now(),createdAt:n[t]?.createdAt||Date.now(),url:s},Rp(n),f.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(r).length});}function $l(s){let e=Cp(s),t=Ip(),n=t[e];return n?(n.lastUsed=Date.now(),Rp(t),f.info("HEADERS","Retrieved headers for domain",{domain:e,headerCount:Object.keys(n.headers).length}),n.headers):(f.info("HEADERS","No saved headers for domain",{domain:e}),null)}function Rv(s){let e={},t=[/^authorization$/i,/^x-/i,/^cookie$/i,/^token$/i,/^auth/i,/^api-key$/i,/^api_key$/i,/^apikey$/i],n=new Set(["user-agent","accept","accept-encoding","accept-language","content-type","content-length","host","origin","referer","connection","cache-control","pragma","upgrade-insecure-requests","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]);for(let[r,i]of Object.entries(s)){let o=r.toLowerCase();if(n.has(o))continue;t.some(l=>l.test(r))&&(e[r]=i);}return e}var Iv,Nl=K(()=>{to();le();Iv="headers.json";});async function Pp(s,e){let t={},n=false,r=o=>{if(n)return;o.url();let l=o.resourceType();if(l==="xhr"||l==="fetch"||l==="document"){let c=o.headers();Object.assign(t,c);}},i=o=>{if(n)return;let a=o.status();o.url();let c=o.request().resourceType();a>=200&&a<300&&(c==="xhr"||c==="fetch")&&(n=true);};return s.on("request",r),s.on("response",i),t}async function Dv(s,e){let t=$l(e);return !t||Object.keys(t).length===0?false:(await s.setExtraHTTPHeaders(t),true)}async function Ul(s,e){let t=s.url(),n=t.toLowerCase();if(t!==e&&Pv.some(i=>n.includes(i)))return {detected:true,original_url:e,redirected_url:t,redirect_type:"url_change",reason:`\u9875\u9762\u88AB\u91CD\u5B9A\u5411\u5230\u767B\u5F55\u9875\u9762: ${t}`};try{for(let r of Av)if(await s.$(r))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"login_form",reason:`\u9875\u9762\u5305\u542B\u767B\u5F55\u8868\u5355\u5143\u7D20: ${r}`}}catch{}try{let r=await s.title(),i=r.toLowerCase(),o=["login","\u767B\u5F55","sign in","\u767B\u5165","authenticate","\u8BA4\u8BC1"];for(let a of o)if(i.includes(a))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"auth_keyword",reason:`\u9875\u9762\u6807\u9898\u5305\u542B\u767B\u5F55\u5173\u952E\u8BCD: "${r}"`}}catch{}return {detected:false,original_url:e}}async function $v(s,e,t){try{t?.("auto_login_start",{message:"\u6B63\u5728\u81EA\u52A8\u586B\u5199\u767B\u5F55\u8868\u5355..."});let n=null;if(e.username_selector&&(n=await s.$(e.username_selector)),!n)for(let o of Mv)try{if(n=await s.$(o),n)break}catch{}if(!n)return {success:!1,error:"\u627E\u4E0D\u5230\u7528\u6237\u540D\u8F93\u5165\u6846"};let r=null;if(e.password_selector&&(r=await s.$(e.password_selector)),!r)for(let o of Lv)try{if(r=await s.$(o),r)break}catch{}if(!r)return {success:!1,error:"\u627E\u4E0D\u5230\u5BC6\u7801\u8F93\u5165\u6846"};let i=null;if(e.submit_selector&&(i=await s.$(e.submit_selector)),!i)for(let o of Ov)try{if(i=await s.$(o),i)break}catch{}return i?(await n.click({clickCount:3}),await n.type(e.username,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u7528\u6237\u540D"}),await r.click({clickCount:3}),await r.type(e.password,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u5BC6\u7801"}),t?.("auto_login_progress",{message:"\u6B63\u5728\u63D0\u4EA4\u767B\u5F55..."}),await Promise.all([s.waitForNavigation({waitUntil:"networkidle0",timeout:3e4}).catch(()=>{}),i.click()]),await new Promise(o=>setTimeout(o,2e3)),{success:!0}):{success:!1,error:"\u627E\u4E0D\u5230\u767B\u5F55\u6309\u94AE"}}catch(n){return {success:false,error:String(n)}}}async function ao(s,e,t){let n=null,r=s.open_for_login===true,i=s.auto_login&&s.auto_login.username&&s.auto_login.password;try{let o=s.url||"auto";if(o==="auto"){t?.("detecting");let g=await Ol(e);if(!g){let y={success:!1,error:"\u672A\u627E\u5230\u8FD0\u884C\u4E2D\u7684\u5F00\u53D1\u670D\u52A1\u5668\u3002\u8BF7\u5148\u542F\u52A8\u5F00\u53D1\u670D\u52A1\u5668\uFF08\u5982 npm run dev\uFF09",url:"",load_time:0,timestamp:Date.now(),summary:"\u9519\u8BEF\uFF1A\u672A\u627E\u5230\u5F00\u53D1\u670D\u52A1\u5668"};return t?.("error",{error:y.error}),y}o=g.url,t?.("detected",{url:o});}t?.("launching",{url:o});let a=r?!1:s.headless!==!1,l=s.use_profile!==!1;n=await Al({headless:a,useProfile:l}),t?.("loading",{url:o});let c=await n.newPage(),u=await Dv(c,o);u&&t?.("headers_applied",{message:"\u5DF2\u5E94\u7528\u4FDD\u5B58\u7684\u8BA4\u8BC1 headers"}),await c.goto(o,{waitUntil:"networkidle0",timeout:3e4});let d=await Ul(c,o);if(i&&d.detected){t?.("auto_login",{message:"\u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0C\u6B63\u5728\u81EA\u52A8\u767B\u5F55..."});let g=Pp(c,o),y=await $v(c,s.auto_login,t);if(!y.success)return await n.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:`\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25: ${y.error}`,login_redirect:d,needs_login:!0};let x=await Ul(c,o),S=await g;if(x.detected)return await n.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:"\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5",login_redirect:x,needs_login:!0};{Object.keys(S).length>0&&(oo(o,S),t?.("headers_saved",{headerCount:Object.keys(S).length})),t?.("auto_login_success",{message:"\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F"}),t?.("collecting",{url:o});let T=await no(c,o,{wait_time:s.wait_time,collect_console:s.collect_console,collect_errors:s.collect_errors,collect_network:s.collect_network,collect_performance:s.collect_performance,take_screenshot:s.take_screenshot,network_filter:{xhr_only:s.network_xhr_only,url_pattern:s.network_url_pattern,status_filter:s.network_status_filter,include_body:s.network_include_body,body_max_length:s.network_body_max_length,max_results:s.network_max_results}}),w=so({console_logs:T.console_logs,errors:T.errors,network_requests:T.network_requests,network_stats:T.network_stats,performance:T.performance});return await n.close(),{success:!0,url:o,load_time:T.load_time,timestamp:Date.now(),console_logs:T.console_logs,errors:T.errors,network_requests:T.network_requests,performance:T.performance,screenshot:T.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
393
+
394
+ ${w}`,login_redirect:{detected:!1,original_url:o},needs_login:!1,captured_headers:S}}}if(d.detected&&!r&&!i)return await n.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:`\u26A0\uFE0F \u9875\u9762\u9700\u8981\u767B\u5F55: ${d.reason}
395
+
396
+ \u{1F4A1} \u63D0\u793A\uFF1A\u8BF7\u63D0\u4F9B\u8D26\u53F7\u548C\u5BC6\u7801\uFF0C\u6211\u53EF\u4EE5\u5E2E\u4F60\u81EA\u52A8\u767B\u5F55`,login_redirect:d,needs_login:!0};if(r){t?.("waiting_login",{message:"\u6D4F\u89C8\u5668\u5DF2\u6253\u5F00\uFF0C\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55...",profile_path:Pl()});let g=Pp(c,o),y=s.login_wait_time||12e4;try{await c.waitForNavigation({timeout:y,waitUntil:"networkidle0"});}catch{}let x=await Ul(c,o),S=await g;return x.detected?(await n.close(),{success:!1,url:o,load_time:0,timestamp:Date.now(),summary:"\u26A0\uFE0F \u767B\u5F55\u672A\u5B8C\u6210\u6216\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5",login_redirect:x,needs_login:!0}):(Object.keys(S).length>0&&(oo(o,S),t?.("headers_saved",{headerCount:Object.keys(S).length})),await n.close(),{success:!0,url:o,load_time:0,timestamp:Date.now(),summary:`\u2705 \u767B\u5F55\u6210\u529F\uFF01\u540E\u7EED\u8BBF\u95EE ${o} \u5C06\u81EA\u52A8\u4FDD\u6301\u767B\u5F55\u72B6\u6001\uFF08\u5DF2\u4FDD\u5B58 ${Object.keys(S).length} \u4E2A\u8BA4\u8BC1 headers\uFF09\u3002`,login_redirect:{detected:!1,original_url:o},needs_login:!1,captured_headers:S})}t?.("collecting",{url:o});let p=await no(c,o,{wait_time:s.wait_time,collect_console:s.collect_console,collect_errors:s.collect_errors,collect_network:s.collect_network,collect_performance:s.collect_performance,take_screenshot:s.take_screenshot,network_filter:{xhr_only:s.network_xhr_only,url_pattern:s.network_url_pattern,status_filter:s.network_status_filter,include_body:s.network_include_body,body_max_length:s.network_body_max_length,max_results:s.network_max_results}});t?.("analyzing");let m=so({console_logs:p.console_logs,errors:p.errors,network_requests:p.network_requests,network_stats:p.network_stats,performance:p.performance});await n.close();let h={success:!0,url:o,load_time:p.load_time,timestamp:Date.now(),console_logs:p.console_logs,errors:p.errors,network_requests:p.network_requests,performance:p.performance,screenshot:p.screenshot,summary:m,login_redirect:d,needs_login:!1,used_saved_headers:u};return t?.("completed",{result:h}),h}catch(o){if(n)try{await n.close();}catch{}let a={success:false,error:String(o),url:s.url||"",load_time:0,timestamp:Date.now(),summary:`\u9519\u8BEF\uFF1A${o}`};return t?.("error",{error:a.error}),a}}var Pv,Av,Mv,Lv,Ov,Ap=K(()=>{to();Ml();Dl();Nl();Pv=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],Av=['input[type="password"]','form[action*="login"]','form[action*="signin"]','form[action*="auth"]','button[type="submit"]:has-text("\u767B\u5F55")','button[type="submit"]:has-text("Login")','button[type="submit"]:has-text("Sign in")'],Mv=['input[name="username"]','input[name="user"]','input[name="email"]','input[name="account"]','input[name="login"]','input[name="userId"]','input[name="loginId"]','input[id="username"]','input[id="user"]','input[id="email"]','input[id="account"]','input[id="login"]','input[type="email"]','input[type="text"][autocomplete="username"]','input[placeholder*="\u7528\u6237\u540D"]','input[placeholder*="\u8D26\u53F7"]','input[placeholder*="\u90AE\u7BB1"]','input[placeholder*="\u624B\u673A"]','input[placeholder*="Username"]','input[placeholder*="Email"]'],Lv=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],Ov=['button[type="submit"]','input[type="submit"]','button:has-text("\u767B\u5F55")','button:has-text("Login")','button:has-text("Sign in")','button:has-text("Log in")','button:has-text("\u786E\u5B9A")','button:has-text("Submit")','a:has-text("\u767B\u5F55")',".login-btn",".submit-btn","#login-btn","#submit"];});var Fl=K(()=>{_p();Ap();to();Ml();Dl();Nl();});var Mp=K(()=>{});var Lp=K(()=>{Mp();});var Op=K(()=>{});var Dp=K(()=>{Op();});var $p=K(()=>{kl();Sp();Fl();Lp();Dp();});async function Hv(s){let e={types:[],skipDirs:new Set(jv),skipPatterns:[],interestingDirs:new Set(Wv),descriptions:[]};try{let t=await he__default.readdir(s),n=new Set(t);for(let[r,i]of Object.entries(Gv))i.detectFiles.some(a=>{if(a.includes("*")){let l=a.replace("*","");return t.some(c=>c.endsWith(l)||c.startsWith(l.replace(".","")))}return n.has(a)})&&(e.types.push(r),e.descriptions.push(i.description),i.skipDirs.forEach(a=>e.skipDirs.add(a)),i.skipPatterns&&e.skipPatterns.push(...i.skipPatterns),i.interestingDirs.forEach(a=>e.interestingDirs.add(a)));}catch{}return e}function Bl(s,e){if(e.skipDirs.has(s))return true;for(let t of e.skipDirs)if(t.includes("*")){let n=t.replace("*","");if(s.endsWith(n)||s.startsWith(n.replace(".","")))return true}return false}function Jv(s,e){return e.interestingDirs.has(s)}async function Np(s,e,t){let{maxDepth:n,currentDepth:r,shallow:i,expandInteresting:o}=t;if(r>n)return [];try{let a=await he__default.readdir(s,{withFileTypes:!0}),l=[],c=a.filter(d=>d.isDirectory()&&!d.name.startsWith(".")),u=a.filter(d=>d.isFile()&&!d.name.startsWith("."));for(let d of c){let p=te__default.join(s,d.name);if(Bl(d.name,e)){let m=0;try{m=(await he__default.readdir(p)).length;}catch{}l.push({name:d.name,path:p,isDirectory:!0,skipped:!0,skipReason:zv(d.name,e),itemCount:m});}else {let m=Jv(d.name,e),g=(i?!1:o&&m||r<n)?await Np(p,e,{maxDepth:n,currentDepth:r+1,shallow:i,expandInteresting:o}):void 0;l.push({name:d.name,path:p,isDirectory:!0,isInteresting:m,children:g});}}if(!i||r===0)for(let d of u){let p=te__default.join(s,d.name),m=!1;for(let h of e.skipPatterns)if(h.test(d.name)){m=!0;break}if(!m)try{let h=await he__default.stat(p);l.push({name:d.name,path:p,isDirectory:!1,size:h.size});}catch{l.push({name:d.name,path:p,isDirectory:!1});}}return l}catch{return []}}function zv(s,e){return ["node_modules","vendor","Pods","deps",".dart_tool","packages"].includes(s)?"dependencies":["dist","build","out","target",".next",".nuxt","bin","obj"].includes(s)?"build output":s.includes("cache")||s.startsWith(".")&&s.includes("_")?"cache":["coverage","htmlcov",".nyc_output"].includes(s)?"coverage":["venv",".venv","env","virtualenv"].includes(s)?"virtual env":"auto-skipped"}function qv(s){return s<1024?`${s}B`:s<1024*1024?`${(s/1024).toFixed(1)}KB`:`${(s/(1024*1024)).toFixed(1)}MB`}function jl(s,e=""){let t=[];for(let n=0;n<s.length;n++){let r=s[n],i=n===s.length-1,o=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";if(r.isDirectory)if(r.skipped){let l=r.itemCount!==void 0?` (${r.itemCount} items)`:"";t.push(`${e}${o}[~] ${r.name}/ [>>] ${r.skipReason}${l}`);}else r.isInteresting?(t.push(`${e}${o}[+] ${r.name}/ [*]`),r.children&&r.children.length>0&&t.push(...jl(r.children,e+a))):(t.push(`${e}${o}[~] ${r.name}/`),r.children&&r.children.length>0&&t.push(...jl(r.children,e+a)));else {let l=r.size!==void 0?` (${qv(r.size)})`:"";t.push(`${e}${o}[] ${r.name}${l}`);}}return t}async function Kv(s,e,t){try{let n=await he__default.readdir(s,{withFileTypes:!0}),r=[],i=[];for(let c of n)c.name.startsWith(".")||(c.isDirectory()?Bl(c.name,t)||r.push(c.name):Vv(c.name)&&i.push(c.name));let o=[],a=r.find(c=>["src","lib","app","core","packages"].includes(c));if(a){let c=te__default.join(s,a);try{let u=await he__default.readdir(c,{withFileTypes:!0});for(let d of u)d.isDirectory()&&!d.name.startsWith(".")&&!Bl(d.name,t)&&o.push(d.name);}catch{}}let l=[];return l.push(`\u{1F4C1} Path: ${e}`),l.push(""),t.descriptions.length>0&&l.push(`\u{1F4E6} Project Type: ${t.descriptions.join(", ")}`),r.length>0&&l.push(`\u{1F4C2} Root Directories: ${r.sort().join(", ")}`),o.length>0&&l.push(`\u{1F527} Modules: ${o.sort().join(", ")}`),i.length>0&&l.push(`\u2699\uFE0F Config Files: ${i.slice(0,5).join(", ")}`),l.push(""),l.push('\u{1F4A1} Tip: Use search(pattern="keyword", path="src/", recursive=true) to locate code'),l.join(`
397
+ `)}catch(n){return JSON.stringify({error:n.message})}}function Vv(s){return new Set(["package.json","tsconfig.json","pom.xml","build.gradle","Cargo.toml","go.mod","requirements.txt","pyproject.toml","Makefile","Dockerfile","docker-compose.yml",".env.example","README.md"]).has(s)}function Yv(s){let e=0,t=[];for(let n=0;n<s.length&&n<ms.maxLines;n++){let r=s[n];if(e+r.length>ms.maxChars){t.push(ms.truncationMessage);break}t.push(r),e+=r.length+1;}return s.length>ms.maxLines&&!t.includes(ms.truncationMessage)&&t.push(ms.truncationMessage),t}function Up(){let s=process.env[Xv];return s&&s.trim()?te__default.resolve(s):process.cwd()}function Zv(s){let e=Up();return !s||s.trim()===""||s.trim()==="."?e:te__default.isAbsolute(s)?te__default.resolve(s):te__default.resolve(e,s)}function Qv(s){let e=Up(),t=te__default.relative(e,s);return t&&!t.startsWith("..")&&!te__default.isAbsolute(t)?t:s}function Bp(s){let e=0;for(let t of s)t.skipped&&e++,t.children&&(e+=Bp(t.children));return e}function jp(s){let e=0;for(let t of s)t.isInteresting&&e++,t.children&&(e+=jp(t.children));return e}var jv,Gv,Wv,ms,Xv,Fp,Gp=K(()=>{jv=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),Gv={nodejs:{detectFiles:["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml"],skipDirs:["node_modules","dist","build","out",".next",".nuxt",".output",".cache",".parcel-cache",".turbo","coverage",".nyc_output","storybook-static"],skipPatterns:[/\.min\.js$/,/\.bundle\.js$/,/\.chunk\.js$/],interestingDirs:["src","lib","app","pages","components","hooks","utils","services","api","types","styles","public","assets","test","tests","__tests__","spec"],description:"Node.js/JavaScript/TypeScript \u9879\u76EE"},python:{detectFiles:["setup.py","pyproject.toml","requirements.txt","Pipfile","poetry.lock"],skipDirs:["__pycache__",".pytest_cache",".mypy_cache",".tox",".nox","venv",".venv","env",".env","virtualenv",".eggs","*.egg-info","dist","build",".ipynb_checkpoints","htmlcov"],skipPatterns:[/\.pyc$/,/\.pyo$/],interestingDirs:["src","lib","app","apps","core","api","models","views","services","utils","tests","test","scripts","notebooks","docs"],description:"Python \u9879\u76EE"},java:{detectFiles:["pom.xml","build.gradle","build.gradle.kts","settings.gradle"],skipDirs:["target","build","out",".gradle","bin",".mvn","gradle"],skipPatterns:[/\.class$/],interestingDirs:["src","main","java","kotlin","resources","test","webapp","templates"],description:"Java/Kotlin/Gradle/Maven \u9879\u76EE"},golang:{detectFiles:["go.mod","go.sum"],skipDirs:["vendor","bin"],interestingDirs:["cmd","pkg","internal","api","web","configs","scripts","test","tests","docs"],description:"Go \u9879\u76EE"},rust:{detectFiles:["Cargo.toml","Cargo.lock"],skipDirs:["target"],interestingDirs:["src","benches","examples","tests"],description:"Rust \u9879\u76EE"},cpp:{detectFiles:["CMakeLists.txt","Makefile","meson.build","configure.ac"],skipDirs:["build","cmake-build-debug","cmake-build-release","bin","obj","out",".ccache"],skipPatterns:[/\.o$/,/\.obj$/,/\.a$/,/\.so$/,/\.dll$/,/\.exe$/],interestingDirs:["src","include","lib","tests","test","examples","docs"],description:"C/C++ \u9879\u76EE"},ruby:{detectFiles:["Gemfile","Gemfile.lock","Rakefile",".ruby-version"],skipDirs:["vendor/bundle",".bundle","tmp","log","coverage","node_modules"],interestingDirs:["app","lib","config","db","spec","test","public","views"],description:"Ruby/Rails \u9879\u76EE"},php:{detectFiles:["composer.json","composer.lock","artisan"],skipDirs:["vendor","node_modules","storage/framework","bootstrap/cache"],interestingDirs:["app","src","config","database","resources","routes","tests","public"],description:"PHP/Laravel/Composer \u9879\u76EE"},dotnet:{detectFiles:["*.csproj","*.fsproj","*.sln","packages.config"],skipDirs:["bin","obj","packages",".nuget","TestResults"],skipPatterns:[/\.dll$/,/\.exe$/,/\.pdb$/],interestingDirs:["src","lib","tests","Controllers","Models","Views","Services","Data"],description:".NET/C#/F# \u9879\u76EE"},swift:{detectFiles:["Package.swift","*.xcodeproj","*.xcworkspace","Podfile"],skipDirs:["Pods","DerivedData","build",".build","Carthage","xcuserdata"],interestingDirs:["Sources","Tests","Resources","Assets"],description:"Swift/iOS/macOS \u9879\u76EE"},flutter:{detectFiles:["pubspec.yaml","pubspec.lock"],skipDirs:[".dart_tool","build",".pub-cache","android/build","ios/Pods","web/build"],interestingDirs:["lib","test","assets","android","ios","web","macos","linux","windows"],description:"Flutter/Dart \u9879\u76EE"},elixir:{detectFiles:["mix.exs","mix.lock"],skipDirs:["_build","deps",".elixir_ls","cover"],interestingDirs:["lib","test","config","priv","assets"],description:"Elixir/Phoenix \u9879\u76EE"}},Wv=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);ms={maxLines:500,maxChars:15e3,truncationMessage:`
398
+ ... [\u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528\u66F4\u5177\u4F53\u7684 directory \u53C2\u6570\u67E5\u770B\u5B50\u76EE\u5F55]`};Xv="NEOX_WORKDIR";Fp={name:"smart_tree",description:`\u667A\u80FD\u76EE\u5F55\u626B\u63CF\u5DE5\u5177 - \u81EA\u52A8\u8BC6\u522B\u9879\u76EE\u7C7B\u578B\u5E76\u4F18\u5316\u663E\u793A\u3002
399
+
400
+ \u3010\u5206\u5C42\u641C\u7D22\u7B56\u7565\u3011
401
+ \u8FD9\u662F Layer 1: \u7ED3\u6784\u611F\u77E5\u5DE5\u5177\u3002\u914D\u5408 search (Layer 2: \u8BED\u4E49\u5B9A\u4F4D) \u4F7F\u7528\u6548\u679C\u6700\u4F73\u3002
402
+
403
+ \u63A8\u8350\u5DE5\u4F5C\u6D41:
404
+ 1. smart_tree(mode="structure") \u2192 \u83B7\u53D6\u9879\u76EE\u7ED3\u6784\u6982\u89C8 (\u6781\u5C0F\u8F93\u51FA\uFF0C~50 tokens)
405
+ 2. search(pattern="\u5173\u952E\u8BCD", path="src/", recursive=true) \u2192 \u5B9A\u4F4D\u4EE3\u7801\u4F4D\u7F6E (\u5E26\u6A21\u5757\u4FE1\u606F)
406
+ 3. readfile(path, start_line, num_lines) \u2192 \u53EA\u8BFB\u5173\u952E\u6587\u4EF6\u7684\u5173\u952E\u90E8\u5206
407
+
408
+ \u626B\u63CF\u6A21\u5F0F:
409
+ - structure: \u{1F525} \u63A8\u8350\uFF01\u8FD4\u56DE\u7CBE\u7B80 JSON \u7ED3\u6784 (root_dirs + modules)\uFF0C\u9002\u5408\u5FEB\u901F\u4E86\u89E3\u9879\u76EE
410
+ - shallow: \u53EA\u663E\u793A\u7B2C\u4E00\u7EA7\u76EE\u5F55\uFF0C\u9002\u5408\u521D\u6B65\u4E86\u89E3
411
+ - normal: \u667A\u80FD\u5C55\u5F00\u6E90\u7801\u76EE\u5F55\uFF0C\u8DF3\u8FC7\u4F9D\u8D56/\u6784\u5EFA
412
+ - deep: \u5B8C\u5168\u5C55\u5F00\u6240\u6709\u76EE\u5F55
413
+
414
+ \u793A\u4F8B:
415
+ {"mode": "structure"} \u2192 {"root_dirs": ["src","config","test"], "modules": ["auth","health","order"]}`,parameters:{type:"object",properties:{directory:{type:"string",description:"\u76EE\u5F55\u8DEF\u5F84 (\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},mode:{type:"string",enum:["structure","shallow","normal","deep"],description:"\u626B\u63CF\u6A21\u5F0F: structure(\u7ED3\u6784JSON), shallow(\u6D45\u5C42), normal(\u6B63\u5E38), deep(\u6DF1\u5C42)\u3002\u9ED8\u8BA4: structure"},max_depth:{type:"number",description:"\u6700\u5927\u6DF1\u5EA6 (structure/shallow \u56FA\u5B9A\u4E3A 1-2\uFF0C\u5176\u4ED6\u6A21\u5F0F\u9ED8\u8BA4 3)"}}},async function({directory:s=".",mode:e="structure",max_depth:t}){try{let n=Zv(s),r=Qv(n);if(!(await he__default.stat(n)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${r}`;let o=await Hv(n);if(e==="structure")return await Kv(n,r,o);let a=e==="shallow",l=t??(a?1:e==="deep"?5:3),u=await Np(n,o,{maxDepth:l,currentDepth:0,shallow:a,expandInteresting:e!=="shallow"}),d=[];d.push(`[~] ${r}/`),d.push(""),o.types.length>0?d.push(`[?] \u68C0\u6D4B\u5230\u9879\u76EE\u7C7B\u578B: ${o.descriptions.join(", ")}`):d.push("[?] \u672A\u68C0\u6D4B\u5230\u7279\u5B9A\u9879\u76EE\u7C7B\u578B"),d.push(`\u{1F4CA} \u626B\u63CF\u6A21\u5F0F: ${e} | \u6700\u5927\u6DF1\u5EA6: ${l}`),d.push(""),d.push("\u56FE\u4F8B: [+][*] \u91CD\u70B9\u76EE\u5F55 | [~][>>] \u5DF2\u8DF3\u8FC7 | [~] \u666E\u901A\u76EE\u5F55"),d.push("\u2500".repeat(50)),d.push(""),u.length===0?d.push("(\u7A7A\u76EE\u5F55)"):d.push(...jl(u));let p=Bp(u),m=jp(u);return d.push(""),d.push("\u2500".repeat(50)),d.push(`\u7EDF\u8BA1: ${m} \u4E2A\u91CD\u70B9\u76EE\u5F55 | ${p} \u4E2A\u5DF2\u8DF3\u8FC7\u76EE\u5F55`),a&&(d.push(""),d.push('\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 mode="normal" \u6DF1\u5165\u63A2\u7D22\u611F\u5174\u8DA3\u7684\u76EE\u5F55')),Yv(d).join(`
416
+ `)}catch(n){return n.code==="ENOENT"?`[x] \u76EE\u5F55\u4E0D\u5B58\u5728: ${s}`:`[x] \u626B\u63CF\u5931\u8D25: ${n.message}`}}};});function ex(){let s=process.platform;if(s==="darwin")return te__default.join(ti__default.homedir(),"Library","Application Support","Neox");if(s==="win32")return te__default.join(process.env.APPDATA||te__default.join(ti__default.homedir(),"AppData","Roaming"),"Neox");{let e=process.env.XDG_CONFIG_HOME||te__default.join(ti__default.homedir(),".config");return te__default.join(e,"neox")}}function Xt(){try{let s=an__default.readFileSync(lt,"utf-8");return JSON.parse(s)}catch{return {}}}function ct(s){try{an__default.existsSync(co)||an__default.mkdirSync(co,{recursive:!0}),an__default.writeFileSync(lt,JSON.stringify(s,null,2),"utf-8");}catch(e){let t=e;throw t.code==="EACCES"||t.code==="EPERM"?(console.error(`
417
+ \u274C Permission denied: Cannot write to config file`),console.error(` Location: ${lt}`),console.error(`
418
+ Please check directory permissions or try:`),console.error(` sudo chown -R $USER "${co}"
419
+ `)):console.error("[Config] Failed to save configuration:",t.message),e}}var co,lt,Sn=K(()=>{co=ex(),lt=te__default.join(co,"config.json");});var Wl,Wp,Hp=K(()=>{Sn();Wl={name:"web_search",description:`Search the web using Google (via Serper.dev API).
420
+
421
+ Use cases:
422
+ - Search for documentation: {"query": "React hooks useEffect tutorial"}
423
+ - Search for error solutions: {"query": "TypeError: Cannot read property of undefined JavaScript"}
424
+ - Search for latest information: {"query": "Node.js 20 new features"}
425
+ - Search for code examples: {"query": "Python async await example"}
426
+
427
+ Returns top search results with title, URL, and description.`,parameters:{type:"object",properties:{query:{type:"string",description:"Search query string"},max_results:{type:"number",description:"Maximum number of results to return (default: 10, max: 20)"}},required:["query"]},async function({query:s,max_results:e=10}){let t=Date.now();try{if(!s||s.trim().length===0)return "\u2717 \u641C\u7D22\u5931\u8D25: \u8BF7\u63D0\u4F9B\u641C\u7D22\u5173\u952E\u8BCD";let r=Xt().webSearch?.apiKey;if(!r)return `\u2717 \u641C\u7D22\u5931\u8D25: \u672A\u914D\u7F6E Serper.dev API Key
428
+
429
+ \u8BF7\u5728\u8BBE\u7F6E\u9875\u9762 \u2192 Agent \u2192 Web Search \u4E2D\u914D\u7F6E API Key
430
+ \u6CE8\u518C\u5730\u5740: https://serper.dev (\u514D\u8D39 2500 \u6B21\u641C\u7D22)`;let i=await fetch("https://google.serper.dev/search",{method:"POST",headers:{"X-API-KEY":r,"Content-Type":"application/json"},body:JSON.stringify({q:s.trim(),num:Math.min(Math.max(1,e),20)})});if(!i.ok)return i.status===401?`\u2717 \u641C\u7D22\u5931\u8D25: API Key \u65E0\u6548
431
+ \u8BF7\u68C0\u67E5 Serper.dev API Key \u662F\u5426\u6B63\u786E`:i.status===429?`\u2717 \u641C\u7D22\u5931\u8D25: API \u914D\u989D\u5DF2\u7528\u5B8C
432
+ \u8BF7\u8BBF\u95EE https://serper.dev \u67E5\u770B\u4F7F\u7528\u60C5\u51B5`:`\u2717 \u641C\u7D22\u5931\u8D25: HTTP ${i.status} ${i.statusText}`;let o=await i.json(),a=Date.now()-t,c=(o.organic||[]).map(d=>({title:d.title||"Untitled",url:d.link||"",description:d.snippet||"",hostname:(()=>{try{return new URL(d.link||"https://unknown").hostname}catch{return "unknown"}})()}));if(c.length===0)return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
433
+ [?] Web Search
434
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
435
+
436
+ \u25B8 \u641C\u7D22\u8BCD: "${s}"
437
+ \u25B8 \u8017\u65F6: ${a}ms
438
+
439
+ \u2717 \u672A\u627E\u5230\u76F8\u5173\u7ED3\u679C
440
+
441
+ \u5EFA\u8BAE:
442
+ - \u5C1D\u8BD5\u4E0D\u540C\u7684\u5173\u952E\u8BCD
443
+ - \u4F7F\u7528\u66F4\u901A\u7528\u7684\u641C\u7D22\u8BCD
444
+ - \u68C0\u67E5\u62FC\u5199\u662F\u5426\u6B63\u786E
445
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`;let u=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
446
+ [?] Web Search
447
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
448
+
449
+ \u25B8 \u641C\u7D22\u8BCD: "${s}"
450
+ \u25B8 \u7ED3\u679C\u6570: ${c.length}
451
+ \u25B8 \u8017\u65F6: ${a}ms
452
+
453
+ `;return c.forEach((d,p)=>{u+=`\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
454
+ [] ${p+1}. ${d.title}
455
+ \u{1F517} ${d.url}
456
+ [.] ${d.description||"(\u65E0\u63CF\u8FF0)"}
457
+ [@] ${d.hostname}
458
+ `;}),u+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",u}catch(n){let r=Date.now()-t;return n.message?.includes("ENOTFOUND")||n.message?.includes("network")?`\u2717 \u641C\u7D22\u5931\u8D25: \u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF
459
+ \u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5`:n.message?.includes("timeout")?`\u2717 \u641C\u7D22\u5931\u8D25: \u8BF7\u6C42\u8D85\u65F6 (${r}ms)
460
+ \u8BF7\u7A0D\u540E\u91CD\u8BD5`:`\u2717 \u641C\u7D22\u5931\u8D25: ${n.message||"\u672A\u77E5\u9519\u8BEF"}`}}},Wp={name:"web_fetch",description:`Fetch content from a URL and extract readable text.
461
+
462
+ Use cases:
463
+ - Read documentation pages: {"url": "https://docs.example.com/api"}
464
+ - Extract article content: {"url": "https://blog.example.com/post"}
465
+ - Get API documentation: {"url": "https://api.example.com/docs"}
466
+
467
+ Note: Works best with text-based pages. May not work well with JavaScript-heavy sites.`,parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch content from"},max_length:{type:"number",description:"Maximum content length to return (default: 8000 chars)"},extract_links:{type:"boolean",description:"Whether to extract and list links from the page (default: false)"}},required:["url"]},async function({url:s,max_length:e=8e3,extract_links:t=false}){let n=Date.now();try{let r;try{r=new URL(s);}catch{return `\u2717 \u83B7\u53D6\u5931\u8D25: \u65E0\u6548\u7684 URL: ${s}`}let i=["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0"],o=i[Math.floor(Math.random()*i.length)],a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(s,{signal:a.signal,headers:{"User-Agent":o,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.5,zh-CN;q=0.3","Accept-Encoding":"gzip, deflate",Connection:"keep-alive","Upgrade-Insecure-Requests":"1"}});if(clearTimeout(l),!c.ok)return `\u2717 \u83B7\u53D6\u5931\u8D25: HTTP ${c.status} ${c.statusText}`;let u=c.headers.get("content-type")||"",d=await c.text(),p=Date.now()-n,m=d.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<noscript[^>]*>[\s\S]*?<\/noscript>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<\/(p|div|h[1-6]|li|tr|br|hr)[^>]*>/gi,`
468
+ `).replace(/<(br|hr)[^>]*\/?>/gi,`
469
+ `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&[a-z]+;/gi,"").replace(/[ \t]+/g," ").replace(/\n[ \t]+/g,`
470
+ `).replace(/[ \t]+\n/g,`
471
+ `).replace(/\n{3,}/g,`
472
+
473
+ `).trim(),h=[];if(t){let S=/<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi,T;for(;(T=S.exec(d))!==null;){let w=T[1],L=T[2].trim();if(w&&L&&!w.startsWith("#")&&!w.startsWith("javascript:"))try{let B=new URL(w,s).href;h.push({text:L,href:B});}catch{}}h=h.filter((w,L,B)=>L===B.findIndex(I=>I.href===w.href)).slice(0,20);}let g=Math.min(Math.max(1e3,e),5e4),y=m.length>g;y&&(m=m.slice(0,g)+`
474
+
475
+ ... (\u5185\u5BB9\u5DF2\u622A\u65AD)`);let x=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
476
+ [@] Web Fetch
477
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
478
+
479
+ \u25B8 URL: ${s}
480
+ \u25B8 \u57DF\u540D: ${r.hostname}
481
+ \u25B8 \u7C7B\u578B: ${u.split(";")[0]||"unknown"}
482
+ \u25B8 \u5185\u5BB9\u957F\u5EA6: ${m.length} \u5B57\u7B26${y?" (\u5DF2\u622A\u65AD)":""}
483
+ \u25B8 \u8017\u65F6: ${p}ms
484
+
485
+ \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
486
+ [] \u5185\u5BB9:
487
+ \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
488
+ ${m}
489
+ `;return t&&h.length>0&&(x+=`
490
+ \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
491
+ \u{1F517} \u94FE\u63A5 (${h.length}):
492
+ \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
493
+ `,h.forEach((S,T)=>{x+=`${T+1}. ${S.text}
494
+ ${S.href}
495
+ `;})),x+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",x}catch(r){let i=Date.now()-n;return r.name==="AbortError"?`\u2717 \u83B7\u53D6\u5931\u8D25: \u8BF7\u6C42\u8D85\u65F6 (${i}ms)
496
+ URL: ${s}`:r.message?.includes("ENOTFOUND")?`\u2717 \u83B7\u53D6\u5931\u8D25: \u65E0\u6CD5\u89E3\u6790\u57DF\u540D
497
+ URL: ${s}`:r.message?.includes("ECONNREFUSED")?`\u2717 \u83B7\u53D6\u5931\u8D25: \u8FDE\u63A5\u88AB\u62D2\u7EDD
498
+ URL: ${s}`:`\u2717 \u83B7\u53D6\u5931\u8D25: ${r.message||"\u672A\u77E5\u9519\u8BEF"}
499
+ URL: ${s}`}}};});function Jp(s){return {...Qi,async function(e){try{f.debug("BROWSER","Starting browser debug",{url:e.url});let t=await ao(e,s,(r,i)=>{f.debug("BROWSER",`Status: ${r}`,i);});f.debug("BROWSER","Browser debug completed",{success:t.success});let n={success:t.success,url:t.url,summary:t.summary,stats:{console_logs:t.console_logs?.length||0,errors:t.errors?.length||0,network_requests:t.network_requests?.length||0,load_time_ms:t.load_time},console_logs:t.console_logs?.slice(0,10).map(r=>({type:r.type,message:r.message})),errors:t.errors?.slice(0,5).map(r=>({type:r.type,message:r.message,file:r.file,line:r.line}))};return t.screenshot&&(n.screenshot={format:"base64",data:t.screenshot,note:"\u9875\u9762\u622A\u56FE\uFF08base64 \u7F16\u7801\uFF09"}),JSON.stringify(n,null,2)}catch(t){return f.error("BROWSER","Browser debug failed",{error:t.message}),JSON.stringify({success:false,error:t.message,url:e.url||"",load_time:0,timestamp:Date.now(),summary:`\u9519\u8BEF\uFF1A${t.message}`},null,2)}}}}var zp=K(()=>{Fl();le();});var qp=K(()=>{});var Er,Hl=K(()=>{Er=class extends EventEmitter{socket=null;sequenceNumber=1;pendingRequests=new Map;buffer="";connected=false;DEFAULT_TIMEOUT=3e4;async connect(e,t,n=1e4){return new Promise((r,i)=>{this.socket=new Kp.Socket;let o=setTimeout(()=>{this.socket?.destroy(),i(new Error(`Connection timeout after ${n}ms`));},n);this.socket.connect(t,e,()=>{clearTimeout(o),this.connected=true,this.emit("connected"),r();}),this.socket.on("data",a=>{this.handleData(a);}),this.socket.on("error",a=>{clearTimeout(o),this.emit("error",a),this.connected||i(a);}),this.socket.on("close",()=>{this.connected=false,this.emit("disconnected"),this.pendingRequests.forEach(({reject:a,timeout:l})=>{clearTimeout(l),a(new Error("Connection closed"));}),this.pendingRequests.clear();});})}disconnect(){this.socket&&(this.socket.end(),this.socket=null),this.connected=false;}isConnected(){return this.connected}async sendRequest(e,t,n=this.DEFAULT_TIMEOUT){if(!this.connected||!this.socket)throw new Error("Not connected to debug server");let r=this.sequenceNumber++,i={seq:r,type:"request",command:e,arguments:t};return new Promise((o,a)=>{let l=setTimeout(()=>{this.pendingRequests.delete(r),a(new Error(`Request timeout: ${e} (${n}ms)`));},n);this.pendingRequests.set(r,{resolve:o,reject:a,timeout:l}),this.send(i);})}send(e){let t=JSON.stringify(e),r=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
500
+ \r
501
+ `,i=Buffer.concat([Buffer.from(r,"utf8"),Buffer.from(t,"utf8")]);this.socket?.write(i);}handleData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.match(/Content-Length: (\d+)\r\n\r\n/);if(!t)break;let n=parseInt(t[1],10),r=t[0].length,i=t.index+r,o=i+n;if(this.buffer.length<o)break;let a=this.buffer.substring(i,o);this.buffer=this.buffer.substring(o);try{let l=JSON.parse(a);this.handleMessage(l);}catch(l){console.error("Failed to parse DAP message:",l);}}}handleMessage(e){if(e.type==="response"){let t=e,n=this.pendingRequests.get(t.request_seq);n&&(clearTimeout(n.timeout),this.pendingRequests.delete(t.request_seq),t.success?n.resolve(t):n.reject(new Error(t.message||"Request failed")));}else if(e.type==="event"){let t=e;this.emit("event",t),this.emit(`event:${t.event}`,t.body);}}async initialize(e){return await this.sendRequest("initialize",e)}async launch(e){return await this.sendRequest("launch",e)}async attach(e){return await this.sendRequest("attach",e)}async setBreakpoints(e){return await this.sendRequest("setBreakpoints",e)}async configurationDone(){return await this.sendRequest("configurationDone")}async continue(e){return await this.sendRequest("continue",e)}async next(e){return await this.sendRequest("next",e)}async stepIn(e){return await this.sendRequest("stepIn",e)}async stepOut(e){return await this.sendRequest("stepOut",e)}async pause(e){return await this.sendRequest("pause",{threadId:e})}async stackTrace(e){return await this.sendRequest("stackTrace",e)}async scopes(e){return await this.sendRequest("scopes",e)}async variables(e){return await this.sendRequest("variables",e)}async evaluate(e){return await this.sendRequest("evaluate",e)}async threads(){return await this.sendRequest("threads")}async exceptionInfo(e){return await this.sendRequest("exceptionInfo",e)}async disconnectRequest(e={}){return await this.sendRequest("disconnect",e)}async restart(){return await this.sendRequest("restart")}async terminate(){return await this.sendRequest("terminate")}};});var uo,zl=K(()=>{uo=class extends EventEmitter{process=null;port=0;isRunning=false;config;constructor(e){super(),this.config=e;}async start(){if(this.isRunning)throw new Error("Java Debug Server is already running");try{await he.access(this.config.jarPath);}catch{throw new Error(`Java Debug JAR not found at: ${this.config.jarPath}
502
+ Please download it from https://github.com/microsoft/java-debug/releases`)}let e=this.getJavaCommand();return new Promise((t,n)=>{let r=this.config.startupTimeout||1e4,i="",o=setTimeout(()=>{this.isRunning||(this.stop(),n(new Error(`Java Debug Server startup timeout (${r}ms)
503
+ Output so far:
504
+ ${i}`)));},r);this.process=spawn(e,["-jar",this.config.jarPath],{stdio:["pipe","pipe","pipe"]}),this.process.stdout?.on("data",a=>{let l=a.toString();i+=l,this.emit("stdout",l);let c=l.match(/Listening.*?address:\s*(\d+)/i);c&&(this.port=parseInt(c[1],10),this.isRunning=true,clearTimeout(o),this.emit("started",this.port),t(this.port));let u=l.match(/listening.*?port\s*(\d+)/i);u&&(this.port=parseInt(u[1],10),this.isRunning=true,clearTimeout(o),this.emit("started",this.port),t(this.port));}),this.process.stderr?.on("data",a=>{let l=a.toString();i+=l,this.emit("stderr",l),l.toLowerCase().includes("error")&&this.emit("error",new Error(l));}),this.process.on("exit",(a,l)=>{this.isRunning=false,this.emit("exit",{code:a,signal:l}),a!==0&&a!==null&&n(new Error(`Java Debug Server exited with code ${a}
505
+ ${i}`));}),this.process.on("error",a=>{clearTimeout(o),this.isRunning=false,this.emit("error",a),n(a);});})}stop(){this.process&&(this.process.kill(),this.process=null),this.isRunning=false,this.port=0,this.emit("stopped");}getPort(){return this.port}isServerRunning(){return this.isRunning}getJavaCommand(){return this.config.javaHome?te.join(this.config.javaHome,"bin","java"):process.env.JAVA_HOME?te.join(process.env.JAVA_HOME,"bin","java"):"java"}async initialize(){if(!this.process||!this.isRunning)throw new Error("Server is not running");let e={jsonrpc:"2.0",id:1,method:"initialize",params:{processId:process.pid,capabilities:{}}};this.sendLSPMessage(e);let t={jsonrpc:"2.0",method:"initialized",params:{}};this.sendLSPMessage(t);}sendLSPMessage(e){if(!this.process?.stdin)throw new Error("Server stdin is not available");let t=JSON.stringify(e),i=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
506
+ \r
507
+ `+t;this.process.stdin.write(i);}async startDAPServer(){return new Promise((e,t)=>{let n=setTimeout(()=>{t(new Error("Timeout waiting for DAP server to start"));},5e3),r=o=>{let a=o.match(/DAP.*?port\s*(\d+)/i);if(a){let l=parseInt(a[1],10);clearTimeout(n),this.removeListener("stdout",r),e(l);}};this.on("stdout",r);let i={jsonrpc:"2.0",id:2,method:"vscode.java.startDebugSession",params:{}};this.sendLSPMessage(i);})}};});var po,ql=K(()=>{Hl();zl();po=class extends EventEmitter{sessions=new Map;config;sessionIdCounter=0;constructor(e){super(),this.config=e,this.config.sessionTimeout&&setInterval(()=>{this.cleanupInactiveSessions();},6e4);}async launch(e){let t=this.generateSessionId();try{let n=new uo({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),r=await n.start(),i=new Er;await i.connect("localhost",r),await i.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await i.launch({mainClass:e.mainClass,projectName:e.projectPath.split("/").pop(),classPaths:e.classpath?[e.classpath]:[],args:e.args?.join(" "),vmArgs:e.vmArgs?.join(" "),cwd:e.cwd||e.projectPath,stopOnEntry:e.stopOnEntry}),await i.configurationDone();let o={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:o,client:i,server:n}),this.setupClientListeners(t,i),{sessionId:t,status:"running",message:`Debug session started for ${e.mainClass}`}}catch(n){throw new Error(`Failed to launch debug session: ${n.message}`)}}async attach(e){let t=this.generateSessionId();try{let n=new Er;await n.connect(e.hostName||"localhost",e.port),await n.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await n.attach({hostName:e.hostName||"localhost",port:e.port,timeout:e.timeout||5e3}),await n.configurationDone();let r={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:r,client:n,server:null}),this.setupClientListeners(t,n),{sessionId:t,status:"running",message:`Attached to Java process on ${e.hostName||"localhost"}:${e.port}`}}catch(n){throw new Error(`Failed to attach to process: ${n.message}`)}}async setBreakpoint(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let r=(await t.client.setBreakpoints({source:{path:e.filePath},breakpoints:[{line:e.line,condition:e.condition,hitCondition:e.hitCondition,logMessage:e.logMessage}]})).body.breakpoints[0];return t.session.breakpoints.has(e.filePath)||t.session.breakpoints.set(e.filePath,[]),t.session.breakpoints.get(e.filePath).push(r),{breakpointId:r.id||-1,verified:r.verified,line:r.line||e.line,message:r.verified?`Breakpoint set at line ${r.line}`:`Breakpoint not verified: ${r.message||"Unknown reason"}`}}catch(n){throw new Error(`Failed to set breakpoint: ${n.message}`)}}async continue(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=e.threadId||t.session.currentThreadId||1;return await t.client.continue({threadId:n}),t.session.status="running",await this.waitForStoppedOrTimeout(t,n)}catch(n){throw new Error(`Failed to continue execution: ${n.message}`)}}async stepOver(e){return await this.performStep(e,"stepOver")}async stepInto(e){return await this.performStep(e,"stepInto")}async stepOut(e){return await this.performStep(e,"stepOut")}async getVariables(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=t.session.currentThreadId||1,r=e.frameId||t.session.currentFrameId||0,i=await t.client.stackTrace({threadId:n,startFrame:0,levels:1});if(i.body.stackFrames.length===0)throw new Error("No stack frames available");let o=i.body.stackFrames[0],a=await t.client.scopes({frameId:o.id}),l=[];for(let c of a.body.scopes){if(e.filter==="local"&&c.name!=="Local"||e.filter==="arguments"&&c.name!=="Arguments")continue;let u=await t.client.variables({variablesReference:c.variablesReference});l.push(...u.body.variables);}return {variables:l.map(c=>({name:c.name,value:c.value,type:c.type||"unknown",variablesReference:c.variablesReference})),message:`Retrieved ${l.length} variables`}}catch(n){throw new Error(`Failed to get variables: ${n.message}`)}}async getStackTrace(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=e.threadId||t.session.currentThreadId||1,r=await t.client.stackTrace({threadId:n,startFrame:0,levels:50});return {stackFrames:r.body.stackFrames.map(i=>({id:i.id,name:i.name,source:{path:i.source?.path||"unknown",line:i.line},presentationHint:i.presentationHint})),totalFrames:r.body.totalFrames||r.body.stackFrames.length,message:`Retrieved ${r.body.stackFrames.length} stack frames`}}catch(n){throw new Error(`Failed to get stack trace: ${n.message}`)}}async evaluate(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=e.frameId||t.session.currentFrameId,r=await t.client.evaluate({expression:e.expression,frameId:n,context:e.context||"repl"});return {result:r.body.result,type:r.body.type||"unknown",variablesReference:r.body.variablesReference,message:`Expression evaluated: ${r.body.result}`}}catch(n){throw new Error(`Failed to evaluate expression: ${n.message}`)}}async stop(e){let t=this.getSessionContext(e.sessionId);try{return await t.client.disconnectRequest({terminateDebuggee:e.terminateDebuggee!==!1}),t.server&&t.server.stop(),this.sessions.delete(e.sessionId),{status:"terminated",message:"Debug session stopped"}}catch(n){return this.sessions.delete(e.sessionId),{status:"terminated",message:`Debug session stopped (with error: ${n.message})`}}}getSession(e){return this.sessions.get(e)?.session||null}listSessions(){return Array.from(this.sessions.values()).map(e=>e.session)}generateSessionId(){return `java-debug-${Date.now()}-${++this.sessionIdCounter}`}getSessionContext(e){let t=this.sessions.get(e);if(!t)throw new Error(`Debug session not found: ${e}`);return t}setupClientListeners(e,t){t.on("event",n=>{let r=this.sessions.get(e);if(r){switch(n.event){case "stopped":r.session.status="stopped",r.session.currentThreadId=n.body.threadId,r.session.stoppedReason=n.body.reason,r.session.lastActivity=Date.now();break;case "continued":r.session.status="running",r.session.lastActivity=Date.now();break;case "terminated":r.session.status="terminated",r.session.lastActivity=Date.now();break}this.emit("session:event",{sessionId:e,event:n.event,body:n.body});}});}async waitForStoppedOrTimeout(e,t,n=5e3){return new Promise(r=>{let i=setTimeout(()=>{e.client.off("event:stopped",o),e.client.off("event:terminated",o),r({status:"running",message:"Program is running"});},n),o=a=>{clearTimeout(i),e.client.off("event:stopped",o),e.client.off("event:terminated",o),a.reason?r({status:"stopped",stoppedReason:a.reason,location:a.source?{filePath:a.source.path,line:a.line,column:a.column||0}:void 0,message:`Program stopped: ${a.reason}`}):r({status:"terminated",message:"Program terminated"});};e.client.once("event:stopped",o),e.client.once("event:terminated",o);})}async performStep(e,t){let n=this.getSessionContext(e.sessionId);n.session.lastActivity=Date.now();try{let r=e.threadId||n.session.currentThreadId||1;switch(t){case "stepOver":await n.client.next({threadId:r});break;case "stepInto":await n.client.stepIn({threadId:r});break;case "stepOut":await n.client.stepOut({threadId:r});break}return new Promise((i,o)=>{let a=setTimeout(()=>{o(new Error("Step operation timeout"));},5e3);n.client.once("event:stopped",async l=>{clearTimeout(a);try{let u=(await n.client.stackTrace({threadId:r,startFrame:0,levels:1})).body.stackFrames[0];n.session.currentFrameId=u.id,i({status:"stopped",location:{filePath:u.source?.path||"unknown",line:u.line,method:u.name},message:`Stepped to ${u.name} at line ${u.line}`});}catch(c){o(c);}});})}catch(r){throw new Error(`Failed to perform step: ${r.message}`)}}cleanupInactiveSessions(){if(!this.config.sessionTimeout)return;let e=Date.now();for(let[t,n]of this.sessions.entries())e-n.session.lastActivity>this.config.sessionTimeout&&(console.log(`Cleaning up inactive session: ${t}`),this.stop({sessionId:t}).catch(i=>{console.error(`Failed to stop inactive session ${t}:`,i);}));}};});async function lx(){let s=process,e=[...s.resourcesPath?[te.join(s.resourcesPath,"java-debug","com.microsoft.java.debug.plugin.jar")]:[],te.join(process.cwd(),"resources","java-debug","com.microsoft.java.debug.plugin.jar"),te.join(ax,"..","..","..","resources","java-debug","com.microsoft.java.debug.plugin.jar")];for(let t of e)try{return await he.access(t),console.log(`\u2713 \u627E\u5230\u5185\u7F6E Java Debug JAR: ${t}`),t}catch{}return null}async function Yp(s){if(s)try{return await he.access(s),console.log(`\u2713 \u4F7F\u7528\u914D\u7F6E\u7684 Java Debug JAR: ${s}`),s}catch{console.warn(`\u26A0\uFE0F \u914D\u7F6E\u7684 JAR \u8DEF\u5F84\u65E0\u6548: ${s}`);}let e=await lx();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
508
+ \u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\u4E4B\u4E00\uFF1A
509
+ 1. \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D
510
+ 2. \u5728\u914D\u7F6E\u4E2D\u6307\u5B9A JAR \u8DEF\u5F84
511
+ 3. \u624B\u52A8\u4E0B\u8F7D\u5E76\u7F16\u8BD1\uFF1Ahttps://github.com/microsoft/java-debug`)}var ox,ax,Xp=K(()=>{ox=fileURLToPath(import.meta.url),ax=te.dirname(ox);});function Rt(){if(!Vl)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Vl}async function Yl(s){let e=await Yp(s);return Vl=new po({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3}),[cx,ux,dx,px,mx,hx,fx,gx,yx,bx,vx]}var Vl,cx,ux,dx,px,mx,hx,fx,gx,yx,bx,vx,Xl=K(()=>{ql();Xp();Vl=null;cx={name:"java_debug_launch",description:`Launch a Java application in debug mode.
512
+
513
+ Use this tool when you need to start debugging a Java program from the beginning.
514
+
515
+ Examples:
516
+ - Debug a Spring Boot application
517
+ - Debug a standalone Java program
518
+ - Debug with specific JVM arguments or classpath
519
+
520
+ After launching, you'll receive a sessionId that you must use for all subsequent debug operations.`,parameters:{type:"object",properties:{mainClass:{type:"string",description:'The fully qualified main class name (e.g., "com.example.Main", "org.springframework.boot.SpringApplication")'},projectPath:{type:"string",description:"The absolute path to the Java project root directory"},classpath:{type:"string",description:"Optional classpath for the application (JAR files, directories)"},args:{type:"array",items:{type:"string"},description:'Optional program arguments (e.g., ["--port", "8080", "--debug"])'},vmArgs:{type:"array",items:{type:"string"},description:'Optional JVM arguments (e.g., ["-Xmx512m", "-Dspring.profiles.active=dev"])'},stopOnEntry:{type:"boolean",description:"Stop at the entry point (main method). Default: false"},cwd:{type:"string",description:"Working directory for the application. Default: projectPath"}},required:["mainClass","projectPath"]},async function(s){try{let t=await Rt().launch(s);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},ux={name:"java_debug_attach",description:`Attach to a running Java process for debugging.
521
+
522
+ Use this tool when the Java application is already running with JDWP enabled.
523
+
524
+ To enable JDWP on a Java application, start it with:
525
+ java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 YourApp
526
+
527
+ Common JDWP ports:
528
+ - 5005 (default)
529
+ - 8000
530
+ - Custom port specified by the application
531
+
532
+ After attaching, you'll receive a sessionId for all subsequent debug operations.`,parameters:{type:"object",properties:{port:{type:"number",description:"The JDWP port number (usually 5005 or 8000)"},hostName:{type:"string",description:'The hostname to connect to. Default: "localhost"'},timeout:{type:"number",description:"Connection timeout in milliseconds. Default: 5000"}},required:["port"]},async function(s){try{let t=await Rt().attach(s);return JSON.stringify({success:!0,sessionId:t.sessionId,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},dx={name:"java_debug_set_breakpoint",description:`Set a breakpoint at a specific line in a Java source file.
533
+
534
+ The program will pause when execution reaches this line, allowing you to inspect variables and stack trace.
535
+
536
+ You can set:
537
+ - Simple breakpoints (just line number)
538
+ - Conditional breakpoints (only trigger when condition is true)
539
+ - Hit condition breakpoints (trigger after N hits)
540
+ - Logpoint breakpoints (log a message without pausing)
541
+
542
+ Examples:
543
+ - Set breakpoint at line 25: {"sessionId": "...", "filePath": "/path/Main.java", "line": 25}
544
+ - Conditional breakpoint: {"sessionId": "...", "filePath": "/path/Main.java", "line": 30, "condition": "count > 10"}`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID from java_debug_launch or java_debug_attach"},filePath:{type:"string",description:"The absolute path to the Java source file"},line:{type:"number",description:"The line number where to set the breakpoint (1-indexed)"},condition:{type:"string",description:'Optional condition expression (e.g., "count > 10", "user != null"). Breakpoint only triggers when condition is true.'},hitCondition:{type:"string",description:'Optional hit condition (e.g., ">5", "==3"). Breakpoint triggers after this many hits.'},logMessage:{type:"string",description:"Optional log message (logpoint). The breakpoint will log this message instead of pausing. Use {variable} for interpolation."}},required:["sessionId","filePath","line"]},async function(s){try{let t=await Rt().setBreakpoint(s);return JSON.stringify({success:!0,breakpointId:t.breakpointId,verified:t.verified,line:t.line,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},px={name:"java_debug_continue",description:`Continue program execution until the next breakpoint or program termination.
545
+
546
+ Use this tool to:
547
+ - Resume execution after hitting a breakpoint
548
+ - Run until the next breakpoint
549
+ - Let the program run to completion
550
+
551
+ The tool will return:
552
+ - "running" if the program continues without hitting a breakpoint (within timeout)
553
+ - "stopped" if a breakpoint is hit, with location details
554
+ - "terminated" if the program exits
555
+
556
+ When the program stops at a breakpoint, you can then use:
557
+ - java_debug_get_variables to inspect variables
558
+ - java_debug_get_stack_trace to see the call stack
559
+ - java_debug_evaluate to test expressions`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(s){try{let t=await Rt().continue(s);return JSON.stringify({success:!0,status:t.status,stoppedReason:t.stoppedReason,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},mx={name:"java_debug_step_over",description:`Execute the current line and move to the next line (step over).
560
+
561
+ If the current line contains a method call, the entire method executes without stopping inside it.
562
+
563
+ Use this when:
564
+ - You want to quickly move through code
565
+ - You don't need to debug inside method calls
566
+ - You're looking for a specific line of code
567
+
568
+ Example workflow:
569
+ 1. Set breakpoint at line 20
570
+ 2. Continue execution (stops at line 20)
571
+ 3. Step over to line 21, 22, 23... until you find the issue`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(s){try{let t=await Rt().stepOver(s);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},hx={name:"java_debug_step_into",description:`Execute the current line and step into method calls.
572
+
573
+ If the current line contains a method call, execution stops at the first line inside that method.
574
+
575
+ Use this when:
576
+ - You need to debug inside a method
577
+ - You want to trace execution flow into method calls
578
+ - You're investigating what a method does
579
+
580
+ Example:
581
+ Line 20: result = processData(input);
582
+
583
+ After step into, you'll be inside processData() at its first line.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(s){try{let t=await Rt().stepInto(s);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},fx={name:"java_debug_step_out",description:`Execute until the current method returns (step out).
584
+
585
+ Execution continues until the current method completes and returns to its caller.
586
+
587
+ Use this when:
588
+ - You're inside a method but don't need to debug it further
589
+ - You want to quickly return to the calling method
590
+ - You stepped into a method by mistake
591
+
592
+ Example:
593
+ You're at line 15 inside processData() method.
594
+ After step out, you'll be at the line that called processData().`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(s){try{let t=await Rt().stepOut(s);return JSON.stringify({success:!0,status:t.status,location:t.location,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},gx={name:"java_debug_get_variables",description:`Get the values of variables in the current scope.
595
+
596
+ Use this tool when the program is paused (at a breakpoint or after stepping) to inspect:
597
+ - Local variables
598
+ - Method arguments
599
+ - Instance variables
600
+ - Static variables
601
+
602
+ This is one of the most important debugging tools - it lets you see the actual values of variables at runtime.
603
+
604
+ You can filter variables by:
605
+ - "local" - only local variables
606
+ - "arguments" - only method parameters
607
+ - "all" - all variables (default)
608
+
609
+ Example use case:
610
+ 1. Program stops at breakpoint line 25
611
+ 2. Call java_debug_get_variables to see all variable values
612
+ 3. Analyze which variables have unexpected values
613
+ 4. Identify the bug!`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame (0 = topmost frame)"},filter:{type:"string",enum:["local","arguments","all"],description:'Filter variables by type. Default: "all"'}},required:["sessionId"]},async function(s){try{let t=await Rt().getVariables(s);return JSON.stringify({success:!0,variables:t.variables,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},yx={name:"java_debug_get_stack_trace",description:`Get the current call stack (stack trace).
614
+
615
+ The stack trace shows the sequence of method calls that led to the current point of execution.
616
+
617
+ Use this tool to:
618
+ - Understand the execution flow
619
+ - See which methods called which
620
+ - Find out how the program reached this point
621
+ - Identify recursion depth
622
+
623
+ The stack frames are ordered from most recent (top) to oldest (bottom):
624
+ Frame 0: Current method where execution is paused
625
+ Frame 1: The method that called Frame 0
626
+ Frame 2: The method that called Frame 1
627
+ ... and so on
628
+
629
+ Example output:
630
+ Frame 0: processUser() at UserService.java:42
631
+ Frame 1: handleRequest() at RequestHandler.java:28
632
+ Frame 2: main() at Main.java:15`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},threadId:{type:"number",description:"Optional thread ID. Default: main thread"}},required:["sessionId"]},async function(s){try{let t=await Rt().getStackTrace(s);return JSON.stringify({success:!0,stackFrames:t.stackFrames,totalFrames:t.totalFrames,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},bx={name:"java_debug_evaluate",description:`Evaluate a Java expression in the current debug context.
633
+
634
+ This is an extremely powerful tool that lets you:
635
+ - Check variable values with custom logic
636
+ - Test hypotheses about the bug
637
+ - Call methods to see what they return
638
+ - Compute complex expressions
639
+ - Test fixes before applying them
640
+
641
+ You can evaluate:
642
+ - Variable access: "user.getName()"
643
+ - Arithmetic: "count * 2 + offset"
644
+ - Comparisons: "user != null && user.isActive()"
645
+ - Method calls: "calculateTotal(items)"
646
+ - Ternary: "count > 0 ? count : DEFAULT_COUNT"
647
+
648
+ The expression is evaluated in the context of the current stack frame, so you have access to all visible variables.
649
+
650
+ Example debugging workflow:
651
+ 1. Program stops at line 25, variable 'user' is null
652
+ 2. Evaluate: "user != null" -> false
653
+ 3. Look at stack trace to see where user was initialized
654
+ 4. Evaluate: "getUserFromCache(userId)" to test if cache has the user
655
+ 5. Identify that cache lookup is failing`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},expression:{type:"string",description:'The Java expression to evaluate (e.g., "user.getName()", "count > 10", "items.size()")'},frameId:{type:"number",description:"Optional stack frame ID. Default: current frame"},context:{type:"string",enum:["watch","repl","hover"],description:'Evaluation context. Default: "repl"'}},required:["sessionId","expression"]},async function(s){try{let t=await Rt().evaluate(s);return JSON.stringify({success:!0,result:t.result,type:t.type,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}},vx={name:"java_debug_stop",description:`Stop the debug session and optionally terminate the debugged program.
656
+
657
+ Always call this tool when you're done debugging to clean up resources.
658
+
659
+ By default, this will terminate the debugged program. Set terminateDebuggee=false to disconnect without killing the program.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},terminateDebuggee:{type:"boolean",description:"Whether to terminate the debugged program. Default: true"}},required:["sessionId"]},async function(s){try{let t=await Rt().stop(s);return JSON.stringify({success:!0,status:t.status,message:t.message},null,2)}catch(e){return JSON.stringify({success:false,error:e.message},null,2)}}};});var Zp=K(()=>{qp();Hl();zl();ql();Xl();Xl();});var Zl,Ee,mo=K(()=>{le();Zl=class extends EventEmitter{processes=new Map;nextId=1;register(e){let t={pid:e.pid,command:e.command,cwd:e.cwd,startTime:new Date,status:"running",background:e.background,processRef:e.processRef};return this.processes.set(e.pid,t),f.debug("PROCESS_MGR",`Registered process PID=${e.pid}`,{command:e.command.substring(0,50),background:e.background}),this.emit("process:start",t),t}markCompleted(e,t){let n=this.processes.get(e);n&&(n.status=t===0?"completed":"failed",n.exitCode=t,n.endTime=new Date,f.debug("PROCESS_MGR",`Process completed PID=${e}`,{exitCode:t,duration:n.endTime.getTime()-n.startTime.getTime()}),this.emit("process:exit",n),setTimeout(()=>{this.processes.delete(e);},1e3));}unregister(e){this.processes.get(e)&&(this.processes.delete(e),f.debug("PROCESS_MGR",`Unregistered process PID=${e}`));}getRunning(){return Array.from(this.processes.values()).filter(e=>e.status==="running")}getBackgroundRunning(){return Array.from(this.processes.values()).filter(e=>e.status==="running"&&e.background)}getAll(){return Array.from(this.processes.values())}getRecent(e=10){return Array.from(this.processes.values()).sort((t,n)=>n.startTime.getTime()-t.startTime.getTime()).slice(0,e)}get(e){return this.processes.get(e)}isAlive(e){try{return process.kill(e,0),!0}catch{return false}}refreshStatus(){for(let[e,t]of this.processes.entries())t.status==="running"&&(this.isAlive(e)||(t.status="completed",t.endTime=new Date,f.debug("PROCESS_MGR",`Process ${e} is no longer alive, marked as completed`)));}kill(e,t="SIGTERM",n=false){let r=this.processes.get(e);try{return process.kill(e,t),f.info("PROCESS_MGR",`Sent ${t} to process PID=${e}`),n&&setTimeout(()=>{try{this.isAlive(e)&&(process.kill(e,"SIGKILL"),f.info("PROCESS_MGR",`Force killed process PID=${e}`));}catch{}},2e3),r&&(r.status="killed",r.endTime=new Date,this.emit("process:kill",r)),!0}catch(i){return i.code==="ESRCH"?(r&&(r.status="completed",r.endTime=new Date),f.debug("PROCESS_MGR",`Process ${e} not found (already exited)`),false):(f.error("PROCESS_MGR",`Failed to kill process ${e}`,{error:i.message}),false)}}killProcessGroup(e,t="SIGTERM"){try{process.kill(-e,t),f.info("PROCESS_MGR",`Sent ${t} to process group PID=${e}`);let n=this.processes.get(e);return n&&(n.status="killed",n.endTime=new Date,this.emit("process:kill",n)),!0}catch{return this.kill(e,t)}}killAll(e=false){let t=this.getRunning(),n=0,r=0;for(let i of t)(i.background?this.killProcessGroup(i.pid):this.kill(i.pid,"SIGTERM",e))?n++:r++;return f.info("PROCESS_MGR",`Killed ${n} processes, ${r} failed`),{killed:n,failed:r}}cleanup(e=20){let n=this.getAll().filter(i=>i.status!=="running");n.sort((i,o)=>{let a=i.endTime?.getTime()||0;return (o.endTime?.getTime()||0)-a});let r=0;for(let i=e;i<n.length;i++)this.processes.delete(n[i].pid),r++;return r}getStats(){let e=this.getAll();return {total:e.length,running:e.filter(t=>t.status==="running").length,backgroundRunning:e.filter(t=>t.status==="running"&&t.background).length,completed:e.filter(t=>t.status==="completed").length,failed:e.filter(t=>t.status==="failed").length,killed:e.filter(t=>t.status==="killed").length}}formatProcess(e){let t=e.endTime?e.endTime.getTime()-e.startTime.getTime():Date.now()-e.startTime.getTime(),n=this.formatDuration(t),r=this.getStatusIcon(e.status),i=e.background?" [BG]":"",o=e.command.length>40?e.command.substring(0,37)+"...":e.command;return `${r} PID ${e.pid}${i} | ${o} | ${n}`}getStatusIcon(e){switch(e){case "running":return "\u{1F7E2}";case "completed":return "\u2705";case "failed":return "\u274C";case "killed":return "\u{1F6D1}";default:return "\u26AA"}}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`:`${Math.floor(e/36e5)}h ${Math.floor(e%36e5/6e4)}m`}reset(){this.processes.clear(),f.debug("PROCESS_MGR","Process manager reset");}},Ee=new Zl;});var Am={};Fs(Am,{ALL_TOOLS:()=>Bx,analyzeCode:()=>Im,applyPatch:()=>gm,createDirectory:()=>mm,deleteFile:()=>hm,editFile:()=>um,executeShell:()=>ym,getTerminalExecutor:()=>lm,getTools:()=>go,gitBlame:()=>Sm,gitBranch:()=>Tm,gitBranchList:()=>_m,gitCommit:()=>wm,gitDiff:()=>xm,gitStatus:()=>vm,isSandboxEnabled:()=>fo,listDirectory:()=>pm,renameFile:()=>fm,runFormat:()=>Em,runLint:()=>Cm,runTests:()=>km,searchFiles:()=>dm,searchTool:()=>Rm,setSandboxEnabled:()=>ic,setTerminalExecutor:()=>Px,showTree:()=>bm,writeFile:()=>cm});function nc(){if(Zt)return Zt;let s={...process.env};if(process.platform==="win32")return Zt=s,Zt;try{let e=process.env.SHELL||"/bin/zsh",t=execaSync(e,["-ilc","env"],{encoding:"utf8",timeout:5e3,reject:!1});if(t.stdout){let n={};for(let r of t.stdout.split(`
660
+ `)){let i=r.indexOf("=");if(i>0){let o=r.substring(0,i),a=r.substring(i+1);n[o]=a;}}Zt={...n,...s,PATH:n.PATH||s.PATH||"",JAVA_HOME:n.JAVA_HOME||s.JAVA_HOME||"",MAVEN_HOME:n.MAVEN_HOME||s.MAVEN_HOME||"",M2_HOME:n.M2_HOME||s.M2_HOME||"",NODE_PATH:n.NODE_PATH||s.NODE_PATH||"",GOPATH:n.GOPATH||s.GOPATH||"",CARGO_HOME:n.CARGO_HOME||s.CARGO_HOME||"",RUSTUP_HOME:n.RUSTUP_HOME||s.RUSTUP_HOME||"",PYENV_ROOT:n.PYENV_ROOT||s.PYENV_ROOT||"",CONDA_PREFIX:n.CONDA_PREFIX||s.CONDA_PREFIX||""},process.env.CLI_DEBUG==="1"&&f.debug("SHELL","Loaded shell environment, PATH length:",{pathLength:Zt.PATH?.length});}else Zt=s;}catch(e){f.warn("SHELL","Failed to load shell environment",{error:e}),Zt=s;}return Zt}function Ix(){let s=process.env.NEOX_WORKER_ENTRY;if(s&&an__default.existsSync(s))return s;let e=process.argv[1];if(e&&e.endsWith(".js")&&an__default.existsSync(e))return e;let t=te__default.resolve(process.cwd(),"dist","cli","main.js");return an__default.existsSync(t)?t:null}async function Rx(s,e,t,n){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let r=Ix();return r?new Promise(i=>{let o=fork(r,[],{env:{...process.env,[Cx]:"execute_shell"},stdio:["ignore","ignore","ignore","ipc"]}),a=false,l=Number(process.env.NEOX_SHELL_WORKER_WATCHDOG_MS)||6e4,c=setTimeout(()=>{f.warn("SHELL_WORKER",`execute_shell running > ${l}ms`,{command:s});},l),u=()=>{clearTimeout(c),n&&n.removeEventListener("abort",p),o.removeAllListeners();},d=m=>{a||(a=true,u(),i(m));},p=()=>{o.connected&&o.send({type:"abort"}),setTimeout(()=>{if(!a){try{o.kill("SIGTERM");}catch{}d({success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
661
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${t}
662
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
663
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
664
+
665
+ \u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
666
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:false});}},500),setTimeout(()=>{if(!a)try{o.kill("SIGKILL");}catch{}},2e3);};n&&(n.aborted?p():n.addEventListener("abort",p,{once:true})),o.on("message",m=>{if(!(!m||typeof m!="object")){if(m.type==="background_exit"){typeof m.pid=="number"&&Ee.markCompleted(m.pid,m.exitCode??0);return}m.type==="result"&&d({success:!!m.success,output:String(m.output??""),background:!!m.background,pid:typeof m.pid=="number"?m.pid:void 0,exitCode:typeof m.exitCode=="number"?m.exitCode:void 0});}}),o.on("exit",m=>{a||(f.warn("SHELL_WORKER","Worker exited before result",{code:m,command:s}),d(null));}),o.send({type:"execute_shell",payload:{command:s,background:e,workspaceRoot:t}});}):(f.warn("SHELL_WORKER","Worker entry not found, fallback to inline execution"),null)}function Px(s){am=s,s?f.info("TOOLS","Terminal executor registered"):f.info("TOOLS","Terminal executor unregistered");}function lm(){return am}function em(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(){let s=process.env[kx];return s&&s.trim()?te__default.resolve(s):process.cwd()}function qe(s){let e=rt();if(!s||s.trim()===""||s.trim()===".")return e;let t=s.trim();if(t.startsWith("~/"))return te__default.resolve(te__default.join(ti__default.homedir(),t.slice(2)));let n=te__default.isAbsolute(t),r=process.platform!=="win32"&&t.startsWith(`Users${te__default.sep}`);if(n||r){let l=!n&&r?te__default.join(te__default.sep,t):t;return te__default.resolve(l)}t=t.replace(/^[.\\/]+/,"");let i=t.split(/[\\/]+/).filter(Boolean),o=te__default.basename(e);i.length>0&&i[0]===o&&i.shift();let a=te__default.join(e,...i);return te__default.resolve(a)}function Ue(s){let e=rt(),t=te__default.relative(e,s);return t&&!t.startsWith("..")&&!te__default.isAbsolute(t)?t:s}function Qt(s){let e=rt(),t=te__default.relative(e,s);return t===""?true:!t.startsWith("..")&&!te__default.isAbsolute(t)}function ho(s,e){return s.length<=e?{text:s,truncated:false}:{text:s.slice(0,e)+`
667
+ ... (truncated)`,truncated:true}}async function Xe(s,e,t,n){let r=Date.now();return new Promise((i,o)=>{let a=spawn(s,e,{cwd:t,env:{...nc(),TERM:"dumb"},stdio:["ignore","pipe","pipe"],detached:false}),l="",c="",u=false;a.stdout?.on("data",m=>{l+=m.toString();}),a.stderr?.on("data",m=>{c+=m.toString();});let d=null;n?.timeoutMs&&(d=setTimeout(()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);},n.timeoutMs));let p=()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);};n?.signal&&(n.signal.aborted?p():n.signal.addEventListener("abort",p,{once:true})),a.on("close",m=>{d&&clearTimeout(d),n?.signal&&n.signal.removeEventListener("abort",p),i({stdout:l,stderr:c,exitCode:u?-1:m??0,durationMs:Date.now()-r});}),a.on("error",m=>{d&&clearTimeout(d),n?.signal&&n.signal.removeEventListener("abort",p),i({stdout:l,stderr:c,exitCode:-1,durationMs:Date.now()-r});});})}async function Dn(s,e){try{let t=await Xe("git",["rev-parse","--show-toplevel"],s,{signal:e,timeoutMs:8e3});return t.exitCode!==0||!t.stdout.trim()?{error:"Not a git repository"}:{repoRoot:t.stdout.trim()}}catch(t){return {error:t?.message||"Not a git repository"}}}function Ax(s){let e=s.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}function Mx(s){let e=s.includes(`\r
668
+ `)?`\r
669
+ `:`
670
+ `,t=s.endsWith(e),n=s.split(/\r?\n/);return t&&n[n.length-1]===""&&n.pop(),{lines:n,lineEnding:e,hasTrailingNewline:t}}function rm(s){let e=s.trim(),t="";for(let n of e)switch(n){case "\u2010":case "\u2011":case "\u2012":case "\u2013":case "\u2014":case "\u2015":case "\u2212":t+="-";break;case "\u2018":case "\u2019":case "\u201A":case "\u201B":t+="'";break;case "\u201C":case "\u201D":case "\u201E":case "\u201F":t+='"';break;case "\xA0":case "\u2002":case "\u2003":case "\u2004":case "\u2005":case "\u2006":case "\u2007":case "\u2008":case "\u2009":case "\u200A":case "\u202F":case "\u205F":case "\u3000":t+=" ";break;default:t+=n;break}return t}function ec(s,e,t){if(e.length===0)return t;if(e.length>s.length)return null;let n=s.length-e.length;for(let r=t;r<=n;r+=1){let i=true;for(let o=0;o<e.length;o+=1)if(s[r+o]!==e[o]){i=false;break}if(i)return r}for(let r=t;r<=n;r+=1){let i=true;for(let o=0;o<e.length;o+=1)if(s[r+o].trimEnd()!==e[o].trimEnd()){i=false;break}if(i)return r}for(let r=t;r<=n;r+=1){let i=true;for(let o=0;o<e.length;o+=1)if(s[r+o].trim()!==e[o].trim()){i=false;break}if(i)return r}for(let r=t;r<=n;r+=1){let i=true;for(let o=0;o<e.length;o+=1)if(rm(s[r+o])!==rm(e[o])){i=false;break}if(i)return r}return null}function Ox(s,e){let t=s.length,n=e.length;if(t*n>Lx)return [...s.map(c=>({type:"delete",line:c})),...e.map(c=>({type:"insert",line:c}))];let i=Array.from({length:t+1},()=>new Array(n+1).fill(0));for(let c=t-1;c>=0;c-=1)for(let u=n-1;u>=0;u-=1)i[c][u]=s[c]===e[u]?i[c+1][u+1]+1:Math.max(i[c+1][u],i[c][u+1]);let o=[],a=0,l=0;for(;a<t&&l<n;){if(s[a]===e[l]){o.push({type:"equal",line:s[a]}),a+=1,l+=1;continue}i[a+1][l]>=i[a][l+1]?(o.push({type:"delete",line:s[a]}),a+=1):(o.push({type:"insert",line:e[l]}),l+=1);}for(;a<t;)o.push({type:"delete",line:s[a]}),a+=1;for(;l<n;)o.push({type:"insert",line:e[l]}),l+=1;return o}function Dx(s,e){if(s.length===0&&e.length===0)return [];let t=Ox(s,e),n=[],r=0,i=0,o=0;for(;o<t.length;){if(t[o].type==="equal"){r+=1,i+=1,o+=1;continue}let a=r,l=[],c=[];for(;o<t.length&&t[o].type!=="equal";){let u=t[o];u.type==="delete"?(l.push(u.line),r+=1):(c.push(u.line),i+=1),o+=1;}n.push({oldStart:a,oldLines:l,newLines:c});}return n}function ic(s){rc=s;}function fo(){return rc}async function $x(s){let e=he__default.stat(te__default.join(s,"package.json")).then(()=>true).catch(()=>false),t=he__default.stat(te__default.join(s,"pnpm-lock.yaml")).then(()=>true).catch(()=>false),n=he__default.stat(te__default.join(s,"yarn.lock")).then(()=>true).catch(()=>false),r=he__default.stat(te__default.join(s,"bun.lockb")).then(()=>true).catch(()=>false),i=he__default.stat(te__default.join(s,"pyproject.toml")).then(()=>true).catch(()=>false),o=he__default.stat(te__default.join(s,"pytest.ini")).then(()=>true).catch(()=>false),a=he__default.stat(te__default.join(s,"go.mod")).then(()=>true).catch(()=>false),l=he__default.stat(te__default.join(s,"Cargo.toml")).then(()=>true).catch(()=>false),c=he__default.stat(te__default.join(s,"Makefile")).then(()=>true).catch(()=>false);return Promise.all([e,t,n,r,i,o,a,l,c]).then(([u,d,p,m,h,g,y,x,S])=>u?d?"pnpm":p?"yarn":m?"bun":"npm":h||g?"pytest":y?"go":x?"cargo":S?"make":null)}function Nx(s,e,t){switch(s){case "npm":case "pnpm":case "yarn":case "bun":return {command:s,args:["run",e==="test"?"test":e==="lint"?"lint":"format",...t]};case "pytest":return {command:"pytest",args:t};case "go":return e==="test"?{command:"go",args:["test","./...",...t]}:e==="lint"?{command:"golangci-lint",args:["run",...t]}:{command:"gofmt",args:["-w",...t]};case "cargo":return e==="test"?{command:"cargo",args:["test",...t]}:e==="lint"?{command:"cargo",args:["clippy","--",...t]}:{command:"cargo",args:["fmt",...t]};case "make":return {command:"make",args:[e,...t]};default:return {command:"npm",args:["run",e,...t]}}}async function oc(s,e,t){let n=qe(t.cwd||".");if(!Qt(n))return JSON.stringify(bn(s,"error","Command rejected: path outside workspace",{error:"cwd is outside workspace"}));if(t.extra_args!==void 0&&!Array.isArray(t.extra_args))return JSON.stringify(bn(s,"error","Invalid extra_args: expected an array of strings",{error:"extra_args must be an array"}));let r=Array.isArray(t.extra_args)?t.extra_args.map(l=>String(l)):[],i=t.preset||await $x(n),o=t.command,a=[];if(o){let l=Ax(o);if(!l.command)return JSON.stringify(bn(s,"error","Invalid command",{error:"Command is empty"}));let c=new Set(["npm","pnpm","yarn","bun","pytest","go","cargo","make"]);if(!c.has(l.command))return JSON.stringify(bn(s,"error","Command not allowed",{error:`Allowed commands: ${Array.from(c).join(", ")}`}));let u=l.args.concat(r),d=await Xe(l.command,u,n,{timeoutMs:t.timeout_ms||3e5}),p=[d.stdout,d.stderr].filter(Boolean).join(`
671
+ `),m=ho(p,tm),h=d.exitCode===0?`${s} succeeded (${d.durationMs}ms)`:`${s} failed with exit code ${d.exitCode}`;return JSON.stringify(bn(s,d.exitCode===0?"success":"error",h,{error:d.exitCode===0?void 0:ho(p,nm).text,metadata:{command:[l.command,...u].join(" "),exit_code:d.exitCode,duration_ms:d.durationMs,output_truncated:m.truncated}}))}if(i){let l=Nx(i,e,r);a=l.args;let c=await Xe(l.command,a,n,{timeoutMs:t.timeout_ms||3e5}),u=[c.stdout,c.stderr].filter(Boolean).join(`
672
+ `),d=ho(u,tm),p=c.exitCode===0?`${s} succeeded (${c.durationMs}ms)`:`${s} failed with exit code ${c.exitCode}`;return JSON.stringify(bn(s,c.exitCode===0?"success":"error",p,{error:c.exitCode===0?void 0:ho(u,nm).text,metadata:{command:[l.command,...a].join(" "),exit_code:c.exitCode,duration_ms:c.durationMs,output_truncated:d.truncated}}))}return JSON.stringify(bn(s,"error","Unable to detect project type for command",{error:"No preset detected. Provide preset."}))}async function sc(){if(On!==null)return On;try{let{rgPath:s}=await import('@vscode/ripgrep');return On=s,f.info("SEARCH",`Using bundled ripgrep: ${s}`),On}catch(s){f.warn("SEARCH",`Bundled ripgrep not available: ${s.message}`);try{if((await Xe("rg",["--version"],rt(),{timeoutMs:2e3})).exitCode===0)return On="rg",f.info("SEARCH","Using system ripgrep"),On}catch{}}return On=null,null}async function Ux(){return Ir!==null||(Ir=await sc()!==null,Ir?f.info("SEARCH","ripgrep available"):f.warn("SEARCH","ripgrep not available, using fallback")),Ir}function Fx(s){let e=s.case_insensitive??true,t=[],n=(r,i,o)=>{if(!r.pattern||!r.pattern.trim())return;let a=(r.op||i).toLowerCase(),l=r.regex??o,c=r.case_insensitive??e;t.push({id:`q${t.length+1}`,pattern:r.pattern,op:a==="and"||a==="or"||a==="not"?a:i,regex:l,caseInsensitive:c});};if((s.pattern||s.query)&&n({pattern:s.pattern||s.query||"",op:s.op},"or",true),Array.isArray(s.keywords))for(let r of s.keywords)n({pattern:r},"or",false);if(Array.isArray(s.queries))for(let r of s.queries)n(r,"or",r.regex??true);return t}async function go(s){let e=Xt(),t=[...Pm];if(s&&t.push(Jp(s)),e.webSearch?.enabled&&t.push(Wl),e.javaDebug?.enabled)try{let i=await Yl(e.javaDebug?.jarPath);t.push(...i),f.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${i.length} \u4E2A\u5DE5\u5177)`);}catch(i){f.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${i.message}`),f.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(e.smartRead?.enabled!==false)try{let i=dl(s);t.push(...i),f.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${i.length} \u4E2A\u5DE5\u5177)`);}catch(i){f.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${i.message}`);}let n=e.enabledTools||{};return t.filter(i=>n[i.name]!==false)}var kx,Cx,Ql,Ex,Zt,am,tm,nm,sm,cm,Lx,um,dm,pm,mm,hm,fm,gm,rc,ym,bm,vm,xm,Sm,_m,Tm,wm,km,Cm,Em,Im,tc,Ir,On,Rm,Pm,Bx,ac=K(()=>{vt();$p();Gp();Hp();Sn();zp();Zp();ji();le();mo();Hi();kx="NEOX_WORKDIR",Cx="NEOX_WORKER",Ql=new Map,Ex=300*1e3,Zt=null;am=null;tm=12e3,nm=4e3,sm=1e6;cm={name:"write_file",description:"Write content to a file (create or overwrite)",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to write"},content:{type:"string",description:"Content to write to the file"},mode:{type:"string",description:"Write mode: overwrite or append",enum:["overwrite","append"]}},required:["file_path","content"]},async function({file_path:s,content:e,mode:t="overwrite"}){if(!s)return JSON.stringify(Y("write_file","error","Missing required parameter: file_path",{error:"file_path is required",verify_hint:"Please provide the file_path parameter."}));if(e==null)return JSON.stringify(Y("write_file","error","Missing required parameter: content",{error:"content is required",verify_hint:"Please provide the content parameter with the text to write."}));let n=typeof e=="string"?e:String(e);if(n.trim()==="")return JSON.stringify(Y("write_file","error","Content is empty - this is likely an error",{error:"Empty content provided",verify_hint:"Please provide non-empty content to write."}));let r=qe(s),i=createHash("sha256").update(n).digest("hex").substring(0,16),o=Ql.get(r),a=Date.now();if(o&&o.checksum===i&&o.success&&a-o.timestamp<Ex){let l=n.split(`
673
+ `).length;return JSON.stringify(Y("write_file","already_done",`File already written with identical content (${l} lines, ${n.length} bytes)`,{file_path:r,checksum:i,verify_hint:`Use "readfile ${s}" to verify the content if needed.`,metadata:{lines:l,bytes:n.length}}))}try{let l=!1;try{await he__default.access(r),l=!0;}catch{}await he__default.mkdir(te__default.dirname(r),{recursive:!0}),t==="append"?await he__default.appendFile(r,n,"utf-8"):await he__default.writeFile(r,n,"utf-8"),Ql.set(r,{checksum:i,timestamp:a,success:!0});let c=n.split(`
674
+ `).length,u=l?"updated":"created";return JSON.stringify(Y("write_file","success",`File ${u}: ${te__default.basename(r)} (${c} lines, ${n.length} bytes)`,{file_path:r,checksum:i,verify_hint:`Use "readfile ${s}" to verify the content.`,metadata:{action:u,lines:c,bytes:n.length}}))}catch(l){return Ql.set(r,{checksum:i,timestamp:a,success:false}),JSON.stringify(Y("write_file","error",`Failed to write file: ${l.message}`,{file_path:r,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};Lx=2e5;um={name:"edit_file",description:`Edit file by replacing a target block with a new block.
675
+ Edits apply line-level hunks (only changed lines are replaced).
676
+ Matches are robust (exact -> trim_end -> trim -> normalize) to avoid brittle edits.
677
+ Use change_context to anchor a location and keep old_string minimal.`,parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to the file to edit"},path:{type:"string",description:"Alias of file_path (fallback)"},filePath:{type:"string",description:"Alias of file_path (camelCase fallback)"},file:{type:"string",description:"Alias of file_path (short fallback)"},old_string:{type:"string",description:"Exact string to find and replace (must match exactly, including whitespace)"},old:{type:"string",description:"Alias of old_string (fallback)"},new_string:{type:"string",description:"New string to replace with"},new:{type:"string",description:"Alias of new_string (fallback)"},change_context:{type:"string",description:"Optional anchor (line or block) to locate the edit area (apply_patch-style @@ context)"},changeContext:{type:"string",description:"Alias of change_context (camelCase fallback)"},context:{type:"string",description:"Alias of change_context (fallback)"},replace_all:{type:"boolean",description:"Replace all occurrences (default: false, only first match)"},replaceAll:{type:"boolean",description:"Alias of replace_all (camelCase fallback)"}},required:["file_path","old_string","new_string"]},async function(s){let e=s.file_path||s.path||s.filePath||s.file,t=s.old_string??s.old,n=s.new_string??s.new,r=s.replace_all??s.replaceAll??false,i=s.change_context??s.changeContext??s.context,o=qe(e);Ue(o);if(!e)return JSON.stringify(Y("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(Y("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(n==null)return JSON.stringify(Y("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await he__default.readFile(o,"utf-8");}catch{return JSON.stringify(Y("edit_file","error",`File not found: ${e}`,{file_path:o,error:"File not found",verify_hint:"Use write_file to create a new file, or check the file path."}))}try{let{lines:c,lineEnding:u,hasTrailingNewline:d}=Mx(l),p=t.split(/\r?\n/),m=n.split(/\r?\n/);if(p.length===1&&p[0]==="")return JSON.stringify(Y("edit_file","error","old_string cannot be empty",{file_path:o,error:"old_string cannot be empty"}));let h=0;if(i){let _=i.split(/\r?\n/),W=ec(c,_,0);if(W===null)return JSON.stringify(Y("edit_file","error",`change_context not found in ${te__default.basename(o)}`,{file_path:o,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));h=W+_.length;}let g=[],y=h;for(;y<=c.length;){let _=ec(c,p,y),W=p,$=m;if(_===null&&p.length>0&&p[p.length-1]===""){let A=p.slice(0,-1);A.length>0&&(_=ec(c,A,y),_!==null&&(W=A,$=m[m.length-1]===""?m.slice(0,-1):m));}if(_===null)break;g.push({start:_,oldLines:W,newLines:$}),y=_+W.length;}if(g.length===0)return JSON.stringify(Y("edit_file","error",`Target block not found in ${te__default.basename(o)}`,{file_path:o,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let x=r?g:[g[0]],S=c.slice(),T=[];for(let _ of x.slice().reverse()){let W=c.slice(_.start,_.start+_.oldLines.length),$=Dx(W,_.newLines);if($.length!==0){for(let A of $)T.push({startLine:_.start+A.oldStart+1,oldLines:A.oldLines,newLines:A.newLines});for(let A of $.slice().reverse())S.splice(_.start+A.oldStart,A.oldLines.length,...A.newLines);}}d&&(S=[...S,""]);let w=S.join(u);if(w===l)return JSON.stringify(Y("edit_file","already_done","No changes needed (content already matches)",{file_path:o,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await he__default.writeFile(o,w,"utf-8");let L=T.slice().sort((_,W)=>_.startLine-W.startLine),B=L[0],I=B?B.oldLines:[],k=B?B.newLines:[],R=B?B.startLine:1,E=S.length,M=!r&&g.length>1?`Found ${g.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(Y("edit_file","success",`Edited ${te__default.basename(o)}: ${x.length} replacement(s) at line ${R}`,{file_path:o,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:x.length,start_line:R,old_lines:I.length,new_lines:k.length,total_lines:E,warning:M,hunks:L.map(_=>({old_string:_.oldLines.join(`
678
+ `),new_string:_.newLines.join(`
679
+ `),start_line:_.startLine,old_line_count:_.oldLines.length,new_line_count:_.newLines.length})),edit_info:{old_string:I.join(`
680
+ `),new_string:k.join(`
681
+ `),start_line:R,old_line_count:I.length,new_line_count:k.length}}}))}catch(c){return JSON.stringify(Y("edit_file","error",`Failed to edit file: ${c.message}`,{file_path:o,error:c.message,verify_hint:"Check file permissions or try using write_file to rewrite the entire file."}))}}},dm={name:"search_files",description:`Fast file pattern matching tool (Glob).
682
+
683
+ Use this to find files by name patterns:
684
+ - "**/*.ts" - all TypeScript files
685
+ - "src/**/*.jsx" - JSX files in src
686
+ - "**/test*.js" - test files anywhere
687
+
688
+ For searching file CONTENTS, use search instead.`,parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g., **/*.ts, src/**/*.jsx, **/test*.js)"},directory:{type:"string",description:"Directory to search in (default: current directory)"},include_hidden:{type:"boolean",description:"Include hidden files (default: false)"}},required:["pattern"]},async function({pattern:s,directory:e=".",include_hidden:t=false}){try{let n=qe(e),r=await om(s,{cwd:n,absolute:!1,dot:t,ignore:["**/node_modules/**","**/.git/**"]});if(r.length===0)return `\u2713 \u641C\u7D22: "${s}" \u5728 ${Ue(n)}
689
+ \u672A\u627E\u5230\u5339\u914D\u7684\u6587\u4EF6
690
+
691
+ \u5EFA\u8BAE:
692
+ - \u68C0\u67E5\u8DEF\u5F84\u662F\u5426\u6B63\u786E
693
+ - \u5C1D\u8BD5\u66F4\u5BBD\u6CDB\u7684\u6A21\u5F0F: "**/*${s.replace(/\*\*/g,"").replace(/\*/g,"")}"`;r.sort();let i=[`\u2713 \u627E\u5230 ${r.length} \u4E2A\u6587\u4EF6`];i.push(`\u25B8 \u76EE\u5F55: ${Ue(n)}`),i.push(`\u25B8 \u6A21\u5F0F: ${s}
694
+ `);let o=50;return r.slice(0,o).forEach(l=>{i.push(` ${l}`);}),r.length>o&&i.push(`
695
+ ... \u8FD8\u6709 ${r.length-o} \u4E2A\u6587\u4EF6`),i.join(`
696
+ `)}catch(n){return `\u2717 \u641C\u7D22\u5931\u8D25: ${n.message}`}}},pm={name:"list_directory",description:"List contents of a directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},show_hidden:{type:"boolean",description:"Show hidden files"}}},async function({directory:s=".",show_hidden:e=false}){try{let t=qe(s),n=await he__default.readdir(t,{withFileTypes:!0}),r=e?n:n.filter(l=>!l.name.startsWith(".")),i=r.filter(l=>l.isDirectory()).map(l=>l.name),o=r.filter(l=>l.isFile()).map(l=>l.name),a=[`\u2713 \u76EE\u5F55: ${Ue(t)}
697
+ `];if(i.length>0&&(a.push("\u5B50\u76EE\u5F55:"),i.forEach(l=>a.push(` - ${l}/`))),o.length>0){a.push(`
698
+ \u6587\u4EF6:`);for(let l of o){let c=await he__default.stat(te__default.join(t,l)),u=c.size<1024?`${c.size}B`:c.size<1024*1024?`${(c.size/1024).toFixed(1)}KB`:`${(c.size/(1024*1024)).toFixed(1)}MB`;a.push(` - ${l} (${u})`);}}return i.length===0&&o.length===0&&a.push("(\u7A7A\u76EE\u5F55)"),a.join(`
699
+ `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},mm={name:"create_directory",description:"Create a new directory",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path to create"}},required:["directory"]},async function({directory:s}){if(!s)return JSON.stringify(Y("create_directory","error","Missing required parameter: directory",{error:"directory path is required",verify_hint:"Please provide the directory path to create."}));let e=qe(s),t=Ue(e);try{try{if((await he__default.stat(e)).isDirectory())return JSON.stringify(Y("create_directory","already_done",`Directory already exists: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${s}" to view contents.`}))}catch{}return await he__default.mkdir(e,{recursive:!0}),JSON.stringify(Y("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${s}" to verify.`}))}catch(n){return JSON.stringify(Y("create_directory","error",`Failed to create directory: ${n.message}`,{file_path:e,error:n.message,verify_hint:"Check path validity and permissions."}))}}},hm={name:"delete_file",description:"Delete a file or directory (directory requires recursive=true)",parameters:{type:"object",properties:{path:{type:"string",description:"Path to the file or directory to delete"},recursive:{type:"boolean",description:"Allow deleting directories recursively (default: false)"},force:{type:"boolean",description:"Ignore missing paths (default: false)"}},required:["path"]},permission:{category:"write",allowInAskMode:false},async function({path:s,recursive:e=false,force:t=false}){if(!s)return JSON.stringify(Y("delete_file","error","Missing required parameter: path",{error:"path is required"}));let n=qe(s),r=Ue(n),i=rt();if(!Qt(n))return JSON.stringify(Y("delete_file","error","Path is \u062E\u0627\u0631\u062C workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:n,error:"Path is outside workspace",verify_hint:"Use a path within the workspace."}));if(n===i)return JSON.stringify(Y("delete_file","error","Refusing to delete workspace root",{file_path:n,error:"Refusing to delete workspace root"}));try{let o=await he__default.lstat(n).catch(()=>null);if(!o)return JSON.stringify(t?Y("delete_file","already_done",`Path already removed: ${r}`,{file_path:n}):Y("delete_file","error",`Path not found: ${r}`,{file_path:n,error:"Path not found"}));if(o.isDirectory()){if(!e)return JSON.stringify(Y("delete_file","error",`Refusing to delete directory without recursive=true: ${r}`,{file_path:n,error:"Directory deletion requires recursive=true"}));await he__default.rm(n,{recursive:!0,force:t});}else await he__default.rm(n,{force:t});return JSON.stringify(Y("delete_file","success",`Deleted: ${r}`,{file_path:n,verify_hint:`Use "list_directory ${te__default.dirname(r)}" to verify.`}))}catch(o){return JSON.stringify(Y("delete_file","error",`Failed to delete: ${r}`,{file_path:n,error:o.message}))}}},fm={name:"rename_file",description:"Rename or move a file/directory within the workspace",parameters:{type:"object",properties:{source_path:{type:"string",description:"Existing path to rename or move"},destination_path:{type:"string",description:"New path"},overwrite:{type:"boolean",description:"Overwrite destination if it exists (default: false)"},create_dirs:{type:"boolean",description:"Create destination parent directories if missing (default: true)"}},required:["source_path","destination_path"]},permission:{category:"write",allowInAskMode:false},async function({source_path:s,destination_path:e,overwrite:t=false,create_dirs:n=true}){if(!s||!e)return JSON.stringify(Y("rename_file","error","Missing required parameters: source_path, destination_path",{error:"source_path and destination_path are required"}));let r=qe(s),i=qe(e),o=Ue(r),a=Ue(i),l=rt();if(!Qt(r)||!Qt(i))return JSON.stringify(Y("rename_file","error","Path is outside workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:`${r} -> ${i}`,error:"Path is outside workspace"}));if(r===l||i===l)return JSON.stringify(Y("rename_file","error","Refusing to rename workspace root",{file_path:r}));try{await he__default.lstat(r);}catch{return JSON.stringify(Y("rename_file","error",`Source not found: ${o}`,{file_path:r,error:"Source not found"}))}let c=await he__default.lstat(i).catch(()=>null);if(c&&!t)return JSON.stringify(Y("rename_file","error",`Destination already exists: ${a}`,{file_path:i,error:"Destination already exists"}));try{return c&&t&&await he__default.rm(i,{recursive:!0,force:!0}),n&&await he__default.mkdir(te__default.dirname(i),{recursive:!0}),await he__default.rename(r,i),JSON.stringify(Y("rename_file","success",`Renamed: ${o} \u2192 ${a}`,{file_path:i,verify_hint:`Use "list_directory ${te__default.dirname(a)}" to verify.`,metadata:{from:r,to:i}}))}catch(u){return JSON.stringify(Y("rename_file","error",`Failed to rename: ${o}`,{file_path:r,error:u.message}))}}},gm={name:"apply_patch",description:"Apply a unified diff patch (git apply style)",parameters:{type:"object",properties:{patch:{type:"string",description:"Unified diff patch content"},strip:{type:"number",description:"Strip leading path components (git apply -p, default: 0)"},reverse:{type:"boolean",description:"Apply patch in reverse (default: false)"}},required:["patch"]},permission:{category:"write",allowInAskMode:false},async function({patch:s,strip:e=0,reverse:t=false}){if(!s||typeof s!="string")return JSON.stringify(Y("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(Y("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(s,"utf8")>sm)return JSON.stringify(Y("apply_patch","error",`Patch too large (max ${sm} bytes)`,{error:"Patch too large"}));let n=s.split(`
700
+ `).filter(c=>c.startsWith("+++ ")||c.startsWith("--- "));for(let c of n){let u=c.slice(4).trim();if(u==="/dev/null")continue;let d=u.replace(/^a\//,"").replace(/^b\//,"");if(d.startsWith("/")||/^[A-Za-z]:[\\/]/.test(d))return JSON.stringify(Y("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(d.split(/[\\/]+/).includes(".."))return JSON.stringify(Y("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let r=rt(),{repoRoot:i,error:o}=await Dn(r);if(!i)return JSON.stringify(Y("apply_patch","error",`Not a git repository: ${o||"unknown error"}`,{error:"Not a git repository"}));let a=await he__default.mkdtemp(te__default.join(ti__default.tmpdir(),"neox-patch-")),l=te__default.join(a,"apply.patch");try{await he__default.writeFile(l,s,"utf8");let c=["apply"];e>0&&c.push(`-p${e}`),t&&c.push("--reverse");let u=await Xe("git",[...c,"--check",l],i);if(u.exitCode!==0){let p=[u.stdout,u.stderr].filter(Boolean).join(`
701
+ `).trim();return JSON.stringify(Y("apply_patch","error","Patch check failed",{error:p||"Patch check failed",verify_hint:"Ensure the patch applies cleanly to the current workspace state."}))}let d=await Xe("git",[...c,"--whitespace=nowarn",l],i);if(d.exitCode!==0){let p=[d.stdout,d.stderr].filter(Boolean).join(`
702
+ `).trim();return JSON.stringify(Y("apply_patch","error","Patch apply failed",{error:p||"Patch apply failed"}))}return JSON.stringify(Y("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(Y("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await he__default.rm(a,{recursive:true,force:true}).catch(()=>{});}}},rc=process.env.NEOX_SANDBOX==="on";ym={name:"execute_shell",description:`Execute shell command with smart background process management.
703
+
704
+ \u{1F525} CRITICAL - Background Process Behavior:
705
+ - background=true: For LONG-RUNNING processes (npm run dev, servers, watch modes)
706
+ \u2022 Process will continue running indefinitely until explicitly killed
707
+ \u2022 DO NOT retry the same command - automatic deduplication will prevent it
708
+ \u2022 DO NOT add '&' at the end - it's handled by the background parameter
709
+ \u2022 The tool will REJECT duplicate background commands automatically
710
+ - background=false: For quick commands (ls, git status, build once)
711
+ \u2022 Process runs once and exits immediately
712
+
713
+ \u26A0\uFE0F IMPORTANT: Each call starts from the WORKSPACE directory!
714
+ - "cd" only works within the SAME call
715
+ - For operations outside workspace, ALWAYS use: cd /absolute/path && your_command
716
+ - Example: cd ~/my-project && npm install (NOT just: npm install)
717
+
718
+ \u{1F4CC} Process Management:
719
+ - Use /processes to list all running background processes
720
+ - Use /kill <pid> to stop a background process before retrying`,parameters:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},background:{type:"boolean",description:"Run in background for long-running processes (npm run dev, servers). Default: false"}},required:["command"]},async function({command:s,background:e=false},t){if(rc){let u=["ls","pwd","echo","cat","grep","find","wc","head","tail"],d=s.trim().split(" ")[0];if(!u.includes(d))return `\u2717 \u6C99\u7BB1\u6A21\u5F0F\uFF1A\u4E0D\u5141\u8BB8\u6267\u884C\u547D\u4EE4: ${d}
721
+ \u5141\u8BB8\u7684\u547D\u4EE4: ${u.join(", ")}
722
+ \u63D0\u793A: \u4F7F\u7528 /sandbox off \u5173\u95ED\u6C99\u7BB1\u6A21\u5F0F`}let r=rt(),i=t?.signal,o=s.trim().endsWith("&"),a=s.includes("|");e&&(o||a)&&(f.warn("SHELL","\u68C0\u6D4B\u5230\u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u4E86 '&' \u6216\u7BA1\u9053\u7B26\u53F7\uFF0C\u8FD9\u53EF\u80FD\u5BFC\u81F4\u975E\u9884\u671F\u884C\u4E3A"),o&&f.info("SHELL","\u63D0\u793A: background=true \u53C2\u6570\u5DF2\u7ECF\u5904\u7406\u540E\u53F0\u8FD0\u884C\uFF0C\u65E0\u9700\u5728\u547D\u4EE4\u672B\u5C3E\u6DFB\u52A0 '&'"),a&&f.warn("SHELL","\u8B66\u544A: \u540E\u53F0\u6A21\u5F0F\u4E0B\u4F7F\u7528\u7BA1\u9053\u53EF\u80FD\u5BFC\u81F4\u8F93\u51FA\u622A\u65AD\u6216\u8FDB\u7A0B\u610F\u5916\u9000\u51FA"));let l=lm();if(l)try{f.debug("SHELL","Using terminal executor (UI mode)");let u=await l({command:s,cwd:r,timeout:6e5}),d=u.output.length>1e4?u.output.slice(0,1e4)+`
723
+
724
+ ... (\u8F93\u51FA\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:u.output;return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
725
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
726
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
727
+ \u25B8 \u6267\u884C\u6A21\u5F0F: \u7EC8\u7AEF UI
728
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
729
+
730
+ ${d||"(\u65E0\u8F93\u51FA)"}
731
+
732
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
733
+ \u9000\u51FA\u7801: ${u.exitCode}
734
+ ${u.exitCode!==0?"\u26A0\uFE0F \u547D\u4EE4\u6267\u884C\u8FD4\u56DE\u975E\u96F6\u9000\u51FA\u7801\uFF0C\u8BF7\u68C0\u67E5\u8F93\u51FA":"\u2713 \u547D\u4EE4\u6267\u884C\u6210\u529F"}
735
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}catch(u){f.warn("SHELL","Terminal executor failed",{error:u.message});}let c=await Rx(s,e,r,i);if(c){if(c.background&&c.pid){Ee.get(c.pid)||Ee.register({pid:c.pid,command:s,cwd:r,background:true});let u=Ee.getBackgroundRunning().length;return c.output.replace(/当前后台进程总数:\s*\d+/,`\u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${u}`)}return c.output}if(e){let u=s.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,""),d=Ee.getBackgroundRunning().find(p=>p.command.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,"")===u);if(d){let p=Math.floor((Date.now()-d.startTime.getTime())/1e3),m=Ee.getBackgroundRunning().length;return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
736
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
737
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
738
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
739
+
740
+ \u26A0\uFE0F \u76F8\u540C\u8FDB\u7A0B\u5DF2\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u65E0\u9700\u91CD\u590D\u542F\u52A8\uFF01
741
+ \u2022 \u5DF2\u5B58\u5728\u8FDB\u7A0B ID (PID): ${d.pid}
742
+ \u2022 \u5DF2\u8FD0\u884C\u65F6\u957F: ${p}\u79D2
743
+ \u2022 \u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${m}
744
+
745
+ \u{1F525} \u91CD\u8981\u63D0\u793A:
746
+ - \u540E\u53F0\u8FDB\u7A0B\u4F1A\u6301\u7EED\u8FD0\u884C\uFF0C\u65E0\u9700\u91CD\u590D\u6267\u884C\u76F8\u540C\u547D\u4EE4
747
+ - \u8BE5\u8FDB\u7A0B\u5C06\u4E00\u76F4\u8FD0\u884C\u76F4\u5230\u4E3B\u52A8\u7EC8\u6B62\u6216\u9047\u5230\u9519\u8BEF
748
+ - \u5982\u9700\u91CD\u542F\uFF0C\u8BF7\u5148\u7EC8\u6B62\u73B0\u6709\u8FDB\u7A0B
749
+
750
+ \u{1F4CC} \u5EFA\u8BAE\u64CD\u4F5C:
751
+ - /processes - \u67E5\u770B\u6240\u6709\u540E\u53F0\u8FDB\u7A0B\u72B6\u6001
752
+ - /kill ${d.pid} - \u7EC8\u6B62\u73B0\u6709\u8FDB\u7A0B\u540E\u91CD\u65B0\u542F\u52A8
753
+ - lsof -i :\u7AEF\u53E3\u53F7 - \u68C0\u67E5\u7AEF\u53E3\u5360\u7528\u60C5\u51B5
754
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}try{let p=execa(s,{shell:!0,cwd:r,detached:!0,stdio:["ignore","pipe","pipe"],env:nc()});p.unref();let m=p.pid;m&&(Ee.register({pid:m,command:s,cwd:r,background:!0,processRef:p}),p.on("exit",T=>{Ee.markCompleted(m,T??0);})),i&&m&&i.addEventListener("abort",()=>{f.info("SHELL",`\u6536\u5230\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B PID: ${m}`),Ee.killProcessGroup(m);});let h=[],g=8e3;p.stdout?.on("data",T=>{let w=T.toString();h.push(w),process.env.CLI_DEBUG==="1"&&f.debug("SHELL_STDOUT",w.trim());}),p.stderr?.on("data",T=>{let w=T.toString();h.push(w),process.env.CLI_DEBUG==="1"&&f.debug("SHELL_STDERR",w.trim());}),f.info("SHELL",`\u6B63\u5728\u6536\u96C6\u8FDB\u7A0B\u8F93\u51FA (${g/1e3}\u79D2)...`),await new Promise((T,w)=>{let L=setTimeout(T,g);i&&i.addEventListener("abort",()=>{clearTimeout(L),w(new Error("Command interrupted by user"));});});let y=h.join(""),x=y.length>3e3?y.slice(0,3e3)+`
755
+ ... (\u8F93\u51FA\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:y,S=Ee.getBackgroundRunning().length;return `\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
756
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
757
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
758
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
759
+
760
+ \u2705 \u540E\u53F0\u8FDB\u7A0B\u5DF2\u6210\u529F\u542F\u52A8\u5E76\u6301\u7EED\u8FD0\u884C\u4E2D
761
+ \u2022 \u8FDB\u7A0B ID (PID): ${m}
762
+ \u2022 \u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${S}
763
+
764
+ \u{1F525} \u91CD\u8981\u63D0\u793A:
765
+ - \u6B64\u8FDB\u7A0B\u5C06\u6301\u7EED\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u76F4\u5230\u4E3B\u52A8\u7EC8\u6B62\u6216\u9047\u5230\u9519\u8BEF
766
+ - \u65E0\u9700\u518D\u6B21\u542F\u52A8\u76F8\u540C\u547D\u4EE4\uFF08\u81EA\u52A8\u53BB\u91CD\u673A\u5236\u4F1A\u62D2\u7EDD\u91CD\u590D\u542F\u52A8\uFF09
767
+ - \u8FDB\u7A0B\u5DF2\u52A0\u5165\u8FDB\u7A0B\u7BA1\u7406\u5668\u8FFD\u8E2A\uFF0C\u53EF\u968F\u65F6\u67E5\u770B\u72B6\u6001
768
+
769
+ \u25E6 \u542F\u52A8\u65E5\u5FD7 (\u524D ${g/1e3} \u79D2):
770
+ ${x||"(\u6682\u65E0\u8F93\u51FA)"}
771
+
772
+ \u{1F4CC} \u8FDB\u7A0B\u7BA1\u7406\u547D\u4EE4:
773
+ - /processes - \u67E5\u770B\u6240\u6709\u540E\u53F0\u8FDB\u7A0B\u72B6\u6001
774
+ - /kill ${m} - \u7EC8\u6B62\u6B64\u8FDB\u7A0B
775
+ - lsof -i :\u7AEF\u53E3\u53F7 - \u68C0\u67E5\u7AEF\u53E3\u5360\u7528
776
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}catch(p){return p.message==="Command interrupted by user"?`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
777
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
778
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
779
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
780
+
781
+ \u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
782
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
783
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
784
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
785
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
786
+
787
+ \u2717 \u540E\u53F0\u542F\u52A8\u5931\u8D25:
788
+ ${p.message}
789
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}try{let{stdout:u,stderr:d,exitCode:p}=await execa(s,{shell:!0,timeout:12e4,cwd:r,reject:!1,signal:i,env:nc(),stdio:["ignore","pipe","pipe"]}),m=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
790
+ `;return m+=`\u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
791
+ `,m+=`\u25B8 \u6267\u884C\u547D\u4EE4: ${s}
792
+ `,m+=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
793
+
794
+ `,p===0?m+=`\u2713 \u6267\u884C\u6210\u529F (\u9000\u51FA\u7801: 0)
795
+
796
+ `:m+=`! \u6267\u884C\u5B8C\u6210\u4F46\u6709\u9519\u8BEF (\u9000\u51FA\u7801: ${p})
797
+
798
+ `,u&&(m+=`\u25E6 \u6807\u51C6\u8F93\u51FA (stdout):
799
+ ${u}
800
+
801
+ `),d&&(m+=`\u25E6 \u9519\u8BEF\u8F93\u51FA (stderr):
802
+ ${d}
803
+
804
+ `),!u&&!d&&(m+=`(\u65E0\u8F93\u51FA)
805
+
806
+ `),m+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",m}catch(u){return u.timedOut?`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
807
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
808
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
809
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
810
+
811
+ \u2717 \u547D\u4EE4\u6267\u884C\u8D85\u65F6 (120\u79D2)
812
+
813
+ \u5EFA\u8BAE:
814
+ 1. \u8FD9\u53EF\u80FD\u662F\u4E00\u4E2A\u957F\u671F\u8FD0\u884C\u7684\u8FDB\u7A0B\uFF08\u5F00\u53D1\u670D\u52A1\u5668\u7B49\uFF09
815
+ 2. \u4F7F\u7528 background=true \u53C2\u6570\u5728\u540E\u53F0\u8FD0\u884C: {"command": "${s}", "background": true}
816
+ 3. \u6216\u8005\u4F7F\u7528\u66F4\u5177\u4F53\u7684\u547D\u4EE4\u51CF\u5C11\u6267\u884C\u65F6\u95F4
817
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
818
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${r}
819
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${s}
820
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
821
+
822
+ \u2717 \u6267\u884C\u5931\u8D25:
823
+ ${u.message}
824
+
825
+ ${u.stdout?`\u25E6 \u90E8\u5206\u8F93\u51FA:
826
+ ${u.stdout}
827
+
828
+ `:""}
829
+ ${u.stderr?`\u25E6 \u9519\u8BEF\u4FE1\u606F:
830
+ ${u.stderr}
831
+
832
+ `:""}
833
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}},bm={name:"show_tree",description:"Display directory tree structure",parameters:{type:"object",properties:{directory:{type:"string",description:"Directory path (default: current directory)"},max_depth:{type:"number",description:"Maximum depth to traverse (default: 3)"}}},async function({directory:s=".",max_depth:e=3}){try{let t=qe(s),n=[`${Ue(t)}/
834
+ `];async function r(i,o="",a=0){if(a>=e)return;let u=(await he__default.readdir(i,{withFileTypes:!0})).filter(d=>!d.name.startsWith(".")).sort((d,p)=>d.isDirectory()&&!p.isDirectory()?-1:!d.isDirectory()&&p.isDirectory()?1:d.name.localeCompare(p.name));for(let d=0;d<u.length;d++){let p=u[d],m=d===u.length-1,h=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",g=m?" ":"\u2502 ";if(p.isDirectory())n.push(`${o}${h}${p.name}/`),await r(te__default.join(i,p.name),o+g,a+1);else {let y=await he__default.stat(te__default.join(i,p.name)),x=y.size<1024?`${y.size}B`:y.size<1024*1024?`${(y.size/1024).toFixed(1)}KB`:`${(y.size/(1024*1024)).toFixed(1)}MB`;n.push(`${o}${h}${p.name} (${x})`);}}}return await r(t),n.join(`
835
+ `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},vm={name:"git_status",description:"Show git status (short by default)",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},short:{type:"boolean",description:"Use short format (default: true)"}}},permission:{category:"read",allowInAskMode:true},async function({path:s=".",short:e=true}){let t=qe(s);if(!Qt(t))return JSON.stringify(ke("git_status","error","git status failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Dn(t);if(!n)return JSON.stringify(ke("git_status","error",`git status failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=["status"];e&&i.push("-sb");let o=await Xe("git",i,n),a=[o.stdout,o.stderr].filter(Boolean).join(`
836
+ `).trim();return o.exitCode!==0?JSON.stringify(ke("git_status","error","git status failed",a||void 0,{error:a||"git status failed"})):JSON.stringify(ke("git_status","success",a?"git status ok":"git status clean",a||"\u2713 clean"))}},xm={name:"git_diff",description:"Show git diff",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},staged:{type:"boolean",description:"Show staged diff (default: false)"},file_path:{type:"string",description:"Limit diff to a specific file"}}},permission:{category:"read",allowInAskMode:true},async function({path:s=".",staged:e=false,file_path:t}){let n=qe(s);if(!Qt(n))return JSON.stringify(ke("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:r,error:i}=await Dn(n);if(!r)return JSON.stringify(ke("git_diff","error",`git diff failed: ${i||"not a git repository"}`,void 0,{error:i||"not a git repository"}));let o=["diff"];if(e&&o.push("--staged"),t){let c=qe(t);if(!Qt(c))return JSON.stringify(ke("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let u=te__default.relative(r,c);if(u.startsWith("..")||te__default.isAbsolute(u))return JSON.stringify(ke("git_diff","error","git diff failed: file outside repo",void 0,{error:"file outside repo"}));o.push("--",u);}let a=await Xe("git",o,r),l=[a.stdout,a.stderr].filter(Boolean).join(`
837
+ `).trim();return a.exitCode!==0?JSON.stringify(ke("git_diff","error","git diff failed",l||void 0,{error:l||"git diff failed"})):JSON.stringify(ke("git_diff","success",l?"git diff ok":"no diff",l||""))}},Sm={name:"git_blame",description:"Show git blame for a file",parameters:{type:"object",properties:{file_path:{type:"string",description:"File path to blame (required)"},start_line:{type:"number",description:"Start line (1-based)"},end_line:{type:"number",description:"End line (1-based)"}},required:["file_path"]},permission:{category:"read",allowInAskMode:true},async function({file_path:s,start_line:e,end_line:t}){if(!s)return JSON.stringify(ke("git_blame","error","git blame failed: file_path is required",void 0,{error:"file_path is required"}));let n=qe(s);if(!Qt(n))return JSON.stringify(ke("git_blame","error","git blame failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:r,error:i}=await Dn(te__default.dirname(n));if(!r)return JSON.stringify(ke("git_blame","error",`git blame failed: ${i||"not a git repository"}`,void 0,{error:i||"not a git repository"}));let o=e&&t?`${e},${t}`:void 0,a=te__default.relative(r,n);if(a.startsWith("..")||te__default.isAbsolute(a))return JSON.stringify(ke("git_blame","error","git blame failed: file outside repo",void 0,{error:"file outside repo"}));let l=["blame","--",a];o&&l.splice(1,0,"-L",o);let c=await Xe("git",l,r),u=[c.stdout,c.stderr].filter(Boolean).join(`
838
+ `).trim();return c.exitCode!==0?JSON.stringify(ke("git_blame","error","git blame failed",u||void 0,{error:u||"git blame failed"})):JSON.stringify(ke("git_blame","success","git blame ok",u||""))}},_m={name:"git_branch_list",description:"List git branches",parameters:{type:"object",properties:{path:{type:"string",description:"Path inside the repo (default: workspace root)"},all:{type:"boolean",description:"Include remote branches (default: false)"}}},permission:{category:"read",allowInAskMode:true},async function({path:s=".",all:e=false}){let t=qe(s);if(!Qt(t))return JSON.stringify(ke("git_branch_list","error","git branch failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:r}=await Dn(t);if(!n)return JSON.stringify(ke("git_branch_list","error",`git branch failed: ${r||"not a git repository"}`,void 0,{error:r||"not a git repository"}));let i=["branch","--list"];e&&i.push("--all");let o=await Xe("git",i,n),a=[o.stdout,o.stderr].filter(Boolean).join(`
839
+ `).trim();return o.exitCode!==0?JSON.stringify(ke("git_branch_list","error","git branch failed",a||void 0,{error:a||"git branch failed"})):JSON.stringify(ke("git_branch_list","success","git branches",a||""))}},Tm={name:"git_branch",description:"Create a git branch",parameters:{type:"object",properties:{name:{type:"string",description:"Branch name to create"},checkout:{type:"boolean",description:"Checkout after creation (default: false)"}},required:["name"]},permission:{category:"write",allowInAskMode:false},async function({name:s,checkout:e=false}){let t=rt(),{repoRoot:n,error:r}=await Dn(t);if(!n)return JSON.stringify(Y("git_branch","error",`Not a git repository: ${r||"unknown error"}`,{error:"Not a git repository"}));if(!s)return JSON.stringify(Y("git_branch","error","Branch name is required (use git_branch_list to list branches)",{error:"name is required"}));let i=typeof s=="string"?s.trim():"",o=/^[A-Za-z0-9._\\/-]+$/.test(i);if(!i||!o||i.includes("..")||i.startsWith("/")||i.endsWith("/"))return JSON.stringify(Y("git_branch","error","Invalid branch name",{error:"Invalid branch name"}));let l=await Xe("git",["branch",i],n);if(l.exitCode!==0){let c=[l.stdout,l.stderr].filter(Boolean).join(`
840
+ `).trim();return JSON.stringify(Y("git_branch","error","Failed to create branch",{error:c||"Failed to create branch"}))}if(e){let c=await Xe("git",["checkout",i],n);if(c.exitCode!==0){let u=[c.stdout,c.stderr].filter(Boolean).join(`
841
+ `).trim();return JSON.stringify(Y("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(Y("git_branch","success",e?`Branch created and checked out: ${i}`:`Branch created: ${i}`,{metadata:{branch:i,checkout:e}}))}},wm={name:"git_commit",description:"Create a git commit",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"Run git add -A before commit (default: false)"}},required:["message"]},permission:{category:"write",allowInAskMode:false},async function({message:s,add_all:e=false}){let t=rt(),{repoRoot:n,error:r}=await Dn(t);if(!n)return JSON.stringify(Y("git_commit","error",`Not a git repository: ${r||"unknown error"}`,{error:"Not a git repository"}));let i=typeof s=="string"?s.trim():"";if(!i||i.length<3)return JSON.stringify(Y("git_commit","error","Commit message is too short",{error:"Commit message is too short"}));if(e){let a=await Xe("git",["add","-A"],n);if(a.exitCode!==0){let l=[a.stdout,a.stderr].filter(Boolean).join(`
842
+ `).trim();return JSON.stringify(Y("git_commit","error","git add -A failed",{error:l||"git add failed"}))}}let o=await Xe("git",["commit","-m",i],n);if(o.exitCode!==0){let a=[o.stdout,o.stderr].filter(Boolean).join(`
843
+ `).trim();return JSON.stringify(Y("git_commit","error","git commit failed",{error:a||"git commit failed"}))}return JSON.stringify(Y("git_commit","success",`Commit created: ${i}`,{metadata:{message:i}}))}};km={name:"run_tests",description:"Run project tests with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(s){return oc("run_tests","test",s)}},Cm={name:"run_lint",description:"Run project lint with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(s){return oc("run_lint","lint",s)}},Em={name:"run_format",description:"Run project formatting with a structured command",parameters:{type:"object",properties:{preset:{type:"string",description:"Command preset (npm|pnpm|yarn|bun|pytest|go|cargo|make)"},command:{type:"string",description:"Explicit command (overrides preset)"},extra_args:{type:"array",items:{type:"string"},description:"Additional args for the command"},cwd:{type:"string",description:"Working directory (default: workspace root)"},timeout_ms:{type:"number",description:"Timeout in milliseconds (default: 300000)"}}},permission:{category:"execute",allowInAskMode:false},async function(s){return oc("run_format","format",s)}},Im={name:"analyze_code",description:"Analyze code file structure and statistics",parameters:{type:"object",properties:{file_path:{type:"string",description:"Path to code file"}},required:["file_path"]},async function({file_path:s}){try{let e=qe(s),n=(await he__default.readFile(e,"utf-8")).split(`
844
+ `),r=n.length,i=n.filter(p=>p.trim()&&!p.trim().startsWith("//")).length,o=n.filter(p=>p.trim().startsWith("//")).length,a=r-i-o,l=n.filter(p=>p.trim().startsWith("import ")||p.trim().startsWith("from ")),c=n.filter(p=>p.trim().startsWith("function ")||p.trim().startsWith("async function")),u=n.filter(p=>p.trim().startsWith("class ")),d=[`\u2713 \u4EE3\u7801\u5206\u6790: ${s}
845
+ `,"\u7EDF\u8BA1:",` \u603B\u884C\u6570: ${r}`,` \u4EE3\u7801\u884C: ${i}`,` \u6CE8\u91CA\u884C: ${o}`,` \u7A7A\u767D\u884C: ${a}`];return l.length>0&&(d.push(`
846
+ \u5BFC\u5165 (${l.length} \u4E2A):`),l.slice(0,5).forEach(p=>d.push(` - ${p.trim()}`)),l.length>5&&d.push(` ... \u8FD8\u6709 ${l.length-5} \u4E2A\u5BFC\u5165`)),u.length>0&&(d.push(`
847
+ \u7C7B\u5B9A\u4E49 (${u.length} \u4E2A):`),u.forEach(p=>d.push(` - ${p.trim()}`))),c.length>0&&(d.push(`
848
+ \u51FD\u6570\u5B9A\u4E49 (${c.length} \u4E2A):`),c.slice(0,10).forEach(p=>d.push(` - ${p.trim()}`)),c.length>10&&d.push(` ... \u8FD8\u6709 ${c.length-10} \u4E2A\u51FD\u6570`)),d.join(`
849
+ `)}catch(e){return `\u2717 \u5206\u6790\u5931\u8D25: ${e.message}`}}},tc=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],Ir=null,On=null;Rm={name:"search",description:`\u3010\u5168\u5C40\u641C\u7D22\u3011\u652F\u6301\u591A\u5173\u952E\u8BCD\u3001\u591A\u67E5\u8BE2\u3001\u8DE8\u76EE\u5F55\u81EA\u52A8\u5B9A\u4F4D\u3002
850
+
851
+ \u{1F525} \u6781\u7B80\u7528\u6CD5\uFF1A
852
+ search(pattern="\u767B\u5F55") \u2192 \u5168\u5C40\u5185\u5BB9\u641C\u7D22
853
+ search(keywords=["TODO","FIXME"]) \u2192 \u591A\u5173\u952E\u8BCD OR \u641C\u7D22
854
+ search(mode="files", pattern="*.ts") \u2192 \u6587\u4EF6\u540D\u641C\u7D22
855
+
856
+ \u667A\u80FD\u9ED8\u8BA4\u503C:
857
+ - path: \u9ED8\u8BA4\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55 (\u5168\u5C40\u641C\u7D22)
858
+ - recursive: \u76EE\u5F55\u81EA\u52A8\u9012\u5F52\uFF0C\u6587\u4EF6\u4E0D\u9012\u5F52
859
+ - case_insensitive: \u9ED8\u8BA4 true
860
+ - \u81EA\u52A8\u5FFD\u7565: node_modules, .git, dist, build, __pycache__, target, vendor
861
+
862
+ \u8F93\u51FA\u7279\u70B9:
863
+ - \u6BCF\u6761\u7ED3\u679C\u5E26 [\u6A21\u5757] \u524D\u7F00
864
+ - \u663E\u793A\u6A21\u5757\u5206\u5E03\u7EDF\u8BA1
865
+ - \u63D0\u4F9B readfile \u6279\u91CF\u8BFB\u53D6\u63D0\u793A`,parameters:{type:"object",properties:{pattern:{type:"string",description:'\u641C\u7D22\u6A21\u5F0F (\u9ED8\u8BA4\u6B63\u5219)\u3002\u793A\u4F8B: "error", "\u767B\u5F55", "function\\s+\\w+"'},query:{type:"string",description:"pattern \u7684\u522B\u540D"},keywords:{type:"array",items:{type:"string"},description:"\u591A\u5173\u952E\u8BCD OR \u641C\u7D22 (\u5B57\u9762\u91CF\u5339\u914D)"},queries:{type:"array",items:{type:"object",properties:{pattern:{type:"string"},op:{type:"string",enum:["and","or","not"]},regex:{type:"boolean"},case_insensitive:{type:"boolean"}},required:["pattern"]},description:"\u9AD8\u7EA7\u591A\u67E5\u8BE2 (\u652F\u6301 and/or/not)"},op:{type:"string",enum:["and","or","not"],description:"pattern \u7684\u903B\u8F91\u64CD\u4F5C (\u9ED8\u8BA4 or)"},mode:{type:"string",enum:["content","files"],description:"\u641C\u7D22\u6A21\u5F0F: \u5185\u5BB9\u641C\u7D22\u6216\u6587\u4EF6\u540D\u641C\u7D22 (\u9ED8\u8BA4: content)"},path:{type:"string",description:"\u641C\u7D22\u8DEF\u5F84 (\u53EF\u9009\uFF0C\u9ED8\u8BA4: \u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55)"},recursive:{type:"boolean",description:"\u9012\u5F52\u5B50\u76EE\u5F55 (\u53EF\u9009\uFF0C\u76EE\u5F55\u9ED8\u8BA4 true\uFF0C\u6587\u4EF6\u9ED8\u8BA4 false)"},file_pattern:{type:"string",description:'\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4 (e.g., "*.ts", "*.{js,jsx,ts,tsx}")'},include_hidden:{type:"boolean",description:"\u5305\u542B\u9690\u85CF\u6587\u4EF6 (\u9ED8\u8BA4: false)"},case_insensitive:{type:"boolean",description:"\u5FFD\u7565\u5927\u5C0F\u5199 (\u9ED8\u8BA4: true)"},context_lines:{type:"number",description:"\u4E0A\u4E0B\u6587\u884C\u6570 (\u9ED8\u8BA4: 2)"},max_matches:{type:"number",description:"\u6700\u5927\u5339\u914D\u6570 (\u9ED8\u8BA4: 200)"},count_only:{type:"boolean",description:"\u4EC5\u8FD4\u56DE\u8BA1\u6570 (\u5FEB\u901F\u4E86\u89E3\u5339\u914D\u5206\u5E03)"}}},async function({pattern:s,query:e,keywords:t,queries:n,op:r,mode:i="content",path:o,recursive:a,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:d=2,max_matches:p=200,count_only:m=false},h){try{let g=h?.signal,y=()=>{if(g?.aborted){let D=new Error("Operation cancelled");throw D.name="AbortError",D}},x=200,S=async()=>{await new Promise(D=>setImmediate(D));},w=qe(o||"."),L="workspace",B=rt();if(o&&te__default.isAbsolute(o))L="absolute";else if(o&&!an__default.existsSync(w)){let D=B,ie=null;for(;;){let se=te__default.resolve(D,o);if(an__default.existsSync(se)){ie=se;break}let fe=te__default.dirname(D);if(fe===D)break;D=fe;}ie&&(w=ie,L="ancestor");}let I=Ue(w);y();let k;try{k=await he__default.stat(w);}catch(D){return JSON.stringify(ke("search","error",`search failed: ${D.message}`,void 0,{error:D.message}))}let R=k.isDirectory(),E=a!==void 0?a:R,M=Fx({pattern:s,query:e,keywords:t,queries:n,op:r,case_insensitive:u});if(y(),M.length===0)return JSON.stringify(ke("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let _=M.filter(D=>D.op!=="not"),W=M.filter(D=>D.op==="and"),$=M.filter(D=>D.op==="or"),A=M.filter(D=>D.op==="not");if(_.length===0)return JSON.stringify(ke("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let G=M.filter(D=>D.regex).map(D=>{try{return new RegExp(D.pattern),null}catch(ie){return `${D.pattern}: ${ie.message}`}}).filter(D=>!!D);if(G.length>0)return JSON.stringify(ke("search","error",`search failed: invalid regex (${G[0]})`,void 0,{error:`Invalid regex: ${G.join("; ")}`}));let N=[];$.length>0&&N.push($.map(D=>D.pattern).join(" OR ")),W.length>0&&N.push(`AND ${W.map(D=>D.pattern).join(" + ")}`),A.length>0&&N.push(`NOT ${A.map(D=>D.pattern).join(" + ")}`);let U=N.join(" "),H=await Ux(),Ie=Math.min(200,Math.max(80,d*4+40));if(f.info("SEARCH",`Strategy: ${H?"ripgrep":"fallback"}`),!H)return JSON.stringify(ke("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
866
+ Please report this issue.`,{error:"ripgrep not available"}));if(y(),i==="files"){let D=await(async()=>{if(!R)return [Ue(w)];if(H){let Se=await sc();if(!Se)throw new Error("ripgrep not available (this should not happen)");let Ae=["--files"];c&&Ae.push("--hidden"),!E&&R&&Ae.push("--max-depth","1"),l&&Ae.push("-g",l),tc.forEach(Tt=>Ae.push("-g",Tt)),Ae.push("--",w);let pt=await Xe(Se,Ae,rt(),{signal:g});if(pt.exitCode!==0&&pt.exitCode!==1)throw new Error(pt.stderr||"rg files search failed");return pt.stdout.split(`
867
+ `).filter(Boolean).map(Tt=>{let $s=te__default.isAbsolute(Tt)?te__default.resolve(Tt):te__default.resolve(rt(),Tt);return Ue($s)})}let ue=l||"**/*",De=E?ue:ue.replace("**/","");return (await om(De,{cwd:w,absolute:!0,dot:c,onlyFiles:!0,ignore:tc.map(Se=>Se.replace("!",""))})).map(Se=>Ue(Se))})();y();let ie=M.map(ue=>{let De=ue.regex?ue.pattern:em(ue.pattern),Pe=ue.caseInsensitive?"i":"";return {query:ue,regex:new RegExp(De,Pe)}}),se=[],fe=0;for(let ue of D){y();let De=ue,Pe=ie.map(Me=>({op:Me.query.op,hit:Me.regex.test(De)})),Se=Pe.some(Me=>Me.op==="or"&&Me.hit),Ae=Pe.filter(Me=>Me.op==="and").every(Me=>Me.hit);!Pe.some(Me=>Me.op==="not"&&Me.hit)&&(W.length===0||Ae)&&($.length===0||Se)&&se.push(ue),fe++,fe%x===0&&await S();}let xe=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${U}`,`\u25B8 \u8DEF\u5F84: ${I}${E?" (\u9012\u5F52)":""}${L==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${se.length} \u4E2A\u6587\u4EF6`,""].filter(ue=>ue!==""),Re=50;return se.slice(0,Re).forEach(ue=>xe.push(` ${ue}`)),se.length>Re&&xe.push(` ... \u8FD8\u6709 ${se.length-Re} \u4E2A\u6587\u4EF6`),JSON.stringify(ke("search","success",se.length>0?`search files "${U}" (${se.length} files)`:`search files "${U}" (no matches)`,xe.join(`
868
+ `),{metadata:{mode:"files",strategy:H?"rg":"glob",regex:M.some(ue=>ue.regex),case_insensitive:u,path:I,resolved_from:L,files:se,queries:M}}))}let J=new Map,ye=new Map,pe=0,ce=A.map(D=>{let ie=D.regex?D.pattern:em(D.pattern),se=D.caseInsensitive?"i":"";return new RegExp(ie,se)}),Oe=[];if(H){let D=await sc();if(!D)throw new Error("ripgrep not available (this should not happen)");for(let ie of _){y();let se=["--json","--with-filename","--line-number","--column","-a"];se.push("-C",String(d)),ie.caseInsensitive&&se.push("-i"),ie.regex||se.push("-F"),c&&se.push("--hidden"),!E&&R&&se.push("--max-depth","1"),l&&se.push("-g",l),tc.forEach(Pe=>se.push("-g",Pe)),se.push("--",ie.pattern,w);let fe=`${D} ${se.join(" ")}`;Oe.push(fe);let xe="",Re=0,ue="";try{let Pe=await Xe(D,se,rt(),{signal:g});xe=Pe.stdout,ue=Pe.stderr||"",Re=Pe.exitCode;}catch(Pe){if(Pe?.name==="AbortError"||g?.aborted)throw Pe;ue=Pe?.message||Pe?.stderr||String(Pe),Re=Pe?.exitCode||2;}if(Re!==0&&Re!==1){let Pe=ue?`
869
+ Error: ${ue}`:"",Se=`
870
+ Command: ${D} ${se.join(" ")}`;throw new Error(`ripgrep failed (exit code ${Re})${Pe}${Se}`)}let De=0;for(let Pe of xe.split(`
871
+ `)){if(y(),De++,De%x===0&&await S(),!Pe.trim())continue;let Se;try{Se=JSON.parse(Pe);}catch{continue}if(Se.type==="summary"){let Bn=Se.data?.stats;Bn&&typeof Bn.searches=="number"&&(pe=Math.max(pe,Bn.searches));continue}let Ae=Se.type==="match",pt=Se.type==="context";if(!Ae&&!pt)continue;let Me=Se.data,Tt=Me?.path?.text,$s=Me?.line_number,pu=Me?.lines?.text,mu=Array.isArray(Me?.submatches)?Me.submatches[0]:void 0;if(!Tt||!$s||typeof pu!="string")continue;let hu=pu.replace(/\n$/,""),la=J.get(Tt)||new Map,Ns=la.get($s)||{line:hu,queryIds:new Set};if(Ns.line=hu,Ae){Ns.queryIds.add(ie.id),Ns.column===void 0&&mu?.start!==void 0&&(Ns.column=mu.start+1);let Bn=ye.get(Tt)||new Set;Bn.add(ie.id),ye.set(Tt,Bn);}la.set($s,Ns),J.set(Tt,la);}}}let _e=new Set(W.map(D=>D.id)),Q=[],be=0,Te=0,P=0,O=[],q=[],X=0;for(let[D,ie]of J.entries()){if(y(),be>=p&&!m)break;X++,X%x===0&&await S();let se=ye.get(D)||new Set,fe=!0;if(_e.forEach(Se=>{se.has(Se)||(fe=!1);}),!fe)continue;let Re=Array.from(ie.keys()).sort((Se,Ae)=>Se-Ae).filter(Se=>{let Ae=ie.get(Se);return Ae?!ce.some(pt=>pt.test(Ae.line)):!1});if(Re.length===0)continue;Te++,be+=Re.length;let ue=Ue(D);if(O.push({file:ue,anchor_lines:Re.slice(0,20),num_lines:Ie}),m){Q.push({file:D,matches:[],matchCount:Re.length});continue}y();let De=[];Array.from(ie.keys()).sort((Se,Ae)=>Se-Ae).forEach(Se=>{let Ae=ie.get(Se);if(!Ae)return;let pt=Re.includes(Se);if(De.push({lineNum:Se,line:Ae.line,isMatch:pt}),pt&&q.length<p){for(let Me of Ae.queryIds)if(q.push({file:ue,line:Se,column:Ae.column,preview:Ae.line,queryId:Me}),q.length>=p)break}}),Q.push({file:D,matches:De,matchCount:Re.length});}Q.sort((D,ie)=>Ue(D.file).localeCompare(Ue(ie.file)));let de=D=>{let se=Ue(D).split(te__default.sep),fe=se.findIndex(xe=>["src","lib","app","core","packages"].includes(xe));return fe>=0&&fe+1<se.length?se[fe+1]:se[0]||"root"},V=[`\u2713 \u641C\u7D22: ${U}`,`\u25B8 \u8DEF\u5F84: ${I}${E?" (\u9012\u5F52)":""}${L==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",H?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",pe>0?`\u6587\u4EF6: ${pe} \u5DF2\u641C\u7D22, ${Te} \u6709\u5339\u914D`:`\u6587\u4EF6: ${Te} \u6709\u5339\u914D`,`\u5339\u914D: ${be}${be>=p?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(D=>D!==""),re=new Map;for(let D of Q){let ie=de(D.file);re.set(ie,(re.get(ie)||0)+D.matchCount);}if(re.size>1){V.push(""),V.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let D=Array.from(re.entries()).sort((ie,se)=>se[1]-ie[1]);for(let[ie,se]of D.slice(0,5))V.push(` ${ie}: ${se}`);D.length>5&&V.push(` ... \u8FD8\u6709 ${D.length-5} \u4E2A\u6A21\u5757`);}if(V.push(""),m)V.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:"),Q.forEach(D=>{let ie=Ue(D.file),se=de(D.file);V.push(` [${se}] ${ie}: ${D.matchCount}`);});else for(let D of Q){if(y(),P>=p){V.push(`
872
+ ... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${p} \u4E0A\u9650)`);break}let ie=Ue(D.file),se=de(D.file);V.push(`
873
+ \u25B8 [${se}] ${ie} (${D.matchCount} \u5904)`),V.push("\u2500".repeat(50));let fe=-10;for(let xe of D.matches){if(P>=p)break;xe.lineNum>fe+1&&fe>0&&V.push(" \u2504\u2504\u2504");let Re=xe.isMatch?"\u25B6":" ";V.push(`${Re}${String(xe.lineNum).padStart(5)} \u2502 ${xe.line}`),fe=xe.lineNum,xe.isMatch&&P++;}}return Q.length===0?(V.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),V.push(""),V.push("\u{1F4A1} \u5EFA\u8BAE:"),V.push(" - \u5C1D\u8BD5 case_insensitive: true"),V.push(" - \u5C1D\u8BD5 recursive: true \u641C\u7D22\u5B50\u76EE\u5F55"),V.push(" - \u4F7F\u7528 keywords \u6216 queries \u7EC4\u5408\u641C\u7D22"),V.push(' - \u67E5\u6587\u4EF6\u540D\u8BF7\u7528 mode="files"')):O.length>0&&(V.push(""),V.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),O.slice(0,3).forEach(D=>{V.push(` readfile(path="${D.file}", anchor_lines=[${D.anchor_lines.join(",")}], num_lines=${D.num_lines})`);})),JSON.stringify(ke("search","success",Q.length>0?`search "${U}" (${be} matches)`:`search "${U}" (no matches)`,V.join(`
874
+ `),{metadata:{mode:"content",strategy:H?"rg":"fallback",regex:M.some(D=>D.regex),case_insensitive:u,path:I,resolved_from:L,queries:M,matches:q,read_hints:O,files_with_matches:Te,command:Oe.length>0?Oe[0]:void 0}}))}catch(g){return JSON.stringify(ke("search","error",`search failed: ${g.message}`,void 0,{error:g.message}))}}},Pm=[cm,um,hm,fm,gm,dm,pm,mm,vm,xm,Sm,_m,Tm,wm,km,Cm,Em,ym,bm,Fp,Im,Rm,El,Il,Rl,Wp];Bx=[...Pm,Wl];});var Lr={};Fs(Lr,{SafeTTYWriter:()=>bo,SignalCategory:()=>Lm,safeTTYWriter:()=>Gx,setupCommonSignals:()=>Wx,signalManager:()=>en});function Wx(s){en.initialize(),s.onSIGINT&&en.register("SIGINT",s.onSIGINT,"user_interrupt"),s.onSIGTERM&&en.register("SIGTERM",s.onSIGTERM,"process_control"),s.onSIGHUP&&en.register("SIGHUP",s.onSIGHUP,"terminal_disconnect"),s.onSIGUSR1&&en.register("SIGUSR1",s.onSIGUSR1,"custom_recovery"),s.onSIGUSR2&&en.register("SIGUSR2",s.onSIGUSR2,"custom_recovery"),s.onSIGCONT&&en.register("SIGCONT",s.onSIGCONT,"process_control"),s.onSIGTSTP&&en.register("SIGTSTP",s.onSIGTSTP,"process_control");}var Lm,cc,en,bo,Gx,Or=K(()=>{le();Lm=(i=>(i.TTY_CONTROL="tty_control",i.TERMINAL_DISCONNECT="terminal_disconnect",i.PROCESS_CONTROL="process_control",i.USER_INTERRUPT="user_interrupt",i.CUSTOM_RECOVERY="custom_recovery",i))(Lm||{}),cc=class{handlers=new Map;initialized=false;isInForeground=true;initialize(){if(this.initialized){f.warn("SIGNAL","SignalManager already initialized");return}f.info("SIGNAL","Initializing SignalManager"),this.setupTTYControlSignals(),this.initialized=true;}setupTTYControlSignals(){if(process.platform==="win32"){f.debug("SIGNAL","Windows platform, skipping POSIX TTY signals");return}try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),f.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) set to ignore");}catch(e){f.error("SIGNAL","Failed to setup TTY control signals",{error:e.message});}}register(e,t,n){this.initialized||(f.warn("SIGNAL",`Registering ${e} before initialization`),this.initialize()),this.handlers.has(e)||(this.handlers.set(e,[]),process.on(e,async()=>{let r=this.handlers.get(e)||[];f.debug("SIGNAL",`Received ${e}, executing ${r.length} handlers`);for(let i of r)try{await i();}catch(o){f.error("SIGNAL",`Handler failed for ${e}`,{error:o.message});}})),this.handlers.get(e).push(t),f.debug("SIGNAL",`Registered handler for ${e} (category: ${n})`);}unregister(e,t){let n=this.handlers.get(e);if(!n)return;let r=n.indexOf(t);r!==-1&&(n.splice(r,1),f.debug("SIGNAL",`Unregistered handler for ${e}`)),n.length===0&&(this.handlers.delete(e),process.removeAllListeners(e),f.debug("SIGNAL",`Removed all listeners for ${e}`));}unregisterAll(){for(let e of this.handlers.keys())process.removeAllListeners(e);this.handlers.clear(),f.info("SIGNAL","Unregistered all signal handlers");}checkForeground(){if(process.platform==="win32")return true;try{let e=process.pid,t=process.getpgid?.(e)??e;return process.stdin.isTTY?(this.isInForeground=!0,!0):!1}catch{return true}}getRegisteredSignals(){return Array.from(this.handlers.keys())}reset(){this.unregisterAll(),this.initialized=false,f.info("SIGNAL","SignalManager reset");}},en=new cc,bo=class s{static instance;static getInstance(){return s.instance||(s.instance=new s),s.instance}writeStdout(e){try{return process.stdout.destroyed||!process.stdout.writable?!1:(process.stdout.write(e),!0)}catch(t){return process.env.CLI_DEBUG==="1"&&f.debug("TTY","stdout write failed",{error:t.message}),false}}writeStderr(e){try{return process.stderr.destroyed||!process.stderr.writable?!1:(process.stderr.write(e),!0)}catch(t){return process.env.CLI_DEBUG==="1"&&f.debug("TTY","stderr write failed",{error:t.message}),false}}safeWriteStdout(e,t){let n=this.writeStdout(e);return !n&&t?.fallbackToStderr?this.writeStderr(e):(!n&&t?.onError&&t.onError(new Error("Failed to write to stdout")),n)}},Gx=bo.getInstance();});var jm={};Fs(jm,{default:()=>oS});var oS,Gm=K(()=>{oS={};});var Km=Us((LA,pS)=>{pS.exports={single:{topLeft:"\u250C",top:"\u2500",topRight:"\u2510",right:"\u2502",bottomRight:"\u2518",bottom:"\u2500",bottomLeft:"\u2514",left:"\u2502"},double:{topLeft:"\u2554",top:"\u2550",topRight:"\u2557",right:"\u2551",bottomRight:"\u255D",bottom:"\u2550",bottomLeft:"\u255A",left:"\u2551"},round:{topLeft:"\u256D",top:"\u2500",topRight:"\u256E",right:"\u2502",bottomRight:"\u256F",bottom:"\u2500",bottomLeft:"\u2570",left:"\u2502"},bold:{topLeft:"\u250F",top:"\u2501",topRight:"\u2513",right:"\u2503",bottomRight:"\u251B",bottom:"\u2501",bottomLeft:"\u2517",left:"\u2503"},singleDouble:{topLeft:"\u2553",top:"\u2500",topRight:"\u2556",right:"\u2551",bottomRight:"\u255C",bottom:"\u2500",bottomLeft:"\u2559",left:"\u2551"},doubleSingle:{topLeft:"\u2552",top:"\u2550",topRight:"\u2555",right:"\u2502",bottomRight:"\u255B",bottom:"\u2550",bottomLeft:"\u2558",left:"\u2502"},classic:{topLeft:"+",top:"-",topRight:"+",right:"|",bottomRight:"+",bottom:"-",bottomLeft:"+",left:"|"},arrow:{topLeft:"\u2198",top:"\u2193",topRight:"\u2199",right:"\u2190",bottomRight:"\u2196",bottom:"\u2191",bottomLeft:"\u2197",left:"\u2192"}};});var Ym=Us((OA,vc)=>{var Vm=Km();vc.exports=Vm;vc.exports.default=Vm;});var ig={};Fs(ig,{runExecuteShellWorker:()=>s0});function YT(s){let e={};for(let[t,n]of Object.entries(s))typeof n=="string"&&(e[t]=n);return e}function rg(){if(oa.value)return oa.value;let s=YT(process.env),e=s;if(process.platform==="win32")return oa.value=e,e;try{let t=process.env.SHELL||"/bin/zsh",n=execaSync(t,["-ilc","env"],{env:s,timeout:3e3,stdio:["ignore","pipe","ignore"]}),r={};n.stdout.split(`
875
+ `).forEach(i=>{let o=i.indexOf("=");if(o>0){let a=i.slice(0,o),l=i.slice(o+1);r[a]=l;}}),e={...r,...s,PATH:r.PATH||s.PATH||"",JAVA_HOME:r.JAVA_HOME||s.JAVA_HOME||"",MAVEN_HOME:r.MAVEN_HOME||s.MAVEN_HOME||"",M2_HOME:r.M2_HOME||s.M2_HOME||"",NODE_PATH:r.NODE_PATH||s.NODE_PATH||"",GOPATH:r.GOPATH||s.GOPATH||"",CARGO_HOME:r.CARGO_HOME||s.CARGO_HOME||"",RUSTUP_HOME:r.RUSTUP_HOME||s.RUSTUP_HOME||"",PYENV_ROOT:r.PYENV_ROOT||s.PYENV_ROOT||"",CONDA_PREFIX:r.CONDA_PREFIX||s.CONDA_PREFIX||""};}catch(t){f.warn("SHELL_WORKER","Failed to load shell environment",{error:t?.message||t}),e=s;}return oa.value=e,e}function aa(s,e){return {success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
876
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
877
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${e}
878
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
879
+
880
+ \u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
881
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:false}}function XT(s,e,t,n){let r=n.length>3e3?n.slice(0,3e3)+`
882
+ ... (\u8F93\u51FA\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:n,i=t?`\u2022 \u8FDB\u7A0B ID (PID): ${t}
883
+ `:"";return {success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
884
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
885
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${e}
886
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
887
+
888
+ \u2705 \u540E\u53F0\u8FDB\u7A0B\u5DF2\u6210\u529F\u542F\u52A8\u5E76\u6301\u7EED\u8FD0\u884C\u4E2D
889
+ ${i}\u2022 \u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: 0
890
+
891
+ \u{1F525} \u91CD\u8981\u63D0\u793A:
892
+ - \u6B64\u8FDB\u7A0B\u5C06\u6301\u7EED\u5728\u540E\u53F0\u8FD0\u884C\uFF0C\u76F4\u5230\u4E3B\u52A8\u7EC8\u6B62\u6216\u9047\u5230\u9519\u8BEF
893
+ - \u65E0\u9700\u518D\u6B21\u542F\u52A8\u76F8\u540C\u547D\u4EE4\uFF08\u81EA\u52A8\u53BB\u91CD\u673A\u5236\u4F1A\u62D2\u7EDD\u91CD\u590D\u542F\u52A8\uFF09
894
+ - \u8FDB\u7A0B\u5DF2\u52A0\u5165\u8FDB\u7A0B\u7BA1\u7406\u5668\u8FFD\u8E2A\uFF0C\u53EF\u968F\u65F6\u67E5\u770B\u72B6\u6001
895
+
896
+ \u25E6 \u542F\u52A8\u65E5\u5FD7 (\u524D 8 \u79D2):
897
+ ${r||"(\u6682\u65E0\u8F93\u51FA)"}
898
+
899
+ \u{1F4CC} \u8FDB\u7A0B\u7BA1\u7406\u547D\u4EE4:
900
+ - /processes - \u67E5\u770B\u6240\u6709\u540E\u53F0\u8FDB\u7A0B\u72B6\u6001
901
+ - /kill ${t??"<pid>"} - \u7EC8\u6B62\u6B64\u8FDB\u7A0B
902
+ - lsof -i :\u7AEF\u53E3\u53F7 - \u68C0\u67E5\u7AEF\u53E3\u5360\u7528
903
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:true,pid:t}}function ZT(s,e,t){return {success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
904
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
905
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${e}
906
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
907
+
908
+ \u2717 \u540E\u53F0\u542F\u52A8\u5931\u8D25:
909
+ ${t}
910
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:true}}function QT(s,e,t,n,r){let i=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
911
+ `;return i+=`\u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
912
+ `,i+=`\u25B8 \u6267\u884C\u547D\u4EE4: ${e}
913
+ `,i+=`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
914
+
915
+ `,t===0?i+=`\u2713 \u6267\u884C\u6210\u529F (\u9000\u51FA\u7801: 0)
916
+
917
+ `:i+=`! \u6267\u884C\u5B8C\u6210\u4F46\u6709\u9519\u8BEF (\u9000\u51FA\u7801: ${t})
918
+
919
+ `,n&&(i+=`\u25E6 \u6807\u51C6\u8F93\u51FA (stdout):
920
+ ${n}
921
+
922
+ `),r&&(i+=`\u25E6 \u9519\u8BEF\u8F93\u51FA (stderr):
923
+ ${r}
924
+
925
+ `),!n&&!r&&(i+=`(\u65E0\u8F93\u51FA)
926
+
927
+ `),i+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",{success:true,output:i,background:false,exitCode:t}}function e0(s,e){return {success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
928
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
929
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${e}
930
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
931
+
932
+ \u2717 \u547D\u4EE4\u6267\u884C\u8D85\u65F6 (120\u79D2)
933
+
934
+ \u5EFA\u8BAE:
935
+ 1. \u8FD9\u53EF\u80FD\u662F\u4E00\u4E2A\u957F\u671F\u8FD0\u884C\u7684\u8FDB\u7A0B\uFF08\u5F00\u53D1\u670D\u52A1\u5668\u7B49\uFF09
936
+ 2. \u4F7F\u7528 background=true \u53C2\u6570\u5728\u540E\u53F0\u8FD0\u884C: {"command": "${e}", "background": true}
937
+ 3. \u6216\u8005\u4F7F\u7528\u66F4\u5177\u4F53\u7684\u547D\u4EE4\u51CF\u5C11\u6267\u884C\u65F6\u95F4
938
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:false}}function t0(s,e,t){return {success:true,output:`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
939
+ \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${s}
940
+ \u25B8 \u6267\u884C\u547D\u4EE4: ${e}
941
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
942
+
943
+ \u2717 \u6267\u884C\u5931\u8D25:
944
+ ${t.message}
945
+
946
+ ${t.stdout?`\u25E6 \u90E8\u5206\u8F93\u51FA:
947
+ ${t.stdout}
948
+
949
+ `:""}
950
+ ${t.stderr?`\u25E6 \u9519\u8BEF\u4FE1\u606F:
951
+ ${t.stderr}
952
+
953
+ `:""}
954
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`,background:false}}function Ds(s){if(s)try{process.kill(-s,"SIGTERM");}catch{try{process.kill(s,"SIGTERM");}catch{}}}async function n0(s){let{command:e,background:t,workspaceRoot:n}=s;if(Os=false,t)try{let r=execa(e,{shell:!0,cwd:n,detached:!0,stdio:["ignore","pipe","pipe"],env:rg()});Ot=r,r.unref();let i=r.pid,o=[],a=8e3;r.stdout?.on("data",d=>{o.push(d.toString());}),r.stderr?.on("data",d=>{o.push(d.toString());});let l=new Promise((d,p)=>{let m=setTimeout(()=>{clearInterval(h),d();},a),h=setInterval(()=>{Os&&(clearTimeout(m),clearInterval(h),p(new Error("Command interrupted by user")));},50);h.unref?.();});try{await l;}catch{return Ds(i),aa(n,e)}let c=o.join(""),u=XT(n,e,i,c);return r.on("exit",d=>{Ot=null,process.send&&i&&process.send({type:"background_exit",pid:i,exitCode:d??0}),process.exit(0);}),u}catch(r){return ZT(n,e,r.message)}try{let r=execa(e,{shell:!0,timeout:12e4,cwd:n,reject:!1,env:rg()});Ot=r;let i=new Promise((l,c)=>{let u=setInterval(()=>{Os&&(clearInterval(u),r.pid&&Ds(r.pid),c(new Error("Aborted by user")));},100);u.unref?.();}),o;try{o=await Promise.race([r,i]);}catch(l){if(l?.message==="Aborted by user")return Ot=null,aa(n,e);throw l}let a=r.pid;return Os?(a&&Ds(a),Ot=null,aa(n,e)):(Ot=null,QT(n,e,o.exitCode??0,o.stdout||"",o.stderr||""))}catch(r){return Os?(r?.pid&&Ds(r.pid),aa(n,e)):r?.timedOut?e0(n,e):t0(n,e,r)}finally{Ot=null;}}async function s0(){process.env[VT]==="execute_shell"&&(process.on("message",async s=>{if(!(!s||typeof s!="object")){if(s.type==="abort"){Os=true,Ot?.pid&&Ds(Ot.pid);return}if(s.type==="execute_shell")try{let e=await n0(s.payload);process.send&&process.send({type:"result",...e}),e.background||process.exit(0);}catch(e){let t={success:false,output:`execute_shell worker failed: ${e?.message||e}`,background:false};process.send&&process.send({type:"result",...t}),process.exit(1);}}}),process.on("disconnect",()=>{Ot?.pid&&Ds(Ot.pid),process.exit(1);}),process.send&&process.send({type:"ready",pid:process.pid}));}var VT,Ot,Os,oa,og=K(()=>{le();VT="NEOX_WORKER",Ot=null,Os=false,oa={value:null};});le();function li(s){return {output_info:s,behavior:{type:"allow"}}}function vu(s,e){return {output_info:e,behavior:{type:"reject_content",message:s}}}function Bs(s){return {type:"message",data:s}}function Gn(){let s=new Date,e=s.toISOString().slice(0,10).replace(/-/g,""),t=s.toISOString().slice(11,19).replace(/:/g,""),n=Math.random().toString(36).slice(2,6);return `session_${e}_${t}_${n}`}function xg(s){let e=s.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=s.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function Sg(s){let e=s.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=s.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let n=s.match(/Error\s+code\s+(\d{3})/i);if(n){let i=n[1];return {502:"Bad gateway",503:"Service unavailable",504:"Gateway timeout",520:"Unknown error",521:"Web server is down",522:"Connection timed out",523:"Origin is unreachable",524:"A timeout occurred"}[i]||"Server error"}let r=s.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return r?r[1].trim():null}function _g(s){let e=s.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=s.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function js(s){return s.trim().startsWith("<!DOCTYPE html")||s.trim().startsWith("<html")||/<html[^>]*>/i.test(s)}function Tg(s){let e=s.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Cn(s,e){let t=Tg(s);if(t)try{let o=JSON.parse(t);if(o.error){let a=o.error,l=a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),c=a.message||"API error",u;if(a.type==="usage_limit_reached"){let d=a.resets_at?new Date(a.resets_at*1e3).toLocaleString():void 0,p=a.resets_in_seconds;if(p){let m=Math.floor(p/3600),h=Math.floor(p%3600/60);u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets in ${m}h ${h}m.`;}else d&&(u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets at ${d}.`);}return {code:l,message:c,detail:u}}}catch{}if(s.trim().startsWith("{"))try{let o=JSON.parse(s);if(o.error){let a=o.error;return {code:a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),message:a.message||"API error"}}}catch{}if(js(s)){let o=xg(s)||String(e||"UNKNOWN"),a=Sg(s)||"Server error",l=_g(s),c;return l&&(l.includes("cloudflare")?c=`The server (${l}) is protected by Cloudflare but is not responding.`:c=`The API server (${l}) is not responding. This may be a temporary issue with your API provider.`),{code:`HTTP_${o}`,message:a,detail:c}}let n=s.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let o=n[1],a=n[2];if(js(a)){let l=Cn(a,parseInt(o,10));return {code:l.code,message:l.message,detail:l.detail}}return a=a.trim(),a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${o}`,message:a}}let r=s.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(r){let o=r[1],a=r[2].trim();return a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${o}`,message:a}}if(s.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(s.includes("ETIMEDOUT")||s.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(s.includes("ENOTFOUND"))return {code:"DNS_ERROR",message:"Server not found",detail:"Could not resolve the API server address. Please check your API base URL."};if(/context.*window.*exceeded/i.test(s)||/maximum.*context.*length/i.test(s))return {code:"CONTEXT_EXCEEDED",message:"Context window exceeded",detail:"The conversation is too long. Please start a new session or use /compact."};if(/rate.*limit/i.test(s)||s.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(s.includes("401")||/unauthorized/i.test(s))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(s.includes("403")||/forbidden/i.test(s))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let i=s;return i=i.replace(/^Error:\s*/i,""),i=i.replace(/^Request failed with status code\s+\d+:\s*/i,""),i.length>300&&(i=i.slice(0,300)+"..."),{code:e?`HTTP_${e}`:"UNKNOWN",message:i}}var we=class s extends Error{category;code;retryable;retryAfter;context;originalError;constructor(e){super(e.message),this.name="NeoxError",this.category=e.category,this.code=e.code,this.retryable=e.retryable,this.retryAfter=e.retryAfter,this.context=e.context,this.originalError=e.originalError,Error.captureStackTrace&&Error.captureStackTrace(this,s);}withContext(e){return new s({...this,context:{...this.context,...e}})}toJSON(){return {name:this.name,category:this.category,code:this.code,message:this.message,retryable:this.retryable,retryAfter:this.retryAfter,context:this.context,stack:this.stack}}};function Jt(s){if(!s)return;if(typeof s!="string")return typeof s=="number"&&s>0?Math.ceil(s*1e3):void 0;let e=s.trim(),t=e.match(/^(\d+(?:\.\d+)?)\s*ms$/i);if(t){let i=parseFloat(t[1]);return i>0?Math.ceil(i):void 0}let n=parseFloat(e);if(!isNaN(n)&&n>0)return Math.ceil(n*1e3);let r=new Date(e);if(!isNaN(r.getTime())){let i=r.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}function wg(s){switch(s){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function ci(s){if(!s)return;let e=s["retry-after"]||s["Retry-After"];if(e){let i=Jt(e);if(i)return i}let t=s["retry-after-ms"]||s["Retry-After-Ms"];if(t){let i=parseFloat(t);if(!isNaN(i)&&i>0)return Math.ceil(i)}let n=s["x-ratelimit-reset-requests"];if(n){let i=Jt(n);if(i)return i}let r=s["anthropic-ratelimit-requests-reset"];if(r){let i=new Date(r);if(!isNaN(i.getTime())){let o=i.getTime()-Date.now();return o>0?Math.ceil(o):void 0}}}function ha(s){return typeof s=="object"&&s!==null&&"message"in s&&typeof s.message=="string"}function xu(s){return [/context.*window.*exceeded/i,/context.*length.*exceeded/i,/maximum.*context.*length/i,/token.*limit.*exceeded/i,/input.*too.*long/i].some(t=>t.test(s))}function kg(s){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(s))}function Cg(s){if(s){if(typeof s=="string")return s;if(typeof s=="object"){if(typeof s.error=="string")return s.error;if(s.error?.message)return s.error.message;if(s.message)return s.message}}}function mt(s){if(s instanceof we)return s;let e=s instanceof Error?s.message:String(s),t=s instanceof Error?s:void 0,n=ha(s)?s:void 0,i=(n?Cg(n.response?.data):void 0)||e;if(n?.response?.status){let o=n.response.status,a=ci(n.response.headers),l=n.response.headers?.["x-request-id"]||n.response.headers?.["cf-ray"];if(o===429){let c=n.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new we({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:o,requestId:l},originalError:t}):new we({category:"retryable_http",code:`HTTP_${o}`,message:i,retryable:true,retryAfter:a,context:{httpStatus:o,requestId:l},originalError:t})}if(o===502||o===503||o===504){let c=i;if(js(i)){let d=Cn(i,o);c=d.message,d.detail&&(c+=`
955
+ `+d.detail);}let u=a||wg(o);return new we({category:"retryable_rate_limit",code:`PROXY_${o}`,message:c||`API \u4EE3\u7406\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528 (${o})`,retryable:true,retryAfter:u,context:{httpStatus:o,requestId:l,rawMessage:i},originalError:t})}if(o>=500){let c=i;if(js(i)){let u=Cn(i,o);c=u.message,u.detail&&(c+=`
956
+ `+u.detail);}return new we({category:"retryable_http",code:`HTTP_${o}`,message:c,retryable:true,retryAfter:a,context:{httpStatus:o,requestId:l,rawMessage:i},originalError:t})}if(o===401)return new we({category:"fatal_auth",code:"UNAUTHORIZED",message:i||"Authentication failed. Please check your API key.",retryable:false,context:{httpStatus:o,requestId:l},originalError:t});if(o===403)return new we({category:"fatal_auth",code:"FORBIDDEN",message:i||"Access denied. Please check your API permissions.",retryable:false,context:{httpStatus:o,requestId:l},originalError:t});if(o===400)return xu(e)?new we({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,context:{httpStatus:o,requestId:l},originalError:t}):i.includes("Upstream request failed")||i.includes("upstream")||i.includes("gateway")?new we({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:i||"Proxy upstream request failed",retryable:true,context:{httpStatus:o,requestId:l},originalError:t}):new we({category:"fatal_invalid",code:"INVALID_REQUEST",message:i,retryable:false,context:{httpStatus:o,requestId:l},originalError:t});if(o>=400&&o<500)return new we({category:"fatal_invalid",code:`HTTP_${o}`,message:i,retryable:false,context:{httpStatus:o,requestId:l},originalError:t})}if(ha(s)){let o=s.code,a=s.name;if(o==="ERR_CANCELED"||a==="CanceledError"||a==="AbortError")return new we({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ECONNRESET")return new we({category:"retryable_network",code:o,message:`Network error: ${e}`,retryable:true,originalError:t});if(o==="ETIMEDOUT"||o==="ESOCKETTIMEDOUT")return new we({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return s instanceof Error&&s.name==="AbortError"?new we({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:s}):ha(s)&&s.code==="STREAM_INCOMPLETE"?new we({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:s.toolName,rawMessage:e},originalError:t}):s?.code==="STREAM_TIMEOUT"?new we({category:"retryable_stream",code:"STREAM_TIMEOUT",message:`API \u4EE3\u7406\u54CD\u5E94\u8D85\u65F6: ${e}`,retryable:true,context:{rawMessage:e},originalError:t}):e.includes("stream")||e.includes("Stream")||e.includes("SSE")||e.includes("disconnected")||e.includes("incomplete")||e.includes("message_stop")?new we({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):xu(e)?new we({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):kg(e)?new we({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new we({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function Su(s,e,t){let n=e||"";return n.trim().endsWith("}")?(s==="write_file"||s==="edit_file")&&!n.includes('"content"')?new we({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new we({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t}):new we({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:s},originalError:t}):new we({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:s,receivedLength:n.length,rawMessage:t.message},originalError:t})}function ui(s){switch(s.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${s.retryAfter?Math.ceil(s.retryAfter/1e3):3} \u79D2\u540E\u81EA\u52A8\u91CD\u8BD5...`;case "retryable_http":return "The request will be automatically retried.";case "retryable_stream":return "\u7F51\u7EDC\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8FDE...";case "retryable_network":return "\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5...";case "fatal_auth":return "Please check your API key and ensure it has the necessary permissions.";case "fatal_limit":return "You have reached your usage limit. Please check your billing settings or wait for the limit to reset.";case "fatal_context":return "The conversation is too long. Please start a new conversation or use /compact to summarize history.";case "fatal_invalid":return "Please check your request parameters and try again.";case "tool_truncated":return "The tool call was truncated. Please use edit_file with smaller, targeted changes instead of rewriting entire files.";case "tool_json_invalid":return "The tool arguments were invalid. The LLM will retry with corrected parameters.";case "tool_timeout":return "The tool execution timed out. Please try again with a smaller operation.";case "tool_denied":return "The tool call was denied. You can manually approve or adjust permissions.";default:return "An unexpected error occurred. Please try again."}}var zt={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function dn(s,e){return {...zt,...s,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var un={openai:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},anthropic:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5},yunwu:{requestMaxRetries:3,streamMaxRetries:10,streamIdleTimeoutMs:9e4},azure:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:6e5},proxy:{requestMaxRetries:10,streamMaxRetries:10,streamIdleTimeoutMs:18e4},gemini:{requestMaxRetries:4,streamMaxRetries:5,streamIdleTimeoutMs:3e5}};function Wn(s,e){let t=s.toLowerCase();if(t.includes("yunwu"))return un.yunwu;if(t.includes("azure"))return un.azure;if(e){let n=e.toLowerCase();if(n.includes("yunwu"))return un.yunwu;if(n.includes("azure"))return un.azure;if(!(n.includes("api.anthropic.com")||n.includes("api.openai.com")))return un.proxy}return t.includes("anthropic")?un.anthropic:t.includes("gemini")?un.gemini:un.openai}var _u=100,Tu=200,wu=1800*1e3;var Gs=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},Hn=class extends Gs{guardrail_result;constructor(e){let t=`Input guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Safety check failed"}`;super(t),this.name="InputGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info}}},Jn=class extends Gs{guardrail_result;blocked_output;constructor(e){let t=`Output guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Output safety check failed"}`;super(t),this.name="OutputGuardrailTripwireTriggered",this.guardrail_result=e,this.blocked_output=e.agent_output;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,blocked_output:this.blocked_output}}},ht=class extends Gs{guardrail_result;constructor(e){let t=`Tool guardrail "${e.guardrail.name}" triggered: ${e.output.output_info?.reason||"Tool safety check failed"}`;super(t),this.name="ToolGuardrailTripwireTriggered",this.guardrail_result=e;}getDetails(){return {guardrail_name:this.guardrail_result.guardrail.name,execution_time_ms:this.guardrail_result.execution_time_ms,output_info:this.guardrail_result.output.output_info,behavior:this.guardrail_result.output.behavior}}};var En=class{static async runInputGuardrails(e,t,n,r){if(e.length===0)return [];let i=e.map(async o=>{let a=Date.now();try{let l=await o.guardrail_function(t,n,r),c={guardrail:o,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Hn(c);return c}catch(l){if(l instanceof Hn)throw l;let c={guardrail:o,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-a};throw new Hn(c)}});return await Promise.all(i)}static async runOutputGuardrails(e,t,n,r){if(e.length===0)return [];let i=e.map(async o=>{let a=Date.now();try{let l=await o.guardrail_function(t,n,r),c={guardrail:o,agent_output:r,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Jn(c);return c}catch(l){if(l instanceof Jn)throw l;let c={guardrail:o,agent_output:r,output:{tripwire_triggered:true,output_info:{error:l instanceof Error?l.message:String(l),reason:"Guardrail execution failed"}},execution_time_ms:Date.now()-a};throw new Jn(c)}});return await Promise.all(i)}static async runToolInputGuardrails(e,t){let n=[];for(let r of e){let i=Date.now();try{let o=await r.guardrail_function(t),a={guardrail:r,output:o,execution_time_ms:Date.now()-i};if(n.push(a),o.behavior.type==="raise_exception")throw new ht(a);if(o.behavior.type==="reject_content")return {results:n,should_execute:!1,rejection_message:o.behavior.message}}catch(o){if(o instanceof ht)throw o;let a={guardrail:r,output:{output_info:{error:o instanceof Error?o.message:String(o)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-i};throw new ht(a)}}return {results:n,should_execute:true}}static async runToolOutputGuardrails(e,t){let n=[];for(let r of e){let i=Date.now();try{let o=await r.guardrail_function(t),a={guardrail:r,output:o,execution_time_ms:Date.now()-i};if(n.push(a),o.behavior.type==="raise_exception")throw new ht(a);if(o.behavior.type==="reject_content")return {results:n,should_use_output:!1,replacement_message:o.behavior.message}}catch(o){if(o instanceof ht)throw o;let a={guardrail:r,output:{output_info:{error:o instanceof Error?o.message:String(o)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-i};throw new ht(a)}}return {results:n,should_use_output:true}}};var ku=null,Cu=false;function Ws(){if(!Cu&&(Cu=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(le(),$e)).then(s=>{ku=s.cliLogger;}).catch(()=>{});}catch{}return ku}var Eu=new WeakMap,fa=null;function Iu(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function Ru(s){if(s){let e=Eu.get(s);return e?process.env.CLI_DEBUG==="1"&&Ws()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(s).join(",")}, history: ${e.toolCallHistory.length}`):(e=Iu(),Eu.set(s,e),process.env.CLI_DEBUG==="1"&&Ws()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(s).join(",")}`)),e}return fa||(fa=Iu()),fa}function ga(s,e,t,n){let r=Ru(s);if(process.env.CLI_DEBUG==="1"){let i=Ws();i?.debug("SESSION","recordToolCall called:"),i?.debug("SESSION",` - tool: ${e}`),i?.debug("SESSION",` - success: ${n}`),i?.debug("SESSION",` - context exists: ${!!s}`),i?.debug("SESSION",` - context identity: ${s?Object.keys(s).join(","):"none"}`),i?.debug("SESSION",` - history length before: ${r.toolCallHistory.length}`);}r.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:n}),process.env.CLI_DEBUG==="1"&&Ws()?.debug("SESSION",` - history length after: ${r.toolCallHistory.length}`),r.toolCallHistory.length>100&&r.toolCallHistory.shift();}function Pu(s,e=10){let t=Ru(s);if(process.env.CLI_DEBUG==="1"){let n=Ws();n?.debug("SESSION","getRecentToolCalls called:"),n?.debug("SESSION",` - context exists: ${!!s}`),n?.debug("SESSION",` - context identity: ${s?Object.keys(s).join(","):"none"}`),n?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),n?.debug("SESSION",` - limit: ${e}`),n?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var Ag=fileURLToPath(import.meta.url),va=dirname(Ag),xa=class{logDir;enabled;consoleEnabled;constructor(){this.logDir=this.getLogDirectory(),this.enabled=process.env.MARKOR_TRACING==="1",this.consoleEnabled=process.env.CLI_DEBUG_CONSOLE==="1";try{this.initLogDir(),this.consoleEnabled&&console.log("[Logger] Initialized at:",this.logDir);}catch(e){console.error("[Logger] Failed to initialize:",e.message),this.enabled=false;}}setEnabled(e){this.enabled=e;}getLogDirectory(){if(va.includes(".asar")||va.includes("app.asar")){try{let{app:e}=Ou();if(e&&e.getPath){let t=e.getPath("userData");return te__default.join(t,"logs")}}catch{}return te__default.join(ti__default.tmpdir(),"neox-logs")}return te__default.join(va,"../../logs")}initLogDir(){try{an__default.existsSync(this.logDir)||an__default.mkdirSync(this.logDir,{recursive:!0});}catch(e){let t=e;t.code==="EACCES"||t.code==="EPERM"?this.enabled=false:(console.warn(`[Logger] Warning: Cannot create log directory: ${t.message}`),this.enabled=false);}}getLogFile(e){let t=new Date().toISOString().split("T")[0];return te__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let n=new Date().toISOString(),r=typeof t=="string"?{message:t}:t||{},i=this.safeStringify({timestamp:n,...r})+`
957
+ `;if(this.enabled)try{let o=this.getLogFile(e);an__default.appendFileSync(o,i,"utf-8");}catch(o){(o.code==="EACCES"||o.code==="EPERM")&&(this.enabled=false);}}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return "[Circular]";t.add(r);}return n==="parser"||n==="socket"||n==="_httpMessage"||n==="req"||n==="res"?"[Omitted]":r&&r.type==="Buffer"&&Array.isArray(r.data)?"[Buffer]":typeof r=="function"?"[Function]":r})}llmRequest(e,t,n,r,i){let o=n.tools?.map(a=>({name:a.name,description:a.description,parameters:a.parameters}));this.write("llm",{type:"REQUEST",provider:e,model:t,url:r,headers:i,messagesCount:n.messages?.length||0,messages:n.messages,toolsCount:n.tools?.length||0,tools:o,temperature:n.temperature});}llmResponse(e,t,n,r){this.write("llm",{type:"RESPONSE",provider:e,duration:`${t}ms`,usage:n,finishReason:r.finish_reason,content:r.content,contentLength:r.content?.length||0,toolCallsCount:r.tool_calls?.length||0,toolCalls:r.tool_calls});}llmError(e,t){let n={type:"ERROR",provider:e,error:t.message,status:t.response?.status};if(t.response?.data)try{let r=t.response.data;typeof r=="string"?n.data=r:typeof r=="object"&&(n.data={error:r.error,message:r.message,type:r.type,code:r.code});}catch{n.data="[Could not serialize response data]";}this.write("llm",n);}agentStart(e){this.write("agent",{type:"START",task:e});}agentIteration(e,t){this.write("agent",{type:"ITERATION",iteration:e,action:t});}agentComplete(e,t,n){this.write("agent",{type:"COMPLETE",iterations:e,toolCalls:t,usage:n});}agentError(e){this.write("agent",{type:"ERROR",error:e});}toolCall(e,t){this.write("tool",{type:"CALL",tool:e,args:t});}toolResult(e,t,n,r){this.write("tool",{type:"RESULT",tool:e,success:t,resultLength:n,duration:`${r}ms`});}toolError(e,t){this.write("tool",{type:"ERROR",tool:e,error:t});}},oe=new xa;function Du(s,e){let t=s||"Unknown error",n=t.toLowerCase(),r=e?.providerName?.trim()||"LLM";if(n.includes("timeout")){let i=Math.round((e?.timeoutMs??12e4)/1e3);return [`\u23F1\uFE0F ${r} \u8BF7\u6C42\u8D85\u65F6 (${i}s)\u3002${r} \u63A5\u53E3\u5F53\u524D\u53EF\u80FD\u4E0D\u7A33\u5B9A\uFF0C\u53EF\u4EE5\u7A0D\u540E\u91CD\u8BD5\u6216\u5207\u6362\u5176\u4ED6\u6A21\u578B\u3002`,"\u5982\u679C\u591A\u6B21\u8D85\u65F6\u8BF7\u544A\u8BC9\u6211\u4EEC\uFF0C\u65B9\u4FBF\u6392\u67E5\u3002",`\u539F\u59CB\u9519\u8BEF\uFF1A${t}`].join(`
958
+ `)}return t}var Lg=new Mg({allErrors:true,strict:false});function Og(s){let e=(s||"").trim();if(e.startsWith("```")){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t&&t[1])return t[1].trim()}return e}function Dg(s){return !s||s.length===0?[]:s.map(e=>{let t=e.instancePath||e.schemaPath||"";return e.keyword==="additionalProperties"&&typeof e.params?.additionalProperty=="string"?`${t} should not contain property "${e.params.additionalProperty}"`:`${t} ${e.message||""}`.trim()})}var pi=class{constructor(e){this.definition=e;this.validateFn=Lg.compile(e.schema);}validateFn;get responseFormatPayload(){return {type:"json_schema",json_schema:{name:this.definition.name,schema:this.definition.schema,strict:this.definition.strict??true}}}buildSystemPrompt(){let e=JSON.stringify(this.definition.schema,null,2);return [`You must respond with valid JSON that exactly matches the schema "${this.definition.name}".`,"Do not include explanations, markdown code fences, or additional commentary.","Schema:",e].join(`
959
+
960
+ `)}validate(e){let t=Og(e||"");if(!t)return {ok:false,reason:"empty_output",message:"The model returned an empty response."};let n;try{n=JSON.parse(t);}catch(i){return {ok:false,reason:"parse_error",message:i?.message||"Failed to parse JSON output."}}return this.validateFn(n)?{ok:true,parsed:n,normalized:JSON.stringify(n,null,2)}:{ok:false,reason:"schema_mismatch",message:"Response does not match the required JSON schema.",errors:Dg(this.validateFn.errors)}}buildRetryPrompt(e){let t=[`Your previous response did not satisfy the required JSON schema "${this.definition.name}".`];return e.errors&&e.errors.length>0?t.push(`Validation issues:
961
+ - `+e.errors.join(`
962
+ - `)):e.message&&t.push(`Validation issue: ${e.message}`),t.push("Return ONLY valid minified JSON (no code fences, no commentary) that matches the schema below:",JSON.stringify(this.definition.schema,null,2)),t.join(`
963
+
964
+ `)}};function _a(s,e={}){let{initialDelayMs:t=zt.initialDelayMs,backoffFactor:n=zt.backoffFactor,maxDelayMs:r=zt.maxDelayMs,jitterRange:i=zt.jitterRange}=e,o=Math.max(0,s-1),a=t*Math.pow(n,o),l=1+(Math.random()*2-1)*i,c=a*l,u=Math.min(c,r);return Math.floor(u)}function pn(s,e,t){return s!==void 0&&s>0?s:_a(e,t)}function ft(s){return new Promise(e=>setTimeout(e,s))}function st(s){if(s<1e3)return `${s}ms`;let e=s/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var $g={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},Ng={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function Ug(s,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return _a(s,$g)}function Hs(s,e,t){return s==="retryable_rate_limit"?Ug(e,t):s==="retryable_stream"||s==="retryable_network"?_a(e,Ng):pn(t,e)}function me(s){return s===null?"":typeof s=="string"?s:s.filter(e=>e.type==="text").map(e=>e.text).join("")}var Fg={unknown:0,normal:1,warn:2,soft_limit:3,limit:4};function $u(s){if(!s)return 0;let e=s.trim();return e.length?Math.ceil(e.length/4):0}function hi(s){let e=me(s.content),t=$u(e),n=s.tool_calls?.length?$u(JSON.stringify(s.tool_calls)):0;return t+n}function In(s){return s.reduce((e,t)=>e+hi(t),0)}function Bg(s,e,t){return !s.contextWindow&&!s.autoCompactLimit?"unknown":s.autoCompactLimit&&e>=s.autoCompactLimit?"limit":t===void 0||s.contextWindow===void 0?"unknown":t>=s.warnThresholds.hard?"limit":t>=s.warnThresholds.soft?"soft_limit":t>=s.warnThresholds.warn?"warn":"normal"}var mi=class{profile;promptTokensActual=0;completionTokensActual=0;promptTokensEstimate=0;completionTokensEstimate=0;constructor(e){this.profile=e;}updateProfile(e){this.profile=e,this.reset();}reset(){this.promptTokensActual=0,this.completionTokensActual=0,this.promptTokensEstimate=0,this.completionTokensEstimate=0;}setPromptEstimateFromMessages(e){return this.promptTokensActual>0?(this.completionTokensEstimate=0,this.getSnapshot()):(this.promptTokensEstimate=In(e),this.promptTokensActual=0,this.completionTokensActual=0,this.completionTokensEstimate=0,this.getSnapshot())}addEstimatedOutputTokens(e){return this.completionTokensEstimate=Math.max(0,this.completionTokensEstimate+e),this.getSnapshot()}recordActualUsage(e,t,n){return this.promptTokensActual=e,this.completionTokensActual=t,this.promptTokensEstimate=0,this.completionTokensEstimate=0,this.getSnapshot(n)}getSnapshot(e){let t=this.promptTokensActual||this.promptTokensEstimate,n=this.completionTokensActual+this.completionTokensEstimate,r=t+n,i=this.profile.contextWindow?r/this.profile.contextWindow:void 0,o=Bg(this.profile,r,i);return {profile:this.profile,tokensUsed:r,promptTokens:t,completionTokens:n,messageCount:e,pressure:i,state:o,timestamp:Date.now()}}getStateRank(e){return Fg[e]}estimateMessagesForDisplay(e){return In(e)}recordCalibration(e,t,n){if(process.env.CLI_DEBUG){let r=t+n,i=e>0?r/e:0;console.log(`[MemoryPressure] \u6821\u51C6: \u4F30\u7B97=${e}, \u5B9E\u9645=${r}, \u6BD4\u7387=${i.toFixed(3)}`);}}};le();var jg=15,Gg=5,Wg=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],Hg=`You are a conversation summarizer. Create a concise summary preserving:
965
+ 1. Key decisions and their rationale
966
+ 2. Important file paths and code changes
967
+ 3. Unresolved issues or next steps
968
+ 4. Technical details that affect future actions
969
+
970
+ Output only the summary in the same language as the input.`,Jg=`\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u6458\u8981\u52A9\u624B\u3002\u521B\u5EFA\u7B80\u6D01\u7684\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
971
+ 1. \u5173\u952E\u51B3\u7B56\u53CA\u5176\u7406\u7531
972
+ 2. \u91CD\u8981\u7684\u6587\u4EF6\u8DEF\u5F84\u548C\u4EE3\u7801\u53D8\u66F4
973
+ 3. \u672A\u89E3\u51B3\u7684\u95EE\u9898\u6216\u540E\u7EED\u6B65\u9AA4
974
+ 4. \u5F71\u54CD\u540E\u7EED\u64CD\u4F5C\u7684\u6280\u672F\u7EC6\u8282
975
+
976
+ \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4F7F\u7528\u4E0E\u8F93\u5165\u76F8\u540C\u7684\u8BED\u8A00\u3002`,Js=class{debug;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1";}async trimSmart(e,t,n={}){let r=[],i=In(e);if(this.debug&&(r.push(`[SmartContext] Original: ${e.length} messages, ~${i} tokens`),r.push(`[SmartContext] Budget: ${t} tokens`)),i<=t)return this.debug&&r.push("[SmartContext] Within budget, no trimming needed"),{messages:e,originalCount:e.length,droppedCount:0,compressedCount:0,priorityStats:this.countPriorities(e,n),originalTokens:i,estimatedTokens:i,debugInfo:this.debug?{originalTokens:i,savedTokens:0,decisions:r}:void 0};let o=this.prioritizeMessages(e,n);if(this.debug){let h=this.countPrioritiesFromPrioritized(o);r.push(`[SmartContext] Priority distribution: CRITICAL=${h[0]}, HIGH=${h[1]}, MEDIUM=${h[2]}, LOW=${h[3]}`);}let a=[],l=0;for(let h of o)h.priority===0&&(a.push(h),l+=h.tokens);this.debug&&r.push(`[SmartContext] After CRITICAL: ${a.length} messages, ${l} tokens`);for(let h of o)h.priority===1&&!a.includes(h)&&l+h.tokens<=t&&(a.push(h),l+=h.tokens);this.debug&&r.push(`[SmartContext] After HIGH: ${a.length} messages, ${l} tokens`);let c=t-l,u=o.filter(h=>h.priority===2&&!a.includes(h)),d=o.filter(h=>h.priority===3&&!a.includes(h)),p=u.reduce((h,g)=>h+g.tokens,0);if(p<=c)a.push(...u),l+=p,this.debug&&r.push(`[SmartContext] All MEDIUM messages fit: ${u.length} messages`);else {let h=n.enableLLMCompression!==false,g=n.minMessagesForCompression??Gg;if(h&&n.llmProvider){let x=[...u,...d];if(x.length>=g){this.debug&&r.push(`[SmartContext] Attempting LLM compression for ${x.length} messages (MEDIUM+LOW)`);let S=await this.compressWithLLM(x.map(T=>T.message),n.llmProvider,n.model);if(S){let T=hi({content:S});if(l+T<=t){a.push({message:{role:"user",content:`[\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55]
977
+ ${S}`,name:"CompressedHistory"},priority:2,tokens:T,index:-1,reason:"LLM compressed history"}),l+=T;let w=x.reduce((L,B)=>L+B.tokens,0);return this.debug&&r.push(`[SmartContext] LLM compression saved ~${w-T} tokens`),this.buildResult(a,e.length,x.length,i,r,S)}}else this.debug&&r.push("[SmartContext] LLM compression failed, falling back to selective retention");}}let y=[...u].sort((x,S)=>S.index-x.index);for(let x of y)l+x.tokens<=t&&(a.push(x),l+=x.tokens);if(this.debug){let x=a.filter(S=>S.priority===2).length;r.push(`[SmartContext] Kept ${x} of ${u.length} MEDIUM messages (selective retention)`);}}let m=d.filter(h=>!a.includes(h));for(let h of m)l+h.tokens<=t&&(a.push(h),l+=h.tokens);return this.buildResult(a,e.length,0,i,r)}prioritizeMessages(e,t){let n=t.minHistoryMessages??jg,r=[];for(let i=0;i<e.length;i++){let o=e[i],a=hi(o),l=e.length-i,c,u;o.role==="system"?(c=0,u="system message"):l<=n?(c=0,u=`recent message (${l} from end)`):this.containsError(o)?(c=1,u="contains error"):o.tool_calls&&o.tool_calls.length>0?(c=1,u="tool calls"):o.role==="user"?(c=2,u="user message"):o.role==="assistant"?(c=2,u="assistant message"):o.role==="tool"?(c=1,u=this.containsError(o)?"error tool result":"tool result (paired with tool_call)"):(c=2,u="default"),t.iteration&&t.iteration>10&&c===2&&this.containsError(o)&&(c=1,u+=" (elevated due to high iteration)"),r.push({message:o,priority:c,tokens:a,index:i,reason:u});}return r}containsError(e){let t=me(e.content);return Wg.some(n=>n.test(t))}async compressWithLLM(e,t,n){try{let r=this.detectChinese(e),i=r?Jg:Hg,o=e.map(u=>{let d=u.role==="assistant"?"Assistant":u.role==="user"?"User":u.role==="tool"?"Tool":u.role,p=me(u.content),m=p.length>500?p.slice(0,500)+"...":p;return `[${d}] ${m}`}).join(`
978
+
979
+ `),a=r?`\u8BF7\u603B\u7ED3\u4EE5\u4E0B\u5BF9\u8BDD\u5386\u53F2\uFF1A
980
+
981
+ ${o}`:`Please summarize the following conversation:
982
+
983
+ ${o}`,l=await t.chat([{role:"system",content:i},{role:"user",content:a}],{model:n,temperature:.3});return me(l.choices[0]?.message?.content)?.trim()||null}catch(r){return f.error("SmartContext",`LLM compression failed: ${r.message}`),null}}detectChinese(e){for(let t of e){let n=me(t.content);if(/[\u4e00-\u9fa5]/.test(n))return true}return false}countPriorities(e,t){let n=this.prioritizeMessages(e,t);return this.countPrioritiesFromPrioritized(n)}countPrioritiesFromPrioritized(e){let t={0:0,1:0,2:0,3:0,4:0};for(let n of e)t[n.priority]++;return t}buildResult(e,t,n,r,i,o){let l=[...e].sort((u,d)=>u.index-d.index).map(u=>u.message),c=In(l);return {messages:l,originalCount:t,droppedCount:t-e.length,compressedCount:n,priorityStats:this.countPrioritiesFromPrioritized(e),originalTokens:r,estimatedTokens:c,compressionSummary:o,debugInfo:this.debug?{originalTokens:r,savedTokens:r-c,decisions:i}:void 0}}};new Js;ji();function Ib(s,e){if(typeof s!="string")return null;let t=s.trim();if(!t.startsWith("{"))return null;try{let n=JSON.parse(t);return !n||typeof n!="object"||n.tool!==e||typeof n.status!="string"?null:n.status}catch{return null}}var Gi=class s{static READ_ONLY_TOOLS=new Set(["readfile","search","search_files","list_directory","show_tree","analyze_code","search_symbol","get_definitions","get_references","git_status","git_diff","git_blame","git_branch_list"]);static STATE_MODIFYING_TOOLS=new Set(["write_file","edit_file","create_directory","delete_file","rename_file","apply_patch","execute_shell","execute_bash","execute_python","execute_javascript","git_commit","git_branch","run_tests","run_lint","run_format"]);static TOOL_METADATA=new Map([["readfile",{name:"readfile",isReadOnly:true,category:"read",description:"Read file contents"}],["search",{name:"search",isReadOnly:true,category:"read",description:"Search file contents"}],["search_files",{name:"search_files",isReadOnly:true,category:"read",description:"Search files by name"}],["list_directory",{name:"list_directory",isReadOnly:true,category:"read",description:"List directory contents"}],["show_tree",{name:"show_tree",isReadOnly:true,category:"read",description:"Show directory tree"}],["analyze_code",{name:"analyze_code",isReadOnly:true,category:"read",description:"Analyze code structure"}],["search_symbol",{name:"search_symbol",isReadOnly:true,category:"read",description:"Search symbols in index"}],["get_definitions",{name:"get_definitions",isReadOnly:true,category:"read",description:"Find symbol definitions"}],["get_references",{name:"get_references",isReadOnly:true,category:"read",description:"Find symbol references"}],["git_status",{name:"git_status",isReadOnly:true,category:"read",description:"Show git status"}],["git_diff",{name:"git_diff",isReadOnly:true,category:"read",description:"Show git diff"}],["git_blame",{name:"git_blame",isReadOnly:true,category:"read",description:"Show git blame"}],["git_branch_list",{name:"git_branch_list",isReadOnly:true,category:"read",description:"List git branches"}],["write_file",{name:"write_file",isReadOnly:false,category:"write",description:"Write file"}],["edit_file",{name:"edit_file",isReadOnly:false,category:"write",description:"Edit file"}],["create_directory",{name:"create_directory",isReadOnly:false,category:"write",description:"Create directory"}],["delete_file",{name:"delete_file",isReadOnly:false,category:"write",description:"Delete file"}],["rename_file",{name:"rename_file",isReadOnly:false,category:"write",description:"Rename file"}],["apply_patch",{name:"apply_patch",isReadOnly:false,category:"write",description:"Apply patch"}],["git_commit",{name:"git_commit",isReadOnly:false,category:"write",description:"Git commit"}],["git_branch",{name:"git_branch",isReadOnly:false,category:"write",description:"Git branch"}],["run_tests",{name:"run_tests",isReadOnly:false,category:"execute",description:"Run tests"}],["run_lint",{name:"run_lint",isReadOnly:false,category:"execute",description:"Run lint"}],["run_format",{name:"run_format",isReadOnly:false,category:"execute",description:"Run format"}],["execute_shell",{name:"execute_shell",isReadOnly:false,category:"execute",description:"Execute shell command"}],["execute_bash",{name:"execute_bash",isReadOnly:false,category:"execute",description:"Execute bash script"}],["execute_python",{name:"execute_python",isReadOnly:false,category:"execute",description:"Execute Python code"}],["execute_javascript",{name:"execute_javascript",isReadOnly:false,category:"execute",description:"Execute JavaScript code"}]]);static isReadOnly(e){return s.READ_ONLY_TOOLS.has(e)}static isStateModifying(e){return s.STATE_MODIFYING_TOOLS.has(e)}static getMetadata(e){return s.TOOL_METADATA.get(e)}analyzePlan(e){let t=[],n=[];for(let r of e){let i=r.function.name;s.isReadOnly(i)?t.push(r):n.push(r);}return {parallel:t,sequential:n,totalTools:e.length,parallelCount:t.length,sequentialCount:n.length}}async executeSingleTool(e,t,n){let r=Date.now();if(n?.aborted)return {id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-r};let i=t.find(o=>o.name===e.function.name);if(!i)return {id:e.id,name:e.function.name,output:`Error: Tool ${e.function.name} not found`,success:false,executionTime:Date.now()-r};try{let o=e.function.arguments.trim(),a=o?JSON.parse(o):{},l=await i.function(a,{signal:n}),c=!0;return Ib(l,e.function.name)==="error"&&(c=!1),n?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:!1,executionTime:Date.now()-r}:{id:e.id,name:e.function.name,output:l,success:c,executionTime:Date.now()-r}}catch(o){return o.name==="AbortError"||n?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-r}:{id:e.id,name:e.function.name,output:`Error: ${o.message}`,success:false,executionTime:Date.now()-r}}}async execute(e,t,n,r){let i=Date.now(),o=this.analyzePlan(e);process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Execution Plan:"),console.log(` Total: ${o.totalTools} tools`),console.log(` Parallel (read-only): ${o.parallelCount} tools`),console.log(` Sequential (state-modifying): ${o.sequentialCount} tools`));let a=new Map,l=0,c=0;if(o.parallel.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.parallel.length} read-only tools in parallel...`);let x=o.parallel.map(T=>this.executeSingleTool(T,t,r).then(w=>(n&&n(w),w))),S=await Promise.all(x);l=Date.now()-y;for(let T of S)a.set(T.id,T);process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Parallel execution completed in ${l}ms`);}if(o.sequential.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${o.sequential.length} state-modifying tools sequentially...`);for(let x of o.sequential){if(r?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted before ${x.function.name}`);break}let S=await this.executeSingleTool(x,t,r);if(n&&n(S),a.set(S.id,S),r?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted after ${x.function.name}`);break}}c=Date.now()-y,process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Sequential execution completed in ${c}ms`);}let u=e.map(y=>{let x=a.get(y.id);return x||{id:y.id,name:y.function.name,output:"Error: Result not found",success:false}}),d=Date.now()-i,p=u.reduce((y,x)=>y+(x.executionTime||0),0),m=p-d,h=p>0?p/d:1,g={totalTime:d,parallelTime:l,sequentialTime:c,timeSaved:m,speedup:h};return process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Performance Stats:"),console.log(` Total time: ${d}ms`),console.log(` Parallel time: ${l}ms`),console.log(` Sequential time: ${c}ms`),console.log(` Estimated sequential time: ${p}ms`),console.log(` Time saved: ${m}ms`),console.log(` Speedup: ${h.toFixed(2)}x`)),{results:u,stats:g}}getToolClassification(e){let t=s.isReadOnly(e),n=s.getMetadata(e);return {isReadOnly:t,category:n?.category||"unknown",canParallel:t}}static canExecuteInParallel(e){return e.every(t=>s.READ_ONLY_TOOLS.has(t))}static getReadOnlyTools(){return Array.from(s.READ_ONLY_TOOLS)}static getStateModifyingTools(){return Array.from(s.STATE_MODIFYING_TOOLS)}};var Rb={view:["view","show","display","read","cat","print","look","see","open","\u67E5\u770B","\u770B\u770B","\u770B\u4E00\u4E0B","\u663E\u793A","\u8BFB\u53D6","\u6253\u5370","\u6253\u5F00","\u5C55\u793A","\u7ED9\u6211\u770B"],search:["search","find","grep","locate","where","which file","\u641C\u7D22","\u67E5\u627E","\u627E\u5230","\u627E\u4E00\u4E0B","\u627E\u627E","\u54EA\u4E2A\u6587\u4EF6","\u5728\u54EA","\u54EA\u91CC","\u5B9A\u4F4D"],explain:["explain","describe","what is","what does","how does","why","understand","\u89E3\u91CA","\u8BF4\u660E","\u662F\u4EC0\u4E48","\u505A\u4EC0\u4E48","\u4EC0\u4E48\u610F\u601D","\u4E3A\u4EC0\u4E48","\u600E\u4E48\u7406\u89E3","\u5206\u6790","\u8BB2\u89E3"],edit:["edit","modify","change","update","fix","replace","rename","alter","\u4FEE\u6539","\u6539\u4E00\u4E0B","\u6539\u6210","\u66F4\u65B0","\u4FEE\u590D","\u66FF\u6362","\u6539\u4E3A","\u53D8\u6210","\u6362\u6210","\u8C03\u6574"],create:["create","add","new","implement","write","make","generate","build","\u521B\u5EFA","\u65B0\u5EFA","\u6DFB\u52A0","\u5B9E\u73B0","\u5199\u4E00\u4E2A","\u751F\u6210","\u65B0\u589E","\u5F00\u53D1","\u7F16\u5199","\u5E2E\u6211\u5199"],refactor:["refactor","restructure","reorganize","optimize","improve","clean","simplify","\u91CD\u6784","\u4F18\u5316","\u6539\u8FDB","\u6574\u7406","\u7B80\u5316","\u63D0\u5347","\u6539\u5584","\u7CBE\u7B80","\u62C6\u5206"],plan:["plan","design","architect","strategy","proposal","roadmap","\u89C4\u5212","\u8BBE\u8BA1","\u67B6\u6784","\u5206\u6790\u7ED3\u6784","\u8BA1\u5212","\u65B9\u6848","\u7B56\u7565","\u84DD\u56FE"],bug:["bug","broken","not working","issue","defect","fault","\u574F\u4E86","\u4E0D\u5DE5\u4F5C","\u6709\u95EE\u9898","\u51FA\u9519","\u6709bug","\u6545\u969C","\u51FA\u95EE\u9898"],error:["error","exception","crash","fail","wrong","undefined","null","\u9519\u8BEF","\u5F02\u5E38","\u5D29\u6E83","\u5931\u8D25","\u62A5\u9519","\u51FA\u9519\u4E86","\u8DD1\u4E0D\u8D77\u6765","\u8FD0\u884C\u4E0D\u4E86"],review:["review","check","audit","inspect","examine","verify","\u5BA1\u67E5","\u68C0\u67E5","\u5BA1\u8BA1","\u5BA1\u6838","\u6821\u9A8C","\u9A8C\u8BC1","\u770B\u770B\u5BF9\u4E0D\u5BF9"],multi:["all","every","multiple","several","batch","across","throughout","\u6240\u6709","\u6BCF\u4E2A","\u591A\u4E2A","\u51E0\u4E2A","\u6279\u91CF","\u5168\u90E8","\u6574\u4E2A\u9879\u76EE","\u5168\u5C40"],steps:["then","after that","next","step","first...then","and then","\u7136\u540E","\u63A5\u7740","\u4E4B\u540E","\u6B65\u9AA4","\u8FD8\u8981","\u518D","\u9996\u5148","\u63A5\u4E0B\u6765"]},Pb=/\b[\w\-./]+\.(ts|tsx|js|jsx|py|java|go|rs|c|cpp|css|html|json|yaml|yml|md|sql|sh)\b/gi,ml=class{classify(e,t){let n=e.toLowerCase(),r=e.match(Pb)||[],i=o=>Rb[o].some(a=>n.includes(a)||e.includes(a));return i("plan")?{taskType:"architecture",confidence:.9,reasoning:"plan"}:i("view")&&!i("edit")&&!i("create")?{taskType:"simple_read",confidence:.95,reasoning:"view only"}:i("search")&&!i("edit")&&!i("create")?{taskType:"simple_search",confidence:.95,reasoning:"search only"}:i("explain")&&!i("edit")&&!i("create")?{taskType:"simple_explain",confidence:.9,reasoning:"explain only"}:i("review")&&!i("edit")&&!i("create")?{taskType:"code_review",confidence:.85,reasoning:"review"}:(i("bug")||i("error"))&&(i("edit")||r.length>0)?{taskType:"bugfix",confidence:.85,reasoning:"bug/error + edit"}:i("refactor")?{taskType:"refactor",confidence:.85,reasoning:"refactor"}:i("multi")||r.length>1||i("steps")&&i("edit")?{taskType:i("create")?"feature_add":"multi_file_edit",confidence:.8,reasoning:"multi-file or feature"}:i("edit")&&r.length===1?{taskType:"single_file_edit",confidence:.85,reasoning:"single file edit"}:i("edit")||i("create")?{taskType:"single_file_edit",confidence:.6,reasoning:"edit/create intent"}:{taskType:"simple_read",confidence:.5,reasoning:"default"}}},Wi=new ml;var hl={simple_read:{name:"\u7B80\u5355\u8BFB\u53D6",description:"\u67E5\u770B\u6587\u4EF6/\u76EE\u5F55\uFF0C\u65E0\u9700\u4FEE\u6539",tokenBudget:300,modules:["core_identity_minimal","read_tools_only"]},simple_search:{name:"\u7B80\u5355\u641C\u7D22",description:"\u641C\u7D22\u4EE3\u7801/\u6587\u4EF6\uFF0C\u5B9A\u4F4D\u95EE\u9898",tokenBudget:350,modules:["core_identity_minimal","search_tools_only"]},simple_explain:{name:"\u4EE3\u7801\u89E3\u91CA",description:"\u89E3\u91CA\u4EE3\u7801\u903B\u8F91\uFF0C\u65E0\u9700\u4FEE\u6539",tokenBudget:300,modules:["core_identity_minimal","explain_guidance"]},single_file_edit:{name:"\u5355\u6587\u4EF6\u7F16\u8F91",description:"\u4FEE\u6539\u5355\u4E2A\u6587\u4EF6",tokenBudget:600,modules:["core_identity","edit_rules_strict","minimal_changes"]},bugfix:{name:"Bug\u4FEE\u590D",description:"\u5B9A\u4F4D\u5E76\u4FEE\u590Dbug",tokenBudget:700,modules:["core_identity","bugfix_workflow","edit_rules_strict","error_recovery_basic"]},code_review:{name:"\u4EE3\u7801\u5BA1\u67E5",description:"\u5BA1\u67E5\u4EE3\u7801\u8D28\u91CF",tokenBudget:500,modules:["core_identity_minimal","review_guidance"]},multi_file_edit:{name:"\u591A\u6587\u4EF6\u7F16\u8F91",description:"\u4FEE\u6539\u591A\u4E2A\u76F8\u5173\u6587\u4EF6",tokenBudget:1100,modules:["core_identity","execution_principles","tool_decision_tree","edit_rules_strict","batch_operations","large_file_chunking","error_recovery"]},feature_add:{name:"\u65B0\u529F\u80FD\u5F00\u53D1",description:"\u5B9E\u73B0\u65B0\u529F\u80FD\uFF0C\u53EF\u80FD\u6D89\u53CA\u591A\u6587\u4EF6",tokenBudget:1300,modules:["core_identity","execution_principles","feature_workflow","tool_decision_tree","edit_rules_strict","batch_operations","large_file_chunking","file_creation_policy"]},refactor:{name:"\u4EE3\u7801\u91CD\u6784",description:"\u91CD\u6784\u4EE3\u7801\uFF0C\u9700\u8981\u5F71\u54CD\u5206\u6790",tokenBudget:1e3,modules:["core_identity","execution_principles","refactor_workflow","tool_decision_tree","edit_rules_strict","batch_operations"]},architecture:{name:"\u67B6\u6784\u89C4\u5212",description:"Plan Mode - \u53EA\u63A2\u7D22\u4E0D\u4FEE\u6539",tokenBudget:600,modules:["core_identity_minimal","plan_mode_strict"]}},Mb={core_identity_minimal:{name:"core_identity_minimal",contentZh:"\u4F60\u662F Neox AI \u4EE3\u7801\u52A9\u624B\u3002\u76F4\u63A5\u4F7F\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1\uFF0C\u7B80\u77ED\u56DE\u590D\u3002",contentEn:"You are Neox AI code assistant. Use tools directly to complete tasks, reply briefly.",priority:"critical",estimatedTokens:30,applicableScenarios:["simple_read","simple_search","simple_explain","code_review","architecture"]},core_identity:{name:"core_identity",contentZh:`\u4F60\u662F Neox AI \u4EE3\u7801\u52A9\u624B\u3002\u76EE\u6807\uFF1A\u7528\u6700\u5C11\u8FED\u4EE3\u9AD8\u6548\u5B8C\u6210\u4EFB\u52A1\u3002
984
+ - \u5148\u7406\u89E3\u540E\u884C\u52A8\uFF1A\u4FEE\u6539\u524D\u5FC5\u987B readfile(path, for_edit=true)
985
+ - \u76F4\u63A5\u6267\u884C\uFF1A\u4E0D\u8981\u7A7A\u8C08\uFF0C\u9A6C\u4E0A\u4F7F\u7528\u5DE5\u5177
986
+ - \u7B80\u6D01\u56DE\u590D\uFF1A\u64CD\u4F5C\u540E\u7B80\u77ED\u786E\u8BA4
987
+ - \u9700\u8981\u5B9A\u4E49/\u5F15\u7528\u65F6\uFF0C\u7528 search_symbol / get_definitions / get_references`,contentEn:`You are Neox AI code assistant. Goal: Complete tasks efficiently with minimal iterations.
988
+ - Understand before acting: Must readfile(path, for_edit=true) before modifying
989
+ - Execute directly: Don't talk, use tools right away
990
+ - Brief replies: Short confirmation after operations
991
+ - For definitions/references, use search_symbol / get_definitions / get_references`,priority:"critical",estimatedTokens:80,applicableScenarios:["single_file_edit","bugfix","multi_file_edit","feature_add","refactor"]},read_tools_only:{name:"read_tools_only",contentZh:`\u5DE5\u5177\uFF1A
992
+ - readfile(path) - \u667A\u80FD\u8BFB\u53D6\uFF08\u9ED8\u8BA4\u524D200\u884C\uFF09
993
+ - readfile(path, for_edit=true) - \u83B7\u53D6\u53EF\u7F16\u8F91\u539F\u6587\uFF08\u7528\u4E8E edit_file\uFF09
994
+ - readfile(path, symbol="xxx") - \u7CBE\u51C6\u5B9A\u4F4D\u51FD\u6570/\u7C7B
995
+ - readfile(path, pattern="xxx", list_matches=true) - \u5148\u5217\u5339\u914D\u884C\u518D\u6279\u91CF\u8BFB\u53D6
996
+ - readfile(path, anchor_lines=[...], num_lines=200) - \u6279\u91CF\u8BFB\u53D6\u591A\u4E2A\u884C\u6BB5
997
+ - readfile(path, start_line=100) - \u6307\u5B9A\u884C\u53F7\u8BFB\u53D6
998
+ - search_symbol(query) - \u7B26\u53F7\u641C\u7D22\uFF08\u9700\u7D22\u5F15\uFF09
999
+ - get_definitions(query) - \u67E5\u5B9A\u4E49
1000
+ - get_references(query) - \u67E5\u5F15\u7528
1001
+ - show_tree(dir), list_directory(dir)
1002
+ \u7528\u4E2D\u6587\u56DE\u590D\u3002`,contentEn:`Tools:
1003
+ - readfile(path) - Smart read (default 200 lines)
1004
+ - readfile(path, for_edit=true) - Provides raw content for edit_file
1005
+ - readfile(path, symbol="xxx") - Precise function/class location
1006
+ - readfile(path, pattern="xxx", list_matches=true) - List matches first
1007
+ - readfile(path, anchor_lines=[...], num_lines=200) - Batch read line blocks
1008
+ - readfile(path, start_line=100) - Read from specific line
1009
+ - search_symbol(query) - Symbol search (index required)
1010
+ - get_definitions(query) - Find definitions
1011
+ - get_references(query) - Find references
1012
+ - show_tree(dir), list_directory(dir)`,priority:"critical",estimatedTokens:80,applicableScenarios:["simple_read"]},search_tools_only:{name:"search_tools_only",contentZh:`\u5DE5\u5177\uFF1A
1013
+ - search(pattern, path) - \u5185\u5BB9\u641C\u7D22
1014
+ - readfile(path, pattern="xxx") - \u641C\u7D22\u5E76\u8BFB\u53D6\u4E0A\u4E0B\u6587
1015
+ - readfile(path, pattern="xxx", list_matches=true) - \u5148\u5217\u5339\u914D\u884C\u518D\u6279\u91CF\u8BFB\u53D6
1016
+ - search_files(pattern) - \u6587\u4EF6\u540D\u641C\u7D22
1017
+ - search_symbol(query) - \u7B26\u53F7\u641C\u7D22\uFF08\u9700\u7D22\u5F15\uFF09
1018
+ - get_references(query) - \u67E5\u5F15\u7528
1019
+ - show_tree(dir)
1020
+ \u76F4\u63A5\u641C\u7D22\uFF0C\u5C55\u793A\u7ED3\u679C\u3002\u7528\u4E2D\u6587\u56DE\u590D\u3002`,contentEn:`Tools:
1021
+ - search(pattern, path) - Content search
1022
+ - readfile(path, pattern="xxx") - Search and read context
1023
+ - readfile(path, pattern="xxx", list_matches=true) - List matches first
1024
+ - search_files(pattern) - Filename search
1025
+ - search_symbol(query) - Symbol search (index required)
1026
+ - get_references(query) - Find references
1027
+ - show_tree(dir)
1028
+ Search directly, show results.`,priority:"critical",estimatedTokens:80,applicableScenarios:["simple_search"]},explain_guidance:{name:"explain_guidance",contentZh:"\u5148 readfile \u83B7\u53D6\u4EE3\u7801\uFF0C\u7528\u4E2D\u6587\u6E05\u6670\u89E3\u91CA\u3002\u4E0D\u4FEE\u6539\u4EFB\u4F55\u6587\u4EF6\u3002",contentEn:"First readfile to get code, explain clearly. Don't modify any files.",priority:"critical",estimatedTokens:30,applicableScenarios:["simple_explain"]},review_guidance:{name:"review_guidance",contentZh:"\u9605\u8BFB\u4EE3\u7801\uFF0C\u6307\u51FA\u95EE\u9898\u548C\u6539\u8FDB\u5EFA\u8BAE\u3002\u4E0D\u76F4\u63A5\u4FEE\u6539\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\u3002",contentEn:"Read code, point out issues and suggestions. Don't modify directly unless explicitly requested.",priority:"critical",estimatedTokens:40,applicableScenarios:["code_review"]},edit_rules_strict:{name:"edit_rules_strict",contentZh:`## \u6587\u4EF6\u7F16\u8F91\uFF08\u5F3A\u5236\uFF09
1029
+ 1. \u{1F525} \u5FC5\u987B\u5148 readfile(path, for_edit=true) - edit_file \u524D\u672A\u8BFB\u53D6\u7684\u6587\u4EF6\u4F1A\u88AB\u62D2\u7EDD
1030
+ 2. \u{1F525} old_string \u4FDD\u6301\u77ED\u5C0F\u4E14\u552F\u4E00\uFF0C\u5FC5\u8981\u65F6\u63D0\u4F9B change_context \u4F5C\u4E3A\u951A\u70B9
1031
+ 3. \u{1F525} \u5339\u914D\u5BB9\u5FCD\u7A7A\u767D/\u6807\u70B9\u5DEE\u5F02\uFF0C\u4F46\u4ECD\u5E94\u5C3D\u91CF\u7CBE\u786E\u907F\u514D\u6B67\u4E49
1032
+ 4. \u5931\u8D252\u6B21 \u2192 write_file \u91CD\u5199\u6574\u4E2A\u6587\u4EF6
1033
+ 5. \u7981\u6B62 sed/awk \u7F16\u8F91`,contentEn:`## File Editing (Mandatory)
1034
+ 1. \u{1F525} Must readfile(path, for_edit=true) first - edit_file will reject files not recently read
1035
+ 2. \u{1F525} Keep old_string minimal and unique; provide change_context when needed
1036
+ 3. \u{1F525} Matching tolerates whitespace/punctuation, but stay precise to avoid ambiguity
1037
+ 4. Fail 2x \u2192 write_file to rewrite entire file
1038
+ 5. No sed/awk editing`,priority:"important",estimatedTokens:120,applicableScenarios:["single_file_edit","bugfix","multi_file_edit","feature_add","refactor"]},minimal_changes:{name:"minimal_changes",contentZh:"\u53EA\u6539\u5FC5\u8981\u7684\u3002\u4E0D\u989D\u5916\u521B\u5EFA\u6587\u6863/\u6D4B\u8BD5\uFF0C\u4E0D\u64C5\u81EA\u91CD\u6784\u3002",contentEn:"Only change what's necessary. No extra docs/tests, no unsolicited refactoring.",priority:"important",estimatedTokens:30,applicableScenarios:["single_file_edit","bugfix"]},execution_principles:{name:"execution_principles",contentZh:`## \u6267\u884C\u539F\u5219
1039
+ - \u72EC\u7ACB\u64CD\u4F5C\u5E76\u884C\uFF08\u591A readfile \u4E00\u6B21\u5B8C\u6210\uFF09
1040
+ - \u4F9D\u8D56\u64CD\u4F5C\u987A\u5E8F\uFF08read \u2192 edit \u5206\u5F00\uFF09
1041
+ - Shell \u72EC\u7ACB\u6267\u884C\uFF0Ccd \u4E0D\u6301\u7EED`,contentEn:`## Execution Principles
1042
+ - Independent ops in parallel (multiple readfile in one go)
1043
+ - Dependent ops sequential (read \u2192 edit separate)
1044
+ - Shell calls independent, cd doesn't persist`,priority:"critical",estimatedTokens:80,applicableScenarios:["multi_file_edit","feature_add","refactor"]},tool_decision_tree:{name:"tool_decision_tree",contentZh:`## \u5DE5\u5177\u9009\u62E9
1045
+ | \u4EFB\u52A1 | \u7528 | \u7981 |
1046
+ |-----|---|---|
1047
+ | \u7ED3\u6784 | show_tree | \u9010\u5C42 list |
1048
+ | \u641C\u5185\u5BB9 | search | shell grep |
1049
+ | \u641C\u6587\u4EF6 | search_files | shell find |
1050
+ | \u6539\u6587\u4EF6 | read\u2192edit | sed/awk |
1051
+ | \u65B0\u6587\u4EF6 | write_file | echo\u91CD\u5B9A\u5411 |
1052
+ | \u5B9A\u4F4D\u51FD\u6570/\u7C7B | readfile(symbol="xxx") | grep \u518D read |
1053
+ | \u67E5\u5B9A\u4E49/\u5F15\u7528 | get_definitions/get_references | \u76F2\u641C |
1054
+ | \u8BFB\u53D6\u4EE3\u7801\u5757 | readfile(function="xxx") | \u731C\u884C\u53F7 |
1055
+
1056
+ \u8865\u5145\uFF1A
1057
+ - Git\uFF1Agit_status / git_diff / git_blame / git_branch_list / git_branch / git_commit
1058
+ - \u6587\u4EF6\uFF1Arename_file / delete_file / apply_patch
1059
+ - \u8FD0\u884C\uFF1Arun_tests / run_lint / run_format`,contentEn:`## Tool Selection
1060
+ | Task | Use | Avoid |
1061
+ |------|-----|-------|
1062
+ | Structure | show_tree | nested list |
1063
+ | Search content | search | shell grep |
1064
+ | Search files | search_files | shell find |
1065
+ | Modify | read\u2192edit | sed/awk |
1066
+ | New file | write_file | echo redirect |
1067
+ | Locate function/class | readfile(symbol="xxx") | grep then read |
1068
+ | Definitions/references | get_definitions/get_references | blind grep |
1069
+ | Read code block | readfile(function="xxx") | guess line numbers |
1070
+
1071
+ Notes:
1072
+ - Git: git_status / git_diff / git_blame / git_branch_list / git_branch / git_commit
1073
+ - Files: rename_file / delete_file / apply_patch
1074
+ - Runs: run_tests / run_lint / run_format`,priority:"important",estimatedTokens:150,applicableScenarios:["multi_file_edit","feature_add","refactor"]},batch_operations:{name:"batch_operations",contentZh:`## \u6279\u91CF\u64CD\u4F5C
1075
+ - \u591A\u6587\u4EF6\u8BFB\u53D6\uFF1A\u4E00\u6B21\u8FED\u4EE3\u5E76\u884C readfile
1076
+ - \u591A\u6587\u4EF6\u4FEE\u6539\uFF1A\u5148\u5168\u90E8 readfile\uFF0C\u518D\u9010\u4E2A\u4FEE\u6539
1077
+ - \u641C\u7D22+\u8BFB\u53D6\uFF1A\u5148 grep\uFF0C\u518D\u6279\u91CF readfile`,contentEn:`## Batch Operations
1078
+ - Multiple reads: Parallel readfile in one iteration
1079
+ - Multiple edits: readfile all first, then edit sequentially
1080
+ - Search+read: grep first, then batch readfile`,priority:"optional",estimatedTokens:80,applicableScenarios:["multi_file_edit","feature_add","refactor"]},bugfix_workflow:{name:"bugfix_workflow",contentZh:`## Bug\u4FEE\u590D\u6D41\u7A0B
1081
+ 1. search \u5B9A\u4F4D\u76F8\u5173\u4EE3\u7801
1082
+ 2. readfile(symbol="xxx") \u7CBE\u51C6\u8BFB\u53D6\u51FD\u6570/\u7C7B
1083
+ 3. \u7D22\u5F15\u53EF\u7528\u65F6\u7528 get_references \u5B9A\u4F4D\u8C03\u7528
1084
+ 4. \u627E\u6839\u56E0\uFF0C\u4E0D\u53EA\u4FEE\u8868\u9762
1085
+ 5. \u6700\u5C0F\u4FEE\u6539\uFF0C\u76EE\u6807 3-5 \u6B21\u8FED\u4EE3`,contentEn:`## Bug Fix Workflow
1086
+ 1. search to locate related code
1087
+ 2. readfile(symbol="xxx") to precisely read function/class
1088
+ 3. Use get_references when index is available
1089
+ 4. Find root cause, not just symptoms
1090
+ 5. Minimal fix, target 3-5 iterations`,priority:"important",estimatedTokens:80,applicableScenarios:["bugfix"]},feature_workflow:{name:"feature_workflow",contentZh:`## \u65B0\u529F\u80FD\u6D41\u7A0B
1091
+ 1. show_tree \u7406\u89E3\u9879\u76EE\u7ED3\u6784
1092
+ 2. search \u627E\u76F8\u4F3C\u5B9E\u73B0 \u2192 readfile(symbol="xxx") \u8BFB\u53D6\u53C2\u8003
1093
+ 3. \u7D22\u5F15\u53EF\u7528\u65F6\u7528 get_references \u67E5\u8C03\u7528\u94FE
1094
+ 4. \u89C4\u5212\u6587\u4EF6\uFF1A\u54EA\u4E9B\u65B0\u5EFA\uFF0C\u54EA\u4E9B\u4FEE\u6539
1095
+ 5. \u6309\u4F9D\u8D56\u987A\u5E8F\u5B9E\u73B0\uFF1A\u88AB\u4F9D\u8D56\u7684\u5148\u5199`,contentEn:`## Feature Workflow
1096
+ 1. show_tree to understand project structure
1097
+ 2. search find similar \u2192 readfile(symbol="xxx") read reference
1098
+ 3. Use get_references when index is available
1099
+ 4. Plan files: which to create, which to modify
1100
+ 5. Implement in dependency order: dependencies first`,priority:"important",estimatedTokens:100,applicableScenarios:["feature_add"]},refactor_workflow:{name:"refactor_workflow",contentZh:`## \u91CD\u6784\u6D41\u7A0B
1101
+ 1. get_references\uFF08\u7D22\u5F15\u53EF\u7528\uFF09\u6216 search \u627E\u5F15\u7528
1102
+ 2. readfile(symbol="xxx") \u7CBE\u51C6\u8BFB\u53D6\u76F8\u5173\u51FD\u6570/\u7C7B
1103
+ 3. \u6309\u4F9D\u8D56\u987A\u5E8F\u4FEE\u6539\uFF1A\u88AB\u4F9D\u8D56\u7684\u5148\u6539
1104
+ 4. \u53EA\u505A\u8981\u6C42\u7684\uFF0C\u4E0D\u6269\u5927\u8303\u56F4`,contentEn:`## Refactor Workflow
1105
+ 1. Use get_references (if indexed) or search to find references
1106
+ 2. readfile(symbol="xxx") to precisely read related functions/classes
1107
+ 3. Modify in dependency order: depended-upon first
1108
+ 4. Only do what's requested, don't expand scope`,priority:"important",estimatedTokens:100,applicableScenarios:["refactor"]},plan_mode_strict:{name:"plan_mode_strict",contentZh:`## Plan Mode\uFF08\u53EA\u63A2\u7D22\uFF09
1109
+ \u5141\u8BB8\uFF1Ashow_tree, search, readfile, search_files, search_symbol, get_definitions, get_references
1110
+ \u7981\u6B62\uFF1Aedit_file, write_file, execute_shell\uFF08\u9664\u4E86\u53EA\u8BFB\u547D\u4EE4\uFF09
1111
+
1112
+ \u63A2\u7D22\u65F6\u4F18\u5148\u7528 readfile(symbol="xxx") \u7CBE\u51C6\u5B9A\u4F4D\u4EE3\u7801
1113
+
1114
+ \u8F93\u51FA\u7ED3\u6784\u5316\u8BA1\u5212\uFF1A
1115
+ 1. \u6D89\u53CA\u6587\u4EF6\u5217\u8868
1116
+ 2. \u4FEE\u6539\u6B65\u9AA4
1117
+ 3. \u6F5C\u5728\u98CE\u9669`,contentEn:`## Plan Mode (Explore Only)
1118
+ Allowed: show_tree, search, readfile, search_files, search_symbol, get_definitions, get_references
1119
+ Forbidden: edit_file, write_file, execute_shell (except read-only)
1120
+
1121
+ Use readfile(symbol="xxx") for precise code location when exploring
1122
+
1123
+ Output structured plan:
1124
+ 1. Files involved
1125
+ 2. Modification steps
1126
+ 3. Potential risks`,priority:"critical",estimatedTokens:140,applicableScenarios:["architecture"]},error_recovery_basic:{name:"error_recovery_basic",contentZh:"edit_file\u5931\u8D25\uFF1A\u91CD\u65B0 readfile(path, for_edit=true)\uFF0C\u7F29\u5C0F old_string\uFF0C\u5FC5\u8981\u65F6\u52A0 change_context\u3002\u5931\u8D252\u6B21\u6539\u7528 write_file\u3002",contentEn:"edit_file fails: Re-readfile(path, for_edit=true), reduce old_string, add change_context if needed. Fail 2x, use write_file.",priority:"optional",estimatedTokens:40,applicableScenarios:["bugfix","single_file_edit"]},error_recovery:{name:"error_recovery",contentZh:`## \u9519\u8BEF\u6062\u590D
1127
+ - edit\u5931\u8D25\uFF1A\u91CD\u65B0 readfile(path, for_edit=true)\uFF0C\u7F29\u5C0F old_string\uFF0C\u5FC5\u8981\u65F6\u52A0 change_context
1128
+ - \u8FDE\u7EED\u5931\u8D253\u6B21\uFF1A\u505C\u6B62\u5F53\u524D\u65B9\u6CD5\uFF0C\u62A5\u544A\u7ED9\u7528\u6237
1129
+ - \u8DEF\u5F84\u95EE\u9898\uFF1A\u68C0\u67E5 cd /\u7EDD\u5BF9\u8DEF\u5F84 &&`,contentEn:`## Error Recovery
1130
+ - edit fails: Re-readfile(path, for_edit=true), reduce old_string, add change_context if needed
1131
+ - 3 consecutive fails: Stop current approach, report to user
1132
+ - Path issues: Check cd /absolute/path &&`,priority:"optional",estimatedTokens:80,applicableScenarios:["multi_file_edit","feature_add","refactor"]},file_creation_policy:{name:"file_creation_policy",contentZh:"\u7981\u6B62\u81EA\u52A8\u521B\u5EFA\uFF1AREADME.md, test.html, summary.md, *.bak \u7B49\uFF08\u9664\u975E\u660E\u786E\u8981\u6C42\uFF09",contentEn:"Don't auto-create: README.md, test.html, summary.md, *.bak etc (unless explicitly requested)",priority:"optional",estimatedTokens:40,applicableScenarios:["feature_add","multi_file_edit"]},large_file_chunking:{name:"large_file_chunking",contentZh:`## \u5927\u6587\u4EF6\u5206\u5757\u5199\u5165
1133
+ \u8D85\u8FC7 300 \u884C\u7684\u6587\u4EF6\u5FC5\u987B\u5206\u5757\u5199\u5165\uFF1A
1134
+ 1. write_file \u521B\u5EFA\u9AA8\u67B6\uFF08imports + \u7B7E\u540D + TODO\u5360\u4F4D\uFF09
1135
+ 2. edit_file \u9010\u5757\u66FF\u6362 TODO \u4E3A\u5B9E\u9645\u4EE3\u7801
1136
+ 3. \u6BCF\u5757 < 200 \u884C`,contentEn:`## Large File Chunking
1137
+ Files > 300 lines must be written in chunks:
1138
+ 1. write_file to create skeleton (imports + signatures + TODO placeholders)
1139
+ 2. edit_file to replace TODOs with actual code section by section
1140
+ 3. Each chunk < 200 lines`,priority:"important",estimatedTokens:80,applicableScenarios:["feature_add","multi_file_edit"]}};function Kd(s){return hl[s]}function Lb(s){return hl[s].modules.map(t=>Mb[t]).filter(t=>t!==void 0)}function Ob(s,e){return e==="zh"?s.contentZh:s.contentEn}function Db(s){return s.reduce((e,t)=>e+t.estimatedTokens,0)}function Vd(s,e,t="zh"){let n=Lb(s),r=[];r.push(t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}`:`Working directory: ${e}`),r.push("");for(let i of n)r.push(Ob(i,t));return r.push(""),r.push(t==="zh"?"\u5F00\u59CB\u5DE5\u4F5C\u3002":"Start working."),{prompt:r.join(`
1141
+ `),modules:n.map(i=>i.name),tokens:Db(n)}}function Yd(s){let{task:e,workDir:t,language:n="zh",planMode:r,iteration:i}=s,o=Wi.classify(e,{currentIteration:i}),a=r?"architecture":o.taskType,l=Kd(a),{prompt:c,modules:u,tokens:d}=Vd(a,t,n);if(process.env.CLI_DEBUG_CONSOLE==="1"){let p=e.length>30?e.substring(0,30)+"...":e;console.log(`[Prompt] "${p}" \u2192 ${l.name} (~${d} tokens)`);}return process.env.CLI_DEBUG_PROMPT==="1"&&(console.log(`
1142
+ `+"=".repeat(60)),console.log("[SYSTEM PROMPT]"),console.log("=".repeat(60)),console.log(`Task Type: ${a} (${o.confidence*100}%)`),console.log(`Scenario: ${l.name}`),console.log(`Modules: ${u.join(", ")}`),console.log(`Tokens: ~${d}`),console.log("-".repeat(60)),console.log(c),console.log("=".repeat(60)+`
1143
+ `)),{prompt:c,taskType:a,taskClassification:o,modules:u,estimatedTokens:d,scenarioName:l.name}}function Xd(s){let{workDir:e,language:t="zh"}=s;return t==="en"?$b(e):Nb(e)}function $b(s){return `You are a code modification agent and must follow these rules.
1144
+
1145
+ Environment
1146
+
1147
+ - Working directory: ${s}
1148
+ - Shell calls are independent; cd does not persist across calls
1149
+
1150
+ \u26D4 Hard Rules (Violation = Failure)
1151
+
1152
+ Rule 1: Structure First, Then Search
1153
+
1154
+ - Before the first grep, you must run smart_tree(mode="structure") to get the project structure
1155
+ - Tree output is only for understanding project layout and narrowing scope when needed
1156
+ - Example:
1157
+ tree \u2192 {"root_dirs": ["src","test"], "modules": ["auth","order"]}
1158
+ search(pattern="login") \u2190 Search entire project first
1159
+
1160
+ Rule 2: Search Strategy - Start Broad, Then Narrow
1161
+
1162
+ - \u2705 Correct: First search entire project without path, then narrow if needed
1163
+ search(pattern="login") \u2190 Search entire project first
1164
+ search(pattern="login", path="src/auth/") \u2190 Narrow if too many results
1165
+ - \u274C Wrong: Always specifying a subdirectory without searching root first
1166
+ - tree output's root_dirs helps narrow scope, but root directory may also contain files
1167
+ - Strategy: Search without path first; if results > 50, narrow to specific root_dirs
1168
+
1169
+ Rule 3: 0 Matches Requires Strategy Adjustment
1170
+
1171
+ - When grep returns 0 matches, you must immediately:
1172
+ a. Expand search scope (change path)
1173
+ b. Adjust keywords (change pattern)
1174
+ c. Try case_insensitive=true
1175
+ - Do not repeat the same parameters
1176
+ - After 3 failed attempts, return a prompt and stop
1177
+
1178
+ Rule 4: Use readfile for Precise Code Reading
1179
+
1180
+ - Use readfile(path, symbol="function_name") to locate and read functions/classes
1181
+ - Use readfile(path, pattern="keyword") to search and read context
1182
+ - Use readfile(path, pattern="keyword", list_matches=true) to list match lines first
1183
+ - Use readfile(path, anchor_lines=[...], num_lines=200) or ranges=[...] for batch reads
1184
+ - Use readfile(path, start_line=N, num_lines=200) to read by line range
1185
+ - Use readfile(path, for_edit=true) before edit_file to capture the latest content
1186
+ - Small files (\u2264700 lines) auto full; for large files, locate before reading
1187
+ - Prefer symbol; use pattern only when symbol doesn't exist
1188
+ - Forbidden: Guessing line numbers to read files directly
1189
+
1190
+ Rule 5: Explain Before Editing
1191
+
1192
+ - Before modification, you must specify:
1193
+ a. File path
1194
+ b. Modification action
1195
+ c. Modification reason
1196
+ d. Before text + After text example
1197
+ - Example:
1198
+ Modifying src/auth/login.ts:42
1199
+ Original: setTimeout(doLogin, 5000)
1200
+ Modified: setTimeout(doLogin, 10000)
1201
+ Reason: User reported login timeout
1202
+
1203
+ Rule 6: Edit Strategy (MANDATORY)
1204
+
1205
+ \u{1F525} IMPORTANT: edit_file uses robust line matching:
1206
+ - You MUST readfile before edit_file (guardrail)
1207
+ - Keep old_string small and specific (minimal block)
1208
+ - Use change_context to anchor the location when snippets repeat
1209
+ - Matching is tolerant (exact -> trim_end -> trim -> normalize), but be precise to avoid ambiguity
1210
+ - After a successful edit, readfile again before the next edit
1211
+
1212
+ Large file chunked writing (only when necessary):
1213
+ a. Over 300 lines or 10KB \u2192 Write in chunks, each chunk <200 lines
1214
+ b. First step write_file: Create skeleton structure
1215
+ c. Subsequent edit_file: Replace sections one by one (readfile before each edit!)
1216
+
1217
+ Rule 7: Understand Tool Results
1218
+
1219
+ - write_file / edit_file return structured results:
1220
+ - "status": "success" + "final": true" \u2192 Modification successful, do not repeat
1221
+ - "status": "already_done" \u2192 Already complete, proceed to next task
1222
+ - "status": "error" \u2192 Read error message and fix
1223
+ - After modification, use readfile to verify key functions/classes
1224
+ - If readfile fails \u2192 Expand scope or adjust keywords, then retry
1225
+
1226
+ Rule 8: Use Specialized Tools
1227
+
1228
+ - Git: git_status / git_diff / git_blame / git_branch_list / git_branch / git_commit
1229
+ - File ops: delete_file / rename_file / apply_patch
1230
+ - Navigation: search_symbol / get_definitions / get_references (use index when available)
1231
+ - Tests: run_tests / run_lint / run_format (avoid raw shell for these)
1232
+ - If you hit iteration/tool/runtime limits, summarize progress and ask to continue
1233
+
1234
+ Standard Workflow
1235
+
1236
+ Step 1: smart_tree(mode="structure")
1237
+ \u2192 {"root_dirs": ["src","test"], "modules": ["auth","order"]}
1238
+
1239
+ Step 2: search(pattern="keyword") \u2190 Search entire project first (no path)
1240
+ \u2192 "[root] login.ts:10: ...", "[auth] src/auth/login.ts:42: function handleLogin"
1241
+
1242
+ Step 3: readfile("src/auth/login.ts", symbol="handleLogin")
1243
+ \u2192 Precisely read handleLogin function
1244
+
1245
+ Step 4: Explain modification intent
1246
+ \u2192 "Modifying src/auth/login.ts:45, adding error handling"
1247
+
1248
+ Step 5: edit_file(...)
1249
+
1250
+ Output Requirements
1251
+
1252
+ - Reply in Chinese
1253
+ - Brief confirmation after operations
1254
+ - Do not create files the user did not request
1255
+ - When encountering errors, verify with readfile first, do not blindly repeat operations
1256
+
1257
+ Begin work.`}function Nb(s){return `\u4F60\u662F\u4EE3\u7801\u4FEE\u6539\u578B Agent\uFF0C\u5FC5\u987B\u9075\u5FAA\u4EE5\u4E0B\u89C4\u5219\u3002
1258
+
1259
+ ## \u73AF\u5883
1260
+ - \u5DE5\u4F5C\u76EE\u5F55: ${s}
1261
+ - Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED
1262
+
1263
+ ## \u26D4 \u786C\u6027\u89C4\u5219\uFF08\u8FDD\u53CD\u5373\u5931\u8D25\uFF09
1264
+
1265
+ ### \u89C4\u5219 1: \u5148\u7ED3\u6784\uFF0C\u518D\u641C\u7D22
1266
+ - \u9996\u6B21 grep \u524D\uFF0C\u5FC5\u987B\u5148 \`smart_tree(mode="structure")\` \u83B7\u53D6\u9879\u76EE\u7ED3\u6784
1267
+ - tree \u8F93\u51FA\u7528\u4E8E\u4E86\u89E3\u9879\u76EE\u5E03\u5C40\uFF0C\u5FC5\u8981\u65F6\u7F29\u5C0F\u641C\u7D22\u8303\u56F4
1268
+ - **\u793A\u4F8B**\uFF1A
1269
+ tree \u2192 {"root_dirs": ["src","test"], "modules": ["auth","order"]}
1270
+ search(pattern="login") \u2190 \u5148\u641C\u7D22\u6574\u4E2A\u9879\u76EE
1271
+
1272
+ ### \u89C4\u5219 2: \u641C\u7D22\u7B56\u7565 - \u5148\u5E7F\u540E\u7A84
1273
+ - \u2705 \u6B63\u786E\uFF1A\u5148\u641C\u7D22\u6574\u4E2A\u9879\u76EE\uFF0C\u518D\u7F29\u5C0F\u8303\u56F4
1274
+ \`search(pattern="login")\` \u2190 \u5148\u641C\u7D22\u6574\u4E2A\u9879\u76EE
1275
+ \`search(pattern="login", path="src/auth/")\` \u2190 \u7ED3\u679C\u592A\u591A\u65F6\u518D\u7F29\u5C0F
1276
+ - \u274C \u9519\u8BEF\uFF1A\u4E0D\u641C\u7D22\u6839\u76EE\u5F55\uFF0C\u76F4\u63A5\u6307\u5B9A\u5B50\u76EE\u5F55
1277
+ - tree \u8F93\u51FA\u7684 root_dirs \u7528\u4E8E\u7F29\u5C0F\u8303\u56F4\uFF0C\u4F46\u6839\u76EE\u5F55\u672C\u8EAB\u4E5F\u53EF\u80FD\u6709\u6587\u4EF6
1278
+ - **\u7B56\u7565**\uFF1A\u5148\u4E0D\u5E26 path \u641C\u7D22\uFF1B\u7ED3\u679C\u8D85\u8FC7 50 \u6761\u518D\u7F29\u5C0F\u5230 root_dirs
1279
+
1280
+ ### \u89C4\u5219 3: 0 \u5339\u914D\u5FC5\u987B\u8C03\u6574\u7B56\u7565
1281
+ - grep \u8FD4\u56DE 0 matches \u65F6\uFF0C\u5FC5\u987B\u7ACB\u523B\uFF1A
1282
+ 1. \u6269\u5927\u641C\u7D22\u8303\u56F4\uFF08\u6362 path\uFF09
1283
+ 2. \u8C03\u6574\u5173\u952E\u8BCD\uFF08\u6362 pattern\uFF09
1284
+ 3. \u5C1D\u8BD5 case_insensitive=true
1285
+ - \u4E0D\u5F97\u91CD\u590D\u4F7F\u7528\u76F8\u540C\u53C2\u6570
1286
+ - \u8D85\u8FC7 3 \u6B21\u4ECD\u65E0\u7ED3\u679C\uFF0C\u5219\u8FD4\u56DE\u63D0\u793A\u5E76\u505C\u6B62
1287
+
1288
+ ### \u89C4\u5219 4: \u4F7F\u7528 readfile \u7CBE\u51C6\u8BFB\u53D6\u4EE3\u7801
1289
+ - \u4F7F\u7528 \`readfile(path, symbol="\u51FD\u6570\u540D")\` \u5B9A\u4F4D\u5E76\u8BFB\u53D6\u51FD\u6570/\u7C7B
1290
+ - \u4F7F\u7528 \`readfile(path, pattern="\u5173\u952E\u8BCD")\` \u641C\u7D22\u5E76\u8BFB\u53D6\u4E0A\u4E0B\u6587
1291
+ - \u4F7F\u7528 \`readfile(path, start_line=N, num_lines=200)\` \u6309\u884C\u8BFB\u53D6
1292
+ - edit_file \u524D\u7528 \`readfile(path, for_edit=true)\` \u83B7\u53D6\u6700\u65B0\u5185\u5BB9\uFF08\u5EFA\u8BAE\uFF09
1293
+ - symbol \u4F18\u5148\uFF0Csymbol \u4E0D\u5B58\u5728\u518D\u7528 pattern
1294
+ - **\u7981\u6B62**\uFF1A\u731C\u6D4B\u884C\u53F7\u76F4\u63A5\u8BFB\u53D6\u6587\u4EF6
1295
+
1296
+ ### \u89C4\u5219 5: edit \u524D\u5FC5\u987B\u8BF4\u660E
1297
+ - \u4FEE\u6539\u524D\u5FC5\u987B\u660E\u786E\uFF1A
1298
+ 1. \u6587\u4EF6\u8DEF\u5F84
1299
+ 2. \u4FEE\u6539\u884C\u4E3A
1300
+ 3. \u4FEE\u6539\u7406\u7531
1301
+ 4. \u4FEE\u6539\u524D\u6587\u672C + \u4FEE\u6539\u540E\u6587\u672C\u793A\u4F8B
1302
+ - **\u793A\u4F8B**\uFF1A
1303
+ \u4FEE\u6539 src/auth/login.ts:42
1304
+ \u539F\u6587\u672C: setTimeout(doLogin, 5000)
1305
+ \u4FEE\u6539: setTimeout(doLogin, 10000)
1306
+ \u7406\u7531: \u7528\u6237\u53CD\u9988\u767B\u5F55\u8D85\u65F6
1307
+
1308
+ ### \u89C4\u5219 6: \u7F16\u8F91\u7B56\u7565\uFF08\u5F3A\u5236\uFF09
1309
+
1310
+ \u{1F525} \u91CD\u8981\uFF1Aedit_file \u4F7F\u7528\u7A33\u5065\u5339\u914D\uFF1A
1311
+ - \u7F16\u8F91\u524D\u5FC5\u987B\u5148 readfile\uFF08guardrail\uFF09
1312
+ - old_string \u4FDD\u6301\u77ED\u5C0F\u4E14\u552F\u4E00\uFF0C\u5FC5\u8981\u65F6\u63D0\u4F9B change_context \u4F5C\u4E3A\u951A\u70B9
1313
+ - \u5339\u914D\u5BB9\u5FCD\u7A7A\u767D/\u6807\u70B9\u5DEE\u5F02\uFF0C\u4F46\u4ECD\u5E94\u5C3D\u91CF\u7CBE\u786E\u907F\u514D\u6B67\u4E49
1314
+ - \u6210\u529F\u7F16\u8F91\u540E\u8BF7\u91CD\u65B0 readfile \u518D\u8FDB\u884C\u4E0B\u4E00\u6B21\u7F16\u8F91
1315
+
1316
+ \u5927\u6587\u4EF6\u5206\u5757\u5199\u5165\uFF08\u5FC5\u8981\u65F6\uFF09\uFF1A
1317
+ 1. \u8D85\u8FC7 300 \u884C\u6216 10KB \u2192 \u5206\u5757\u5199\u5165\uFF0C\u6BCF\u5757 <200\u884C
1318
+ 2. \u7B2C\u4E00\u6B65 write_file\uFF1A\u521B\u5EFA\u9AA8\u67B6\u7ED3\u6784
1319
+ 3. \u540E\u7EED edit_file\uFF1A\u9010\u5757\u66FF\u6362\uFF08\u6BCF\u6B21\u7F16\u8F91\u524D\u90FD\u8981 readfile\uFF01\uFF09
1320
+
1321
+ ### \u89C4\u5219 7: \u7406\u89E3\u5DE5\u5177\u7ED3\u679C
1322
+ - write_file / edit_file \u8FD4\u56DE\u7ED3\u6784\u5316\u7ED3\u679C\uFF1A
1323
+ - \`"status": "success" + "final": true"\` \u2192 \u4FEE\u6539\u6210\u529F\uFF0C\u4E0D\u91CD\u590D\u64CD\u4F5C
1324
+ - \`"status": "already_done"\` \u2192 \u5DF2\u5B8C\u6210\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u4E2A\u4EFB\u52A1
1325
+ - \`"status": "error"\` \u2192 \u8BFB\u53D6\u9519\u8BEF\u4FE1\u606F\u5E76\u4FEE\u590D
1326
+ - \u4FEE\u6539\u5B8C\u6210\u540E\u4F7F\u7528 \`readfile\` \u9A8C\u8BC1\u5173\u952E\u51FD\u6570/\u7C7B\u5185\u5BB9
1327
+ - readfile \u5931\u8D25 \u2192 \u6269\u5927\u8303\u56F4\u6216\u8C03\u6574\u5173\u952E\u8BCD\uFF0C\u518D\u5C1D\u8BD5
1328
+
1329
+ ### \u89C4\u5219 8: \u4F7F\u7528\u4E13\u7528\u5DE5\u5177
1330
+ - Git\uFF1A\`git_status\` / \`git_diff\` / \`git_blame\` / \`git_branch_list\` / \`git_branch\` / \`git_commit\`
1331
+ - \u6587\u4EF6\u64CD\u4F5C\uFF1A\`delete_file\` / \`rename_file\` / \`apply_patch\`
1332
+ - \u5BFC\u822A\uFF1A\`search_symbol\` / \`get_definitions\` / \`get_references\`\uFF08\u7D22\u5F15\u53EF\u7528\u65F6\u4F18\u5148\uFF09
1333
+ - \u6D4B\u8BD5\uFF1A\`run_tests\` / \`run_lint\` / \`run_format\`\uFF08\u907F\u514D\u7528 shell \u4EE3\u66FF\uFF09
1334
+ - \u82E5\u89E6\u8FBE\u8FED\u4EE3/\u5DE5\u5177/\u8FD0\u884C\u65F6\u95F4\u9650\u5236\uFF0C\u5148\u603B\u7ED3\u8FDB\u5EA6\u5E76\u8BE2\u95EE\u662F\u5426\u7EE7\u7EED
1335
+
1336
+ ## \u6807\u51C6\u5DE5\u4F5C\u6D41
1337
+
1338
+ \`\`\`
1339
+ Step 1: smart_tree(mode="structure")
1340
+ \u2192 {"root_dirs": ["src","test"], "modules": ["auth","order"]}
1341
+
1342
+ Step 2: search(pattern="\u5173\u952E\u8BCD") \u2190 \u5148\u641C\u7D22\u6574\u4E2A\u9879\u76EE\uFF08\u4E0D\u5E26 path\uFF09
1343
+ \u2192 "[root] login.ts:10: ...", "[auth] src/auth/login.ts:42: function handleLogin"
1344
+
1345
+ Step 3: readfile("src/auth/login.ts", symbol="handleLogin")
1346
+ \u2192 \u7CBE\u51C6\u8BFB\u53D6 handleLogin \u51FD\u6570
1347
+
1348
+ Step 4: \u8BF4\u660E\u4FEE\u6539\u610F\u56FE
1349
+ \u2192 "\u4FEE\u6539 src/auth/login.ts:45\uFF0C\u6DFB\u52A0\u9519\u8BEF\u5904\u7406"
1350
+
1351
+ Step 5: edit_file(...)
1352
+ \`\`\`
1353
+
1354
+ ## \u8F93\u51FA\u8981\u6C42
1355
+ - \u7528\u4E2D\u6587\u56DE\u590D
1356
+ - \u64CD\u4F5C\u540E\u7B80\u77ED\u786E\u8BA4
1357
+ - \u4E0D\u521B\u5EFA\u7528\u6237\u672A\u8981\u6C42\u7684\u6587\u4EF6
1358
+ - \u9047\u5230\u9519\u8BEF\u4F18\u5148\u7528 readfile \u9A8C\u8BC1\uFF0C\u4E0D\u76F2\u76EE\u91CD\u590D\u64CD\u4F5C
1359
+
1360
+ \u5F00\u59CB\u5DE5\u4F5C\u3002`}function Zd(s){return s===15?`\u{1F4E2} \u63D0\u793A\uFF1A\u5DF2\u8FED\u4EE3 15 \u6B21\u3002\u8BF7\u68C0\u67E5\uFF1A
1361
+ 1. \u662F\u5426\u9677\u5165\u4E86\u91CD\u590D\u7684\u5DE5\u5177\u8C03\u7528\u5FAA\u73AF
1362
+ 2. edit_file \u662F\u5426\u53CD\u590D\u5931\u8D25 - \u8003\u8651\u7528 write_file
1363
+ 3. \u662F\u5426\u5728\u8FC7\u5EA6\u9A8C\u8BC1 - \u64CD\u4F5C\u5B8C\u6210\u540E\u4E0D\u9700\u8981\u53CD\u590D\u68C0\u67E5
1364
+ \u8BF7\u5C3D\u5FEB\u5B8C\u6210\u6838\u5FC3\u4EFB\u52A1\u3002`:s===25?`\u26A0\uFE0F \u8B66\u544A\uFF1A\u5DF2\u8FED\u4EE3 25 \u6B21\u3002\u8FD9\u53EF\u80FD\u8868\u793A\uFF1A
1365
+ 1. \u5DE5\u5177\u4F7F\u7528\u7B56\u7565\u9700\u8981\u8C03\u6574
1366
+ 2. \u4EFB\u52A1\u8303\u56F4\u53EF\u80FD\u8D85\u51FA\u9884\u671F
1367
+ \u8BF7\u7ACB\u5373\u5B8C\u6210\u6216\u62A5\u544A\u65E0\u6CD5\u5B8C\u6210\u7684\u539F\u56E0\u3002`:s===35?`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1A\u5DF2\u8FED\u4EE3 35 \u6B21\u3002
1368
+ 1. \u8BF7\u7ACB\u5373\u505C\u6B62\u5E76\u603B\u7ED3\u5F53\u524D\u8FDB\u5EA6
1369
+ 2. \u62A5\u544A\u9047\u5230\u7684\u963B\u585E\u95EE\u9898
1370
+ 3. \u8BA9\u7528\u6237\u51B3\u5B9A\u4E0B\u4E00\u6B65\u884C\u52A8`:null}function Qd(s,e){return e!=="edit_file"?null:s===2?`\u26A0\uFE0F edit_file \u8FDE\u7EED\u5931\u8D25 2 \u6B21\u3002\u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\uFF1A
1371
+ 1. \u4F7F\u7528 readfile(path, for_edit=true) \u91CD\u65B0\u8BFB\u53D6\u76EE\u6807\u6587\u4EF6\u7684\u76F8\u5173\u90E8\u5206
1372
+ 2. \u7F29\u5C0F old_string \u4E3A\u6700\u5C0F\u53EF\u552F\u4E00\u5B9A\u4F4D\u7684\u5757
1373
+ 3. \u5FC5\u8981\u65F6\u589E\u52A0 change_context \u4F5C\u4E3A\u951A\u70B9
1374
+ 4. \u5982\u679C\u4ECD\u7136\u5931\u8D25\uFF0C\u8003\u8651\u7528 write_file \u91CD\u5199\u6574\u4E2A\u6587\u4EF6
1375
+ 5. \u7981\u6B62\u4F7F\u7528 sed/awk \u7B49 shell \u547D\u4EE4\u4F5C\u4E3A\u66FF\u4EE3\u65B9\u6848`:s>=3?`\u{1F534} edit_file \u8FDE\u7EED\u5931\u8D25 ${s} \u6B21\u3002
1376
+ \u5EFA\u8BAE\u7ACB\u5373\u4F7F\u7528 write_file \u91CD\u5199\u6574\u4E2A\u6587\u4EF6\u3002
1377
+ \u7981\u6B62\u7EE7\u7EED\u5C1D\u8BD5 edit_file \u6216\u4F7F\u7528 shell \u547D\u4EE4\u7F16\u8F91\u3002`:null}le();var fl=class{history=[];maxHistory=20;interventionCount=0;hashArgs(e,t){let n={};e==="readfile"?Object.assign(n,t):e==="edit_file"||e==="Edit"?(n.file_path=t.file_path||t.path,t.old_string&&typeof t.old_string=="string"&&(n.old_string_prefix=t.old_string.substring(0,200))):e==="write_file"||e==="Write"?n.file_path=t.file_path||t.path:t.file_path?n.file_path=t.file_path:t.path?n.path=t.path:t.directory?n.directory=t.directory:Object.assign(n,t);let r=`${e}:${JSON.stringify(n)}`;return createHash("sha256").update(r).digest("hex").substring(0,16)}record(e,t,n){let r=this.hashArgs(e,t),i=t.file_path||t.path||t.directory;this.history.push({hash:r,toolName:e,args:t,timestamp:Date.now(),resultStatus:n,filePath:i}),this.history.length>this.maxHistory&&this.history.shift();}updateLastStatus(e){this.history.length>0&&(this.history[this.history.length-1].resultStatus=e);}detect(e,t){let n=this.hashArgs(e,t),r=this.history.filter(i=>i.hash===n);return r.length>=4?4:r.length>=3?3:r.length>=2?2:0}wasLastSuccessful(e,t){let n=this.hashArgs(e,t),r=[...this.history].reverse().find(i=>i.hash===n);return r?.resultStatus==="success"||r?.resultStatus==="already_done"}getLastFilePath(e,t){let n=this.hashArgs(e,t);return [...this.history].reverse().find(i=>i.hash===n)?.filePath}didSwitchTool(e){return this.history.length<2?true:this.history[this.history.length-1]?.toolName!==e}incrementIntervention(){return ++this.interventionCount}getInterventionCount(){return this.interventionCount}generateIntervention(e,t,n){let r=this.getLastFilePath(t,n)||n.file_path||n.path||n.directory,i=this.wasLastSuccessful(t,n),o=this.getVerifyCommand(t,r),a=this.getAlternativeAction(t,r);switch(e){case 2:return {level:e,wasSuccessful:i,shouldTerminate:false,message:`
1378
+ [SYSTEM NOTICE]
1379
+ You have called "${t}" ${this.getCallCount(t,n)} times with similar arguments.
1380
+ ${i?"\u26A0\uFE0F Previous calls already returned SUCCESS.":""}
1381
+
1382
+ STOP and think:
1383
+ 1. ${a}
1384
+ 2. If you already have the information you need, proceed with your task
1385
+ 3. Do NOT call ${t} again with the same arguments
1386
+
1387
+ ${o?`To verify: ${o}`:""}
1388
+ `.trim()};case 3:return {level:e,wasSuccessful:i,shouldTerminate:false,message:`
1389
+ [SYSTEM WARNING]
1390
+ You have called "${t}" ${this.getCallCount(t,n)} times with identical arguments.
1391
+ ${i?"\u2705 Previous calls returned SUCCESS - the operation already completed!":""}
1392
+
1393
+ \u{1F6D1} REQUIRED ACTION:
1394
+ 1. STOP calling ${t}
1395
+ 2. ${a}
1396
+ 3. If stuck, ask the user for help
1397
+
1398
+ Next ${t} call with same arguments will TERMINATE the task.
1399
+ `.trim()};case 4:return {level:e,wasSuccessful:i,shouldTerminate:true,message:i?`
1400
+ [TASK COMPLETED]
1401
+ The "${t}" operation has already succeeded (called ${this.getCallCount(t,n)} times).
1402
+
1403
+ ${r?`\u2705 File: ${r}`:""}
1404
+ The data you need should already be available from previous calls.
1405
+ `.trim():`
1406
+ [TASK TERMINATED]
1407
+ Unable to complete after ${this.getCallCount(t,n)} attempts with "${t}".
1408
+
1409
+ Please:
1410
+ - Check if the file/path exists
1411
+ - Verify your approach
1412
+ - Try a different method
1413
+ `.trim()};default:return {level:0,shouldTerminate:false,message:""}}}getVerifyCommand(e,t){return e==="readfile"?t?"Use search to locate specific content, or list_directory to check if file exists":"":e==="write_file"||e==="Write"||e==="edit_file"||e==="Edit"?t?`Use readfile "${t}" to verify the changes`:"":e==="search"||e==="search_files"||e==="Glob"?"Try a different search pattern or read the file directly":e==="execute_shell"||e==="execute_bash"||e==="Bash"?"Check the command output from previous calls":""}getAlternativeAction(e,t){return e==="readfile"?"The file content should already be in your context from previous reads - use it directly":e==="write_file"||e==="Write"?"The file was already written - verify with readfile if needed":e==="edit_file"||e==="Edit"?"The edit may have already been applied - use readfile to check current content":e==="search"||e==="search_files"||e==="Glob"?"Search results should already be available - try a different pattern if not found":"Review the output from previous calls before retrying"}getCallCount(e,t){let n=this.hashArgs(e,t);return this.history.filter(r=>r.hash===n).length}reset(){this.history=[],this.interventionCount=0;}getHistory(){return [...this.history]}getRecentDuplicates(){let e=new Map;for(let t of this.history){let n=`${t.toolName}:${t.hash}`;e.set(n,(e.get(n)||0)+1);}return e}};function ep(){return new fl}Hi();var gl={write_file:"ephemeral",Write:"ephemeral",edit_file:"ephemeral",Edit:"ephemeral",create_directory:"ephemeral",mkdir:"ephemeral",delete_file:"ephemeral",rename_file:"ephemeral",apply_patch:"ephemeral",move_file:"ephemeral",copy_file:"ephemeral",git_commit:"ephemeral",git_add:"ephemeral",git_push:"ephemeral",git_checkout:"ephemeral",git_branch:"ephemeral",git_merge:"ephemeral",git_stash:"ephemeral",npm_install:"ephemeral",npm_uninstall:"ephemeral",pip_install:"ephemeral",readfile:"contextual",search:"contextual",grep:"contextual",Grep:"contextual",glob:"contextual",Glob:"contextual",search_files:"contextual",ripgrep:"contextual",ls:"contextual",list_directory:"contextual",show_tree:"contextual",git_diff:"contextual",git_status:"contextual",git_blame:"contextual",git_branch_list:"contextual",git_log:"contextual",git_show:"contextual",web_search:"contextual",WebSearch:"contextual",web_fetch:"contextual",WebFetch:"contextual",analyze_code:"contextual",search_symbol:"contextual",get_definitions:"contextual",get_references:"contextual",execute_shell:"summarized",Bash:"summarized",bash:"summarized",shell:"summarized",run_tests:"summarized",run_lint:"summarized",run_format:"summarized",test:"summarized",pytest:"summarized",jest:"summarized",build:"summarized",compile:"summarized",npm_build:"summarized",code_interpreter:"summarized",python_exec:"summarized",browser_debug:"summarized"};function yl(s){if(s in gl)return gl[s];let e=s.toLowerCase();for(let[t,n]of Object.entries(gl))if(t.toLowerCase()===e)return n;return "contextual"}function np(s){return yl(s)==="contextual"}vt();var vn=class{config;toolPermissions=new Map;permissionMemory=new Map;constructor(e={}){this.config=e;}setToolPermission(e){this.toolPermissions.set(e.toolName,e);}setToolPermissions(e){e.forEach(t=>this.setToolPermission(t));}async checkPermission(e,t){let n=e.name,r=this.getToolCategory(e),i=this.getToolPermission(e);if(i==="deny")return {allowed:false,source:"config",reason:this.toolPermissions.get(n)?.reason||`Tool "${n}" is denied`};if(i==="allow")return {allowed:true,source:"config"};let o=this.checkMemory(n);if(o)return {allowed:o.decision,source:"remembered",reason:o.decision?void 0:"User previously denied this tool"};if(!this.config.approvalHandler)return {allowed:false,source:"config",reason:"Tool requires approval but no approval handler is set",needsApproval:true};try{let a=this.toolPermissions.get(n),l=await this.config.approvalHandler({toolName:n,toolCategory:r,args:t,reason:a?.reason,allowRemember:a?.allowRemember??!0});return l.remember&&this.saveMemory(n,l.approved),{allowed:l.approved,source:"user",reason:l.approved?void 0:"User denied approval",remember:l.remember}}catch(a){return {allowed:false,source:"config",reason:`Approval handler failed: ${a instanceof Error?a.message:String(a)}`}}}getToolPermission(e){let t=this.toolPermissions.get(e.name);return t?t.permission:e.permission?.defaultPermission?e.permission.defaultPermission:this.config.defaultPermission??"ask"}getToolCategory(e){return e.permission?.category?e.permission.category:this.inferToolCategory(e.name)}inferToolCategory(e){let t=e.toLowerCase();return t.includes("read")||t.includes("grep")||t.includes("glob")||t.includes("search")||t.includes("list")||t.includes("show")?"read":t.includes("write")||t.includes("edit")||t.includes("create")||t.includes("delete")||t.includes("update")?"write":t.includes("bash")||t.includes("exec")||t.includes("run")||t.includes("command")?"execute":t.includes("fetch")||t.includes("request")||t.includes("api")||t.includes("http")||t.includes("download")?"network":"system"}checkMemory(e){let t=this.permissionMemory.get(e);return t?t.expiresAt&&Date.now()>t.expiresAt?(this.permissionMemory.delete(e),null):t:null}saveMemory(e,t){let n=this.config.memoryExpirationMs?Date.now()+this.config.memoryExpirationMs:void 0;this.permissionMemory.set(e,{toolName:e,decision:t,timestamp:Date.now(),expiresAt:n});}clearMemory(e){e?this.permissionMemory.delete(e):this.permissionMemory.clear();}setApprovalHandler(e){this.config.approvalHandler=e;}};vt();var Bb=[{toolName:"readfile",permission:"allow"},{toolName:"search_symbol",permission:"allow"},{toolName:"get_definitions",permission:"allow"},{toolName:"get_references",permission:"allow"},{toolName:"search",permission:"allow"},{toolName:"search_files",permission:"allow"},{toolName:"list_directory",permission:"allow"},{toolName:"show_tree",permission:"allow"},{toolName:"git_status",permission:"allow"},{toolName:"git_diff",permission:"allow"},{toolName:"git_blame",permission:"allow"},{toolName:"git_branch_list",permission:"allow"},{toolName:"smart_tree",permission:"allow"},{toolName:"analyze_code",permission:"allow"},{toolName:"write_file",permission:"ask",reason:"This will create or overwrite a file",allowRemember:true},{toolName:"edit_file",permission:"ask",reason:"This will modify an existing file",allowRemember:true},{toolName:"create_directory",permission:"ask",reason:"This will create a directory",allowRemember:true},{toolName:"delete_file",permission:"ask",reason:"This will permanently delete files or directories",allowRemember:false},{toolName:"rename_file",permission:"ask",reason:"This will rename or move files or directories",allowRemember:true},{toolName:"apply_patch",permission:"ask",reason:"This will apply a patch to the repository",allowRemember:true},{toolName:"git_branch",permission:"ask",reason:"This will create or switch git branches",allowRemember:true},{toolName:"git_commit",permission:"ask",reason:"This will create a git commit",allowRemember:true},{toolName:"build_index",permission:"ask",reason:"This will build a local code index",allowRemember:true},{toolName:"execute_shell",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_bash",permission:"ask",reason:"WARNING: running shell commands can modify your system",allowRemember:false},{toolName:"execute_python",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"execute_javascript",permission:"ask",reason:"WARNING: executing code can modify files or run external commands",allowRemember:false},{toolName:"debug_in_browser",permission:"ask",reason:"WARNING: this will launch a browser session",allowRemember:false},{toolName:"run_tests",permission:"ask",reason:"WARNING: running tests executes project code",allowRemember:false},{toolName:"run_lint",permission:"ask",reason:"WARNING: running lint executes project tools",allowRemember:false},{toolName:"run_format",permission:"ask",reason:"WARNING: running format executes project tools",allowRemember:false},{toolName:"web_fetch",permission:"ask",reason:"This will make a network request",allowRemember:true},{toolName:"web_search",permission:"ask",reason:"This will make a network request",allowRemember:true}];function vl(s){s.setToolPermissions(Bb);}var xn=class{static strategies=new Map;static register(e){this.strategies.set(e.mode,e);}static getStrategy(e){let t=this.strategies.get(e);if(!t)throw new Error(`No strategy registered for mode: ${e}`);return t}static getAllModes(){return Array.from(this.strategies.keys())}};vt();var br=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1414
+ - Read files and search code
1415
+ - Analyze and understand the codebase
1416
+ - Answer questions about the project
1417
+ - Explore the project structure
1418
+
1419
+ You CANNOT make any changes. If the user needs edits, inform them that you are in read-only mode and suggest they switch to AGENT mode.
1420
+
1421
+ Available operations: Reading, Searching, Analyzing, Exploring.`}shouldAutoApprove(){return true}getDescription(){return "Read-only mode - Analyze and explore code without making changes"}getIcon(){return "\u{1F512}"}isReadOnlyTool(e){if(e.permission?.allowInAskMode===true)return true;if(e.permission?.allowInAskMode===false)return false;if(e.permission?.category)return e.permission.category==="read";let t=e.name.toLowerCase();return ["read","grep","glob","search","list","show","get","fetch","find","view","cat","ls","describe","inspect","analyze","check"].some(r=>t.includes(r))}};vt();var vr=class{mode="agent";filterTools(e){return e}getSystemPrompt(){return `You are in AGENT mode (standard). You have access to:
1422
+ - Read and analyze the codebase
1423
+ - Make file edits and create new files
1424
+ - Run commands and scripts
1425
+ - Perform all available operations
1426
+
1427
+ Some dangerous operations may require user approval before execution. When requesting approval:
1428
+ - Clearly explain what the operation will do
1429
+ - Mention any potential risks
1430
+ - Wait for user confirmation before proceeding
1431
+
1432
+ Available operations: All tools (with approval for dangerous operations).`}shouldAutoApprove(){return false}getDescription(){return "Standard mode - Full access with approval for dangerous operations"}getIcon(){return "\u2699\uFE0F"}};vt();var xr=class{mode="auto";filterTools(e){return e}getSystemPrompt(){return `You are in AUTO mode (automatic). You have full access to:
1433
+ - Read and write files
1434
+ - Execute commands
1435
+ - Make changes to the project
1436
+ - All available tools without approval
1437
+
1438
+ All operations will execute automatically without user confirmation. You should:
1439
+ - Be confident in your actions
1440
+ - Explain what you're doing
1441
+ - Report results clearly
1442
+ - Handle errors gracefully
1443
+
1444
+ \u26A0\uFE0F Important: Since there's no approval step, double-check your actions before executing.
1445
+
1446
+ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return true}getDescription(){return "Automatic mode - All operations execute without approval (use with caution)"}getIcon(){return "\u26A1"}};xn.register(new br);xn.register(new vr);xn.register(new xr);function xl(s){return xn.getStrategy(s)}vt();vt();var sp=2e4,jb=15e3;function ap(s,e){let t=process.env[s];if(!t)return e;let n=Number(t);return !Number.isFinite(n)||n<=0?e:Math.floor(n)}function rp(s,e){let t=s??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function Ji(){let s=new Error("Request aborted");return s.name="AbortError",s.code="ERR_CANCELED",s.category="canceled",s}async function ip(s,e){if(s?.aborted)throw Ji();return e()}function Gb(s,e){let t=Math.round(e/1e3),n=new Error(s==="first_chunk"?`Stream timeout: no response for ${t}s`:`Stream timeout: no data for ${t}s`);return n.code="STREAM_TIMEOUT",n.category="retryable_network",n.isNetworkInterrupt=true,n.streamTimeoutPhase=s,n.timeoutMs=e,n}var Wb=ap("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),Hb=ap("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Jb=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function op(s,e=jb){if(!s||s.length<=e)return s;let t=s.split(`
1447
+ `).length,n=s.length,r=Math.floor(e*.4),i=Math.floor(e*.4),o=r,a=s.length-i;for(;o>0&&(s.charCodeAt(o)&192)===128;)o--;for(;a<s.length&&(s.charCodeAt(a)&192)===128;)a++;let l=s.slice(0,o),c=s.slice(a),d=`
1448
+
1449
+ \u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
1450
+
1451
+ `;return l+d+c}var Sr=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;smartContextManager;currentTaskType;compressionMode;toolMetricsHistory=[];workspacePath;runContext;permissionManager;modeStrategy;currentMode;loopDetector;constructor(e){if(this.llmProvider=e.llmProvider,this.providerName=e.providerName,this.model=e.model,this.tools=e.tools,this.memory=e.memory,this.config=e.config,this.agentName=e.agentName||"DefaultAgent",this.agentDescription=e.agentDescription||"",this.instructions=e.instructions,this.userData=e.userData,this.plannerMode=e.plannerMode??false,this.structuredOutput=e.structuredOutput,this.maxInputTokensOverride=e.maxInputTokensOverride,this.maxInputTokens=this.computeMaxInputTokens(e.contextWindow,e.tailTokenBudget,this.maxInputTokensOverride),this.minHistoryMessages=Math.max(1,e.minHistoryMessages??6),e.structuredOutput&&(this.structuredValidator=new pi(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Gi,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.smartContextManager=new Js({debug:process.env.CLI_DEBUG==="1"}),this.currentMode=e.config.mode??"agent",this.modeStrategy=xl(this.currentMode),this.permissionManager=e.permissionManager??new vn({defaultPermission:"ask"}),this.loopDetector=ep(),e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async n=>({approved:await t({id:"",name:n.toolName,args:n.args}),remember:false}));}}setApprovalHandler(e){if(!e){this.permissionManager.setApprovalHandler(void 0);return}this.permissionManager.setApprovalHandler(async t=>({approved:await e({id:"",name:t.toolName,args:t.args}),remember:false}));}setMode(e){this.currentMode=e,this.modeStrategy=xl(e),f.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,n){if(n&&n>0)return n;let i=e&&e>0?e:19e4,o=.7,a=Math.floor(i*o),l=Math.min(t??sp,Math.floor(i*.1)),c=Math.max(2e3,a-l);if(process.env.CLI_DEBUG==="1"||process.env.CLI_DEBUG_CONSOLE==="1"){let u=`[Context] maxInputTokens=${c} (contextWindow=${i}, override=${n}, tailBudget=${t??sp}, safety=${o})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Jb){for await(let o of e)yield o;return}let n=e[Symbol.asyncIterator](),r=t?new Promise((o,a)=>{t.aborted?a(Ji()):t.addEventListener("abort",()=>a(Ji()),{once:true});}):null,i=false;for(;;){if(t?.aborted){if(n.return)try{await n.return();}catch{}throw Ji()}let o=i?Hb:Wb,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Gb(i?"idle":"first_chunk",o));},o);});try{let c=await Promise.race(r?[n.next(),l,r]:[n.next(),l]);if(a&&clearTimeout(a),c.done)return;i=!0,yield c.value;}catch(c){if(a&&clearTimeout(a),n.return)try{await n.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&f.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),n=await this.smartContextManager.trimSmart(t,this.maxInputTokens,{taskType:this.currentTaskType,iteration:e,llmProvider:this.llmProvider,model:this.model,minHistoryMessages:this.minHistoryMessages,enableLLMCompression:true});if(n.droppedCount>0||n.compressedCount>0){this.memory.setMessages(n.messages);let r=this.compressionMode==="async"?"Async":"Sync",i=(n.originalTokens/1e3).toFixed(1),o=(n.estimatedTokens/1e3).toFixed(1),a=((n.originalTokens-n.estimatedTokens)/1e3).toFixed(1),l=n.originalCount,c=n.messages.length;f.info("Context",`[${r}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${i}K \u2192 ${c}\u6761/${o}K (\u8282\u7701 ${a}K, \u4E22\u5F03${n.droppedCount}\u6761, LLM\u538B\u7F29${n.compressedCount}\u6761)`),n.debugInfo&&n.debugInfo.decisions.forEach(u=>f.debug("Context",u));}return n}setCompressionMode(e){this.compressionMode=e,f.info("Context",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}async getInstructions(e){if(typeof this.instructions=="string")return this.instructions;let t={name:this.agentName,description:this.agentDescription};return await this.instructions(e,t)}createRunContext(e,t=0){return {task:e,timestamp:Date.now(),currentTime:new Date,iteration:t,userData:this.userData,systemStatus:void 0}}setUserData(e){this.userData={...this.userData,...e};}async*run(e,t,n){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(f.debug("MK",` hasSignal: ${!!n}`),f.debug("RUNNER","========================================"),f.debug("RUNNER","=== runner.run ENTRY ==="),f.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),f.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),f.debug("RUNNER",` hasSignal: ${!!n}`)),oe.agentStart(e);let r=Wi.classify(e);this.currentTaskType=r.taskType,process.env.CLI_DEBUG_CONSOLE==="1"&&(f.log(`[SmartContext] Task classified as: ${r.taskType} (confidence: ${r.confidence}, reason: ${r.reasoning})`),f.info("MK","\u5F53\u524D\u4EFB\u52A1 \uFF1A"+this.currentTaskType)),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let i=this.createRunContext(e,0);this.inputGuardrails.length>0&&(yield {type:"raw_response_event",data:{type:"input_guardrails.check_start",count:this.inputGuardrails.length},event_type:"input_guardrails.check_start"},await En.runInputGuardrails(this.inputGuardrails,i,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let o=await this.getInstructions(i);if(!this.memory.getMessagesForLLM().some(k=>k.role==="system")){let k=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:k}),this.memory.add({role:"system",content:o}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let R=await ul(this.workspacePath);R&&this.memory.add({role:"system",content:R});}catch{}}if(t&&t.length>0){let k=[{type:"text",text:e},...t.map(R=>({type:"image_url",image_url:{url:R,detail:"auto"}}))];this.memory.add({role:"user",content:k});}else this.memory.add({role:"user",content:e});let c=Date.now(),u=0,d="",p=0,m={totalTokens:0,promptTokens:0,completionTokens:0},h=false,g=0,y=null,x=new Map,S=0,T=zt.streamMaxRetries,w=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:_u,L=w===0||w===1/0,B=rp(this.config.maxToolCalls,Tu),I=rp(this.config.maxRuntimeMs,wu);for(;L||u<w;){if(n?.aborted){y="interrupted",h=true,yield {type:"error",error:"Task interrupted by user."};break}if(I!==null&&Date.now()-c>=I){y="runtime_limit",h=true,yield {type:"error",error:`Reached max runtime (${st(I)}). Please summarize progress and ask whether to continue.`};break}if(B!==null&&p>=B){y="tool_call_limit",h=true,yield {type:"error",error:`Reached max tool calls (${B}). Please summarize progress and ask whether to continue.`};break}u++;let k=Zd(u);k&&this.memory.add({role:"system",content:k});let R=null;if(this.maxInputTokens){let M=In(this.memory.getMessagesForLLM()),_=this.maxInputTokens*.97;M>_&&(R=await this.applyContextWindow(u));}R&&(R.droppedCount>0||R.compressedCount>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:R.originalCount,keptMessages:R.messages.length,droppedMessages:R.droppedCount,compressedMessages:R.compressedCount,originalTokens:R.originalTokens,finalTokens:R.estimatedTokens,budgetTokens:this.maxInputTokens||0,useLLM:R.compressedCount>0,timestamp:Date.now()});let E=this.memory.checkContextHealth();if((E.warnings.length>0||E.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:E.totalTokens,toolResultTokens:E.toolResultTokens,toolResultRatio:E.toolResultRatio,messageCount:E.messageCount,toolMessageCount:E.toolMessageCount,warnings:E.warnings,shouldCompress:E.shouldCompress,shouldCleanup:E.shouldCleanup,byType:E.byType},event_type:"context_health"},E.shouldCleanup&&E.byType.ephemeral.count>5)){let M=this.memory.cleanupEphemeral();M>0&&f.info("Runner",`Cleaned ${M} ephemeral messages`);}f.debug("Runner",this.memory.getTokenSummary()),oe.agentIteration(u,"thinking"),yield {type:"iteration_start",iteration:u};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let M=this.memory.getMessagesForLLM();f.info("LLM",`Request: model=${this.model}, messages=${M.length}, tools=${this.tools.length}`),f.debug("LLM","Request messages",{messageCount:M.length,lastMessage:M[M.length-1]?.content?.toString().substring(0,200)});let _=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&f.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${_.length}/${this.tools.length}`);let W=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:_,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,signal:n}),$="",A="",G=[],N=[],U="",H={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let J of this.withStreamWatchdog(W,n)){if(J.type==="stream_retry"){yield J;continue}if(J.type==="stream_recovered"){yield {type:"stream_recovered",attempt:J.attempt,maxRetries:J.maxRetries};continue}yield {type:"raw_response_event",data:J,event_type:J.choices?.[0]?.delta?"response.delta":"response.chunk"};let ye=J.choices?.[0]?.delta;if(J.usage){H={prompt_tokens:J.usage.prompt_tokens||H.prompt_tokens,completion_tokens:J.usage.completion_tokens||H.completion_tokens,total_tokens:J.usage.total_tokens||H.total_tokens,cached_tokens:J.usage.cached_tokens,cache_read_input_tokens:J.usage.cache_read_input_tokens,cache_creation_input_tokens:J.usage.cache_creation_input_tokens,prompt_tokens_details:J.usage.prompt_tokens_details},m={promptTokens:H.prompt_tokens,completionTokens:H.completion_tokens,totalTokens:H.total_tokens};let pe=!!J.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:H,is_final:pe};}if(ye){if(ye.reasoning_content&&(A+=ye.reasoning_content,yield {type:"reasoning_delta",delta:ye.reasoning_content}),ye.content&&($+=ye.content,d=$,yield {type:"text_delta",delta:ye.content}),ye.tool_calls)for(let pe of ye.tool_calls){let ce=pe.index;N[ce]||(N[ce]={id:pe.id||`call_${Date.now()}_${ce}`,type:"function",function:{name:"",arguments:""}}),pe.id&&(N[ce].id=pe.id),pe.function?.name&&(N[ce].function.name=pe.function.name),pe.function?.arguments&&(N[ce].function.arguments+=pe.function.arguments,yield {type:"tool_call_delta",id:N[ce].id,name:N[ce].function.name,arguments_delta:pe.function.arguments});}J.choices?.[0]?.finish_reason&&(U=J.choices[0].finish_reason),J.thinking_blocks&&Array.isArray(J.thinking_blocks)&&(G=J.thinking_blocks.map(pe=>({type:pe.type,thinking:pe.thinking,signature:pe.signature,data:pe.data})));}}$&&(yield {type:"text_done"}),process.env.CLI_DEBUG_CONSOLE==="1"&&process.env.NEOX_UI_MODE==="1"&&console.log("[Runner] \u{1F3AF} Emitting response.completed event (after LLM response)"),yield {type:"raw_response_event",data:{type:"response.completed"},event_type:"response.completed"};let Ie={role:"assistant",content:($||"").trimEnd()};if(A&&(Ie.reasoning_content=A),G.length>0&&(Ie.thinking_blocks=G),N.length>0&&(Ie.tool_calls=N.map(J=>({...J,function:{...J.function,arguments:J.function.arguments}}))),this.memory.add(Ie),process.env.CLI_DEBUG==="1"&&f.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${N.length}, fullContent.length=${$.length}`),N.length>0){let J=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let P of N){let O=P.function.arguments||"";if(J.test(O)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${P.function.name}`),console.error(`[Runner] Arguments preview: ${O.substring(0,500)}`),yield {type:"raw_response_event",data:{type:"error.placeholder_detected",message:"Model generated placeholder string instead of actual content. This usually happens when the model sees truncated data in conversation history.",tool:P.function.name},event_type:"error.placeholder_detected"},yield {type:"error",error:'Error: Model attempted to write placeholder text ("[omitted ...]") instead of actual content. This happens when conversation history contains truncated data. Please start a new conversation.'},h=!0;break}}if(h)break;if(B!==null&&p+N.length>B){y="tool_call_limit",h=!0,yield {type:"error",error:`Tool call budget exceeded (max ${B}, requested ${N.length}). Please summarize progress and ask whether to continue.`};break}for(let P of N){p++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:P.id,name:P.function.name,arguments:P.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:P.id,name:P.function.name};let q=!1;try{P.function.arguments&&(JSON.parse(P.function.arguments),q=!0);}catch(X){oe.toolError(P.function.name,`Invalid JSON arguments (${X.message}): ${P.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${P.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${P.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${P.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${P.function.arguments.substring(Math.max(0,P.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:P.id,name:P.function.name,arguments:P.function.arguments,success:q},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:P.id,name:P.function.name,arguments:P.function.arguments},event_type:"response.function_call_arguments.done"};}let ye=new Set,pe=null;for(let P of N){let O={};try{let re=P.function.arguments?.trim()||"";O=re?JSON.parse(re):{};}catch(re){oe.toolError(P.function.name,`Loop detection skipped: invalid JSON (${re.message})`);continue}this.loopDetector.record(P.function.name,O);let q=this.loopDetector.detect(P.function.name,O);if(q===0)continue;let X=this.loopDetector.generateIntervention(q,P.function.name,O);if(this.memory.add({role:"system",content:X.message}),q===2&&np(P.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:P.id,name:P.function.name,output:X.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:P.function.name,output:X.message,success:!1},this.memory.addToolResult(P.id,P.function.name,X.message),this.loopDetector.updateLastStatus("error"),ye.add(P.id),X.shouldTerminate){pe=X;break}}if(pe&&(yield {type:"error",error:pe.message},h=!0),h)break;let ce=ye.size>0?N.filter(P=>!ye.has(P.id)):N,Oe=new Set(this.modeStrategy.filterTools(this.tools).map(P=>P.name)),_e=[];for(let P of ce){if(Oe.has(P.function.name)){_e.push(P);continue}let O=`Tool "${P.function.name}" is not allowed in ${this.currentMode} mode`;oe.toolError(P.function.name,O),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:P.id,name:P.function.name,output:O,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:P.function.name,output:O,success:!1},this.memory.addToolResult(P.id,P.function.name,O),f.info("PERMISSION",`Tool blocked by mode: ${P.function.name} - ${O}`);}if(_e.length===0)continue;let Q=_e.map(P=>({id:P.id,type:"function",function:{name:P.function.name,arguments:P.function.arguments}})),be=!1;if(process.env.CLI_DEBUG==="1"&&f.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${Q.length}`),!this.modeStrategy.shouldAutoApprove()){let P=new Set;try{for(let O of _e)try{let q=O.function.arguments.trim(),X=q?JSON.parse(q):{},de=this.tools.find(re=>re.name===O.function.name);if(!de){f.warn("RUNNER",`Tool not found: ${O.function.name}`);continue}let V=await ip(n,async()=>this.permissionManager.checkPermission(de,X));if(!V.allowed){P.add(O.id);let re=V.reason||`Tool "${O.function.name}" was denied`;oe.toolError(O.function.name,re),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:O.id,name:O.function.name,output:re,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:O.function.name,output:re,success:!1},f.info("PERMISSION",`Tool denied: ${O.function.name} - ${re}`),be=!0;}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED")throw q;oe.toolError(O.function.name,q?.message||"permission check failed");}}catch(O){if(O?.name==="AbortError"||O?.code==="ERR_CANCELED"){f.info("RUNNER","Interrupt detected during permission check"),h=!0;break}throw O}if(_e=_e.filter(O=>!P.has(O.id)),Q=Q.filter(O=>!P.has(O.id)),be){f.info("RUNNER","User denied tool - terminating current turn");break}if(Q.length===0)continue}if(process.env.CLI_DEBUG==="1"&&f.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${Q.length}, userDeniedTool=${be}`),this.toolInputGuardrails.length>0){let P=new Set;try{for(let O of _e)try{let q=O.function.arguments.trim(),X=q?JSON.parse(q):{},de={tool_name:O.function.name,tool_input:X,tool_call_id:O.id},V=this.tools.find(D=>D.name===O.function.name);if(!V)continue;this.runContext.iteration=u;let re=await ip(n,async()=>En.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:de,agent_name:this.agentName,tool:V}));if(!re.should_execute){P.add(O.id);let D=re.rejection_message||`Tool ${O.function.name} was blocked by guardrail`;oe.toolError(O.function.name,`Blocked by guardrail: ${D}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:O.id,name:O.function.name,output:D,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:O.function.name,output:D,success:!1},this.memory.addToolResult(O.id,O.function.name,D),ga(this.runContext,O.function.name,X,!1);}}catch(q){if(q?.name==="AbortError"||q?.code==="ERR_CANCELED")throw q;if(q instanceof ht){oe.toolError(O.function.name,`Guardrail tripwire triggered: ${q.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${O.function.name}: ${q.message}`},h=!0;break}oe.toolError(O.function.name,`Guardrail check failed: ${q?.message}`);}}catch(O){if(O?.name==="AbortError"||O?.code==="ERR_CANCELED"){f.info("RUNNER","Interrupt detected during guardrails check"),h=!0;break}throw O}if(h)break;if(_e=_e.filter(O=>!P.has(O.id)),Q=Q.filter(O=>!P.has(O.id)),Q.length===0)continue}process.env.CLI_DEBUG==="1"&&f.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${Q.length}`);let Te=await this.parallelExecutor.execute(Q,this.tools,P=>{if(oe.toolCall(P.name,{}),P.success){let q=typeof P.output=="string"?P.output.length:JSON.stringify(P.output).length;oe.toolResult(P.name,!0,q,P.executionTime||0);}else oe.toolError(P.name,P.output);let O={type:"tool_call_output_item",id:P.id,name:P.name,output:P.output,success:P.success,timestamp:Date.now()};},n);for(let P of Te.results){this.toolMetricsHistory.push({name:P.name,duration:P.executionTime||0,success:P.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:P.id,name:P.name,output:P.output,success:P.success,timestamp:Date.now()}},yield {type:"tool_output",name:P.name,output:P.output,success:P.success};let q=typeof P.output=="string"?op(P.output):op(JSON.stringify(P.output));q=this.enrichToolResult(q,P.name,P.executionTime||0);let X=N.find(re=>re.id===P.id),de={};if(X)try{de=JSON.parse(X.function.arguments||"{}");}catch{}if(this.toolOutputGuardrails.length>0)try{let re=this.tools.find(D=>D.name===P.name);if(re){let D={tool_name:P.name,tool_input:de,tool_call_id:P.id},ie=await En.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:D,agent_name:this.agentName,tool:re,output:P.output});ie.should_use_output||(q=ie.replacement_message||"[Output blocked by guardrail]",oe.toolError(P.name,"Output blocked by guardrail"));}}catch(re){re instanceof ht&&oe.toolError(P.name,`Output guardrail tripwire triggered: ${re.message}`);}if(!P.success&&typeof P.output=="string"){let re=P.output.toLowerCase();if(re.includes("operation cancelled")||re.includes("command interrupted")||re.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),f.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),h=!0;break}}ga(this.runContext,P.name,de,P.success),f.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${P.name}`,{toolName:P.name,success:P.success,rawLength:typeof P.output=="string"?P.output.length:JSON.stringify(P.output).length,truncatedLength:q.length,outputPreview:q.substring(0,500)}),this.memory.addToolResult(P.id,P.name,q);let V=P.success?"success":"error";try{let re=typeof P.output=="string"?P.output:JSON.stringify(P.output),D=JSON.parse(re);D.status==="already_done"?V="already_done":D.status==="success"?V="success":D.status==="error"&&(V="error");}catch{}if(this.loopDetector.updateLastStatus(V),V==="error"){let re=(x.get(P.name)||0)+1;if(x.set(P.name,re),P.name==="edit_file"){let D=Qd(re,P.name);D&&(re===2||re===3)&&this.memory.add({role:"system",content:D});}}else x.set(P.name,0);}if(u>0&&u%5===0){let P=this.buildPerformanceHint();P&&(this.memory.add({role:"system",content:P}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",P));}if(process.env.CLI_DEBUG_CONSOLE==="1"&&Te.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:Te.stats},event_type:"parallel_execution.stats"}),n?.aborted){h=!0;break}continue}else {if(this.plannerMode&&g<2&&this.shouldAutoContinuePlan($)){g++;let J=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:$,followup_prompt:J,count:g},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:J});continue}if($&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:$,role:"assistant",timestamp:Date.now()}}),this.structuredValidator){let J=this.structuredValidator.validate($);if(J.ok)d=J.normalized||$,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:d,parsed:J.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:J.reason,message:J.message,errors:J.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(J)}),d="";continue}}else d=$;this.outputGuardrails.length>0&&d&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await En.runOutputGuardrails(this.outputGuardrails,i,this.agentName,d),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});break}}catch(M){if(M?.type==="stream_retry"){yield M;continue}let _=M instanceof we?M:mt(M);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:_.category,code:_.code,retryable:_.retryable,message:_.message}),_.category==="canceled"){y="interrupted",h=true,yield {type:"error",error:"Task interrupted by user."};break}if(_.retryable&&S<T){S++;let G=Hs(_.category,S,_.retryAfter),N=_.category==="retryable_rate_limit",U=_.code==="STREAM_TIMEOUT",H=_.category==="retryable_network"||_.category==="retryable_stream";f.warn("RUNNER",`Retrying after ${st(G)} (attempt ${S}/${T}): ${_.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:_.message,errorCode:_.code,attempt:S,maxRetries:T,delayMs:G,isRateLimit:N,isStreamTimeout:U,isNetworkError:H},event_type:"runner.stream_retry"},await ft(G),u--;continue}let W=ui(_),$=_.message;W&&!$.includes(W)&&($=`${$}
1452
+
1453
+ \u{1F4A1} Suggestion: ${W}`),h=true;let A=Du($,{providerName:this.providerName});oe.agentError(A),yield {type:"raw_response_event",data:{type:"error.classified",category:_.category,code:_.code,message:_.message,retryable:_.retryable,suggestion:W,context:_.context},event_type:"error.classified"},yield {type:"error",error:A};break}}!h&&!L&&u>=w&&!d&&(y=y||"iteration_limit",h=true,yield {type:"error",error:`Reached max iterations (${w}). Please summarize progress and ask whether to continue.`}),h||(oe.agentComplete(u,p,m),f.info("LLM",`Complete: iterations=${u}, toolCalls=${p}, tokens=${m.totalTokens} (prompt=${m.promptTokens}, completion=${m.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(f.debug("RUNNER","=== runner.run COMPLETING ==="),f.debug("RUNNER",` iterations: ${u}`),f.debug("RUNNER",` toolCalls: ${p}`),f.debug("RUNNER",` encounteredError: ${h}`),y&&f.debug("RUNNER",` stoppedBy: ${y}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&f.debug("RUNNER","=== runner.run END (run_done yielded) ===");}shouldAutoContinuePlan(e){if(!this.plannerMode)return false;let t=(e||"").trim();if(t.length<40)return false;let n=t.toLowerCase();return ["planned steps","plan:","execution plan","\u884C\u52A8\u8BA1\u5212","\u8BA1\u5212\uFF1A","\u8BA1\u5212\u5982\u4E0B","\u65B9\u6848\uFF1A","\u6B65\u9AA4\u8BA1\u5212"].some(a=>n.includes(a))?(t.match(/(^|\n)\s*[-*•]\s+/g)||[]).length+(t.match(/(^|\n)\s*\d+\.\s+/g)||[]).length>=2:false}buildPlanFollowupPrompt(){return "Plan approved. Continue executing the plan step by step and start working immediately."}enrichToolResult(e,t,n){if(n<1e3)return e;let r=n>=1e3?`${(n/1e3).toFixed(1)}s`:`${n}ms`;return `\u23F1\uFE0F [${t} took ${r}]
1454
+
1455
+ `+e}buildPerformanceHint(){let e=this.toolMetricsHistory.slice(-15);if(e.length<5)return null;let t=new Map;for(let i of e)if(i.duration>2e3){let o=t.get(i.name)||{count:0,totalTime:0};t.set(i.name,{count:o.count+1,totalTime:o.totalTime+i.duration});}let n=new Map;for(let i of e){let o=n.get(i.name)||{total:0,failed:0};n.set(i.name,{total:o.total+1,failed:o.failed+(i.success?0:1)});}let r=[];for(let[i,o]of t.entries())o.count>=3&&r.push(`\u26A0\uFE0F Tool "${i}" is slow (>2s), called ${o.count} times, total ${(o.totalTime/1e3).toFixed(1)}s. Consider caching results or using alternatives.`);for(let[i,o]of n.entries()){let a=o.failed/o.total;o.total>=3&&a>=.5&&r.push(`\u26A0\uFE0F Tool "${i}" has ${Math.round(a*100)}% failure rate (${o.failed}/${o.total}). Check arguments or try different approach.`);}return r.length===0?null:`
1456
+ [Performance Notice]
1457
+ ${r.join(`
1458
+ `)}
1459
+ `}};vt();var Sl=null;function lp(s){Sl=s;}function zb(){if(!Sl)throw new Error("Approval prompt is not configured");return Sl}async function cp(s){let{toolName:e,args:t,reason:n,allowRemember:r}=s,i=zb(),o=Object.keys(t).length>0?` (${Object.keys(t).slice(0,2).join(", ")}${Object.keys(t).length>2?"...":""})`:"",a=`Allow tool ${e}${o}?`,l=n?`Warning: ${n}`:void 0,c=[{label:"Allow Once",value:"allow_once",description:"Allow this tool call only this time"}];switch(r&&c.push({label:"Always Allow",value:"always_allow",description:`Don't ask again for "${e}"`}),c.push({label:"Deny",value:"deny",description:"Reject this tool call"}),await i(a,c,"allow_once",l)){case "allow_once":return {approved:true,remember:false};case "always_allow":return {approved:true,remember:true};case "deny":return {approved:false,remember:false};default:return {approved:false,remember:false}}}function up(){let s=new vn({approvalHandler:cp,defaultPermission:"ask",memoryExpirationMs:864e5});return vl(s),s}var Kb=16e3;function dp(s,e=Kb){if(!s||s.length<=e)return s;let t=s.split(`
1460
+ `).length,n=s.length,r=Math.floor(e*.4),i=Math.floor(e*.4),o=r,a=s.length-i;for(;o>0&&(s.charCodeAt(o)&192)===128;)o--;for(;a<s.length&&(s.charCodeAt(a)&192)===128;)a++;let l=s.slice(0,o),c=s.slice(a),d=`
1461
+
1462
+ \u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
1463
+
1464
+ `;return l+d+c}function pp(s,e={}){let t={...s};return !e.allowServiceTier&&"service_tier"in t&&delete t.service_tier,e.disableStore&&"store"in t&&delete t.store,!e.allowSafetyIdentifier&&"safety_identifier"in t&&delete t.safety_identifier,t}function mp(s){if(!s)return null;let e=process.env.CD_REASONING_EFFORT||process.env.NEOX_REASONING_EFFORT,t=process.env.CD_REASONING_VERBOSITY||process.env.NEOX_REASONING_VERBOSITY;return {effort:e||"low",verbosity:t||"low"}}var zi=class{client;defaultModel;isProxy;useResponsesAPI;apiEndpoint;streamFormat;retryConfig;baseUrl;privacySettings;sessionId;doubaoThinking;constructor(e){this.baseUrl=e.baseUrl||"https://api.openai.com/v1",this.isProxy=e.baseUrl?!e.baseUrl.includes("api.openai.com"):false,this.useResponsesAPI=e.useResponsesAPI||false,this.apiEndpoint=e.apiEndpoint||"/chat/completions",this.streamFormat=e.streamFormat||"openai",this.sessionId=e.sessionId||`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,this.privacySettings=e.privacySettings||{},this.doubaoThinking=e.doubaoThinking,this.client=qb.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=Wn("openai",this.baseUrl);this.retryConfig=dn(void 0,{...t,...e.retry}),process.env.CLI_DEBUG==="1"&&console.log("[OpenAI] Initialized with:",{baseUrl:this.baseUrl,isProxy:this.isProxy,useResponsesAPI:this.useResponsesAPI,apiEndpoint:this.apiEndpoint,streamFormat:this.streamFormat});}async chat(e,t={}){let{model:n=this.defaultModel}=t;return this.shouldUseResponsesAPI(n)?this.chatWithResponsesAPI(e,t):this.chatWithChatCompletions(e,t)}async*chatStreamed(e,t={}){let{model:n=this.defaultModel}=t;this.shouldUseResponsesAPI(n)?yield*this.chatStreamedWithResponsesAPI(e,t):yield*this.chatStreamedWithChatCompletions(e,t);}async chatWithChatCompletions(e,t){let{model:n=this.defaultModel,tools:r,temperature:i=.7,maxInputTokens:o}=t,a=this.buildChatCompletionsPayload(e,{model:n,tools:r,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:o,stream:false}),l=`${this.client.defaults.baseURL}/chat/completions`;oe.llmRequest("openai",n,a,l,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&(console.log(`
1465
+ [OpenAI Chat Completions Request]`),console.log("URL:",l),console.log("Payload:",JSON.stringify(a,null,2)));let c=this.retryConfig.requestMaxRetries,u=null;for(let d=0;d<=c;d++)try{let p=Date.now(),m=await this.client.post("/chat/completions",a),h=Date.now()-p;return oe.llmResponse("openai",h,m.data.usage,m.data.choices[0]),process.env.CLI_DEBUG==="1"&&(console.log(`
1466
+ [OpenAI Chat Completions Response]`),console.log("Duration:",`${h}ms`),console.log("Data:",JSON.stringify(m.data,null,2))),m.data}catch(p){u=p;let m=mt(p);if(process.env.CLI_DEBUG==="1"&&(console.log(`
1467
+ [OpenAI Chat Completions Error]`),console.log("Message:",p.message),console.log("Category:",m.category),console.log("Retryable:",m.retryable),console.log("Attempt:",`${d+1}/${c+1}`)),oe.llmError("openai",p),!m.retryable||d===c)throw m;let h=p.response?.headers?.["retry-after"],g=Jt(h),y=pn(g,d+1,this.retryConfig);console.log(`[OpenAI] Request failed (${m.code}), retrying in ${st(y)} (${d+1}/${c})...`),await ft(y);}throw u||new Error("Unknown error during retry")}async*chatStreamedWithChatCompletions(e,t){let{model:n=this.defaultModel,tools:r,temperature:i=.7,maxInputTokens:o,signal:a}=t,l=this.buildChatCompletionsPayload(e,{model:n,tools:r,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:o,stream:true}),c=`${this.client.defaults.baseURL}${this.apiEndpoint}`;oe.llmRequest("openai-stream",n,l,c,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&(console.log(`
1468
+ [OpenAI Chat Completions Stream Request]`),console.log("URL:",c),console.log("Endpoint:",this.apiEndpoint),console.log("Payload:",JSON.stringify(l,null,2)));let u=this.retryConfig.streamMaxRetries,d=0;for(;;)try{if(a?.aborted){let g=new Error("Request aborted");throw g.name="AbortError",g}let p=Date.now(),m=await this.client.post(this.apiEndpoint,l,{responseType:"stream",signal:a});if(process.env.CLI_DEBUG==="1"&&(console.log(`
1469
+ [OpenAI Stream Started]`),console.log("Status:",m.status)),m.status!==200){let g="";for await(let y of m.data)g+=y.toString();throw new Error(`OpenAI API error: ${m.status} - ${g}`)}this.streamFormat==="anthropic"?yield*this.parseAnthropicStreamResponse(m.data):yield*this.parseOpenAIStreamResponse(m.data);let h=Date.now()-p;oe.llmResponse("openai-stream",h,{},{}),process.env.CLI_DEBUG==="1"&&(console.log(`
1470
+ [OpenAI Stream Complete]`),console.log("Duration:",`${h}ms`));return}catch(p){let m=mt(p);if(process.env.CLI_DEBUG==="1"&&(console.log(`
1471
+ [OpenAI Stream Error]`),console.log("Message:",p.message),console.log("Retryable:",m.retryable)),oe.llmError("openai-stream",p),m.retryable&&d<u){d++;let h=p.response?.headers?.["retry-after"],g=Jt(h),y=pn(g,d,this.retryConfig);console.log(`[OpenAI] Stream failed (${m.code}), reconnecting in ${st(y)} (${d}/${u})...`),yield {choices:[],type:"stream_retry",error:m.message,errorCode:m.code,attempt:d,maxRetries:u,delayMs:y},await ft(y);continue}throw m}}buildChatCompletionsPayload(e,t){let{model:n,tools:r,temperature:i,structuredOutput:o,maxInputTokens:a,stream:l}=t,c=this.formatMessagesForChatCompletions(e);if(this.baseUrl.includes("ark.cn-beijing.volces.com")){let m={model:n,messages:c,stream:l};return this.doubaoThinking&&n.includes("doubao-seed")&&(m.thinking={type:this.doubaoThinking.type},process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Doubao thinking mode: ${this.doubaoThinking.type}`)),r&&r.length>0&&(m.tools=r.map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})),process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Added ${m.tools.length} tools to Doubao payload`)),m}let d={model:n,messages:c,temperature:i,stream:l};l&&(d.stream_options={include_usage:true}),a!==void 0&&(d.max_tokens=a);let p=mp(false);return p&&(d.reasoning_effort=p.effort,p.verbosity&&(d.verbosity=p.verbosity)),r&&r.length>0&&(d.tools=r.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Added ${d.tools.length} tools to Chat Completions payload`)),o&&(d.response_format={type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict??true}}),pp(d,this.privacySettings)}formatMessagesForChatCompletions(e){return e.filter(t=>{let n=t.content&&(typeof t.content=="string"?t.content.trim().length>0:Array.isArray(t.content)&&t.content.length>0),r=t.tool_calls&&t.tool_calls.length>0;return n||r}).map(t=>{let n={role:t.role,content:null};if(t.role==="tool"){let r=typeof t.content=="string"?t.content:me(t.content);n.content=dp(r);}else Array.isArray(t.content)?n.content=t.content:t.tool_calls&&t.tool_calls.length>0?n.content=t.content||"":n.content=t.content||null;return t.name&&(n.name=t.name),t.tool_call_id&&(n.tool_call_id=t.tool_call_id),t.tool_calls&&(n.tool_calls=t.tool_calls.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:r.function.arguments}}))),n})}async chatWithResponsesAPI(e,t){let n="",r=[],i;for await(let o of this.chatStreamedWithResponsesAPI(e,t)){let a=o.choices?.[0]?.delta;if(a&&(a.content&&(n+=a.content),a.tool_calls))for(let l of a.tool_calls){let c=r.find(u=>u.index===l.index);c?l.function?.arguments&&(c.function.arguments+=l.function.arguments):r.push({id:l.id||`call_${r.length}`,type:"function",function:{name:l.function?.name||"",arguments:l.function?.arguments||""},index:l.index});}o.usage&&(i=o.usage);}return {id:`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:n||null,...r.length>0?{tool_calls:r}:{}},finish_reason:"stop"}],usage:i||{total_tokens:0,prompt_tokens:0,completion_tokens:0}}}async*chatStreamedWithResponsesAPI(e,t){let{model:n=this.defaultModel,tools:r,temperature:i=.7,structuredOutput:o,maxInputTokens:a,signal:l}=t,c=this.buildResponsesAPIPayload(e,{model:n,tools:r,temperature:i,structuredOutput:o,maxInputTokens:a}),u=`${this.client.defaults.baseURL}/responses`;oe.llmRequest("openai-responses-stream",n,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&(console.log(`
1472
+ [OpenAI Responses API Stream Request]`),console.log("URL:",u),console.log("Payload Tools Count:",c.tools?.length||0),console.log("Full Payload:",JSON.stringify(c,null,2)));try{if(l?.aborted){let h=new Error("Request aborted");throw h.name="AbortError",h}let d=Date.now(),p=await this.client.post("/responses",c,{responseType:"stream",signal:l,headers:{Accept:"text/event-stream",conversation_id:this.sessionId,session_id:this.sessionId}});if(process.env.CLI_DEBUG==="1"&&(console.log(`
1473
+ [OpenAI Responses API Stream Started]`),console.log("Status:",p.status)),p.status!==200){let h="";for await(let y of p.data)h+=y.toString();let g=Cn(h,p.status);throw new Error(`OpenAI Responses API error: ${p.status} - ${g.message}`)}yield*this.parseResponsesAPIStream(p.data);let m=Date.now()-d;oe.llmResponse("openai-responses-stream",m,{},{}),process.env.CLI_DEBUG==="1"&&(console.log(`
1474
+ [OpenAI Responses API Stream Complete]`),console.log("Duration:",`${m}ms`));}catch(d){let p,m=d.response?.status;if(d.response?.data){let g=d.response.data;try{if(g&&typeof g.on=="function"){let y="";try{for await(let x of g)y+=x.toString();p=y;}catch{p="[Could not read error stream]";}}else if(typeof g=="string")p=g;else if(g&&typeof g=="object"){let y={error:g.error,message:g.message,type:g.type,code:g.code};p=JSON.stringify(y);}}catch{p="[Could not parse error data]";}}process.env.CLI_DEBUG==="1"&&(console.log(`
1475
+ [OpenAI Responses API Stream Error]`),console.log("Status:",m),console.log("Error Data:",p),console.log("Message:",d.message)),oe.llmError("openai-responses-stream",d);let h;if(m&&p){let g=Cn(p,m);h=`${g.message}${g.detail?`
1476
+ `+g.detail:""}`;}else h=d.message||"Unknown error";throw new Error(h)}}buildResponsesAPIPayload(e,t){let{model:n,tools:r,temperature:i,structuredOutput:o,maxInputTokens:a}=t,l=this.convertToResponsesInput(e),c=this.buildResponsesInstructions(e),u={model:n,input:l,stream:true,temperature:i,store:false,prompt_cache_key:this.sessionId};if(c&&(u.instructions=c),!this.isProxy){let d=mp(true);a!==void 0&&(u.max_input_tokens=a),u.text={format:{type:"text"},verbosity:d?.verbosity||"medium"},d&&(u.reasoning={effort:d.effort,summary:"auto"});}return r&&r.length>0?(u.tools=r.map(d=>this.formatResponsesFunctionTool(d)),process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Added ${u.tools.length} tools to Responses API payload`)):u.tools=[],o&&(u.response_format={type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict??true}}),pp(u,this.privacySettings)}buildResponsesInstructions(e){let t=e.filter(n=>n.role==="system").map(n=>me(n.content).trim()).filter(n=>n.length>0);return t.length>0?t.join(`
1477
+
1478
+ `):void 0}convertToResponsesInput(e){let t=new Map;return e.filter(n=>n.role!=="system").flatMap(n=>this.convertMessageToResponsesItems(n,t))}convertMessageToResponsesItems(e,t){if(e.role==="assistant"){let r=[],i=me(e.content);if(i.trim().length>0&&r.push({type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:i,annotations:[]}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let o of e.tool_calls){let a=this.getNormalizedFunctionCallId(o.id,t);r.push({type:"function_call",id:a,call_id:a,name:o.function.name,arguments:o.function.arguments||"",status:"completed"});}return r}if(e.role==="tool"){let r=this.getNormalizedFunctionCallId(e.tool_call_id||e.name,t),i=me(e.content),o=dp(i);return [{type:"function_call_output",call_id:r,output:o}]}if(Array.isArray(e.content)){let r=[];for(let i of e.content)i.type==="text"&&i.text.trim()?r.push({type:"input_text",text:i.text}):i.type==="image_url"&&r.push({type:"input_image",image_url:i.image_url.url});return r.length===0?[]:[{type:"message",role:"user",content:r}]}let n=me(e.content);return !n||n.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:n}]}]}getNormalizedFunctionCallId(e,t){if(e&&t.has(e))return t.get(e);let n;return e?n=e.startsWith("fc_")?e:`fc_${e}`:n=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,n):t.set(n,n),n}formatResponsesFunctionTool(e){let t=new Set(e.parameters.required||[]),n=Object.entries(e.parameters.properties||{}),r=Object.fromEntries(n.map(([o,a])=>[o,t.has(o)?{...a}:this.makeSchemaNullable(a)])),i={...e.parameters,properties:r,required:Object.keys(r),additionalProperties:false};return {type:"function",name:e.name,description:e.description,parameters:i,strict:true}}makeSchemaNullable(e){if(!e||typeof e!="object")return e;let t={...e};return t.type&&(Array.isArray(t.type)?t.type.includes("null")||(t.type=[...t.type,"null"]):t.type!=="null"&&(t.type=[t.type,"null"])),Array.isArray(t.enum)&&!t.enum.includes(null)&&(t.enum=[...t.enum,null]),Array.isArray(t.anyOf)&&(t.anyOf=t.anyOf.map(n=>this.makeSchemaNullable(n))),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(n=>this.makeSchemaNullable(n))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>this.makeSchemaNullable(n))),t}async*parseOpenAIStreamResponse(e){let t="";for await(let n of e){t+=n.toString();let r=t.split(`
1479
+ `);t=r.pop()||"";for(let i of r){let o=i.trim();if(!o||!o.startsWith("data: "))continue;let a=o.slice(6);if(a==="[DONE]"){process.env.CLI_DEBUG==="1"&&console.log("[OpenAI Stream] Received [DONE]");return}try{let l=JSON.parse(a);process.env.CLI_DEBUG==="1"&&console.log("[OpenAI Stream Chunk]",JSON.stringify(l,null,2)),yield l;}catch{process.env.CLI_DEBUG==="1"&&console.log("[OpenAI Stream] Invalid JSON:",a);}}}}async*parseResponsesAPIStream(e){let t=new Map,n=0,r=null,i=null,o=false,a=false,l=u=>{let d={...u};return a||(d.role="assistant",a=true),{choices:[{index:0,delta:d}]}};for await(let u of this.parseOpenAIStreamResponse(e))if(!(!u||typeof u!="object"))switch(u.type){case "response.output_text.delta":{let d=typeof u.delta=="string"?u.delta:"";if(!d)break;o=true,yield l({content:d});break}case "response.output_item.added":{if(u.item?.type==="function_call"){let d=u.item.id||`item_${u.output_index}`,p={id:u.item.call_id||u.item.id||`call_${Date.now()}_${n}`,name:u.item.name,index:n++,arguments:""};t.set(d,p),o=true,yield l({tool_calls:[{index:p.index,id:p.id,type:"function",function:{name:p.name}}]});}break}case "response.function_call_arguments.delta":{let d=u.item_id?t.get(u.item_id):void 0;if(!d)break;let p=typeof u.delta=="string"?u.delta:"";if(!p)break;d.arguments+=p,o=true,yield l({tool_calls:[{index:d.index,id:d.id,type:"function",function:{name:d.name,arguments:p}}]});break}case "response.completed":{r=u.response,i=u.response?.usage;break}case "response.error":case "response.failed":{let d=u.error?.message||u.error?.code||u.message||"Responses stream failed";throw new Error(d)}}if(!o&&r){let u=Array.isArray(r.output)?r.output:[],d="";for(let p of u)if(p?.type==="message"&&Array.isArray(p.content))for(let m of p.content)m?.type==="output_text"&&typeof m.text=="string"&&(d+=m.text);d&&(yield {choices:[{index:0,delta:{role:"assistant",content:d}}]});}let c={choices:[{index:0,delta:{},finish_reason:"stop"}]};i&&(c.usage=this.normalizeUsage(i)),yield c;}async*parseAnthropicStreamResponse(e){let t="",n=[],r=0,i=false,o=null;for await(let l of e){t+=l.toString();let c=t.split(`
1480
+ `);t=c.pop()||"";for(let u of c){let d=u.trim();if(!d||!d.startsWith("data: "))continue;let p=d.slice(6);if(p!=="[DONE]")try{let m=JSON.parse(p);switch(m.type){case "message_start":m.message?.usage&&(o=m.message.usage);break;case "content_block_start":if(m.content_block?.type==="text")i||(i=!0,yield {choices:[{delta:{role:"assistant"},index:0}]});else if(m.content_block?.type==="tool_use"){let h=m.content_block;n.push({index:r,id:h.id,type:"function",function:{name:h.name,arguments:""}}),yield {choices:[{delta:{tool_calls:[{index:r,id:h.id,type:"function",function:{name:h.name}}]},index:0}]},r++;}break;case "content_block_delta":if(m.delta?.type==="text_delta")yield {choices:[{delta:{content:m.delta.text||""},index:0}]};else if(m.delta?.type==="input_json_delta"){let h=m.delta.partial_json||"";if(n.length>0){let g=n[n.length-1];g.function.arguments+=h,yield {choices:[{delta:{tool_calls:[{index:g.index,function:{arguments:h}}]},index:0}]};}}break;case "message_delta":m.usage&&(o=m.usage);break;case "error":throw new Error(m.error?.message||"Stream error")}}catch{}}}let a={choices:[{delta:{},finish_reason:n.length>0?"tool_calls":"stop",index:0}]};o&&(a.usage=this.normalizeUsage(o)),yield a;}normalizeUsage(e){let t={prompt_tokens:e.input_tokens??e.prompt_tokens??0,completion_tokens:e.output_tokens??e.completion_tokens??0,total_tokens:0};return t.total_tokens=t.prompt_tokens+t.completion_tokens,e.prompt_tokens_details?.cached_tokens!==void 0&&(t.prompt_tokens_details={cached_tokens:e.prompt_tokens_details.cached_tokens,text_tokens:e.prompt_tokens_details.text_tokens,audio_tokens:e.prompt_tokens_details.audio_tokens,image_tokens:e.prompt_tokens_details.image_tokens}),e.completion_tokens_details&&(t.completion_tokens_details={text_tokens:e.completion_tokens_details.text_tokens,audio_tokens:e.completion_tokens_details.audio_tokens,reasoning_tokens:e.completion_tokens_details.reasoning_tokens}),e.prompt_cache_hit_tokens!==void 0&&(t.prompt_cache_hit_tokens=e.prompt_cache_hit_tokens),e.cache_read_input_tokens!==void 0&&(t.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!==void 0&&(t.cache_creation_input_tokens=e.cache_creation_input_tokens),t}shouldUseResponsesAPI(e){return this.useResponsesAPI}setSessionId(e){this.sessionId=e,process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Session ID updated to: ${e}`);}getSessionId(){return this.sessionId}setDoubaoThinking(e){this.doubaoThinking=e,process.env.CLI_DEBUG==="1"&&console.log(`[OpenAI] Doubao thinking updated to: ${e?.type||"undefined"}`);}getDoubaoThinking(){return this.doubaoThinking}};le();var Yb=15e3,Tr=2*1024*1024,Xb=1.5*1024*1024;function Zb(s,e=Yb){if(!s||s.length<=e)return s;let t=s.split(`
1481
+ `).length,n=s.length,r=Math.floor(e*.4),i=Math.floor(e*.4),o=r,a=s.length-i;for(;o>0&&(s.charCodeAt(o)&192)===128;)o--;for(;a<s.length&&(s.charCodeAt(a)&192)===128;)a++;let l=s.slice(0,o),c=s.slice(a),d=`
1482
+
1483
+ \u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
1484
+
1485
+ `;return l+d+c}function hp(s,e=2e3){let t=s&&typeof s.toJSON=="function"?s.toJSON():s,n="";try{n=JSON.stringify(t??{},null,2);}catch{n=String(t??"");}return n?n.length>e?`${n.slice(0,e)}
1486
+ ...[truncated ${n.length-e} chars]`:n:"No headers"}var _l="You are Claude Code, Anthropic's official CLI for Claude.",Qb=["claude-code-20250219","interleaved-thinking-2025-05-14"],Ki="2023-06-01",Vi=64,ev=1024;var fp=6e4,gp=3e4,yp={readfile:"Read",write_file:"Write",edit_file:"Edit",glob_search:"Glob",glob:"Glob",search:"Grep",execute_shell:"Bash",bash:"Bash",shell:"Bash",todo_write:"TodoWrite",task:"Task",web_fetch:"WebFetch",web_search:"WebSearch",notebook_edit:"NotebookEdit",ask_user:"AskUserQuestion"},Tl={Read:"readfile",Write:"write_file",Edit:"edit_file",Glob:"glob_search",Grep:"search",Bash:"execute_shell",TodoWrite:"todo_write",Task:"task",WebFetch:"web_fetch",WebSearch:"web_search",NotebookEdit:"notebook_edit",AskUserQuestion:"ask_user"},Yi=class{client;defaultModel;maxTokens;retryConfig;baseUrl;authToken;isProxyMode;claudeCodeUserId;betaFeatures;systemPromptPrefix;sanitizeToolsForProxy;disableCaching;thinkingConfig=null;constructor(e){this.authToken=e.authToken,this.baseUrl=(e.baseUrl||"https://api.anthropic.com").replace(/\/+$/,"");let t=this.baseUrl.includes("api.anthropic.com");this.isProxyMode=e.forceClaudeCodeMode||!t,this.claudeCodeUserId=this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||Qb,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?_l:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=qb.create({baseURL:this.baseUrl,headers:this.buildHeaders(),timeout:3e5,validateStatus:()=>true}),this.defaultModel=e.defaultModel||"claude-sonnet-4-5-20250929",this.maxTokens=e.maxTokens||32e3;let n=Wn("anthropic",this.baseUrl);this.retryConfig=dn(void 0,{...n,...e.retry}),this.debugLog("Initialized",{baseUrl:this.baseUrl,isProxyMode:this.isProxyMode,defaultModel:this.defaultModel,betaFeatures:this.betaFeatures});}setThinking(e){this.thinkingConfig=e,this.debugLog("Thinking config updated",{config:e});}isCacheControlError(e){let t=JSON.stringify(e.response?.data||e.message||"").toLowerCase();return t.includes("cache_control")||t.includes("ttl=")||t.includes("ephemeral")||t.includes("cache")&&t.includes("block")}async chat(e,t={}){let n={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},r=this.retryConfig.requestMaxRetries,i=null,o=n.disableCaching||false;for(let a=0;a<=r;a++){let l={...n,...o?{disableCaching:true}:{}},c=this.buildPayload(e,l);a===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(p.status!==200){let g="";for await(let T of p.data)g+=T.toString();let y=`${this.baseUrl}${d}`,x=jn(y,this.buildHeaders(),c,!1);f.error("CURL","=== [chat] API Error - Full Request CURL ==="),f.error("CURL",x),f.error("CURL",`=== Error Headers: ${hp(p.headers)} ===`),f.error("CURL",`=== Error Response: ${g.substring(0,1e3)} ===`);let S=new Error(`Anthropic API error: ${p.status}`);S.response={status:p.status,headers:p.headers,data:g};try{let T=JSON.parse(g);S.response.data=T,T.error?.message?S.message=`Anthropic API error: ${p.status} - ${T.error.message}`:T.message&&(S.message=`Anthropic API error: ${p.status} - ${T.message}`),this.debugLog("API Error Details",T);}catch{this.debugLog("API Error (non-JSON)",{status:p.status,dataLength:g.length});}throw S}let m=await this.collectStreamResponse(p.data),h=Date.now()-u;return oe.llmResponse("anthropic",h,m.usage,m.choices[0]),this.debugLog("Response",{duration:`${h}ms`,usage:m.usage}),m}catch(u){await this.normalizeAxiosStreamError(u),i=u;let d=mt(u);if(d.code==="PROXY_UPSTREAM_FAILED"){let y=JSON.stringify(c||{}).length,x=Array.isArray(e)?e.length:0,S=Array.isArray(e)?e.reduce((T,w)=>w?.content?typeof w.content=="string"?T+w.content.length:Array.isArray(w.content)?T+w.content.map(L=>typeof L.text=="string"?L.text.length:0).reduce((L,B)=>L+B,0):T:T,0):0;f.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${a+1}/${r+1}`,payloadSize:y,msgCount:x,promptChars:S,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:d.category,code:d.code,attempt:`${a+1}/${r+1}`}),oe.llmError("anthropic",u),this.isCacheControlError(u)&&!o){o=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:a+1}),f.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!d.retryable||a===r)throw d;let p=ci(u.response?.headers),m=Hs(d.category,a+1,p||d.retryAfter),h=d.category==="retryable_rate_limit",g=h?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${st(m)} \u540E\u91CD\u8BD5...`:`Retrying in ${st(m)}...`;this.debugLog("Retrying",{delay:st(m),attempt:a+1,isRateLimit:h,serverDelay:p?st(p):"none",retryMsg:g}),await ft(m);}}throw i||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",n="",r=[],i="",o=null,a="";for await(let c of e){let u=c.toString();t+=u;let d=t.split(`
1487
+ `);t=d.pop()||"";for(let p of d){let m=p.trim();if(!m||!m.startsWith("data: "))continue;let h=m.slice(6);if(h!=="[DONE]")try{let g=JSON.parse(h);if(process.env.CLI_DEBUG==="1"){let y=JSON.stringify(g).substring(0,80);f.debug("SSE",`${g.type.padEnd(20)} ${y}${JSON.stringify(g).length>80?"...":""}`);}switch(g.type){case "message_start":a=g.message?.id||"",o=g.message?.usage;break;case "content_block_start":if(g.content_block?.type==="tool_use"){let y=g.content_block,x=this.isProxyMode?Tl[y.name]||this.fromClaudeCodeToolName(y.name):y.name;r.push({id:y.id,type:"function",function:{name:x,arguments:""}});}break;case "content_block_delta":g.delta?.type==="text_delta"?n+=g.delta.text||"":g.delta?.type==="input_json_delta"?r.length>0&&(r[r.length-1].function.arguments+=g.delta.partial_json||""):g.delta?.type==="thinking_delta"&&(i+=g.delta.thinking||"");break;case "message_delta":g.usage&&(o={...o,...g.usage});break}}catch(g){process.env.CLI_DEBUG==="1"&&f.warn("Anthropic",`Stream parse error: ${g}, data: ${h.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(o);return {id:a,choices:[{message:{role:"assistant",content:n||"",tool_calls:r.length>0?r:void 0,...i?{reasoning_content:i}:{}},finish_reason:r.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let n={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},r=this.retryConfig.streamMaxRetries,i=0,o=n.disableCaching||false,a=true;for(;;){let l={...n,...o?{disableCaching:true}:{}},c=this.buildPayload(e,l);c.stream=true,a&&(this.logRequest(t.model||this.defaultModel,c,true),a=false);try{let u=Date.now(),d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",p=await this.client.post(d,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:p.status}),p.status!==200){let M="";for await(let A of p.data)M+=A.toString();let _=`${this.baseUrl}${d}`,W=jn(_,this.buildHeaders(),c,!1);f.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),f.error("CURL",W),f.error("CURL",`=== Error Headers: ${hp(p.headers)} ===`),f.error("CURL",`=== Error Response: ${M.substring(0,1e3)} ===`);let $=new Error(`Anthropic API error: ${p.status}`);$.response={status:p.status,headers:p.headers,data:M};try{let A=JSON.parse(M);$.response.data=A,A.error?.message?$.message=`Anthropic API error: ${p.status} - ${A.error.message}`:A.message&&($.message=`Anthropic API error: ${p.status} - ${A.message}`),this.debugLog("API Error Details (stream)",A);}catch{this.debugLog("API Error (non-JSON, stream)",{status:p.status,dataLength:M.length});}throw $}let m="",h=[],g=0,y=!1,x=null,S=!1,T=Date.now(),w=0,L=0,B=null,I=[],k=null;for await(let M of this.createTimeoutStream(p.data,t.signal)){T=Date.now();let _=M.toString();m+=_;let W=m.split(/\n\n+/);m=W.pop()||"";for(let $ of W){let A=$.split(`
1488
+ `),G="";for(let N of A){let U=N.trim();if(U&&!U.startsWith("event:"))if(U.startsWith("data:")){let H=U.slice(5);H.startsWith(" ")&&(H=H.slice(1)),G+=H;}else G+=U;}if(!(!G||G==="[DONE]"))try{let N=G.trim(),U=JSON.parse(N);if(process.env.CLI_DEBUG==="1"){let Ie=JSON.stringify(U).substring(0,80);f.debug("SSE",`${U.type.padEnd(20)} ${Ie}${JSON.stringify(U).length>80?"...":""}`);}let H=this.handleStreamEvent(U,h,g,y,x);if(H.yield&&(yield H.yield),H.roleSent!==void 0&&(y=H.roleSent),H.incrementToolIndex&&g++,H.usage&&(x=H.usage),H.error)throw new Error(H.error);H.contentBlockStart&&L++,H.contentBlockStop&&w++,H.messageStop&&(S=!0),H.stopReason&&(B=H.stopReason),U.type==="content_block_start"?U.content_block?.type==="thinking"?k={type:"thinking",thinking:"",signature:""}:U.content_block?.type==="redacted_thinking"&&I.push({type:"redacted_thinking",data:U.content_block.data}):U.type==="content_block_delta"?k&&(U.delta?.type==="thinking_delta"?k.thinking+=U.delta.thinking||"":U.delta?.type==="signature_delta"&&(k.signature+=U.delta.signature||"")):U.type==="content_block_stop"&&k&&(I.push({type:k.type,thinking:k.thinking,signature:k.signature}),k=null);}catch{}}}let R=Date.now()-u;if(!S){let M=new Error(`Stream incomplete: message_stop not received (blocks: ${L} started, ${w} completed)`);throw M.code="STREAM_INCOMPLETE",M.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:S,contentBlocksStarted:L,contentBlocksCompleted:w,toolCallsCount:h.length,duration:`${R}ms`}),M}if(L!==w)if(B==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:L,contentBlocksCompleted:w,stopReason:B}),f.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let M=new Error(`Stream incomplete: content blocks mismatch (${L} started, ${w} completed)`);throw M.code="STREAM_INCOMPLETE",M.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:L,contentBlocksCompleted:w,stopReason:B}),M}if(h.length>0&&B!=="max_tokens")for(let M of h){let _=M.function?.arguments||"";if(_&&_.trim())try{JSON.parse(_);}catch{let W=new Error(`Stream incomplete: tool arguments truncated for ${M.function?.name}`);throw W.code="STREAM_INCOMPLETE",W.isNetworkInterrupt=!0,W.toolName=M.function?.name,this.debugLog("Tool arguments truncated",{toolName:M.function?.name,argsLength:_.length,argsPreview:_.substring(0,100)}),W}}else if(B==="max_tokens"&&h.length>0){let M=h[h.length-1],_=M?.function?.arguments||"";try{JSON.parse(_);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:M?.function?.name,argsLength:_.length}),f.warn("Anthropic",`\u26A0\uFE0F Tool call ${M?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",x);let E=this.buildUsageFromRaw(x);this.debugLog("usage after build",E),!y&&h.length===0&&f.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${R}ms, usage: ${JSON.stringify(x)}`),oe.llmResponse("anthropic-stream",R,E||{},{}),this.debugLog("Stream complete",{duration:`${R}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...E?{usage:E}:{},...I.length>0?{thinking_blocks:I}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let d=mt(u);this.debugLog("Stream error",{message:u.message,category:d.category,retryable:d.retryable});let p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",m=`${this.baseUrl}${p}`,h=jn(m,this.buildHeaders(),c,false);if(f.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),f.error("CURL",h),f.error("CURL",`=== Error: ${d.message} ===`),oe.llmError("anthropic-stream",u),this.isCacheControlError(u)&&!o){o=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:i+1}),f.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(d.retryable&&i<r){i++;let g=ci(u.response?.headers),y=Hs(d.category,i,g||d.retryAfter),x=d.category==="retryable_rate_limit",S=d.category==="retryable_stream";this.debugLog("Stream retrying",{delay:st(y),attempt:`${i}/${r}`,isRateLimit:x,isStreamIncomplete:S}),yield {type:"stream_retry",error:d.message,errorCode:d.code,attempt:i,maxRetries:r,delayMs:y,isRateLimit:x,isNetworkError:S},await ft(y),this.debugLog("Stream retry starting",{attempt:i}),yield {type:"stream_recovered",attempt:i,maxRetries:r};continue}throw d}}}buildPayload(e,t){let n=t.model||this.defaultModel,{system:r,anthropicMessages:i}=this.convertMessages(e,t),o=i,a=[];t.disableCaching?(a.push({type:"text",text:_l}),r&&a.push({type:"text",text:`
1489
+ `+r})):(a.push({type:"text",text:_l,cache_control:{type:"ephemeral"}}),r&&a.push({type:"text",text:`
1490
+ `+r,cache_control:{type:"ephemeral"}}));let l={model:this.normalizeModelName(n),system:a,metadata:this.buildMetadata(t.metadata),max_tokens:this.maxTokens};return (!t.thinking?.type||t.thinking.type==="disabled")&&(l.temperature=t.temperature??.7),l.stream=true,l.messages=o,t.tools?.length&&(l.tools=this.buildToolsPayload(t.tools,t)),t.webSearch?.enabled&&(l.tools=l.tools||[],l.tools.push(this.buildWebSearchTool(t.webSearch))),l.tools?.length>0&&this.ensureLastToolCacheControl(l.tools,t),this.shouldEnableThinking(n,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let n=JSON.stringify(e).length;if(n>Tr){if(this.debugLog("Request body exceeds limit",{bodySize:n,limit:Tr,messageCount:e.messages?.length||0}),e.messages){let i=[...e.messages.map((o,a)=>({index:a,role:o.role,contentSize:JSON.stringify(o.content||"").length}))].sort((o,a)=>a.contentSize-o.contentSize);this.debugLog("Largest messages in request",{top5:i.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(n/1024/1024).toFixed(2)}MB) exceeds ${(Tr/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else n>Xb&&this.debugLog("Request body approaching limit",{bodySize:n,limit:Tr,percentage:(n/Tr*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let n=[...t],r=n.findIndex(i=>i.role==="user");if(r>=0){let i=n[r],o={type:"text",text:`<system_context>
1491
+ ${e}
1492
+ </system_context>`};Array.isArray(i.content)?n[r]={...i,content:[o,...i.content]}:typeof i.content=="string"&&(n[r]={...i,content:[o,{type:"text",text:i.content}]});}return n}buildToolsPayload(e,t){return e.map(r=>this.transformToolDefinition(r))}ensureLastToolCacheControl(e,t){if(e.length===0||t.disableCaching)return;let n=e[e.length-1];n.cache_control={type:"ephemeral"},this.debugLog("Added cache_control to last tool",{toolName:n.name});}buildWebSearchTool(e){let t={type:"web_search_20250305",name:"web_search"};return e.max_uses&&(t.max_uses=e.max_uses),e.user_location&&(t.user_location=e.user_location),t}buildThinkingPayload(e){let t=e.thinking?.budget_tokens||this.maxTokens-1;return {type:"enabled",budget_tokens:Math.max(t,ev)}}buildMetadata(e){let t={...e};return t.user_id?t.user_id=this.sanitizeUserId(t.user_id):t.user_id=this.claudeCodeUserId,t}shouldEnableThinking(e,t){return t.thinking?.type==="enabled"?true:t.thinking?.type==="disabled"?false:!!(e.endsWith("-thinking")||e.includes("opus-4-5")||e.includes("opus-4.5"))}normalizeModelName(e){return e.endsWith("-thinking")?e.replace(/-thinking$/,""):e}convertMessages(e,t){let n=this.normalizeMessages(e),r=null,i=[];for(let c of n){if(c.role==="system"){r=me(c.content);continue}let u=this.convertSingleMessage(c);u&&i.push(u);}let o=this.mergeConsecutiveUserMessages(i),l=this.validateToolResultPairs(o);return l.length>0&&l[0].role!=="user"&&l.unshift({role:"user",content:[{type:"text",text:"..."}]}),l.length>0&&!t.disableCaching&&this.addMessageCacheControl(l),{system:r,anthropicMessages:l}}addMessageCacheControl(e){let t=false;for(let n=e.length-1;n>=0;n--){let r=e[n];if(!(r.role!=="user"||!Array.isArray(r.content))){for(let i=r.content.length-1;i>=0;i--){let o=r.content[i];if(!t&&o.type==="tool_result"){o.cache_control={type:"ephemeral"},t=true,this.debugLog("Added cache_control to tool_result",{tool_use_id:o.tool_use_id});break}}if(t)break}}t||this.addTextBlockCacheControl(e);}addTextBlockCacheControl(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"&&Array.isArray(n.content)){for(let r=n.content.length-1;r>=0;r--)if(n.content[r].type==="text"){n.content[r].cache_control={type:"ephemeral"},this.debugLog("Added cache_control to user text block");return}}}}validateToolResultPairs(e){let t=new Set,n=new Set;for(let o of e)if(Array.isArray(o.content))for(let a of o.content)a.type==="tool_use"&&a.id&&t.add(a.id),a.type==="tool_result"&&a.tool_use_id&&n.add(a.tool_use_id);let r=new Set;for(let o of t)n.has(o)&&r.add(o);this.debugLog("Tool pairing analysis",{toolUseCount:t.size,toolResultCount:n.size,pairedCount:r.size,orphanToolUseIds:Array.from(t).filter(o=>!r.has(o)),orphanToolResultIds:Array.from(n).filter(o=>!r.has(o))});let i=[];for(let o of e){if(!Array.isArray(o.content)){i.push(o);continue}let a=o.content.filter(l=>{if(l.type==="tool_use"){let c=r.has(l.id);return c||this.debugLog("Removing orphan tool_use",{id:l.id}),c}if(l.type==="tool_result"){let c=r.has(l.tool_use_id);return c||this.debugLog("Removing orphan tool_result",{tool_use_id:l.tool_use_id}),c}return true});a.length>0?i.push({...o,content:a}):this.debugLog("Skipping empty message after tool pairing filter",{role:o.role});}return i}mergeConsecutiveUserMessages(e){if(e.length===0)return [];let t=[];for(let n of e){let r=t[t.length-1];if(r&&r.role==="user"&&n.role==="user"){let i=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];r.content=[...i,...o];}else t.push(n);}return t}convertSingleMessage(e){if(e.role==="tool"){let n=me(e.content),r=Zb(n);return n.length!==r.length&&this.debugLog("Tool output truncated",{tool_call_id:e.tool_call_id,original:n.length,truncated:r.length}),{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:r}]}}if(e.role==="assistant"){let n=[],r=false;if(e.thinking_blocks&&e.thinking_blocks.length>0){r=true;for(let o of e.thinking_blocks)if(o.type==="thinking"){let a={type:"thinking",thinking:o.thinking};o.signature!==void 0&&(a.signature=o.signature),n.push(a);}else if(o.type==="redacted_thinking"){let a={type:"redacted_thinking"};o.data!==void 0&&(a.data=o.data),n.push(a);}}let i=me(e.content);if(i){let o=i.trimEnd();n.push({type:"text",text:o||"."});}else r&&(n.push({type:"text",text:"."}),this.debugLog("Added placeholder text after thinking (no text content)"));if(e.tool_calls)for(let o of e.tool_calls){let a=(o.function.arguments||"").trim(),l={};if(a.length>0)try{l=JSON.parse(a);}catch{this.debugLog("Failed to parse tool arguments",{tool:o.function.name});}let c=this.isProxyMode?yp[o.function.name]||this.toClaudeCodeToolName(o.function.name):o.function.name;n.push({type:"tool_use",id:o.id,name:c,input:l});}if(n.length>0){let o=n[n.length-1];this.debugLog("Assistant message final check",{contentLength:n.length,lastBlockType:o.type,hasThinkingBlocks:r,blockTypes:n.map(a=>a.type),lastBlockTextPreview:o.type==="text"?(o.text||"").substring(0,50):void 0}),o.type==="thinking"||o.type==="redacted_thinking"?(n.push({type:"text",text:"."}),this.debugLog("Fixed: Added text block after thinking")):o.type==="text"&&(!o.text||!o.text.trim())&&n.some(l=>l.type==="thinking"||l.type==="redacted_thinking")&&(o.text=".",this.debugLog("Fixed: Ensured text block has content after thinking"));}return n.length>0?{role:"assistant",content:n}:null}if(Array.isArray(e.content)){let n=e.content.filter(o=>o.type==="text");if(!e.content.some(o=>o.type!=="text")&&n.length===1){let o=n[0].text;return o.trim()?{role:"user",content:o}:null}let i=this.convertMultimodalContent(e.content);return i.length>0?{role:"user",content:i}:null}let t=me(e.content);return t.trim()?{role:"user",content:t}:null}convertMultimodalContent(e){let t=[];for(let n of e)if(n.type==="text")t.push({type:"text",text:n.text});else if(n.type==="image_url"){let r=this.convertImageUrl(n.image_url.url);r&&t.push(r);}return t}convertImageUrl(e){if(e.startsWith("data:")){let t=e.match(/^data:([^;]+);base64,(.+)$/);if(t)return {type:"image",source:{type:"base64",media_type:t[1],data:t[2]}}}else return {type:"image",source:{type:"url",url:e}};return null}normalizeMessages(e){let t=e.filter(n=>{let r=n.role==="assistant"&&!!(n.tool_calls&&n.tool_calls.length>0),i=n.role==="assistant"&&!!(n.thinking_blocks&&n.thinking_blocks.length>0);return r||i?true:n.content?typeof n.content=="string"?n.content.trim().length>0:Array.isArray(n.content)?n.content.length>0:true:false});return t.length===0?[]:(this.validateMessageAlternation(t),t)}validateMessageAlternation(e){let t=e.filter(r=>r.role!=="system"),n=false;for(let r=1;r<t.length;r++)t[r].role===t[r-1].role&&(n=true,this.debugLog("Message alternation warning",{index:r,prevRole:t[r-1].role,currentRole:t[r].role}));!n&&t.length>1&&this.debugLog("Message alternation OK",{messageCount:t.length,roles:t.map(r=>r.role)});}convertResponse(e){this.debugLog("Raw response",e);let t=e.content||[],n="",r=[],i="";for(let a of t)if(a.type==="text")n+=a.text;else if(a.type==="tool_use"){let l=this.isProxyMode?Tl[a.name]||this.fromClaudeCodeToolName(a.name):a.name;r.push({id:a.id,type:"function",function:{name:l,arguments:JSON.stringify(a.input)}});}else a.type==="thinking"&&(i=a.thinking||"");let o=this.buildUsageFromRaw(e.usage);return {id:e.id,choices:[{message:{role:"assistant",content:n||"",tool_calls:r.length>0?r:void 0,...i?{reasoning_content:i}:{}},finish_reason:this.convertStopReason(e.stop_reason)}],usage:o}}buildUsageFromRaw(e){if(!e)return {prompt_tokens:0,completion_tokens:0,total_tokens:0};let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:(e.input_tokens||0)+(e.output_tokens||0)};return e.cache_read_input_tokens&&(t.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens&&(t.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(e.cache_creation.ephemeral_5m_input_tokens&&(t.cache_creation_5m_tokens=e.cache_creation.ephemeral_5m_input_tokens),e.cache_creation.ephemeral_1h_input_tokens&&(t.cache_creation_1h_tokens=e.cache_creation.ephemeral_1h_input_tokens)),t}convertStopReason(e){switch(e){case "end_turn":return "stop";case "max_tokens":return "length";case "tool_use":return "tool_calls";default:return "stop"}}handleStreamEvent(e,t,n,r,i){switch(e.type){case "message_start":return this.debugLog("message_start usage",e.message?.usage),process.env.CLI_DEBUG==="1"&&e.message&&f.debug("Anthropic",`message_start full: ${JSON.stringify(e.message,null,2)}`),{usage:e.message?.usage};case "content_block_start":return {...this.handleContentBlockStart(e,t,n,r),contentBlockStart:true};case "content_block_delta":return this.handleContentBlockDelta(e,t);case "content_block_stop":return this.validateToolArguments(t),{contentBlockStop:true};case "message_delta":this.debugLog("message_delta usage",{eventUsage:e.usage,currentUsage:i});let a=e.delta?.stop_reason;if(a&&this.debugLog("message_delta stop_reason",a),e.usage&&i){let l={...i,...e.usage};return this.debugLog("merged usage",l),{usage:l,stopReason:a}}return {usage:e.usage||i,stopReason:a};case "message_stop":return this.debugLog("Message stop received"),{messageStop:true};case "ping":return {};case "error":return {error:e.error?.message||"Stream error"};default:return this.debugLog("Unknown event type",{type:e.type}),{}}}handleContentBlockStart(e,t,n,r){if(e.content_block?.type==="text"){if(!r)return {yield:{choices:[{delta:{role:"assistant"},index:0}]},roleSent:true}}else if(e.content_block?.type==="tool_use"){let i=e.content_block,o=this.isProxyMode?Tl[i.name]||this.fromClaudeCodeToolName(i.name):i.name,a="";return i.input&&typeof i.input=="object"&&Object.keys(i.input).length>0&&(a=JSON.stringify(i.input)),t.push({index:n,id:i.id,type:"function",function:{name:o,arguments:a}}),{yield:{choices:[{delta:{tool_calls:[{index:n,id:i.id,type:"function",function:{name:o}}]},index:0}]},incrementToolIndex:true}}else if(e.content_block?.type==="thinking")return {};return {}}handleContentBlockDelta(e,t){if(e.delta?.type==="text_delta")return {yield:{choices:[{delta:{content:e.delta.text||""},index:0}]}};if(e.delta?.type==="input_json_delta"){let n=e.delta.partial_json||"";if(t.length>0){let r=t[t.length-1];return r.function.arguments+=n,{yield:{choices:[{delta:{tool_calls:[{index:r.index,function:{arguments:n}}]},index:0}]}}}}else {if(e.delta?.type==="thinking_delta")return {yield:{choices:[{delta:{reasoning_content:e.delta.thinking},index:0}]}};if(e.delta?.type==="signature_delta")return {}}return {}}validateToolArguments(e){if(e.length===0)return;let t=e[e.length-1];if(t.function.arguments)try{JSON.parse(t.function.arguments);}catch{let n=this.tryFixJson(t.function.arguments);n?(t.function.arguments=n,this.debugLog("Auto-fixed tool arguments",{tool:t.function.name})):this.debugLog("Invalid tool arguments JSON",{tool:t.function.name});}}tryFixJson(e){let t=e.trim();if(!t.endsWith("}")){t+="}";try{return JSON.parse(t),t}catch{}}t=e.replace(/,\s*$/,""),t.endsWith("}")||(t+="}");try{return JSON.parse(t),t}catch{}let n=0,r=0,i=false,o=false;for(let a of e){if(o){o=false;continue}if(a==="\\"){o=true;continue}if(a==='"'){i=!i;continue}i||(a==="{"?n++:a==="}"?n--:a==="["?r++:a==="]"&&r--);}for(t=e,i&&(t+='"');r>0;)t+="]",r--;for(;n>0;)t+="}",n--;try{return JSON.parse(t),t}catch{return null}}transformToolDefinition(e){let t=this.isProxyMode?yp[e.name]||this.toClaudeCodeToolName(e.name):e.name;if(this.isProxyMode){let i=this.stripSchemaPropertyDescriptions(e.parameters);return {name:t,description:e.description,input_schema:i}}if(!this.sanitizeToolsForProxy)return {name:t,description:e.description,input_schema:e.parameters};let n=this.truncateDescription(e.description||e.name),r=this.stripSchemaDescriptions(e.parameters);return {name:t,description:n,input_schema:r}}stripSchemaPropertyDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.stripSchemaPropertyDescriptions(n));let t={...e};if(t.properties&&typeof t.properties=="object"){let n={};for(let[r,i]of Object.entries(t.properties))if(i&&typeof i=="object"){let o={...i};delete o.description,o.properties&&(o.properties=this.stripSchemaPropertyDescriptions({properties:o.properties}).properties),o.items&&(o.items=this.stripSchemaPropertyDescriptions(o.items)),n[r]=o;}else n[r]=i;t.properties=n;}t.items&&(t.items=this.stripSchemaPropertyDescriptions(t.items));for(let n of ["oneOf","anyOf","allOf"])t[n]&&Array.isArray(t[n])&&(t[n]=t[n].map(r=>this.stripSchemaPropertyDescriptions(r)));return t}toClaudeCodeToolName(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}fromClaudeCodeToolName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}truncateDescription(e){if(!e)return "Utility tool";let t=e.replace(/\s+/g," ").trim();return t?t.length>120?`${t.slice(0,117)}...`:t:"Utility tool"}stripSchemaDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.stripSchemaDescriptions(n));let t={...e};if(delete t.description,t.properties&&typeof t.properties=="object"){let n={};for(let[r,i]of Object.entries(t.properties))n[r]=this.stripSchemaDescriptions(i);t.properties=n;}for(let n of ["items","oneOf","anyOf","allOf"])t[n]&&(t[n]=Array.isArray(t[n])?t[n].map(r=>this.stripSchemaDescriptions(r)):this.stripSchemaDescriptions(t[n]));return t}buildHeaders(){return this.isProxyMode?this.buildClaudeCodeHeaders():this.buildOfficialHeaders()}buildOfficialHeaders(){return {"anthropic-api-key":this.authToken,"anthropic-version":Ki,"Content-Type":"application/json"}}buildClaudeCodeHeaders(){return {Accept:"application/json","X-Stainless-Retry-Count":"0","X-Stainless-Timeout":"600","X-Stainless-Lang":"js","X-Stainless-Package-Version":"0.70.0","X-Stainless-OS":"MacOS","X-Stainless-Arch":"arm64","X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version,"anthropic-dangerous-direct-browser-access":"true","anthropic-version":Ki,"x-app":"cli","User-Agent":"claude-cli/2.0.55 (external, cli)",Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json","anthropic-beta":this.betaFeatures.join(","),"x-stainless-helper-method":"stream","accept-language":"*","sec-fetch-mode":"cors","accept-encoding":"br, gzip, deflate"}}generateSafeUserId(){if(this.isProxyMode){let n=randomBytes(32).toString("hex"),r=this.generateUUID();return `user_${n}_account__session_${r}`}let e=randomBytes(16).toString("hex"),t=randomBytes(4).toString("hex");return `user_${e}_session_${t}`}generateUUID(){let e=randomBytes(16);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=e.toString("hex");return `${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}sanitizeUserId(e){if(this.isProxyMode){if(/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),n=this.generateUUID();return `user_${t}_account__session_${n}`}if(/^\+?[\d\s-]{10,}$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),n=this.generateUUID();return `user_${t}_account__session_${n}`}return e}return e.length>Vi?createHash("sha256").update(e).digest("hex").slice(0,Vi):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Vi):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Vi):e}async normalizeAxiosStreamError(e){let t=e?.response?.data;if(!(!t||typeof t!="object"||!(typeof t.pipe=="function")))try{let r=await this.readStreamToString(t);try{e.response.data=JSON.parse(r);}catch{e.response.data=r;}}catch{}}readStreamToString(e){return new Promise((t,n)=>{let r=[];e.on("data",i=>{r.push(typeof i=="string"?Buffer.from(i):i);}),e.on("end",()=>t(Buffer.concat(r).toString("utf-8"))),e.on("error",n);})}async*createTimeoutStream(e,t){let n=false,r=Date.now(),i=0,o=e[Symbol.asyncIterator](),a=()=>new Promise(l=>setImmediate(l));for(process.env.CLI_DEBUG==="1"&&f.debug("STREAM","\u{1F30A} Stream processing started");;){if(t?.aborted)throw this.debugLog("Stream aborted by signal"),process.env.CLI_DEBUG==="1"&&f.debug("STREAM",`\u26D4 Stream aborted after ${i} chunks`),e.destroy?.(),new Error("Request aborted");await a();let l=n?fp:gp,c;try{let u=t?new Promise((m,h)=>{let g=()=>{h(new Error("Request aborted"));};t.aborted?g():t.addEventListener("abort",g,{once:!0});}):null,d=[o.next(),new Promise((m,h)=>{c=setTimeout(()=>{h(new Error(n?`Stream idle timeout: no data for ${fp/1e3}s`:`Stream first chunk timeout: no response for ${gp/1e3}s`));},l);})];u&&d.push(u);let p=await Promise.race(d);if(c&&clearTimeout(c),p.done){process.env.CLI_DEBUG==="1"&&f.debug("STREAM",`\u2705 Stream completed successfully (${i} chunks, ${Date.now()-r}ms)`);return}n=!0,r=Date.now(),i++,process.env.CLI_DEBUG==="1"&&i%100===0&&f.debug("STREAM",`\u{1F4E6} Processed ${i} chunks`),yield p.value;}catch(u){c&&clearTimeout(c);let d=u.message?.includes("aborted")||u.message==="Request aborted";throw this.debugLog("Stream timeout or abort",{error:u.message,isAbort:d,receivedFirstChunk:n,idleTime:`${(Date.now()-r)/1e3}s`}),e.destroy?.(),d?(u.name="AbortError",u.code="ERR_CANCELED",u.category="canceled",u):(u.code="STREAM_TIMEOUT",u.isNetworkInterrupt=true,u)}}}debugLog(e,t){process.env.CLI_DEBUG==="1"&&f.debug("Anthropic",t?`${e} ${JSON.stringify(t,null,2)}`:e);}logRequest(e,t,n=false){this.debugLog("Full payload",JSON.stringify(t,null,2));let r=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",i=`${this.baseUrl}${r}`,o=this.buildHeaders();pa(i,o,t);let a=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":Ki,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":Ki,"Content-Type":"application/json"};oe.llmRequest(n?"anthropic-stream":"anthropic",e,t,i,a),this.debugLog(`${n?"Stream ":""}Request`,{url:i,model:e,isProxyMode:this.isProxyMode});}};var nv=16e3;function sv(s,e=nv){if(!s||s.length<=e)return s;let t=s.split(`
1493
+ `).length,n=s.length,r=Math.floor(e*.4),i=Math.floor(e*.4),o=r,a=s.length-i;for(;o>0&&(s.charCodeAt(o)&192)===128;)o--;for(;a<s.length&&(s.charCodeAt(a)&192)===128;)a++;let l=s.slice(0,o),c=s.slice(a),d=`
1494
+
1495
+ \u2026[${n-l.length-c.length} chars truncated, total ${t} lines]\u2026
1496
+
1497
+ `;return l+d+c}var Xi=class{client;defaultModel;retryConfig;baseUrl;thinking;reasoning;caching;store;lastResponseId=null;sessionResponseIds=new Map;constructor(e){this.baseUrl=e.baseUrl||"https://ark.cn-beijing.volces.com/api/v3",this.defaultModel=e.defaultModel||"doubao-seed-1-6-251015",this.thinking=e.thinking,this.reasoning=e.reasoning,this.caching=e.caching||{type:"enabled"},this.store=e.store??true,this.client=qb.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:18e4}),this.retryConfig=dn(void 0,{requestMaxRetries:3,streamMaxRetries:5,...e.retry}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao] Initialized with:",{baseUrl:this.baseUrl,defaultModel:this.defaultModel,thinking:this.thinking,caching:this.caching,store:this.store});}async chat(e,t={}){let n="",r="",i=[],o,a;for await(let l of this.chatStreamed(e,t)){let c=l.choices?.[0]?.delta;if(c&&(c.content&&(n+=c.content),c.reasoning_content&&(r+=c.reasoning_content),c.tool_calls))for(let u of c.tool_calls){let d=i.find(p=>p.index===u.index);d?u.function?.arguments&&(d.function.arguments+=u.function.arguments):i.push({id:u.id||`call_${i.length}`,type:"function",function:{name:u.function?.name||"",arguments:u.function?.arguments||""},index:u.index});}l.usage&&(o=l.usage),l.id&&(a=l.id);}return a&&(this.lastResponseId=a,t.sessionId&&this.sessionResponseIds.set(t.sessionId,a)),{id:a||`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:n||null,reasoning_content:r||void 0,...i.length>0?{tool_calls:i}:{}},finish_reason:i.length>0?"tool_calls":"stop"}],usage:o||{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}async*chatStreamed(e,t={}){let{model:n=this.defaultModel,tools:r,temperature:i=.7,sessionId:o,signal:a}=t,l=t.previousResponseId;!l&&o&&(l=this.sessionResponseIds.get(o)),l||(l=this.lastResponseId||void 0);let c=this.buildPayload(e,{model:n,tools:r,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:t.maxInputTokens,previousResponseId:l}),u=`${this.baseUrl}/responses`;oe.llmRequest("doubao-responses",n,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1498
+ [Doubao Responses API Request]`),console.log("URL:",u),console.log("Payload:",JSON.stringify(c,null,2)));let d=this.retryConfig.streamMaxRetries,p=0;for(;;)try{if(a?.aborted){let y=new Error("Request aborted");throw y.name="AbortError",y}let m=Date.now(),h=await this.client.post("/responses",c,{responseType:"stream",signal:a,headers:{Accept:"text/event-stream"}});if(process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1499
+ [Doubao Stream Started]`),console.log("Status:",h.status)),h.status!==200){let y="";for await(let x of h.data)y+=x.toString();throw new Error(`Doubao API error: ${h.status} - ${y}`)}yield*this.parseStreamResponse(h.data);let g=Date.now()-m;oe.llmResponse("doubao-responses",g,{},{}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1500
+ [Doubao Stream Complete]`),console.log("Duration:",`${g}ms`));return}catch(m){let h="";if(m.response?.data)try{if(typeof m.response.data.on=="function"){let y=[];for await(let S of m.response.data)y.push(Buffer.from(S));let x=Buffer.concat(y).toString("utf-8");try{let S=JSON.parse(x);h=JSON.stringify(S.error||S,null,2);}catch{h=x;}}else typeof m.response.data=="string"?h=m.response.data:m.response.data.error?h=JSON.stringify(m.response.data.error,null,2):h=JSON.stringify(m.response.data,null,2);}catch(y){h=`HTTP ${m.response?.status||"unknown"} (\u65E0\u6CD5\u8BFB\u53D6\u54CD\u5E94\u4F53: ${y})`;}let g=mt(m);if(process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1501
+ [Doubao Stream Error]`),console.log("Message:",m.message),console.log("Status:",m.response?.status),console.log("Error Details:",h||"none"),console.log("Retryable:",g.retryable)),h&&(g.message=`${m.message}
1502
+ ${h}`),oe.llmError("doubao-responses",m),g.retryable&&p<d){p++;let y=m.response?.headers?.["retry-after"],x=Jt(y),S=pn(x,p,this.retryConfig);console.log(`[Doubao] Stream failed (${g.code}), reconnecting in ${st(S)} (${p}/${d})...`),yield {choices:[],type:"stream_retry",error:g.message,errorCode:g.code,attempt:p,maxRetries:d,delayMs:S},await ft(S);continue}throw g}}getResponseId(e){return e?this.sessionResponseIds.get(e)||null:this.lastResponseId}setResponseId(e,t){this.lastResponseId=e,t&&this.sessionResponseIds.set(t,e);}clearSession(e){e?this.sessionResponseIds.delete(e):this.lastResponseId=null;}setThinking(e){this.thinking=e;}setCaching(e){this.caching=e;}buildPayload(e,t){let {model:n,tools:r,temperature:i,structuredOutput:o,maxInputTokens:a,previousResponseId:l}=t,c=this.convertToDoubaoInput(e,l);this.extractSystemInstructions(e);let d={model:n,input:c,stream:true,temperature:i};return l&&(d.previous_response_id=l),this.thinking&&(d.thinking=this.thinking),this.reasoning&&(d.reasoning=this.reasoning),r&&r.length>0&&(d.tools=r.map(p=>({type:"function",name:p.name,description:p.description,parameters:p.parameters})),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Doubao] Added ${d.tools.length} tools`)),o&&(d.text={format:{type:"json_schema",name:o.name,schema:o.schema}}),d}extractSystemInstructions(e){let t=e.filter(n=>n.role==="system").map(n=>me(n.content).trim()).filter(n=>n.length>0);return t.length>0?t.join(`
1503
+
1504
+ `):void 0}convertToDoubaoInput(e,t){let n=new Map;if(!e.some(o=>o.role==="tool"||o.role==="assistant"&&Array.isArray(o.tool_calls)&&o.tool_calls.length>0))return e.map(o=>({role:o.role,content:me(o.content)}));let i=e.filter(o=>o.role!=="system");if(t){let o=[],a=false;for(let l=i.length-1;l>=0;l--){let c=i[l];if(c.role==="user"&&!a)o.unshift(...this.convertMessageToInputItems(c,n)),a=true;else if(c.role==="tool"&&a)o.unshift(...this.convertMessageToInputItems(c,n));else if(a)break}return o}return i.flatMap(o=>this.convertMessageToInputItems(o,n)).filter(o=>o!==null)}convertMessageToInputItems(e,t){if(e.role==="assistant"){let r=[],i=me(e.content);if(i.trim().length>0&&r.push({type:"message",role:"assistant",status:"completed",content:[{type:"input_text",text:i}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let o of e.tool_calls){let a=this.normalizeCallId(o.id,t);r.push({type:"function_call",id:a,call_id:a,name:o.function.name,arguments:o.function.arguments||"",status:"completed"});}return r}if(e.role==="tool"){let r=this.normalizeCallId(e.tool_call_id||e.name,t),i=me(e.content),o=sv(i);return [{type:"function_call_output",call_id:r,output:o}]}if(Array.isArray(e.content)){let r=[];for(let i of e.content)i.type==="text"&&i.text.trim()?r.push({type:"input_text",text:i.text}):i.type==="image_url"&&r.push({type:"input_image",image_url:i.image_url.url});return r.length===0?[]:[{type:"message",role:"user",content:r}]}let n=me(e.content);return !n||n.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:n}]}]}normalizeCallId(e,t){if(e&&t.has(e))return t.get(e);let n;return e?n=e.startsWith("fc_")?e:`fc_${e}`:n=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,n):t.set(n,n),n}async*parseStreamResponse(e){let t="",n=new Map,r=0,i=null,o=null,a=false,l=false,c,u=p=>{let m={...p};return l||(m.role="assistant",l=true),{id:c,choices:[{index:0,delta:m}]}};for await(let p of e){t+=p.toString();let m=t.split(`
1505
+ `);t=m.pop()||"";for(let h of m){let g=h.trim();if(!g||!g.startsWith("data: "))continue;let y=g.slice(6);if(y==="[DONE]"){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream] Received [DONE]");continue}let x;try{x=JSON.parse(y);}catch{process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream] Invalid JSON:",y);continue}switch(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream Event]",x.type,JSON.stringify(x,null,2).slice(0,200)),x.type){case "response.created":case "response.in_progress":x.response?.id&&(c=x.response.id);break;case "response.output_text.delta":{let S=typeof x.delta=="string"?x.delta:"";if(!S)break;a=true,yield u({content:S});break}case "response.reasoning_summary_text.delta":{let S=typeof x.delta=="string"?x.delta:"";if(!S)break;a=true,yield u({reasoning_content:S});break}case "response.reasoning_summary_part.added":case "response.reasoning_summary_part.done":break;case "response.output_item.added":{if(x.item?.type==="function_call"){let S=x.item,T=S.id||`item_${x.output_index}`,w={id:S.call_id||S.id||`call_${Date.now()}_${r}`,name:S.name,index:r++,arguments:""};n.set(T,w),a=true,yield u({tool_calls:[{index:w.index,id:w.id,type:"function",function:{name:w.name}}]});}else if(x.item?.type==="reasoning"){let S=x.item;if(S.summary?.length>0){let T=S.summary.map(w=>w.text).join(`
1506
+ `);T&&(yield u({reasoning_content:T}));}}break}case "response.function_call_arguments.delta":{let S=x.item_id?n.get(x.item_id):void 0;if(!S)break;let T=typeof x.delta=="string"?x.delta:"";if(!T)break;S.arguments+=T,a=true,yield u({tool_calls:[{index:S.index,id:S.id,type:"function",function:{name:S.name,arguments:T}}]});break}case "response.completed":{i=x.response||null,o=x.response?.usage||null,x.response?.id&&(c=x.response.id,this.lastResponseId=c);break}case "response.error":case "response.failed":{let S=x.error?.message||x.error?.code||"Doubao stream failed";throw new Error(S)}}}}if(!a&&i){let p=Array.isArray(i.output)?i.output:[],m="",h="";for(let g of p)if(g?.type==="message"&&Array.isArray(g.content))for(let y of g.content)y?.type==="output_text"&&typeof y.text=="string"&&(m+=y.text);else if(g?.type==="reasoning"){let y=g;y.summary?.length>0&&(h=y.summary.map(x=>x.text).join(`
1507
+ `));}(m||h)&&(yield {id:c,choices:[{index:0,delta:{role:"assistant",content:m||void 0,reasoning_content:h||void 0}}]});}let d={id:c,choices:[{index:0,delta:{},finish_reason:n.size>0?"tool_calls":"stop"}]};o&&(d.usage=this.normalizeUsage(o)),yield d;}normalizeUsage(e){let t={prompt_tokens:e.input_tokens||0,completion_tokens:e.output_tokens||0,total_tokens:e.total_tokens||0};return e.input_tokens_details?.cached_tokens!==void 0&&(t.cached_tokens=e.input_tokens_details.cached_tokens,t.prompt_tokens_details={cached_tokens:e.input_tokens_details.cached_tokens}),e.output_tokens_details?.reasoning_tokens!==void 0&&(t.completion_tokens_details={reasoning_tokens:e.output_tokens_details.reasoning_tokens}),t}};var Zi=class{client;apiKey;baseURL;userId;retryConfig;constructor(e,t="https://generativelanguage.googleapis.com",n){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.userId=randomUUID(),this.retryConfig=dn(Wn("gemini"),n),this.client=qb.create({baseURL:this.baseURL,timeout:6e5,headers:{"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${ti__default.platform()}; ${ti__default.arch()})`,"x-goog-api-client":"google-genai-sdk/1.30.0 gl-node/v22.16.0","x-gemini-api-privileged-user-id":this.userId}});}convertMessages(e){let t=[],n=[];for(let i of e)if(i.role==="system"){let o=me(i.content);o&&t.push(o);}else if(i.role==="user"){let o=[];if(typeof i.content=="string")o.push({text:i.content});else if(Array.isArray(i.content)){for(let a of i.content)if(a.type==="text")o.push({text:a.text});else if(a.type==="image_url"){let l=a.image_url.url;if(l.startsWith("data:")){let c=l.match(/^data:([^;]+);base64,(.+)$/);c&&o.push({inlineData:{mimeType:c[1],data:c[2]}});}}}n.push({parts:o,role:"user"});}else if(i.role==="assistant"){let o=[],a=me(i.content);if(a&&o.push({text:a}),i.tool_calls)for(let l of i.tool_calls)o.push({functionCall:{name:l.function.name,args:JSON.parse(l.function.arguments)}});n.push({parts:o,role:"model"});}else if(i.role==="tool"){let o=me(i.content)||"";n.push({parts:[{functionResponse:{name:i.name||"unknown",response:{name:i.name||"unknown",content:o}}}],role:"user"});}let r={contents:n};return t.length>0&&(r.systemInstruction={parts:t.map(i=>({text:i})),role:"user"}),r}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(n=>({name:n.name,description:n.description,parametersJsonSchema:{type:n.parameters.type,properties:n.parameters.properties,required:n.parameters.required,additionalProperties:n.parameters.additionalProperties}}))}]}buildGenerationConfig(e,t){let n={temperature:e??1,topP:.95,topK:64};return t&&(n.responseMimeType="application/json",n.responseSchema=t.schema),n}parseSSELine(e){let t=e.trim();if(!t||(t.startsWith("data: ")&&(t=t.slice(6).trim()),t==="[DONE]")||!t.startsWith("{"))return null;try{return JSON.parse(t)}catch{return null}}convertResponse(e,t){let n=e.candidates[0];if(!n)throw new Error("No candidate in Gemini response");let r=n.content.parts,i=null,o=[];for(let l of r)l.text?i=(i||"")+l.text:l.functionCall&&o.push({id:`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:l.functionCall.name,arguments:JSON.stringify(l.functionCall.args)}});let a=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};return {id:t,choices:[{message:{role:"assistant",content:i,tool_calls:o.length>0?o:void 0},finish_reason:n.finishReason||"stop"}],usage:{prompt_tokens:a.promptTokenCount,completion_tokens:a.candidatesTokenCount,total_tokens:a.totalTokenCount,cached_tokens:a.cachedContentTokenCount}}}async makeRequest(e,t){let n,r=0;for(;r<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(i){n=i,r++;let o=mt(i),a=Jt(i.response?.headers?.["retry-after"]);if(!o.retryable||r>this.retryConfig.requestMaxRetries)break;let l=pn(a,r,this.retryConfig);await ft(l);}throw n}async chat(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:i}=this.convertMessages(e),o=this.convertTools(t.tools||[]),a=this.buildGenerationConfig(t.temperature,t.structuredOutput),l={contents:r,systemInstruction:i,generationConfig:a};o.length>0&&(l.tools=o);let c=`gemini-${Date.now()}`;return this.makeRequest(async()=>{let u=await this.client.post(`/v1beta/models/${n}:generateContent`,l,{params:{key:this.apiKey},signal:t.signal});return this.convertResponse(u.data,c)},"chat")}async*chatStreamed(e,t){let n=t.model||"gemini-2.5-flash",{contents:r,systemInstruction:i}=this.convertMessages(e),o=this.convertTools(t.tools||[]),a=this.buildGenerationConfig(t.temperature,t.structuredOutput),l={contents:r,systemInstruction:i,generationConfig:a};o.length>0&&(l.tools=o);let c=`gemini-${Date.now()}`,u=`/v1beta/models/${n}:streamGenerateContent`,d=`${this.baseURL}${u}`;process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1508
+ [Gemini Stream Request]`),console.log(`URL: ${d}`),console.log(`Model: ${n}`),console.log(`Tools: ${o.length>0?o[0].functionDeclarations.length:0}`),console.log(`Contents: ${r.length} messages`));let p=Date.now(),m=await this.makeRequest(async()=>await this.client.post(u,l,{params:{key:this.apiKey,alt:"sse"},responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}}),"chatStreamed");process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1509
+ [Gemini Stream Started]`),console.log(`Status: ${m.status}`)),yield*this.streamGenerator(m.data,c,p);}async*streamGenerator(e,t,n){let r="",i="",o=[],a;try{for await(let l of e){let c=l.toString();r+=c,process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Gemini] Raw chunk (${c.length} bytes): ${c.slice(0,200)}...`);let u=r.split(`
1510
+ `);r=u.pop()||"";for(let d of u){let p=d.trim();if(!p||p==="data: [DONE]")continue;let m=this.parseSSELine(p);if(!m){process.env.CLI_DEBUG_CONSOLE==="1"&&p.length>0&&console.log(`[Gemini] Failed to parse line: ${p.slice(0,100)}...`);continue}let h=m.candidates?.[0];if(!h){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Gemini] No candidate in response: ${JSON.stringify(m).slice(0,200)}`);continue}if(!h.content?.parts){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Gemini] No parts in candidate: ${JSON.stringify(h).slice(0,200)}`);continue}m.usageMetadata&&(a=m.usageMetadata);for(let g of h.content.parts){if(g.thought&&g.text){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Gemini] Yielding reasoning: ${g.text.slice(0,50)}...`),yield {choices:[{index:0,delta:{reasoning_content:g.text}}]};continue}if(g.text)i+=g.text,process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Gemini] Yielding content: ${g.text.slice(0,100)}...`),yield {choices:[{index:0,delta:{content:g.text}}]};else if(g.functionCall){let y={id:`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:g.functionCall.name,arguments:JSON.stringify(g.functionCall.args)}};o.push(y),yield {choices:[{index:0,delta:{tool_calls:[{index:o.length-1,id:y.id,type:"function",function:{name:y.function.name,arguments:y.function.arguments}}]}}]};}}if(h.finishReason){let g=a||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG_CONSOLE==="1"){let y=n?Date.now()-n:0;console.log(`
1511
+ [Gemini Stream Complete]`),console.log(`Duration: ${y}ms`),console.log(`Finish Reason: ${h.finishReason}`),console.log(`Tool Calls: ${o.length}`),console.log(`Usage: prompt=${g.promptTokenCount}, completion=${g.candidatesTokenCount}, total=${g.totalTokenCount}`);}yield {id:t,choices:[{index:0,delta:{},finish_reason:h.finishReason==="STOP"?"stop":h.finishReason.toLowerCase()}],usage:{prompt_tokens:g.promptTokenCount,completion_tokens:g.candidatesTokenCount,total_tokens:g.totalTokenCount,cached_tokens:g.cachedContentTokenCount}};}}}}catch(l){if(process.env.CLI_DEBUG_CONSOLE==="1"){let c=n?Date.now()-n:0;console.log(`
1512
+ [Gemini Stream Error]`),console.log(`Duration: ${c}ms`),console.log(`Error: ${l.message||l}`),l.response?.data&&console.log(`Response: ${JSON.stringify(l.response.data)}`);}throw l}}};Hi();le();var ov=60*1e3;function wl(s){if(!s)return 0;let e=0;for(let t of s){let n=t.codePointAt(0)||0;n>=19968&&n<=40959||n>=12288&&n<=12351||n>=65280&&n<=65519||n>=44032&&n<=55215?e+=.67:e+=.25;}return Math.ceil(e)}var ds=class{messages=[];maxMessages;constructor(e=500){this.maxMessages=e;}add(e){let t=typeof e.content=="string"?e.content:JSON.stringify(e.content),n=wl(t),r={...e,_timestamp:Date.now(),_estimatedTokens:n};if(this.messages.push(r),this.messages.length>this.maxMessages){let i=this.messages.filter(l=>l.role==="system"),a=this.messages.filter(l=>l.role!=="system").slice(-(this.maxMessages-i.length));this.messages=[...i,...a];}}addToolResult(e,t,n){let r=yl(t),i=null;try{let c=JSON.parse(n);c.type&&c.status&&c.summary&&(i=c);}catch{}let o,a=r;f.info("MEMORY","addToolResult: parsedResult\uFF1A"+i),f.info("MEMORY","addToolResult: effectiveResultType\uFF1A"+a),i?(a=i.type||r,o=tp(i),f.info("MEMORY","\u7CBE\u7B80\u7ED3\u679C: content \uFF1A"+o),f.info("MEMORY",`addToolResult: ${t} parsed as ToolResult`,{parsedResult:JSON.stringify(i).substring(0,500),contentAfter:o.substring(0,500),rawLength:n.length,contentLength:o.length})):(o=n,f.debug("MEMORY",`addToolResult: ${t} using raw output`,{rawOutput:n.substring(0,500),rawLength:n.length}));let l={role:"tool",tool_call_id:e,name:t,content:o,_resultType:a,_toolName:t,_timestamp:Date.now(),_estimatedTokens:wl(o)};if(this.messages.push(l),this.messages.length>this.maxMessages){let c=this.messages.filter(p=>p.role==="system"),d=this.messages.filter(p=>p.role!=="system").slice(-(this.maxMessages-c.length));this.messages=[...c,...d];}}stripMetadata(e){let{_resultType:t,_toolName:n,_timestamp:r,_estimatedTokens:i,...o}=e;return o}getAll(){return this.messages.map(e=>this.stripMetadata(e))}getRawMessages(){return this.messages}getMessagesForLLM(){let e=Date.now();return this.messages.filter(t=>t.role!=="tool"?true:t._resultType==="ephemeral"?e-(t._timestamp||0)<ov:true).map(t=>this.stripMetadata(t))}cleanupEphemeral(){let e=this.messages.length;return this.messages=this.messages.filter(t=>t._resultType!=="ephemeral"),e-this.messages.length}getStats(){let e={total:this.messages.length,ephemeral:0,contextual:0,summarized:0,other:0};for(let t of this.messages)t._resultType==="ephemeral"?e.ephemeral++:t._resultType==="contextual"?e.contextual++:t._resultType==="summarized"?e.summarized++:e.other++;return e}checkContextHealth(){let e={ephemeral:{count:0,tokens:0},contextual:{count:0,tokens:0},summarized:{count:0,tokens:0},other:{count:0,tokens:0}},t=0,n=0,r=0;for(let a of this.messages){let l=a._estimatedTokens||wl(typeof a.content=="string"?a.content:JSON.stringify(a.content));t+=l,a.role==="tool"?(r++,n+=l,a._resultType==="ephemeral"?(e.ephemeral.count++,e.ephemeral.tokens+=l):a._resultType==="contextual"?(e.contextual.count++,e.contextual.tokens+=l):a._resultType==="summarized"?(e.summarized.count++,e.summarized.tokens+=l):(e.other.count++,e.other.tokens+=l)):(e.other.count++,e.other.tokens+=l);}let i=t>0?n/t:0,o=[];return i>.5?o.push(`Tool results\u5360\u7528 ${(i*100).toFixed(1)}% \u7684\u4E0A\u4E0B\u6587\uFF08\u8D85\u8FC750%\u8B66\u6212\u7EBF\uFF09`):i>.4&&o.push(`Tool results\u5360\u7528 ${(i*100).toFixed(1)}% \u7684\u4E0A\u4E0B\u6587\uFF08\u63A5\u8FD1\u8B66\u6212\u7EBF\uFF09`),t>18e4?o.push(`\u4E0A\u4E0B\u6587\u5DF2\u8FBE ${t} tokens\uFF08\u8D85\u8FC7180k\uFF0C\u5EFA\u8BAE\u6E05\u7406\uFF09`):t>15e4&&o.push(`\u4E0A\u4E0B\u6587\u5DF2\u8FBE ${t} tokens\uFF08\u63A5\u8FD1180k\uFF09`),r>100?o.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8FC7\u957F\uFF08${r} \u6761\uFF09`):r>60&&o.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8F83\u957F\uFF08${r} \u6761\uFF09`),e.ephemeral.count>10&&o.push(`\u79EF\u7D2F\u4E86 ${e.ephemeral.count} \u6761 ephemeral \u6D88\u606F\uFF0C\u5EFA\u8BAE\u6E05\u7406`),{totalTokens:t,toolResultTokens:n,toolResultRatio:i,messageCount:this.messages.length,toolMessageCount:r,warnings:o,shouldCompress:i>.3||t>12e4,shouldCleanup:t>15e4||e.ephemeral.count>5,byType:e}}getTokenSummary(){let e=this.checkContextHealth(),t=[`Total: ${e.totalTokens} tokens`,`Tool: ${e.toolResultTokens} (${(e.toolResultRatio*100).toFixed(1)}%)`,`Messages: ${e.messageCount}`];return e.byType.ephemeral.count>0&&t.push(`Ephemeral: ${e.byType.ephemeral.count}`),t.join(" | ")}getMemoryFootprint(){let e=JSON.stringify(this.messages),t=new Blob([e]).size,n=Math.round(t/1024*10)/10,r=this.messages.length*150,i=t+r,o=Math.round(i/1024*10)/10;return {totalKB:o,messagesKB:n,messageCount:this.messages.length,averageKBPerMessage:this.messages.length>0?Math.round(o/this.messages.length*10)/10:0}}logMemoryStats(){let e=this.checkContextHealth(),t=this.getMemoryFootprint();f.info("MEMORY_STATS","ShortTermMemory snapshot",{memoryTotalKB:t.totalKB,memoryMessagesKB:t.messagesKB,avgKBPerMessage:t.averageKBPerMessage,totalTokens:e.totalTokens,toolResultTokens:e.toolResultTokens,toolResultRatio:`${(e.toolResultRatio*100).toFixed(1)}%`,messageCount:e.messageCount,toolMessageCount:e.toolMessageCount,maxMessages:this.maxMessages,byType:{ephemeral:`${e.byType.ephemeral.count} msgs, ${e.byType.ephemeral.tokens} tokens`,contextual:`${e.byType.contextual.count} msgs, ${e.byType.contextual.tokens} tokens`,summarized:`${e.byType.summarized.count} msgs, ${e.byType.summarized.tokens} tokens`,other:`${e.byType.other.count} msgs, ${e.byType.other.tokens} tokens`},warnings:e.warnings.length>0?e.warnings:["None"],shouldCompress:e.shouldCompress,shouldCleanup:e.shouldCleanup});}clear(){let e=this.messages.filter(t=>t.role==="system");this.messages=e;}setMessages(e){let t=Array.isArray(e)?e:[],n=t.filter(a=>a.role==="system"),r=t.filter(a=>a.role!=="system"),i=Math.max(0,this.maxMessages-n.length),o=i>0?r.slice(-i):[];this.messages=[...n,...o].map(a=>({...a,_timestamp:Date.now()}));}get length(){return this.messages.length}};ac();mo();var yo=class{currentStatus="";statusBrightness=50;brightnessDirection=1;animationInterval=null;toolHistory=[];fileOperations=[];statusLine=0;isDark;isActive=false;spinnerFrame=0;spinnerChars=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];currentType="thinking";constructor(e){this.isDark=e.isDarkBackground;}start(){this.isActive=true,this.clear(),this.renderStatusBar(),this.startAnimation();}stop(){this.isActive=false,this.stopAnimation();}updateStatus(e,t="thinking"){this.isActive&&(this.currentStatus=e,this.currentType=t,t==="thinking"||t==="tool_call"||t==="compacting"||t==="info"?this.startAnimation():this.stopAnimation(),this.renderStatusBar());}addToolCall(e){this.toolHistory.push(e);}addFileOperation(e){this.fileOperations.push(e);}updateToolResult(e,t,n){let r=this.toolHistory[this.toolHistory.length-1];r&&r.name===e&&(r.result=t,r.duration=n);}updateToolError(e,t){let n=this.toolHistory[this.toolHistory.length-1];n&&n.name===e&&(n.error=t);}clear(){console.clear(),this.toolHistory=[],this.fileOperations=[],this.statusLine=0;}startAnimation(){this.animationInterval||(this.animationInterval=setInterval(()=>{this.isActive&&(this.spinnerFrame=(this.spinnerFrame+1)%this.spinnerChars.length,this.statusBrightness+=this.brightnessDirection*8,this.statusBrightness>=100?(this.statusBrightness=100,this.brightnessDirection=-1):this.statusBrightness<=40&&(this.statusBrightness=40,this.brightnessDirection=1),this.renderStatusBar());},80));}stopAnimation(){this.animationInterval&&(clearInterval(this.animationInterval),this.animationInterval=null);}renderStatusBar(){if(!this.isActive)return;process.stdout.write("\x1B[H\x1B[2J");let e="";j.blue;switch(this.currentType){case "thinking":e=this.spinnerChars[this.spinnerFrame],j.cyan;break;case "tool_call":e=this.spinnerChars[this.spinnerFrame],j.yellow;break;case "tool_result":e="\u2713",j.green;break;case "complete":e="\u2728",j.green;break;case "error":e="[x]",j.red;break}let n=Math.floor(this.statusBrightness),r=`${e} ${this.currentStatus}`,i=this.applyBrightness(r,n,this.currentType),o="\u2550".repeat(process.stdout.columns||80);console.log(j.dim(o)),console.log(i),console.log(j.dim(o)),this.renderToolHistory(),this.renderFileOperations();}applyBrightness(e,t,n){let r=Math.floor(t/100*255),i=0,o=0,a=0;switch(n){case "thinking":i=Math.floor(r*.2),o=Math.floor(r*.9),a=r;break;case "tool_call":i=r,o=Math.floor(r*.9),a=Math.floor(r*.2);break;case "tool_result":i=0,o=r,a=0;break;case "complete":i=0,o=r,a=Math.floor(r*.5);break;case "error":i=r,o=0,a=0;break;default:i=0,o=Math.floor(r*.5),a=r;}return `\x1B[38;2;${i};${o};${a}m${e}\x1B[0m`}renderToolHistory(){if(!this.isActive||this.toolHistory.length===0)return;console.log(`
1513
+ `+j.bold("Tool Calls:"));let e=this.toolHistory.slice(-5);for(let t of e){let n=this.formatTime(t.timestamp),r=t.duration?j.dim(` (${t.duration}ms)`):"";if(t.error)console.log(j.red(` \u2717 ${n} ${t.name}${r}`)),console.log(j.red(` Error: ${t.error}`));else if(t.result){let i=this.truncate(t.result,60);console.log(j.green(` \u2713 ${n} ${t.name}${r}`)),console.log(j.dim(` \u2192 ${i}`));}else console.log(j.yellow(` \u22EF ${n} ${t.name}...`));}}renderFileOperations(){if(!this.isActive||this.fileOperations.length===0)return;console.log(`
1514
+ `+j.bold("File Operations:"));let e=this.fileOperations.slice(-5);for(let t of e){let n=t.size?j.dim(` (${this.formatSize(t.size)})`):"",r=t.lines?j.dim(` (${t.lines} lines)`):"";switch(t.type){case "read":console.log(j.blue(` [r] Read: ${t.path}${r}${n}`));break;case "write":console.log(j.green(` [w] Write: ${t.path}${r}${n}`));break;case "search":console.log(j.cyan(` [?] Search: ${t.path}`));break}}}formatTime(e){let t=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0"),r=e.getSeconds().toString().padStart(2,"0");return j.dim(`${t}:${n}:${r}`)}formatSize(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}displaySummary(e,t,n,r){if(this.stop(),console.log(`
1515
+ `+j.dim("\u2500".repeat(process.stdout.columns||80))),console.log(j.bold("Summary:")),console.log(j.dim(` \u2022 Iterations: ${e}`)),console.log(j.dim(` \u2022 Tool Calls: ${t}`)),console.log(j.dim(` \u2022 Tokens Used: ${n}`)),console.log(j.dim(` \u2022 Duration: ${(r/1e3).toFixed(2)}s`)),this.fileOperations.length>0){let i=this.fileOperations.filter(l=>l.type==="read").length,o=this.fileOperations.filter(l=>l.type==="write").length,a=this.fileOperations.filter(l=>l.type==="search").length;console.log(j.dim(` \u2022 Files Read: ${i}`)),console.log(j.dim(` \u2022 Files Written: ${o}`)),console.log(j.dim(` \u2022 Searches: ${a}`));}console.log(j.dim("\u2500".repeat(process.stdout.columns||80)));}};function jx(){let s=process.env.TERM||"",e=process.env.TERM_PROGRAM||"",t=process.env.COLORTERM||"",n={termType:s,termProgram:e,supportsCursorSaveRestore:true,supportsScrollRegion:true,supportsAlternateScreen:true,supportsTrueColor:t==="truecolor"||s.includes("256color"),needsExtraFlush:false,hasScrollRegionBug:false,hasCursorRestoreBug:false,minRenderInterval:16};return e==="Termius"&&(n.hasScrollRegionBug=true,n.hasCursorRestoreBug=true,n.needsExtraFlush=true,n.minRenderInterval=50),e==="Apple_Terminal"&&(n.minRenderInterval=33,n.needsExtraFlush=true),e==="iTerm.app"&&(n.minRenderInterval=16),(s.startsWith("screen")||s.startsWith("tmux"))&&(n.supportsCursorSaveRestore=false,n.minRenderInterval=33),e==="Alacritty"&&(n.minRenderInterval=16),e==="vscode"&&(n.minRenderInterval=33,n.supportsCursorSaveRestore=false),n}var lc=null;function Mm(){return lc||(lc=jx()),lc}var Pr=class s{stdout;writeBuffer=[];flushScheduled=false;flushImmediate=null;disabled=false;onError=null;termCaps;static ESC="\x1B";static CSI="\x1B[";static CURSOR_HIDE="\x1B[?25l";static CURSOR_SHOW="\x1B[?25h";static CURSOR_HOME="\x1B[H";static CURSOR_SAVE="\x1B7";static CURSOR_RESTORE="\x1B8";static ERASE_LINE_END="\x1B[K";static ERASE_LINE_START="\x1B[1K";static ERASE_LINE_FULL="\x1B[2K";static SCROLL_RESET="\x1B[r";static ALT_SCREEN_ON="\x1B[?1049h";static ALT_SCREEN_OFF="\x1B[?1049l";constructor(e=process.stdout){this.stdout=e,this.termCaps=Mm();}setErrorHandler(e){this.onError=e;}static cursorTo(e,t){return `\x1B[${e};${t}H`}static cursorUp(e){return e>0?`\x1B[${e}A`:""}static cursorDown(e){return e>0?`\x1B[${e}B`:""}static cursorForward(e){return e>0?`\x1B[${e}C`:""}static cursorBack(e){return e>0?`\x1B[${e}D`:""}static setScrollRegion(e,t){return `\x1B[${e};${t}r`}static scrollUp(e=1){return `\x1B[${e}S`}static scrollDown(e=1){return `\x1B[${e}T`}moveTo(e,t){return this.buffer(`\x1B[${e};${t}H`),this}moveToRow(e){return this.buffer(`\x1B[${e};1H`),this}moveToCol(e){return this.buffer(`\x1B[${e}G`),this}moveUp(e=1){return e>0&&this.buffer(`\x1B[${e}A`),this}moveDown(e=1){return e>0&&this.buffer(`\x1B[${e}B`),this}moveForward(e=1){return e>0&&this.buffer(`\x1B[${e}C`),this}moveBack(e=1){return e>0&&this.buffer(`\x1B[${e}D`),this}writeLine(e,t){return this.moveTo(e,1),this.buffer(t),this.buffer(s.ERASE_LINE_END),this}writeAt(e,t,n){return this.moveTo(e,t),this.buffer(n),this}append(e){return this.buffer(e),this}raw(e){return this.buffer(e),this}clearLine(e){return this.moveTo(e,1),this.buffer(s.ERASE_LINE_FULL),this}eraseToEndOfLine(){return this.buffer(s.ERASE_LINE_END),this}clearLines(e,t){for(let n=0;n<t;n++)this.clearLine(e+n);return this}setScrollRegion(e,t){return this.termCaps.supportsScrollRegion&&!this.termCaps.hasScrollRegionBug&&this.buffer(`\x1B[${e};${t}r`),this}resetScrollRegion(){return this.termCaps.supportsScrollRegion&&!this.termCaps.hasScrollRegionBug&&this.buffer(s.SCROLL_RESET),this}scrollUp(e=1){return this.buffer(`\x1B[${e}S`),this}scrollDown(e=1){return this.buffer(`\x1B[${e}T`),this}hideCursor(){return this.buffer(s.CURSOR_HIDE),this}showCursor(){return this.buffer(s.CURSOR_SHOW),this}saveCursor(){return this.termCaps.supportsCursorSaveRestore&&!this.termCaps.hasCursorRestoreBug?this.buffer(s.CURSOR_SAVE):this.buffer("\x1B[s"),this}restoreCursor(){return this.termCaps.supportsCursorSaveRestore&&!this.termCaps.hasCursorRestoreBug?this.buffer(s.CURSOR_RESTORE):this.buffer("\x1B[u"),this}buffer(e){this.writeBuffer.push(e),this.scheduleFlush();}scheduleFlush(){this.flushScheduled||(this.flushScheduled=true,this.flushImmediate=setImmediate(()=>this.flush()));}flush(){if(this.writeBuffer.length===0||this.disabled)return this;let e=this.writeBuffer.join("");this.writeBuffer=[],this.flushScheduled=false,this.flushImmediate&&(clearImmediate(this.flushImmediate),this.flushImmediate=null);try{this.stdout.write(e),this.termCaps.needsExtraFlush&&e.includes("\x1B[")&&typeof this.stdout.uncork=="function"&&(this.stdout.cork(),this.stdout.uncork());}catch(t){this.disabled=true,this.onError&&this.onError(t);}return this}flushSync(){if(this.writeBuffer.length===0||this.disabled)return this;let e=this.writeBuffer.join("");this.writeBuffer=[],this.flushScheduled=false,this.flushImmediate&&(clearImmediate(this.flushImmediate),this.flushImmediate=null);try{this.stdout.write(e);}catch(t){this.disabled=true,this.onError&&this.onError(t);}return this}getPendingSize(){return this.writeBuffer.reduce((e,t)=>e+t.length,0)}clearBuffer(){return this.writeBuffer=[],this.flushScheduled=false,this.flushImmediate&&(clearImmediate(this.flushImmediate),this.flushImmediate=null),this}get rows(){return this.stdout.rows||24}get cols(){return this.stdout.columns||80}get isTTY(){return this.stdout.isTTY||false}};var Ar=class{lines=[];prevLines=[];dirtyRows=new Set;_width;_height;constructor(e,t){this._width=e,this._height=t,this.lines=new Array(t).fill(""),this.prevLines=new Array(t).fill("");}get width(){return this._width}get height(){return this._height}setLine(e,t){if(e<0||e>=this._height)return;let n=this.truncateToWidth(t);this.lines[e]!==n&&(this.lines[e]=n,this.dirtyRows.add(e));}getLine(e){return e<0||e>=this._height?"":this.lines[e]||""}appendToLine(e,t){if(e<0||e>=this._height)return;let n=this.lines[e]||"";this.lines[e]=this.truncateToWidth(n+t),this.dirtyRows.add(e);}clearRow(e){e<0||e>=this._height||this.lines[e]!==""&&(this.lines[e]="",this.dirtyRows.add(e));}shiftUp(e=1,t=0,n){let r=n??this._height-1;for(let i=t;i<=r;i++)i+e<=r?this.lines[i]=this.lines[i+e]:this.lines[i]="",this.dirtyRows.add(i);}getDiff(){let e=[];for(let t of this.dirtyRows){if(t>=this._height)continue;let n=this.lines[t]||"",r=this.prevLines[t]||"";if(n!==r)if(n==="")e.push({type:"clear",row:t+1});else if(r===""||n.length<r.length*.5)e.push({type:"write",row:t+1,content:n});else {let i=0,o=Math.min(r.length,n.length);for(;i<o;){if(r[i]==="\x1B"||n[i]==="\x1B"){e.push({type:"write",row:t+1,content:n});break}if(r[i]!==n[i])break;i++;}(i<o||n.length!==r.length)&&(i===0||r[0]==="\x1B"||n[0]==="\x1B"?e.push({type:"write",row:t+1,content:n}):i<n.length&&e.push({type:"write-partial",row:t+1,col:i+1,content:n.slice(i)}));}}return e}commit(){for(let e of this.dirtyRows)e<this._height&&(this.prevLines[e]=this.lines[e]);this.dirtyRows.clear();}markAllDirty(){for(let e=0;e<this._height;e++)this.dirtyRows.add(e);}markRangeDirty(e,t){for(let n=e;n<=t&&n<this._height;n++)this.dirtyRows.add(n);}hasDirtyRows(){return this.dirtyRows.size>0}getDirtyCount(){return this.dirtyRows.size}resize(e,t){let n=this._height;if(this._width=e,this._height=t,t>n)for(let r=n;r<t;r++)this.lines.push(""),this.prevLines.push("");else t<n&&(this.lines.length=t,this.prevLines.length=t);for(let r=0;r<t;r++){let i=this.truncateToWidth(this.lines[r]);i!==this.lines[r]&&(this.lines[r]=i,this.dirtyRows.add(r));}this.markAllDirty();}clear(){for(let e=0;e<this._height;e++)this.lines[e]!==""&&(this.lines[e]="",this.dirtyRows.add(e));}getRawLines(){return [...this.lines]}truncateToWidth(e){if(!e)return "";if(this.getVisibleLength(e)<=this._width)return e;let n=0,r="",i=false,o="";for(let a=0;a<e.length;a++){let l=e[a];if(l==="\x1B"){i=true,o=l;continue}if(i){o+=l,/[A-Za-z]/.test(l)&&(i=false,r+=o,o="");continue}if(n>=this._width-1){r+="\u2026",r+="\x1B[0m";break}r+=l,n++;}return r}getVisibleLength(e){return e?e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").length:0}static stripAnsi(e){return e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"")}};var Mr=class s{static HEADER_HEIGHT=10;static STATUS_HEIGHT=2;static INPUT_HEIGHT=3;static MIN_ROWS=15;static MIN_COLS=60;layout;listeners=new Map;resizeHandler=null;menuHeight=0;inputHeight=s.INPUT_HEIGHT;constructor(){this.layout=this.calculate();}setMenuHeight(e){this.menuHeight!==e&&(this.menuHeight=Math.max(0,e),this.layout=this.calculate(),this.emit("resize",this.layout));}setInputHeight(e){let t=process.stdout.rows||s.MIN_ROWS,n=Math.max(s.INPUT_HEIGHT,t-s.STATUS_HEIGHT-this.menuHeight-1),r=Math.min(Math.max(s.INPUT_HEIGHT,e),n);return r!==this.inputHeight?(this.inputHeight=r,this.layout=this.calculate(),this.emit("resize",this.layout),true):false}getMenuHeight(){return this.menuHeight}startResizeListener(){this.resizeHandler||(this.resizeHandler=()=>{let e=this.calculate();(e.totalRows!==this.layout.totalRows||e.totalCols!==this.layout.totalCols)&&(this.layout=e,this.emit("resize",this.layout));},process.stdout.on("resize",this.resizeHandler));}stopResizeListener(){this.resizeHandler&&(process.stdout.off("resize",this.resizeHandler),this.resizeHandler=null);}calculate(){let e=process.stdout.rows||24,t=process.stdout.columns||80,n=Math.max(e,s.MIN_ROWS),r=Math.max(t,s.MIN_COLS),i=s.HEADER_HEIGHT,o=s.STATUS_HEIGHT,a=this.inputHeight,l=o+a+this.menuHeight,c=n-l,u=n-l+1,d=u+o-1,p=d+1,m=p+a-1;return {header:{startRow:1,endRow:i,height:i},timeline:{startRow:1,endRow:n-l,height:c},statusBar:{startRow:u,endRow:d,height:o},inputBox:{startRow:p,endRow:m,height:a},totalRows:n,totalCols:r,bottomFixedHeight:l}}getLayout(){return this.layout}recalculate(){return this.layout=this.calculate(),this.layout}getHeader(){return this.layout.header}getTimeline(){return this.layout.timeline}getStatusBar(){return this.layout.statusBar}getInputBox(){return this.layout.inputBox}getCols(){return this.layout.totalCols}getRows(){return this.layout.totalRows}getBottomFixedHeight(){return this.layout.bottomFixedHeight}isTooSmall(){let e=process.stdout.rows||24,t=process.stdout.columns||80;return e<s.MIN_ROWS||t<s.MIN_COLS}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let n=this.listeners.get(e);if(n){let r=n.indexOf(t);r>=0&&n.splice(r,1);}}emit(e,t){let n=this.listeners.get(e)||[];for(let r of n)try{r(t);}catch{}}destroy(){this.stopResizeListener(),this.listeners.clear();}};le();var Dr=class s{rawModeEnabled=false;started=false;paused=false;keypressEventsEnabled=false;listeners=new Map;keypressHandler=null;dataHandler=null;readableHandler=null;stdinErrorHandler=null;stdinCloseHandler=null;boundStdin=null;healthCheckInterval=null;static HEALTH_CHECK_INTERVAL=1e3;static EVENT_LOOP_DELAY_THRESHOLD=1e4;static EVENT_LOOP_RECOVERY_COOLDOWN=3e4;recoveryAttempts=0;static MAX_RECOVERY_ATTEMPTS=5;rawGuardInterval=null;static RAW_GUARD_INTERVAL=2e3;static RAW_GUARD_ENABLED=process.env.NEOX_RAW_GUARD_DISABLED!=="1";lastInputActivity=Date.now();inputActivityInterval=null;lastIdleRecoveryAt=0;static DEFAULT_INPUT_IDLE_THRESHOLD=3e4;static INPUT_ACTIVITY_CHECK_INTERVAL=2e3;static INPUT_IDLE_RECOVERY_COOLDOWN=5e3;static INPUT_IDLE_THRESHOLD=Number.isFinite(Number(process.env.NEOX_INPUT_IDLE_MS))?Number(process.env.NEOX_INPUT_IDLE_MS):s.DEFAULT_INPUT_IDLE_THRESHOLD;static INPUT_ACTIVITY_GUARD_ENABLED=process.env.NEOX_INPUT_GUARD_DISABLED!=="1";static IDLE_STAGE_DISABLED=3;idleConfigProvider=null;idleRecoveryStage=0;onIdleRecoveryFailed=null;idleGuardWasEnabled=true;usingFallbackStdin=false;ttyUnavailable=false;lastHealthCheckAt=Date.now();lastEventLoopRecoveryAt=0;lastInterruptAt=0;static INTERRUPT_DEBOUNCE_MS=50;lastSubmitAt=0;onFatalError=null;escBuffer="";escTimeout=null;static ESC_TIMEOUT=20;inBracketedPaste=false;pasteBuffer="";pasteAbortTimeout=null;static PASTE_START="\x1B[200~";static PASTE_END="\x1B[201~";static PASTE_ABORT_TIMEOUT=5e3;suppressKeypressUntil=0;static PASTE_SUPPRESS_DURATION=800;rapidInputBuffer="";rapidInputTimeout=null;lastInputTime=0;static RAPID_INPUT_THRESHOLD=50;static RAPID_INPUT_FLUSH_DELAY=100;start(){if(!this.started){if(!process.stdin.isTTY){f.error("INPUT","Not a TTY, input handling disabled");return}this.initializeStdin(),this.started=true,this.startHealthCheck(),this.startRawGuard(),this.startInputActivityCheck(),process.on("SIGHUP",()=>{this.started&&(f.warn("INPUT","Received SIGHUP (terminal disconnected), will attempt to reconnect..."),setTimeout(()=>{if(this.started){f.info("INPUT","Attempting to reconnect TTY after SIGHUP...");try{this.forceReinitialize({reopenTty:!0,reason:"SIGHUP",resetRecoveryAttempts:!0}),this.isStdinHealthy()?f.info("INPUT","\u2713 TTY reconnected successfully after SIGHUP"):f.warn("INPUT","TTY reconnection may need user input to activate");}catch(e){f.error("INPUT","Failed to reconnect TTY after SIGHUP",{error:e});}}},1e3));});}}initializeStdin(){try{this.boundStdin&&this.boundStdin!==process.stdin&&this.detachHandlersFromStdin(this.boundStdin),this.detachHandlersFromStdin(process.stdin),this.boundStdin=process.stdin,this.keypressEventsEnabled||(zo.emitKeypressEvents(process.stdin),this.keypressEventsEnabled=!0,f.debug("INPUT","readline.emitKeypressEvents() called (first time)")),process.stdin.isTTY&&!process.stdin.destroyed&&(process.stdin.setRawMode(!0),this.rawModeEnabled=!0),process.stdin.resume(),Promise.resolve().then(()=>(Or(),Lr)).then(({safeTTYWriter:e})=>{e.writeStdout("\x1B[?2004h")?f.debug("INPUT","Bracketed paste mode enabled"):f.warn("INPUT","Failed to enable bracketed paste (stdout not writable)");}).catch(e=>{f.warn("INPUT","Failed to import safeTTYWriter",{error:e});try{!process.stdout.destroyed&&process.stdout.writable&&(process.stdout.write("\x1B[?2004h"),f.debug("INPUT","Bracketed paste mode enabled (fallback)"));}catch(t){f.warn("INPUT","Bracketed paste failed",{error:t});}}),this.attachStdinLifecycleHandlers(process.stdin),this.readableHandler=()=>{if(process.env.CLI_DEBUG==="1"&&f.debug("INPUT_READABLE",`readable event fired, paused=${this.paused}`),this.paused){process.env.CLI_DEBUG==="1"&&f.debug("INPUT_READABLE","SKIPPED: paused=true");return}if(process.stdin.destroyed||!process.stdin.readable){process.env.CLI_DEBUG==="1"&&f.debug("INPUT_READABLE","SKIPPED: stdin destroyed or not readable");return}let e=Date.now()+500;this.suppressKeypressUntil=e;let t,n=!1;try{for(;(t=process.stdin.read())!==null;){n=!0;let r=Buffer.isBuffer(t)?t:Buffer.from(t);if(process.env.CLI_DEBUG==="1"){let i=Array.from(r).map(o=>o.toString(16).padStart(2,"0")).join(" ");f.debug("INPUT_READABLE",`read chunk: ${r.length} bytes [${i}]`);}this.markInputActivity(),this.handleRawData(r);}n||(this.suppressKeypressUntil=0);}catch(r){process.env.CLI_DEBUG==="1"&&f.error("INPUT_READABLE","Error reading from stdin",{error:r}),this.suppressKeypressUntil=0;}},process.stdin.on("readable",this.readableHandler),this.keypressHandler=(e,t)=>{if(process.env.CLI_DEBUG==="1"&&f.debug("INPUT_KEYPRESS",`keypress received: name=${t?.name}, paused=${this.paused}`),this.paused){process.env.CLI_DEBUG==="1"&&f.debug("INPUT_KEYPRESS","SKIPPED: paused=true");return}if(process.stdin.destroyed||!process.stdin.readable){process.env.CLI_DEBUG==="1"&&f.debug("INPUT_KEYPRESS","SKIPPED: stdin destroyed or not readable");return}if(this.markInputActivity(),t?.name==="escape"){this.emitInterrupt();return}this.handleKeypress(e,t);},process.stdin.on("keypress",this.keypressHandler),this.recoveryAttempts=0;}catch(e){f.error("INPUT","Failed to initialize stdin",{error:e});}}detachHandlersFromStdin(e){if(this.readableHandler)try{e.off("readable",this.readableHandler);}catch{}if(this.dataHandler)try{e.off("data",this.dataHandler);}catch{}if(this.keypressHandler)try{e.off("keypress",this.keypressHandler);}catch{}if(this.stdinErrorHandler)try{e.off("error",this.stdinErrorHandler);}catch{}if(this.stdinCloseHandler)try{e.off("close",this.stdinCloseHandler);}catch{}}attachStdinLifecycleHandlers(e){this.stdinErrorHandler||(this.stdinErrorHandler=t=>{this.handleStdinError(t);}),this.stdinCloseHandler||(this.stdinCloseHandler=()=>{this.handleStdinClose();}),e.on("error",this.stdinErrorHandler),e.on("close",this.stdinCloseHandler);}handleStdinError(e){if(!this.started)return;let t=e?.code;f.error("INPUT","stdin error detected",{code:t,message:e?.message,destroyed:process.stdin.destroyed,readable:process.stdin.readable});let n=["EIO","EBADF","EPIPE","ENXIO","ENOTTY"].includes(t||"");n?f.warn("INPUT",`TTY disconnection error (${t}), will attempt to reopen...`):f.warn("INPUT",`Non-critical stdin error (${t}), will attempt soft recovery`),this.attemptRecovery({reason:`stdin_error_${t||"unknown"}`,reopenTty:n});}handleStdinClose(){this.started&&(f.warn("INPUT","stdin closed"),this.attemptRecovery({reason:"stdin_close",reopenTty:true}));}handleRawData(e){if(process.stdin.destroyed||!process.stdin.readable)return;let t=e.toString();if(!t||t.length===0)return;if(t.includes("")||t.includes("")){this.abortBracketedPaste("ctrl"),this.suppressKeypressUntil=Date.now()+200,this.emit("exit");return}if(t.includes(s.PASTE_START)){this.inBracketedPaste=true,this.pasteBuffer="",this.resetPasteAbortTimeout(),this.suppressKeypressUntil=Date.now()+s.PASTE_SUPPRESS_DURATION;let d=t.indexOf(s.PASTE_START)+s.PASTE_START.length,p=t.substring(d);if(p.includes(s.PASTE_END)){let m=p.indexOf(s.PASTE_END);this.pasteBuffer=p.substring(0,m),this.finishBracketedPaste();return}else {this.pasteBuffer=p;return}}if(this.inBracketedPaste){if(t==="\x1B"){this.abortBracketedPaste("esc"),this.emitInterrupt();return}if(t.includes(s.PASTE_END)){let d=t.indexOf(s.PASTE_END);this.pasteBuffer+=t.substring(0,d),this.finishBracketedPaste();return}else {this.pasteBuffer+=t,this.resetPasteAbortTimeout();return}}let n=t.charCodeAt(0)===27,r=t.length>1,i=t.includes(`
1516
+ `)||t.includes("\r"),o=Date.now();o-this.lastInputTime;this.lastInputTime=o;r&&!n&&(t.length>8||i);if(r&&!n&&(t.length>8||i)){process.env.CLI_DEBUG==="1"&&f.debug("INPUT",`Paste detected: ${t.length} chars, containsNewline=${i}`),this.suppressKeypressUntil=o+s.PASTE_SUPPRESS_DURATION;let d=t.replace(/\x1b\[[0-9;]*[~A-Za-z]/g,"").replace(/\r\n/g,`
1517
+ `).replace(/\r/g,`
1518
+ `);d.length>0&&this.emit("char",d);return}if(r&&!n&&t.length<=8){let d=t.replace(/\x1b\[[0-9;]*[~A-Za-z]/g,"").replace(/\r\n/g,`
1519
+ `).replace(/\r/g,`
1520
+ `);d.length>0&&(this.suppressKeypressUntil=o+100,this.emit("char",d));return}n?(this.escTimeout&&(clearTimeout(this.escTimeout),this.escTimeout=null),t.length===1?(this.escBuffer=t,this.escTimeout=setTimeout(()=>{this.escBuffer="",this.escTimeout=null,!process.stdin.destroyed&&process.stdin.readable&&this.emitInterrupt();},s.ESC_TIMEOUT)):this.escBuffer=""):this.escBuffer&&(this.escTimeout&&(clearTimeout(this.escTimeout),this.escTimeout=null),this.escBuffer="");}flushRapidInputBuffer(){if(this.rapidInputBuffer.length===0)return;let e=this.rapidInputBuffer;this.rapidInputBuffer="",this.rapidInputTimeout=null,process.env.CLI_DEBUG==="1"&&f.debug("INPUT",`Rapid input flushed: ${e.length} chars, ${e.split(`
1521
+ `).length} lines`),this.suppressKeypressUntil=0;let t=e.replace(/\x1b\[[0-9;]*[~A-Za-z]/g,"");t.length>0&&this.emit("char",t);}emitInterrupt(){let e=Date.now();if(process.env.CLI_DEBUG==="1"&&f.debug("ESC",`emitInterrupt called at ${e}`),e-this.lastInterruptAt<s.INTERRUPT_DEBOUNCE_MS){process.env.CLI_DEBUG==="1"&&f.debug("ESC",`DEBOUNCED: ${e-this.lastInterruptAt}ms < ${s.INTERRUPT_DEBOUNCE_MS}ms`);return}this.lastInterruptAt=e,process.env.CLI_DEBUG==="1"&&f.debug("ESC","Emitting 'interrupt' event"),this.emit("interrupt");}finishBracketedPaste(){let e=this.pasteBuffer;this.inBracketedPaste=false,this.pasteBuffer="",this.clearPasteAbortTimeout(),this.suppressKeypressUntil=Date.now()+s.PASTE_SUPPRESS_DURATION;let t=e.replace(/\r\n/g,`
1522
+ `).replace(/\r/g,`
1523
+ `);process.env.CLI_DEBUG==="1"&&f.debug("INPUT",`Bracketed paste completed: ${t.length} chars, ${t.split(`
1524
+ `).length} lines`),t.length>0&&this.emit("char",t);}resetPasteAbortTimeout(){this.clearPasteAbortTimeout(),this.pasteAbortTimeout=setTimeout(()=>{this.inBracketedPaste&&(process.env.CLI_DEBUG==="1"&&f.warn("INPUT","Bracketed paste timeout - clearing paste state"),this.inBracketedPaste=false,this.pasteBuffer="",this.suppressKeypressUntil=0,this.pasteAbortTimeout=null);},s.PASTE_ABORT_TIMEOUT),this.pasteAbortTimeout.unref?.();}clearPasteAbortTimeout(){this.pasteAbortTimeout&&(clearTimeout(this.pasteAbortTimeout),this.pasteAbortTimeout=null);}abortBracketedPaste(e){this.inBracketedPaste&&(process.env.CLI_DEBUG==="1"&&f.debug("INPUT",`Bracketed paste aborted (${e})`),this.inBracketedPaste=false,this.pasteBuffer="",this.clearPasteAbortTimeout(),this.suppressKeypressUntil=0);}startHealthCheck(){this.healthCheckInterval||(this.lastHealthCheckAt=Date.now(),this.lastEventLoopRecoveryAt=0,this.healthCheckInterval=setInterval(()=>{if(!this.started||this.paused)return;let e=Date.now(),t=e-this.lastHealthCheckAt;this.lastHealthCheckAt=e,t>s.EVENT_LOOP_DELAY_THRESHOLD&&e-this.lastEventLoopRecoveryAt>s.EVENT_LOOP_RECOVERY_COOLDOWN&&(this.lastEventLoopRecoveryAt=e,f.warn("INPUT",`Event loop delay detected: ${t}ms, attempting input recovery`),this.attemptRecovery({reason:"event_loop_delay",reopenTty:true}));let n=process.stdin.listenerCount("data"),r=process.stdin.listenerCount("keypress"),i=process.stdin.isPaused?.()??"unknown",o=process.stdin.readableFlowing,a=process.stdin.isRaw??"unknown";process.env.CLI_DEBUG==="1"&&f.debug("INPUT_HEALTH",`listeners: data=${n}, keypress=${r}, paused=${this.paused}, stdin.isPaused=${i}, flowing=${o}, isRaw=${a}`);let l=false;if(this.dataHandler&&(process.stdin.listeners("data").includes(this.dataHandler)||(f.warn("INPUT_HEALTH","\u26A0\uFE0F Our data handler is missing! Attempting recovery..."),l=true)),this.keypressHandler&&(process.stdin.listeners("keypress").includes(this.keypressHandler)||(f.warn("INPUT_HEALTH","\u26A0\uFE0F Our keypress handler is missing! Attempting recovery..."),l=true)),l){this.attemptRecovery({reason:"handler_missing"});return}if(o!==void 0&&o!==true&&!this.paused&&process.stdin.isTTY&&!process.stdin.destroyed){f.warn("INPUT","stdin not flowing, attempting resume");try{process.stdin.resume();}catch(c){f.warn("INPUT","Failed to resume stdin",{error:c});}}if(!this.isStdinHealthy()){f.warn("INPUT","stdin unhealthy, attempting recovery..."),this.attemptRecovery({reason:"stdin_unhealthy",reopenTty:process.stdin.destroyed});return}if(s.RAW_GUARD_ENABLED&&this.rawModeEnabled&&!this.paused&&!(process.stdin.isRaw??false)&&process.stdin.isTTY&&!process.stdin.destroyed){f.warn("INPUT","Raw mode lost, attempting to restore");try{process.stdin.setRawMode(!0),process.stdin.resume();}catch(u){f.error("INPUT","Failed to restore raw mode",{error:u});}}},s.HEALTH_CHECK_INTERVAL),this.healthCheckInterval.unref());}markInputActivity(){this.lastInputActivity=Date.now(),this.idleRecoveryStage=0;}setIdleConfigProvider(e){this.idleConfigProvider=e;}setOnIdleRecoveryFailed(e){this.onIdleRecoveryFailed=e;}getIdleGuardConfig(){if(this.idleConfigProvider)try{return this.idleConfigProvider()}catch(e){f.warn("INPUT","Idle config provider failed, falling back to defaults",{error:e});}return {enabled:s.INPUT_ACTIVITY_GUARD_ENABLED,thresholdMs:s.INPUT_IDLE_THRESHOLD}}startInputActivityCheck(){!s.INPUT_ACTIVITY_GUARD_ENABLED||this.inputActivityInterval||process.stdin.isTTY&&(this.inputActivityInterval=setInterval(()=>{if(!this.started||this.paused)return;let e=this.getIdleGuardConfig();if(!e.enabled){this.idleGuardWasEnabled=false;return}if(!this.idleGuardWasEnabled){this.idleGuardWasEnabled=true,this.lastInputActivity=Date.now(),this.lastIdleRecoveryAt=0,this.idleRecoveryStage=0,process.env.CLI_DEBUG==="1"&&f.debug("INPUT","Idle guard re-enabled; reset idle timer");return}if(!Number.isFinite(e.thresholdMs)||e.thresholdMs<=0)return;let t=Date.now()-this.lastInputActivity;if(this.idleRecoveryStage>=s.IDLE_STAGE_DISABLED)if(t>12e4){f.warn("INPUT",`[FORCE RETRY] ${Math.round(t/1e3)}s idle after recovery failure, forcing medium recovery`),this.lastIdleRecoveryAt=Date.now(),this.idleRecoveryStage=0;try{this.mediumRecover();}catch(n){f.error("INPUT","Force retry medium recovery failed",{error:n});}return}else return;t<e.thresholdMs||Date.now()-this.lastIdleRecoveryAt<s.INPUT_IDLE_RECOVERY_COOLDOWN||(f.warn("INPUT",`Idle for ${Math.round(t/1e3)}s (threshold: ${Math.round(e.thresholdMs/1e3)}s), attempting recovery...`),this.idleRecoveryStage===0&&this.logDeepTTYDiagnostics("idle_detected_first_time",0),this.attemptIdleRecovery());},s.INPUT_ACTIVITY_CHECK_INTERVAL));}stopInputActivityCheck(){this.inputActivityInterval&&(clearInterval(this.inputActivityInterval),this.inputActivityInterval=null);}attemptIdleRecovery(){if(this.lastIdleRecoveryAt=Date.now(),!(this.idleRecoveryStage>=s.IDLE_STAGE_DISABLED)){if(this.logDeepTTYDiagnostics("before_recovery",this.idleRecoveryStage),this.idleRecoveryStage===0){let e=this.softRecover();this.idleRecoveryStage=1,e||f.warn("INPUT","Idle soft recovery had no effect");return}if(this.idleRecoveryStage===1){this.mediumRecover(),this.idleRecoveryStage=2;return}this.idleRecoveryStage=s.IDLE_STAGE_DISABLED,f.warn("INPUT","Idle recovery escalated to manual intervention"),this.logDeepTTYDiagnostics("all_recovery_failed",this.idleRecoveryStage),this.onIdleRecoveryFailed&&this.onIdleRecoveryFailed();}}softRecover(){if(!process.stdin.isTTY||process.stdin.destroyed)return false;let e=false,t=process.stdin.isPaused?.()??false,n=process.stdin.isRaw??false,r=process.stdin.readableFlowing;if(t)try{process.stdin.resume(),e=!0;}catch(i){f.warn("INPUT","Idle soft recovery: resume failed",{error:i});}if(!t&&r!==void 0&&r!==true)try{process.stdin.resume(),e=!0;}catch(i){f.warn("INPUT","Idle soft recovery: resume (flowing) failed",{error:i});}if(this.rawModeEnabled&&!n)try{process.stdin.setRawMode(!0),e=!0;}catch(i){f.warn("INPUT","Idle soft recovery: setRawMode failed",{error:i});}return this.dataHandler&&(process.stdin.listeners("data").includes(this.dataHandler)||(process.stdin.prependListener("data",this.dataHandler),e=true)),this.keypressHandler&&(process.stdin.listeners("keypress").includes(this.keypressHandler)||(process.stdin.on("keypress",this.keypressHandler),e=true)),e&&f.info("INPUT","Idle soft recovery applied"),e}mediumRecover(){f.warn("INPUT","Idle medium recovery: aggressive wakeup without TTY reopen");try{this.aggressiveStdinWakeup(),this.forceReinitialize({reopenTty:!1,reason:"idle_medium"});}catch(e){f.error("INPUT","Idle medium recovery failed",{error:e});}}aggressiveStdinWakeup(){if(!(!process.stdin.isTTY||process.stdin.destroyed))try{if(f.warn("INPUT","\u{1F528} Aggressive wakeup: trying multiple techniques..."),process.stdin.readable&&!process.stdin.readableEnded){let e=process.stdin.read(0);f.info("INPUT","Triggered stdin.read(0)",{chunk:e});}typeof process.stdin.flush=="function"&&(process.stdin.flush(),f.info("INPUT","Flushed stdin buffer"));for(let e=0;e<3;e++)process.stdin.isPaused?.()===!1&&(process.stdin.pause(),process.stdin.resume());f.info("INPUT","Performed 3x pause/resume cycles"),process.stdin.setRawMode&&(process.stdin.setRawMode(!1),setTimeout(()=>{try{process.stdin.setRawMode&&(process.stdin.setRawMode(!0),f.info("INPUT","Raw mode reset cycle completed"));}catch(e){f.warn("INPUT","Raw mode reset failed",{error:e});}},20)),process.stdin.resume(),f.warn("INPUT","\u{1F528} Aggressive wakeup completed");}catch(e){f.error("INPUT","Aggressive wakeup failed",{error:e});}}stopHealthCheck(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null);}stopHealthMonitoring(){this.stopHealthCheck(),this.stopRawGuard(),this.stopInputActivityCheck();}startRawGuard(){!s.RAW_GUARD_ENABLED||this.rawGuardInterval||(this.rawGuardInterval=setInterval(()=>{if(!this.started||this.paused||!this.rawModeEnabled||process.stdin.destroyed||!process.stdin.isTTY)return;let e=process.stdin.isRaw??false,t=process.stdin.isPaused?.()??false;if(!e){f.warn("INPUT","Raw mode unexpectedly disabled, restoring...");try{process.stdin.setRawMode(!0),t&&process.stdin.resume();}catch(n){f.error("INPUT","Raw guard failed to restore raw mode",{error:n});}}},s.RAW_GUARD_INTERVAL),this.rawGuardInterval.unref());}stopRawGuard(){this.rawGuardInterval&&(clearInterval(this.rawGuardInterval),this.rawGuardInterval=null);}attemptRecovery(e){if(this.recoveryAttempts>=s.MAX_RECOVERY_ATTEMPTS){f.error("INPUT","Max recovery attempts reached. stdin may be permanently broken."),f.error("INPUT","Use Ctrl+C (SIGINT) to interrupt if needed."),this.onFatalError&&this.onFatalError();return}this.recoveryAttempts++;let t=e?.reason||"auto",n=e?.reopenTty||process.stdin.destroyed||!process.stdin.isTTY;f.warn("INPUT",`Recovery attempt ${this.recoveryAttempts}/${s.MAX_RECOVERY_ATTEMPTS}`,{reason:t,reopenTty:n,stdin:{isTTY:process.stdin.isTTY,destroyed:process.stdin.destroyed,readable:process.stdin.readable}});try{n?this.forceReinitialize({reopenTty:!0,reason:t,resetRecoveryAttempts:!1}):this.initializeStdin();}catch(r){f.error("INPUT","Recovery failed",{error:r});}if(this.isStdinHealthy()){this.recoveryAttempts=0,f.info("INPUT","stdin recovered successfully");return}if(this.ttyUnavailable&&process.stdin.destroyed){this.onFatalError&&this.onFatalError();return}this.recoveryAttempts>=s.MAX_RECOVERY_ATTEMPTS&&this.onFatalError&&this.onFatalError();}stop(){if(this.started){if(this.stopHealthCheck(),this.stopRawGuard(),this.stopInputActivityCheck(),this.escTimeout&&(clearTimeout(this.escTimeout),this.escTimeout=null),this.escBuffer="",this.rapidInputTimeout&&(clearTimeout(this.rapidInputTimeout),this.rapidInputTimeout=null),this.rapidInputBuffer="",this.inBracketedPaste=false,this.pasteBuffer="",this.clearPasteAbortTimeout(),Promise.resolve().then(()=>(Or(),Lr)).then(({safeTTYWriter:e})=>{e.writeStdout("\x1B[?2004l");}),this.detachHandlersFromStdin(process.stdin),this.dataHandler=null,this.keypressHandler=null,this.stdinErrorHandler=null,this.stdinCloseHandler=null,this.boundStdin=null,this.rawModeEnabled&&process.stdin.isTTY&&!process.stdin.destroyed){try{process.stdin.setRawMode(!1);}catch{}this.rawModeEnabled=false;}this.started=false;}}pause(){if(!(!this.started||this.paused)){if(this.paused=true,this.rawModeEnabled&&process.stdin.isTTY&&!process.stdin.destroyed)try{process.stdin.setRawMode(!1);}catch{}try{process.stdin.pause();}catch{}}}resume(){if(!this.started){f.warn("INPUT","Cannot resume: not started");return}if(!this.paused){if(f.debug("INPUT","Resume called but not paused, ensuring raw mode..."),process.stdin.isTTY&&!process.stdin.destroyed)try{process.stdin.setRawMode(!0),process.stdin.resume();}catch(e){f.error("INPUT","Failed to ensure raw mode",{error:e});}return}if(f.debug("INPUT","Resuming input handling..."),this.paused=false,process.stdin.destroyed||!process.stdin.readable){f.warn("INPUT","stdin was destroyed during pause, attempting recovery..."),this.attemptRecovery({reason:"resume",reopenTty:true});return}if(this.rawModeEnabled&&process.stdin.isTTY)try{if(process.stdin.setRawMode(!0),process.stdin.resume(),this.keypressHandler){let e=process.stdin.listeners("keypress");f.debug("INPUT",`Current keypress listeners: ${e.length}`),e.includes(this.keypressHandler)||(f.debug("INPUT","Re-attaching keypress handler"),process.stdin.on("keypress",this.keypressHandler));}f.debug("INPUT","Resume completed successfully");}catch(e){f.error("INPUT","Failed to resume raw mode",{error:e}),this.attemptRecovery({reason:"resume",reopenTty:true});}}resumeInput(){if(this.started&&(this.paused=false,process.stdin.isTTY&&!process.stdin.destroyed))try{process.stdin.setRawMode(!0),process.stdin.resume(),f.debug("INPUT","resumeInput: stdin resumed");}catch(e){f.error("INPUT","resumeInput: failed",{error:e});}}tryReopenStdinFromTty(e){if(this.usingFallbackStdin&&!process.stdin.destroyed)return f.debug("INPUT","Already using fallback stdin and not destroyed, skipping reopen"),false;if(process.platform==="win32")return f.debug("INPUT","Windows platform, /dev/tty not available"),false;if(this.ttyUnavailable)return f.debug("INPUT","TTY marked as unavailable, skipping reopen"),false;f.info("INPUT",`Attempting to reopen TTY device for recovery (reason: ${e})...`);try{if(!an.existsSync("/dev/tty"))return f.error("INPUT","/dev/tty does not exist"),this.ttyUnavailable=!0,!1;let t=an.openSync("/dev/tty","r+");f.debug("INPUT",`Opened /dev/tty with fd=${t}`);let n=new Dm.ReadStream(t,{readable:!0,writable:!1});if(!n.isTTY)return f.error("INPUT","Reopened stream is not a TTY"),n.destroy(),an.closeSync(t),!1;n.on("error",i=>{f.warn("INPUT","Reopened TTY stream encountered error",{error:i});}),n.on("close",()=>{f.warn("INPUT","Reopened TTY stream closed");});let r=process.stdin;if(Object.defineProperty(process,"stdin",{value:n,configurable:!0,enumerable:!0,writable:!0}),this.usingFallbackStdin&&r!==n)try{this.detachHandlersFromStdin(r),f.debug("INPUT","Detached handlers from old stdin (not destroyed to avoid SIGHUP)");}catch{}return this.usingFallbackStdin=!0,f.info("INPUT",`\u2713 Successfully rebound stdin to /dev/tty (reason: ${e})`),!0}catch(t){return t?.code==="ENXIO"||t?.code==="ENODEV"?(this.ttyUnavailable=true,f.error("INPUT","TTY device not available (ENXIO/ENODEV)",{error:t})):t?.code==="EACCES"?f.error("INPUT","Permission denied accessing /dev/tty",{error:t}):f.error("INPUT","Failed to open /dev/tty for stdin recovery",{error:t,reason:e}),false}}forceReinitialize(e){if(!this.started)return;let t=process.stdin,n=false;e?.reopenTty&&(n=this.tryReopenStdinFromTty(e.reason||"manual"));let r=process.stdin;n&&r!==t&&(this.keypressEventsEnabled=false,this.rawModeEnabled=false),f.debug("INPUT","Force reinitializing stdin..."),f.debug("INPUT",`Current state: started=${this.started}, paused=${this.paused}, rawMode=${this.rawModeEnabled}`),f.debug("INPUT",`stdin state: isTTY=${process.stdin.isTTY}, destroyed=${process.stdin.destroyed}, readable=${process.stdin.readable}`),e?.resetRecoveryAttempts!==false&&(this.recoveryAttempts=0),this.lastInputActivity=Date.now(),this.idleRecoveryStage=0,this.escTimeout&&(clearTimeout(this.escTimeout),this.escTimeout=null),this.escBuffer="",this.rapidInputTimeout&&(clearTimeout(this.rapidInputTimeout),this.rapidInputTimeout=null),this.rapidInputBuffer="";try{this.detachHandlersFromStdin(t),this.initializeStdin(),this.paused=!1,f.debug("INPUT","Force reinitialize completed"),f.debug("INPUT",`New state: rawMode=${this.rawModeEnabled}, listeners=${process.stdin.listenerCount("keypress")}`);}catch(i){f.error("INPUT","Force reinitialize failed",{error:i});}}isStdinHealthy(){try{return process.stdin.isTTY&&!process.stdin.destroyed&&process.stdin.readable}catch{return false}}isActive(){return this.started&&!this.paused}isFullyFunctional(){return this.started&&!this.paused&&this.isStdinHealthy()}dumpDebugState(){let e={started:this.started,paused:this.paused,rawModeEnabled:this.rawModeEnabled,keypressEventsEnabled:this.keypressEventsEnabled,inBracketedPaste:this.inBracketedPaste,suppressKeypressUntil:this.suppressKeypressUntil,lastInputActivity:this.lastInputActivity,idleMs:Date.now()-this.lastInputActivity,idleRecoveryStage:this.idleRecoveryStage,usingFallbackStdin:this.usingFallbackStdin,stdin:{isTTY:process.stdin.isTTY,destroyed:process.stdin.destroyed,readable:process.stdin.readable,readableFlowing:process.stdin.readableFlowing,readableLength:process.stdin.readableLength,isPaused:process.stdin.isPaused?.()??"unknown",isRaw:process.stdin.isRaw??"unknown",fd:process.stdin.fd,dataListeners:process.stdin.listenerCount("data"),keypressListeners:process.stdin.listenerCount("keypress")},handlers:{hasDataHandler:!!this.dataHandler,hasKeypressHandler:!!this.keypressHandler}};f.info("INPUT_DEBUG","Full input state",e),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(Or(),Lr)).then(({safeTTYWriter:t})=>{t.writeStderr(`
1525
+ === INPUT DEBUG STATE ===
1526
+ `),t.writeStderr(`${JSON.stringify(e,null,2)}
1527
+ `),t.writeStderr(`=========================
1528
+ `);});}setOnFatalError(e){this.onFatalError=e;}handleKeypress(e,t){if(this.inBracketedPaste)return;let n={name:t?.name||e||"",ctrl:t?.ctrl||false,meta:t?.meta||false,shift:t?.shift||false,sequence:t?.sequence||e||""};if(n.name==="return"){let r=Date.now();if(r-(this.lastSubmitAt||0)<100){process.env.CLI_DEBUG==="1"&&f.debug("INPUT_KEYPRESS","Ignoring duplicate Enter within 100ms");return}this.lastSubmitAt=r,process.env.CLI_DEBUG==="1"&&f.debug("INPUT_KEYPRESS","Enter key detected, emitting submit"),this.emit("submit");return}if(n.ctrl&&n.name==="c"){this.emit("exit");return}if(n.ctrl&&n.name==="d"){this.emit("exit");return}if(n.name==="backspace"){this.emit("backspace");return}if(n.name==="delete"){this.emit("delete");return}if(n.name==="tab"){this.emit("tab");return}if(n.name==="left"){this.emit("cursor-left");return}if(n.name==="right"){this.emit("cursor-right");return}if(n.name==="up"){this.emit("history-prev");return}if(n.name==="down"){this.emit("history-next");return}if(n.ctrl&&n.name==="u"){this.emit("clear-line");return}if(n.ctrl&&n.name==="w"){this.emit("clear-word");return}if(this.emit("raw",n),n.name!=="escape"){if(n.ctrl&&n.name==="i"&&n.sequence!==" "){this.emit("attach-image");return}if(n.name==="home"||n.ctrl&&n.name==="a"){this.emit("cursor-home");return}if(n.name==="end"||n.ctrl&&n.name==="e"){this.emit("cursor-end");return}if(n.name==="pageup"){this.emit("page-up");return}if(n.name==="pagedown"){this.emit("page-down");return}if(Date.now()<this.suppressKeypressUntil){process.env.CLI_DEBUG==="1"&&f.debug("INPUT",`Suppressing keypress: name=${t?.name}, str="${e?.substring(0,10)}"`);return}if(e&&!n.ctrl&&!n.meta&&e.length>0){let r=e.replace(/\x1b\[[0-9;]*[~A-Za-z]/g,"");r.length>0&&this.emit("char",r);return}}}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);}off(e,t){let n=this.listeners.get(e);if(n){let r=n.indexOf(t);r>=0&&n.splice(r,1);}}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear();}emit(e,t){process.env.CLI_DEBUG==="1"&&e!=="char"&&e!=="raw"&&f.debug("INPUT_EVENT",`Emitting: ${e}`);let n=this.listeners.get(e)||[];for(let r of n)try{r(t);}catch(i){process.env.CLI_DEBUG==="1"&&f.error("INPUT_EVENT",`Handler error for ${e}`,{error:i});}}logDeepTTYDiagnostics(e,t){try{let n=process.stdin,r={context:e,recoveryStage:t,timestamp:new Date().toISOString(),timeSinceLastInput:Date.now()-this.lastInputActivity},i={isTTY:n.isTTY,isRaw:n.isRaw,isPaused:n.isPaused?.(),readable:n.readable,destroyed:n.destroyed,readableFlowing:n.readableFlowing,readableLength:n.readableLength,readableHighWaterMark:n.readableHighWaterMark,readableEnded:n.readableEnded,fd:n.fd,listeners:{data:n.listenerCount("data"),keypress:n.listenerCount("keypress"),error:n.listenerCount("error"),close:n.listenerCount("close"),end:n.listenerCount("end"),readable:n.listenerCount("readable")},_readableState:n._readableState?{flowing:n._readableState.flowing,ended:n._readableState.ended,endEmitted:n._readableState.endEmitted,reading:n._readableState.reading,constructed:n._readableState.constructed,sync:n._readableState.sync,needReadable:n._readableState.needReadable,emittedReadable:n._readableState.emittedReadable,readableListening:n._readableState.readableListening,resumeScheduled:n._readableState.resumeScheduled,errorEmitted:n._readableState.errorEmitted,closed:n._readableState.closed}:null},o={pid:process.pid,ppid:process.ppid,platform:process.platform,arch:process.arch,nodeVersion:process.version,uptime:process.uptime()},a={TERM:process.env.TERM,TERM_PROGRAM:process.env.TERM_PROGRAM,TERM_PROGRAM_VERSION:process.env.TERM_PROGRAM_VERSION,COLORTERM:process.env.COLORTERM,LANG:process.env.LANG},l={started:this.started,paused:this.paused,rawModeEnabled:this.rawModeEnabled,keypressEventsEnabled:this.keypressEventsEnabled,usingFallbackStdin:this.usingFallbackStdin,ttyUnavailable:this.ttyUnavailable,recoveryAttempts:this.recoveryAttempts,idleRecoveryStage:this.idleRecoveryStage,inBracketedPaste:this.inBracketedPaste,escBuffer:this.escBuffer.length},c={...r,process:o,stdin:i,terminal:a,inputManager:l};f.error("TTY_DIAGNOSTICS",`Deep TTY diagnostics [${e}]`,c);let u=[];i.destroyed&&u.push("\u274C CRITICAL: stdin.destroyed = true - stdin stream has been destroyed"),i.readable||u.push("\u274C CRITICAL: stdin.readable = false - stdin is not readable"),i.isPaused&&u.push("\u26A0\uFE0F WARNING: stdin.isPaused = true - stdin is paused"),i.readableFlowing===!1&&u.push("\u26A0\uFE0F WARNING: stdin.readableFlowing = false - flow is paused"),i.readableFlowing===null&&u.push("\u26A0\uFE0F WARNING: stdin.readableFlowing = null - no listeners or paused"),!i.isRaw&&this.rawModeEnabled&&u.push("\u26A0\uFE0F WARNING: stdin.isRaw = false but rawModeEnabled = true - raw mode lost"),i.listeners.data===0&&u.push("\u274C CRITICAL: No data listeners on stdin"),i._readableState?.ended&&u.push("\u274C CRITICAL: stdin._readableState.ended = true - stream ended"),i._readableState?.errorEmitted&&u.push("\u274C CRITICAL: stdin._readableState.errorEmitted = true - error occurred"),u.length===0&&(u.push("\u{1F914} MYSTERY: stdin appears healthy in Node.js, but no events from TTY driver"),u.push(" \u2192 This suggests the issue is at OS/Terminal.app level, not Node.js"),u.push(" \u2192 Possible causes:"),u.push(" 1. Terminal.app stopped sending input events to the TTY"),u.push(" 2. macOS TTY driver in inconsistent state"),u.push(" 3. Input method (IME) intercepting all input"),u.push(" 4. Terminal.app window/tab state issue")),f.error("TTY_ANALYSIS",`TTY freeze analysis [${e}]`,{analysis:u});}catch(n){f.error("TTY_DIAGNOSTICS","Failed to capture TTY diagnostics",{error:n});}}destroy(){this.stop(),this.listeners.clear();}};var ys=class{renderer;layout;state={active:false,row:0,col:1,content:"",lines:[""],startRow:0};onScrollNeeded;constructor(e,t){this.renderer=e,this.layout=t;}setScrollCallback(e){this.onScrollNeeded=e;}start(e,t){let r=this.layout.getLayout().timeline,i=Math.min(Math.max(e,r.startRow),r.endRow);this.state={active:true,row:i,col:1,content:"",lines:[""],startRow:i},this.renderer.setScrollRegion(r.startRow,r.endRow),this.renderer.moveTo(i,1),t&&(this.renderer.append(t),this.state.col=this.getVisibleLength(t)+1,this.state.lines[0]=t),this.renderer.flushSync();}appendDelta(e){if(!this.state.active||!e)return;let t=this.layout.getLayout(),n=t.totalCols,r=t.timeline,i=r.endRow;for(let o of e)if(o===`
1529
+ `)this.handleNewline(i,r);else if(o==="\r")this.state.col=1,this.renderer.moveToCol(1);else if(o===" "){let a=4-(this.state.col-1)%4;for(let l=0;l<a;l++)this.appendChar(" ",n,i,r);}else this.appendChar(o,n,i,r);this.state.content+=e,this.renderer.flushSync();}appendChar(e,t,n,r){this.state.col>=t&&this.handleNewline(n,r),this.renderer.append(e),this.state.col++;let i=this.state.lines.length-1;this.state.lines[i]=(this.state.lines[i]||"")+e;}handleNewline(e,t){this.state.row>=e?(this.renderer.scrollUp(1),this.onScrollNeeded&&this.onScrollNeeded(1)):this.state.row++,this.renderer.append(`\r
1530
+ `),this.state.col=1,this.state.lines.push("");}end(){this.renderer.resetScrollRegion();let e={content:this.state.content,lines:[...this.state.lines],lineCount:this.state.lines.length};return this.state={active:false,row:0,col:1,content:"",lines:[""],startRow:0},e}abort(){this.renderer.resetScrollRegion(),this.state={active:false,row:0,col:1,content:"",lines:[""],startRow:0};}isActive(){return this.state.active}getContent(){return this.state.content}getLineCount(){return this.state.lines.length}getCurrentRow(){return this.state.row}getCurrentCol(){return this.state.col}getLastLinePreview(e=50){let t=this.state.lines[this.state.lines.length-1]||"";return t.length<=e?t:"\u2026"+t.slice(-e+1)}repositionCursor(){this.state.active&&(this.renderer.moveTo(this.state.row,this.state.col),this.renderer.flushSync());}getVisibleLength(e){return e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"").length}};var $r=class s{options;static SYNTAX_PATTERNS={javascript:[{pattern:/\b(const|let|var|function|return|if|else|for|while|class|extends|import|export|from|async|await|new|this|try|catch|throw)\b/g,style:j.magenta},{pattern:/\b(true|false|null|undefined|NaN|Infinity)\b/g,style:j.cyan},{pattern:/(['"`])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/\/\/.*$/gm,style:j.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow},{pattern:/\b([A-Z][a-zA-Z0-9]*)\b/g,style:j.cyan}],typescript:[{pattern:/\b(const|let|var|function|return|if|else|for|while|class|extends|import|export|from|async|await|new|this|try|catch|throw|type|interface|enum|implements|readonly|private|public|protected)\b/g,style:j.magenta},{pattern:/\b(true|false|null|undefined|NaN|Infinity|string|number|boolean|any|void|never)\b/g,style:j.cyan},{pattern:/(['"`])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/\/\/.*$/gm,style:j.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow},{pattern:/\b([A-Z][a-zA-Z0-9]*)\b/g,style:j.cyan},{pattern:/<[^>]+>/g,style:j.blue}],python:[{pattern:/\b(def|class|if|elif|else|for|while|try|except|finally|with|as|import|from|return|yield|raise|pass|break|continue|lambda|and|or|not|in|is)\b/g,style:j.magenta},{pattern:/\b(True|False|None)\b/g,style:j.cyan},{pattern:/(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/("""[\s\S]*?"""|'''[\s\S]*?''')/g,style:j.green},{pattern:/#.*$/gm,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow},{pattern:/@\w+/g,style:j.cyan}],java:[{pattern:/\b(public|private|protected|static|final|abstract|class|interface|extends|implements|new|return|if|else|for|while|try|catch|throw|throws|void|import|package)\b/g,style:j.magenta},{pattern:/\b(true|false|null)\b/g,style:j.cyan},{pattern:/(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/\/\/.*$/gm,style:j.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:j.gray},{pattern:/\b(\d+\.?\d*[fdFL]?)\b/g,style:j.yellow},{pattern:/@\w+/g,style:j.cyan}],go:[{pattern:/\b(func|var|const|type|struct|interface|map|chan|package|import|return|if|else|for|range|switch|case|default|go|defer|select)\b/g,style:j.magenta},{pattern:/\b(true|false|nil|iota)\b/g,style:j.cyan},{pattern:/(['"`])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/\/\/.*$/gm,style:j.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow}],rust:[{pattern:/\b(fn|let|mut|const|static|struct|enum|impl|trait|pub|mod|use|self|Self|return|if|else|for|while|loop|match|move|async|await|unsafe)\b/g,style:j.magenta},{pattern:/\b(true|false|None|Some|Ok|Err)\b/g,style:j.cyan},{pattern:/(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/\/\/.*$/gm,style:j.gray},{pattern:/\/\*[\s\S]*?\*\//g,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow},{pattern:/'[a-z_]+\b/g,style:j.cyan}],bash:[{pattern:/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|export|local|readonly)\b/g,style:j.magenta},{pattern:/\$\{?[a-zA-Z_][a-zA-Z0-9_]*\}?/g,style:j.cyan},{pattern:/(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/#.*$/gm,style:j.gray}],sql:[{pattern:/\b(SELECT|FROM|WHERE|AND|OR|INSERT|INTO|VALUES|UPDATE|SET|DELETE|CREATE|TABLE|ALTER|DROP|INDEX|JOIN|LEFT|RIGHT|INNER|OUTER|ON|ORDER|BY|GROUP|HAVING|LIMIT|OFFSET|AS|DISTINCT|NULL|NOT|IN|LIKE|BETWEEN)\b/gi,style:j.magenta},{pattern:/(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/--.*$/gm,style:j.gray},{pattern:/\b(\d+\.?\d*)\b/g,style:j.yellow}],json:[{pattern:/"[^"]*"\s*:/g,style:j.cyan},{pattern:/:\s*"[^"]*"/g,style:j.green},{pattern:/:\s*(-?\d+\.?\d*)/g,style:j.yellow},{pattern:/:\s*(true|false|null)/g,style:j.magenta}],yaml:[{pattern:/^[a-zA-Z_][a-zA-Z0-9_]*\s*:/gm,style:j.cyan},{pattern:/:\s+(['"])(?:(?!\1)[^\\]|\\.)*\1/g,style:j.green},{pattern:/:\s+(-?\d+\.?\d*)/g,style:j.yellow},{pattern:/:\s+(true|false|null|~)/gi,style:j.magenta},{pattern:/#.*$/gm,style:j.gray}],markdown:[{pattern:/^#+\s.+$/gm,style:j.bold.cyan},{pattern:/\*\*[^*]+\*\*/g,style:j.bold},{pattern:/\*[^*]+\*/g,style:j.italic},{pattern:/`[^`]+`/g,style:j.bgGray.white}]};static LANGUAGE_ALIASES={js:"javascript",ts:"typescript",py:"python",sh:"bash",shell:"bash",zsh:"bash",yml:"yaml",md:"markdown",rs:"rust"};constructor(e={}){this.options={maxWidth:e.maxWidth??80,codeBlockBg:e.codeBlockBg??true,indentSize:e.indentSize??2};}render(e){if(!e)return "";let t=e.split(`
1531
+ `),n=[],r=false,i="",o=[];for(let a=0;a<t.length;a++){let l=t[a];if(l.startsWith("```")){if(!r)r=true,i=l.slice(3).trim().toLowerCase(),o=[];else {r=false;let c=this.renderCodeBlock(i,o.join(`
1532
+ `));n.push(...c.split(`
1533
+ `)),i="",o=[];}continue}if(r){o.push(l);continue}n.push(this.renderLine(l));}if(r&&o.length>0){let a=this.renderCodeBlock(i,o.join(`
1534
+ `));n.push(...a.split(`
1535
+ `));}return n.join(`
1536
+ `)}renderLine(e){if(e.startsWith("# "))return j.bold.cyan("\u2588 ")+j.bold.white(this.renderInline(e.slice(2)));if(e.startsWith("## "))return j.bold.cyan("\u258C ")+j.bold.white(this.renderInline(e.slice(3)));if(e.startsWith("### "))return j.cyan("\u258E ")+j.bold(this.renderInline(e.slice(4)));if(e.startsWith("#### "))return j.dim("\u258F ")+j.bold(this.renderInline(e.slice(5)));if(/^---+$/.test(e)||/^\*\*\*+$/.test(e)||/^___+$/.test(e))return j.dim("\u2500".repeat(Math.min(this.options.maxWidth,40)));if(/^\s*[-*+]\s/.test(e)){let t=e.match(/^(\s*)([-*+])\s(.*)$/);if(t){let[,n,,r]=t,i=Math.floor(n.length/2),o=i===0?j.cyan("\u2022"):i===1?j.blue("\u25E6"):j.dim("\xB7");return " ".repeat(i*this.options.indentSize)+o+" "+this.renderInline(r)}}if(/^\s*\d+\.\s/.test(e)){let t=e.match(/^(\s*)(\d+)\.\s(.*)$/);if(t){let[,n,r,i]=t,o=Math.floor(n.length/2);return " ".repeat(o*this.options.indentSize)+j.cyan(r+".")+" "+this.renderInline(i)}}if(e.startsWith("> "))return j.dim("\u2502 ")+j.italic(this.renderInline(e.slice(2)));if(e.startsWith(">"))return j.dim("\u2502 ")+j.italic(this.renderInline(e.slice(1)));if(/^\s*[-*]\s\[[ x]\]\s/.test(e)){let t=e.match(/^(\s*)[-*]\s\[([ x])\]\s(.*)$/);if(t){let[,n,r,i]=t,o=r==="x"?j.green("\u2611"):j.dim("\u2610");return " ".repeat(Math.floor(n.length/2)*this.options.indentSize)+o+" "+this.renderInline(i)}}return e.trim()===""?"":this.renderInline(e)}renderInline(e){if(!e)return "";let t=e;return t=t.replace(/`([^`]+)`/g,(n,r)=>j.bgGray.white(` ${r} `)),t=t.replace(/\*\*\*([^*]+)\*\*\*/g,(n,r)=>j.bold.italic(r)),t=t.replace(/___([^_]+)___/g,(n,r)=>j.bold.italic(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>j.bold(r)),t=t.replace(/__([^_]+)__/g,(n,r)=>j.bold(r)),t=t.replace(/(?<![a-zA-Z0-9])\*([^*]+)\*(?![a-zA-Z0-9])/g,(n,r)=>j.italic(r)),t=t.replace(/(?<![a-zA-Z0-9])_([^_]+)_(?![a-zA-Z0-9])/g,(n,r)=>j.italic(r)),t=t.replace(/~~([^~]+)~~/g,(n,r)=>j.strikethrough(r)),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,i)=>j.blue.underline(r)+j.dim(` (${i})`)),t=t.replace(/!\[([^\]]*)\]\(([^)]+)\)/g,(n,r,i)=>j.dim(`[Image: ${r||i}]`)),t}renderCodeBlock(e,t){let n=[],r=s.LANGUAGE_ALIASES[e]||e,i=s.SYNTAX_PATTERNS[r],o=r?` ${r} `:" code ";n.push(j.bgGray.white(o)+j.dim(" \u2500".repeat(10)));let a=t.split(`
1537
+ `),l=String(a.length).length;for(let c=0;c<a.length;c++){let u=String(c+1).padStart(l," "),d=j.dim(`${u} \u2502 `),p=a[c];i?p=this.highlightSyntax(p,i):p=j.white(p),this.options.codeBlockBg?n.push(j.bgRgb(30,30,30)(d+p+" ".repeat(Math.max(0,this.options.maxWidth-this.stripAnsi(p).length-l-3)))):n.push(d+p);}return n.push(j.dim("\u2500".repeat(Math.min(this.options.maxWidth,40)))),n.join(`
1538
+ `)}highlightSyntax(e,t){let n=e;for(let{pattern:r,style:i}of t)r.lastIndex=0,n=n.replace(r,o=>i(o));return n}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"")}getDisplayWidth(e){let t=this.stripAnsi(e),n=0;for(let r of t){let i=r.charCodeAt(0);i>=19968&&i<=40959||i>=12288&&i<=12351||i>=65280&&i<=65519?n+=2:n+=1;}return n}};new $r;var Nr=class s{renderer;buffer;layout;entries=[];nextId=1;onAfterPrint=null;onBeforePrint=null;compactMode=true;bottomBarRenderedAfterTimeline=true;static ENTRY_STYLES={user:{icon:"\u276F",color:j.green,prefix:"You",showBox:true,indent:0},tool_call:{icon:"\u25B6",color:j.yellow,prefix:"Tool",indent:2},tool_result:{icon:"\u2713",color:j.green,prefix:"\u2514\u2500",indent:4},tool_error:{icon:"\u2717",color:j.red,prefix:"\u2514\u2500",indent:4},thinking:{icon:"\u25CF",color:j.cyan,prefix:"Thinking",indent:2},reasoning:{icon:"\u25D0",color:j.magenta,prefix:"Reasoning",showBox:true,indent:0},assistant:{icon:"\u25C6",color:j.cyan,prefix:"Assistant",showBox:true,indent:0},file_update:{icon:"\u270E",color:j.blue,prefix:"Edit",indent:2},command_exec:{icon:"$",color:j.yellow,prefix:"Shell",indent:2},code_exec:{icon:"\u03BB",color:j.yellow,prefix:"Code",indent:2},web_search:{icon:"\u2315",color:j.cyan,prefix:"Search",indent:2},web_fetch:{icon:"\u21E3",color:j.cyan,prefix:"Fetch",indent:2},readfile:{icon:"\u2263",color:j.cyan,prefix:"readfile",indent:0},search:{icon:"\u2387",color:j.cyan,prefix:"Grep",indent:0},search_files:{icon:"\u27D0",color:j.cyan,prefix:"Glob",indent:2},show_tree:{icon:"\u2301",color:j.cyan,prefix:"Tree",indent:0},browser_debug:{icon:"\u25CD",color:j.cyan,prefix:"Browser",indent:2},info:{icon:"\u2022",color:j.blue,prefix:"info",indent:0,showBox:true},error:{icon:"\u2717",color:j.red,prefix:"Error",showBox:true,indent:0}};static BOX={TL:"\u256D",TR:"\u256E",BL:"\u2570",BR:"\u256F",H:"\u2500",V:"\u2502",T:"\u251C",TREE_L:"\u2514",TREE_V:"\u2502"};markdownRenderer;constructor(e,t,n){this.renderer=e,this.buffer=t,this.layout=n,this.markdownRenderer=new $r;}setAfterPrintCallback(e){this.onAfterPrint=e;}setBeforePrintCallback(e){this.onBeforePrint=e;}setCompactMode(e){this.compactMode=e;}markBottomBarRendered(){this.bottomBarRenderedAfterTimeline=true;}isBottomBarRenderedAfterTimeline(){return this.bottomBarRenderedAfterTimeline}isCompactMode(){return this.compactMode}addEntry(e){let t=this.nextId++;return e.id=t,this.entries.push(e),this.printEntry(e),t}updateEntry(e,t){let n=this.entries.find(r=>r.id===e);n&&Object.assign(n,t);}printEntry(e){let t=this.layout.getLayout(),n=t.totalCols,r=t.totalRows-t.bottomFixedHeight,i=s.ENTRY_STYLES[e.type]||s.ENTRY_STYLES.info,o=this.formatTime(e.timestamp),a=i.indent||0,l=[],c=e.isStreaming?j.dim(" \u2026"):"",u=j.dim(o)+j.dim(" \u2022 "),d=15,p=d,m=" ".repeat(a);if(i.showBox){let h=n-p-a-6,g=i.prefix?`${i.prefix}`:e.type,y=`${u}${m}${i.color(s.BOX.TL)}${i.color(s.BOX.H)} ${i.color(i.icon)} ${j.bold(g)}${c}`;l.push(this.truncateLine(y,n-1));let x=" ".repeat(d),S=(e.type==="assistant"||e.type==="reasoning")&&e.details;if(!S){let w=this.wrapText(e.message,h);for(let L of w){let B=`${x}${m}${i.color(s.BOX.V)} ${j.whiteBright(L)}`;l.push(this.truncateLine(B,n-1));}}if(e.details){S||l.push(`${x}${m}${i.color(s.BOX.V)}`);let L=(e.type==="assistant"?this.markdownRenderer.render(e.details):e.details).split(`
1539
+ `),I=`${x}${m}\u2502 `.length,k=n-I-2;for(let R of L){let E=e.type==="assistant"?_=>_:e.type==="info"?_=>_:e.type==="user"?j.white:j.dim,M=this.wrapLineByDisplayWidth(R,k);for(let _ of M){let W=`${x}${m}${i.color(s.BOX.V)} ${E(_)}`;l.push(W);}}}let T=`${x}${m}${i.color(s.BOX.BL)}${i.color(s.BOX.H.repeat(Math.min(40,h)))}`;l.push(T);}else {let g=i.prefix?`${i.prefix} `:"",y=`${u}${m} ${i.color(i.icon)} ${i.color(g)}${e.message}${c}`;if(l.push(this.truncateLine(y,n-1)),e.details){let x=e.details.split(`
1540
+ `),S=e.type==="file_update"?1/0:e.type==="readfile"?30:10,T=x.slice(0,S),w=" ".repeat(d),L=" ".repeat(a+4+3),I=`${w}${L}${s.BOX.TREE_V} `.length,k=n-I-1;for(let R=0;R<T.length;R++){let M=R===T.length-1&&x.length<=S?s.BOX.TREE_L:s.BOX.TREE_V,_=e.type==="file_update"?T[R]:j.dim(T[R]),W=this.wrapLine(_,k);for(let $=0;$<W.length;$++){let A=$===0?j.dim(M):j.dim(" "),G=`${w}${L}${A} ${W[$]}`;l.push(G);}}if(x.length>S){let R=" ".repeat(d);l.push(`${R}${L}${j.dim(s.BOX.TREE_L)} ${j.dim(`\u2026(${x.length-S} more lines)`)}`);}}}if(l.push(""),this.compactMode){this.onBeforePrint&&this.onBeforePrint(),this.bottomBarRenderedAfterTimeline?(this.renderer.append("\x1B[2A"),this.renderer.append("\r"),this.renderer.append("\x1B[J")):this.renderer.append("\r");for(let h of l)this.renderer.append(h+`
1541
+ `);this.renderer.flushSync(),this.bottomBarRenderedAfterTimeline=false,this.onAfterPrint&&setImmediate(()=>{!this.bottomBarRenderedAfterTimeline&&this.onAfterPrint&&this.onAfterPrint();});}else {this.renderer.saveCursor();for(let h of l)this.renderer.moveTo(r,1),this.renderer.append(h+`
1542
+ `);this.renderer.restoreCursor(),this.renderer.flushSync(),this.onAfterPrint&&this.onAfterPrint();}}wrapText(e,t){if(!e)return [""];let n=e.split(`
1543
+ `),r=[];for(let i of n){if(!i){r.push("");continue}let o=i.split(" "),a="";for(let l of o){let c=this.getDisplayWidth(l);this.getDisplayWidth(a)+c+(a?1:0)<=t?a+=(a?" ":"")+l:(a&&r.push(a),c>t?a=this.truncateByDisplayWidth(l,t-3)+"...":a=l);}a&&r.push(a);}return r.length>0?r:[""]}getDisplayWidth(e){let t=0;for(let n of e){let r=n.codePointAt(0)||0;r>=19968&&r<=40959||r>=12288&&r<=12351||r>=65280&&r<=65519||r>=127744&&r<=129535?t+=2:t+=1;}return t}truncateByDisplayWidth(e,t){let n=0,r="";for(let i of e){let o=this.getDisplayWidth(i);if(n+o>t)break;r+=i,n+=o;}return r}wrapLine(e,t){if(!e)return [""];if(!e.includes("\x1B[")){if(e.length<=t)return [e];let l=[];for(let c=0;c<e.length;c+=t)l.push(e.slice(c,c+t));return l}let n=[],r="",i=0,o=[],a=0;for(;a<e.length;)if(e[a]==="\x1B"&&e[a+1]==="["){let l=a+2;for(;l<e.length&&!/[A-Za-z]/.test(e[l]);)l++;if(l<e.length){l++;let c=e.slice(a,l);r+=c,c.includes("m")&&(c.includes("0m")||c==="\x1B[m"?o=[]:o.push(c)),a=l;}else a++;}else r+=e[a],i++,a++,i>=t&&(n.push(r),r=o.join(""),i=0);return (r||n.length===0)&&n.push(r),n}getCharDisplayWidth(e){let t=e.charCodeAt(0);return t>=19968&&t<=40959||t>=13312&&t<=19903||t>=12288&&t<=12351||t>=65280&&t<=65519||t>=44032&&t<=55215||t>=12352&&t<=12447||t>=12448&&t<=12543?2:1}wrapLineByDisplayWidth(e,t){if(!e)return [""];let n=[],r="",i=0,o=[],a=0;for(;a<e.length;)if(e[a]==="\x1B"&&e[a+1]==="["){let l=a+2;for(;l<e.length&&!/[A-Za-z]/.test(e[l]);)l++;if(l<e.length){l++;let c=e.slice(a,l);r+=c,c.includes("m")&&(c.includes("0m")||c==="\x1B[m"?o=[]:o.push(c)),a=l;}else a++;}else {let l=e[a],c=this.getCharDisplayWidth(l);i+c>t&&(n.push(r),r=o.join(""),i=0),r+=l,i+=c,a++;}return (r||n.length===0)&&n.push(r),n}truncateLine(e,t){if(!e.includes("\x1B["))return e.length<=t?e:e.slice(0,t-1)+"\u2026";let n=0,r=0,i="";for(;r<e.length&&n<t;)if(e[r]==="\x1B"&&e[r+1]==="["){let o=r+2;for(;o<e.length&&!/[A-Za-z]/.test(e[o]);)o++;o<e.length?(o++,i+=e.slice(r,o),r=o):r++;}else i+=e[r],n++,r++;return n>=t&&r<e.length&&(i+="\u2026"),i}scrollUp(e=5){}scrollDown(e=5){}scrollToTop(){}scrollToBottom(){}isViewScrolledUp(){return false}formatTime(e){let t=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0"),r=e.getSeconds().toString().padStart(2,"0"),i=e.getMilliseconds().toString().padStart(3,"0");return `${t}:${n}:${r}.${i}`}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"")}getCurrentLine(){return this.entries.length}getNextRow(){return this.layout.getLayout().timeline.endRow}clear(){this.entries=[],this.nextId=1;}getEntryCount(){return this.entries.length}getTotalLines(){return this.entries.length}fullRender(){}};var uc=class{pending=new Set;scheduled=false;executor=null;paused=false;setExecutor(e){this.executor=e;}request(e){this.paused||(this.pending.add(e),this.scheduled||(this.scheduled=true,queueMicrotask(()=>this.flush())));}flush(){if(this.scheduled=false,!this.executor||this.pending.size===0){this.pending.clear();return}try{this.pending.has("full")?this.executor.renderFull():(this.pending.has("status")&&this.executor.renderStatusOnly(),this.pending.has("input")&&this.executor.renderInputOnly());}catch{this.paused=true;}this.pending.clear();}pause(){this.paused=true;}resume(){this.paused=false;}hasPending(){return this.pending.size>0}clear(){this.pending.clear(),this.scheduled=false;}forceFlush(){this.scheduled&&this.flush();}},Fe=new uc;var Ur=class s{renderer;buffer;layout;status="Ready";statusType="complete";spinnerIndex=0;spinnerFrames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];spinnerInterval=null;shimmerIndex=0;shimmerInterval=null;static SHIMMER_SPEED=100;tokens={inputTokens:0,outputTokens:0,totalTokens:0};inputValue="";inputCursor=0;placeholder="Type a message... (? for help)";prompt=null;thinkingEnabled=true;taskStartTime=null;timerInterval=null;taskTokens=0;displayedTokens=0;tokenAnimationInterval=null;isTokenEstimate=true;lastRenderKey="";flowMode=true;actualStatusRow=0;compactMode=true;initialRenderDone=false;renderingAfterTimeline=false;renderingLocked=false;timelinePrinting=false;isRenderingStatusLine=false;lastInputLineCount=1;constructor(e,t,n){this.renderer=e,this.buffer=t,this.layout=n;let r={renderFull:()=>this.renderFullInternal(),renderStatusOnly:()=>this.renderStatusLineOnly(),renderInputOnly:()=>this.renderInputLineOnly()};Fe.setExecutor(r);}startSpinner(){this.spinnerInterval||(this.spinnerInterval=setInterval(()=>{this.shouldSpin()&&(this.spinnerIndex=(this.spinnerIndex+1)%this.spinnerFrames.length,this.compactMode||this.render());},80),this.spinnerInterval.unref(),this.startShimmer());}stopSpinner(){this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.stopShimmer();}startShimmer(){this.shimmerInterval||(this.shimmerInterval=setInterval(()=>{this.shouldSpin()&&this.compactMode&&!this.renderingLocked&&!this.timelinePrinting&&this.initialRenderDone&&!this.renderingAfterTimeline&&this.shimmerInterval!==null&&(this.shimmerIndex=(this.shimmerIndex+1)%20,Fe.request("status"));},s.SHIMMER_SPEED),this.shimmerInterval.unref());}stopShimmer(){this.shimmerInterval&&(clearInterval(this.shimmerInterval),this.shimmerInterval=null),this.shimmerIndex=0;}renderStatusLineOnly(){if(!(!this.initialRenderDone||this.renderingLocked||this.timelinePrinting||this.renderingAfterTimeline||this.isRenderingStatusLine)){this.isRenderingStatusLine=true;try{let t=this.layout.getLayout().totalCols,n=this.buildStatusLine(t),r=2,i=this.inputValue.slice(0,this.inputCursor),o=r+1+this.getDisplayWidth(i);this.renderer.hideCursor(),this.renderer.append("\x1B[2A"),this.renderer.append("\r"),this.renderer.append(n),this.renderer.append("\x1B[K"),this.renderer.append("\x1B[2B"),this.renderer.append(`\x1B[${o}G`),this.renderer.showCursor(),this.renderer.flushSync();}finally{this.isRenderingStatusLine=false;}}}renderInputLineOnly(){if(!this.initialRenderDone||this.renderingLocked||this.timelinePrinting||this.renderingAfterTimeline)return;let t=this.layout.getLayout().totalCols,n=this.buildInputLines(t);this.renderer.hideCursor(),this.renderer.append("\x1B[s"),this.renderer.append("\r"),this.renderer.append(n[this.getCursorLineIndex()]||n[0]),this.renderer.append("\x1B[K"),this.renderer.append("\x1B[u"),this.positionCursorMultiline(t),this.renderer.showCursor(),this.renderer.flushSync();}applyShimmer(e,t){if(!this.shouldSpin())return t(e);let n=[...e],r=[],i=6,o=n.length+i*2,a=this.shimmerIndex*2%o;for(let l=0;l<n.length;l++){let c=Math.abs(l-a+i);if(c<i){let u=1-c/i;u>.7?r.push(j.white.bold(n[l])):u>.4?r.push(j.cyan.bold(n[l])):r.push(t(n[l]));}else r.push(t(n[l]));}return r.join("")}startTimer(){this.taskStartTime===null&&(this.taskStartTime=Date.now(),this.taskTokens=0,this.displayedTokens=0,this.isTokenEstimate=true,this.timerInterval||(this.timerInterval=setInterval(()=>{this.taskStartTime!==null&&(this.compactMode&&this.initialRenderDone?Fe.request("status"):this.render());},100),this.timerInterval.unref()));}stopTimer(){this.taskStartTime=null,this.timerInterval&&(clearInterval(this.timerInterval),this.timerInterval=null),this.tokenAnimationInterval&&(clearInterval(this.tokenAnimationInterval),this.tokenAnimationInterval=null);}updateTaskTokens(e,t=false){this.taskTokens=e,t&&(this.isTokenEstimate=false),this.tokenAnimationInterval||(this.tokenAnimationInterval=setInterval(()=>{if(this.displayedTokens<this.taskTokens){let n=this.taskTokens-this.displayedTokens,r=Math.max(1,Math.ceil(n/5));this.displayedTokens=Math.min(this.taskTokens,this.displayedTokens+r),this.compactMode||this.render();}else this.displayedTokens>this.taskTokens&&(this.displayedTokens=this.taskTokens,this.compactMode||this.render());},30),this.tokenAnimationInterval.unref());}formatElapsedTime(){if(this.taskStartTime===null)return "";let e=Date.now()-this.taskStartTime,t=Math.floor(e/1e3);if(t<60)return `${t}s`;{let n=Math.floor(t/60),r=t%60;return `${n}m ${r}s`}}lastStatusMessage="";lastStatusType="complete";pendingStatusUpdate=false;updateStatus(e,t){e===this.lastStatusMessage&&t===this.lastStatusType||(this.lastStatusMessage=e,this.lastStatusType=t,this.status=e,this.statusType=t,this.compactMode&&this.initialRenderDone&&!this.renderingLocked&&!this.timelinePrinting?Fe.request("status"):this.renderingLocked||this.timelinePrinting?this.pendingStatusUpdate=true:this.render());}updateTokens(e){this.tokens={...this.tokens,...e},this.compactMode&&this.initialRenderDone?Fe.request("status"):this.render();}updateInput(e,t){let n=this.calculateInputLineCount(this.inputValue);this.inputValue=e,this.inputCursor=t;let r=this.calculateInputLineCount(e);this.compactMode&&this.initialRenderDone&&!this.renderingLocked&&!this.timelinePrinting?n!==r?Fe.request("full"):Fe.request("input"):this.render();}calculateInputLineCount(e){let n=this.layout.getLayout().totalCols;return this.buildInputLinesForValue(e,n).length}buildInputLinesForValue(e,t){let n=j.cyan("> "),i=t-2-1;if(!e)return [n+j.dim(this.placeholder)];let o=e.split(`
1544
+ `),a=[];for(let l of o)if(l.length<=i)a.push(n+l);else {let c=l,u=true;for(;c.length>0;){let d=c.slice(0,i);c=c.slice(i),a.push((u?n:" ")+d),u=false;}}return a}setPrompt(e){this.prompt=e,Fe.request("full");}updatePromptSelection(e){this.prompt&&this.prompt.type==="select"&&(this.prompt.selectedIndex=e,Fe.request("full"));}setThinkingEnabled(e){this.thinkingEnabled=e,Fe.request("full");}updateStreamingPreview(e){}renderInitial(){let t=this.layout.getLayout().totalCols,n=this.buildStatusLine(t),r=j.dim("\u2500".repeat(t)),i=this.buildInputLines(t),o=j.dim("\u2500".repeat(t)),a=this.buildHintLine(t);this.lastInputLineCount=i.length,this.renderer.append(n+`
1545
+ `),this.renderer.append(r+`
1546
+ `);for(let p of i)this.renderer.append(p+`
1547
+ `);this.renderer.append(o+`
1548
+ `),this.renderer.append(a);let l=2+i.length-1;this.renderer.append(`\x1B[${l}A`);let c=2,u=this.inputValue.slice(0,this.inputCursor),d=this.getDisplayWidth(u);this.renderer.append(`\x1B[${c+1+d}G`),this.renderer.flushSync(),this.initialRenderDone=true,this.compactMode=true;}setNormalMode(){this.compactMode=false;}isCompactMode(){return this.compactMode}setRenderingAfterTimeline(e){this.renderingAfterTimeline=e;}lockRender(){this.renderingLocked=true,this.timelinePrinting=true;}unlockRender(){this.renderingLocked=false,this.timelinePrinting=false,this.pendingStatusUpdate=false;}isRenderLocked(){return this.renderingLocked||this.timelinePrinting}renderFullInternal(){this.renderInternal();}render(){if(this.compactMode&&this.initialRenderDone&&!this.renderingLocked&&!this.timelinePrinting){Fe.request("full");return}this.renderInternal();}renderInternal(){if(process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:p})=>{p.debug("BOTTOMBAR","render() called",{initialRenderDone:this.initialRenderDone,compactMode:this.compactMode,timelinePrinting:this.timelinePrinting,renderingLocked:this.renderingLocked,renderingAfterTimeline:this.renderingAfterTimeline,statusType:this.statusType});}),!this.initialRenderDone)return;if(this.compactMode){if(this.timelinePrinting){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:p})=>{p.debug("BOTTOMBAR","render() skipped: timelinePrinting=true");});return}if(this.renderingLocked&&!this.renderingAfterTimeline){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:p})=>{p.debug("BOTTOMBAR","render() skipped: renderingLocked=true");});return}}let e=this.layout.getLayout(),t=e.totalCols,n=this.buildInputLines(t);if(!this.compactMode){let p=Math.max(3,n.length+2);this.layout.setInputHeight(p)&&(e=this.layout.getLayout());}let r=this.compactMode?`${this.status}|${this.statusType}|${this.inputValue}|${this.inputCursor}|${JSON.stringify(this.tokens)}`:`${this.status}|${this.statusType}|${this.spinnerIndex}|${this.inputValue}|${this.inputCursor}|${JSON.stringify(this.tokens)}`;if(r===this.lastRenderKey){this.compactMode||this.positionCursorMultilineNormal(e.inputBox);return}if(this.lastRenderKey=r,this.compactMode){this.renderer.hideCursor();let p=this.buildStatusLine(t),m=j.dim("\u2500".repeat(t-1)),h=this.buildInputLines(t),g=j.dim("\u2500".repeat(t-1)),y=this.buildHintLine(t),x=this.lastInputLineCount||1;if(this.lastInputLineCount=h.length,this.renderingAfterTimeline){this.renderer.append("\r"),this.renderer.append(p+`
1549
+ `),this.renderer.append(m+`
1550
+ `);for(let T of h)this.renderer.append(T+`
1551
+ `);this.renderer.append(g+`
1552
+ `),this.renderer.append(y),this.renderingAfterTimeline=false;let S=2+h.length-1;this.renderer.append(`\x1B[${S}A`);}else {let S=4+x,T=4+h.length,L=Math.min(x-1,this.getCursorLineIndex())+2;L>0&&this.renderer.append(`\x1B[${L}A`),this.renderer.append("\r");for(let k=0;k<S;k++)this.renderer.append("\x1B[2K"),k<S-1&&this.renderer.append("\x1B[1B");if(T>S){let k=T-S;for(let R=0;R<k;R++)this.renderer.append(`
1553
+ `);this.renderer.append(`\x1B[${T-1}A`);}else T<S?this.renderer.append(`\x1B[${S-1}A`):S>1&&this.renderer.append(`\x1B[${S-1}A`);this.renderer.append("\r"),this.renderer.append(p+`
1554
+ `),this.renderer.append(m+`
1555
+ `);for(let k of h)this.renderer.append(k+`
1556
+ `);if(this.renderer.append(g+`
1557
+ `),this.renderer.append(y),T<S){let k=S-T;for(let R=0;R<k;R++)this.renderer.append(`
1558
+ \x1B[2K`);this.renderer.append(`\x1B[${k}A`);}let B=this.getCursorLineIndex(),I=2+(h.length-B-1);I>0&&this.renderer.append(`\x1B[${I}A`);}this.positionCursorMultiline(t),this.renderer.showCursor(),this.renderer.flushSync();return}let i=e.statusBar,o=e.inputBox;this.renderer.hideCursor();for(let p=i.startRow;p<=o.endRow;p++)this.renderer.writeLine(p," ".repeat(t));let a=this.buildStatusLine(t);this.renderer.writeLine(i.startRow,a);let l=j.dim("\u2500".repeat(t));this.renderer.writeLine(o.startRow-1,l);for(let p=0;p<n.length;p++)this.renderer.writeLine(o.startRow+p,n[p]);let c=o.startRow+n.length,u=j.dim("\u2500".repeat(t));this.renderer.writeLine(c,u);let d=this.buildHintLine(t);this.renderer.writeLine(c+1,d),this.renderer.showCursor(),this.positionCursorMultilineNormal(o);}buildStatusLine(e){let t=this.shouldSpin()?j.cyan(this.spinnerFrames[this.spinnerIndex])+" ":"",n=this.getStatusIcon(),r=this.getStatusColor(),i=this.compactMode&&this.shouldSpin()?this.applyShimmer(this.status,r):r(this.status),o="";if(this.taskStartTime!==null){let h=this.formatElapsedTime(),g="";this.displayedTokens>0&&(g=` \xB7 \u2193 ${this.isTokenEstimate?"~":""}${this.formatNumber(this.displayedTokens)} tokens`);let y=Number(process.env.NEOX_ESC_CONFIRM_MS),S=(Number.isFinite(y)?y>0:true)?"esc twice to interrupt":"esc to interrupt";o=j.dim(` (${S} \xB7 `)+j.yellow(h)+j.cyan(g)+j.dim(")");}let a=`${t}${n} ${i}${o}`,l=[];if(l.push(j.dim("in ")+j.cyan(this.formatNumber(this.tokens.inputTokens))),l.push(j.dim("out ")+j.green(this.formatNumber(this.tokens.outputTokens))),this.tokens.contextWindow){let h=this.tokens.tokensUsedForContext||this.tokens.totalTokens,g=this.formatNumber(h),y=this.tokens.pressure||0,x=(y*100).toFixed(0),S=y>.8?j.red:y>.5?j.yellow:j.green;l.push(j.dim("context ")+j.yellow(g)+j.dim(" tokens ")+S(`${x}%`));}let c=l.join(" "),u=this.getDisplayWidth(this.stripAnsi(a)),d=this.getDisplayWidth(this.stripAnsi(c));if(u+d>=e-1){let h=e-d-4;return h>10?this.truncateToWidth(a,h)+" "+c:this.truncateToWidth(a+" "+c,e-2)}let m=Math.max(1,e-u-d-1);return a+" ".repeat(m)+c}truncateToWidth(e,t){let n=0,r="",i=0;for(;i<e.length&&n<t-2;)if(e[i]==="\x1B"&&e[i+1]==="["){let o=i+2;for(;o<e.length&&!/[A-Za-z]/.test(e[o]);)o++;o<e.length?(o++,r+=e.slice(i,o),i=o):i++;}else {let o=this.getDisplayWidth(e[i]);if(n+o>t-2)break;r+=e[i],n+=o,i++;}return i<e.length&&(r+=".."),r}buildInputLines(e){let t=this.prompt?j.yellow("\u276F "):j.green("> "),n=j.dim("\u2502 "),r=2,i=e-r-1;if(this.inputValue===""&&!this.prompt){let l=j.dim(this.placeholder),c=t+l,u=r+this.getDisplayWidth(this.stripAnsi(l)),d=Math.max(0,e-u);return [c+" ".repeat(d)]}let o=this.inputValue.split(`
1559
+ `),a=[];for(let l=0;l<o.length;l++){let c=o[l],u=l===0?t:n;if(this.getDisplayWidth(c)>i){let d=c,p=true;for(;d.length>0;){let m=0,h=0;for(let w=0;w<d.length;w++){let L=this.getDisplayWidth(d[w]);if(h+L>i)break;h+=L,m=w+1;}let g=d.slice(0,m);d=d.slice(m);let x=(l===0&&p?t:n)+g,S=r+this.getDisplayWidth(g),T=Math.max(0,e-S);a.push(x+" ".repeat(T)),p=false;}}else {let d=u+c,p=r+this.getDisplayWidth(c),m=Math.max(0,e-p);a.push(d+" ".repeat(m));}}return a}getInputLineCount(){if(this.inputValue==="")return 1;let e=this.inputValue.split(`
1560
+ `);return Math.max(1,e.length)}buildInputLine(e){return this.buildInputLines(e)[0]}buildHintLine(e){if(this.prompt?.type==="select"&&this.prompt.choices){let l=j.dim(" \u2191\u2193 to select, Enter to confirm, ESC to cancel"),c=this.prompt.choices[this.prompt.selectedIndex||0],u=c?j.cyan(c.title):"",d=this.getDisplayWidth(this.stripAnsi(l)),p=this.getDisplayWidth(this.stripAnsi(u)),m=Math.max(1,e-d-p);return l+" ".repeat(m)+u}let t=j.dim(" ? for shortcuts"),r=(this.thinkingEnabled?j.cyan("Thinking on"):j.dim("Thinking off"))+j.dim(" (tab to toggle)"),i=this.getDisplayWidth(this.stripAnsi(t)),o=this.getDisplayWidth(this.stripAnsi(r)),a=Math.max(1,e-i-o);return t+" ".repeat(a)+r}positionCursor(e,t){let r=t-2-1,i=this.inputValue.slice(0,this.inputCursor),o=this.getDisplayWidth(i);if(this.getDisplayWidth(this.inputValue)>r){let c=0,u=0;for(let d=0;d<this.inputCursor;d++){let p=this.getDisplayWidth(this.inputValue[d]);u+this.getDisplayWidth(this.inputValue.slice(d,this.inputCursor))>r-10&&(c=d,u+=p);}o=this.getDisplayWidth(this.inputValue.slice(c,this.inputCursor));}let a=e.startRow,l=3+o;this.renderer.moveTo(a,l),this.renderer.showCursor(),this.renderer.flushSync();}getCursorLineIndex(){return this.inputValue.includes(`
1561
+ `)?(this.inputValue.slice(0,this.inputCursor).match(/\n/g)||[]).length:0}positionCursorMultiline(e){let n=this.inputValue.split(`
1562
+ `),r=0,i=0,o=0;for(let u=0;u<n.length;u++){let d=n[u].length,p=r+d;if(this.inputCursor<=p){i=u,o=this.inputCursor-r;break}r=p+1,i=u+1,o=0;}let l=(n[i]||"").slice(0,o),c=this.getDisplayWidth(l);this.renderer.append(`\x1B[${3+c}G`);}positionCursorMultilineNormal(e){let n=this.getCursorLineIndex(),r=this.inputValue.split(`
1563
+ `),i=0;for(let p=0;p<n;p++)i+=(r[p]?.length??0)+1;let o=Math.max(0,this.inputCursor-i),l=(r[n]||"").slice(0,o),c=this.getDisplayWidth(l),u=e.startRow+n,d=3+c;this.renderer.moveTo(u,d),this.renderer.showCursor(),this.renderer.flushSync();}fullRender(){this.lastRenderKey="",this.render();}shouldSpin(){return this.statusType==="thinking"||this.statusType==="tool_call"||this.statusType==="compacting"}getStatusIcon(){return {thinking:j.cyan("\u25CF"),tool_call:j.yellow("\u25B6"),tool_result:j.green("\u2713"),complete:j.green("\u25A0"),error:j.red("\u2717"),compacting:j.magenta("\u21BB")}[this.statusType]||j.white("\u25CF")}getStatusColor(){return {thinking:j.cyan,tool_call:j.yellow,tool_result:j.green,complete:j.green,error:j.red,compacting:j.magenta}[this.statusType]||j.white}formatNumber(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toString()}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*[A-Za-z]/g,"")}getDisplayWidth(e){let t=0;for(let n of e){let r=n.codePointAt(0)||0;r>=19968&&r<=40959||r>=12288&&r<=12351||r>=65280&&r<=65519||r>=127744&&r<=129535?t+=2:t+=1;}return t}getInputValue(){return this.inputValue}getInputCursor(){return this.inputCursor}isPromptActive(){return this.prompt!==null}getPrompt(){return this.prompt}isInitialRenderDone(){return this.initialRenderDone}destroy(){this.stopSpinner();}};le();var Fr=class s{renderer;buffer;layout;input;terminalBroken=false;stdoutErrorHandler=null;stderrErrorHandler=null;streamRenderer;reasoningStreamRenderer;timelineRenderer;bottomBar;options;started=false;paused=false;callbacks=null;inputValue="";inputCursor=0;history=[];historyIndex=-1;historyDraft="";attachedImages=[];thinkingEnabled=true;streamingTextId=null;streamingReasoningId=null;streamingTextContent="";streamingReasoningContent="";tokens={inputTokens:0,outputTokens:0,totalTokens:0};taskStartTime=null;taskDurationMs=0;durationInterval=null;promptResolve=null;promptReject=null;logIdCounter=0;runningToolMap=new Map;lastEscAt=0;static ESC_CONFIRM_MS=Number.isFinite(Number(process.env.NEOX_ESC_CONFIRM_MS))?Number(process.env.NEOX_ESC_CONFIRM_MS):1200;instance=null;constructor(e){this.options=e,this.renderer=new Pr(process.stdout),this.layout=new Mr;let t=this.layout.getLayout();this.buffer=new Ar(t.totalCols,t.totalRows),this.input=new Dr,this.renderer.setErrorHandler(n=>{this.handleTerminalError(n);}),this.streamRenderer=new ys(this.renderer,this.layout),this.reasoningStreamRenderer=new ys(this.renderer,this.layout),this.timelineRenderer=new Nr(this.renderer,this.buffer,this.layout),this.bottomBar=new Ur(this.renderer,this.buffer,this.layout),this.streamRenderer.setScrollCallback(n=>{}),this.reasoningStreamRenderer.setScrollCallback(n=>{}),this.timelineRenderer.setBeforePrintCallback(()=>{this.compactMode&&this.bottomBar.lockRender();}),this.timelineRenderer.setAfterPrintCallback(()=>{if(this.compactMode&&(this.bottomBar.unlockRender(),this.bottomBar.setRenderingAfterTimeline(true)),this.bottomBar.fullRender(),Fe.forceFlush(),this.timelineRenderer.markBottomBarRendered(),this.pendingSelectOverlay){let n=this.pendingSelectOverlay;this.pendingSelectOverlay=null,this.showSelectOverlay(n.message,n.choices,n.selectedIndex),this.bottomBar.lockRender();}else if(this.selectOverlayVisible){let n=this.bottomBar.getPrompt();n?.type==="select"&&n.choices&&(this.showSelectOverlay(n.message,n.choices,n.selectedIndex||0),this.bottomBar.lockRender());}});}sigintHandler=null;sigusr1Handler=null;sigusr2Handler=null;exiting=false;start(e){if(this.started)return;this.started=true,this.callbacks=e,this.stdoutErrorHandler=r=>{this.handleTerminalError(r);},this.stderrErrorHandler=r=>{this.handleTerminalError(r);},process.stdout.on("error",this.stdoutErrorHandler),process.stderr.on("error",this.stderrErrorHandler),this.input.setIdleConfigProvider(()=>{if(this.callbacks?.isTaskRunning?.()??false)return {enabled:false,thresholdMs:Number.POSITIVE_INFINITY};let i=Number(process.env.NEOX_INPUT_IDLE_MS);return {enabled:true,thresholdMs:Number.isFinite(i)?i:3e4}}),this.input.setOnIdleRecoveryFailed(()=>{process.env.CLI_DEBUG==="1"&&f.debug("INPUT","Idle recovery escalated to manual intervention (will auto-retry in 120s)");}),this.setupInputHandlers(),this.input.start(),this.input.setOnFatalError(()=>{this.handleTerminalError(new Error("stdin_fatal"));}),this.layout.startResizeListener(),this.layout.on("resize",()=>this.handleResize()),this.bottomBar.startSpinner();let t=0,n=2e3;this.sigintHandler=()=>{let r=Date.now();if(r-t<n){process.stderr.write(`
1564
+
1565
+ \u26A0\uFE0F \u5F3A\u5236\u9000\u51FA...
1566
+ `);try{let{processManager:o}=(ac(),gg(Am));o?.killAll?.(!0);}catch{}process.exit(1);}t=r,this.exiting&&(process.stderr.write(`
1567
+
1568
+ \u26A0\uFE0F \u5F3A\u5236\u9000\u51FA...
1569
+ `),process.exit(1)),process.env.CLI_DEBUG==="1"&&process.stderr.write(`
1570
+ [DEBUG] SIGINT received
1571
+ `),this.callbacks?.isTaskRunning?.()??false?(process.stderr.write(`
1572
+ \u26A0\uFE0F \u4E2D\u65AD\u4EFB\u52A1... (\u518D\u6309\u4E00\u6B21 Ctrl+C \u5F3A\u5236\u9000\u51FA)
1573
+ `),this.callbacks?.onInterrupt()):this.requestExit("sigint");},process.on("SIGINT",this.sigintHandler),process.platform!=="win32"&&(this.sigusr1Handler=()=>{this.exiting||(this.addInfo("\u26A0\uFE0F \u68C0\u6D4B\u5230\u5916\u90E8\u6062\u590D\u4FE1\u53F7\uFF0C\u6B63\u5728\u91CD\u7F6E\u8F93\u5165..."),this.input.forceReinitialize({reopenTty:true,reason:"sigusr1"}),this.bottomBar.fullRender());},process.on("SIGUSR1",this.sigusr1Handler),this.sigusr2Handler=()=>{this.input.dumpDebugState(),this.addInfo("\u2139\uFE0F \u5DF2\u8F93\u51FA\u8F93\u5165\u8BCA\u65AD\u4FE1\u606F\u5230\u65E5\u5FD7");},process.on("SIGUSR2",this.sigusr2Handler)),this.renderInitial(),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:r})=>{r.debug("UI_V2","UIController started");});}stopHealthMonitoring(){this.input.stopHealthMonitoring();}stop(){let e=process.env.CLI_DEBUG==="1",t=[];e&&t.push(`UIController.stop() called, started=${this.started}`),this.started&&(this.started=false,this.sigintHandler&&(process.off("SIGINT",this.sigintHandler),this.sigintHandler=null),this.sigusr1Handler&&(process.off("SIGUSR1",this.sigusr1Handler),this.sigusr1Handler=null),this.sigusr2Handler&&(process.off("SIGUSR2",this.sigusr2Handler),this.sigusr2Handler=null),this.stdoutErrorHandler&&(process.stdout.off("error",this.stdoutErrorHandler),this.stdoutErrorHandler=null),this.stderrErrorHandler&&(process.stderr.off("error",this.stderrErrorHandler),this.stderrErrorHandler=null),this.stopTaskTimer(),this.bottomBar.stopSpinner(),this.bottomBar.lockRender(),this.input.stop(),this.layout.stopResizeListener(),e&&t.push("About to call cleanupTerminal()"),this.cleanupTerminal(),e&&t.push("cleanupTerminal() completed"),e&&t.length>0&&process.stderr.write(`
1574
+ `+t.map(n=>`[DEBUG] ${n}`).join(`
1575
+ `)+`
1576
+ `));}pause(){this.paused=true,this.input.pause();}resume(){this.paused=false,this.input.forceReinitialize({reopenTty:true,reason:"ui-resume"}),this.bottomBar.fullRender();}refreshUI(){this.bottomBar.fullRender();}checkAndRecoverInput(){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:e})=>{e.debug("UI_V2",`checkAndRecoverInput: isFullyFunctional=${this.input.isFullyFunctional()}, isActive=${this.input.isActive()}`);}),this.input.isFullyFunctional()?this.input.isActive()||(process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:e})=>{e.debug("UI_V2","Input is healthy but paused, resuming...");}),this.input.resumeInput()):(this.addInfo("\u26A0\uFE0F \u68C0\u6D4B\u5230\u8F93\u5165\u5F02\u5E38\uFF0C\u6B63\u5728\u6062\u590D..."),this.input.forceReinitialize({reopenTty:true,reason:"input_check"}));}headerPrinted=false;renderInitial(){this.headerPrinted||(this.printHeader(),this.headerPrinted=true),this.bottomBar.updateStatus("Ready","complete"),this.bottomBar.updateInput(this.inputValue,this.inputCursor),this.bottomBar.renderInitial(),this.setupScrollRegion(),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:e})=>{e.debug("UI_V2","UIController started (Compact Mode)");});}compactMode=true;setupScrollRegion(){let e=this.layout.getLayout();if(this.compactMode){this.renderer.flushSync();return}let t=1,n=e.statusBar.startRow-1;this.renderer.setScrollRegion(t,n),this.renderer.moveTo(n,1),this.renderer.flushSync(),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:r})=>{r.debug("UI_V2",`Scroll region: ${t}-${n} | BottomBar: ${e.statusBar.startRow}`);});}switchToNormalMode(){if(!this.compactMode)return;this.compactMode=false,this.bottomBar.setNormalMode(),this.timelineRenderer.setCompactMode(false);let e=this.layout.getLayout(),t=1,n=e.statusBar.startRow-1;this.renderer.setScrollRegion(t,n),this.renderer.flushSync(),this.bottomBar.fullRender(),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:r})=>{r.debug("UI_V2","Switched to normal mode");});}printHeader(){let e=this.layout.getLayout(),t=e.totalCols;e.statusBar.startRow-1;let r=j.hex("#5C9DFF"),i="\u256D",o="\u256E",a="\u2570",l="\u256F",c="\u2500",u="\u2502",d="\u2534",p="\u252C",m=t-2,h=45,g=m-h-3,y=A=>{let G=this.stripAnsi(A),N=0;for(let U of G){let H=U.codePointAt(0)||0;H>8192&&H<12288||H>=19968&&H<=40959||H>=127744&&H<=129535?N+=2:N+=1;}return N},x=(A,G)=>{let N=y(A);return N>=G?A:A+" ".repeat(G-N)},S=(A,G)=>{let N=y(A);if(N>=G)return A;let U=Math.floor((G-N)/2),H=G-N-U;return " ".repeat(U)+A+" ".repeat(H)},T=(A,G)=>A.length<=G?A:A.slice(0,G-3)+"...",w=j.cyan(" ____ ____"),L=j.cyan("| ")+j.white("o-o")+j.cyan(" |"),B=j.cyan("\\___/")+" "+j.cyan("\\___/"),I=T(this.options.provider,h-12),k=T(this.options.model,h-12),R=this.truncatePath(this.options.workDir,h-12),E=(A,G)=>r(u)+x(A,h)+r(u)+x(G,g)+r(u),M=[r(i+c.repeat(h)+p+c.repeat(g)+o)],_=" "+j.bold.cyan("Neox")+" "+j.dim(`v${this.options.version}`),W=S(j.dim("Welcome! Enjoy!"),h),$=" "+j.bold.yellow("Tips for getting started");M.push(E(_,$)),M.push(E(W," "+j.dim("Type your message to start"))),M.push(E(""," "+j.dim("/help or ? for commands"))),M.push(E(S(w,h)," "+j.dim("Press ? to see all shortcuts"))),M.push(E(S(L,h),"")),M.push(E(S(B,h)," "+j.bold.white("What is Neox?"))),M.push(E(""," "+j.dim("Your intelligent coding assistant"))),M.push(E(""," "+j.dim("Multi-agent collaboration support"))),M.push(E(" "+j.yellow("Provider")+" "+j.dim(I)," "+j.dim("Smart context management"))),M.push(E(" "+j.cyan("Model")+" "+j.dim(k),"")),M.push(E(" "+j.blue("Path")+" "+j.dim(R),"")),M.push(r(a+c.repeat(h)+d+c.repeat(g)+l));for(let A of M)this.renderer.append(A+`
1577
+ `);this.renderer.flushSync();}renderHeader(){}stripAnsi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}getDisplayWidth(e){let t=0;for(let n of e){let r=n.codePointAt(0)||0;r>=19968&&r<=40959||r>=12288&&r<=12351||r>=65280&&r<=65519||r>=127744&&r<=129535?t+=2:t+=1;}return t}truncatePath(e,t){if(e.length<=t)return e;let n=process.env.HOME||"";return n&&e.startsWith(n)&&(e="~"+e.slice(n.length)),e.length<=t?e:"..."+e.slice(-t+3)}cleanupTerminal(){this.compactMode||this.renderer.resetScrollRegion(),this.renderer.showCursor(),this.compactMode&&(this.renderer.append("\x1B[2B"),this.renderer.append("\r")),this.renderer.flushSync(),process.stdout.write(`
1578
+
1579
+ `),process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] cleanupTerminal done (compactMode=${this.compactMode})
1580
+ `);}handleResize(){let e=this.layout.getLayout();this.buffer.resize(e.totalCols,e.totalRows),this.setupScrollRegion(),this.bottomBar.fullRender();}setupInputHandlers(){this.input.on("char",e=>{this.insertText(e);}),this.input.on("submit",()=>{this.handleSubmit();}),this.input.on("interrupt",()=>{this.handleInterrupt();}),this.input.on("exit",()=>{this.requestExit("keypress");}),this.input.on("backspace",()=>{if(this.bottomBar.isPromptActive()&&this.bottomBar.getPrompt()?.type==="select")return this.handleSelectBack(),void 0;this.inputCursor>0&&(this.inputValue=this.inputValue.slice(0,this.inputCursor-1)+this.inputValue.slice(this.inputCursor),this.inputCursor--,this.updateInputDisplay());}),this.input.on("delete",()=>{this.inputCursor<this.inputValue.length&&(this.inputValue=this.inputValue.slice(0,this.inputCursor)+this.inputValue.slice(this.inputCursor+1),this.updateInputDisplay());}),this.input.on("cursor-left",()=>{this.inputCursor>0&&(this.inputCursor--,this.updateInputDisplay());}),this.input.on("cursor-right",()=>{this.inputCursor<this.inputValue.length&&(this.inputCursor++,this.updateInputDisplay());}),this.input.on("cursor-home",()=>{this.inputCursor=0,this.updateInputDisplay();}),this.input.on("cursor-end",()=>{this.inputCursor=this.inputValue.length,this.updateInputDisplay();}),this.input.on("history-prev",()=>{this.historyPrev();}),this.input.on("history-next",()=>{this.historyNext();}),this.input.on("tab",()=>{this.handleTab();}),this.input.on("clear-line",()=>{this.inputValue="",this.inputCursor=0,this.attachedImages=[],this.updateInputDisplay();}),this.input.on("page-up",()=>{this.timelineRenderer.scrollUp(10);}),this.input.on("page-down",()=>{this.timelineRenderer.scrollDown(10);}),this.input.on("attach-image",async()=>{await this.promptAttachImage();});}async promptAttachImage(){try{let e=await this.promptText({message:"Enter image file path:",hint:"Path to image file (png, jpg, gif, etc.)",allowEmpty:!1});e&&e.trim()&&this.attachImage(e.trim());}catch{}}insertText(e){if(process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:t})=>{let n=e.includes(`
1581
+ `);t.debug("INSERT_TEXT",`Inserting ${e.length} chars, hasNewline=${n}, lines=${e.split(`
1582
+ `).length}`);}),this.isImagePath(e)){this.attachImage(e.trim());return}this.inputValue=this.inputValue.slice(0,this.inputCursor)+e+this.inputValue.slice(this.inputCursor),this.inputCursor+=e.length,process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:t})=>{let n=this.inputValue.split(`
1583
+ `).length;t.debug("INSERT_TEXT",`After insert: inputValue has ${n} lines, cursor at ${this.inputCursor}`);}),this.updateInputDisplay();}isImagePath(e){let t=e.trim(),n=/\.(png|jpe?g|gif|bmp|webp|svg|ico)$/i;return (t.includes("/")||t.includes("\\")||t.startsWith("~"))&&n.test(t)}attachImage(e){if(this.attachedImages.some(t=>t.path===e)){this.addInfo(`\u26A0\uFE0F Image already attached: ${e}`);return}this.attachedImages.push({path:e}),this.addInfo(`\u{1F4CE} Attached image #${this.attachedImages.length}: ${e}`),this.updateInputDisplay();}updateInputDisplay(){let e=this.inputValue;if(this.attachedImages.length>0){let t=this.attachedImages.map((n,r)=>`[Image #${r+1}]`).join(" ");e=this.inputValue?`${this.inputValue} ${t}`:t;}this.bottomBar.updateInput(e,this.inputCursor);}handleSubmit(){if(process.env.CLI_DEBUG==="1"&&(f.debug("UI","========================================"),f.debug("UI","=== UIController.handleSubmit ENTRY ==="),f.debug("UI",` inputValue: "${this.inputValue?.substring(0,50)}..."`),f.debug("UI",` promptActive: ${this.bottomBar.isPromptActive()}`),f.debug("UI",` stdin.isPaused: ${process.stdin.isPaused?.()}`),f.debug("UI",` stdin.destroyed: ${process.stdin.destroyed}`),Je.logStdinState("UIController.handleSubmit.entry")),this.bottomBar.isPromptActive()){let i=this.bottomBar.getPrompt();if(i?.type==="select"&&i.choices){let o=i.choices[i.selectedIndex||0];this.resolvePrompt(o.value);}else this.resolvePrompt(this.inputValue);return}let e=this.inputValue.trim(),t=this.attachedImages.length>0?[...this.attachedImages]:void 0,n=e.length>0||t&&t.length>0;if(this.callbacks?.isTaskRunning?.()??false){n&&this.addInfo("\u4EFB\u52A1\u6267\u884C\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210\u6216\u6309 ESC \u4E2D\u65AD");return}n&&(e&&this.addToHistory(e),this.inputValue="",this.inputCursor=0,this.attachedImages=[],this.bottomBar.updateInput(this.inputValue,this.inputCursor),e&&(process.env.CLI_DEBUG==="1"&&(f.debug("UI","=== UIController.handleSubmit calling onSubmit ==="),f.debug("UI",` value: "${e.substring(0,50)}..."`),f.debug("UI",` hasImages: ${!!(t&&t.length>0)}`),Je.logStdinState("UIController.handleSubmit.beforeCallback")),this.callbacks?.onSubmit(e,t),process.env.CLI_DEBUG==="1"&&(f.debug("UI","=== UIController.handleSubmit onSubmit returned ==="),Je.logStdinState("UIController.handleSubmit.afterCallback"))));}handleInterrupt(){if(process.env.CLI_DEBUG==="1"&&f.debug("UI","handleInterrupt called"),this.bottomBar.isPromptActive()){process.env.CLI_DEBUG==="1"&&f.debug("UI","Closing active prompt"),this.rejectPrompt(new Error("cancelled"));return}let e=this.callbacks?.isTaskRunning?.()??false;process.env.CLI_DEBUG==="1"&&f.debug("UI",`isTaskRunning: ${e}`),e?(process.env.CLI_DEBUG==="1"&&f.debug("UI","Calling onInterrupt callback"),process.stderr.write(`
1584
+ \u26A0\uFE0F \u4E2D\u65AD\u4EFB\u52A1 (ESC)...
1585
+ `),this.addInfo(j.red("\u23BF Interrupted")),this.callbacks?.onInterrupt(),this.lastEscAt=0):this.inputValue.length>0?(process.env.CLI_DEBUG==="1"&&f.debug("UI","Clearing input"),this.inputValue="",this.inputCursor=0,this.attachedImages=[],this.updateInputDisplay(),this.lastEscAt=0):(process.env.CLI_DEBUG==="1"&&f.debug("UI","No action needed"),this.lastEscAt=0);}handleTerminalError(e){if(this.terminalBroken)return;this.terminalBroken=true,Fe.pause();try{process.stderr.write(`
1586
+ \u26A0\uFE0F Terminal disconnected. Exiting...
1587
+ `);}catch{}setTimeout(()=>{this.exiting||this.requestExit("fatal");},1e3).unref?.();}requestExit(e){this.exiting||(this.exiting=true,process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] requestExit source=${e}
1588
+ `),this.callbacks?.onExit());}handleTab(){if(this.inputValue.startsWith("/")){this.showCommandAutocomplete();return}this.thinkingEnabled=!this.thinkingEnabled,this.bottomBar.setThinkingEnabled(this.thinkingEnabled),this.callbacks?.onToggleThinking&&this.callbacks.onToggleThinking(this.thinkingEnabled);let e=this.thinkingEnabled?j.cyan("on"):j.dim("off");this.addInfo(`Thinking ${e}`);}async showCommandAutocomplete(){let e=this.inputValue,t=[];if(this.options.getCompletions)t=this.options.getCompletions(e);else if(this.options.commandHints){let n=e.toLowerCase();t=this.options.commandHints.filter(r=>r.toLowerCase().startsWith(n)||r.toLowerCase().includes(n));}if(t.length===0){this.addInfo(j.dim("No matching commands"));return}if(t.length===1){this.inputValue=t[0],this.inputCursor=this.inputValue.length,this.updateInputDisplay();return}try{let n=t.map(i=>({title:i,value:i})),r=await this.promptSelect({message:"Commands",choices:n,hint:"Select a command"});r&&(this.inputValue=r,this.inputCursor=this.inputValue.length,this.updateInputDisplay());}catch{}}addToHistory(e){if(!e)return;this.history[this.history.length-1]!==e&&(this.history.push(e),this.history.length>200&&(this.history=this.history.slice(-200))),this.historyIndex=-1,this.historyDraft="";}historyPrev(){if(this.bottomBar.isPromptActive()){let e=this.bottomBar.getPrompt();if(e?.type==="select"&&e.choices){let t=Math.max(0,(e.selectedIndex||0)-1);this.updateSelectList(t);}return}this.history.length!==0&&(this.historyIndex===-1?(this.historyDraft=this.inputValue,this.historyIndex=this.history.length-1):this.historyIndex>0&&this.historyIndex--,this.inputValue=this.history[this.historyIndex]||"",this.inputCursor=this.inputValue.length,this.updateInputDisplay());}historyNext(){if(this.bottomBar.isPromptActive()){let e=this.bottomBar.getPrompt();if(e?.type==="select"&&e.choices){let t=e.choices.length-1,n=Math.min(t,(e.selectedIndex||0)+1);this.updateSelectList(n);}return}this.history.length===0||this.historyIndex===-1||(this.historyIndex++,this.historyIndex>=this.history.length?(this.historyIndex=-1,this.inputValue=this.historyDraft):this.inputValue=this.history[this.historyIndex]||"",this.inputCursor=this.inputValue.length,this.updateInputDisplay());}updateStatus(e,t){this.bottomBar.updateStatus(e,t);}updateProvider(e,t){this.options.provider=e,this.options.model=t,this.renderHeader(),this.renderer.flushSync();}streamingLineRow=0;lastPrintedLineCount=0;addTextDelta(e){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:t})=>{t.debug("UI",`addTextDelta: received ${e.length} chars, total now: ${this.streamingTextContent.length+e.length}`);}),this.streamingTextContent+=e,this.bottomBar.updateStatus(`Streaming... (${this.streamingTextContent.length} chars)`,"thinking");}updateStreamingPreview(){}printStreamingLines(){}renderCurrentStreamingLine(e){}completeTextStreaming(){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:e})=>{e.debug("UI",`completeTextStreaming called, content length: ${this.streamingTextContent.length}`);}),this.streamingTextContent&&(this.timelineRenderer.addEntry({type:"assistant",message:`Assistant response (${this.streamingTextContent.length} chars)`,details:this.streamingTextContent,timestamp:new Date,isComplete:true}),this.streamingTextContent="",this.lastPrintedLineCount=0,this.streamingTextId=null);}renderStreamingText(){}lastPrintedReasoningLineCount=0;addReasoningDelta(e){this.streamingReasoningContent+=e,this.bottomBar.updateStatus(`Thinking... (${this.streamingReasoningContent.length} chars)`,"thinking");}updateReasoningPreview(){}printReasoningLines(){}renderCurrentReasoningLine(e){}completeReasoningStreaming(){this.streamingReasoningContent&&(this.timelineRenderer.addEntry({type:"reasoning",message:`Reasoning (${this.streamingReasoningContent.length} chars)`,details:this.streamingReasoningContent,timestamp:new Date,isComplete:true}),this.streamingReasoningContent="",this.lastPrintedReasoningLineCount=0,this.streamingReasoningId=null);}resetStreamingState(){this.streamingTextContent="",this.streamingReasoningContent="",this.streamingTextId=null,this.streamingReasoningId=null,this.lastPrintedLineCount=0,this.lastPrintedReasoningLineCount=0,this.bottomBar.updateStreamingPreview("");}addUserMessage(e,t){this.timelineRenderer.addEntry({type:"user",message:e,timestamp:new Date});}addInfo(e,t){this.timelineRenderer.addEntry({type:"info",message:e,details:t,timestamp:new Date});}addError(e,t){this.timelineRenderer.addEntry({type:"error",message:e,details:t,timestamp:new Date});}addThinking(e){this.timelineRenderer.addEntry({type:"thinking",message:`iteration ${e}`,timestamp:new Date});}addToolCall(e,t){let n=t?JSON.stringify(t,null,2):void 0;this.timelineRenderer.addEntry({type:"tool_call",message:`Calling: ${e}`,details:n?`Args:
1589
+ ${n.slice(0,500)}${n.length>500?"...":""}`:void 0,timestamp:new Date});}addWriteFileCall(e,t){let n=t.split(`
1590
+ `),r=n.length,i=n.slice(0,15),o=String(Math.min(r,15)).length,a=[];a.push(j.dim(`+++ new: ${r} lines`)),a.push("");for(let l=0;l<i.length;l++){let c=String(l+1).padStart(o," ");a.push(j.bgRgb(20,50,20)(j.dim(`${c} `)+j.green(`+ ${i[l]}`)));}r>15&&a.push(j.dim(` ... (${r-15} more lines)`)),this.timelineRenderer.addEntry({type:"file_update",message:`Writing ${e} (${r} lines)`,details:a.join(`
1591
+ `),timestamp:new Date});}addEditFileCall(e,t,n,r){let i=t?t.split(`
1592
+ `):[],o=n?n.split(`
1593
+ `):[],a=r||1,l=[];l.push(j.dim(`\u2500\u2500\u2500 old: ${i.length} lines`)),l.push(j.dim(`+++ new: ${o.length} lines`)),l.push("");let c=Math.max(i.length,o.length),u=String(a+c).length;for(let d=0;d<c;d++){let p=a+d,m=String(p).padStart(u," "),h=i[d],g=o[d];h!==void 0&&l.push(j.bgRgb(60,20,20)(j.dim(`${m} `)+j.red(`- ${h}`))),g!==void 0&&l.push(j.bgRgb(20,50,20)(j.dim(`${m} `)+j.green(`+ ${g}`)));}this.timelineRenderer.addEntry({type:"file_update",message:`Editing ${e}${r?` @${r}`:""}`,details:l.join(`
1594
+ `),timestamp:new Date});}addToolResult(e,t){let n=t.length>500?`${t.slice(0,500)}...`:t;this.timelineRenderer.addEntry({type:"tool_result",message:`${e} completed`,details:n,timestamp:new Date});}addToolError(e,t){this.timelineRenderer.addEntry({type:"tool_error",message:`${e} failed`,details:t,timestamp:new Date});}addEditFileResult(e){let t=e.filePath.split("/").pop()||e.filePath;if(e.status==="completed"){let n=e.alreadyDone?`Edit already applied: ${t}`:`Edited ${t}${e.replacements&&e.replacements>1?` (${e.replacements} replacements)`:""}`;this.timelineRenderer.addEntry({type:"tool_result",message:n,details:e.summary||"",timestamp:new Date});}else this.timelineRenderer.addEntry({type:"tool_error",message:`Edit failed: ${t}`,details:e.error||e.summary||"Unknown error",timestamp:new Date});}startToolCallWithId(e,t,n,r){let i=this.timelineRenderer.addEntry({type:"tool_call",message:`Calling: ${t}`,details:r?.description||JSON.stringify(n,null,2)?.slice(0,500),timestamp:new Date,isStreaming:true});return this.runningToolMap.set(e,i),i}updateToolCallOutput(e,t,n){let r=this.runningToolMap.get(e);if(!r)return;let i=n?.preview||t.slice(0,500);this.timelineRenderer.updateEntry(r,{details:`Output:
1595
+ ${i}${n?.truncated?`
1596
+ ...(truncated)`:""}`});}completeToolCall(e,t){let n=this.runningToolMap.get(e);if(!n)return;let r=t.duration?` (${t.duration}ms)`:"";this.timelineRenderer.updateEntry(n,{message:t.success?`Tool completed${r}`:`Tool failed${r}`,details:t.error||t.summary,isStreaming:false}),this.runningToolMap.delete(e);}getRunningToolLogId(e){return this.runningToolMap.get(e)}updateTokenStats(e,t,n){this.tokens.inputTokens+=e,this.tokens.outputTokens+=t,this.tokens.totalTokens=this.tokens.inputTokens+this.tokens.outputTokens,n&&Object.assign(this.tokens,n),this.bottomBar.updateTokens(this.tokens);}setTokenStats(e,t,n){this.tokens.inputTokens=e,this.tokens.outputTokens=t,this.tokens.totalTokens=e+t,n&&Object.assign(this.tokens,n),this.bottomBar.updateTokens(this.tokens);}resetTokenStats(){let{contextWindow:e,pressure:t,warningLevel:n}=this.tokens;this.tokens={inputTokens:0,outputTokens:0,totalTokens:0,contextWindow:e,pressure:t,warningLevel:n},this.bottomBar.updateTokens(this.tokens);}getTokenStats(){return {...this.tokens}}startTaskTimer(){this.taskStartTime=Date.now(),this.taskDurationMs=0,this.bottomBar.startTimer(),this.durationInterval&&clearInterval(this.durationInterval),this.durationInterval=setInterval(()=>{this.taskStartTime&&(this.taskDurationMs=Date.now()-this.taskStartTime);},1e3),this.durationInterval.unref();}stopTaskTimer(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.taskStartTime&&(this.taskDurationMs=Date.now()-this.taskStartTime,this.taskStartTime=null),this.bottomBar.stopTimer();}updateTaskTokens(e,t=false){this.bottomBar.updateTaskTokens(e,t);}forceRenderBottomBar(){this.bottomBar.fullRender();}flushRenderScheduler(){Fe.forceFlush();}async promptText(e){return new Promise((t,n)=>{this.promptResolve=t,this.promptReject=n,this.inputValue=e.defaultValue||"",this.inputCursor=this.inputValue.length,this.bottomBar.setPrompt({type:"text",message:e.message,hint:e.hint,allowEmpty:e.allowEmpty}),this.bottomBar.updateInput(this.inputValue,this.inputCursor);})}selectOverlayVisible=false;selectScrollOffset=0;static MAX_VISIBLE_OPTIONS=20;pendingSelectOverlay=null;selectStack=[];async promptSelect(e){return new Promise((t,n)=>{this.promptResolve=t,this.promptReject=n;let r=e.initialValue?Math.max(0,e.choices.findIndex(i=>i.value===e.initialValue)):0;if(this.selectOverlayVisible){let i=this.bottomBar.getPrompt();i&&i.choices&&(this.selectStack.push({message:i.message,choices:i.choices,selectedIndex:i.selectedIndex||0,scrollOffset:this.selectScrollOffset}),process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:o})=>{o.debug("UI_V2",`Pushed to stack: "${i.message}", stack length now: ${this.selectStack.length}`);}));}if(this.bottomBar.setPrompt({type:"select",message:e.message,hint:e.hint,choices:e.choices,selectedIndex:r}),Fe.forceFlush(),this.compactMode&&this.bottomBar.isRenderLocked()){this.pendingSelectOverlay={message:e.message,choices:e.choices,selectedIndex:r};return}this.pendingSelectOverlay=null,this.showSelectOverlay(e.message,e.choices,r),this.compactMode&&this.bottomBar.lockRender();})}handleSelectBack(){if(process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:e})=>{e.debug("UI_V2",`handleSelectBack: stack length = ${this.selectStack.length}`);}),this.selectStack.length>0){let e=this.selectStack.pop();return this.selectScrollOffset=e.scrollOffset,this.showSelectOverlay(e.message,e.choices,e.selectedIndex),this.bottomBar.setPrompt({type:"select",message:e.message,choices:e.choices,selectedIndex:e.selectedIndex}),true}return false}clearSelectStack(){this.selectStack=[];}showSelectOverlay(e,t,n){this.bottomBar.isInitialRenderDone()||this.bottomBar.renderInitial(),this.compactMode&&!this.timelineRenderer.isBottomBarRenderedAfterTimeline()&&(this.bottomBar.unlockRender(),this.bottomBar.setRenderingAfterTimeline(true),this.bottomBar.fullRender(),Fe.forceFlush(),this.timelineRenderer.markBottomBarRendered()),this.selectOverlayVisible=true,this.selectScrollOffset=0,this.adjustScrollForSelection(n,t.length),this.renderSelectOverlay(e,t,n);}adjustScrollForSelection(e,t){let n=s.MAX_VISIBLE_OPTIONS;if(t<=n){this.selectScrollOffset=0;return}e<this.selectScrollOffset?this.selectScrollOffset=e:e>=this.selectScrollOffset+n&&(this.selectScrollOffset=e-n+1);}currentMenuLines=0;renderSelectOverlay(e,t,n){let r=this.layout.getLayout(),i=r.totalCols,o=s.MAX_VISIBLE_OPTIONS,a=Math.min(t.length,o),l=this.selectScrollOffset>0,c=this.selectScrollOffset+a<t.length,u=[];l&&u.push(j.dim(" \u2191 more"));for(let T=0;T<a;T++){let w=this.selectScrollOffset+T,L=t[w],B=w===n,I=B?j.cyan("\u276F "):" ",k=B?j.cyan.bold(L.title):L.title,R=L.description?j.dim(` - ${L.description}`):"",E=I+k+R,M=i-4,_=this.stripAnsi(E),W=this.getDisplayWidth(_),$=E;if(W>M){let A=0,G=0,N=_;for(;G<N.length&&A<M-3;){let J=N[G].codePointAt(0)||0;J>8192&&J<12288||J>=19968&&J<=40959||J>=12352&&J<=12447||J>=12448&&J<=12543||J>=44032&&J<=55215?A+=2:A+=1,G++;}let U=0,H=0;for(;H<G&&U<E.length;)if(E[U]==="\x1B"){for(;U<E.length&&!/[a-zA-Z]/.test(E[U]);)U++;U++;}else H++,U++;$=E.slice(0,U)+"...";}u.push(" "+$);}c&&u.push(j.dim(" \u2193 more"));let d=u.length;if(this.currentMenuLines=d,this.compactMode){process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:k})=>{k.debug("SELECT_OVERLAY","Rendering select overlay in compact mode",{totalLines:d,choices:t.length,selectedIndex:n});}),this.renderer.hideCursor(),this.renderer.append("\x1B[2B"),this.renderer.append("\r");let T=this.currentMenuLines||0,w=Math.max(d,T);process.env.CLI_DEBUG==="1"&&Promise.resolve().then(()=>(le(),$e)).then(({cliLogger:k})=>{k.debug("SELECT_OVERLAY","Reserving space for menu",{maxLinesToReserve:w,prevMenuLines:T,lines:u.slice(0,3)});});for(let k=0;k<w+1;k++)this.renderer.append(`
1597
+ `);this.renderer.append(`\x1B[${w}A`),this.renderer.append("\r");for(let k=0;k<w;k++)this.renderer.append("\x1B[2K"),k<d&&this.renderer.append(u[k]),k<w-1&&this.renderer.append(`
1598
+ \r`);this.renderer.append(`\x1B[${w+2}A`);let L=2,B=this.bottomBar.getInputCursor(),I=L+1+B;this.renderer.append(`\x1B[${I}G`),this.renderer.showCursor(),this.renderer.flushSync();return}let p=r.totalRows,m=this.layout.getMenuHeight(),g=d-m;if(g>0){let T=r.statusBar.startRow-1;for(let w=0;w<g;w++)this.renderer.moveTo(T,1),this.renderer.append(`
1599
+ `);this.renderer.flushSync();}this.renderer.resetScrollRegion();for(let T=r.statusBar.startRow;T<=p;T++)this.renderer.moveTo(T,1),this.renderer.append("\x1B[2K");this.renderer.flushSync();let y=Math.max(d,m);this.layout.setMenuHeight(y);let x=this.layout.getLayout();this.setupScrollRegion(),this.renderer.hideCursor(),this.bottomBar.fullRender();let S=x.inputBox.endRow+1;for(let T=0;T<d;T++)this.renderer.moveTo(S+T,1),this.renderer.append(u[T]);this.renderer.showCursor(),this.renderer.flushSync();}hideSelectOverlay(){if(!this.selectOverlayVisible)return;if(this.selectOverlayVisible=false,this.compactMode){if(this.currentMenuLines>0){this.renderer.hideCursor(),this.renderer.append("\x1B[3B"),this.renderer.append("\r");for(let c=0;c<this.currentMenuLines;c++)this.renderer.append("\x1B[2K"),c<this.currentMenuLines-1&&this.renderer.append("\x1B[1B");this.renderer.append(`\x1B[${this.currentMenuLines+2}A`);let o=2,a=this.bottomBar.getInputCursor(),l=o+1+a;this.renderer.append(`\x1B[${l}G`),this.renderer.showCursor(),this.renderer.flushSync();}this.selectScrollOffset=0,this.currentMenuLines=0;return}let e=this.layout.getLayout(),t=e.totalRows;this.renderer.resetScrollRegion();let n=e.inputBox.endRow+1;for(let o=n;o<=t;o++)this.renderer.moveTo(o,1),this.renderer.append("\x1B[2K");this.renderer.flushSync(),this.selectScrollOffset=0,this.currentMenuLines=0;let r=1,i=e.statusBar.startRow-1;this.renderer.setScrollRegion(r,i),this.renderer.flushSync(),this.bottomBar.fullRender();}updateSelectList(e){let t=this.bottomBar.getPrompt();if(!(!t||t.type!=="select"||!t.choices)){if(this.adjustScrollForSelection(e,t.choices.length),this.bottomBar.updatePromptSelection(e),Fe.forceFlush(),this.pendingSelectOverlay){this.pendingSelectOverlay.selectedIndex=e;return}this.compactMode&&this.bottomBar.unlockRender(),this.renderSelectOverlay(t.message,t.choices,e),this.compactMode&&this.bottomBar.lockRender();}}resolvePrompt(e){this.hideSelectOverlay(),this.clearSelectStack(),this.pendingSelectOverlay=null,this.compactMode&&this.bottomBar.unlockRender(),this.promptResolve&&this.promptResolve(e),this.promptResolve=null,this.promptReject=null,this.bottomBar.setPrompt(null),this.bottomBar.updateInput("",0),this.inputValue="",this.inputCursor=0;}rejectPrompt(e){this.hideSelectOverlay(),this.clearSelectStack(),this.pendingSelectOverlay=null,this.compactMode&&this.bottomBar.unlockRender(),this.promptReject&&this.promptReject(e),this.promptResolve=null,this.promptReject=null,this.bottomBar.setPrompt(null),this.bottomBar.updateInput("",0),this.inputValue="",this.inputCursor=0;}updateCodeGenerationPreview(e,t,n,r){let i=t.split(`
1600
+ `),o=i.length,a=i.slice(0,10),l=String(Math.min(o,10)).length,c=[];r&&(c.push(r),c.push("")),c.push(j.dim(`+++ new: ${o} lines`)),c.push("");for(let u=0;u<a.length;u++){let d=String(u+1).padStart(l," ");c.push(j.bgRgb(20,50,20)(j.dim(`${d} `)+j.green(`+ ${a[u]}`)));}o>10&&c.push(j.dim(` ... (${o-10} more lines)`)),this.timelineRenderer.addEntry({type:"file_update",message:`Generating ${e} (${o} lines)`,details:c.join(`
1601
+ `),timestamp:new Date,isStreaming:true});}completeCodeGenerationPreview(e,t){if(!t){this.timelineRenderer.addEntry({type:"file_update",message:`Generated ${e}`,timestamp:new Date,isComplete:true});return}let n=t.split(`
1602
+ `),r=n.length,i=n.slice(0,15),o=String(Math.min(r,15)).length,a=[];a.push(j.dim(`+++ new: ${r} lines`)),a.push("");for(let l=0;l<i.length;l++){let c=String(l+1).padStart(o," ");a.push(j.bgRgb(20,50,20)(j.dim(`${c} `)+j.green(`+ ${i[l]}`)));}r>15&&a.push(j.dim(` ... (${r-15} more lines)`)),this.timelineRenderer.addEntry({type:"file_update",message:`Generated ${e} (${r} lines)`,details:a.join(`
1603
+ `),timestamp:new Date,isComplete:true});}startEditFile(e,t,n,r,i,o,a){let l=[];o&&(l.push(o),l.push(""));let c=(u,d,p,m)=>{m&&l.push(j.dim(m)),l.push(j.dim(`\u2500\u2500\u2500 old: ${u.length} lines`)),l.push(j.dim(`+++ new: ${d.length} lines`)),l.push("");let h=Math.max(u.length,d.length),g=String(p+h).length;for(let y=0;y<h;y++){let x=p+y,S=String(x).padStart(g," "),T=u[y],w=d[y];T!==void 0&&l.push(j.bgRgb(60,20,20)(j.dim(`${S} `)+j.red(`- ${T}`))),w!==void 0&&l.push(j.bgRgb(20,50,20)(j.dim(`${S} `)+j.green(`+ ${w}`)));}};if(a&&a.length>0)a.forEach((u,d)=>{d>0&&l.push("");let p=`@@ hunk ${d+1} @${u.startLine}`,m=u.oldString?u.oldString.split(`
1604
+ `):[],h=u.newString?u.newString.split(`
1605
+ `):[];c(m,h,u.startLine||1,p);});else {let u=n?n.split(`
1606
+ `):[],d=r?r.split(`
1607
+ `):[];c(u,d,i||1);}this.timelineRenderer.addEntry({type:"file_update",message:`Editing ${e}${i?` @${i}`:""}`,details:l.join(`
1608
+ `),timestamp:new Date});}startWriteFile(e,t,n,r){let i=n.split(`
1609
+ `),o=[];r&&(o.push(r),o.push("")),o.push(j.dim(`+++ new file: ${i.length} lines`)),o.push("");let a=String(i.length).length,l=500,c=Math.min(i.length,l);for(let u=0;u<c;u++){let d=u+1,p=String(d).padStart(a," ");o.push(j.bgRgb(20,50,20)(j.dim(`${p} `)+j.green(`+ ${i[u]}`)));}i.length>l&&(o.push(""),o.push(j.dim(`... (${i.length-l} more lines omitted)`))),this.timelineRenderer.addEntry({type:"file_update",message:`Creating ${e}`,details:o.join(`
1610
+ `),timestamp:new Date});}parseCodeToDiff(e,t=true){return e.split(`
1611
+ `).map((n,r)=>({lineNumber:r+1,content:n,type:t?"added":"unchanged"}))}addFileUpdate(e,t,n,r){let i=t.filter(a=>a.type==="added").length,o=t.filter(a=>a.type==="removed").length;this.timelineRenderer.addEntry({type:"file_update",message:`Updated ${e} (+${i}/-${o})`,details:n,timestamp:new Date});}addBrowserDebugResult(e){this.timelineRenderer.addEntry({type:"browser_debug",message:`Browser Debug: ${e.url} (${e.status})`,details:e.summary||e.error,timestamp:new Date});}addWebSearchResult(e){let t=e.results?.slice(0,3).map(n=>n.title).join(", ")||"";this.timelineRenderer.addEntry({type:"web_search",message:`Web Search: "${e.query}"`,details:t?`Results: ${t}`:e.error,timestamp:new Date});}addWebFetchResult(e){this.timelineRenderer.addEntry({type:"web_fetch",message:`Web Fetch: ${e.url}`,details:e.contentPreview?.slice(0,200),timestamp:new Date});}addReadFileResult(e){this.timelineRenderer.addEntry({type:"readfile",message:`readfile: ${e.filePath}`,details:e.preview?.slice(0,500),timestamp:new Date});}addSearchResult(e){let t=[];e.pattern&&t.push(`pattern="${e.pattern}"`),e.filePath&&t.push(`path="${e.filePath}"`),e.mode&&t.push(`mode="${e.mode}"`),e.strategy&&t.push(`strategy="${e.strategy}"`),typeof e.regex=="boolean"&&t.push(`regex=${e.regex?"on":"off"}`),typeof e.caseInsensitive=="boolean"&&t.push(`case_insensitive=${e.caseInsensitive?"on":"off"}`),e.matchCount!==void 0&&t.push(`matches=${e.matchCount}`);let n=t.length>0?`${t.join(", ")}`:"Search";this.timelineRenderer.addEntry({type:"search",message:n,details:e.details,timestamp:new Date});}addSearchFilesResult(e){let t=[];e.pattern&&t.push(`pattern="${e.pattern}"`),e.path&&t.push(`path="${e.path}"`),e.mode&&t.push(`mode="${e.mode}"`),e.strategy&&t.push(`strategy="${e.strategy}"`),typeof e.regex=="boolean"&&t.push(`regex=${e.regex?"on":"off"}`),typeof e.caseInsensitive=="boolean"&&t.push(`case_insensitive=${e.caseInsensitive?"on":"off"}`),e.fileCount!==void 0&&t.push(`files=${e.fileCount}`);let n=t.length>0?`${t.join(", ")}`:"Search";this.timelineRenderer.addEntry({type:"search_files",message:n,timestamp:new Date});}formatSmartTreeList(e,t){if(!Array.isArray(e))return;let n=e.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>a.length>0);if(n.length===0)return "(none)";let r=n.slice(0,t),i=n.length-r.length,o=i>0?` ...(+${i} more)`:"";return `${r.join(", ")}${o}`}formatSmartTreeDetails(e){if(!e)return;let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return;let n;try{n=JSON.parse(t);}catch{return}if(!n||typeof n!="object"||Array.isArray(n)||!["path","project_types","root_dirs","modules","config_files","tip","error"].some(p=>Object.prototype.hasOwnProperty.call(n,p)))return;if(typeof n.error=="string"&&n.error.trim())return `error: ${n.error.trim()}`;let i=[],o=typeof n.path=="string"?n.path.trim():"";o&&i.push(`path: ${o}`);let a=this.formatSmartTreeList(n.project_types,6);a!==void 0&&i.push(`project_types: ${a}`);let l=this.formatSmartTreeList(n.root_dirs,12);l!==void 0&&i.push(`root_dirs: ${l}`);let c=this.formatSmartTreeList(n.modules,12);c!==void 0&&i.push(`modules: ${c}`);let u=this.formatSmartTreeList(n.config_files,8);u!==void 0&&i.push(`config_files: ${u}`);let d=typeof n.tip=="string"?n.tip.trim():"";if(d&&i.push(`tip: ${d}`),i.length!==0)return i.join(`
1612
+ `)}addShowTreeResult(e){let t=this.formatSmartTreeDetails(e.content),r=[`path="${e.path||"."}"`];e.mode&&e.mode!=="structure"&&r.push(`mode="${e.mode}"`),e.maxDepth!==void 0&&e.maxDepth!==null&&r.push(`depth=${e.maxDepth}`);let i=r.join(", ");if(t){let o=t.split(`
1613
+ `),a=[];for(let l of o)l.startsWith("project_types:")?a.push(l.replace("project_types:","").trim()):l.startsWith("root_dirs:")?a.push(l.replace("root_dirs:","\u{1F4C2}").trim()):l.startsWith("modules:")&&a.push(l.replace("modules:","\u{1F527}").trim());a.length>0&&(i=`${i} \u2022 ${a.join(" \u2022 ")}`);}else e.totalChars&&(i=`${i} (${e.totalChars} chars)`);this.timelineRenderer.addEntry({type:"show_tree",message:i,details:t??e.content?.slice(0,300),timestamp:new Date});}addCommandExecResult(e){this.timelineRenderer.addEntry({type:"command_exec",message:`$ ${e.command}`,details:e.output?.slice(0,500),timestamp:new Date});}addCodeExecResult(e){this.timelineRenderer.addEntry({type:"code_exec",message:`Code: ${e.toolName||"execute"}`,details:e.output?.slice(0,500),timestamp:new Date});}printCommandOutput(e){let t=this.layout.getLayout(),n=t.totalRows-t.bottomFixedHeight;this.renderer.moveTo(n,1),this.renderer.append("\x1B[2K"),this.renderer.append(e+`
1614
+ `),this.renderer.flushSync(),this.bottomBar.render();}printCommandOutputLines(e){let t=this.layout.getLayout(),n=t.totalRows-t.bottomFixedHeight;for(let r of e)this.renderer.moveTo(n,1),this.renderer.append("\x1B[2K"),this.renderer.append(r+`
1615
+ `);this.renderer.flushSync(),this.bottomBar.fullRender();}};function b(s){process.stdout.write(s+`
1616
+ `);}var $m=new Map,Jx=s=>{if(s.length===0)return {width:0,height:0};let e=$m.get(s);if(e)return e;let t=Hx(s),n=s.split(`
1617
+ `).length,r={width:t,height:n};return $m.set(s,r),r},dc=Jx;function xo(s,e,t){if(s.charAt(e)===" ")return e;let n=t?1:-1;for(let r=0;r<=3;r++){let i=e+r*n;if(s.charAt(i)===" ")return i}return e}function pc(s,e,t={}){let{position:n="end",space:r=false,preferTruncationOnSpace:i=false}=t,{truncationCharacter:o="\u2026"}=t;if(typeof s!="string")throw new TypeError(`Expected \`input\` to be a string, got ${typeof s}`);if(typeof e!="number")throw new TypeError(`Expected \`columns\` to be a number, got ${typeof e}`);if(e<1)return "";let a=vo(s);if(a<=e)return s;if(e===1)return o;let l={ESC:27,LEFT_BRACKET:91,LETTER_M:109},c=h=>h>=48&&h<=57||h===59;function u(h){let g=0;for(;g+2<h.length&&h.codePointAt(g)===l.ESC&&h.codePointAt(g+1)===l.LEFT_BRACKET;){let y=g+2;for(;y<h.length&&c(h.codePointAt(y));)y++;if(y<h.length&&h.codePointAt(y)===l.LETTER_M){g=y+1;continue}break}return g}function d(h){let g=h.length;for(;g>1&&h.codePointAt(g-1)===l.LETTER_M;){let y=g-2;for(;y>=0&&c(h.codePointAt(y));)y--;if(y>=1&&h.codePointAt(y-1)===l.ESC&&h.codePointAt(y)===l.LEFT_BRACKET){g=y-1;continue}break}return g}function p(h,g){let y=d(h);return y===h.length?h+g:h.slice(0,y)+g+h.slice(y)}function m(h,g){let y=u(g);return y===0?h+g:g.slice(0,y)+h+g.slice(y)}if(n==="start"){if(i){let g=xo(s,a-e+1,true),y=_n(s,g,a).trim();return m(o,y)}r&&(o+=" ");let h=_n(s,a-e+vo(o),a);return m(o,h)}if(n==="middle"){r&&(o=` ${o} `);let h=Math.floor(e/2);if(i){let g=xo(s,h),y=xo(s,a-(e-h)+1,true);return _n(s,0,g)+o+_n(s,y,a).trim()}return _n(s,0,h)+o+_n(s,a-(e-h)+vo(o),a)}if(n==="end"){if(i){let g=xo(s,e-1),y=_n(s,0,g);return p(y,o)}r&&(o=` ${o}`);let h=_n(s,0,e-vo(o));return p(h,o)}throw new Error(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${n}`)}var Nm={},qx=(s,e,t)=>{let n=s+String(e)+String(t),r=Nm[n];if(r)return r;let i=s;if(t==="wrap"&&(i=zx(s,e,{trim:false,hard:true})),t.startsWith("truncate")){let o="end";t==="truncate-middle"&&(o="middle"),t==="truncate-start"&&(o="start"),i=pc(s,e,{position:o});}return Nm[n]=i,i},So=qx;var Um=s=>{let e="";for(let t=0;t<s.childNodes.length;t++){let n=s.childNodes[t];if(n===void 0)continue;let r="";n.nodeName==="#text"?r=n.nodeValue:((n.nodeName==="ink-text"||n.nodeName==="ink-virtual-text")&&(r=Um(n)),r.length>0&&typeof n.internal_transform=="function"&&(r=n.internal_transform(r,t))),e+=r;}return e},Br=Um;var _o=s=>{let e={nodeName:s,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:s==="ink-virtual-text"?void 0:ae.Node.create(),internal_accessibility:{}};return s==="ink-text"&&e.yogaNode?.setMeasureFunc(Vx.bind(null,e)),e},To=(s,e)=>{e.parentNode&&jr(e.parentNode,e),e.parentNode=s,s.childNodes.push(e),e.yogaNode&&s.yogaNode?.insertChild(e.yogaNode,s.yogaNode.getChildCount()),(s.nodeName==="ink-text"||s.nodeName==="ink-virtual-text")&&wo(s);},mc=(s,e,t)=>{e.parentNode&&jr(e.parentNode,e),e.parentNode=s;let n=s.childNodes.indexOf(t);if(n>=0){s.childNodes.splice(n,0,e),e.yogaNode&&s.yogaNode?.insertChild(e.yogaNode,n);return}s.childNodes.push(e),e.yogaNode&&s.yogaNode?.insertChild(e.yogaNode,s.yogaNode.getChildCount()),(s.nodeName==="ink-text"||s.nodeName==="ink-virtual-text")&&wo(s);},jr=(s,e)=>{e.yogaNode&&e.parentNode?.yogaNode?.removeChild(e.yogaNode),e.parentNode=void 0;let t=s.childNodes.indexOf(e);t>=0&&s.childNodes.splice(t,1),(s.nodeName==="ink-text"||s.nodeName==="ink-virtual-text")&&wo(s);},hc=(s,e,t)=>{if(e==="internal_accessibility"){s.internal_accessibility=t;return}s.attributes[e]=t;},fc=(s,e)=>{s.style=e;},Fm=s=>{let e={nodeName:"#text",nodeValue:s,yogaNode:void 0,parentNode:void 0,style:{}};return Gr(e,s),e},Vx=function(s,e){let t=s.nodeName==="#text"?s.nodeValue:Br(s),n=dc(t);if(n.width<=e||n.width>=1&&e>0&&e<1)return n;let r=s.style?.textWrap??"wrap",i=So(t,e,r);return dc(i)},Bm=s=>{if(s?.parentNode)return s.yogaNode??Bm(s.parentNode)},wo=s=>{Bm(s)?.markDirty();},Gr=(s,e)=>{typeof e!="string"&&(e=String(e)),s.nodeValue=e,wo(s);};var Xx=(s,e)=>{"position"in e&&s.setPositionType(e.position==="absolute"?ae.POSITION_TYPE_ABSOLUTE:ae.POSITION_TYPE_RELATIVE);},Zx=(s,e)=>{"margin"in e&&s.setMargin(ae.EDGE_ALL,e.margin??0),"marginX"in e&&s.setMargin(ae.EDGE_HORIZONTAL,e.marginX??0),"marginY"in e&&s.setMargin(ae.EDGE_VERTICAL,e.marginY??0),"marginLeft"in e&&s.setMargin(ae.EDGE_START,e.marginLeft||0),"marginRight"in e&&s.setMargin(ae.EDGE_END,e.marginRight||0),"marginTop"in e&&s.setMargin(ae.EDGE_TOP,e.marginTop||0),"marginBottom"in e&&s.setMargin(ae.EDGE_BOTTOM,e.marginBottom||0);},Qx=(s,e)=>{"padding"in e&&s.setPadding(ae.EDGE_ALL,e.padding??0),"paddingX"in e&&s.setPadding(ae.EDGE_HORIZONTAL,e.paddingX??0),"paddingY"in e&&s.setPadding(ae.EDGE_VERTICAL,e.paddingY??0),"paddingLeft"in e&&s.setPadding(ae.EDGE_LEFT,e.paddingLeft||0),"paddingRight"in e&&s.setPadding(ae.EDGE_RIGHT,e.paddingRight||0),"paddingTop"in e&&s.setPadding(ae.EDGE_TOP,e.paddingTop||0),"paddingBottom"in e&&s.setPadding(ae.EDGE_BOTTOM,e.paddingBottom||0);},eS=(s,e)=>{"flexGrow"in e&&s.setFlexGrow(e.flexGrow??0),"flexShrink"in e&&s.setFlexShrink(typeof e.flexShrink=="number"?e.flexShrink:1),"flexWrap"in e&&(e.flexWrap==="nowrap"&&s.setFlexWrap(ae.WRAP_NO_WRAP),e.flexWrap==="wrap"&&s.setFlexWrap(ae.WRAP_WRAP),e.flexWrap==="wrap-reverse"&&s.setFlexWrap(ae.WRAP_WRAP_REVERSE)),"flexDirection"in e&&(e.flexDirection==="row"&&s.setFlexDirection(ae.FLEX_DIRECTION_ROW),e.flexDirection==="row-reverse"&&s.setFlexDirection(ae.FLEX_DIRECTION_ROW_REVERSE),e.flexDirection==="column"&&s.setFlexDirection(ae.FLEX_DIRECTION_COLUMN),e.flexDirection==="column-reverse"&&s.setFlexDirection(ae.FLEX_DIRECTION_COLUMN_REVERSE)),"flexBasis"in e&&(typeof e.flexBasis=="number"?s.setFlexBasis(e.flexBasis):typeof e.flexBasis=="string"?s.setFlexBasisPercent(Number.parseInt(e.flexBasis,10)):s.setFlexBasis(Number.NaN)),"alignItems"in e&&((e.alignItems==="stretch"||!e.alignItems)&&s.setAlignItems(ae.ALIGN_STRETCH),e.alignItems==="flex-start"&&s.setAlignItems(ae.ALIGN_FLEX_START),e.alignItems==="center"&&s.setAlignItems(ae.ALIGN_CENTER),e.alignItems==="flex-end"&&s.setAlignItems(ae.ALIGN_FLEX_END)),"alignSelf"in e&&((e.alignSelf==="auto"||!e.alignSelf)&&s.setAlignSelf(ae.ALIGN_AUTO),e.alignSelf==="flex-start"&&s.setAlignSelf(ae.ALIGN_FLEX_START),e.alignSelf==="center"&&s.setAlignSelf(ae.ALIGN_CENTER),e.alignSelf==="flex-end"&&s.setAlignSelf(ae.ALIGN_FLEX_END)),"justifyContent"in e&&((e.justifyContent==="flex-start"||!e.justifyContent)&&s.setJustifyContent(ae.JUSTIFY_FLEX_START),e.justifyContent==="center"&&s.setJustifyContent(ae.JUSTIFY_CENTER),e.justifyContent==="flex-end"&&s.setJustifyContent(ae.JUSTIFY_FLEX_END),e.justifyContent==="space-between"&&s.setJustifyContent(ae.JUSTIFY_SPACE_BETWEEN),e.justifyContent==="space-around"&&s.setJustifyContent(ae.JUSTIFY_SPACE_AROUND),e.justifyContent==="space-evenly"&&s.setJustifyContent(ae.JUSTIFY_SPACE_EVENLY));},tS=(s,e)=>{"width"in e&&(typeof e.width=="number"?s.setWidth(e.width):typeof e.width=="string"?s.setWidthPercent(Number.parseInt(e.width,10)):s.setWidthAuto()),"height"in e&&(typeof e.height=="number"?s.setHeight(e.height):typeof e.height=="string"?s.setHeightPercent(Number.parseInt(e.height,10)):s.setHeightAuto()),"minWidth"in e&&(typeof e.minWidth=="string"?s.setMinWidthPercent(Number.parseInt(e.minWidth,10)):s.setMinWidth(e.minWidth??0)),"minHeight"in e&&(typeof e.minHeight=="string"?s.setMinHeightPercent(Number.parseInt(e.minHeight,10)):s.setMinHeight(e.minHeight??0));},nS=(s,e)=>{"display"in e&&s.setDisplay(e.display==="flex"?ae.DISPLAY_FLEX:ae.DISPLAY_NONE);},sS=(s,e)=>{if("borderStyle"in e){let t=e.borderStyle?1:0;e.borderTop!==false&&s.setBorder(ae.EDGE_TOP,t),e.borderBottom!==false&&s.setBorder(ae.EDGE_BOTTOM,t),e.borderLeft!==false&&s.setBorder(ae.EDGE_LEFT,t),e.borderRight!==false&&s.setBorder(ae.EDGE_RIGHT,t);}},rS=(s,e)=>{"gap"in e&&s.setGap(ae.GUTTER_ALL,e.gap??0),"columnGap"in e&&s.setGap(ae.GUTTER_COLUMN,e.columnGap??0),"rowGap"in e&&s.setGap(ae.GUTTER_ROW,e.rowGap??0);},iS=(s,e={})=>{Xx(s,e),Zx(s,e),Qx(s,e),eS(s,e),tS(s,e),nS(s,e),sS(s,e),rS(s,e);},gc=iS;if(Oo.env.DEV==="true")try{await Promise.resolve().then(()=>(Gm(),jm));}catch(s){if(s.code==="ERR_MODULE_NOT_FOUND")console.warn(`
1618
+ The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`,
1619
+ but this failed as it was not installed. Debugging with React Devtools requires it.
1620
+
1621
+ To install use this command:
1622
+
1623
+ $ npm install --save-dev react-devtools-core
1624
+ `.trim()+`
1625
+ `);else throw s}var Hm=(s,e)=>{if(s===e)return;if(!s)return e;let t={},n=false;for(let r of Object.keys(s))(e?!Object.hasOwn(e,r):true)&&(t[r]=void 0,n=true);if(e)for(let r of Object.keys(e))e[r]!==s[r]&&(t[r]=e[r],n=true);return n?t:void 0},Jm=s=>{s?.unsetMeasureFunc(),s?.freeRecursive();},ko=NoEventPriority,yc,tn=lS({getRootHostContext:()=>({isInsideText:false}),prepareForCommit:()=>null,preparePortalMount:()=>null,clearContainer:()=>false,resetAfterCommit(s){if(typeof s.onComputeLayout=="function"&&s.onComputeLayout(),s.isStaticDirty){s.isStaticDirty=false,typeof s.onImmediateRender=="function"&&s.onImmediateRender();return}typeof s.onRender=="function"&&s.onRender();},getChildHostContext(s,e){let t=s.isInsideText,n=e==="ink-text"||e==="ink-virtual-text";return t===n?s:{isInsideText:n}},shouldSetTextContent:()=>false,createInstance(s,e,t,n){if(n.isInsideText&&s==="ink-box")throw new Error("<Box> can\u2019t be nested inside <Text> component");let r=s==="ink-text"&&n.isInsideText?"ink-virtual-text":s,i=_o(r);for(let[o,a]of Object.entries(e))if(o!=="children"){if(o==="style"){fc(i,a),i.yogaNode&&gc(i.yogaNode,a);continue}if(o==="internal_transform"){i.internal_transform=a;continue}if(o==="internal_static"){yc=t,i.internal_static=true,t.isStaticDirty=true,t.staticNode=i;continue}hc(i,o,a);}return i},createTextInstance(s,e,t){if(!t.isInsideText)throw new Error(`Text string "${s}" must be rendered inside <Text> component`);return Fm(s)},resetTextContent(){},hideTextInstance(s){Gr(s,"");},unhideTextInstance(s,e){Gr(s,e);},getPublicInstance:s=>s,hideInstance(s){s.yogaNode?.setDisplay(ae.DISPLAY_NONE);},unhideInstance(s){s.yogaNode?.setDisplay(ae.DISPLAY_FLEX);},appendInitialChild:To,appendChild:To,insertBefore:mc,finalizeInitialChildren(){return false},isPrimaryRenderer:true,supportsMutation:true,supportsPersistence:false,supportsHydration:false,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},getInstanceFromNode:()=>null,prepareScopeUpdate(){},getInstanceFromScope:()=>null,appendChildToContainer:To,insertInContainerBefore:mc,removeChildFromContainer(s,e){jr(s,e),Jm(e.yogaNode);},commitUpdate(s,e,t,n){yc&&s.internal_static&&(yc.isStaticDirty=true);let r=Hm(t,n),i=Hm(t.style,n.style);if(!(!r&&!i)){if(r)for(let[o,a]of Object.entries(r)){if(o==="style"){fc(s,a);continue}if(o==="internal_transform"){s.internal_transform=a;continue}if(o==="internal_static"){s.internal_static=true;continue}hc(s,o,a);}i&&s.yogaNode&&gc(s.yogaNode,i);}},commitTextUpdate(s,e,t){Gr(s,t);},removeChild(s,e){jr(s,e),Jm(e.yogaNode);},setCurrentUpdatePriority(s){ko=s;},getCurrentUpdatePriority:()=>ko,resolveUpdatePriority(){return ko!==NoEventPriority?ko:DefaultEventPriority},maySuspendCommit(){return false},NotPendingTransition:void 0,HostTransitionContext:createContext(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return false},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return -1.1},preloadInstance(){return true},startSuspendingCommit(){},suspendInstance(){},waitForCommitToBeReady(){return null}});function bc(s,e=1,t={}){let{indent:n=" ",includeEmptyLines:r=false}=t;if(typeof s!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof s}\``);if(typeof e!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof e}\``);if(e<0)throw new RangeError(`Expected \`count\` to be at least 0, got \`${e}\``);if(typeof n!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof n}\``);if(e===0)return s;let i=r?/^/gm:/^(?!\s*$)/gm;return s.replace(i,n.repeat(e))}var dS=s=>s.getComputedWidth()-s.getComputedPadding(ae.EDGE_LEFT)-s.getComputedPadding(ae.EDGE_RIGHT)-s.getComputedBorder(ae.EDGE_LEFT)-s.getComputedBorder(ae.EDGE_RIGHT),qm=dS;var Xm=yu(Ym());var mS=/^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/,hS=/^ansi256\(\s?(\d+)\s?\)$/,fS=s=>s in j,gS=(s,e,t)=>{if(!e)return s;if(fS(e)){if(t==="foreground")return j[e](s);let n=`bg${e[0].toUpperCase()+e.slice(1)}`;return j[n](s)}if(e.startsWith("#"))return t==="foreground"?j.hex(e)(s):j.bgHex(e)(s);if(e.startsWith("ansi256")){let n=hS.exec(e);if(!n)return s;let r=Number(n[1]);return t==="foreground"?j.ansi256(r)(s):j.bgAnsi256(r)(s)}if(e.startsWith("rgb")){let n=mS.exec(e);if(!n)return s;let r=Number(n[1]),i=Number(n[2]),o=Number(n[3]);return t==="foreground"?j.rgb(r,i,o)(s):j.bgRgb(r,i,o)(s)}return s},Ut=gS;var yS=(s,e,t,n)=>{if(t.style.borderStyle){let r=t.yogaNode.getComputedWidth(),i=t.yogaNode.getComputedHeight(),o=typeof t.style.borderStyle=="string"?Xm.default[t.style.borderStyle]:t.style.borderStyle,a=t.style.borderTopColor??t.style.borderColor,l=t.style.borderBottomColor??t.style.borderColor,c=t.style.borderLeftColor??t.style.borderColor,u=t.style.borderRightColor??t.style.borderColor,d=t.style.borderTopDimColor??t.style.borderDimColor,p=t.style.borderBottomDimColor??t.style.borderDimColor,m=t.style.borderLeftDimColor??t.style.borderDimColor,h=t.style.borderRightDimColor??t.style.borderDimColor,g=t.style.borderTop!==false,y=t.style.borderBottom!==false,x=t.style.borderLeft!==false,S=t.style.borderRight!==false,T=r-(x?1:0)-(S?1:0),w=g?Ut((x?o.topLeft:"")+o.top.repeat(T)+(S?o.topRight:""),a,"foreground"):void 0;g&&d&&(w=j.dim(w));let L=i;g&&(L-=1),y&&(L-=1);let B=(Ut(o.left,c,"foreground")+`
1626
+ `).repeat(L);m&&(B=j.dim(B));let I=(Ut(o.right,u,"foreground")+`
1627
+ `).repeat(L);h&&(I=j.dim(I));let k=y?Ut((x?o.bottomLeft:"")+o.bottom.repeat(T)+(S?o.bottomRight:""),l,"foreground"):void 0;y&&p&&(k=j.dim(k));let R=g?1:0;w&&n.write(s,e,w,{transformers:[]}),x&&n.write(s,e+R,B,{transformers:[]}),S&&n.write(s+r-1,e+R,I,{transformers:[]}),k&&n.write(s,e+i-1,k,{transformers:[]});}},Zm=yS;var bS=(s,e,t,n)=>{if(!t.style.backgroundColor)return;let r=t.yogaNode.getComputedWidth(),i=t.yogaNode.getComputedHeight(),o=t.style.borderStyle&&t.style.borderLeft!==false?1:0,a=t.style.borderStyle&&t.style.borderRight!==false?1:0,l=t.style.borderStyle&&t.style.borderTop!==false?1:0,c=t.style.borderStyle&&t.style.borderBottom!==false?1:0,u=r-o-a,d=i-l-c;if(!(u>0&&d>0))return;let p=Ut(" ".repeat(u),t.style.backgroundColor,"background");for(let m=0;m<d;m++)n.write(s+o,e+l+m,p,{transformers:[]});},Qm=bS;var xS=(s,e)=>{let t=s.childNodes[0]?.yogaNode;if(t){let n=t.getComputedLeft(),r=t.getComputedTop();e=`
1628
+ `.repeat(r)+bc(e,n);}return e},Io=(s,e={})=>{if(e.skipStaticElements&&s.internal_static||s.yogaNode?.getDisplay()===ae.DISPLAY_NONE)return "";let t="";if(s.nodeName==="ink-text")t=Br(s);else if(s.nodeName==="ink-box"||s.nodeName==="ink-root"){let n=s.style.flexDirection==="row"||s.style.flexDirection==="row-reverse"?" ":`
1629
+ `;t=(s.style.flexDirection==="row-reverse"||s.style.flexDirection==="column-reverse"?[...s.childNodes].reverse():[...s.childNodes]).map(i=>Io(i,{parentRole:s.internal_accessibility?.role,skipStaticElements:e.skipStaticElements})).filter(Boolean).join(n);}if(s.internal_accessibility){let{role:n,state:r}=s.internal_accessibility;if(r){let o=Object.keys(r).filter(a=>r[a]).join(", ");o&&(t=`(${o}) ${t}`);}n&&n!==e.parentRole&&(t=`${n}: ${t}`);}return t},eh=(s,e,t)=>{let{offsetX:n=0,offsetY:r=0,transformers:i=[],skipStaticElements:o}=t;if(o&&s.internal_static)return;let{yogaNode:a}=s;if(a){if(a.getDisplay()===ae.DISPLAY_NONE)return;let l=n+a.getComputedLeft(),c=r+a.getComputedTop(),u=i;if(typeof s.internal_transform=="function"&&(u=[s.internal_transform,...i]),s.nodeName==="ink-text"){let p=Br(s);if(p.length>0){let m=Hx(p),h=qm(a);if(m>h){let g=s.style.textWrap??"wrap";p=So(p,h,g);}p=xS(s,p),e.write(l,c,p,{transformers:u});}return}let d=false;if(s.nodeName==="ink-box"){Qm(l,c,s,e),Zm(l,c,s,e);let p=s.style.overflowX==="hidden"||s.style.overflow==="hidden",m=s.style.overflowY==="hidden"||s.style.overflow==="hidden";if(p||m){let h=p?l+a.getComputedBorder(ae.EDGE_LEFT):void 0,g=p?l+a.getComputedWidth()-a.getComputedBorder(ae.EDGE_RIGHT):void 0,y=m?c+a.getComputedBorder(ae.EDGE_TOP):void 0,x=m?c+a.getComputedHeight()-a.getComputedBorder(ae.EDGE_BOTTOM):void 0;e.clip({x1:h,x2:g,y1:y,y2:x}),d=true;}}if(s.nodeName==="ink-root"||s.nodeName==="ink-box"){for(let p of s.childNodes)eh(p,e,{offsetX:l,offsetY:c,transformers:u,skipStaticElements:o});d&&e.unclip();}}},xc=eh;var vs=class{width;height;operations=[];constructor(e){let{width:t,height:n}=e;this.width=t,this.height=n;}write(e,t,n,r){let{transformers:i}=r;n&&this.operations.push({type:"write",x:e,y:t,text:n,transformers:i});}clip(e){this.operations.push({type:"clip",clip:e});}unclip(){this.operations.push({type:"unclip"});}get(){let e=[];for(let r=0;r<this.height;r++){let i=[];for(let o=0;o<this.width;o++)i.push({type:"char",value:" ",fullWidth:false,styles:[]});e.push(i);}let t=[];for(let r of this.operations)if(r.type==="clip"&&t.push(r.clip),r.type==="unclip"&&t.pop(),r.type==="write"){let{text:i,transformers:o}=r,{x:a,y:l}=r,c=i.split(`
1630
+ `),u=t.at(-1);if(u){let p=typeof u?.x1=="number"&&typeof u?.x2=="number",m=typeof u?.y1=="number"&&typeof u?.y2=="number";if(p){let h=Hx(i);if(a+h<u.x1||a>u.x2)continue}if(m){let h=c.length;if(l+h<u.y1||l>u.y2)continue}if(p&&(c=c.map(h=>{let g=a<u.x1?u.x1-a:0,y=vo(h),x=a+y>u.x2?u.x2-a:y;return _n(h,g,x)}),a<u.x1&&(a=u.x1)),m){let h=l<u.y1?u.y1-l:0,g=c.length,y=l+g>u.y2?u.y2-l:g;c=c.slice(h,y),l<u.y1&&(l=u.y1);}}let d=0;for(let[p,m]of c.entries()){let h=e[l+d];if(!h)continue;for(let x of o)m=x(m,p);let g=styledCharsFromTokens(tokenize(m)),y=a;for(let x of g){h[y]=x;let S=Math.max(1,vo(x.value));if(S>1)for(let T=1;T<S;T++)h[y+T]={type:"char",value:"",fullWidth:false,styles:x.styles};y+=S;}d++;}}return {output:e.map(r=>{let i=r.filter(o=>o!==void 0);return styledCharsToString(i).trimEnd()}).join(`
1631
+ `),height:e.length}}};var CS=(s,e)=>{if(s.yogaNode){if(e){let o=Io(s,{skipStaticElements:true}),a=o===""?0:o.split(`
1632
+ `).length,l="";return s.staticNode&&(l=Io(s.staticNode,{skipStaticElements:false})),{output:o,outputHeight:a,staticOutput:l?`${l}
1633
+ `:""}}let t=new vs({width:s.yogaNode.getComputedWidth(),height:s.yogaNode.getComputedHeight()});xc(s,t,{skipStaticElements:true});let n;if(s.staticNode?.yogaNode&&s.staticNode.childNodes&&s.staticNode.childNodes.length>0){let a=s.staticNode.yogaNode.getComputedWidth(),l=s.staticNode.yogaNode.getComputedHeight();n=new vs({width:a,height:l}),xc(s.staticNode,n,{skipStaticElements:false});}let{output:r,height:i}=t.get();return {output:r,outputHeight:i,staticOutput:n?`${n.get().output}
1634
+ `:""}}return {output:"",outputHeight:0,staticOutput:""}},nh=CS;var ES=(s,{showCursor:e=false}={})=>{let t=0,n="",r=false,i=o=>{!e&&!r&&(Ro.hide(),r=true);let a=o+`
1635
+ `;a!==n&&(n=a,s.write(Ft.eraseLines(t)+a),t=a.split(`
1636
+ `).length);};return i.clear=()=>{s.write(Ft.eraseLines(t)),n="",t=0;},i.done=()=>{n="",t=0,e||(Ro.show(),r=false);},i.sync=o=>{let a=o+`
1637
+ `;n=a,t=a.split(`
1638
+ `).length;},i},IS=(s,{showCursor:e=false}={})=>{let t=[],n="",r=false,i=o=>{!e&&!r&&(Ro.hide(),r=true);let a=o+`
1639
+ `;if(a===n)return;let l=t.length,c=a.split(`
1640
+ `),u=c.length,d=u-1;if(a===`
1641
+ `||n.length===0){s.write(Ft.eraseLines(l)+a),n=a,t=c;return}let p=[];u<l?p.push(Ft.eraseLines(l-u+1),Ft.cursorUp(d)):p.push(Ft.cursorUp(l-1));for(let m=0;m<d;m++){if(c[m]===t[m]){p.push(Ft.cursorNextLine);continue}p.push(Ft.cursorTo(0)+c[m]+Ft.eraseEndLine+`
1642
+ `);}s.write(p.join("")),n=a,t=c;};return i.clear=()=>{s.write(Ft.eraseLines(t.length)),n="",t=[];},i.done=()=>{n="",t=[],e||(Ro.show(),r=false);},i.sync=o=>{let a=o+`
1643
+ `;n=a,t=a.split(`
1644
+ `);},i},RS=(s,{showCursor:e=false,incremental:t=false}={})=>t?IS(s,{showCursor:e}):ES(s,{showCursor:e}),PS={create:RS},sh=PS;var AS=new WeakMap,xs=AS;var rh=createContext({exit(){}});rh.displayName="InternalAppContext";var Sc=rh;var ih=createContext({stdin:Oo.stdin,internal_eventEmitter:new EventEmitter,setRawMode(){},isRawModeSupported:false,internal_exitOnCtrlC:true});ih.displayName="InternalStdinContext";var Po=ih;var oh=createContext({stdout:Oo.stdout,write(){}});oh.displayName="InternalStdoutContext";var _c=oh;var ah=createContext({stderr:Oo.stderr,write(){}});ah.displayName="InternalStderrContext";var Tc=ah;var lh=createContext({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});lh.displayName="InternalFocusContext";var Ao=lh;var jS=(s,e=2)=>s.replace(/^\t+/gm,t=>" ".repeat(t.length*e)),ch=jS;var GS=(s,e)=>{let t=[],n=s-e,r=s+e;for(let i=n;i<=r;i++)t.push(i);return t},WS=(s,e,t={})=>{var n;if(typeof s!="string")throw new TypeError("Source code is missing.");if(!e||e<1)throw new TypeError("Line number must start from `1`.");let r=ch(s).split(/\r?\n/);if(!(e>r.length))return GS(e,(n=t.around)!==null&&n!==void 0?n:3).filter(i=>r[i-1]!==void 0).map(i=>({line:i,value:r[i-1]}))},uh=WS;var Tn=createContext({isScreenReaderEnabled:false});var Mo=createContext(void 0);var dh=forwardRef(({children:s,backgroundColor:e,"aria-label":t,"aria-hidden":n,"aria-role":r,"aria-state":i,...o},a)=>{let{isScreenReaderEnabled:l}=useContext(Tn),c=t?Z.createElement("ink-text",null,t):void 0;if(l&&n)return null;let u=Z.createElement("ink-box",{ref:a,style:{flexWrap:"nowrap",flexDirection:"row",flexGrow:0,flexShrink:1,...o,backgroundColor:e,overflowX:o.overflowX??o.overflow??"visible",overflowY:o.overflowY??o.overflow??"visible"},internal_accessibility:{role:r,state:i}},l&&c?c:s);return e?Z.createElement(Mo.Provider,{value:e},u):u});dh.displayName="Box";var F=dh;function C({color:s,backgroundColor:e,dimColor:t=false,bold:n=false,italic:r=false,underline:i=false,strikethrough:o=false,inverse:a=false,wrap:l="wrap",children:c,"aria-label":u,"aria-hidden":d=false}){let{isScreenReaderEnabled:p}=useContext(Tn),m=useContext(Mo),h=p&&u?u:c;if(h==null)return null;let g=y=>{t&&(y=j.dim(y)),s&&(y=Ut(y,s,"foreground"));let x=e??m;return x&&(y=Ut(y,x,"background")),n&&(y=j.bold(y)),r&&(y=j.italic(y)),i&&(y=j.underline(y)),o&&(y=j.strikethrough(y)),a&&(y=j.inverse(y)),y};return p&&d?null:Z.createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:l},internal_transform:g},p&&u?u:c)}var kc=s=>s?.replace(`file://${cwd()}/`,""),hh=new mh({cwd:cwd(),internals:mh.nodeInternals()});function Cc({error:s}){let e=s.stack?s.stack.split(`
1645
+ `).slice(1):void 0,t=e?hh.parseLine(e[0]):void 0,n=kc(t?.file),r,i=0;if(n&&t?.line&&an.existsSync(n)){let o=an.readFileSync(n,"utf8");if(r=uh(o,t.line),r)for(let{line:a}of r)i=Math.max(i,String(a).length);}return Z.createElement(F,{flexDirection:"column",padding:1},Z.createElement(F,null,Z.createElement(C,{backgroundColor:"red",color:"white"}," ","ERROR"," "),Z.createElement(C,null," ",s.message)),t&&n&&Z.createElement(F,{marginTop:1},Z.createElement(C,{dimColor:true},n,":",t.line,":",t.column)),t&&r&&Z.createElement(F,{marginTop:1,flexDirection:"column"},r.map(({line:o,value:a})=>Z.createElement(F,{key:o},Z.createElement(F,{width:i+1},Z.createElement(C,{dimColor:o!==t.line,backgroundColor:o===t.line?"red":void 0,color:o===t.line?"white":void 0,"aria-label":o===t.line?`Line ${o}, error`:`Line ${o}`},String(o).padStart(i," "),":")),Z.createElement(C,{key:o,backgroundColor:o===t.line?"red":void 0,color:o===t.line?"white":void 0}," "+a)))),s.stack&&Z.createElement(F,{marginTop:1,flexDirection:"column"},s.stack.split(`
1646
+ `).slice(1).map(o=>{let a=hh.parseLine(o);return a?Z.createElement(F,{key:o},Z.createElement(C,{dimColor:true},"- "),Z.createElement(C,{dimColor:true,bold:true},a.function),Z.createElement(C,{dimColor:true,color:"gray","aria-label":`at ${kc(a.file)??""} line ${a.line} column ${a.column}`}," ","(",kc(a.file)??"",":",a.line,":",a.column,")")):Z.createElement(F,{key:o},Z.createElement(C,{dimColor:true},"- "),Z.createElement(C,{dimColor:true,bold:true},o,"\\t"," "))})))}var ZS=" ",QS="\x1B[Z",e_="\x1B",Wr=class extends PureComponent{static displayName="InternalApp";static getDerivedStateFromError(e){return {error:e}}state={isFocusEnabled:true,activeFocusId:void 0,focusables:[],error:void 0};rawModeEnabledCount=0;internal_eventEmitter=new EventEmitter;isRawModeSupported(){return this.props.stdin.isTTY}render(){return Z.createElement(Sc.Provider,{value:{exit:this.handleExit}},Z.createElement(Po.Provider,{value:{stdin:this.props.stdin,setRawMode:this.handleSetRawMode,isRawModeSupported:this.isRawModeSupported(),internal_exitOnCtrlC:this.props.exitOnCtrlC,internal_eventEmitter:this.internal_eventEmitter}},Z.createElement(_c.Provider,{value:{stdout:this.props.stdout,write:this.props.writeToStdout}},Z.createElement(Tc.Provider,{value:{stderr:this.props.stderr,write:this.props.writeToStderr}},Z.createElement(Ao.Provider,{value:{activeId:this.state.activeFocusId,add:this.addFocusable,remove:this.removeFocusable,activate:this.activateFocusable,deactivate:this.deactivateFocusable,enableFocus:this.enableFocus,disableFocus:this.disableFocus,focusNext:this.focusNext,focusPrevious:this.focusPrevious,focus:this.focus}},this.state.error?Z.createElement(Cc,{error:this.state.error}):this.props.children)))))}componentDidMount(){Ro.hide(this.props.stdout);}componentWillUnmount(){Ro.show(this.props.stdout),this.isRawModeSupported()&&this.handleSetRawMode(false);}componentDidCatch(e){this.handleExit(e);}handleSetRawMode=e=>{let{stdin:t}=this.props;if(!this.isRawModeSupported())throw t===Oo.stdin?new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
1647
+ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`):new Error(`Raw mode is not supported on the stdin provided to Ink.
1648
+ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(t.setEncoding("utf8"),e){this.rawModeEnabledCount===0&&(t.ref(),t.setRawMode(true),t.addListener("readable",this.handleReadable)),this.rawModeEnabledCount++;return}--this.rawModeEnabledCount===0&&(t.setRawMode(false),t.removeListener("readable",this.handleReadable),t.unref());};handleReadable=()=>{let e;for(;(e=this.props.stdin.read())!==null;)this.handleInput(e),this.internal_eventEmitter.emit("input",e);};handleInput=e=>{e===""&&this.props.exitOnCtrlC&&this.handleExit(),e===e_&&this.state.activeFocusId&&this.setState({activeFocusId:void 0}),this.state.isFocusEnabled&&this.state.focusables.length>0&&(e===ZS&&this.focusNext(),e===QS&&this.focusPrevious());};handleExit=e=>{this.isRawModeSupported()&&this.handleSetRawMode(false),this.props.onExit(e);};enableFocus=()=>{this.setState({isFocusEnabled:true});};disableFocus=()=>{this.setState({isFocusEnabled:false});};focus=e=>{this.setState(t=>t.focusables.some(r=>r?.id===e)?{activeFocusId:e}:t);};focusNext=()=>{this.setState(e=>{let t=e.focusables.find(r=>r.isActive)?.id;return {activeFocusId:this.findNextFocusable(e)??t}});};focusPrevious=()=>{this.setState(e=>{let t=e.focusables.findLast(r=>r.isActive)?.id;return {activeFocusId:this.findPreviousFocusable(e)??t}});};addFocusable=(e,{autoFocus:t})=>{this.setState(n=>{let r=n.activeFocusId;return !r&&t&&(r=e),{activeFocusId:r,focusables:[...n.focusables,{id:e,isActive:true}]}});};removeFocusable=e=>{this.setState(t=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.filter(n=>n.id!==e)}));};activateFocusable=e=>{this.setState(t=>({focusables:t.focusables.map(n=>n.id!==e?n:{id:e,isActive:true})}));};deactivateFocusable=e=>{this.setState(t=>({activeFocusId:t.activeFocusId===e?void 0:t.activeFocusId,focusables:t.focusables.map(n=>n.id!==e?n:{id:e,isActive:false})}));};findNextFocusable=e=>{let t=e.focusables.findIndex(n=>n.id===e.activeFocusId);for(let n=t+1;n<e.focusables.length;n++){let r=e.focusables[n];if(r?.isActive)return r.id}};findPreviousFocusable=e=>{let t=e.focusables.findIndex(n=>n.id===e.activeFocusId);for(let n=t-1;n>=0;n--){let r=e.focusables[n];if(r?.isActive)return r.id}}};var Sh=()=>{},Hr=class{options;log;throttledLog;isScreenReaderEnabled;isUnmounted;lastOutput;lastOutputHeight;lastTerminalWidth;container;rootNode;exitPromise;restoreConsole;unsubscribeResize;constructor(e){t_(this),this.options=e,this.rootNode=_o("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=e.isScreenReaderEnabled??Oo.env.INK_SCREEN_READER==="true";let t=e.debug||this.isScreenReaderEnabled,n=e.maxFps??30,r=n>0?Math.max(1,Math.ceil(1e3/n)):0;this.rootNode.onRender=t?this.onRender:throttle(this.onRender,r,{leading:true,trailing:true}),this.rootNode.onImmediateRender=this.onRender,this.log=sh.create(e.stdout,{incremental:e.incrementalRendering}),this.throttledLog=t?this.log:throttle(this.log,void 0,{leading:true,trailing:true}),this.isUnmounted=false,this.lastOutput="",this.lastOutputHeight=0,this.lastTerminalWidth=this.getTerminalWidth(),this.container=tn.createContainer(this.rootNode,LegacyRoot,null,false,null,"id",()=>{},()=>{},()=>{},()=>{},null),this.unsubscribeExit=onExit(this.unmount,{alwaysLast:false}),Oo.env.DEV==="true"&&tn.injectIntoDevTools({bundleType:0,version:"16.13.1",rendererPackageName:"ink"}),e.patchConsole&&this.patchConsole(),Ts||(e.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{e.stdout.off("resize",this.resized);});}getTerminalWidth=()=>this.options.stdout.columns||80;resized=()=>{let e=this.getTerminalWidth();e<this.lastTerminalWidth&&(this.log.clear(),this.lastOutput=""),this.calculateLayout(),this.onRender(),this.lastTerminalWidth=e;};resolveExitPromise=()=>{};rejectExitPromise=()=>{};unsubscribeExit=()=>{};calculateLayout=()=>{let e=this.getTerminalWidth();this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,ae.DIRECTION_LTR);};onRender=()=>{if(this.isUnmounted)return;let e=performance.now(),{output:t,outputHeight:n,staticOutput:r}=nh(this.rootNode,this.isScreenReaderEnabled);this.options.onRender?.({renderTime:performance.now()-e});let i=r&&r!==`
1649
+ `;if(this.options.debug){i&&this.options.stdout.write(r),t!==this.lastOutput&&(this.options.stdout.write(t),this.lastOutput=t,this.lastOutputHeight=n);return}if(Ts){i&&this.options.stdout.write(r),this.lastOutput=t,this.lastOutputHeight=n;return}if(this.isScreenReaderEnabled){if(i){let l=this.lastOutputHeight>0?Ft.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(l+r),this.lastOutputHeight=0;}if(t===this.lastOutput&&!i)return;let o=this.options.stdout.columns||80,a=zx(t,o,{trim:false,hard:true});if(i)this.options.stdout.write(a);else {let l=this.lastOutputHeight>0?Ft.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(l+a);}this.lastOutput=t,this.lastOutputHeight=a===""?0:a.split(`
1650
+ `).length;return}i?(this.log.clear(),this.options.stdout.write(r),this.log(t)):t!==this.lastOutput&&this.throttledLog(t),this.lastOutput=t,this.lastOutputHeight=n;};render(e){let t=Z.createElement(Tn.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},Z.createElement(Wr,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount},e));tn.updateContainerSync(t,this.container,null,Sh),tn.flushSyncWork();}writeToStdout(e){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(e+this.lastOutput);return}if(Ts){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput);}}writeToStderr(e){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.lastOutput);return}if(Ts){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput);}}unmount(e){this.isUnmounted||(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),Ts?this.options.stdout.write(this.lastOutput+`
1651
+ `):this.options.debug||this.log.done(),this.isUnmounted=true,tn.updateContainerSync(null,this.container,null,Sh),tn.flushSyncWork(),xs.delete(this.options.stdout),e instanceof Error?this.rejectExitPromise(e):this.resolveExitPromise());}async waitUntilExit(){return this.exitPromise||=new Promise((e,t)=>{this.resolveExitPromise=e,this.rejectExitPromise=t;}),this.exitPromise}clear(){!Ts&&!this.options.debug&&this.log.clear();}patchConsole(){this.options.debug||(this.restoreConsole=s_((e,t)=>{e==="stdout"&&this.writeToStdout(t),e==="stderr"&&(t.startsWith("The above error occurred")||this.writeToStderr(t));}));}};var l_=(s,e)=>{let t={stdout:Oo.stdout,stdin:Oo.stdin,stderr:Oo.stderr,debug:false,exitOnCtrlC:true,patchConsole:true,maxFps:30,incrementalRendering:true,...c_(e)},n=u_(t.stdout,()=>new Hr(t));return n.render(s),{rerender:n.render,unmount(){n.unmount();},waitUntilExit:n.waitUntilExit,cleanup:()=>xs.delete(t.stdout),clear:n.clear}},Ec=l_,c_=(s={})=>s instanceof Stream?{stdout:s,stdin:Oo.stdin}:s,u_=(s,e)=>{let t=xs.get(s);return t||(t=e(),xs.set(s,t)),t};function Do(s){let{items:e,children:t,style:n}=s,[r,i]=useState(0),o=useMemo(()=>e.slice(r),[r,e]);useLayoutEffect(()=>{i(e.length);},[e.length]);let a=useMemo(()=>o.map((c,u)=>t(c,r+u)),[o,t,r]),l=useMemo(()=>({position:"absolute",flexDirection:"column",...n}),[n]);return Z.createElement("ink-box",{internal_static:true,style:l},a)}var f_=/^(?:\x1b)([a-zA-Z0-9])$/,g_=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,_h={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},Th=[...Object.values(_h),"backspace"],y_=s=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(s),b_=s=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(s),v_=(s="")=>{let e;Buffer$1.isBuffer(s)?s[0]>127&&s[1]===void 0?(s[0]-=128,s="\x1B"+String(s)):s=String(s):s!==void 0&&typeof s!="string"?s=String(s):s||(s="");let t={name:"",ctrl:false,meta:false,shift:false,option:false,sequence:s,raw:s};if(t.sequence=t.sequence||s||t.name,s==="\r")t.raw=void 0,t.name="return";else if(s===`
1652
+ `)t.name="enter";else if(s===" ")t.name="tab";else if(s==="\b"||s==="\x1B\b")t.name="backspace",t.meta=s.charAt(0)==="\x1B";else if(s==="\x7F"||s==="\x1B\x7F")t.name="delete",t.meta=s.charAt(0)==="\x1B";else if(s==="\x1B"||s==="\x1B\x1B")t.name="escape",t.meta=s.length===2;else if(s===" "||s==="\x1B ")t.name="space",t.meta=s.length===2;else if(s.length===1&&s<="")t.name=String.fromCharCode(s.charCodeAt(0)+97-1),t.ctrl=true;else if(s.length===1&&s>="0"&&s<="9")t.name="number";else if(s.length===1&&s>="a"&&s<="z")t.name=s;else if(s.length===1&&s>="A"&&s<="Z")t.name=s.toLowerCase(),t.shift=true;else if(e=f_.exec(s))t.meta=true,t.shift=/^[A-Z]$/.test(e[1]);else if(e=g_.exec(s)){let n=[...s];n[0]==="\x1B"&&n[1]==="\x1B"&&(t.option=true);let r=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),i=(e[3]||e[5]||1)-1;t.ctrl=!!(i&4),t.meta=!!(i&10),t.shift=!!(i&1),t.code=r,t.name=_h[r],t.shift=y_(r)||t.shift,t.ctrl=b_(r)||t.ctrl;}return t},wh=v_;var S_=()=>useContext(Po),$o=S_;var __=(s,e={})=>{let{stdin:t,setRawMode:n,internal_exitOnCtrlC:r,internal_eventEmitter:i}=$o();useEffect(()=>{if(e.isActive!==false)return n(true),()=>{n(false);}},[e.isActive,n]),useEffect(()=>{if(e.isActive===false)return;let o=a=>{let l=wh(a),c={upArrow:l.name==="up",downArrow:l.name==="down",leftArrow:l.name==="left",rightArrow:l.name==="right",pageDown:l.name==="pagedown",pageUp:l.name==="pageup",home:l.name==="home",end:l.name==="end",return:l.name==="return",escape:l.name==="escape",ctrl:l.ctrl,shift:l.shift,tab:l.name==="tab",backspace:l.name==="backspace",delete:l.name==="delete",meta:l.meta||l.name==="escape"||l.option},u=l.ctrl?l.name:l.sequence;Th.includes(l.name)&&(u=""),u.startsWith("\x1B")&&(u=u.slice(1)),u.length===1&&typeof u[0]=="string"&&/[A-Z]/.test(u[0])&&(c.shift=true),(!(u==="c"&&c.ctrl)||!r)&&tn.batchedUpdates(()=>{s(u,c);});};return i?.on("input",o),()=>{i?.removeListener("input",o);}},[e.isActive,t,r,s]);},$n=__;var Ch=({version:s,provider:e,model:t,workDir:n})=>{let r=(l,c=50)=>{if(l.length<=c)return l;let u=l.split("/");return u.length<=2?l.slice(0,c-3)+"...":".../"+u.slice(-2).join("/")},i=(l,c=40)=>l.length<=c?l:l.slice(0,c-3)+"...",o=r(n),a=i(t);return Z.createElement(F,{flexDirection:"column",marginBottom:1},Z.createElement(F,{flexDirection:"row",borderStyle:"single",borderColor:"cyan",paddingX:1},Z.createElement(F,{flexDirection:"column",paddingRight:2,width:45},Z.createElement(F,null,Z.createElement(C,{bold:true,color:"cyan"},"Neox"),Z.createElement(C,{color:"gray"}," v",s)),Z.createElement(C,{color:"gray"},"Welcome! Enjoy!"),Z.createElement(F,{marginY:1,flexDirection:"column",alignItems:"center"},Z.createElement(C,{color:"cyan"}," ____ ____"),Z.createElement(C,{color:"cyan"},"| ",Z.createElement(C,{color:"white",bold:true},"o-o")," |"),Z.createElement(C,{color:"cyan"},"\\___/ \\___/")),Z.createElement(F,{flexDirection:"column"},Z.createElement(F,null,Z.createElement(C,{color:"cyan"},"Provider"),Z.createElement(C,null," "),Z.createElement(C,{color:"white"},e)),Z.createElement(F,null,Z.createElement(C,{color:"cyan"},"Model"),Z.createElement(C,null," "),Z.createElement(C,{color:"white"},a)),Z.createElement(F,null,Z.createElement(C,{color:"cyan"},"Path"),Z.createElement(C,null," "),Z.createElement(C,{color:"gray"},o)))),Z.createElement(F,{flexDirection:"column"},Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u251C"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502"),Z.createElement(C,{color:"cyan"},"\u2502")),Z.createElement(F,{flexDirection:"column",flexGrow:1},Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"yellow",bold:true},"Tips for getting started")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"Type your message to start")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"/help or ? for commands")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"Press ? to see all shortcuts")),Z.createElement(C,{color:"cyan"},"\u2500".repeat(40),"\u2524"),Z.createElement(F,{marginTop:1,paddingLeft:1},Z.createElement(C,{color:"blue",bold:true},"What is Neox?")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"Your intelligent coding assistant")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"Multi-agent collaboration support")),Z.createElement(F,{paddingLeft:1},Z.createElement(C,{color:"white"},"Smart context management")))))};function Bt(s){let e=s||new Date,t=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0"),r=e.getSeconds().toString().padStart(2,"0"),i=e.getMilliseconds().toString().padStart(3,"0");return `${t}:${n}:${r}.${i}`}var Eh=({message:s,timestamp:e})=>{let t="",n=0;if(typeof s.content=="string")t=s.content;else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"?t+=o.text:o.type==="image_url"&&n++;let r=Bt(e),i=t.split(`
1653
+ `);return Z.createElement(F,{flexDirection:"column"},Z.createElement(F,null,Z.createElement(C,{dimColor:true},r," \u2022 "),Z.createElement(C,{color:"green"},"\u256D\u2500 \u276F "),Z.createElement(C,{bold:true,color:"green"},"You"),n>0&&Z.createElement(C,{color:"magenta"}," \u{1F4CE} ",n," image",n>1?"s":"")),i.map((o,a)=>Z.createElement(F,{key:a},Z.createElement(C,{color:"green"}," \u2502 "),Z.createElement(C,null,o))),Z.createElement(F,null,Z.createElement(C,{color:"green"}," \u2570","\u2500".repeat(60))))};var Ih=({content:s,streaming:e=false})=>{let[t,n]=useState(true);useEffect(()=>{if(!e){n(false);return}let o=setInterval(()=>{n(a=>!a);},800);return ()=>clearInterval(o)},[e]);let r=s.trim();if(!r)return null;let i=r.split(`
1654
+ `);return Z.createElement(F,{flexDirection:"column"},i.map((o,a)=>Z.createElement(C,{key:a},o,e&&a===i.length-1&&t&&Z.createElement(C,{color:"cyan"},"\u258A"))))};var Rh=({message:s,streaming:e=false,timestamp:t})=>{let[n,r]=useState(0);useEffect(()=>{if(!e){r(0);return}let d=setInterval(()=>{r(p=>(p+1)%3);},600);return ()=>clearInterval(d)},[e]);let i="",o=[];if(typeof s.content=="string")i=s.content;else if(Array.isArray(s.content)){for(let d of s.content)if(d.type==="text")i+=d.text;else if(d.type==="tool_use"){let p=d;o.push({id:p.id,name:p.name,input:p.input});}}let a=Bt(t),c=e&&["cyan","cyanBright","cyan"][n]||"cyan",u=i.split(`
1655
+ `);return Z.createElement(F,{flexDirection:"column"},Z.createElement(F,null,Z.createElement(C,{dimColor:true},a," \u2022 "),Z.createElement(C,{color:c},"\u256D\u2500 \u25C6 "),Z.createElement(C,{bold:true,color:c},"Assistant"),e&&Z.createElement(C,{color:"yellow"}," \u2026")),u.map((d,p)=>Z.createElement(F,{key:p},Z.createElement(C,{color:c}," \u2502 "),Z.createElement(Ih,{content:d,streaming:e&&p===u.length-1}))),o.map(d=>Z.createElement(F,{key:d.id},Z.createElement(C,{color:c}," \u2502 "),Z.createElement(C,{color:"yellow"},"\u25B6 ",d.name),Z.createElement(C,{dimColor:true}," ",JSON.stringify(d.input).slice(0,50),"..."))),Z.createElement(F,null,Z.createElement(C,{color:c}," \u2570","\u2500".repeat(60))))};var Ph=({message:s,toolName:e,timestamp:t})=>{let n="",r=false;if(Array.isArray(s.content)){for(let u of s.content)if(u.type==="tool_result"){let d=u;n=typeof d.content=="string"?d.content:JSON.stringify(d.content,null,2),r=d.is_error||false,d.tool_use_id||"";break}}else typeof s.content=="string"&&(n=s.content);let o=1e3,a=n.length>o?n.slice(0,o)+`
1656
+
1657
+ ... (truncated `+(n.length-o)+" chars)":n,l=Bt(t),c=a.split(`
1658
+ `);return Z.createElement(F,{flexDirection:"column",marginBottom:1},Z.createElement(F,null,Z.createElement(C,{color:r?"red":"blue"},r?"\u2717":"\u23BF"," Tool Result"),e&&Z.createElement(C,{color:"gray",dimColor:true}," (",e,")"),l&&Z.createElement(C,{color:"gray",dimColor:true}," \u2022 ",l)),Z.createElement(F,{paddingLeft:2,flexDirection:"column"},c.map((u,d)=>Z.createElement(C,{key:d,color:r?"red":"gray",dimColor:!r},u))))};var No=({text:s,details:e,type:t="info",timestamp:n})=>{let r={info:{icon:"\u2022",color:"blue"},error:{icon:"\u2717",color:"red"},warning:{icon:"\u26A0",color:"yellow"},success:{icon:"\u2713",color:"green"}},{icon:i,color:o}=r[t],a=Bt(n),l=e&&e.trim().length>0,c=[];if(c.push(s),l){let u=e.split(`
1659
+ `);c.push(...u);}return Z.createElement(F,{flexDirection:"column"},Z.createElement(F,null,Z.createElement(C,{dimColor:true},a," \u2022 "),Z.createElement(C,{color:o},"\u256D\u2500 ",i," "),Z.createElement(C,{color:o,bold:true},t)),c.map((u,d)=>Z.createElement(F,{key:d},Z.createElement(C,{color:o}," \u2502 "),Z.createElement(C,null,u))),Z.createElement(F,null,Z.createElement(C,{color:o}," \u2570","\u2500".repeat(40))))};var Ah=({content:s,streaming:e=false,collapsed:t=false})=>{let r=(t&&s.length>200?s.slice(0,200)+"...":s).split(`
1660
+ `);return Z.createElement(F,{flexDirection:"column",marginBottom:1,borderStyle:"round",borderColor:"magenta",paddingX:1},Z.createElement(F,null,Z.createElement(C,{color:"magenta",bold:true},"\u{1F4AD} Thinking"),e&&Z.createElement(C,{color:"magenta"}," ",Z.createElement(E_,{type:"dots"}))),Z.createElement(F,{flexDirection:"column",paddingLeft:1,paddingTop:0},r.map((i,o)=>Z.createElement(C,{key:o,color:"white"},i))),t&&s.length>200&&Z.createElement(F,null,Z.createElement(C,{color:"yellow",italic:true},"[Truncated - ",s.length," chars total]")))};var Uo={tool_call:{icon:"\u25B6",color:"yellow",prefix:"Tool"},tool_result:{icon:"\u2713",color:"green",prefix:"Result"},tool_error:{icon:"\u2717",color:"red",prefix:"Error"},file_update:{icon:"\u270E",color:"blue",prefix:"Edit"},command_exec:{icon:"$",color:"yellow",prefix:"Shell"},code_exec:{icon:"\u03BB",color:"yellow",prefix:"Code"},web_search:{icon:"\u2315",color:"cyan",prefix:"Search"},web_fetch:{icon:"\u21E3",color:"cyan",prefix:"Fetch"},readfile:{icon:"\u2263",color:"cyan",prefix:"Read"},search:{icon:"\u2387",color:"cyan",prefix:"Search"},search_files:{icon:"\u27D0",color:"cyan",prefix:"Glob"},show_tree:{icon:"\u2301",color:"cyan",prefix:"Tree"},browser_debug:{icon:"\u25CD",color:"cyan",prefix:"Browser"}};function I_(s){let e=s.match(/^(\s*\d+\s+)([-+])\s*(.*)$/);if(e){let[,t,n,r]=e;if(n==="-")return {color:"red",bgColor:"bgRed",text:`${t}- ${r}`};if(n==="+")return {color:"green",bgColor:"bgGreen",text:`${t}+ ${r}`}}return s.startsWith("\u2500\u2500\u2500")||s.startsWith("\u2500\u2500\u2500 old:")?{color:"gray",text:s}:s.startsWith("+++")||s.startsWith("+++ new:")?{color:"gray",text:s}:{text:s}}var Mh=({type:s,message:e,details:t,timestamp:n,isStreaming:r=false})=>{let i=Uo[s]||Uo.tool_call,o=Bt(n),a=[];if(a.push(e),t){let l=t.split(`
1661
+ `);a.push(...l);}return Z.createElement(F,{flexDirection:"column"},Z.createElement(F,null,Z.createElement(C,{dimColor:true},o," \u2022 "),Z.createElement(C,{color:i.color},"\u256D\u2500 ",i.icon," "),Z.createElement(C,{color:i.color,bold:true},i.prefix),r&&Z.createElement(C,{color:"yellow"}," \u2026")),a.map((l,c)=>{let u=I_(l);return Z.createElement(F,{key:c,flexDirection:"row"},Z.createElement(C,{color:i.color}," \u2502 "),Z.createElement(F,{flexDirection:"column",flexShrink:1},Z.createElement(C,{wrap:"wrap",color:u.color,dimColor:u.color==="gray"},u.text)))}),Z.createElement(F,null,Z.createElement(C,{color:i.color}," \u2570","\u2500".repeat(40))))};var R_=({entry:s})=>{let e=null;return s.type==="info"&&s.text?e=Z.createElement(No,{text:s.text,details:s.details,type:"info",timestamp:s.timestamp}):s.type==="warning"&&s.text?e=Z.createElement(No,{text:s.text,details:s.details,type:"warning",timestamp:s.timestamp}):s.type==="error"&&s.text?e=Z.createElement(No,{text:s.text,details:s.details,type:"error",timestamp:s.timestamp}):(s.type==="thinking"||s.type==="reasoning")&&s.text?e=Z.createElement(Ah,{content:s.text,streaming:s.isStreaming}):Uo[s.type]&&s.text?e=Z.createElement(Mh,{type:s.type,message:s.text,details:s.details,timestamp:s.timestamp,isStreaming:s.isStreaming}):s.message&&(e=P_(s.message,s.id,s.isStreaming,s.timestamp)),e?Z.createElement(F,{flexDirection:"column"},e):null};function P_(s,e,t,n){let r=`msg-${e}`;switch(s.role){case "user":return Z.createElement(Eh,{key:r,message:s,timestamp:n});case "assistant":return Z.createElement(Rh,{key:r,message:s,streaming:t,timestamp:n});case "system":case "tool":let i=s;return i.role==="user"&&Array.isArray(i.content)&&i.content.some(o=>o.type==="tool_result")?Z.createElement(Ph,{key:r,message:i,timestamp:n}):Z.createElement(F,{key:r},Z.createElement(C,{color:"gray",dimColor:true},"[Unknown message type: ",s.role,"]"))}}var Pc=Z.memo(R_,(s,e)=>s.entry.id===e.entry.id&&s.entry.isStreaming===e.entry.isStreaming);le();var Lh=({value:s,placeholder:e="Type a message... (? for help)",disabled:t=false,multiline:n=false,completions:r=[],onChange:i,onSubmit:o,onHistoryUp:a,onHistoryDown:l,onTabComplete:c})=>{let[u,d]=useState(0),[p,m]=useState(false),[h,g]=useState(0),y=s.length-u;$n((B,I)=>{if(!t&&!I.escape){if(I.tab){if(c){let k=c(s);k&&(i(k),d(0));}return}if(I.return){if(n&&!I.shift){let k=s.slice(0,y)+`
1662
+ `+s.slice(y);i(k);return}process.env.CLI_DEBUG==="1"&&f.debug("INPUT_LINE","Enter pressed - submitting",{valueLength:s.length,value:s.substring(0,50),disabled:t}),o(),d(0),m(false);return}if(I.upArrow){a(),d(0);return}if(I.downArrow){l(),d(0);return}if(I.leftArrow){d(Math.min(u+1,s.length));return}if(I.rightArrow){d(Math.max(u-1,0));return}if(I.home||I.ctrl&&B==="a"){d(s.length);return}if(I.end||I.ctrl&&B==="e"){d(0);return}if(I.backspace||I.delete){if(u===s.length)return;let k=y-1,R=s.slice(0,k)+s.slice(k+1);i(R);return}if(!I.ctrl&&!I.meta&&B){let k=s.slice(0,y)+B+s.slice(y);i(k);return}}},{isActive:true});let x=s.slice(0,y),S=s[y]||" ",T=s.slice(y+1),w=n?s.split(`
1663
+ `):[s];return Z.createElement(F,{flexDirection:"column"},Z.createElement(F,{flexDirection:n?"column":"row"},!n&&Z.createElement(C,{color:"green",bold:true},"> "),t?Z.createElement(C,{dimColor:true},s||e):!s?Z.createElement(F,null,!n&&Z.createElement(C,{inverse:true}," "),Z.createElement(C,{dimColor:true},e)):n?w.map((B,I)=>Z.createElement(F,{key:I},Z.createElement(C,{color:"green",bold:true},I===0?"> ":"\u2502 "),Z.createElement(C,null,B))):Z.createElement(C,null,x,Z.createElement(C,{inverse:true},S),T)),p&&r.length>0&&Z.createElement(F,{paddingLeft:2,flexDirection:"column"},Z.createElement(C,{color:"yellow"},"Suggestions:"),r.slice(0,5).map((B,I)=>Z.createElement(C,{key:I,color:I===h?"cyan":"white",bold:I===h},I===h?"\u2192 ":" ",B))))};var M_=({isRunning:s,statusText:e="",tokenStats:t,streamingTokens:n=0,streamingStartTime:r=null,provider:i,model:o})=>{let[a,l]=useState(null),[c,u]=useState(0),[d,p]=useState(0),[m,h]=useState(0),[g,y]=useState(0);useEffect(()=>{s&&a===null?l(r||Date.now()):!s&&(t?.output||0)===0&&(l(null),u(0));},[s,r,a,t?.output]),useEffect(()=>{if(!s||a===null)return;let R=setInterval(()=>{u(Math.floor((Date.now()-a)/1e3));},500);return ()=>clearInterval(R)},[s,a]),useEffect(()=>{if(!s||n===0){p(0);return}let R=Math.floor(n);if(d===R)return;let E=R-d,M=Math.min(Math.abs(E),20),_=E/M,$=setInterval(()=>{p(A=>{let G=A+_;return Math.abs(G-R)<1?R:G});},50);return ()=>clearInterval($)},[n,s,d]),useEffect(()=>{let R=t?.output||0;if(m===R)return;let E=R-m;if(Math.abs(E)>100){h(R);return}let M=Math.max(Math.ceil(Math.abs(E)/10),3),_=E/M,$=setInterval(()=>{h(A=>{let G=A+_;return Math.abs(G-R)<1?R:G});},10);return ()=>clearInterval($)},[t?.output,m]),useEffect(()=>{if(!s){y(0);return}let E=(e||"Thinking...").length,M=setInterval(()=>{y(_=>(_+1)%(E+3));},80);return ()=>clearInterval(M)},[s,e]);let x=()=>{if(c<60)return `${c}s`;let R=Math.floor(c/60),E=c%60;return `${R}m ${E}s`},S=R=>R>=1e6?(R/1e6).toFixed(1)+"M":R>=1e3?(R/1e3).toFixed(1)+"K":R.toString(),T=t?.contextWindow||0,w=t?.tokensUsedForContext||t?.total||0,L=t?.pressure||0,B=Math.round(L*100),I=()=>L>.8?"red":L>.5?"yellow":"green";return Z.createElement(F,{justifyContent:"space-between"},Z.createElement(F,null,s?Z.createElement(F,null,Z.createElement(E_,{type:"dots"}),Z.createElement(C,null," "),Z.createElement(C,{bold:true,color:"cyan"},"\u25CF"),Z.createElement(C,null," "),(R=>R.split("").map((M,_)=>{let W=_-g;return W>=0&&W<2?Z.createElement(C,{key:_,color:"white",bold:true},M):W>=-1&&W<0?Z.createElement(C,{key:_,color:"cyanBright"},M):Z.createElement(C,{key:_,color:"cyan"},M)}))(e||"Thinking..."),c>0&&Z.createElement(Z.Fragment,null,Z.createElement(C,{dimColor:true}," ("),Z.createElement(C,{color:"yellow"},x()),Z.createElement(C,{dimColor:true}," \u2022 esc to interrupt"),d>0&&Z.createElement(Z.Fragment,null,Z.createElement(C,{dimColor:true}," \u2022 "),Z.createElement(C,{color:"green"},"\u2193 ",Math.floor(d)),Z.createElement(C,{dimColor:true}," tokens")),Z.createElement(C,{dimColor:true},")"))):Z.createElement(F,null,(t?.output||0)>0?Z.createElement(Z.Fragment,null,Z.createElement(C,{color:"green",bold:true},"\u25A0"),Z.createElement(C,null," "),Z.createElement(C,{color:"green"},"Complete!"),c>0&&Z.createElement(Z.Fragment,null,Z.createElement(C,{dimColor:true}," ("),Z.createElement(C,{color:"yellow"},x()),Z.createElement(C,{dimColor:true},")"))):Z.createElement(Z.Fragment,null,Z.createElement(C,{color:"cyan",bold:true},"\u25CF"),Z.createElement(C,null," "),Z.createElement(C,{color:"cyan"},"Ready")))),Z.createElement(F,null,Z.createElement(C,{dimColor:true},"in "),Z.createElement(C,{color:"cyan"},S(t?.input||0)),Z.createElement(C,null," "),Z.createElement(C,{dimColor:true},"out "),Z.createElement(C,{color:"green"},S(Math.floor(m))),T>0&&Z.createElement(Z.Fragment,null,Z.createElement(C,null," "),Z.createElement(C,{dimColor:true},"context "),Z.createElement(C,{color:"yellow"},S(w)),Z.createElement(C,{dimColor:true}," tokens "),Z.createElement(C,{color:I()},B,"%"))))},Oh=Z.memo(M_,(s,e)=>s.isRunning===e.isRunning&&s.statusText===e.statusText&&s.streamingTokens===e.streamingTokens&&s.streamingStartTime===e.streamingStartTime&&s.tokenStats?.input===e.tokenStats?.input&&s.tokenStats?.output===e.tokenStats?.output&&s.tokenStats?.total===e.tokenStats?.total&&s.tokenStats?.pressure===e.tokenStats?.pressure);var Dh=({isRunning:s,hasInput:e,customHints:t,menuActive:n=false,thinkingEnabled:r=true})=>t?Z.createElement(F,{justifyContent:"space-between"},Z.createElement(C,{color:"yellow"},t)):n?Z.createElement(F,{justifyContent:"space-between"},Z.createElement(C,{dimColor:true}," ","\u2191\u2193 to select, Enter to confirm, ESC to cancel")):Z.createElement(F,{justifyContent:"space-between"},Z.createElement(C,{dimColor:true}," ","? for shortcuts"),Z.createElement(F,null,r?Z.createElement(C,{color:"cyan"},"Thinking on"):Z.createElement(C,{dimColor:true},"Thinking off"),Z.createElement(C,{dimColor:true}," (tab to toggle)")));var $h=({attachments:s,onRemove:e})=>s.length===0?null:Z.createElement(F,{flexDirection:"column",paddingLeft:2,marginBottom:1},Z.createElement(C,{color:"magenta",dimColor:true},"Attachments:"),s.map((t,n)=>{let r=t.name||t.path.split("/").pop()||"unknown",i=t.type?.startsWith("image/")||r.match(/\.(png|jpg|jpeg|gif|webp)$/i);return Z.createElement(F,{key:n},Z.createElement(C,{color:"magenta"},i?"\u{1F4CE} \u{1F5BC}\uFE0F ":"\u{1F4CE} ",r),e&&Z.createElement(C,{color:"gray",dimColor:true}," (press Del to remove)"))}));le();var L_=({inputValue:s,isRunning:e,statusText:t="",tokenStats:n,streamingTokens:r=0,streamingStartTime:i=null,provider:o,model:a,customHints:l,attachments:c=[],multiline:u=false,completions:d=[],menuActive:p=false,thinkingEnabled:m=true,onInputChange:h,onSubmit:g,onInterrupt:y,onExit:x,onHistoryUp:S,onHistoryDown:T,onTabComplete:w,onRemoveAttachment:L})=>($n((B,I)=>{if(process.env.CLI_DEBUG==="1"&&f.debug("INK_INPUT","BottomBar useInput",{key:I,input:B,menuActive:p,isRunning:e,inputValue:s.substring(0,20)}),!p){if(I.ctrl&&B==="z"){process.env.CLI_DEBUG==="1"&&f.debug("INK_INPUT","Ctrl+Z blocked (prevents suspension)");return}if(I.escape){f.debug("INK_INPUT","ESC pressed in BottomBar",{isRunning:e,hasInput:!!s}),e?y():s&&h("");return}I.ctrl&&B==="c"&&(process.env.CLI_DEBUG==="1"&&f.debug("INK_INPUT","Ctrl+C pressed",{isRunning:e}),e?y():(f.info("INK_INPUT","\u26A0\uFE0F Ctrl+C pressed - exiting"),x()));}},{isActive:true}),Z.createElement(F,{flexDirection:"column"},Z.createElement(Oh,{isRunning:e,statusText:t,tokenStats:n,streamingTokens:r,streamingStartTime:i,provider:o,model:a}),c.length>0&&Z.createElement($h,{attachments:c,onRemove:L}),Z.createElement(F,{flexDirection:"column"},Z.createElement(C,{color:"gray"},"\u2500".repeat(process.stdout.columns||80)),Z.createElement(Lh,{value:s,placeholder:"Type a message...",disabled:e,multiline:u,completions:d,onChange:h,onSubmit:()=>g(s),onHistoryUp:S,onHistoryDown:T,onTabComplete:w}),Z.createElement(C,{color:"gray"},"\u2500".repeat(process.stdout.columns||80))),Z.createElement(Dh,{isRunning:e,hasInput:s.length>0,customHints:l,menuActive:p,thinkingEnabled:m}))),Nh=Z.memo(L_);var Bh=({message:s,choices:e,initialIndex:t=0,hint:n,maxVisible:r=20,onSelect:i,onCancel:o})=>{let[a,l]=useState(t),[c,u]=useState(0);useEffect(()=>{l(t);},[t]),useEffect(()=>{if(e.length<=r){u(0);return}a<c?u(a):a>=c+r&&u(a-r+1);},[a,e.length,r,c]),$n((h,g)=>{if(g.escape&&o){process.nextTick(()=>o());return}if(g.upArrow){l(y=>y>0?y-1:e.length-1);return}if(g.downArrow){l(y=>y<e.length-1?y+1:0);return}if(g.return){i(e[a].value);return}});let d=Math.min(e.length,r),p=c>0,m=c+d<e.length;return Z.createElement(F,{flexDirection:"column"},s&&Z.createElement(F,{marginBottom:1,paddingX:2},Z.createElement(C,{bold:true,color:"cyan"},s)),n&&Z.createElement(F,{marginBottom:1,paddingX:2},Z.createElement(C,{dimColor:true},n)),p&&Z.createElement(F,{paddingX:2},Z.createElement(C,{dimColor:true}," \u2191 more")),e.slice(c,c+d).map((h,g)=>{let y=c+g,x=y===a,S=x?"\u276F ":" ";return Z.createElement(F,{key:`${h.value}-${y}`,flexDirection:"row",paddingX:2},Z.createElement(C,{color:x?"cyan":void 0,bold:x},S,h.label),h.description&&Z.createElement(C,{dimColor:true}," - ",h.description))}),m&&Z.createElement(F,{paddingX:2},Z.createElement(C,{dimColor:true}," \u2193 more")))};var N_=fileURLToPath(import.meta.url),Lc=dirname(N_),ws=null;function U_(){if(ws)return ws;try{let s=[join(Lc,"../package.json"),join(Lc,"../../package.json"),join(Lc,"../../../package.json")];for(let e of s)try{let t=JSON.parse(readFileSync(e,"utf-8"));if(t.version)return ws=t.version,ws}catch{continue}throw new Error("package.json not found")}catch{ws="2.0.7";}return ws}var Fo=U_();var Dc=({staticEntries:s=[],pendingEntries:e=[],isRunning:t,statusText:n="",tokenStats:r,streamingTokens:i=0,streamingStartTime:o=null,version:a=Fo,provider:l="OpenAI",model:c="gpt-4",workDir:u=process.cwd(),showHeader:d=true,thinkingEnabled:p=true,selectMenuOptions:m=null,getCompletions:h,onStaticRendered:g,onSubmit:y,onInterrupt:x,onExit:S})=>{let[T,w]=useState(""),[L,B]=useState([]),[I,k]=useState(-1),R=useRef(false),E=e,M=d&&!R.current,_=Z.useCallback((U,H)=>U,[]),W=useMemo(()=>{let U=[];return M&&U.push(Z.createElement(Ch,{key:"header",version:a,provider:l,model:c,workDir:u})),s.forEach(H=>{U.push(Z.createElement(Pc,{key:`static-entry-${H.id}`,entry:H}));}),U},[M,s,a,l,c,u]);useEffect(()=>{!M&&s.length===0||(M&&(R.current=true),g?.());},[M,s.length,g]);let $=U=>{U.trim()&&(B([...L,U]),k(-1),w(""),y(U));},A=()=>{if(L.length===0)return;let U=I+1;U<L.length&&(k(U),w(L[L.length-1-U]));},G=()=>{if(I<=0){k(-1),w("");return}let U=I-1;k(U),w(L[L.length-1-U]);},N=U=>{if(!h)return null;let H=h(U);return H.length===0?null:H[0]};return Z.createElement(F,{flexDirection:"column",width:"100%"},Z.createElement(Do,{items:W},_),E.map(U=>Z.createElement(Pc,{key:`pending-${U.id}`,entry:U})),Z.createElement(C,null,`
1664
+ `),Z.createElement(F,{flexShrink:0,flexDirection:"column"},Z.createElement(Nh,{inputValue:T,isRunning:t,statusText:n,tokenStats:r,streamingTokens:i,streamingStartTime:o,provider:l,model:c,menuActive:!!m,thinkingEnabled:p,onInputChange:w,onSubmit:$,onInterrupt:x,onExit:S,onHistoryUp:A,onHistoryDown:G,onTabComplete:N}),m&&Z.createElement(Bh,{message:m.message,choices:m.choices,initialIndex:m.initialIndex,onSelect:m.onSelect,onCancel:m.onCancel})))};le();var Kr=class s{appInstance=null;messages=[];staticEntries=[];nextEntryId=1;isRunning=false;statusText="";tokenStats={input:0,output:0,total:0};version="";provider="";model="";workDir="";showHeader=true;thinkingEnabled=true;callbacks;forceUpdate=null;selectMenuOptions=null;getCompletions;memoryLogTimer=null;pendingEntries=[];streamingTokens=0;streamingStartTime=null;static MAX_QUEUED_STATIC=50;constructor(e){this.callbacks=e;}setCompletionFunction(e){this.getCompletions=e;}start(){f.info("INK","Starting Ink runtime"),this.startMemorySampler();let e=()=>{let[,t]=useState(0);return useEffect(()=>(this.forceUpdate=()=>t(n=>n+1),()=>{this.forceUpdate=null;}),[]),Z.createElement(Dc,{staticEntries:this.staticEntries,pendingEntries:this.pendingEntries,isRunning:this.isRunning,statusText:this.statusText,tokenStats:this.tokenStats,streamingTokens:this.streamingTokens,streamingStartTime:this.streamingStartTime,version:this.version,provider:this.provider,model:this.model,workDir:this.workDir,showHeader:this.showHeader,thinkingEnabled:this.thinkingEnabled,selectMenuOptions:this.selectMenuOptions,getCompletions:this.getCompletions,onStaticRendered:void 0,onSubmit:this.callbacks.onSubmit,onInterrupt:this.callbacks.onInterrupt,onExit:this.callbacks.onExit})};this.appInstance=Ec(Z.createElement(e,null),{stdout:process.stdout,stdin:process.stdin,exitOnCtrlC:false,patchConsole:false});try{process.removeAllListeners("SIGTSTP"),process.on("SIGTSTP","ignore"),process.env.CLI_DEBUG==="1"&&f.debug("INK","SIGTSTP handler registered (Ctrl+Z ignored)");}catch{process.env.CLI_DEBUG==="1"&&f.debug("INK","SIGTSTP not supported on this platform");}f.info("INK","Ink runtime started");}stop(){this.appInstance&&(this.appInstance.unmount(),this.appInstance=null,f.info("INK","Ink runtime stopped")),this.stopMemorySampler();}addMessage(e){this.messages=[...this.messages.slice(-4),e],this.forceUpdate?.();}addEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};return this.staticEntries.length>=s.MAX_QUEUED_STATIC&&(f.warn("INK_RUNTIME",`Static queue reached limit (${this.staticEntries.length}). Forcing immediate render to prevent OOM.`),this.forceUpdate?.(),setImmediate(()=>{this.clearStaticEntries();})),this.staticEntries=[...this.staticEntries,t],f.debug("INK_RUNTIME",`Queued static entry ${t.id}. Pending static: ${this.staticEntries.length}`),this.forceUpdate?.(),t.id}updateEntry(e,t){let n=this.staticEntries.findIndex(i=>i.id===e);if(n>=0){this.staticEntries=this.staticEntries.map((i,o)=>o===n?{...i,...t}:i),this.forceUpdate?.();return}let r=this.pendingEntries.findIndex(i=>i.id===e);r>=0&&(this.pendingEntries=this.pendingEntries.map((i,o)=>o===r?{...i,...t}:i),this.forceUpdate?.());}getEntry(e){return this.staticEntries.find(t=>t.id===e)||this.pendingEntries.find(t=>t.id===e)}addPendingEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};if(this.pendingEntries.length>=10){f.warn("INK_RUNTIME",`Too many pending entries (${this.pendingEntries.length}). Auto-committing oldest.`);let r=this.pendingEntries[0];this.staticEntries=[...this.staticEntries,r],this.pendingEntries=this.pendingEntries.slice(1);}return this.pendingEntries=[...this.pendingEntries,t],f.debug("INK_RUNTIME",`Added pending entry ${t.id}. Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),t.id}updatePendingEntry(e,t){let n=this.pendingEntries.findIndex(r=>r.id===e);n>=0&&(this.pendingEntries=this.pendingEntries.map((r,i)=>i===n?{...r,...t}:r),this.forceUpdate?.());}commitPendingEntry(e){let t=this.pendingEntries.findIndex(n=>n.id===e);if(t>=0){let n=this.pendingEntries[t];this.pendingEntries=this.pendingEntries.filter((r,i)=>i!==t),this.staticEntries=[...this.staticEntries,n],f.debug("INK_RUNTIME",`Committed entry ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.();}else f.warn("INK_RUNTIME",`Cannot commit entry ${e} - not found in pending entries`);}clearPendingEntries(){this.pendingEntries.length>0&&(this.pendingEntries=[],this.forceUpdate?.());}updateStreamingStats(e){this.streamingTokens=e,this.streamingStartTime||(this.streamingStartTime=Date.now()),this.forceUpdate?.();}resetStreamingStats(){this.streamingTokens=0,this.streamingStartTime=null;}updateLastMessage(e){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1];if(typeof t.content=="string")t.content=e;else if(Array.isArray(t.content)){let n=t.content.find(r=>r.type==="text");n&&"text"in n&&(n.text=e);}this.forceUpdate?.();}getLastMessageText(){if(this.messages.length===0)return "";let e=this.messages[this.messages.length-1];if(typeof e.content=="string")return e.content;if(Array.isArray(e.content)){let t=e.content.find(n=>n.type==="text");if(t&&"text"in t)return t.text||""}return ""}setRunning(e){this.isRunning!==e&&(this.isRunning=e,this.forceUpdate?.());}setStatusText(e){this.statusText!==e&&(this.statusText=e,this.forceUpdate?.());}setTokenStats(e){(this.tokenStats.input!==e.input||this.tokenStats.output!==e.output||this.tokenStats.total!==e.total||this.tokenStats.contextWindow!==e.contextWindow||this.tokenStats.tokensUsedForContext!==e.tokensUsedForContext||this.tokenStats.pressure!==e.pressure)&&(this.tokenStats={...e},this.forceUpdate?.());}clearMessages(){f.warn("INK_RUNTIME",`clearMessages called! This will clear pending/static queues. Messages: ${this.messages.length}`),this.messages=[],this.staticEntries=[],this.pendingEntries=[],this.forceUpdate?.();}setVersion(e){this.version=e,this.forceUpdate?.();}setProvider(e){this.provider=e,this.forceUpdate?.();}setModel(e){this.model=e,this.forceUpdate?.();}setWorkDir(e){this.workDir=e,this.forceUpdate?.();}setShowHeader(e){this.showHeader=e,this.forceUpdate?.();}setThinkingEnabled(e){this.thinkingEnabled!==e&&(this.thinkingEnabled=e,this.forceUpdate?.());}showSelectMenu(e){f.debug("INK_RUNTIME","Show select menu",{options:e}),this.selectMenuOptions=e,this.forceUpdate?.();}hideSelectMenu(){f.debug("INK_RUNTIME","Hide select menu"),this.selectMenuOptions=null,this.forceUpdate?.();}clearStaticEntries(){if(this.staticEntries.length===0)return;let e=this.staticEntries.length;f.debug("INK_RUNTIME",`Clearing ${e} static entries from memory`),this.staticEntries=[],global.gc&&e>10&&(f.debug("INK_RUNTIME","Triggering manual GC after clearing entries"),setImmediate(()=>{global.gc&&global.gc();}));}startMemorySampler(){this.memoryLogTimer||process.env.INK_MEM!=="1"||(this.memoryLogTimer=setInterval(()=>{let e=process.memoryUsage(),t=n=>Math.round(n/1024/1024*10)/10;f.info("INK_MEM","usage",{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),heapTotalMB:t(e.heapTotal),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers??0),pendingEntries:this.pendingEntries.length,queuedStatic:this.staticEntries.length,isRunning:this.isRunning});},1e4));}stopMemorySampler(){this.memoryLogTimer&&(clearInterval(this.memoryLogTimer),this.memoryLogTimer=null);}};le();var Vr=class{runtime;config;callbacks;currentThinkingText="";lastMessageRole=null;lastEntryId=null;tokenStats={inputTokens:0,outputTokens:0,totalTokens:0};memory;streamingTextPendingId=null;streamingReasoningPendingId=null;streamingTextBuffer="";streamingReasoningBuffer="";constructor(e){this.config=e,this.memory=e.memory,this.runtime=new Kr({onSubmit:t=>{this.callbacks?.onSubmit&&this.callbacks.onSubmit(t,[]);},onInterrupt:()=>{this.callbacks?.onInterrupt&&this.callbacks.onInterrupt();},onExit:()=>{this.callbacks?.onExit&&this.callbacks.onExit();}});}start(e){this.callbacks=e,this.runtime.setVersion(this.config.version),this.runtime.setProvider(this.config.provider),this.runtime.setModel(this.config.model),this.runtime.setWorkDir(this.config.workDir),this.config.getCompletions&&this.runtime.setCompletionFunction(this.config.getCompletions),this.runtime.start(),f.info("INK_ADAPTER","Ink UI started");}stop(){this.runtime.stop(),this.callbacks=void 0,f.info("INK_ADAPTER","Ink UI stopped");}addUserMessage(e,t){let n=[{type:"text",text:e}];if(t&&t.length>0)for(let i of t)n.push({type:"image_url",image_url:{url:`data:${i.mediaType};base64,${i.data}`}});let r={role:"user",content:n};this.lastEntryId=this.runtime.addEntry({type:"user",message:r}),this.lastMessageRole="user";}addAssistantMessage(e=""){if(e===""){this.lastMessageRole="assistant";return}let t={role:"assistant",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"assistant",message:t,isStreaming:false}),this.lastMessageRole="assistant";}streamText(e){this.streamingTextBuffer+=e;}addTextDelta(e){this.streamText(e);}addToolCall(e,t){let n={role:"assistant",content:[{type:"tool_use",id:`tool_${Date.now()}`,name:e,input:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_call";}addToolResult(e,t=false){let n={role:"user",content:[{type:"tool_result",tool_use_id:`tool_${Date.now()}`,content:e,is_error:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_result";}addInfo(e,t,n="info"){f.info("INK_ADAPTER",`Info: ${e}`,t?{details:t}:void 0);let r=n==="warning"||e.includes("\u26A0")||e.includes("\u23F3")||e.includes("\u23F1\uFE0F")||e.includes("\u{1F504}");this.runtime.addEntry({type:r?"warning":"info",text:e,details:t});}addError(e,t){f.error("INK_ADAPTER",e,t?{details:t}:void 0),this.runtime.addEntry({type:"error",text:e,details:t});}updateStatus(e,t){this.runtime.setStatusText(e);}setRunning(e){this.runtime.setRunning(e);}updateTokenStats(e,t){this.tokenStats.inputTokens=e,this.tokenStats.outputTokens=t,this.tokenStats.totalTokens=e+t,this.runtime.setTokenStats({input:e,output:t,total:e+t});}getTokenStats(){return {...this.tokenStats}}setTokenStats(e,t,n){this.tokenStats={inputTokens:e,outputTokens:t,totalTokens:e+t,...n};let r=n?.contextWindow||0,i=n?.tokensUsedForContext||e+t,o=r>0?i/r:0;this.runtime.setTokenStats({input:e,output:t,total:e+t,contextWindow:n?.contextWindow,tokensUsedForContext:n?.tokensUsedForContext,pressure:o});}startThinking(){this.streamingReasoningBuffer="";}streamThinking(e){this.streamingReasoningBuffer+=e,this.streamingReasoningPendingId?this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{text:this.streamingReasoningBuffer}):this.streamingReasoningPendingId=this.runtime.addPendingEntry({type:"thinking",text:this.streamingReasoningBuffer,isStreaming:true});}endThinking(){if(!this.streamingReasoningPendingId){this.updateStatus("","info");return}this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{isStreaming:false,isComplete:true}),this.runtime.commitPendingEntry(this.streamingReasoningPendingId),this.streamingReasoningPendingId=null,this.streamingReasoningBuffer="",this.runtime.resetStreamingStats(),this.updateStatus("","info");}startTaskTimer(){this.runtime.setRunning(true);}stopTaskTimer(){this.runtime.setRunning(false);}clear(){this.runtime.clearMessages(),this.lastMessageRole=null;}resetStreamingState(){this.streamingTextBuffer="",this.streamingReasoningBuffer="",this.streamingTextPendingId=null,this.streamingReasoningPendingId=null,this.currentThinkingText="",this.runtime.clearPendingEntries(),this.runtime.resetStreamingStats(),this.runtime.setStatusText(""),f.debug("INK_ADAPTER","Reset streaming state");}startReasoningStreaming(){this.startThinking();}streamReasoningText(e){this.streamThinking(e);}addReasoningDelta(e){this.streamThinking(e);}completeReasoningStreaming(){this.endThinking();}addThinking(e){}completeTextStreaming(){if(!this.streamingTextBuffer){f.debug("INK_ADAPTER","Complete text streaming - no text to commit");return}let e={role:"assistant",content:[{type:"text",text:this.streamingTextBuffer}]};this.runtime.addEntry({type:"assistant",message:e,isStreaming:false,isComplete:true}),this.streamingTextBuffer="",this.lastMessageRole="assistant",this.runtime.resetStreamingStats(),f.debug("INK_ADAPTER","Complete text streaming - added to static entries");}printCommandOutput(e){f.info("INK_ADAPTER",`Command output: ${e}`);}startToolCallWithId(e,t,n,r){f.debug("INK_ADAPTER",`Start tool call: ${t}`,{toolId:e,args:n}),this.addToolCall(t,n);}updateToolCallOutput(e,t,n){f.debug("INK_ADAPTER",`Update tool output: ${e}`,{output:t});}completeToolCall(e,t){f.debug("INK_ADAPTER",`Complete tool call: ${e}`),t.result&&this.addToolResult(t.result,t.isError||false);}updateTaskTokens(e,t=false){f.debug("INK_ADAPTER",`Update task tokens: ${e}`,{isActual:t}),!t&&this.runtime.updateStreamingStats(e);}addToolError(e,t){f.error("INK_ADAPTER",`Tool error: ${e}`,{error:t}),this.addToolResult(t,true);}printCommandOutputLines(e){e.forEach(t=>this.printCommandOutput(t));}resetTokenStats(){this.tokenStats={inputTokens:0,outputTokens:0,totalTokens:0},this.runtime.setTokenStats({input:0,output:0,total:0});}pause(){f.debug("INK_ADAPTER","Pause UI");}resume(){f.debug("INK_ADAPTER","Resume UI");}refreshUI(){f.debug("INK_ADAPTER","Refresh UI");}updateProvider(e,t){this.config.provider=e,this.config.model=t,this.runtime.setProvider(e),this.runtime.setModel(t);}setThinkingEnabled(e){this.runtime.setThinkingEnabled(e);}async promptText(e){return null}async promptSelect(e){return new Promise(t=>{let n=e.choices.map(i=>({label:i.title,value:i.value,description:i.description})),r=e.initial||0;if(e.initialValue){let i=e.choices.findIndex(o=>o.value===e.initialValue);i>=0&&(r=i);}this.runtime.showSelectMenu({message:e.message,choices:n,initialIndex:r,onSelect:i=>{this.runtime.hideSelectMenu(),t(i);},onCancel:()=>{this.runtime.hideSelectMenu(),t(null);}});})}handleSelectBack(){return f.debug("INK_ADAPTER","Handle select back"),false}addWebSearchResult(e){if(e.status==="searching"){f.debug("INK_ADAPTER","Skip web search start (waiting for completion)");return}f.debug("INK_ADAPTER","Add web search result",{options:e});let t=e.query||"query",n=e.results?`Found ${e.results.length} results`:void 0;this.runtime.addEntry({type:"web_search",text:t,details:n});}addWebFetchResult(e){if(e.status==="fetching"){f.debug("INK_ADAPTER","Skip web fetch start (waiting for completion)");return}f.debug("INK_ADAPTER","Add web fetch result",{options:e});let t=e.url||"URL",n=e.contentLength?`${(e.contentLength/1024).toFixed(1)}KB`:e.contentPreview?`${e.contentPreview.length} chars`:void 0;this.runtime.addEntry({type:"web_fetch",text:t,details:n});}addReadFileResult(e){if(e.status==="reading"){f.debug("INK_ADAPTER","Skip read file start (waiting for completion)");return}f.debug("INK_ADAPTER","Add read file result",{options:e});let t=e.filePath||"file",n=[];e.totalLines&&n.push(`${e.totalLines} lines`),e.fileSize&&n.push(e.fileSize);let r=n.length>0?n.join(", "):void 0;this.runtime.addEntry({type:"readfile",text:t,details:r});}addSearchResult(e){if(e.status==="searching"){f.debug("INK_ADAPTER","Skip search start (waiting for completion)");return}f.debug("INK_ADAPTER","Add search result",{options:e});let t=[];if(e.pattern&&t.push(`pattern="${e.pattern}"`),e.filePath){let o=e.filePath==="."?".":e.filePath;t.push(`path="${o}"`);}e.mode&&t.push(`mode="${e.mode}"`),e.status==="completed"?e.matchCount!==void 0&&t.push(`matches=${e.matchCount}`):e.status==="error"&&t.push("\u274C ERROR");let n=t.join(", "),r=[];if(e.command){let o=this.simplifyRipgrepCommand(e.command);r.push(`$ ${o}`),r.push("");}e.status==="error"&&e.error?r.push(this.parseErrorMessage(e.error)):e.details&&r.push(e.details);let i=r.length>0?r.join(`
1665
+ `):void 0;this.runtime.addEntry({type:"search",text:n,details:i});}addSearchFilesResult(e){if(e.status==="searching"){f.debug("INK_ADAPTER","Skip search files start (waiting for completion)");return}f.debug("INK_ADAPTER","Add search files result",{options:e});let t=[];e.pattern&&t.push(`pattern="${e.pattern}"`),e.path&&t.push(`path="${e.path}"`),e.fileCount!==void 0&&t.push(`files=${e.fileCount}`);let n=t.length>0?t.join(", "):"Glob";this.runtime.addEntry({type:"search_files",text:n});}addShowTreeResult(e){if(e.status==="loading"){f.debug("INK_ADAPTER","Skip show tree start (waiting for completion)");return}f.debug("INK_ADAPTER","Add show tree result",{options:e});let n=[`path="${e.path||"."}"`];if(e.mode&&n.push(`mode="${e.mode}"`),e.maxDepth!==void 0&&e.maxDepth!==null&&n.push(`depth=${e.maxDepth}`),e.status==="completed"&&e.totalChars){let a=(e.totalChars/1024).toFixed(1);n.push(`${a}KB`);}else e.status==="error"&&n.push("\u274C ERROR");let r=n.join(", "),i=this.formatSmartTreeDetails(e.content),o;e.status==="error"&&e.error?o=`Error: ${e.error}`:i?o=i:e.content&&(o=e.content.length>500?e.content.slice(0,500)+"...":e.content),this.runtime.addEntry({type:"show_tree",text:r,details:o});}addCommandExecResult(e){if(e.status==="running"){f.debug("INK_ADAPTER","Skip command exec start (waiting for completion)");return}f.debug("INK_ADAPTER","Add command exec result",{options:e});let t=`$ ${e.command||"command"}`,n=e.output?.slice(0,500);this.runtime.addEntry({type:"command_exec",text:t,details:n});}addCodeExecResult(e){if(e.status==="running"){f.debug("INK_ADAPTER","Skip code exec start (waiting for completion)");return}f.debug("INK_ADAPTER","Add code exec result",{options:e});let t=`Code: ${e.toolName||"execute"}`,n=e.output?.slice(0,500);this.runtime.addEntry({type:"code_exec",text:t,details:n});}addBrowserDebugResult(e){if(e.status==="detecting"){f.debug("INK_ADAPTER","Skip browser debug start (waiting for completion)");return}f.debug("INK_ADAPTER","Add browser debug result",{data:e});let t=e.url||"unknown",n=[];e.summary&&n.push(e.summary),e.loadTime&&n.push(`Load: ${e.loadTime}ms`),e.consoleLogs&&n.push(`Logs: ${e.consoleLogs}`),e.errors?.length&&n.push(`Errors: ${e.errors.length}`);let r=n.length>0?n.join(", "):void 0;this.runtime.addEntry({type:"browser_debug",text:t,details:r});}formatSmartTreeDetails(e){if(!e)return;let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return;let n;try{n=JSON.parse(t);}catch{return}if(!n||typeof n!="object"||Array.isArray(n)||!["path","project_types","root_dirs","modules","config_files","tip","error"].some(p=>Object.prototype.hasOwnProperty.call(n,p)))return;if(typeof n.error=="string"&&n.error.trim())return `error: ${n.error.trim()}`;let i=[],o=typeof n.path=="string"?n.path.trim():"";o&&i.push(`\u{1F4C1} Path: ${o}`);let a=this.formatSmartTreeList(n.project_types,6);a!==void 0&&i.push(`\u{1F4E6} Project Type: ${a}`);let l=this.formatSmartTreeList(n.root_dirs,12);l!==void 0&&i.push(`\u{1F4C2} Root Directories: ${l}`);let c=this.formatSmartTreeList(n.modules,12);c!==void 0&&i.push(`\u{1F527} Modules: ${c}`);let u=this.formatSmartTreeList(n.config_files,8);u!==void 0&&i.push(`\u2699\uFE0F Config Files: ${u}`);let d=typeof n.tip=="string"?n.tip.trim():"";if(d&&i.push(`\u{1F4A1} Tip: ${d}`),i.length!==0)return i.join(`
1666
+ `)}formatSmartTreeList(e,t){if(!Array.isArray(e))return;let n=e.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>a.length>0);if(n.length===0)return "(none)";let r=n.slice(0,t),i=n.length-r.length,o=i>0?` ...(+${i} more)`:"";return `${r.join(", ")}${o}`}addWriteFileCall(e,t){f.debug("INK_ADAPTER","Add write file call",{filePath:e});let n=t.split(`
1667
+ `),r=n.length,i=n.slice(0,15),o=String(Math.min(r,15)).length,a=[];a.push(`+++ new: ${r} lines`),a.push("");for(let u=0;u<i.length;u++){let d=String(u+1).padStart(o," ");a.push(`${d} + ${i[u]}`);}r>15&&a.push(` ... (${r-15} more lines)`);let l=`Writing ${e} (${r} lines)`,c=a.join(`
1668
+ `);this.runtime.addEntry({type:"file_update",text:l,details:c});}addEditFileCall(e,t,n,r){f.debug("INK_ADAPTER","Add edit file call",{filePath:e});let i=t?t.split(`
1669
+ `):[],o=n?n.split(`
1670
+ `):[],a=r||1,l=[];l.push(`\u2500\u2500\u2500 old: ${i.length} lines`),l.push(`+++ new: ${o.length} lines`),l.push("");let c=a+Math.max(i.length,o.length),u=String(c).length,d=Math.max(i.length,o.length);for(let h=0;h<d;h++){let g=a+h,y=String(g).padStart(u," "),x=i[h],S=o[h];x!==void 0&&l.push(`${y} - ${x}`),S!==void 0&&l.push(`${y} + ${S}`);}let p=`Editing ${e}${r?` @${r}`:""}`,m=l.join(`
1671
+ `);this.runtime.addEntry({type:"file_update",text:p,details:m});}addEditFileResult(e){f.debug("INK_ADAPTER","Add edit file result",{options:e}),process.env.CLI_DEBUG==="1"&&f.debug("INK_ADAPTER","Edit file result (already shown)",{filePath:e.filePath,status:e.status,summary:e.summary});}addFileUpdate(e,t,n,r){f.debug("INK_ADAPTER","Add file update",{filePath:e,description:n});let i=e,o=`${n} (${t.length} lines)`;this.runtime.addEntry({type:"file_update",text:i,details:o});}startEditFile(e,t,n,r,i,o,a){f.debug("INK_ADAPTER","Start edit file",{filePath:e,startLine:i,description:o});let l=[];o&&(l.push(o),l.push(""));let c=(p,m,h,g)=>{g&&l.push(g),l.push(`\u2500\u2500\u2500 old: ${p.length} lines`),l.push(`+++ new: ${m.length} lines`),l.push("");let y=h+Math.max(p.length,m.length),x=String(y).length,S=Math.max(p.length,m.length);for(let T=0;T<S;T++){let w=h+T,L=String(w).padStart(x," "),B=p[T],I=m[T];B!==void 0&&l.push(`${L} - ${B}`),I!==void 0&&l.push(`${L} + ${I}`);}l.push("");};if(a&&a.length>0)a.forEach((p,m)=>{let h=a.length>1?`Hunk ${m+1}/${a.length}:`:void 0,g=p.oldString?p.oldString.split(`
1672
+ `):[],y=p.newString?p.newString.split(`
1673
+ `):[];c(g,y,p.startLine||1,h);});else {let p=n?n.split(`
1674
+ `):[],m=r?r.split(`
1675
+ `):[];c(p,m,i||1);}let u=`Editing ${e}${i?` @${i}`:""}`,d=l.join(`
1676
+ `);this.runtime.addEntry({type:"file_update",text:u,details:d});}startWriteFile(e,t,n,r){f.debug("INK_ADAPTER","Start write file",{filePath:e,description:r});let i=n.split(`
1677
+ `),o=[];r&&(o.push(r),o.push("")),o.push(`+++ new file: ${i.length} lines`),o.push("");let a=String(i.length).length,l=500,c=Math.min(i.length,l);for(let p=0;p<c;p++){let m=p+1,h=String(m).padStart(a," ");o.push(`${h} + ${i[p]}`);}i.length>l&&(o.push(""),o.push(`... (${i.length-l} more lines omitted)`));let u=`Creating ${e}`,d=o.join(`
1678
+ `);this.runtime.addEntry({type:"file_update",text:u,details:d});}updateCodeGenerationPreview(e,t,n,r){f.debug("INK_ADAPTER","Update code generation preview",{filePath:e});let i=e,o=r||`${n} (${t.length} bytes)`;this.runtime.addEntry({type:"file_update",text:i,details:o});}completeCodeGenerationPreview(e,t){f.debug("INK_ADAPTER","Complete code generation preview",{filePath:e});let n=e;this.runtime.addEntry({type:"file_update",text:n});}parseCodeToDiff(e,t=true){return f.debug("INK_ADAPTER","Parse code to diff"),[]}updateSelectList(e){f.debug("INK_ADAPTER","Update select list",{selectedIndex:e});}getRunningToolLogId(e){}attachImage(e){f.debug("INK_ADAPTER","Attach image",{path:e});}checkAndRecoverInput(){f.debug("INK_ADAPTER","Check and recover input");}stopHealthMonitoring(){f.debug("INK_ADAPTER","Stop health monitoring");}flushRenderScheduler(){f.debug("INK_ADAPTER","Flush render scheduler (no-op for Ink)");}getLastMessageText(){if(!this.lastEntryId)return "";let e=this.runtime.getEntry(this.lastEntryId);if(!e||!e.message)return "";let t=e.message;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)){let n=t.content.find(r=>r.type==="text");if(n&&"text"in n)return n.text||""}return ""}parseErrorMessage(e){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}"))try{let n=JSON.parse(t),r=[];return n.summary?r.push(n.summary):n.error&&r.push(n.error),n.tool&&r.push(`Tool: ${n.tool}`),n.status&&n.status!=="error"&&r.push(`Status: ${n.status}`),n.metadata&&(n.metadata.exit_code!==void 0&&r.push(`Exit code: ${n.metadata.exit_code}`),n.metadata.command&&r.push(`Command: ${n.metadata.command}`)),r.length>0?r.join(`
1679
+ `):e}catch{}return e.startsWith("Error:")?e:`Error: ${e}`}simplifyRipgrepCommand(e){let t=e.split(/\s+/),n=[],r=false,i=0;for(let o=0;o<t.length;o++){if(r){r=false;continue}let a=t[o];if(a.includes("/rg")||a.includes("\\rg")){n.push("rg");continue}if(o===t.length-1&&a.startsWith("/")){let l=process.cwd();if(a===l)n.push(".");else if(a.startsWith(l+"/")){let c=a.substring(l.length+1);n.push(c||".");}else {let c=a.split("/").pop()||".";n.push(c);}continue}if(a==="-g"){if(i++,i<=2)n.push(a),o+1<t.length&&(n.push(t[o+1]),r=true);else if(i===3){let l=t.slice(o).filter(c=>c==="-g").length;for(n.push(`... (+${l} more -g)`);o<t.length&&(t[o]==="-g"||o>0&&t[o-1]==="-g");)t[o]==="-g"&&o+1<t.length&&o++,o++;o--;}continue}n.push(a);}return n.join(" ")}};var Bo={warn:.7,soft:.8,hard:.95},$c=2e4,H_=[{kind:"exact",value:"gpt-5.2",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.2-pro",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.2-chat-latest",contextWindow:128e3,maxOutputTokens:16384},{kind:"prefix",value:"gpt-5.2-",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.1-codex-max",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.1-codex",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.1-codex-mini",contextWindow:128e3,maxOutputTokens:32e3},{kind:"prefix",value:"gpt-5.1-codex-",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5.1",contextWindow:4e5,maxOutputTokens:128e3},{kind:"prefix",value:"gpt-5.1-",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"gpt-5",contextWindow:4e5,maxOutputTokens:128e3},{kind:"prefix",value:"gpt-5-",contextWindow:4e5,maxOutputTokens:128e3},{kind:"exact",value:"codex-1",contextWindow:192e3,maxOutputTokens:42e3},{kind:"exact",value:"codex-mini-latest",contextWindow:128e3,maxOutputTokens:32e3},{kind:"prefix",value:"codex-",contextWindow:192e3,maxOutputTokens:42e3},{kind:"exact",value:"o3",contextWindow:2e5,maxOutputTokens:1e5},{kind:"exact",value:"o4-mini",contextWindow:2e5,maxOutputTokens:1e5},{kind:"prefix",value:"o3-",contextWindow:2e5,maxOutputTokens:1e5},{kind:"prefix",value:"o4-",contextWindow:2e5,maxOutputTokens:1e5},{kind:"exact",value:"claude-opus-4-5-20251101",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4-5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4.5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4-1-20250630",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4-1",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4.1",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-opus-4-20250514",contextWindow:2e5,maxOutputTokens:64e3},{kind:"prefix",value:"claude-opus-4",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-sonnet-4-5-20250929",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-sonnet-4-5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-sonnet-4.5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-sonnet-4-20250514",contextWindow:2e5,maxOutputTokens:64e3},{kind:"prefix",value:"claude-sonnet-4",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-haiku-4-5-20250929",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-haiku-4-5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"claude-haiku-4.5",contextWindow:2e5,maxOutputTokens:64e3},{kind:"prefix",value:"claude-haiku-4",contextWindow:2e5,maxOutputTokens:64e3},{kind:"prefix",value:"claude-3-5-sonnet",contextWindow:2e5,maxOutputTokens:8192},{kind:"prefix",value:"claude-3.5-sonnet",contextWindow:2e5,maxOutputTokens:8192},{kind:"prefix",value:"claude-3-5-haiku",contextWindow:2e5,maxOutputTokens:8192},{kind:"prefix",value:"claude-3.5-haiku",contextWindow:2e5,maxOutputTokens:8192},{kind:"prefix",value:"claude-3-opus",contextWindow:2e5,maxOutputTokens:4096},{kind:"prefix",value:"claude-3-sonnet",contextWindow:2e5,maxOutputTokens:4096},{kind:"prefix",value:"claude-3-haiku",contextWindow:2e5,maxOutputTokens:4096},{kind:"prefix",value:"claude-2",contextWindow:1e5,maxOutputTokens:4096},{kind:"prefix",value:"claude-instant",contextWindow:1e5,maxOutputTokens:4096},{kind:"prefix",value:"claude-",contextWindow:2e5,maxOutputTokens:64e3},{kind:"exact",value:"doubao-seed-1-6",contextWindow:256e3,maxOutputTokens:16e3},{kind:"exact",value:"doubao-seed-1-6-thinking",contextWindow:256e3,maxOutputTokens:16e3},{kind:"exact",value:"doubao-seed-1-6-flash",contextWindow:256e3,maxOutputTokens:16e3},{kind:"exact",value:"doubao-seed-1-6-vision",contextWindow:256e3,maxOutputTokens:16e3},{kind:"prefix",value:"doubao-seed-1-6",contextWindow:256e3,maxOutputTokens:16e3},{kind:"exact",value:"doubao-seed-code",contextWindow:256e3,maxOutputTokens:32e3},{kind:"prefix",value:"doubao-seed-code",contextWindow:256e3,maxOutputTokens:32e3},{kind:"prefix",value:"doubao-seed",contextWindow:256e3,maxOutputTokens:16e3},{kind:"exact",value:"doubao-pro-128k",contextWindow:128e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-pro-32k",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-pro-8k",contextWindow:8e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-pro-4k",contextWindow:4e3,maxOutputTokens:4096},{kind:"prefix",value:"doubao-pro",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-1-5-pro-32k",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"doubao-1-5-lite-32k",contextWindow:32e3,maxOutputTokens:8192},{kind:"prefix",value:"doubao-1-5",contextWindow:32e3,maxOutputTokens:8192},{kind:"prefix",value:"doubao-1.5",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"doubao-lite-32k",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-lite-8k",contextWindow:8e3,maxOutputTokens:4096},{kind:"exact",value:"doubao-lite-4k",contextWindow:4e3,maxOutputTokens:4096},{kind:"prefix",value:"doubao-lite",contextWindow:32e3,maxOutputTokens:4096},{kind:"prefix",value:"doubao-",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"kimi-k2-thinking",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2-thinking-turbo",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2-turbo-preview",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2-turbo",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2-instruct-0905",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2-instruct",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-k2",contextWindow:128e3,maxOutputTokens:64e3},{kind:"prefix",value:"kimi-k2",contextWindow:256e3,maxOutputTokens:64e3},{kind:"exact",value:"kimi-linear",contextWindow:1e6,maxOutputTokens:64e3},{kind:"prefix",value:"kimi-linear",contextWindow:1e6,maxOutputTokens:64e3},{kind:"exact",value:"kimi-dev-72b",contextWindow:128e3,maxOutputTokens:32e3},{kind:"exact",value:"kimi-dev",contextWindow:128e3,maxOutputTokens:32e3},{kind:"prefix",value:"kimi-dev",contextWindow:128e3,maxOutputTokens:32e3},{kind:"exact",value:"kimi-vl",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"kimi-vl",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"kimi-k1.5",contextWindow:128e3,maxOutputTokens:32e3},{kind:"exact",value:"kimi-k1-5",contextWindow:128e3,maxOutputTokens:32e3},{kind:"exact",value:"moonshot-v1-128k",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"moonshot-v1-32k",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"moonshot-v1-8k",contextWindow:8e3,maxOutputTokens:8192},{kind:"exact",value:"moonshot-v1-128k-vision-preview",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"moonshot-v1-32k-vision-preview",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"moonshot-v1-8k-vision-preview",contextWindow:8e3,maxOutputTokens:8192},{kind:"prefix",value:"moonshot-v1",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"moonshot-",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"kimi-",contextWindow:128e3,maxOutputTokens:64e3},{kind:"exact",value:"qwen-long",contextWindow:1e7,maxOutputTokens:8192},{kind:"exact",value:"qwen-plus",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"qwen-turbo",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"qwen-flash",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"qwen3-coder-plus",contextWindow:1e6,maxOutputTokens:65536},{kind:"prefix",value:"qwen3-coder",contextWindow:1e6,maxOutputTokens:65536},{kind:"exact",value:"qwen3-235b-a22b-instruct",contextWindow:256e3,maxOutputTokens:8192},{kind:"prefix",value:"qwen3-235b",contextWindow:256e3,maxOutputTokens:8192},{kind:"exact",value:"qwen3-vl-plus",contextWindow:256e3,maxOutputTokens:32e3},{kind:"prefix",value:"qwen3-vl",contextWindow:256e3,maxOutputTokens:32e3},{kind:"exact",value:"qwen2.5-14b-instruct-1m",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"qwen2.5-7b-instruct-1m",contextWindow:1e6,maxOutputTokens:8192},{kind:"prefix",value:"qwen2.5-",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"qwen-max",contextWindow:32768,maxOutputTokens:8192},{kind:"prefix",value:"qwen-vl",contextWindow:131072,maxOutputTokens:8192},{kind:"prefix",value:"qwen",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"deepseek-v3.1",contextWindow:128e3,maxOutputTokens:8e3},{kind:"exact",value:"deepseek-v3-1",contextWindow:128e3,maxOutputTokens:8e3},{kind:"exact",value:"deepseek-chat",contextWindow:64e3,maxOutputTokens:8e3},{kind:"exact",value:"deepseek-v3",contextWindow:64e3,maxOutputTokens:8e3},{kind:"exact",value:"deepseek-reasoner",contextWindow:64e3,maxOutputTokens:64e3},{kind:"exact",value:"deepseek-r1",contextWindow:64e3,maxOutputTokens:64e3},{kind:"prefix",value:"deepseek-r1",contextWindow:64e3,maxOutputTokens:64e3},{kind:"prefix",value:"deepseek-coder",contextWindow:64e3,maxOutputTokens:8e3},{kind:"prefix",value:"deepseek-",contextWindow:64e3,maxOutputTokens:8e3},{kind:"exact",value:"glm-4.6",contextWindow:2e5,maxOutputTokens:128e3},{kind:"exact",value:"glm-4-6",contextWindow:2e5,maxOutputTokens:128e3},{kind:"prefix",value:"glm-4.6",contextWindow:2e5,maxOutputTokens:128e3},{kind:"prefix",value:"glm-4-6",contextWindow:2e5,maxOutputTokens:128e3},{kind:"exact",value:"glm-4.5",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"glm-4-5",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"glm-4-plus",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"glm-4-long",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"glm-4",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"glm-4-flash",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"glm-4",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"chatglm",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"glm-",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"baichuan2-turbo",contextWindow:192e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan2-turbo-192k",contextWindow:192e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan4",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan4-turbo",contextWindow:128e3,maxOutputTokens:4096},{kind:"prefix",value:"baichuan4",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan3-turbo",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan3-turbo-128k",contextWindow:128e3,maxOutputTokens:4096},{kind:"prefix",value:"baichuan3",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"baichuan2-53b",contextWindow:4096,maxOutputTokens:4096},{kind:"exact",value:"baichuan2-13b",contextWindow:4096,maxOutputTokens:4096},{kind:"exact",value:"baichuan2-7b",contextWindow:4096,maxOutputTokens:4096},{kind:"prefix",value:"baichuan2",contextWindow:32e3,maxOutputTokens:4096},{kind:"prefix",value:"baichuan",contextWindow:32e3,maxOutputTokens:4096},{kind:"exact",value:"minimax-text-01",contextWindow:4e6,maxOutputTokens:16384},{kind:"exact",value:"minimax-m1-80k",contextWindow:1e6,maxOutputTokens:8e4},{kind:"exact",value:"minimax-m1-40k",contextWindow:1e6,maxOutputTokens:4e4},{kind:"exact",value:"minimax-m1",contextWindow:1e6,maxOutputTokens:8e4},{kind:"exact",value:"minimax-m2",contextWindow:1e6,maxOutputTokens:8e4},{kind:"exact",value:"abab-5.5",contextWindow:256e3,maxOutputTokens:8192},{kind:"exact",value:"abab-5.5-chat",contextWindow:256e3,maxOutputTokens:8192},{kind:"exact",value:"abab-6.5",contextWindow:256e3,maxOutputTokens:8192},{kind:"prefix",value:"abab-",contextWindow:256e3,maxOutputTokens:8192},{kind:"prefix",value:"minimax-",contextWindow:256e3,maxOutputTokens:8192},{kind:"exact",value:"gemini-2.5-pro",contextWindow:2e6,maxOutputTokens:65536},{kind:"prefix",value:"gemini-2.5-pro",contextWindow:2e6,maxOutputTokens:65536},{kind:"exact",value:"gemini-2.5-flash",contextWindow:1e6,maxOutputTokens:65536},{kind:"prefix",value:"gemini-2.5-flash",contextWindow:1e6,maxOutputTokens:65536},{kind:"exact",value:"gemini-2.0-flash",contextWindow:1e6,maxOutputTokens:8192},{kind:"prefix",value:"gemini-2.0",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"gemini-1.5-pro",contextWindow:2e6,maxOutputTokens:8192},{kind:"exact",value:"gemini-1.5-pro-002",contextWindow:2e6,maxOutputTokens:8192},{kind:"exact",value:"gemini-1.5-flash",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"gemini-1.5-flash-002",contextWindow:1e6,maxOutputTokens:8192},{kind:"prefix",value:"gemini-1.5",contextWindow:1e6,maxOutputTokens:8192},{kind:"prefix",value:"gemini-1.0",contextWindow:32768,maxOutputTokens:8192},{kind:"prefix",value:"gemini-",contextWindow:1e6,maxOutputTokens:8192},{kind:"exact",value:"mistral-large",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"mistral-medium",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"mistral-small",contextWindow:32e3,maxOutputTokens:8192},{kind:"prefix",value:"mistral-",contextWindow:32e3,maxOutputTokens:8192},{kind:"exact",value:"llama-3.3-70b",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"llama-3.2-90b",contextWindow:128e3,maxOutputTokens:8192},{kind:"exact",value:"llama-3.1-405b",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"llama-3",contextWindow:128e3,maxOutputTokens:8192},{kind:"prefix",value:"llama-",contextWindow:128e3,maxOutputTokens:8192}];function J_(s){let e=s.toLowerCase();return H_.find(t=>{let n=t.value.toLowerCase();return t.kind==="exact"?e===n:e.startsWith(n)})}function z_(s,e){return {warn:e?.warn??s?.warn??Bo.warn,soft:e?.soft??s?.soft??Bo.soft,hard:e?.hard??s?.hard??Bo.hard}}function q_(s,e){if(e!==void 0)return e;if(s)return Math.floor(s*9/10)}function K_(s,e){if(e!==void 0)return e;if(!s)return $c;let t=Math.floor(s*.15);return Math.min($c,t||$c)}function Gh(s,e){let t=J_(s),n=e?.contextWindow??t?.contextWindow,r=q_(n,e?.autoCompactTokenLimit??t?.autoCompactLimit),i=K_(n,e?.tailTokenBudget??t?.tailTokenBudget),o=z_(t?.warnThresholds??Bo,e?.warnThresholds);return {model:s,contextWindow:n,autoCompactLimit:r,maxOutputTokens:e?.maxOutputTokens??t?.maxOutputTokens,tailTokenBudget:i,warnThresholds:o,source:e?"override":t?"baseline":"unknown"}}function Nc(){return `sess_${jo.randomBytes(16).toString("hex")}`}function Uc(){return `iter_${jo.randomBytes(16).toString("hex")}`}function ks(){return `span_${jo.randomBytes(16).toString("hex")}`}function ut(){return new Date().toISOString()}function Yr(s,e){let t=new Date(s).getTime();return new Date(e).getTime()-t}function Xr(s,e=100){if(!s)return "";let t=s.trim().replace(/\s+/g," ");return t.length<=e?t:t.substring(0,e-3)+"..."}function Go(s,e=200){if(s==null)return String(s);try{let t=JSON.stringify(s);return Xr(t,e)}catch{return "[Circular or Invalid JSON]"}}function Wo(s){return s<1e3?`${Math.round(s)}ms`:`${(s/1e3).toFixed(1)}s`}function Wh(s){let e=new WeakSet;return JSON.stringify(s,(t,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return n})}function wn(){let s=new Date,e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}async function Hh(s){let e=await import('fs');await import('path');await e.promises.mkdir(s,{recursive:true});}var Zr=class{enabled;exporters=[];currentSession=null;currentIteration=null;thinkingBuffer="";thinkingStartTime=null;sessions=new Map;maxSessionsInMemory=100;constructor(e={}){this.enabled=e.enabled??true,e.exporters&&(this.exporters=e.exporters);}addExporter(e){this.exporters.push(e);}removeExporter(e){let t=this.exporters.indexOf(e);t!==-1&&this.exporters.splice(t,1);}setEnabled(e){this.enabled=e;}isEnabled(){return this.enabled}startSession(e){if(!this.enabled)return "";let t={session_id:Nc(),user_input:e,started_at:ut(),iterations:[],total_tokens:{input:0,output:0,total:0},result:"pending"};if(this.currentSession=t,this.sessions.set(t.session_id,t),this.sessions.size>this.maxSessionsInMemory){let r=this.sessions.keys().next().value;r&&this.sessions.delete(r);}let n={type:"session_start",session_id:t.session_id,user_input:e,timestamp:t.started_at};return this.exportEvent(n),t.session_id}endSession(e,t){if(!this.enabled||!this.currentSession)return;let n=ut();this.currentSession.ended_at=n,this.currentSession.duration_ms=Yr(this.currentSession.started_at,n),this.currentSession.result=e;let r;t&&(r={message:t.message||"Unknown error",...t.stack&&{stack:t.stack},...t.data&&typeof t.data=="object"&&{data:this.safeSerialize(t.data)}},this.currentSession.error=r);let i={type:"session_end",session_id:this.currentSession.session_id,result:e,total_tokens:this.currentSession.total_tokens,duration_ms:this.currentSession.duration_ms,timestamp:n,error:r};this.exportEvent(i),this.currentSession=null,this.currentIteration=null;}startIteration(){if(!this.enabled||!this.currentSession)return "";let e={iteration_id:Uc(),number:this.currentSession.iterations.length+1,started_at:ut(),spans:[],token_usage:{input:0,output:0,total:0}};this.currentIteration=e,this.currentSession.iterations.push(e),this.thinkingBuffer="",this.thinkingStartTime=null;let t={type:"iteration_start",session_id:this.currentSession.session_id,iteration:e.number,timestamp:e.started_at};return this.exportEvent(t),e.iteration_id}endIteration(){if(!this.enabled||!this.currentIteration||!this.currentSession)return;this.thinkingBuffer&&this.completeThinking();let e=ut();this.currentIteration.ended_at=e,this.currentIteration.duration_ms=Yr(this.currentIteration.started_at,e),this.currentSession.total_tokens.input+=this.currentIteration.token_usage.input,this.currentSession.total_tokens.output+=this.currentIteration.token_usage.output,this.currentSession.total_tokens.total=this.currentSession.total_tokens.input+this.currentSession.total_tokens.output;let t={type:"iteration_end",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,duration_ms:this.currentIteration.duration_ms,token_usage:this.currentIteration.token_usage,timestamp:e};this.exportEvent(t);}logThinkingDelta(e){if(!this.enabled||!this.currentIteration||!this.currentSession)return;this.thinkingStartTime||(this.thinkingStartTime=ut()),this.thinkingBuffer+=e;let t={type:"thinking_delta",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,delta:e,timestamp:ut()};this.exportEvent(t);}completeThinking(e="unknown",t){if(!this.enabled||!this.currentIteration||!this.currentSession||!this.thinkingBuffer)return;let n=ut(),r=this.thinkingStartTime||n,i={span_id:ks(),type:"thinking",model:e,input_tokens:t?.input||0,output_tokens:t?.output||0,content:this.thinkingBuffer,content_preview:Xr(this.thinkingBuffer,100),started_at:r,ended_at:n,duration_ms:Yr(r,n)};this.currentIteration.spans.push(i),t&&(this.currentIteration.token_usage.input+=t.input,this.currentIteration.token_usage.output+=t.output,this.currentIteration.token_usage.total=this.currentIteration.token_usage.input+this.currentIteration.token_usage.output);let o={type:"thinking",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,model:e,content:this.thinkingBuffer,content_preview:i.content_preview,tokens:{input:i.input_tokens,output:i.output_tokens},duration_ms:i.duration_ms||0,timestamp:n};this.exportEvent(o),this.thinkingBuffer="",this.thinkingStartTime=null;}updateTokens(e,t){this.enabled&&this.thinkingBuffer&&this.completeThinking(e,t);}logToolCall(e,t,n,r,i){if(!this.enabled||!this.currentIteration||!this.currentSession)return;let o=ut(),a=ut(),l={span_id:ks(),type:"tool_call",tool_name:e,arguments:t,arguments_preview:Go(t,200),result:n,result_preview:Go(n,200),success:r,started_at:a,ended_at:o,duration_ms:0,error:i};this.currentIteration.spans.push(l);let c={type:"tool_call",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,tool_name:e,arguments_preview:l.arguments_preview,result_preview:l.result_preview,success:r,duration_ms:l.duration_ms||0,timestamp:o,error:i};this.exportEvent(c);}logResponse(e){if(!this.enabled||!this.currentIteration||!this.currentSession)return;let t=ut(),n={span_id:ks(),type:"response",content:e,content_preview:Xr(e,100),started_at:t,ended_at:t};this.currentIteration.spans.push(n);let r={type:"response",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,content:e,content_preview:n.content_preview,timestamp:t};this.exportEvent(r);}logGuardrail(e,t,n){if(!this.enabled||!this.currentIteration||!this.currentSession)return;let r=ut(),i={span_id:ks(),type:"guardrail",guardrail_type:e,triggered:t,reason:n,started_at:r,ended_at:r};this.currentIteration.spans.push(i);let o={type:"guardrail",session_id:this.currentSession.session_id,iteration:this.currentIteration.number,guardrail_type:e,triggered:t,reason:n,timestamp:r};this.exportEvent(o);}getCurrentSession(){return this.currentSession}getSession(e){return this.sessions.get(e)||null}getAllSessionIds(){return Array.from(this.sessions.keys())}safeSerialize(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>{try{return this.safeSerialize(n)}catch{return "[Serialization Error]"}});let t={};try{for(let n in e)if(e.hasOwnProperty(n)){let r=e[n];if(typeof r=="function"||r&&typeof r=="object"&&(r.constructor?.name==="TLSSocket"||r.constructor?.name==="Socket"||r.constructor?.name==="HTTPParser"))continue;try{JSON.stringify(r),t[n]=r;}catch{t[n]="[Circular or Invalid]";}}}catch{return "[Serialization Error]"}return t}async exportEvent(e){if(!this.enabled)return;let t=this.exporters.map(n=>n.export(e).catch(r=>{console.error("[AgentLogger] Exporter failed:",r);}));await Promise.all(t);}async flush(){let e=this.exporters.map(t=>t.flush().catch(n=>{console.error("[AgentLogger] Flush failed:",n);}));await Promise.all(e);}async close(){await this.flush();let e=this.exporters.map(t=>t.close().catch(n=>{console.error("[AgentLogger] Close failed:",n);}));await Promise.all(e);}};var Qr=class{logDir;autoRotate;bufferSize;buffer=[];currentFilePath=null;writeStream=null;constructor(e={}){this.logDir=e.logDir||te.join(ti.homedir(),".neox","traces"),this.autoRotate=e.autoRotate??true,this.bufferSize=e.bufferSize??10;}async export(e){try{await Hh(this.logDir);let t=this.getLogFilePath();this.currentFilePath!==t&&(await this.closeStream(),this.currentFilePath=t),this.writeStream||(this.writeStream=an.createWriteStream(t,{flags:"a"}));let n=Wh(e)+`
1680
+ `;this.buffer.push(n),this.buffer.length>=this.bufferSize&&await this.flush();}catch(t){console.error("[FileExporter] Failed to export event:",t);}}async flush(){if(!(this.buffer.length===0||!this.writeStream))try{let e=this.buffer.join("");return this.buffer=[],new Promise((t,n)=>{this.writeStream.write(e,r=>{r?n(r):t();});})}catch(e){console.error("[FileExporter] Failed to flush buffer:",e);}}async close(){await this.flush(),await this.closeStream();}async closeStream(){if(this.writeStream)return new Promise(e=>{this.writeStream.end(()=>{this.writeStream=null,e();});})}getLogFilePath(){if(this.autoRotate){let e=wn();return te.join(this.logDir,`${e}.jsonl`)}else return te.join(this.logDir,"traces.jsonl")}getLogDir(){return this.logDir}getCurrentLogFile(){return this.currentFilePath}};var Fc=class{constructor(e){this.enabled=e;}dim(e){return this.enabled?`\x1B[2m${e}\x1B[0m`:e}gray(e){return this.enabled?`\x1B[90m${e}\x1B[0m`:e}green(e){return this.enabled?`\x1B[32m${e}\x1B[0m`:e}yellow(e){return this.enabled?`\x1B[33m${e}\x1B[0m`:e}blue(e){return this.enabled?`\x1B[34m${e}\x1B[0m`:e}magenta(e){return this.enabled?`\x1B[35m${e}\x1B[0m`:e}cyan(e){return this.enabled?`\x1B[36m${e}\x1B[0m`:e}red(e){return this.enabled?`\x1B[31m${e}\x1B[0m`:e}bold(e){return this.enabled?`\x1B[1m${e}\x1B[0m`:e}},ei=class{options;colors;constructor(e={}){this.options={showTimestamp:e.showTimestamp??true,showSessionId:e.showSessionId??false,verbose:e.verbose??false,useColors:e.useColors??true},this.colors=new Fc(this.options.useColors);}formatTimestamp(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),i=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return `${n}:${r}:${i}.${o}`}formatEvent(e){let t=[],n=[];if(this.options.showTimestamp&&"timestamp"in e&&n.push(this.colors.gray(this.formatTimestamp(e.timestamp))),this.options.showSessionId&&"session_id"in e){let i=e.session_id.slice(-8);n.push(this.colors.dim(`[${i}]`));}let r=n.length>0?n.join(" ")+" ":"";switch(e.type){case "session_start":t.push(r+this.colors.bold(this.colors.green("\u2501\u2501\u2501 \u4F1A\u8BDD\u5F00\u59CB \u2501\u2501\u2501"))),t.push(r+this.colors.cyan("\u7528\u6237\u8F93\u5165: ")+this.colors.bold(e.user_input));break;case "session_end":let i=e.result==="success"?this.colors.green:e.result==="error"?this.colors.red:this.colors.yellow;t.push(r+this.colors.bold(i(`\u2501\u2501\u2501 \u4F1A\u8BDD\u7ED3\u675F (${e.result}) \u2501\u2501\u2501`))),e.total_tokens&&t.push(r+this.colors.gray(`\u603B Tokens: ${e.total_tokens.input} \u8F93\u5165 + ${e.total_tokens.output} \u8F93\u51FA = ${e.total_tokens.total}`)),e.duration_ms!==void 0&&t.push(r+this.colors.gray(`\u8017\u65F6: ${Wo(e.duration_ms)}`)),e.error&&t.push(r+this.colors.red(`\u9519\u8BEF: ${e.error.message}`));break;case "iteration_start":t.push(r+this.colors.blue(`\u250C\u2500 \u7B2C ${e.iteration} \u8F6E\u601D\u8003\u5F00\u59CB`));break;case "iteration_end":t.push(r+this.colors.blue(`\u2514\u2500 \u7B2C ${e.iteration} \u8F6E\u601D\u8003\u7ED3\u675F`)),this.options.verbose&&e.token_usage&&t.push(r+this.colors.gray(` Tokens: ${e.token_usage.input} \u2192 ${e.token_usage.output}`));break;case "thinking_delta":break;case "thinking":t.push(r+this.colors.magenta("\u{1F4AD} \u601D\u8003: ")+e.content_preview),this.options.verbose&&e.tokens&&t.push(r+this.colors.gray(` Model: ${e.model}, Tokens: ${e.tokens.input} \u2192 ${e.tokens.output}`));break;case "tool_call":let o=e.success?"[*]":"[x]",a=e.success?this.colors.cyan:this.colors.red;t.push(r+a(`${o} \u5DE5\u5177\u8C03\u7528: ${e.tool_name}`)),this.options.verbose&&(t.push(r+this.colors.gray(` \u53C2\u6570: ${e.arguments_preview}`)),t.push(r+this.colors.gray(` \u7ED3\u679C: ${e.result_preview}`))),!e.success&&e.error&&t.push(r+this.colors.red(` \u9519\u8BEF: ${e.error.message}`));break;case "response":t.push(r+this.colors.green("\u2713 \u54CD\u5E94: ")+e.content_preview);break;case "guardrail":e.triggered&&t.push(r+this.colors.yellow(`\u26A0\uFE0F \u5B88\u62A4\u680F\u89E6\u53D1 (${e.guardrail_type}): ${e.reason||"\u65E0\u539F\u56E0"}`));break;default:this.options.verbose&&t.push(r+this.colors.gray(`[${e.type}] ${JSON.stringify(e)}`));}return t.join(`
1681
+ `)}async formatFile(e){let t=[],n=an.createReadStream(e),r=zo.createInterface({input:n,crlfDelay:1/0});for await(let i of r)if(i.trim())try{let o=JSON.parse(i),a=this.formatEvent(o);a&&t.push(a);}catch{this.options.verbose&&t.push(this.colors.red(`\u89E3\u6790\u9519\u8BEF: ${i.slice(0,50)}...`));}return t.join(`
1682
+ `)}async formatSession(e,t){let n=[],r=an.createReadStream(e),i=zo.createInterface({input:r,crlfDelay:1/0});for await(let o of i)if(o.trim())try{let a=JSON.parse(o);if("session_id"in a&&a.session_id===t){let l=this.formatEvent(a);l&&n.push(l);}}catch{}return n.join(`
1683
+ `)}async getSessionSummaries(e){let t=new Map,n=an.createReadStream(e),r=zo.createInterface({input:n,crlfDelay:1/0});for await(let i of r)if(i.trim())try{let o=JSON.parse(i);if(o.type==="session_start")t.set(o.session_id,{session_id:o.session_id,user_input:o.user_input,timestamp:o.timestamp});else if(o.type==="session_end"){let a=t.get(o.session_id);a&&(a.result=o.result,a.total_tokens=o.total_tokens?.total,a.duration_ms=o.duration_ms);}}catch{}return Array.from(t.values())}};async function jc(s){let{logDir:e,retentionDays:t=7,dryRun:r=false}=s,i={filesDeleted:0,deletedFiles:[],bytesFreed:0,filesRetained:0,dryRun:r};try{await he.access(e);}catch{return i}let o=await he.readdir(e),a=/^\d{4}-\d{2}-\d{2}\.jsonl$/,l=o.filter(p=>a.test(p)),c=new Date,u=new Date(c);u.setDate(u.getDate()-t);let d=V_(u);for(let p of l)if(p.replace(".jsonl","")<d){let h=te.join(e,p),y=(await he.stat(h)).size;r||await he.unlink(h),i.filesDeleted++,i.deletedFiles.push(p),i.bytesFreed+=y;}else i.filesRetained++;return i}function V_(s){let e=s.getFullYear(),t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return `${e}-${t}-${n}`}async function Gc(s){let e={totalFiles:0,totalSize:0,oldestFile:null,newestFile:null,files:[]};try{await he.access(s);}catch{return e}let t=await he.readdir(s),n=/^\d{4}-\d{2}-\d{2}\.jsonl$/,r=t.filter(a=>n.test(a)),i=new Date;wn();for(let a of r){let l=te.join(s,a),c=await he.stat(l),u=a.replace(".jsonl",""),d=new Date(u),p=Math.floor((i.getTime()-d.getTime())/(1e3*60*60*24));e.totalFiles++,e.totalSize+=c.size,e.files.push({name:a,date:u,size:c.size,age:p}),(!e.oldestFile||u<e.oldestFile)&&(e.oldestFile=a),(!e.newestFile||u>e.newestFile)&&(e.newestFile=a);}return e.files.sort((a,l)=>l.date.localeCompare(a.date)),e}function qo(s){if(s===0)return "0 B";let e=["B","KB","MB","GB","TB"],t=1024,n=Math.floor(Math.log(s)/Math.log(t));return `${(s/Math.pow(t,n)).toFixed(2)} ${e[n]}`}async function Wc(s){let e=new Map,t=new Map,n=an.createReadStream(s),r=zo.createInterface({input:n,crlfDelay:1/0});for await(let m of r)if(m.trim())try{let h=JSON.parse(m);if(h.type==="session_start")e.set(h.session_id,{session_id:h.session_id,user_input:h.user_input,timestamp:h.timestamp,iterations:0,tokens:{input:0,output:0,total:0},duration_ms:0,tools_used:[]});else if(h.type==="session_end"){let g=e.get(h.session_id);g&&(g.result=h.result,g.tokens={input:h.total_tokens.input,output:h.total_tokens.output,total:h.total_tokens.total||h.total_tokens.input+h.total_tokens.output},g.duration_ms=h.duration_ms);}else if(h.type==="iteration_start"){let g=e.get(h.session_id);g&&(g.iterations=(g.iterations||0)+1);}else if(h.type==="tool_call"){let g=e.get(h.session_id);g&&g.tools_used&&(g.tools_used.includes(h.tool_name)||g.tools_used.push(h.tool_name));let y=t.get(h.tool_name)||{total:0,success:0};y.total++,h.success&&y.success++,t.set(h.tool_name,y);}}catch{}let i=Array.from(e.values()).filter(m=>m.result!==void 0),o=i.length,a=i.filter(m=>m.result==="success").length,l=i.filter(m=>m.result==="error").length,c=i.filter(m=>m.result==="interrupted").length,u=i.reduce((m,h)=>({input:m.input+h.tokens.input,output:m.output+h.tokens.output,total:m.total+h.tokens.total}),{input:0,output:0,total:0}),d=i.reduce((m,h)=>m+h.duration_ms,0),p=Array.from(t.entries()).map(([m,h])=>({name:m,count:h.total,successRate:h.total>0?h.success/h.total*100:0})).sort((m,h)=>h.count-m.count).slice(0,10);return {totalSessions:o,successSessions:a,errorSessions:l,interruptedSessions:c,successRate:o>0?a/o*100:0,totalTokens:u,avgTokens:{input:o>0?u.input/o:0,output:o>0?u.output/o:0,total:o>0?u.total/o:0},totalDuration:d,avgDuration:o>0?d/o:0,topTools:p,sessions:i}}function Hc(s){let e=[];return e.push("\u{1F4CA} TRACING STATISTICS"),e.push(""),e.push(`Total Sessions: ${s.totalSessions}`),e.push(` [v] Success: ${s.successSessions} (${s.successRate.toFixed(1)}%)`),e.push(` [x] Error: ${s.errorSessions}`),e.push(` \u26A0\uFE0F Interrupted: ${s.interruptedSessions}`),e.push(""),e.push("\u{1FA99} TOKEN USAGE"),e.push(` Total: ${s.totalTokens.total.toLocaleString()} tokens`),e.push(` Input: ${s.totalTokens.input.toLocaleString()}`),e.push(` Output: ${s.totalTokens.output.toLocaleString()}`),e.push(""),e.push(` Average per session: ${Math.round(s.avgTokens.total).toLocaleString()} tokens`),e.push(` Input: ${Math.round(s.avgTokens.input).toLocaleString()}`),e.push(` Output: ${Math.round(s.avgTokens.output).toLocaleString()}`),e.push(""),e.push("\u23F1\uFE0F DURATION"),e.push(` Total: ${qh(s.totalDuration)}`),e.push(` Average: ${qh(s.avgDuration)}`),e.push(""),s.topTools.length>0&&(e.push("[*] TOP TOOLS"),s.topTools.forEach((t,n)=>{e.push(` ${n+1}. ${t.name}: ${t.count} calls (${t.successRate.toFixed(1)}% success)`);}),e.push("")),e.join(`
1684
+ `)}function qh(s){if(s<1e3)return `${s}ms`;if(s<6e4)return `${(s/1e3).toFixed(1)}s`;{let e=Math.floor(s/6e4),t=Math.floor(s%6e4/1e3);return `${e}m ${t}s`}}Sn();Sn();var Jc={openai:"https://api.openai.com/v1","openai-responses":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com","anthropic-openai":"https://api.anthropic.com/v1",doubao:"https://ark.cn-beijing.volces.com/api/v3",gemini:"https://generativelanguage.googleapis.com"},Cs=class{config;constructor(e){this.config=e??Xt(),this.config.providers||(this.config.providers={});}sanitizeId(e){return e.toLowerCase().trim().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").substring(0,48)}ensureValidId(e){let t=this.sanitizeId(e);if(!t)throw new Error("Provider ID must contain letters or numbers (allowed: lowercase letters, numbers, hyphen).");if(!/^[a-z0-9][a-z0-9-]*$/.test(t))throw new Error("Provider ID can only include lowercase letters, numbers, and hyphen.");return t}slugifyName(e){return this.sanitizeId(e)||"provider"}ensureProviderId(e,t){let n=e||this.slugifyName(t||"provider");if(this.config.providers||(this.config.providers={}),!this.config.providers[n])return n;let r=2,i=`${n}-${r}`;for(;this.config.providers[i];)r+=1,i=`${n}-${r}`;return i}persist(){ct(this.config);}getProviderCount(){return Object.keys(this.config.providers||{}).length}getProviders(){return Object.values(this.config.providers||{}).sort((e,t)=>e.name.localeCompare(t.name))}getProvider(e){if(e)return this.config.providers?.[e]}getDefaultProvider(){if(this.config.defaultProviderId){let t=this.getProvider(this.config.defaultProviderId);if(t)return t}let[e]=this.getProviders();return e&&(this.config.defaultProviderId=e.id,this.persist()),e}setDefaultProvider(e){let t=this.getProvider(e);if(!t)throw new Error(`Provider "${e}" does not exist.`);return this.config.defaultProviderId=e,this.persist(),t}addProvider(e){if(!e.name.trim())throw new Error("Provider name is required.");if(!e.apiKey.trim())throw new Error("Provider API key/token is required.");let t=this.ensureProviderId(e.id,e.name),n=new Date().toISOString(),r=e.baseUrl?.trim()||Jc[e.protocol],i=(e.models||[]).map(a=>typeof a=="string"?{name:a,createdAt:n}:{...a,createdAt:a.createdAt||n}),o={id:t,name:e.name.trim(),protocol:e.protocol,apiKey:e.apiKey.trim(),baseUrl:r,urlSuffix:e.urlSuffix,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens,models:i,defaultModel:e.defaultModel||i[0]?.name,lastSelectedModel:e.defaultModel||i[0]?.name,createdAt:n,updatedAt:n};if(!o.defaultModel)throw new Error("At least one model is required when creating a provider.");return this.config.providers||(this.config.providers={}),this.config.providers[t]=o,(!this.config.defaultProviderId||e.setAsDefault)&&(this.config.defaultProviderId=t),this.persist(),o}updateProvider(e,t){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);let r=new Date().toISOString(),i={...n,...t,baseUrl:t.baseUrl?.trim()||n.baseUrl||Jc[n.protocol],urlSuffix:t.urlSuffix!==void 0?t.urlSuffix:n.urlSuffix,apiKey:t.apiKey?.trim()||n.apiKey,maxTokens:t.maxTokens!==void 0?t.maxTokens:n.maxTokens,maxInputTokens:t.maxInputTokens!==void 0?t.maxInputTokens:n.maxInputTokens,updatedAt:r};if(t.protocol&&t.protocol!==n.protocol&&(i.protocol=t.protocol,t.baseUrl||(i.baseUrl=Jc[t.protocol])),t.defaultModel){if(!i.models.some(a=>a.name===t.defaultModel))throw new Error(`Model "${t.defaultModel}" does not exist for provider "${e}".`);i.defaultModel=t.defaultModel,i.lastSelectedModel=t.defaultModel;}return this.config.providers[e]=i,this.persist(),i}renameProvider(e,t){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);let r=this.ensureValidId(t);if(r===e)return n;if(this.config.providers?.[r])throw new Error(`Provider ID "${r}" already exists.`);delete this.config.providers[e];let i=new Date().toISOString(),o={...n,id:r,updatedAt:i};return this.config.providers[r]=o,this.config.defaultProviderId===e&&(this.config.defaultProviderId=r),this.persist(),o}deleteProvider(e){if(!this.config.providers?.[e])throw new Error(`Provider "${e}" does not exist.`);delete this.config.providers[e],this.config.defaultProviderId===e&&(this.config.defaultProviderId=void 0),this.persist();}addModel(e,t,n=false){let r=this.getProvider(e);if(!r)throw new Error(`Provider "${e}" does not exist.`);let i=t.trim();if(!i)throw new Error("Model name cannot be empty.");if(r.models.some(a=>a.name===i))throw new Error(`Model "${i}" already exists for provider "${e}".`);let o={...r,models:[...r.models,{name:i,createdAt:new Date().toISOString()}],updatedAt:new Date().toISOString()};return (!r.defaultModel||n)&&(o.defaultModel=i,o.lastSelectedModel=i),this.config.providers[e]=o,this.persist(),o}removeModel(e,t){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);if(n.models.length<=1)throw new Error("A provider must have at least one model.");let r=n.models.filter(o=>o.name!==t);if(r.length===n.models.length)throw new Error(`Model "${t}" does not exist for provider "${e}".`);let i={...n,models:r,updatedAt:new Date().toISOString()};return n.defaultModel===t&&(i.defaultModel=r[0].name),n.lastSelectedModel===t&&(i.lastSelectedModel=i.defaultModel),this.config.providers[e]=i,this.persist(),i}setLastSelectedModel(e,t){let n=this.getProvider(e);if(!n)throw new Error(`Provider "${e}" does not exist.`);if(!n.models.some(i=>i.name===t))throw new Error(`Model "${t}" does not exist for provider "${e}".`);return n.lastSelectedModel=t,n.updatedAt=new Date().toISOString(),this.config.providers[e]=n,this.persist(),n}resolveModel(e,t){let n=this.getProvider(e);if(n)return t&&n.models.some(i=>i.name===t)?t:n.lastSelectedModel||n.defaultModel||n.models[0]?.name}};var Un=class s{sessionId;filePath;directory;options;sequenceNumber=0;initialized=false;constructor(e){typeof e=="string"&&(e={sessionId:e}),this.sessionId=e.sessionId,this.options=e,this.directory=e.directory||te__default.join(ti__default.homedir(),".neox","sessions"),this.filePath=te__default.join(this.directory,`${this.sessionId}.jsonl`);}async ensureDirectory(){await he__default.mkdir(this.directory,{recursive:true});}async ensureInitialized(){if(!this.initialized){await this.ensureDirectory();try{await he__default.access(this.filePath);let e=await this.readAllItems();e.length>0&&(this.sequenceNumber=Math.max(...e.map(t=>t.seq))+1);}catch{if(this.options.autoCreateMeta!==false){let e={sessionId:this.sessionId,createdAt:new Date().toISOString(),agentName:this.options.agentName,model:this.options.model};await this.appendItem({type:"meta",data:e});}}this.initialized=true;}}async readAllItems(){let e=[];try{let t=an__default.createReadStream(this.filePath,{encoding:"utf-8"}),n=zo__default.createInterface({input:t,crlfDelay:1/0});for await(let r of n)if(r.trim())try{let i=JSON.parse(r);e.push(i);}catch{console.warn(`Invalid JSONL line: ${r.slice(0,50)}...`);}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,n)=>t.seq-n.seq),e}async appendItem(e){await this.ensureDirectory();let t={item:e,timestamp:Date.now(),seq:this.sequenceNumber++},n=JSON.stringify(t)+`
1685
+ `;await he__default.appendFile(this.filePath,n,"utf-8");}async writeAllItems(e){await this.ensureDirectory();let t=e.map(n=>JSON.stringify(n)).join(`
1686
+ `);await he__default.writeFile(this.filePath,t?t+`
1687
+ `:"","utf-8"),e.length>0?this.sequenceNumber=Math.max(...e.map(n=>n.seq))+1:this.sequenceNumber=0;}async getItems(e){await this.ensureInitialized();let n=(await this.readAllItems()).map(r=>r.item);return e===void 0?n:n.slice(-e)}async addItems(e){if(e.length!==0){await this.ensureInitialized();for(let t of e)await this.appendItem(t);}}async popItem(){await this.ensureInitialized();let e=await this.readAllItems();if(e.length===0)return null;let t=e.pop();return await this.writeAllItems(e),t.item}async popItems(e){if(e<=0)return [];await this.ensureInitialized();let t=await this.readAllItems();if(t.length===0)return [];let n=Math.min(e,t.length),r=t.splice(-n);return await this.writeAllItems(t),r.map(i=>i.item)}async createCheckpoint(e,t){await this.ensureInitialized();let n=`cp_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,r={type:"checkpoint",data:{id:n,name:e,description:t}};return await this.appendItem(r),n}async rollbackToCheckpoint(e){await this.ensureInitialized();let t=await this.readAllItems(),n=t.findIndex(o=>o.item.type==="checkpoint"&&o.item.data.id===e);if(n===-1)throw new Error(`Checkpoint not found: ${e}`);let r=t.slice(0,n+1),i=t.length-r.length;return await this.writeAllItems(r),i}async getCheckpoints(){await this.ensureInitialized();let e=await this.readAllItems(),t=[];for(let n of e)if(n.item.type==="checkpoint"){let r=n.item;t.push({id:r.data.id,name:r.data.name,timestamp:n.timestamp});}return t}async clearSession(){try{await he__default.unlink(this.filePath);}catch(e){if(e.code!=="ENOENT")throw e}this.sequenceNumber=0,this.initialized=false;}async getMeta(){await this.ensureInitialized();let e=await this.readAllItems();for(let t of e)if(t.item.type==="meta")return t.item.data;return null}async getMessages(){await this.ensureInitialized();let e=await this.readAllItems(),t=[];for(let n of e)n.item.type==="message"&&t.push(n.item.data);return t}async getItemCount(){return (await this.readAllItems()).length}async getTimeline(){return await this.ensureInitialized(),await this.readAllItems()}async replaceTimeline(e){await this.ensureDirectory();let t=e.map((n,r)=>({item:n.item,timestamp:n.timestamp??Date.now(),seq:r}));await this.writeAllItems(t),this.initialized=true;}static async listSessions(e){let t=e||te__default.join(ti__default.homedir(),".neox","sessions");try{return (await he__default.readdir(t)).filter(r=>r.endsWith(".jsonl")).map(r=>r.replace(".jsonl",""))}catch{return []}}static async getMostRecentId(e){let t=e||te__default.join(ti__default.homedir(),".neox","sessions");try{let r=(await he__default.readdir(t)).filter(o=>o.endsWith(".jsonl"));if(r.length===0)return null;let i=await Promise.all(r.map(async o=>({name:o.replace(".jsonl",""),mtime:(await he__default.stat(te__default.join(t,o))).mtime})));return i.sort((o,a)=>a.mtime.getTime()-o.mtime.getTime()),i[0].name}catch{return null}}static async deleteSession(e,t){let n=t||te__default.join(ti__default.homedir(),".neox","sessions"),r=te__default.join(n,`${e}.jsonl`);try{return await he__default.unlink(r),!0}catch{return false}}static async getSessionInfo(e,t){let n=t||te__default.join(ti__default.homedir(),".neox","sessions"),r=te__default.join(n,`${e}.jsonl`);try{let i=await he__default.stat(r);return {sessionId:e,filePath:r,size:i.size,createdAt:i.birthtime,updatedAt:i.mtime}}catch{return null}}static create(e){return new s({sessionId:Gn(),...e})}};var Es=class{directory;options;sessionCache=new Map;constructor(e){this.options=e||{},this.directory=e?.directory||te__default.join(ti__default.homedir(),".neox","sessions");}async getSession(e){if(this.sessionCache.has(e))return this.sessionCache.get(e);let t=new Un({sessionId:e,directory:this.directory,agentName:this.options.defaultAgentName,model:this.options.defaultModel});return this.sessionCache.set(e,t),t}async listSessions(){let e=[];try{await he__default.mkdir(this.directory,{recursive:!0});let t=await he__default.readdir(this.directory);for(let n of t){if(!n.endsWith(".jsonl"))continue;let r=n.replace(".jsonl",""),i=te__default.join(this.directory,n);try{let o=await he__default.stat(i),a=await this.readSessionMeta(i),l=await this.countItems(i);e.push({sessionId:r,createdAt:o.birthtime,updatedAt:o.mtime,itemCount:l,agentName:a?.agentName});}catch{}}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,n)=>n.updatedAt.getTime()-t.updatedAt.getTime()),e}async getMostRecent(){let e=await this.listSessions();return e.length===0?null:this.getSession(e[0].sessionId)}async deleteSession(e){this.sessionCache.delete(e);let t=te__default.join(this.directory,`${e}.jsonl`);try{return await he__default.unlink(t),!0}catch{return false}}async searchSessions(e){let t=await this.listSessions(),n=e.toLowerCase(),r=[];for(let i of t){if(i.sessionId.toLowerCase().includes(n)){r.push(i);continue}if(i.agentName?.toLowerCase().includes(n)){r.push(i);continue}let o=te__default.join(this.directory,`${i.sessionId}.jsonl`);await this.searchInFile(o,n)&&r.push(i);}return r}async createSession(e){let t=e?.sessionId||Gn(),n=new Un({sessionId:t,directory:this.directory,agentName:e?.agentName||this.options.defaultAgentName,model:e?.model||this.options.defaultModel});return this.sessionCache.set(t,n),n}async getOrCreateSession(e){return e?this.getSession(e):this.createSession()}async continueOrCreate(){let e=await this.getMostRecent();return e||this.createSession()}async cleanupOldSessions(e=30){let t=await this.listSessions(),n=Date.now()-e*24*60*60*1e3,r=0;for(let i of t)i.updatedAt.getTime()<n&&await this.deleteSession(i.sessionId)&&r++;return r}getDirectory(){return this.directory}async getSessionCount(){return (await this.listSessions()).length}async exportSession(e){let t=await this.getSession(e),n=await t.getItems(),r=await t.getMeta();return JSON.stringify({sessionId:e,meta:r,items:n,exportedAt:new Date().toISOString()},null,2)}async readSessionMeta(e){try{let t=createReadStream(e,{encoding:"utf-8"}),n=zo__default.createInterface({input:t,crlfDelay:1/0});for await(let r of n)if(r.trim())try{let i=JSON.parse(r);if(i.item?.type==="meta")return n.close(),i.item.data}catch{}}catch{}return null}async countItems(e){let t=0;try{let n=createReadStream(e,{encoding:"utf-8"}),r=zo__default.createInterface({input:n,crlfDelay:1/0});for await(let i of r)i.trim()&&t++;}catch{}return t}async searchInFile(e,t){try{let n=createReadStream(e,{encoding:"utf-8"}),r=zo__default.createInterface({input:n,crlfDelay:1/0});for await(let i of r)if(i.toLowerCase().includes(t))return r.close(),!0}catch{}return false}};var Is=class{session;memory;systemPrompt;turnCount=0;isSyncing=false;constructor(e){this.session=e.session,this.memory=e.memory,this.systemPrompt=e.systemPrompt;}async loadHistory(){let e=await this.session.getMessages();this.memory.clear(),this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});for(let t of e)t.role!=="system"&&this.memory.add(t);return this.turnCount=e.filter(t=>t.role==="user").length,e.length}async saveMessage(e){this.isSyncing||e.role!=="system"&&(await this.session.addItems([Bs(e)]),e.role==="assistant"&&this.turnCount++);}async saveTurn(e,t){this.isSyncing||(await this.session.addItems([Bs(e),Bs(t)]),this.turnCount++);}async undo(e=1){if(e<=0)return {success:false,undoneCount:0,messages:[]};this.isSyncing=true;let t=[];try{for(let n=0;n<e;n++){let r=await this.session.popItem();if(!r)break;let i=await this.session.popItem();if(!i){await this.session.addItems([r]);break}r.type==="message"&&t.unshift(r.data),i.type==="message"&&t.unshift(i.data);}return await this.loadHistory(),{success:t.length>0,undoneCount:Math.floor(t.length/2),messages:t}}finally{this.isSyncing=false;}}async undoUntil(e){this.isSyncing=true;let t=[];try{for(;;){let n=await this.session.popItem();if(!n)break;if(n.type==="message"){let r=n.data;if(t.unshift(r),me(r.content)?.startsWith(e)){await this.session.addItems([n]),t.shift();break}}}return await this.loadHistory(),{success:t.length>0,undoneCount:Math.ceil(t.length/2),messages:t}}finally{this.isSyncing=false;}}async createCheckpoint(e){let t=`Turn ${this.turnCount}, ${new Date().toLocaleString()}`;return await this.session.createCheckpoint(e,t)}async rollback(e){this.isSyncing=true;try{let t=await this.session.getItems(),n=t.findIndex(o=>o.type==="checkpoint"&&o.data.id===e);if(n===-1)throw new Error(`Checkpoint not found: ${e}`);let r=t.slice(n+1),i=await this.session.rollbackToCheckpoint(e);return await this.rollbackFileOperations(r),await this.loadHistory(),{success:!0,removedCount:i}}finally{this.isSyncing=false;}}async rollbackFileOperations(e){let t=[],n=[];for(let o of e)o.type==="file_snapshot"?t.push(o):o.type==="file_edit_snapshot"&&n.push(o);let r=new Map;for(let o of t){let a=o.data.filePath;r.has(a)||r.set(a,o);}let i=new Map;for(let o of n){let a=o.data.filePath;i.has(a)||i.set(a,[]),i.get(a).push(o);}for(let[o,a]of r)try{let l=te.resolve(o);if(a.data.originalContent===null)an.existsSync(l)&&(await an.promises.unlink(l),console.log(` \u21BA Deleted file: ${o}`));else {let c=te.dirname(l);await an.promises.mkdir(c,{recursive:!0}),await an.promises.writeFile(l,a.data.originalContent,"utf-8"),console.log(` \u21BA Restored file: ${o}`);}i.delete(o);}catch(l){console.error(` \u26A0 Failed to restore ${o}: ${l.message}`);}for(let[o,a]of i)try{let l=te.resolve(o);if(!an.existsSync(l)){console.error(` \u26A0 File not found for rollback: ${o}`);continue}let c=await an.promises.readFile(l,"utf-8");for(let u=a.length-1;u>=0;u--){let d=a[u];if(d.data.replaceAll)c=c.split(d.data.newString).join(d.data.oldString);else {let p=c.lastIndexOf(d.data.newString);p!==-1&&(c=c.substring(0,p)+d.data.oldString+c.substring(p+d.data.newString.length));}}await an.promises.writeFile(l,c,"utf-8"),console.log(` \u21BA Reverted ${a.length} edit(s) in: ${o}`);}catch(l){console.error(` \u26A0 Failed to rollback edits in ${o}: ${l.message}`);}}async getCheckpoints(){return await this.session.getCheckpoints()}getTurnCount(){return this.turnCount}getSessionId(){return this.session.sessionId}getSession(){return this.session}getMemory(){return this.memory}async getSessionInfo(){let e=await this.session.getMeta();await this.session.getItemCount();let n=await this.session.getCheckpoints();return {sessionId:this.session.sessionId,turnCount:this.turnCount,messageCount:(await this.session.getMessages()).length,checkpointCount:n.length,meta:e}}setSystemPrompt(e){this.systemPrompt=e;}async clearSession(){await this.session.clearSession(),this.memory.clear(),this.turnCount=0,this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});}};function Kc(s=process.argv){let e={continue:false,resume:false,help:false,version:false,noSession:false};for(let t=2;t<s.length;t++)switch(s[t]){case "-c":case "--continue":e.continue=true;break;case "-r":case "--resume":let r=s[t+1];r&&!r.startsWith("-")?(e.resume=r,t++):e.resume=true;break;case "-m":case "--model":s[t+1]&&(e.model=s[++t]);break;case "-p":case "--provider":s[t+1]&&(e.provider=s[++t]);break;case "-d":case "--dir":case "--workdir":s[t+1]&&(e.workDir=s[++t]);break;case "-h":case "--help":e.help=true;break;case "-v":case "--version":e.version=true;break;case "--no-session":e.noSession=true;break;case "--output-schema":s[t+1]&&(e.outputSchema=s[++t]);break;}return e}function Yh(s){console.log(`
1688
+ Neox CLI - AI \u4EE3\u7801\u52A9\u624B (AI Code Assistant) v${s}
1689
+
1690
+ \u7528\u6CD5 (Usage): neox [options]
1691
+
1692
+ \u4F1A\u8BDD\u9009\u9879 (Session Options):
1693
+ -c, --continue \u7EE7\u7EED\u6700\u8FD1\u7684\u4F1A\u8BDD (Continue most recent session)
1694
+ -r, --resume [id] \u6062\u590D\u4F1A\u8BDD (Resume session - shows selector if no ID)
1695
+ --no-session \u7981\u7528\u4F1A\u8BDD\u6301\u4E45\u5316 (Disable session persistence)
1696
+
1697
+ \u901A\u7528\u9009\u9879 (General Options):
1698
+ -m, --model <model> \u6307\u5B9A\u6A21\u578B (Specify model)
1699
+ -p, --provider <id> \u6307\u5B9A\u63D0\u4F9B\u5546 (Specify provider)
1700
+ -d, --dir <path> \u5DE5\u4F5C\u76EE\u5F55 (Working directory)
1701
+ --output-schema <path> \u6307\u5B9A JSON Schema \u6587\u4EF6\uFF0C\u7528\u4E8E\u7ED3\u6784\u5316\u8F93\u51FA (Structured output schema)
1702
+ -h, --help \u663E\u793A\u5E2E\u52A9 (Show help)
1703
+ -v, --version \u663E\u793A\u7248\u672C (Show version)
1704
+
1705
+ \u4F1A\u8BDD\u547D\u4EE4 (Session Commands in CLI):
1706
+ /sessions \u5217\u51FA\u6240\u6709\u4F1A\u8BDD (List all sessions)
1707
+ /session <id> \u5207\u6362\u4F1A\u8BDD (Switch to session)
1708
+ /session-new \u521B\u5EFA\u65B0\u4F1A\u8BDD (Create new session)
1709
+ /session-info \u663E\u793A\u4F1A\u8BDD\u4FE1\u606F (Show session info)
1710
+ /undo [n] \u64A4\u9500\u6700\u8FD1 n \u8F6E\u5BF9\u8BDD (Undo last n turns)
1711
+ /checkpoint [name] \u521B\u5EFA\u68C0\u67E5\u70B9 (Create checkpoint)
1712
+ /checkpoints \u5217\u51FA\u68C0\u67E5\u70B9 (List checkpoints)
1713
+ /rollback <id> \u56DE\u6EDA\u5230\u68C0\u67E5\u70B9 (Rollback to checkpoint)
1714
+ /session-clear \u6E05\u7A7A\u5F53\u524D\u4F1A\u8BDD (Clear current session)
1715
+ /session-export \u5BFC\u51FA\u4F1A\u8BDD\u4E3A JSON (Export session to JSON)
1716
+
1717
+ \u793A\u4F8B (Examples):
1718
+ neox \u542F\u52A8\u65B0\u4F1A\u8BDD (Start new session)
1719
+ neox -c \u7EE7\u7EED\u4E0A\u6B21\u4F1A\u8BDD (Continue last session)
1720
+ neox -r \u663E\u793A\u4F1A\u8BDD\u9009\u62E9\u5668 (Show session selector)
1721
+ neox -r session_123 \u6062\u590D\u6307\u5B9A\u4F1A\u8BDD (Resume specific session)
1722
+ neox --no-session \u65E0\u6301\u4E45\u5316\u8FD0\u884C (Run without persistence)
1723
+ neox --output-schema ./schema.json \u542F\u7528\u7ED3\u6784\u5316\u8F93\u51FA (Enable structured output)
1724
+
1725
+ \u5FEB\u7167\u529F\u80FD (Snapshot Features):
1726
+ \u2022 \u81EA\u52A8\u5FEB\u7167\uFF1A\u6BCF\u8F6E\u5BF9\u8BDD\u524D\u81EA\u52A8\u521B\u5EFA\u68C0\u67E5\u70B9 (Auto checkpoint before each turn)
1727
+ \u2022 \u7CBE\u7EC6\u56DE\u6EDA\uFF1A\u53EF\u56DE\u6EDA\u5230\u4EFB\u610F\u5386\u53F2\u8F6E\u6B21 (Rollback to any turn)
1728
+ \u2022 \u6587\u4EF6\u6062\u590D\uFF1A\u81EA\u52A8\u6062\u590D\u6587\u4EF6\u4FEE\u6539 (Auto restore file changes)
1729
+
1730
+ \u66F4\u591A\u4FE1\u606F (More Info):
1731
+ \u6587\u6863 (Docs): https://github.com/your-repo/Neox
1732
+ \u95EE\u9898 (Issues): https://github.com/your-repo/Neox/issues
1733
+ `);}function Xh(s){console.log(`Neox CLI v${s}`);}vt();var Vc="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",eT=60,tT=200,nT=`You are a highly skilled assistant tasked with summarizing conversation history.
1734
+
1735
+ Your goal is to create a concise yet comprehensive summary that captures:
1736
+ 1. The main topics and objectives discussed
1737
+ 2. Key decisions made and their rationale
1738
+ 3. Important code changes, file paths, and technical details
1739
+ 4. Current state of any ongoing tasks
1740
+ 5. Any unresolved issues or next steps
1741
+
1742
+ Guidelines:
1743
+ - Be specific about file names, function names, and code snippets when relevant
1744
+ - Preserve technical accuracy - don't generalize away important details
1745
+ - Maintain chronological flow of events when helpful
1746
+ - Keep the summary under 2000 tokens while preserving critical information
1747
+ - Write in the same language as the conversation (Chinese if Chinese, English if English)
1748
+ - Format the summary clearly with sections if needed
1749
+
1750
+ Output only the summary, no additional commentary.`,sT=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1751
+
1752
+ \u4F60\u7684\u76EE\u6807\u662F\u521B\u5EFA\u4E00\u4E2A\u7B80\u6D01\u4F46\u5168\u9762\u7684\u6458\u8981\uFF0C\u9700\u8981\u5305\u542B\uFF1A
1753
+ 1. \u8BA8\u8BBA\u7684\u4E3B\u8981\u4E3B\u9898\u548C\u76EE\u6807
1754
+ 2. \u505A\u51FA\u7684\u5173\u952E\u51B3\u7B56\u53CA\u5176\u7406\u7531
1755
+ 3. \u91CD\u8981\u7684\u4EE3\u7801\u53D8\u66F4\u3001\u6587\u4EF6\u8DEF\u5F84\u548C\u6280\u672F\u7EC6\u8282
1756
+ 4. \u4EFB\u4F55\u6B63\u5728\u8FDB\u884C\u7684\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001
1757
+ 5. \u4EFB\u4F55\u672A\u89E3\u51B3\u7684\u95EE\u9898\u6216\u540E\u7EED\u6B65\u9AA4
1758
+
1759
+ \u6307\u5357\uFF1A
1760
+ - \u5728\u76F8\u5173\u65F6\u5177\u4F53\u8BF4\u660E\u6587\u4EF6\u540D\u3001\u51FD\u6570\u540D\u548C\u4EE3\u7801\u7247\u6BB5
1761
+ - \u4FDD\u6301\u6280\u672F\u51C6\u786E\u6027 - \u4E0D\u8981\u6982\u62EC\u6389\u91CD\u8981\u7EC6\u8282
1762
+ - \u5728\u6709\u5E2E\u52A9\u65F6\u4FDD\u6301\u4E8B\u4EF6\u7684\u65F6\u95F4\u987A\u5E8F
1763
+ - \u5C06\u6458\u8981\u63A7\u5236\u5728 2000 tokens \u4EE5\u5185\uFF0C\u540C\u65F6\u4FDD\u7559\u5173\u952E\u4FE1\u606F
1764
+ - \u4F7F\u7528\u4E0E\u5BF9\u8BDD\u76F8\u540C\u7684\u8BED\u8A00\uFF08\u4E2D\u6587\u5BF9\u8BDD\u7528\u4E2D\u6587\uFF0C\u82F1\u6587\u5BF9\u8BDD\u7528\u82F1\u6587\uFF09
1765
+ - \u5982\u679C\u9700\u8981\uFF0C\u4F7F\u7528\u5206\u8282\u6765\u6E05\u6670\u5730\u683C\u5F0F\u5316\u6458\u8981
1766
+
1767
+ \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function rT(s){for(let e of s){let t=me(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function iT(s){let e=[];for(let t of s){let n=t.role==="assistant"?"Assistant":t.role==="user"?"User":t.role==="tool"?"Tool Result":t.role,r=me(t.content),i="";if(t.tool_calls?.length&&(i=` [Called tools: ${t.tool_calls.map(a=>a.function.name).join(", ")}]`),r||i){let o=r.length>1e3?r.slice(0,1e3)+"...[truncated]":r;e.push(`[${n}]${i}
1768
+ ${o}`);}}return `Please summarize the following conversation history:
1769
+
1770
+ ---
1771
+ ${e.join(`
1772
+
1773
+ ---
1774
+ `)}
1775
+ ---
1776
+
1777
+ Provide a comprehensive summary:`}function Yc(s){let t=me(s.content).length,n=s.tool_calls?JSON.stringify(s.tool_calls).length:0;return Math.ceil((t+n)/4)}function Zc(s,e){return s.length<=e?s:s.slice(0,e-1).trimEnd()+"\u2026"}function oT(s){return s.replace(/\s+/g," ").trim()}function Xc(s,e){if(s.length===0)return {summary:"",lines:0};let t=[];for(let r of s){if(t.length>=eT)break;let i=r.role==="assistant"?"Assistant":r.role==="user"?"User":r.role,o=me(r.content),l=(o?oT(o):"")||(r.tool_calls?.length?`Tool calls: ${r.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${i}] ${Zc(l,tT)}`);}return {summary:`${e}
1778
+ ${t.join(`
1779
+ `)}`,lines:t.length}}async function Zh(s){let{session:e,profile:t,llmProvider:n,model:r,onProgress:i,timeout:o=6e4,signal:a}=s,l=s.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;i?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map(($,A)=>({entry:$,index:A})).filter(({entry:$})=>$.item.type==="message");if(u.length===0)return null;let d=0,p=u.length;for(let $=u.length-1;$>=0;$--){let A=u[$].entry.item.data;if(d+=Yc(A),d>=l){p=$;break}}if(p>=u.length)return null;let m=u.slice(0,p).map(({entry:$})=>$.item.data);if(m.length===0)return null;let h=m.reduce(($,A)=>$+Yc(A),0);i?.("summarizing",`Summarizing ${m.length} messages with AI...`);let g=rT(m),y=g==="zh"?sT:nT,x=iT(m),S,T;try{let $=new AbortController,A=setTimeout(()=>$.abort(),o),G=a?AbortSignal.any([a,$.signal]):$.signal;try{let N=await n.chat([{role:"system",content:y},{role:"user",content:x}],{model:r,temperature:.3,signal:G});clearTimeout(A),S=me(N.choices[0]?.message?.content)||"",T=N.usage?.total_tokens;}catch(N){throw clearTimeout(A),N?.name==="AbortError"||N?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",N.message),N}if(!S.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:N}=Xc(m,Vc);S=N;}}catch($){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",$.message);let{summary:A}=Xc(m,Vc);S=A;}i?.("saving","Saving compacted history...");let L=`${g==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1780
+
1781
+ ${S}`,B=u.length-m.length,I=u[0]?.entry.timestamp??Date.now(),k={item:{type:"message",data:{role:"user",content:L,name:"SmartCompactSummary"}},timestamp:I,seq:0},R={item:{type:"compacted",data:{summary:Zc(S,2e3),originalCount:m.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:T}},timestamp:I,seq:0},E=[],M=false,_=0;for(let $ of c){if($.item.type!=="message"){E.push({...$});continue}_<p?M||(E.push({...k}),E.push({...R}),M=true):E.push({...$}),_++;}if(!M)return null;let W=E.map(($,A)=>({item:$.item,timestamp:$.timestamp??Date.now(),seq:A}));return await e.replaceTimeline(W),{removedMessages:m.length,keptMessages:B,summaryText:L,estimatedTokensSaved:h,llmTokensUsed:T}}async function Qc(s){let{session:e,profile:t}=s,n=s.tailTokenBudget??t.tailTokenBudget??2e4;if(!n||n<=0)return null;let r=await e.getTimeline(),i=r.map((T,w)=>({entry:T,index:w})).filter(({entry:T})=>T.item.type==="message");if(i.length===0)return null;let o=0,a=i.length;for(let T=i.length-1;T>=0;T--){let w=i[T].entry.item.data;if(o+=Yc(w),o>=n){a=T;break}}if(a>=i.length)return null;let l=i.slice(0,a).map(({entry:T})=>T.item.data);if(l.length===0)return null;let{summary:c,lines:u}=Xc(l,s.summaryHeader??Vc);if(!c.trim())return null;let d=i.length-l.length,p=i[0]?.entry.timestamp??Date.now(),m={item:{type:"message",data:{role:"user",content:c,name:"CompatSummary"}},timestamp:p,seq:0},h={item:{type:"compacted",data:{summary:Zc(c,2e3),originalCount:l.length,compactedAt:new Date().toISOString()}},timestamp:p,seq:0},g=[],y=false,x=0;for(let T of r){if(T.item.type!=="message"){g.push({...T});continue}x<a?y||(g.push({...m}),g.push({...h}),y=true):g.push({...T}),x++;}if(!y)return null;let S=g.map((T,w)=>({item:T.item,timestamp:T.timestamp??Date.now(),seq:w}));return await e.replaceTimeline(S),{removedMessages:l.length,keptMessages:d,summaryText:c,summaryLines:u}}var Yo=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let n=[/I(?:'ll| will) (\w+.*?) to (.*?)(?:\.|$)/i,/Let me (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) going to (\w+.*?) to (.*?)(?:\.|$)/i,/(?:I'm|I am) (\w+ing.*?) to (.*?)(?:\.|$)/i,/To (.*?)[,,] I(?:'ll| will) (\w+.*?)(?:\.|$)/i,/(?:First|Now|Next|Then)[,,] (?:I'll |I will |let me )?(\w+.*?)(?:\.|$)/i,/(?:我将|我会|让我)([^。,,]+)(?:来|以便|用于)([^。,,]+)/,/(?:首先|现在|接下来|然后)[,,](?:我将|我会|让我)?([^。,,]+)/];for(let o of n){let a=e.match(o);if(a){let l=a[2]||a[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let r=t.toLowerCase(),i=e.split(/[.。!!??]/);for(let o of i)if(o.toLowerCase().includes(r)||o.toLowerCase().includes("read")||o.toLowerCase().includes("search")||o.toLowerCase().includes("file")){let a=o.trim();if(a.length>10&&a.length<200)return a}}extractActionFromToolName(e){return {readfile:"read",write_file:"write",create_file:"create",edit_file:"edit",Edit:"edit",search:"search",list_directory:"list",LS:"list",Glob:"find",find_files:"find",Execute:"execute",execute:"execute"}[e]||e.toLowerCase()}},Xo=class{generateEquivalentCommand(e,t){switch(e){case "search":return this.generateSearchCommand(t);case "Glob":case "find_files":return this.generateFindCommand(t);case "Execute":case "execute":return this.generateExecuteCommand(t);case "readfile":return this.generateReadCommand(t);case "list_directory":case "LS":return this.generateLsCommand(t);case "write_file":case "create_file":return this.generateWriteCommand(t);default:return}}generateSearchCommand(e){let t="rg";e.case_insensitive&&(t+=" -i"),e.line_numbers&&(t+=" -n"),e.context_lines?t+=` -C ${e.context_lines}`:e.context?t+=` -C ${e.context}`:(e.context_before&&(t+=` -B ${e.context_before}`),e.context_after&&(t+=` -A ${e.context_after}`));let n=e.pattern||"";t+=` "${this.escapeShellArg(n)}"`;let r=e.path||e.directory||".";return t+=` ${this.escapeShellPath(r)}`,e.type&&(t+=` --type=${e.type}`),e.file_pattern?t+=` -g "${this.escapeShellArg(e.file_pattern)}"`:e.glob_pattern&&(t+=` -g "${this.escapeShellArg(e.glob_pattern)}"`),t}generateFindCommand(e){let t="find",n=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(n)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let r=e.patterns.map(i=>`-name "${this.escapeShellArg(i)}"`).join(" -o ");t+=` \\( ${r} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(r=>{t+=` ! -path "${this.escapeShellArg(r)}"`;}),e.maxDepth&&(t+=` -maxdepth ${e.maxDepth}`),e.type==="f"?t+=" -type f":e.type==="d"&&(t+=" -type d"),t}generateExecuteCommand(e){return e.command||""}generateReadCommand(e){let t=e.path||e.file_path||e.filename||"";if(e.start_line&&e.num_lines){let n=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${n}p' ${this.escapeShellPath(t)}`}return e.num_lines&&!e.start_line?`head -n ${e.num_lines} ${this.escapeShellPath(t)}`:`cat ${this.escapeShellPath(t)}`}generateLsCommand(e){let t="ls";(e.all||e.show_hidden)&&(t+=" -a"),(e.long||e.detailed)&&(t+=" -l"),t.includes("-")||(t+=" -la");let n=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(n)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",n=e.content||"";return n.length<100&&!n.includes(`
1782
+ `)?`echo "${this.escapeShellArg(n)}" > ${this.escapeShellPath(t)}`:`# Use editor to create ${t}`}escapeShellArg(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}escapeShellPath(e){return /[\s()[\]{}$`!*?<>|&;]/.test(e)?`"${this.escapeShellArg(e)}"`:e}};function Rs(s,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let n of t)if(e[n]&&typeof e[n]=="string")return e[n];switch(s){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let r=e.command,i=r.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return i?i[1]:r.substring(0,50)+(r.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let n=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${n} (${e.patterns.join(", ")})`:n;case "read_multiple_files":if(e.files&&Array.isArray(e.files))return e.files.length>1?`${e.files.length} files`:e.files[0];break}}function Qh(s,e){switch(s){case "readfile":let t=Rs(s,e);return t?`Reading ${t}`:"Reading file";case "write_file":case "create_file":let n=Rs(s,e);return n?`Writing ${n}`:"Writing file";case "edit_file":case "Edit":let r=Rs(s,e);return r?`Editing ${r}`:"Editing file";case "search":let i=e.pattern||e.query;return i?`Searching for "${i}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Rs(s,e)||"."}`;case "Glob":case "find_files":return e.patterns&&Array.isArray(e.patterns)?`Finding files: ${e.patterns.join(", ")}`:"Finding files";case "Execute":case "execute":let a=e.command||"";return a.length>60?`Running: ${a.substring(0,60)}...`:`Running: ${a}`;case "read_multiple_files":return e.files&&Array.isArray(e.files)?`Reading ${e.files.length} files`:"Reading multiple files";default:return `Executing ${s}`}}var Zo=class{batchTimeWindow;activeBatches=new Map;pendingCalls=new Map;batchableTools=new Set(["readfile","write_file","create_file","list_directory","LS","Glob","find_files","read_multiple_files"]);constructor(e=200){this.batchTimeWindow=e;}detectBatch(e,t,n,r,i){if(!this.isBatchable(t))return {type:"single",merge:false};let o=this.pendingCalls.get(t)||[];if(o.length===0)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:n,startTime:i,args:r}]),{type:"single",merge:false};let a=o[o.length-1];if(i-a.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:n,startTime:i,args:r}]),{type:"single",merge:false};if(o.some(u=>u.targetPath===n))return {type:"single",merge:false};if(o.length===1){let u=this.createBatch(a,e,n,i);return o.push({toolId:e,toolName:t,targetPath:n,startTime:i,args:r}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(o.push({toolId:e,toolName:t,targetPath:n,startTime:i,args:r}),this.updateBatch(u,n,i),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:n,startTime:i,args:r}]),{type:"single",merge:false})}}recordCompletion(e,t){let n=this.findActiveBatch(e);if(n){let r=this.activeBatches.get(n);r&&(r.completed++,r.completed>=r.total&&this.completeBatch(n));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,n,r){let i=`batch-${e.toolName}-${r}`;return this.activeBatches.set(i,{batchId:i,toolName:e.toolName,targets:[e.targetPath,n],startTime:e.startTime,lastCallTime:r,completed:0,total:2}),i}updateBatch(e,t,n){let r=this.activeBatches.get(e);r&&(r.targets.push(t),r.total++,r.lastCallTime=n);}findActiveBatch(e){for(let[t,n]of this.activeBatches.entries())if(n.toolName===e)return t}completeBatch(e){this.activeBatches.delete(e);let t=this.activeBatches.get(e);t&&this.pendingCalls.delete(t.toolName);}cleanupExpiredBatches(e){let t=this.batchTimeWindow*5,n=[];this.activeBatches.forEach((i,o)=>{e-i.lastCallTime>t&&n.push(o);}),n.forEach(i=>this.completeBatch(i));let r=[];this.pendingCalls.forEach((i,o)=>{if(i.length>0){let a=i[i.length-1];e-a.startTime>t&&r.push(o);}}),r.forEach(i=>this.pendingCalls.delete(i));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,n)=>{e.push({batchId:n,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};le();function ef(s){if(!s||s.trim().length===0)return null;let e=s.trim();if(!e.endsWith("}")){let l=e+"}";try{return JSON.parse(l),console.log("[JsonRepair] Fixed by adding closing }"),l}catch{}}let t=e.replace(/,\s*$/,"");if(!t.endsWith("}")){let l=t+"}";try{return JSON.parse(l),console.log("[JsonRepair] Fixed by removing trailing comma and adding }"),l}catch{}}if(e.lastIndexOf('"')>0){let l=0,c=false;for(let u=0;u<e.length;u++){if(c){c=false;continue}if(e[u]==="\\"){c=true;continue}e[u]==='"'&&l++;}if(l%2===1){let u=e+'"}';try{return JSON.parse(u),console.log("[JsonRepair] Fixed by closing unclosed string"),u}catch{}}}let r=0,i=0,o=false,a=false;for(let l of e){if(a){a=false;continue}if(l==="\\"){a=true;continue}if(l==='"'){o=!o;continue}o||(l==="{"?r++:l==="}"?r--:l==="["?i++:l==="]"&&i--);}for(o&&(e+='"');i>0;)e+="]",i--;for(;r>0;)e+="}",r--;try{return JSON.parse(e),console.log("[JsonRepair] Fixed by force-closing structures"),e}catch{return null}}function tf(s,e){if(!e||e.trim().length===0)return {isTruncated:false};if(!e.trim().endsWith("}"))return {isTruncated:true,reason:"JSON structure incomplete - missing closing brace"};if(s==="write_file"||s==="edit_file"){if(!e.includes('"content"')&&!e.includes('"new_string"'))return {isTruncated:true,reason:"File content field is missing - likely truncated during streaming"};let n=e.match(/"content"\s*:\s*"([^]*)/);if(n){let r=n[1],i=0,o=false;for(let a of r){if(o){o=false;continue}if(a==="\\"){o=true;continue}if(a==='"'){i++;break}}if(i===0)return {isTruncated:true,reason:"Content string is unclosed - truncated during streaming"}}}return {isTruncated:false}}function nf(s,e,t){let n=Su(s,e,t),r=ui(n);return {success:false,error:n.code,code:n.code,category:n.category,message:n.message,suggestion:r,retryable:n.retryable,receivedArgs:e?.substring(0,500)}}function sf(){return {contentBuffer:"",phase:"none",beforeText:"",blockContent:"",afterText:"",startEmitted:false,beforeTextEmitted:false}}function rf(s){s.contentBuffer="",s.phase="none",s.beforeText="",s.blockContent="",s.afterText="",s.startEmitted=false,s.beforeTextEmitted=false;}function of(s,e,t){if(!t)return {handled:false,events:[]};let n=[];switch(s.phase==="none"&&(s.phase="before"),s.contentBuffer+=e,s.phase){case "before":{let r="---PLAN_START---",i=s.contentBuffer.indexOf(r);if(i===-1)return s.beforeText+=e,{handled:true,events:[]};let o=s.contentBuffer.substring(0,i);o.trim()&&!s.beforeTextEmitted&&(s.beforeTextEmitted=true,n.push({type:"plan_before_text",text:o.trim()})),s.startEmitted||(s.startEmitted=true,n.push({type:"plan_start"}));let a=s.contentBuffer.substring(i+r.length);return a&&(s.blockContent=a,n.push({type:"plan_content_delta",delta:a})),s.phase="content",{handled:true,events:n}}case "content":{let r="---PLAN_END---",i=s.contentBuffer.indexOf(r);if(i===-1)return s.blockContent+=e,n.push({type:"plan_content_delta",delta:e}),{handled:true,events:n};let o="---PLAN_START---",a=s.contentBuffer.indexOf(o),l=s.contentBuffer.substring(a+o.length,i).trim(),c=aT(l);c&&n.push({type:"plan_content_complete",plan:c});let u=s.contentBuffer.substring(i+r.length);return s.afterText=u,s.phase="after",{handled:true,events:n}}case "after":return s.afterText+=e,{handled:true,events:[]};default:return {handled:false,events:[]}}}function af(s,e){if(!e)return null;let t=s.afterText.trim();return t||s.phase==="after"?{type:"plan_summary",text:t||"\u4EE5\u4E0A\u662F\u6211\u5236\u5B9A\u7684\u6267\u884C\u8BA1\u5212\uFF0C\u786E\u8BA4\u540E\u5C06\u5F00\u59CB\u6267\u884C\u3002"}:null}function aT(s){try{let e=s.match(/^#\s+([^#\n]+)/m);if(!e)return console.warn("[Plan Mode] No title found in plan content"),null;let t=e[1].trim(),n=s.match(/\*\*(?:目标|Goal)\*\*[:\s:]\s*(.+)/i),r=n?n[1].trim():t,i=[],o=s.split(`
1783
+ `),a=null;for(let c of o){let u=c.trim();if(!u)continue;let d=c.match(/^\s*(\d+)[.、)]\s*(.+)/);if(d){if(a){let m=a.subItems.length>0?`${a.title}
1784
+ ${a.subItems.join(`
1785
+ `)}`:a.title;i.push({id:`step-${i.length+1}`,content:m,status:"pending",priority:"medium"});}a={title:d[2].replace(/^\[[\sx]\]\s*/,"").replace(/\*\*/g,"").trim(),subItems:[]};}else if(a&&u&&!u.startsWith("#")){let p=u.replace(/^[-•]\s*/,"").replace(/\*\*/g,"").trim();p&&p.length>2&&a.subItems.push(p);}}if(a){let c=a.subItems.length>0?`${a.title}
1786
+ ${a.subItems.join(`
1787
+ `)}`:a.title;i.push({id:`step-${i.length+1}`,content:c,status:"pending",priority:"medium"});}return i.length===0?(console.warn("[Plan Mode] No steps found in plan content"),null):{id:`plan-${Date.now()}-${Math.random().toString(16).slice(2)}`,title:t,goal:r,steps:i,status:"pending_approval"}}catch(e){return console.warn("[Plan Mode] Failed to parse plan content:",e),null}}var cf=12e3,Qo=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;agentLogger;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";pendingAutoCompact=null;autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;eventEmitter=new EventEmitter;descriptionExtractor=new Yo;commandGenerator=new Xo;lastAssistantMessage="";batchDetector=new Zo;toolCallIdCounter=0;recentToolCalls=new Map;planModeState=sf();currentTaskMetadata;constructor(e){this.runner=e.runner,this.memory=e.memory,this.sessionManager=e.sessionManager,this.sessionSync=e.sessionSync,this.session=e.session,this.sessionEnabled=e.sessionEnabled??true,this.workDir=te__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.agentLogger=e.agentLogger,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.syncWorkspaceEnv();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=te__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t;}interrupt(){this.shouldInterrupt=true,this.abortController&&this.abortController.abort(),this.interruptResolver&&this.interruptResolver();}createInterruptPromise(){return this.interruptPromise?this.interruptPromise:(this.interruptPromise=new Promise(e=>{this.interruptResolver=()=>e({interrupted:true});}),this.interruptPromise)}clearInterruptPromise(){this.interruptResolver=null,this.interruptPromise=null;}emitEvent(e){this.eventEmitter.emit("event",e);}emitLog(e,t,n){process.env.CLI_DEBUG&&(f.debug("EMIT",`emitLog: level=${e}, message="${t.substring(0,50)}..."`),f.debug("EMIT",` eventEmitter.listenerCount: ${this.eventEmitter.listenerCount("event")}`)),this.emitEvent({type:"log",level:e,message:t,detail:n});}updateRuntime(e){this.runner=e.runner,this.memory=e.memory,this.model=e.model,e.systemPrompt&&(this.systemPrompt=e.systemPrompt);}prepareTaskInput(e,t){let n=e,r=t?.attachments?.filter(i=>i.type==="url")||[];return r.length>0&&(n=`Attachments:
1788
+ ${r.map((o,a)=>`Attachment ${a+1}: [URL: ${o.data}]`).join(`
1789
+ `)}
1790
+
1791
+ ${n}`),t?.mode==="ask"&&(n=`Mode: ASK (respond conversationally and avoid unnecessary tool calls).
1792
+
1793
+ ${n}`),t?.isInPlanMode&&(n=`Mode: PLAN
1794
+
1795
+ You are in Plan Mode. Before outputting your final plan, you can use tools to:
1796
+ - Explore the codebase (readfile, search, search_files, etc.)
1797
+ - Search the web for information (web_search, web_fetch)
1798
+ - Understand project structure and dependencies
1799
+
1800
+ When ready, output your response in TWO parts:
1801
+
1802
+ ---PLAN_START---
1803
+ # Plan Title
1804
+
1805
+ **\u76EE\u6807**: Goal description
1806
+
1807
+ 1. First step
1808
+ 2. Second step
1809
+ 3. Third step
1810
+ ---PLAN_END---
1811
+
1812
+ Then write a brief summary for the user (1-2 sentences), like:
1813
+ "\u4EE5\u4E0A\u662F\u6211\u5236\u5B9A\u7684\u8BA1\u5212\uFF0C\u5305\u542B X \u4E2A\u6B65\u9AA4\u3002\u786E\u8BA4\u540E\u6211\u5C06\u5F00\u59CB\u6267\u884C\u3002"
1814
+
1815
+ Important:
1816
+ - The plan MUST be between ---PLAN_START--- and ---PLAN_END--- markers
1817
+ - After the markers, write a short summary (this will be shown to user)
1818
+ - Keep steps specific and actionable (3-7 steps)
1819
+
1820
+ User Request:
1821
+ ${n}`),n.trim()}handlePlanModeTextDelta(e){let t=!!this.currentTaskMetadata?.isInPlanMode,n=of(this.planModeState,e,t);for(let r of n.events)switch(r.type){case "plan_before_text":console.log("[Plan Mode] \u{1F4DD} Emitting plan_before_text:",r.text.substring(0,50)+"..."),this.emitEvent({type:"plan_before_text",text:r.text,timestamp:Date.now()});break;case "plan_start":console.log("[Plan Mode] \u{1F680} Emitting plan_start"),this.emitEvent({type:"plan_start",timestamp:Date.now()});break;case "plan_content_delta":this.emitEvent({type:"plan_content_delta",delta:r.delta,timestamp:Date.now()});break;case "plan_content_complete":console.log("[Plan Mode] \u2705 Emitting plan_content_complete:",r.plan.title),this.emitEvent({type:"plan_content_complete",plan:r.plan,timestamp:Date.now()});break}return n.handled}finalizePlanModeHandler(){let e=!!this.currentTaskMetadata?.isInPlanMode,t=af(this.planModeState,e);t&&t.type==="plan_summary"&&(console.log("[Plan Mode] \u{1F4CB} Emitting plan_summary:",t.text.substring(0,50)+"..."),this.emitEvent({type:"plan_summary",text:t.text,timestamp:Date.now()}));}resetPlanModeStateHandler(){rf(this.planModeState);}extractImageUrls(e){return e?.attachments?.length?e.attachments.filter(t=>t.type==="image"&&t.data).map(t=>t.data):[]}handleMemorySnapshot(e){e&&(this.emitEvent({type:"memory_snapshot",snapshot:e}),this.maybeAnnounceMemoryPressure(e));}maybeAnnounceMemoryPressure(e){if(!e.profile.contextWindow){this.lastMemoryPressureState=e.state;return}let t={unknown:0,normal:1,warn:2,soft_limit:3,limit:4},n=t[this.lastMemoryPressureState]??0;if((t[e.state]??0)>n&&e.state!=="normal"&&e.state!=="unknown"){let i=e.pressure!==void 0?Math.round(e.pressure*100):void 0,o=`${e.tokensUsed.toLocaleString()} / ${e.profile.contextWindow.toLocaleString()} tokens`,a="\u4E0A\u4E0B\u6587\u538B\u529B\u5DF2\u5347\u9AD8\uFF0C\u5EFA\u8BAE\u5C3D\u5FEB\u6267\u884C /compact \u6216\u4F7F\u7528 /new \u5F00\u542F\u65B0\u4F1A\u8BDD\u3002";e.state==="soft_limit"?a="\u4E0A\u4E0B\u6587\u5DF2\u975E\u5E38\u63A5\u8FD1\u6781\u9650\uFF0C\u6267\u884C /compact \u53EF\u907F\u514D\u6A21\u578B\u622A\u65AD\u3002":e.state==="limit"&&(a="\u4E0A\u4E0B\u6587\u5DF2\u5230\u8FBE\u6781\u9650\uFF0C\u5FC5\u987B\u6267\u884C /compact \u6216 /new \u624D\u80FD\u7EE7\u7EED\u3002");let l=i!==void 0?`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528 ${i}% (${o})`:`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528\u504F\u9AD8 (${o})`;this.emitLog("warn",l,a);}this.lastMemoryPressureState=e.state,this.shouldScheduleAutoCompaction(e.state)&&this.scheduleAutoCompaction(e);}shouldScheduleAutoCompaction(e){return this.sessionEnabled?e==="soft_limit"||e==="limit":false}scheduleAutoCompaction(e){!this.sessionEnabled||!this.sessionSync||!this.compatProfile||(this.pendingAutoCompact=e,this.isRunning||this.runPendingAutoCompactionIfIdle());}async runPendingAutoCompactionIfIdle(){if(!this.pendingAutoCompact||!this.sessionSync||!this.compatProfile||!this.memoryPressure||this.autoCompactionInProgress||this.isRunning)return;let e=this.pendingAutoCompact;this.pendingAutoCompact=null,this.autoCompactionInProgress=true;try{let t=this.sessionSync.getSession(),n="";if(e.profile.contextWindow){let r=Math.round(e.tokensUsed/e.profile.contextWindow*100),i=Math.round(e.tokensUsed/1e3),o=Math.round(e.profile.contextWindow/1e3);n=`${i}K / ${o}K tokens (${r}%)`;}if(this.llmProvider){this.emitLog("info","\u{1F916} \u6B63\u5728\u667A\u80FD\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${n}\uFF0C\u4F7F\u7528 AI \u751F\u6210\u9AD8\u8D28\u91CF\u4E0A\u4E0B\u6587\u6458\u8981...`),this.emitEvent({type:"status",status:"compacting",message:"\u{1F9F9} Auto-compacting history..."});let r=await Zh({session:t,profile:this.compatProfile,llmProvider:this.llmProvider,model:this.model,timeout:6e4,onProgress:(a,l)=>{let c={analyzing:"\u{1F4CA} \u5206\u6790\u5BF9\u8BDD\u5386\u53F2...",summarizing:"\u{1F916} AI \u6B63\u5728\u751F\u6210\u6458\u8981...",saving:"\u{1F4BE} \u4FDD\u5B58\u538B\u7F29\u7ED3\u679C..."};this.emitEvent({type:"status",status:"compacting",message:c[a]||l||"Compacting..."});}});if(!r)return;await this.sessionSync.loadHistory();let i="";if(this.memoryPressure){this.memoryPressure.reset();let a=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(a),a.profile.contextWindow){let l=Math.round(a.tokensUsed/a.profile.contextWindow*100);i=`
1822
+ \u5F53\u524D\u4E0A\u4E0B\u6587: ${a.tokensUsed.toLocaleString()} / ${a.profile.contextWindow.toLocaleString()} tokens (${l}%)`;}}let o=r.llmTokensUsed?`\uFF0C\u538B\u7F29\u6D88\u8017 ${r.llmTokensUsed} tokens`:"";this.emitLog("info","\u2705 \u667A\u80FD\u538B\u7F29\u5B8C\u6210",`\u79FB\u9664 ${r.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${r.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\uFF0C\u8282\u7701\u7EA6 ${r.estimatedTokensSaved.toLocaleString()} tokens${o}\u3002${i}`);}else {this.emitLog("info","\u2699\uFE0F \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${n}\uFF0C\u4E3A\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF0C\u5C06\u603B\u7ED3\u8F83\u65E7\u7684\u6D88\u606F\u3002`),this.emitEvent({type:"status",status:"compacting",message:"\u{1F9F9} Auto-compacting history..."});let r=await Qc({session:t,profile:this.compatProfile});if(!r)return;await this.sessionSync.loadHistory();let i="";if(this.memoryPressure){this.memoryPressure.reset();let o=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(o),o.profile.contextWindow){let a=Math.round(o.tokensUsed/o.profile.contextWindow*100);i=`
1823
+ \u5F53\u524D\u4E0A\u4E0B\u6587: ${o.tokensUsed.toLocaleString()} / ${o.profile.contextWindow.toLocaleString()} tokens (${a}%)`;}}this.emitLog("info","\u2705 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${r.summaryLines} \u884C\uFF0C\u79FB\u9664 ${r.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${r.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${i}`);}}catch(t){this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",t?.message||String(t));}finally{this.autoCompactionInProgress=false,this.pendingAutoCompact&&!this.isRunning&&await this.runPendingAutoCompactionIfIdle();}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(f.debug("TASK","========================================"),f.debug("TASK","=== runTask ENTRY ==="),f.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),f.debug("TASK",` isRunning: ${this.isRunning}`),f.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),f.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),f.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController;let n=t?.metadata?.mode,r=this.runner.getMode(),i=n==="ask"&&r!=="ask";i&&this.runner.setMode("ask");let o=this.prepareTaskInput(e,t?.metadata),a=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.resetPlanModeStateHandler(),this.sessionSync&&this.sessionEnabled)try{let S=this.sessionSync.getTurnCount()+1,T=await this.sessionSync.createCheckpoint(`turn_${S}`);this.emitEvent({type:"checkpoint",id:T,auto:!0});}catch(S){f.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",S),console.error("Failed to create auto checkpoint",S);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."}),this.agentLogger&&this.agentLogger.startSession(o);let l=Date.now(),c="",u=0,d=0,p=0,m="",h="",g="",y=0,x=0;try{let S=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&f.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let T=0,w=this.createInterruptPromise(),L=this.runner.run(o,a.length>0?a:void 0,S)[Symbol.asyncIterator]();for(;;){let E=L.next();E.catch(()=>{});let M=await Promise.race([E,w]);if("interrupted"in M){if(this.shouldInterrupt=!0,L.return)try{L.return(void 0)?.catch?.(()=>{});}catch{}break}if(M.done)break;let _=M.value;if(T++,process.env.CLI_DEBUG==="1"&&f.debug("TASK",` \u4E8B\u4EF6 #${T}: ${_.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&f.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(_.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=_.iteration||0,this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:`Thinking... (iteration ${u})`}),x=0,this.memoryPressure){let A=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(f.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${A.length} \u6D88\u606F`),A.forEach((G,N)=>{let U=typeof G.content=="string"?G.content.length:JSON.stringify(G.content).length;f.debug("CONTEXT",` [${N}] role=${G.role}, content_len=${U}`);}));}this.agentLogger&&this.agentLogger.startIteration();break;case "text_delta":if(_.delta){c+=_.delta,m+=_.delta;let A=Math.ceil(_.delta.length/4);x+=A,this.handlePlanModeTextDelta(_.delta)||(_.delta.trim().length>0||_.delta.includes(`
1824
+ `))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:_.delta})),this.agentLogger&&this.agentLogger.logThinkingDelta(_.delta);}break;case "reasoning_delta":_.delta&&(this.emitEvent({type:"reasoning",delta:_.delta,timestamp:Date.now()}),this.agentLogger&&this.agentLogger.logThinkingDelta(`[reasoning] ${_.delta}`));break;case "tool_call_start":d++,h="",y=0,g=_.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${_.name}`});break;case "tool_call_delta":if(_.arguments_delta){h+=_.arguments_delta,y+=_.arguments_delta.length;let A=Math.ceil(_.arguments_delta.length/4);if(x+=A,_.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:g||_.name||"unknown",argumentsDelta:_.arguments_delta}),y>1e3){let H=1-h.trim().length/y;H>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${g} - ${(H*100).toFixed(1)}% whitespace (${y} bytes)`),this.emitLog("warn",`Model output abnormal: ${g} generating mostly whitespace content`));}if(g==="write_file"||g==="Write"||_.name==="write_file"||_.name==="Write"){let U=Math.floor(y/80),H=(y/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${H}KB (~${U} lines)`});try{let Ie=h.match(/"file_path"\s*:\s*"([^"]+)"/),J=h.match(/"content"\s*:\s*"/);if(Ie&&J){let ye=Ie[1],pe=h.indexOf('"',J.index+9+1)+1;if(pe>0){let ce=h.substring(pe),Oe=-1,_e=0;for(let X=0;X<ce.length;X++)if(ce[X]==="\\")_e++;else {if(ce[X]==='"'&&_e%2===0){Oe=X;break}_e=0;}Oe>0&&(ce=ce.substring(0,Oe));let Q=ce.replace(/\\n/g,`
1825
+ `).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),be=ye.split(".").pop()||"",Te={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"},P=Q.split(`
1826
+ `),q=P.length<=5;Q.length>2e3&&(Q=Q.slice(-2e3)),q?this.emitEvent({type:"file_stream",filePath:ye,content:Q,language:Te[be]||be,description:m.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${ye} (${P.length} lines)...`});}}}catch{f.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(_.name&&_.arguments)try{let A=_.arguments.trim(),G=tf(_.name,A);if(G.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&f.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${G.reason}`);let _e=ef(A);if(_e)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),A=_e;else throw new Error(`Tool arguments truncated: ${G.reason}`)}let N=A?JSON.parse(A):{};process.env.CLI_DEBUG_CONSOLE==="1"&&f.debug("TOOL",`\u2705 Tool call parsed: ${_.name}`,{argsLength:A.length});let U=Rs(_.name,N),H=this.descriptionExtractor.extractFromAssistantMessage(m,_.name);H||(H=Qh(_.name,N));let Ie=this.commandGenerator.generateEquivalentCommand(_.name,N),J=`tool-${++this.toolCallIdCounter}-${Date.now()}`,ye=Date.now(),pe=this.batchDetector.detectBatch(J,_.name,U||"",N,ye);this.recentToolCalls.set(_.name,{toolId:J,batchId:pe.batchId,targetPath:U,args:N}),f.info("TOOL",`Call: ${_.name}`,{targetPath:U,argsPreview:JSON.stringify(N)}),this.emitEvent({type:"tool_call_start",name:_.name,args:N,targetPath:U,description:H,equivalentCommand:Ie,timestamp:ye+Math.random()*.1,toolId:J,isBatch:pe.type==="batch",batchId:pe.batchId});let ce=_.name==="write_file"||_.name==="Write",Oe=N.file_path||N.filePath||N.path;ce&&Oe&&N.content&&(await this.emitFileStreamEvent(Oe,N.content,m.trim()||void 0),m="");}catch(A){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",_.name),console.error("[AgentHost] Error:",A.message),console.error("[AgentHost] Arguments length:",_.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",_.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",_.arguments?.substring(Math.max(0,(_.arguments?.length||0)-200))||""));let G=nf(_.name,_.arguments||"",A),N=G.category==="tool_truncated"?`\u274C Tool ${_.name}: content truncated during streaming`:`\u274C Tool ${_.name}: ${G.code}`;this.emitEvent({type:"status",status:"error",message:N}),this.emitEvent({type:"tool_call_start",name:_.name,args:{_raw:_.arguments?.substring(0,500)||"",_error:G.code,_errorCategory:G.category,_errorMessage:G.message,_suggestion:G.suggestion,_retryable:G.retryable},timestamp:Date.now()}),this.emitEvent({type:"tool_output",name:_.name,output:JSON.stringify(G),success:!1});}break}case "tool_output":if(_.name&&_.output!==void 0){let A=typeof _.output=="string"?_.output:JSON.stringify(_.output),G=A.length,N=_.success??!0,U=A.slice(0,cf),H=A.length>cf;f.info("TOOL",`Result: ${_.name} ${N?"\u2713":"\u2717"}`,{success:N,resultLength:G,outputString:A});let Ie=this.recentToolCalls.get(_.name),{toolId:J,batchId:ye,targetPath:pe,args:ce}=Ie||{},Oe=pe||(ce&&typeof ce.directory=="string"?ce.directory:void 0),_e=_.name==="show_tree"?`show_tree: ${Oe||"."} (${G} chars)`:void 0;if(N&&Oe&&this.batchDetector.recordCompletion(_.name,Oe),this.emitEvent({type:"tool_call_end",name:_.name,success:N,resultLength:G,timestamp:Date.now()+Math.random()*.1,toolId:J,batchId:ye,targetPath:Oe,summary:_e,output:U,outputTruncated:H,args:ce}),_.name==="write_file"&&_.success&&ce?.file_path&&ce?.content){try{let Q=ce.file_path,be=ce.content,Te=Q.split(".").pop()?.toLowerCase()||"",P={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"write_file_stream",filePath:Q,content:be,isComplete:!0,language:P[Te]||Te,timestamp:Date.now()});}catch(Q){f.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",Q);}await this.handleWriteFile(ce.file_path,ce.content,void 0);}if(_.name==="edit_file"&&_.success&&this.sessionSync&&this.sessionEnabled)try{let Q=JSON.parse(A),be=Q.metadata?.edit_info||Q.edit_info,Te=Q.metadata?.hunks;if(f.info("TOOL","edit file\u7684\u7ED3\u679C "+Q),f.info("TOOL","edit file\u7684editInfo "+be),Q.status==="success"&&be){let P=[];if(Array.isArray(Te)&&Te.length>0)for(let O of Te)P.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:O.old_string,newString:O.new_string,startLine:O.start_line,oldLineCount:O.old_line_count,newLineCount:O.new_line_count,replaceAll:!1,replacementCount:1}});else P.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:be.old_string,newString:be.new_string,startLine:be.start_line,oldLineCount:be.old_line_count,newLineCount:be.new_line_count,replaceAll:(Q.metadata?.replacements||Q.replacements)>1,replacementCount:Q.metadata?.replacements||Q.replacements}});await this.sessionSync.getSession().addItems(P);}}catch{f.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(_.name==="edit_file"&&_.success)try{let Q=JSON.parse(A),be=Q.metadata?.edit_info||Q.edit_info;if(Q.status==="success"&&be){let Te=Array.isArray(Q.metadata?.hunks)?Q.metadata.hunks.map(q=>({oldString:q.old_string,newString:q.new_string,startLine:q.start_line})):void 0,P=Q.file_path.split(".").pop()?.toLowerCase()||"",O={ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",css:"css",scss:"scss",less:"less",html:"html",vue:"vue",svelte:"svelte",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",sh:"bash"};this.emitEvent({type:"edit_file_stream",filePath:Q.file_path,oldString:be.old_string,newString:be.new_string,startLine:be.start_line,hunks:Te,isComplete:!0,language:O[P]||P,timestamp:Date.now()});}}catch{f.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:_.name,output:_.output,success:N}),this.agentLogger&&this.agentLogger.logToolCall(_.name,{},_.output,N,N?void 0:{message:"Tool execution failed",data:{output:_.output}});}break;case "token_usage":if(_.usage){p=_.usage.total_tokens;let A=_.usage.prompt_tokens||0,G=_.usage.completion_tokens||0,N=_.usage.prompt_tokens_details?.cached_tokens||0,U=_.usage.cache_read_input_tokens||0,H=_.usage.cache_creation_input_tokens||0,Ie=N||U||_.usage.cached_tokens||0;this.sessionTotalInputTokens+=A,this.sessionTotalOutputTokens+=G;let J=A+U+N;if(process.env.CLI_DEBUG&&(f.debug("CONTEXT","token_usage event received:"),f.debug("CONTEXT",` actualInputTokens=${A}, actualOutputTokens=${G}`),f.debug("CONTEXT",` anthropicCacheReadTokens=${U}, openaiCachedTokens=${N}`),f.debug("CONTEXT",` fullContextInputTokens=${J}`),f.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),f.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let ye=this.memory.getMessagesForLLM(),pe=this.memoryPressure.estimateMessagesForDisplay(ye);this.memoryPressure.recordCalibration(pe,A,U);let ce=this.memoryPressure.recordActualUsage(J,G,ye.length);process.env.CLI_DEBUG&&(f.debug("CONTEXT","recordActualUsage snapshot:"),f.debug("CONTEXT",` tokensUsed=${ce.tokensUsed}, promptTokens=${ce.promptTokens}`),f.debug("CONTEXT",` completionTokens=${ce.completionTokens}, contextWindow=${ce.profile.contextWindow}`),f.debug("CONTEXT",` pressure=${ce.pressure}, state=${ce.state}`)),this.handleMemorySnapshot(ce);}x=0,this.emitEvent({type:"token_usage",promptTokens:A,completionTokens:G,totalTokens:p,cachedTokens:Ie>0?Ie:void 0,openaiCachedTokens:N>0?N:void 0,anthropicCacheReadTokens:U>0?U:void 0,anthropicCacheCreationTokens:H>0?H:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens}),this.agentLogger&&this.agentLogger.updateTokens(this.model,{input:A,output:G});}break;case "raw_response_event":if(_.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(_.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(_.event_type==="plan.auto_continue")this.emitLog("info","Codex \u8BA1\u5212\u5DF2\u751F\u6210",_.data?.plan_text?.slice(0,1e3)),this.emitEvent({type:"status",status:"thinking",message:"Plan approved, executing..."});else if(_.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let A=Array.isArray(_.data?.errors)&&_.data.errors.length>0?_.data.errors.join("; "):_.data?.message;this.emitLog("warn","Structured output validation failed",A),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(_.event_type==="structured_output.accepted")typeof _.data?.normalized_text=="string"&&(c=_.data.normalized_text),this.emitLog("info","Structured output ready",_.data?.schema?`Schema: ${_.data.schema}`:void 0);else if(_.event_type==="error.classified"){let A=_.data;this.emitEvent({type:"error_classified",category:A.category||"INTERNAL",code:A.code||"UNKNOWN_ERROR",message:A.message||"An unknown error occurred",suggestion:A.suggestion,retryable:A.retryable??!1});}else if(_.event_type==="context_compaction"){let A=_.data;if(this.memoryPressure&&A.finalTokens!==void 0){let U=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot(U);}let G=A.droppedMessages||0,N=A.compressedMessages||0;if(G>0||N>0){let U=(A.originalTokens||0)-(A.finalTokens||0),H=A.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u{1F9F9} \u4E0A\u4E0B\u6587${H}`,`\u79FB\u9664 ${G} \u6761\u6D88\u606F${N>0?`\uFF0C\u538B\u7F29 ${N} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${U.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${G} messages`});}}else _.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&f.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:_.data,event_type:_.event_type}));break;case "run_done":this.agentLogger&&this.agentLogger.endIteration();break;case "error":f.error("AGENT",`Error: ${_.error||"Unknown error"}`),this.emitEvent({type:"error",message:_.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${_.error||"Unknown error"}`});break;case "stream_retry":let W=_;this.emitEvent({type:"stream_retry",error:W.error,errorCode:W.errorCode||"STREAM_ERROR",attempt:W.attempt,maxRetries:W.maxRetries,delayMs:W.delayMs});break;case "stream_recovered":let $=_;this.emitEvent({type:"stream_recovered",attempt:$.attempt,maxRetries:$.maxRetries});break}}process.env.CLI_DEBUG==="1"&&(f.debug("TASK","=== runner.run loop COMPLETED ==="),f.debug("TASK",` Total events: ${T}`),f.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let B=Date.now()-l,I=c;this.currentTaskMetadata?.isInPlanMode&&!this.shouldInterrupt&&(this.finalizePlanModeHandler(),this.planModeState.afterText.trim()?I=this.planModeState.afterText.trim():this.planModeState.phase!=="none"&&(I="\u4EE5\u4E0A\u662F\u6211\u5236\u5B9A\u7684\u6267\u884C\u8BA1\u5212\uFF0C\u786E\u8BA4\u540E\u5C06\u5F00\u59CB\u6267\u884C\u3002"),console.log("[Plan Mode] Will save summary to session instead of full response"));let k=this.currentTaskMetadata?.isInPlanMode&&!this.shouldInterrupt?I:c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.agentLogger&&this.agentLogger.endSession("interrupted");else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${d} tool calls, ${p} tokens, ${(B/1e3).toFixed(2)}s`),this.agentLogger&&this.agentLogger.endSession("success"),this.sessionSync&&this.sessionEnabled&&k)try{await this.sessionSync.saveTurn({role:"user",content:o},{role:"assistant",content:I});}catch{}let R={output:k,totalTokens:p,durationMs:B,iterations:u,toolCalls:d,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:k,totalTokens:p,iterations:u,toolCalls:d,durationMs:B}),R}catch(S){if(S?.code==="ERR_CANCELED"||S?.name==="CanceledError"||S?.name==="AbortError"||S?.category==="canceled"||this.shouldInterrupt){this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:"Task interrupted"}),this.emitLog("info","Task interrupted by user"),this.agentLogger&&this.agentLogger.endSession("interrupted");let L=Date.now()-l;return {output:c,totalTokens:p,durationMs:L,iterations:u,toolCalls:d,interrupted:true}}let w=S?.message||String(S)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${w}`}),this.emitLog("error",`Error: ${w}`),this.agentLogger&&this.agentLogger.endSession("error",{message:w,stack:S?.stack}),S}finally{process.env.CLI_DEBUG&&(f.debug("TASK","=== runTask finally block START ==="),f.debug("TASK",` isRunning was: ${this.isRunning}`)),i&&this.runner.setMode(r),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&(f.debug("TASK"," isRunning set to: false"),f.debug("TASK"," calling runPendingAutoCompactionIfIdle (non-blocking)")),this.runPendingAutoCompactionIfIdle(),process.env.CLI_DEBUG&&f.debug("TASK","=== runTask finally block END ===");}}syncWorkspaceEnv(){this.workDir&&(process.env.NEOX_WORKDIR=this.workDir);}async listSessions(){return this.sessionManager.listSessions()}getCurrentSessionId(){return this.session?.sessionId}async getSessionInfo(){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.getSessionInfo()}async emitFileStreamEvent(e,t,n){let r=e.split(".").pop()||"",o={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:o,description:n,timestamp:a});}async handleWriteFile(e,t,n){let r=e.split(".").pop()||"",o={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[r]||r,a=Date.now();try{let l=await import('fs'),c=await import('path'),u=c.isAbsolute(e)?c.resolve(e):c.resolve(this.workDir,e);if(this.sessionSync&&this.sessionEnabled)try{let d=null,p="create";l.existsSync(u)&&(p="modify",d=null);let m={type:"file_snapshot",data:{filePath:e,originalContent:d,operation:p,newContent:t}};await this.sessionSync.getSession().addItems([m]);}catch(d){console.debug("Failed to capture file snapshot",d);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:o,description:n,timestamp:a}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
1827
+ `).length} lines written to disk`);}catch(l){this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:true,language:o,description:n,timestamp:a}),this.emitLog("error",`Error handling file write: ${l.message}`);}}async switchSession(e){let t=await this.sessionManager.getSession(e);if(!t)throw new Error(`Session ${e} not found`);return this.session=t,this.session}async createSession(e){let t=await this.sessionManager.createSession({model:e||this.model});return this.session=t,t}async saveTurn(e,t){!this.sessionSync||!this.sessionEnabled||await this.sessionSync.saveTurn({role:"user",content:e},{role:"assistant",content:t});}async undoTurns(e=1){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.undo(e)}async createCheckpoint(e){if(!this.sessionSync)throw new Error("Session is not ready");let t=await this.sessionSync.createCheckpoint(e);return this.emitEvent({type:"checkpoint",id:t}),t}async listCheckpoints(){if(!this.sessionSync)throw new Error("Session is not ready");return await this.sessionSync.getSession().getCheckpoints()}async rollbackTo(e){if(!this.sessionSync)throw new Error("Session is not ready");return this.sessionSync.rollback(e)}async clearSession(){this.sessionSync&&await this.sessionSync.clearSession(),this.memory.clear();}async compactSession(){if(!this.sessionSync||!this.compatProfile)throw new Error("Compaction is not available");let e=this.sessionSync.getSession(),t=await Qc({session:e,profile:this.compatProfile});t&&(await this.sessionSync.loadHistory(),this.emitLog("info","\u624B\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${t.summaryLines} \u884C\uFF0C\u79FB\u9664 ${t.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${t.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002`));}setAgentLogger(e){this.agentLogger=e||void 0;}setSandboxMode(e){this.sandboxSetter?.(e);}setApprovalHandler(e){this.runner.setApprovalHandler(e);}setMode(e){this.runner.setMode(e);}setConversationHistory(e){this.memory.clear(),this.systemPrompt&&this.memory.add({role:"system",content:this.systemPrompt});for(let t of e)!t||!t.content||this.memory.add({role:t.role,content:t.content,name:t.name,tool_calls:t.tool_calls});}dispose(){this.isRunning&&this.interrupt(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.eventEmitter.removeAllListeners(),this.memory.clear(),this.pendingAutoCompact=null,this.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};le();var uT={name:"require_read_before_edit",guardrail_function:async s=>{let{tool_name:e,tool_input:t}=s.tool_context;if(e!=="edit_file")return li();let n=t.file_path;if(!n)return li();let r=l=>te__default.resolve(l).replace(/\\/g,"/"),i=r(n),o=Pu(s.context,20);return process.env.CLI_DEBUG==="1"&&(f.debug("GUARDRAIL",`Checking edit for: ${n}`),f.debug("GUARDRAIL",`Normalized path: ${i}`),f.debug("GUARDRAIL",`Recent tool calls (${o.length}):`),o.forEach((l,c)=>{if(l.name==="readfile"){let u=l.args.path,d=u?r(u):"undefined";f.debug("GUARDRAIL",` [${c}] readfile: ${u} (normalized: ${d}) success=${l.success}`);}})),o.some(l=>{if(l.name!=="readfile"||!l.success)return false;let c=l.args.path;if(!c)return false;let d=r(c)===i||c===n;return process.env.CLI_DEBUG==="1"&&d&&f.debug("GUARDRAIL",` \u2713 Found matching readfile: ${c}`),d})?li():(f.warn("GUARDRAIL",`Edit without recent readfile: ${n} (abs: ${i})`),process.env.CLI_DEBUG==="1"&&f.debug("GUARDRAIL",`Available readfile calls: ${o.filter(l=>l.name==="readfile").length}`),vu(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1828
+
1829
+ \u6587\u4EF6: ${n}
1830
+
1831
+ \u{1F4A1} \u8BF7\u5148\u4F7F\u7528 readfile \u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u786E\u8BA4\u5F53\u524D\u72B6\u6001\u540E\u518D\u8FDB\u884C\u7F16\u8F91\u3002
1832
+ \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:n,suggestion:"use readfile first"}))}};var eu=[uT],tu=[];var Ps=Fo,si=["/help","/exit","/quit","/mode","/mode ask","/mode agent","/approval","/approval on","/approval off","/sandbox","/sandbox on","/sandbox off","/sandbox status","/provider","/provider list","/provider add","/provider edit","/provider remove","/provider default","/provider use","/model","/model list","/model add","/model use","/model remove","/model default","/attach","/attachments","/tracing","/tracing on","/tracing off","/tracing status","/thinking","/thinking on","/thinking off","/thinking status","/trace","/trace-history","/trace-stats","/trace-clean","/sessions","/session","/session-new","/session-info","/undo","/checkpoint","/checkpoints","/rollback","/session-clear","/session-export","/compact","/processes","/ps","/kill","/clear","/config-clear","/config-reset","/stats","/context","/index","/index-build","/index-status","/schema-example"],As={openai:"https://api.openai.com/v1","openai-responses":"https://api.openai.com/v1",anthropic:"https://api.anthropic.com","anthropic-openai":"https://api.anthropic.com/v1",doubao:"https://ark.cn-beijing.volces.com/api/v3",gemini:"https://generativelanguage.googleapis.com"},ln={openai:"OpenAI (Chat)","openai-responses":"OpenAI (Responses)",anthropic:"Anthropic","anthropic-openai":"Anthropic (OpenAI Format)",doubao:"\u8C46\u5305 (Doubao)",gemini:"Google Gemini"},ea={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},dT=()=>{let s=process.env.COLORFGBG;if(s){let t=s.split(";");if(t.length>1){let n=parseInt(t[1]);return n<8||isNaN(n)}}process.env.TERM_PROGRAM;return true},Mt=dT(),v={primary:s=>Mt?j.cyan(s):j.blue(s),success:s=>Mt?j.green(s):j.green(s),error:s=>Mt?j.red(s):j.red(s),warning:s=>Mt?j.yellow(s):j.yellow(s),info:s=>Mt?j.blueBright(s):j.blue(s),dim:s=>Mt?j.gray(s):j.gray(s),highlight:s=>Mt?j.white.bold(s):j.black.bold(s),code:s=>Mt?j.magenta(s):j.magenta(s),text:s=>Mt?j.white(s):j.black(s)};function ta(s){let t=Date.now()-s.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),i=Math.floor(t/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i===1?"yesterday":`${i} days ago`}function uf(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m ${Math.floor(s%6e4/1e3)}s`:`${Math.floor(s/36e5)}h ${Math.floor(s%36e5/6e4)}m`}function ri(s){return !s||s.length===0?"":` [${s.join(", ")}]`}function nu(s){if(!s||Object.keys(s).length===0)return "";let e=Object.entries(s);if(e.length===0)return "";let t=e.slice(0,2).map(([r,i])=>{let o=String(i);return o.length>30&&(o=o.substring(0,27)+"..."),`${r}=${o}`}),n=e.length>2?`, +${e.length-2}`:"";return j.dim(` (${t.join(", ")}${n})`)}function df(s,e){let t=e.trim();if(!t.startsWith("/"))return [];let n=/\s$/.test(e),r=t.split(/\s+/);if(r.length===0)return [];let i=r[0],o=r.slice(1),a=s.providerStore.getProviders().map(m=>m.id),l=s.providerSettings?.models.map(m=>m.name)||[],c=["list","add","edit","remove","default","use"],u=["list","add","use","remove","default"],d=(m,h)=>h.map(g=>`${m} ${g}`),p=()=>{if(n)return e;let m=e.lastIndexOf(" ");return m===-1?`${e} `:e.slice(0,m+1)};if(o.length===0&&!n){let m=si.filter(h=>h.startsWith(t)&&h!==t);if(m.length>0)return m}switch(i){case "/provider":{if(o.length===0||o.length===1&&!n)return d("/provider",c);let m=o[0];if(!c.includes(m))return d("/provider",c);if(["use","edit","remove","default"].includes(m)){if(o.length===1&&!n)return a.map(g=>`/provider ${m} ${g}`);let h=p();return a.map(g=>`${h}${g}`)}return []}case "/model":{if(o.length===0||o.length===1&&!n)return d("/model",u);let m=o[0],h=o.slice(1);if(!u.includes(m))return d("/model",u);switch(m){case "list":{if(a.length===0)return [];let g=h.length===0?`${t} `:p();return a.map(y=>`${g}${y}`)}case "use":{if(h.length===0)return Array.from(new Set([...a.map(S=>`/model use ${S}`),...l.map(S=>`/model use ${S}`)]));let g=h[0],y=s.providerStore.getProvider(g);if(y){let S=p();return (y.models||[]).map(T=>`${S}${T.name}`)}if(l.length===0)return [];let x=h.length===1?`${t} `:p();return l.map(S=>`${x}${S}`)}case "remove":case "delete":case "default":{if(l.length===0)return [];let g=h.length===0?`${t} `:p();return l.map(y=>`${g}${y}`)}default:return []}}default:return []}}function mT(s){let e=s.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{let t=JSON.parse(e);return !t||typeof t!="object"||typeof t.type!="string"?null:t}catch{return null}}function pf(s){if(!s)return "";let e=[],t=[],n=[];if((s.pattern||s.query)&&e.push(s.pattern||s.query),Array.isArray(s.keywords)&&e.push(...s.keywords),Array.isArray(s.queries))for(let i of s.queries){if(!i?.pattern)continue;let o=(i.op||"or").toLowerCase();o==="and"?t.push(i.pattern):o==="not"?n.push(i.pattern):e.push(i.pattern);}let r=[];return e.length>0&&r.push(e.join(" OR ")),t.length>0&&r.push(`AND ${t.join(" + ")}`),n.length>0&&r.push(`NOT ${n.join(" + ")}`),r.join(" ")}function mf(s,e,t){if(!s)return;let n=e.toLowerCase();if(n==="web_search"||n.includes("websearch")){s.addWebSearchResult({query:t.query||t.q||"",status:"searching"});return}if(n==="web_fetch"||n.includes("webfetch")){s.addWebFetchResult({url:t.url||"",status:"fetching"});return}if(n==="readfile"){s.addReadFileResult({filePath:t.path||t.file_path||"",startLine:t.start_line,numLines:t.num_lines,status:"reading"});return}if(n==="search"){let r=pf(t)||t.pattern||t.query||"",i=t.mode||"content",o=Array.isArray(t.keywords)?false:Array.isArray(t.queries)?t.queries.some(l=>l?.regex!==false):true,a=t.path||t.file_path||".";i==="files"?s.addSearchFilesResult({pattern:r,path:a,status:"searching"}):s.addSearchResult({pattern:r,filePath:a,contextLines:t.context_lines,mode:i,regex:o,caseInsensitive:t.case_insensitive,status:"searching"});return}if(n==="search_files"||n==="glob"){s.addSearchFilesResult({pattern:t.pattern||"",path:t.path,status:"searching"});return}if(n==="show_tree"||n==="list_directory"||n==="smart_tree"){s.addShowTreeResult({path:t.directory||t.path||".",maxDepth:t.max_depth,mode:t.mode,status:"loading"});return}if(n==="execute_bash"||n==="execute_shell"||n==="bash"){s.addCommandExecResult({command:t.command||t.code||"",cwd:t.cwd,timeout:t.timeout,background:t.run_in_background,status:"running"});return}if(n==="execute_python"||n==="execute_js"||n==="execute_javascript"){s.addCodeExecResult({toolName:e,code:t.code,cwd:t.cwd,status:"running"});return}if(n==="debug_in_browser"){s.addBrowserDebugResult({url:t.url||"auto",status:"detecting"});return}if(n==="write_file"||n==="write"){let r=t.file_path||t.path||"",i=t.content||"";s.addWriteFileCall(r,i);return}if(n==="edit_file"||n==="edit"){let r=t.file_path||t.path||"",i=t.old_string||t.old||"",o=t.new_string||t.new||"",a=t.start_line;s.addEditFileCall(r,i,o,a);return}s.addToolCall(e,t);}function su(s,e,t,n,r){if(!s)return;let i=e.toLowerCase();if(i==="edit_file"||i==="edit"){try{let o=JSON.parse(t);o.status==="success"?s.addEditFileResult({filePath:o.file_path||r?.file_path||"",status:"completed",summary:o.summary||"Edit completed successfully",replacements:o.metadata?.replacements||1}):o.status==="already_done"?s.addEditFileResult({filePath:o.file_path||r?.file_path||"",status:"completed",summary:o.summary||"Edit already applied",alreadyDone:!0}):s.addEditFileResult({filePath:o.file_path||r?.file_path||"",status:"error",error:o.summary||o.error||"Edit failed"});}catch{n?s.addEditFileResult({filePath:r?.file_path||"",status:"completed",summary:"Edit completed"}):s.addEditFileResult({filePath:r?.file_path||"",status:"error",error:t});}return}if(i==="web_search"||i.includes("websearch")){if(n)try{let o=hT(t);s.addWebSearchResult({query:r?.query||r?.q||"",results:o,status:"completed"});}catch{s.addWebSearchResult({query:r?.query||r?.q||"",status:"completed"});}else s.addWebSearchResult({query:r?.query||"",status:"error",error:t});return}if(i==="web_fetch"||i.includes("webfetch")){n?s.addWebFetchResult({url:r?.url||"",contentLength:t.length,contentPreview:t.slice(0,500),status:"completed"}):s.addWebFetchResult({url:r?.url||"",status:"error",error:t});return}if(i==="readfile"){if(n){let o=t.split(`
1833
+ `);s.addReadFileResult({filePath:r?.path||r?.file_path||"",totalLines:o.length,fileSize:t.length>=1024?`${(t.length/1024).toFixed(1)}KB`:`${t.length} chars`,preview:t.slice(0,1e3),status:"completed"});}else s.addReadFileResult({filePath:r?.path||r?.file_path||"",status:"error",error:t});return}if(i==="search"){let o=mT(t),a=o?.content&&typeof o.content=="string"?o.content:t,l=o?.metadata,c=r?.mode==="files"||l?.mode==="files",u=pf(r)||r?.pattern||r?.query||"",d=l?.mode||r?.mode||(c?"files":"content"),p=l?.regex??(Array.isArray(r?.keywords)?false:Array.isArray(r?.queries)?r.queries.some(y=>y?.regex!==false):true),m=r?.case_insensitive,h=r?.path||r?.file_path||l?.path||"",g=l?.command;if(n)if(c){let y=l?.files||a.split(`
1834
+ `).filter(x=>x.trim().startsWith(" ")).map(x=>x.trim());s.addSearchFilesResult({pattern:u,path:h,fileCount:y.length,files:y.slice(0,30),status:"completed",mode:d,strategy:l?.strategy,regex:p,caseInsensitive:m,command:g});}else {let y=fT(a),x=gT(a),S=x.entries.length>0?yT(x.entries):void 0;s.addSearchResult({pattern:u,filePath:h,matchCount:x.matchCount??y.length,details:S,status:"completed",mode:d,strategy:l?.strategy,regex:p,caseInsensitive:m,command:g});}else c?s.addSearchFilesResult({pattern:u,path:h,status:"error",error:a,mode:d,strategy:l?.strategy,regex:p,caseInsensitive:m,command:g}):s.addSearchResult({pattern:u,filePath:h,status:"error",error:a,mode:d,strategy:l?.strategy,regex:p,caseInsensitive:m,command:g});return}if(i==="search_files"||i==="glob"){if(n){let o=t.split(`
1835
+ `).filter(a=>a.trim());s.addSearchFilesResult({pattern:r?.pattern||"",path:r?.path,fileCount:o.length,files:o.slice(0,30),status:"completed"});}else s.addSearchFilesResult({pattern:r?.pattern||"",status:"error",error:t});return}if(i==="show_tree"||i==="list_directory"||i==="smart_tree"){n?s.addShowTreeResult({path:r?.directory||r?.path||".",mode:r?.mode,maxDepth:r?.max_depth,content:t,totalChars:t.length,status:"completed"}):s.addShowTreeResult({path:r?.directory||r?.path||".",mode:r?.mode,maxDepth:r?.max_depth,status:"error",error:t});return}if(i==="execute_bash"||i==="execute_shell"||i==="bash"){n?s.addCommandExecResult({command:r?.command||r?.code||"",cwd:r?.cwd,output:t,exitCode:0,status:"completed"}):s.addCommandExecResult({command:r?.command||r?.code||"",cwd:r?.cwd,output:t,status:"error",error:t});return}if(i==="execute_python"||i==="execute_js"||i==="execute_javascript"){n?s.addCodeExecResult({toolName:e,code:r?.code,output:t,exitCode:0,status:"completed"}):s.addCodeExecResult({toolName:e,code:r?.code,status:"error",error:t});return}if(i==="debug_in_browser"){if(n)try{let o=JSON.parse(t);s.addBrowserDebugResult({url:o.url||"unknown",status:o.success?"completed":"error",summary:o.summary,loadTime:o.load_time,consoleLogs:o.console_logs?.length||0,errors:o.errors?.map(a=>({type:a.type,message:a.message,file:a.file,line:a.line}))||[],networkRequests:o.network_requests?.length||0,performance:o.performance,error:o.error});}catch{"addToolCall"in s&&typeof s.addToolCall=="function"?s.addToolResult(e,t):s.addToolResult(t,false);}else "addBrowserDebugResult"in s&&typeof s.addBrowserDebugResult=="function"&&s.addBrowserDebugResult({url:"unknown",status:"error",error:t});return}n?"addToolCall"in s&&typeof s.addToolCall=="function"?s.addToolResult(e,t):s.addToolResult(t,false):s.addToolError(e,t);}function hT(s){let e=[];try{let r=JSON.parse(s);if(Array.isArray(r))return r.map(i=>({title:i.title||i.name||"",url:i.url||i.link||"",description:i.description||i.snippet||"",hostname:i.hostname||(i.url?new URL(i.url).hostname:"")}))}catch{}let t=s.split(`
1836
+ `),n={};for(let r of t){let i=r.match(/^(?:[]\s*)?\d+\.\s*(.+)$/);if(i){n.title&&n.url&&e.push(n),n={title:i[1].trim()};continue}let o=r.match(/^🔗\s*(.+)$/)||r.match(/^https?:\/\/\S+/);if(o&&n.title){let l=o[1]||o[0];n.url=l.trim();try{n.hostname=new URL(n.url).hostname;}catch{n.hostname=n.url;}continue}let a=r.match(/^[.]\s*(.+)$/);a&&n.title&&(n.description=a[1].trim());}return n.title&&n.url&&e.push(n),e}function fT(s){let e=[],t=s.split(`
1837
+ `);for(let n of t){let r=n.match(/^([▶▸► ])\s*(\d+)\s*│\s*(.*)$/);if(r){e.push({lineNumber:parseInt(r[2],10),content:r[3],isMatch:r[1]!==" "});continue}let i=n.match(/^[^:]+:(\d+):(.*)$/);i&&e.push({lineNumber:parseInt(i[1],10),content:i[2],isMatch:true});}return e}function gT(s){let e=s.split(`
1838
+ `),t={entries:[]};for(let n of e){let r=n.match(/^文件:\s*(\d+)\s+已搜索,\s*(\d+)\s+有匹配/);if(r){t.filesSearched=parseInt(r[1],10),t.filesWithMatches=parseInt(r[2],10);continue}let i=n.match(/^匹配:\s*(\d+)/);if(i){t.matchCount=parseInt(i[1],10);continue}let o=n.match(/^▸\s*\[([^\]]+)\]\s+(.+)\s+\((\d+)\s*处\)/);if(o){t.entries.push({module:o[1].trim(),path:o[2].trim(),count:parseInt(o[3],10)});continue}let a=n.match(/^\s*\[([^\]]+)\]\s+(.+?):\s*(\d+)/);a&&t.entries.push({module:a[1].trim(),path:a[2].trim(),count:parseInt(a[3],10)});}return t}function yT(s){let e=[];for(let n=0;n<s.length;n++){if(e.length>=20){e.push(`... +${s.length-e.length} more files`);break}let r=s[n],i=r.module?`[${r.module}] ${r.path} (${r.count} \u5904)`:`${r.path} (${r.count} \u5904)`;e.push(i);}return e.join(`
1839
+ `)}le();function hf(s){let e=0;for(let t of s){let n=t.codePointAt(0)||0;n>=19968&&n<=40959||n>=12288&&n<=12351||n>=65280&&n<=65519||n>=44032&&n<=55215?e+=.67:e+=.25;}return Math.ceil(e)}var bT=new Set(["ephemeral","contextual","summarized"]);function vT(s){let e=s.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.type;return typeof n!="string"||!bT.has(n)?null:t}catch{return null}}function xT(s){let e=[];if(typeof s.summary=="string"&&s.summary.trim()&&e.push(s.summary.trim()),typeof s.file_path=="string"&&s.file_path.trim()&&e.push(`Path: ${s.file_path}`),typeof s.verify_hint=="string"&&s.verify_hint.trim()&&e.push(`Verify: ${s.verify_hint}`),s.status==="error"){let t=typeof s.error=="string"?s.error.trim():"";t&&(e.length===0||!e[0].includes(t))&&e.push(`Error: ${t}`);}return e.length?e.join(`
1840
+ `):void 0}function ST(s,e,t){let n=typeof e=="string"&&e.trim()?e.trim():void 0;if(!s||typeof s!="string")return n;let r=vT(s);if(r)return xT(r)||n;let i=t?`${s}
1841
+ ...(truncated)`:s;return n?`${n}
1842
+
1843
+ ${i}`:i}function ff(s){let e=false;return t=>{if(process.env.CLI_DEBUG==="1"&&f.debug("EVENT",`Received event: type=${t.type}`),!s.uiController){process.env.CLI_DEBUG==="1"&&f.debug("EVENT"," -> SKIPPED: no uiController!");return}switch(process.env.CLI_DEBUG==="1"&&(t.type==="log"?f.debug("EVENT",` log message: "${t.message?.substring(0,50)}..."`):t.type==="text"&&f.debug("EVENT",` text delta: "${t.delta?.substring(0,30)}..."`)),t.type){case "status":if(t.message.includes(" lines)...")){let n=Date.now(),r=s._lastStatusTime||0;if(n-r<100)break;s._lastStatusTime=n;}s.uiController.updateStatus(t.message,t.status);break;case "log":t.level==="error"?f.error("AGENT",t.message,t.detail?{detail:t.detail}:void 0):t.level==="warn"?f.warn("AGENT",t.message,t.detail?{detail:t.detail}:void 0):f.info("AGENT",t.message,t.detail?{detail:t.detail}:void 0),s.uiController.addInfo(t.message,t.detail);break;case "thinking":e=false;break;case "reasoning":if(s.uiController.addReasoningDelta(t.delta),s.setStreamingTokenCount&&s.getStreamingTokenCount&&t.delta){let n=s.getStreamingTokenCount(),r=hf(t.delta);s.setStreamingTokenCount(n+r),s.uiController.updateTaskTokens(n+r);}break;case "text":if(process.env.CLI_DEBUG==="1"&&f.debug("EVENT",` text delta received: "${t.delta?.substring(0,50)}..." (len=${t.delta?.length})`),s.uiController.addTextDelta(t.delta),s.setStreamingTokenCount&&s.getStreamingTokenCount&&t.delta){let n=s.getStreamingTokenCount(),r=hf(t.delta);s.setStreamingTokenCount(n+r),s.uiController.updateTaskTokens(n+r);}break;case "text_complete":process.env.CLI_DEBUG==="1"&&f.debug("EVENT"," text_complete received"),s.uiController.completeReasoningStreaming(),s.uiController.completeTextStreaming();break;case "tool_call_start":{s.uiController.completeTextStreaming(),s.uiController.completeReasoningStreaming(),s.lastToolCallArgs.set(t.name,t.args||{});let n=t.toolId||`${t.name}_${Date.now()}`;s.toolIdToName.set(n,t.name),TT(s.uiController,n,t.name,t.args||{},{targetPath:t.targetPath,description:t.description});break}case "tool_call_delta":process.env.CLI_DEBUG&&f.debug("EVENT",`tool_call_delta: ${t.name} +${t.argumentsDelta.length} chars`);break;case "tool_call_end":{let n=t.toolId,r=(t.name||"").toLowerCase(),o=r==="readfile"||r==="search"?t.summary:ST(typeof t.output=="string"?t.output:void 0,t.summary,t.outputTruncated);n&&s.uiController.getRunningToolLogId(n)&&s.uiController.completeToolCall(n,{success:t.success,duration:t.duration,resultLength:t.resultLength,outputTruncated:t.outputTruncated,summary:o,error:t.success?void 0:o||t.output||t.summary}),n&&s.toolIdToName.delete(n);let a=t.name.toLowerCase();(a.includes("browser")||a.includes("debug_in"))&&s.uiController.checkAndRecoverInput(),s.uiController.updateStatus(t.success?`${t.name} \u2192 ${t.resultLength||0}B`:`${t.name}: Error`,t.success?"tool_result":"error");break}case "tool_output":{let n=s.lastToolCallArgs.get(t.name),r=t.name.toLowerCase();if(gf(r))su(s.uiController,t.name,t.output,t.success,n);else {let o;for(let[a,l]of s.toolIdToName.entries())if(l===t.name){o=a;break}o&&s.uiController.getRunningToolLogId(o)?s.uiController.updateToolCallOutput(o,t.output,{truncated:t.output.length>2e3}):su(s.uiController,t.name,t.output,t.success,n);}s.lastToolCallArgs.delete(t.name);break}case "file_stream":if(t.isComplete)s.uiController.completeCodeGenerationPreview(t.filePath,t.content);else {let n=t.content.split(`
1844
+ `).length;s.uiController.updateStatus(`Generating ${t.filePath} (${n} lines)...`,"tool_call");}break;case "edit_file_stream":t.isComplete&&s.uiController.startEditFile(t.filePath,t.language||"",t.oldString,t.newString,t.startLine,t.description,t.hunks);break;case "write_file_stream":t.isComplete&&s.uiController.startWriteFile(t.filePath,t.language||"",t.content,t.description);break;case "token_usage":{let n={input:t.sessionPromptTokens,output:t.sessionCompletionTokens};s.setRuntimeTokens(n.input,n.output);let r=t.promptTokens+t.completionTokens;s.uiController?.updateTaskTokens(r,true),process.env.CLI_DEBUG&&f.debug("MAIN",`token_usage: sessionPrompt=${t.sessionPromptTokens}, sessionCompletion=${t.sessionCompletionTokens}`);let i={cachedTokens:t.cachedTokens,openaiCachedTokens:t.openaiCachedTokens,anthropicCacheReadTokens:t.anthropicCacheReadTokens,anthropicCacheCreationTokens:t.anthropicCacheCreationTokens};s.pushTokenStats(n.input,n.output,void 0,i);break}case "memory_snapshot":{let n=s.getRuntimeTokens();process.env.CLI_DEBUG&&(f.debug("MAIN","memory_snapshot received:"),f.debug("MAIN",` tokensUsed=${t.snapshot.tokensUsed}, contextWindow=${t.snapshot.profile.contextWindow}`),f.debug("MAIN",` pressure=${t.snapshot.pressure}, state=${t.snapshot.state}`),f.debug("MAIN",` runtimeInputTokens=${n.input}, runtimeOutputTokens=${n.output}`)),s.pushTokenStats(n.input,n.output,t.snapshot);break}case "checkpoint":s.uiController.addInfo(t.auto?`\u21BB Checkpoint: ${t.id} (auto-created before turn)`:`\u21BB Checkpoint: ${t.id}`);break;case "run_result":{s.uiController.completeReasoningStreaming(),s.uiController.completeTextStreaming();let n=t.iterations??0,r=t.toolCalls??0,i=t.durationMs??0,o=t.totalTokens??0,a=(i/1e3).toFixed(1),l=[`iterations: ${n}`,`tools: ${r}`,`duration: ${a}s`,`tokens: ${o}`];s.uiController.addInfo("\u2713 Run completed",l.join(" ")),s.uiController.updateStatus("Complete!","complete"),s.uiController.checkAndRecoverInput();break}case "stream_retry":{let n=t.delayMs>=1e3?`${(t.delayMs/1e3).toFixed(1)}s`:`${t.delayMs}ms`,r="",i="";t.isRateLimit?(r=`\u23F3 API \u901F\u7387\u9650\u5236\uFF0C${n} \u540E\u91CD\u8BD5 (${t.attempt}/${t.maxRetries})`,i=`Rate limited, retrying in ${n}...`):t.isStreamTimeout?(r=`\u23F1\uFE0F Stream \u8D85\u65F6\uFF0C${n} \u540E\u91CD\u8BD5 (${t.attempt}/${t.maxRetries})`,i=`Timeout, retrying in ${n}...`):t.isNetworkError?(r=`\u{1F504} \u7F51\u7EDC\u4E2D\u65AD\uFF0C${n} \u540E\u91CD\u8FDE (${t.attempt}/${t.maxRetries})`,i=`Reconnecting in ${n}...`):(r=`\u{1F504} ${n} \u540E\u91CD\u8BD5 (${t.attempt}/${t.maxRetries})`,i=`Retrying in ${n}...`),s.uiController.addInfo(r,t.error),s.uiController.updateStatus(i,"thinking");break}case "stream_recovered":{let n=`\u2713 \u91CD\u8BD5 ${t.attempt}/${t.maxRetries}\uFF0C\u6B63\u5728\u91CD\u8FDE...`;s.uiController.addInfo(n),s.uiController.updateStatus("Reconnecting...","thinking");break}case "error_classified":e=true,s.uiController.addError(`${t.category}: ${t.code}`,`${t.message}${t.suggestion?`
1845
+ \u{1F4A1} Suggestion: ${t.suggestion}`:""}
1846
+ Retryable: ${t.retryable}`);break;case "error":if(s.uiController.completeReasoningStreaming(),s.uiController.completeTextStreaming(),!e){let n=t.message.split(`
1847
+ `),r=n[0],i=n.length>1?n.slice(1).join(`
1848
+ `):void 0;s.uiController.addError(r,i);}s.uiController.updateStatus(t.message.split(`
1849
+ `)[0],"error"),e=false,s.uiController.checkAndRecoverInput();break}}}var _T=new Set(["web_search","websearch","web_fetch","webfetch","readfile","search","search_files","glob","show_tree","list_directory","smart_tree","execute_bash","execute_shell","bash","execute_python","execute_js","execute_javascript","debug_in_browser","edit_file","edit"]);function gf(s){return _T.has(s)||s.includes("websearch")||s.includes("webfetch")}function TT(s,e,t,n,r){if(!s)return;let i=t.toLowerCase();if(gf(i)){mf(s,t,n);return}s.startToolCallWithId(e,t,n,r);}le();function wT(s,e){let t=te.basename(e,te.extname(e))||"structured_output";return s&&typeof s=="object"&&s.schema&&typeof s.schema=="object"?{name:s.name||t,description:s.description,schema:s.schema,strict:s.strict??true}:{name:s?.title||t,schema:s||{},strict:true}}function yf(s){let e=s||process.env.CD_OUTPUT_SCHEMA||process.env.NEOX_OUTPUT_SCHEMA;if(!e)return;let t=te.isAbsolute(e)?e:te.resolve(process.cwd(),e);try{let n=an.readFileSync(t,"utf-8"),r=JSON.parse(n),i=wT(r,t);return f.info("SCHEMA",`Structured output schema loaded: ${i.name}`),i}catch(n){throw f.error("SCHEMA",`Failed to load structured output schema from ${e}: ${n.message}`),n}}async function bf(s,e){let t="structured-output-example.schema.json",n=te.resolve(s,e||t),r={name:"TaskSummary",description:"\u793A\u4F8B\uFF1A\u4EFB\u52A1\u603B\u7ED3 Schema\uFF0C\u53EF\u4F5C\u4E3A\u81EA\u5B9A\u4E49 Schema \u7684\u8D77\u70B9",schema:{type:"object",properties:{status:{type:"string",enum:["ok","needs_attention","error"],description:"\u672C\u6B21\u4EFB\u52A1\u7684\u6700\u7EC8\u72B6\u6001"},summary:{type:"string",description:"\u5BF9\u4EFB\u52A1\u7684\u7B80\u8981\u603B\u7ED3\uFF0C1-3 \u53E5\u8BDD"},steps:{type:"array",description:"\u6267\u884C\u6B65\u9AA4\u5217\u8868",items:{type:"object",properties:{title:{type:"string"},result:{type:"string"}},required:["title"],additionalProperties:false}},next_actions:{type:"array",description:"\u9700\u8981\u8DDF\u8FDB\u7684\u52A8\u4F5C",items:{type:"string"}}},required:["status","summary"],additionalProperties:false},strict:true};try{await an.promises.writeFile(n,JSON.stringify(r,null,2),"utf-8"),b(""),b(v.success(`[v] \u793A\u4F8B Schema \u5DF2\u751F\u6210: ${n}`)),b(v.dim("\u4F7F\u7528\u65B9\u5F0F:")),b(v.dim(" 1. \u6839\u636E\u9700\u8981\u4FEE\u6539\u5B57\u6BB5/\u63CF\u8FF0")),b(v.dim(` 2. \u542F\u52A8 CLI: neox --output-schema ${e||t}`)),b(v.dim(" 3. CLI \u4F1A\u5F3A\u5236\u8F93\u51FA\u7B26\u5408\u8BE5 Schema \u7684 JSON")),b(""),b(v.highlight("\u793A\u4F8B\u7ED3\u6784 (\u6458\u5F55):")),b(v.dim(JSON.stringify(r.schema,null,2)));}catch(i){b(v.error(`[x] \u751F\u6210\u793A\u4F8B Schema \u5931\u8D25: ${i.message}`));}}function vf(s){return s.map(e=>({id:e.id??e.data?.id,name:e.name??e.data?.name,timestamp:e.timestamp??e.data?.timestamp??Date.now()})).filter(e=>typeof e.id=="string")}var kT=[{id:"provider",title:"Provider",description:"\u4EA4\u4E92\u5F0F\u9009\u62E9/\u5207\u6362 Provider"},{id:"model",title:"Model",description:"\u4EA4\u4E92\u5F0F\u9009\u62E9 Provider \u2192 Model"},{id:"session",title:"Session",description:"\u4EA4\u4E92\u5F0F\u9009\u62E9/\u5207\u6362\u4F1A\u8BDD"},{id:"mode",title:"Mode",description:"\u4EA4\u4E92\u5F0F\u5207\u6362 Agent/Ask \u6A21\u5F0F"},{id:"sandbox",title:"Sandbox",description:"\u4EA4\u4E92\u5F0F\u5207\u6362\u6C99\u7BB1\u6A21\u5F0F"},{id:"tracing",title:"Tracing",description:"\u4EA4\u4E92\u5F0F\u5207\u6362\u8FFD\u8E2A\u529F\u80FD"},{id:"thinking",title:"Thinking",description:"\u4EA4\u4E92\u5F0F\u5207\u6362\u6DF1\u5EA6\u601D\u8003"},{id:"approval",title:"Approval",description:"\u4EA4\u4E92\u5F0F\u5207\u6362\u5BA1\u6279\u6A21\u5F0F"},{id:"index",title:"Index",description:"\u4EE3\u7801\u7D22\u5F15\u7BA1\u7406 (\u6784\u5EFA/\u67E5\u770B/\u6E05\u9664)"},{id:"help-text",title:"View Help Text",description:"\u67E5\u770B\u5E2E\u52A9\u6587\u6863"}];function Ms(s,e){b(s);}function CT(){return ["",v.highlight(" \u57FA\u672C\u547D\u4EE4 (Commands):"),v.dim(" \u6240\u6709\u547D\u4EE4\u652F\u6301\u4EA4\u4E92\u5F0F\u9009\u62E9\uFF0C\u76F4\u63A5\u8F93\u5165\u547D\u4EE4\u5373\u53EF"),"",v.primary(" /help ")+v.dim("\u4EA4\u4E92\u5F0F\u5E2E\u52A9\u83DC\u5355"),v.primary(" /exit ")+v.dim("\u9000\u51FA CLI"),v.primary(" /provider ")+v.dim("\u4EA4\u4E92\u5F0F\u9009\u62E9/\u5207\u6362 Provider"),v.primary(" /model ")+v.dim("\u4EA4\u4E92\u5F0F\u9009\u62E9 Provider \u2192 Model"),v.primary(" /mode ")+v.dim("\u4EA4\u4E92\u5F0F\u5207\u6362 Agent/Ask \u6A21\u5F0F"),v.primary(" /approval ")+v.dim("\u4EA4\u4E92\u5F0F\u5207\u6362\u5BA1\u6279\u6A21\u5F0F Auto/Manual"),v.primary(" /sandbox ")+v.dim("\u4EA4\u4E92\u5F0F\u5207\u6362\u6C99\u7BB1\u6A21\u5F0F On/Off"),v.primary(" /tracing ")+v.dim("\u4EA4\u4E92\u5F0F\u5207\u6362\u8FFD\u8E2A\u529F\u80FD On/Off"),v.primary(" /thinking ")+v.dim("\u4EA4\u4E92\u5F0F\u5207\u6362\u6DF1\u5EA6\u601D\u8003 On/Off"),v.primary(" /index ")+v.dim("\u4EE3\u7801\u7D22\u5F15\u7BA1\u7406 (\u6784\u5EFA/\u67E5\u770B/\u6E05\u9664)"),"",v.dim(" \u76F4\u63A5\u547D\u4EE4 (\u4E5F\u53EF\u76F4\u63A5\u6307\u5B9A\u53C2\u6570):"),v.dim(" /provider <id> \u5207\u6362\u5230\u6307\u5B9A Provider"),v.dim(" /model <name> \u5207\u6362\u5230\u6307\u5B9A Model"),v.dim(" /mode agent|ask \u76F4\u63A5\u8BBE\u7F6E\u6A21\u5F0F"),v.dim(" /sandbox on|off \u76F4\u63A5\u8BBE\u7F6E\u6C99\u7BB1"),v.dim(" /tracing on|off \u76F4\u63A5\u8BBE\u7F6E\u8FFD\u8E2A"),v.dim(" /thinking on|off \u76F4\u63A5\u8BBE\u7F6E\u601D\u8003"),"",v.primary(" /clear ")+v.dim("\u6E05\u7A7A\u5BF9\u8BDD\u5386\u53F2"),v.primary(" /stats ")+v.dim("\u663E\u793A\u7EDF\u8BA1\u4FE1\u606F"),v.primary(" /config-clear")+v.dim("\u6E05\u9664\u914D\u7F6E\u6587\u4EF6"),v.primary(" /attach <path>")+v.dim("\u6DFB\u52A0\u56FE\u7247\u9644\u4EF6"),v.primary(" /attachments ")+v.dim("\u7BA1\u7406\u9644\u4EF6 (list/clear/remove)")]}function ET(s=Ms){for(let e of CT())s(e);}function IT(){return [v.primary(" /trace ")+v.dim("\u67E5\u770B\u5F53\u524D\u4F1A\u8BDD\u8FFD\u8E2A (View current session trace)"),v.primary(" /trace-history ")+v.dim("\u67E5\u770B\u5386\u53F2\u8FFD\u8E2A\u8BB0\u5F55 (View recent session history)"),v.primary(" /trace-stats ")+v.dim("\u663E\u793A\u8FFD\u8E2A\u7EDF\u8BA1 (Show tracing statistics)"),v.primary(" /trace-clean ")+v.dim("\u6E05\u7406\u65E7\u65E5\u5FD7 (Clean up old trace logs)")]}function RT(s=Ms){for(let e of IT())s(e);}function PT(){return ["",v.highlight(" \u4F1A\u8BDD\u547D\u4EE4 (Session Commands):"),"",v.primary(" /sessions ")+v.dim("\u4EA4\u4E92\u5F0F\u9009\u62E9/\u5207\u6362\u4F1A\u8BDD"),v.primary(" /session <id> ")+v.dim("\u76F4\u63A5\u5207\u6362\u5230\u6307\u5B9A\u4F1A\u8BDD"),v.primary(" /session-new ")+v.dim("\u521B\u5EFA\u65B0\u4F1A\u8BDD"),v.primary(" /session-info ")+v.dim("\u663E\u793A\u4F1A\u8BDD\u4FE1\u606F"),v.primary(" /undo [n] ")+v.dim("\u64A4\u9500\u6700\u8FD1 n \u8F6E\u5BF9\u8BDD"),v.primary(" /checkpoint ")+v.dim("\u521B\u5EFA\u68C0\u67E5\u70B9"),v.primary(" /checkpoints ")+v.dim("\u5217\u51FA\u68C0\u67E5\u70B9"),v.primary(" /rollback <id> ")+v.dim("\u56DE\u6EDA\u5230\u68C0\u67E5\u70B9"),v.primary(" /session-clear ")+v.dim("\u6E05\u7A7A\u4F1A\u8BDD"),v.primary(" /session-export ")+v.dim("\u5BFC\u51FA\u4F1A\u8BDD"),v.primary(" /compact ")+v.dim("\u624B\u52A8\u538B\u7F29\u4E0A\u4E0B\u6587")]}function AT(s=Ms){for(let e of PT())s(e);}function MT(){return ["",v.highlight(" \u8FDB\u7A0B\u7BA1\u7406 (Process Management):"),"",v.primary(" /processes ")+v.dim("\u67E5\u770B\u8FDB\u7A0B\u5217\u8868"),v.primary(" /ps ")+v.dim("/processes \u7684\u7B80\u5199"),v.primary(" /kill <pid> ")+v.dim("\u7EC8\u6B62\u6307\u5B9A\u8FDB\u7A0B"),v.primary(" /kill all ")+v.dim("\u7EC8\u6B62\u6240\u6709\u540E\u53F0\u8FDB\u7A0B")]}function LT(s=Ms){for(let e of MT())s(e);}function OT(){return ["",v.highlight(" \u5FEB\u6377\u952E (Keyboard Shortcuts):"),"",v.dim(" \u4EA4\u4E92\u5F0F\u9009\u62E9\u65F6:"),v.primary(" \u2191/\u2193 ")+v.dim("\u4E0A\u4E0B\u79FB\u52A8\u9009\u62E9"),v.primary(" Enter ")+v.dim("\u786E\u8BA4\u9009\u62E9"),v.primary(" ESC ")+v.dim("\u53D6\u6D88\u9009\u62E9"),"",v.dim(" \u8FD0\u884C\u65F6:"),v.primary(" ESC ")+v.dim("\u4E2D\u65AD\u5F53\u524D\u4EFB\u52A1\uFF08\u6309\u4E24\u6B21\uFF09"),v.primary(" Tab ")+v.dim("\u5207\u6362 Thinking \u6A21\u5F0F"),v.error(" Ctrl+C ")+v.dim("\u9000\u51FA\u7A0B\u5E8F"),""]}function DT(s=Ms){for(let e of OT())s(e);}function sa(s,e=Ms){ET(e),s&&RT(e),AT(e),LT(e),DT(e);}function xf(){return kT.map(s=>({title:s.title,value:s.id,description:s.description}))}async function ru(s){let{runtimeHost:e,colors:t,promptSelect:n,sessionEnabled:r,activateSession:i,logInfo:o}=s;if(!r){o("Session disabled","Session persistence is not enabled.");return}let a=await e.listSessions();if(a.length===0){o("No sessions","No sessions found. Start chatting to create one.");return}let l=e.getCurrentSessionId();try{let c=a.slice(0,15).map(m=>{let h=l&&m.sessionId===l,g=ta(m.updatedAt);return {label:h?`\u25CF ${m.sessionId}`:m.sessionId,value:m.sessionId,description:`${m.itemCount} items, ${g}${h?" (current)":""}`}}),u=await n("Select session",c,l||void 0);if(u===l){o("Session","Already on this session.");return}let d=await e.switchSession(u),p=await i(d,{loadHistory:!0});o("Session switched",`${u}${p>0?` (${p} messages loaded)`:""}`);}catch(c){c.message!=="cancelled"&&o("Session switch failed",c.message);}}async function _f(s,e){let{runtimeHost:t,sessionEnabled:n,activateSession:r,colors:i}=s;if(!n){b(i.error(" [x] Session persistence is disabled"));return}try{let o=await t.switchSession(e),a=await r(o,{loadHistory:!0});b(""),b(i.success(` \u2713 Switched to session: ${e}`)),a>0&&b(i.dim(` Loaded ${a} messages`)),b("");}catch(o){b(i.error(` [x] ${o.message}`));}}async function Tf(s,e){let{runtimeHost:t,sessionEnabled:n,activateSession:r,colors:i}=s;if(!n){b(i.error(" [x] Session persistence is disabled"));return}try{let o=await t.createSession(e);await r(o,{loadHistory:!1}),await t.createCheckpoint("session_start"),b(""),b(i.success(` \u2713 Created new session: ${o.sessionId}`)),b("");}catch(o){b(i.error(` [x] Failed to create session: ${o.message}`));}}async function wf(s){let{runtimeHost:e,colors:t}=s;try{let n=await e.getSessionInfo();b(""),b(t.highlight(" Session Info:")),b(""),b(t.dim(" Session ID: ")+t.info(n.sessionId)),b(t.dim(" Turns: ")+t.info(n.turnCount.toString())),b(t.dim(" Messages: ")+t.info(n.messageCount.toString())),b(t.dim(" Checkpoints: ")+t.info(n.checkpointCount.toString())),n.meta&&(b(t.dim(" Model: ")+t.info(n.meta.model||"N/A")),n.meta.createdAt&&b(t.dim(" Created: ")+t.info(new Date(n.meta.createdAt).toLocaleString()))),b("");}catch{b(t.dim(" No active session"));}}async function kf(s,e){let{runtimeHost:t,colors:n}=s;try{let r=parseInt(e||"1")||1,i=await t.undoTurns(r);if(i.success){if(b(""),b(n.success(` \u2713 Undone ${i.undoneCount} turn(s)`)),i.messages.length>0){b(n.dim(" Removed messages:"));for(let o of i.messages.slice(0,4)){let a=(o.content||"").slice(0,50);b(n.dim(` [${o.role}] ${a}${a.length>=50?"...":""}`));}i.messages.length>4&&b(n.dim(` ... and ${i.messages.length-4} more`));}b("");}else b(n.warning(" \u26A0 Nothing to undo"));}catch(r){b(n.error(` [x] Undo failed: ${r.message}`));}}async function Cf(s,e){let{runtimeHost:t,colors:n}=s;try{let r=await t.createCheckpoint(e||void 0);b(""),b(n.success(` \u2713 Checkpoint created: ${r}`)),e&&b(n.dim(` Name: ${e}`)),b("");}catch(r){b(n.error(` [x] Failed to create checkpoint: ${r.message}`));}}async function Ef(s){let{runtimeHost:e,normalizeCheckpoints:t,colors:n}=s;try{let r=t(await e.listCheckpoints());if(r.length===0){b(""),b(n.dim(" No checkpoints")),b("");return}b(""),b(n.highlight(" Checkpoints:")),b("");for(let i of r){let o=new Date(i.timestamp).toLocaleString();b(n.info(` ${i.id}`)+(i.name?n.primary(` [${i.name}]`):"")+n.dim(` (${o})`));}b(""),b(n.dim(" Use /rollback <id> to restore")),b("");}catch(r){b(n.error(` [x] Failed to list checkpoints: ${r.message}`));}}async function If(s,e){let{runtimeHost:t,normalizeCheckpoints:n,colors:r}=s;try{if(!e){let o=n(await t.listCheckpoints());if(o.length===0){b(r.warning(" \u26A0 No checkpoints available")),b(r.dim(" Checkpoints are auto-created before each turn"));return}let a=o.find(u=>u.name==="session_start"),l=o.filter(u=>u.name?.startsWith("turn_")),c=o.filter(u=>u.name!=="session_start"&&!u.name?.startsWith("turn_"));if(b(""),b(r.highlight(" Available Checkpoints:")),b(""),a){b(r.success(" Session Start:"));let u=new Date(a.timestamp).toLocaleString();b(r.dim(` ${a.id}`)),b(r.dim(` ${u}`)),b("");}l.length>0&&(b(r.primary(" Turn Checkpoints:")),l.slice().reverse().forEach(u=>{let d=new Date(u.timestamp).toLocaleString(),p=u.name?.match(/turn_(\d+)/),m=p?`Turn ${p[1]}`:u.name;b(r.dim(` ${u.id} \u2190 ${m}`)),b(r.dim(` ${d}`)),b("");})),c.length>0&&(b(r.highlight(" Manual Checkpoints:")),c.forEach(u=>{let d=new Date(u.timestamp).toLocaleString();b(r.dim(` ${u.id} (${u.name||"unnamed"})`)),b(r.dim(` ${d}`)),b("");})),b(r.dim(" Usage: /rollback <checkpoint_id>")),b(r.dim(" Tip: Checkpoints are auto-created before each turn")),b("");return}let i=await t.rollbackTo(e);b(""),b(r.success(` \u2713 Rolled back to checkpoint: ${e}`)),b(r.dim(` Removed ${i.removedCount} items`)),b("");}catch(i){b(r.error(` [x] Rollback failed: ${i.message}`));}}async function Rf(s){let{runtimeHost:e,colors:t}=s;try{await e.clearSession(),b(""),b(t.success(" \u2713 Session cleared")),b("");}catch(n){b(t.error(` [x] Failed to clear session: ${n.message}`));}}async function Pf(s,e){let{currentSession:t,sessionManager:n,colors:r}=s;if(!t){b(r.error(" [x] No active session"));return}try{let i=t.sessionId,o=await n.exportSession(i);e?(await an.promises.writeFile(e,o,"utf-8"),b(""),b(r.success(` \u2713 Session exported to: ${e}`)),b("")):(b(""),b(r.highlight(" Session Export (JSON):")),b(""),b(o),b(""));}catch(i){b(r.error(` [x] Export failed: ${i.message}`));}}async function Af(s,e){let{sessionEnabled:t,compatProfile:n,uiController:r,runtimeHost:i,logInfo:o,colors:a}=s,{autoCompactionInProgress:l}=s;if(!t)return o("\u4F1A\u8BDD\u5DF2\u7981\u7528","\u538B\u7F29\u4EC5\u9002\u7528\u4E8E\u542F\u7528\u4E86\u6301\u4E45\u5316\u7684\u4F1A\u8BDD\u3002"),l;if(!n)return o("\u7F3A\u5C11\u6A21\u578B\u4E0A\u4E0B\u6587\u753B\u50CF","\u8BF7\u68C0\u67E5 Provider/Model \u914D\u7F6E\u3002"),l;if(e)return o("\u6B63\u5728\u6267\u884C\u4EFB\u52A1","\u8BF7\u7B49\u5F85\u5F53\u524D\u4EFB\u52A1\u5B8C\u6210\u6216\u6309 ESC \u4E24\u6B21\u4E2D\u65AD\u540E\u518D\u538B\u7F29\u3002"),l;if(l)return o("\u538B\u7F29\u8FDB\u884C\u4E2D","\u8BF7\u7A0D\u5019\u7247\u523B\u3002"),l;l=true;try{r&&(r.addInfo("[~] \u624B\u52A8\u538B\u7F29\u4F1A\u8BDD","\u6B63\u5728\u6574\u7406\u65E7\u7684\u5386\u53F2\u6D88\u606F\u2026"),r.updateStatus("[~] Manual compaction...","compacting")),await i.compactSession();}catch(c){o("\u624B\u52A8\u538B\u7F29\u5931\u8D25",c?.message||String(c));}finally{l=false;}return l}mo();async function Mf(s){Ee.refreshStatus();let e=Ee.getBackgroundRunning();if(b(""),b(v.highlight(" \u540E\u53F0\u8FDB\u7A0B (Background Processes)")),b(""),e.length===0){b(v.dim(" \u6CA1\u6709\u8FD0\u884C\u4E2D\u7684\u540E\u53F0\u8FDB\u7A0B")),b(""),b(v.dim(" \u63D0\u793A: \u4F7F\u7528 execute_shell \u7684 background=true \u53C2\u6570\u542F\u52A8\u540E\u53F0\u8FDB\u7A0B")),b("");return}b(v.success(` \u{1F7E2} ${e.length} \u4E2A\u540E\u53F0\u8FDB\u7A0B\u6B63\u5728\u8FD0\u884C:`)),b(""),e.forEach(t=>{let n=Date.now()-t.startTime.getTime(),r=uf(n),i=t.command.length>50?t.command.substring(0,47)+"...":t.command;b(v.dim(" ")+v.warning(`PID ${t.pid}`)),b(v.dim(" \u547D\u4EE4: ")+v.info(i)),b(v.dim(" \u8FD0\u884C: ")+v.dim(r)),b(v.dim(" \u76EE\u5F55: ")+v.dim(t.cwd)),b("");}),b(v.dim(" \u547D\u4EE4:")),b(v.dim(" /kill <pid> ")+v.dim("\u7EC8\u6B62\u6307\u5B9A\u8FDB\u7A0B")),b(v.dim(" /kill all ")+v.dim("\u7EC8\u6B62\u6240\u6709\u540E\u53F0\u8FDB\u7A0B")),b("");}async function Lf(s){if(!s){b(""),b(v.error(" \u7528\u6CD5: /kill <pid> \u6216 /kill all")),b(v.dim(" \u4F7F\u7528 /processes \u67E5\u770B\u8FD0\u884C\u4E2D\u7684\u8FDB\u7A0B")),b("");return}if(Ee.refreshStatus(),s.toLowerCase()==="all"){let r=Ee.getBackgroundRunning();if(r.length===0){b(""),b(v.info(" \u6CA1\u6709\u8FD0\u884C\u4E2D\u7684\u540E\u53F0\u8FDB\u7A0B")),b("");return}b(""),b(v.warning(` \u5373\u5C06\u7EC8\u6B62 ${r.length} \u4E2A\u540E\u53F0\u8FDB\u7A0B:`)),r.forEach(o=>{b(v.dim(` PID ${o.pid}: ${o.command.substring(0,40)}...`));}),b("");let{confirm:i}=await kn({type:"confirm",name:"confirm",message:"\u786E\u8BA4\u7EC8\u6B62\u6240\u6709\u540E\u53F0\u8FDB\u7A0B?",initial:false});if(i){let o=Ee.killAll(true);b(""),b(v.success(` \u2713 \u5DF2\u7EC8\u6B62 ${o.killed} \u4E2A\u8FDB\u7A0B`)),o.failed>0&&b(v.warning(` \u26A0 ${o.failed} \u4E2A\u8FDB\u7A0B\u7EC8\u6B62\u5931\u8D25`)),b("");}else b(v.dim(" \u5DF2\u53D6\u6D88"));return}let e=parseInt(s,10);if(isNaN(e)){b(""),b(v.error(` \u65E0\u6548\u7684 PID: ${s}`)),b("");return}let t=Ee.get(e);if(!t)try{process.kill(e,0),b(""),b(v.warning(` PID ${e} \u4E0D\u5728\u8FDB\u7A0B\u7BA1\u7406\u5668\u4E2D\uFF0C\u5C1D\u8BD5\u76F4\u63A5\u7EC8\u6B62...`));let{confirm:r}=await kn({type:"confirm",name:"confirm",message:`\u786E\u8BA4\u7EC8\u6B62 PID ${e}?`,initial:!1});r?(process.kill(e,"SIGTERM"),b(v.success(` \u2713 \u5DF2\u53D1\u9001 SIGTERM \u5230 PID ${e}`))):b(v.dim(" \u5DF2\u53D6\u6D88")),b("");return}catch{b(""),b(v.error(` \u8FDB\u7A0B ${e} \u4E0D\u5B58\u5728`)),b("");return}if(t.status!=="running"){b(""),b(v.info(` \u8FDB\u7A0B ${e} \u5DF2\u7ECF\u7ED3\u675F (\u72B6\u6001: ${t.status})`)),b("");return}b(""),b(v.warning(" \u5373\u5C06\u7EC8\u6B62\u8FDB\u7A0B:")),b(v.dim(` PID: ${t.pid}`)),b(v.dim(` \u547D\u4EE4: ${t.command}`)),b(v.dim(` \u7C7B\u578B: ${t.background?"\u540E\u53F0":"\u540C\u6B65"}`)),b("");let{confirm:n}=await kn({type:"confirm",name:"confirm",message:"\u786E\u8BA4\u7EC8\u6B62\u6B64\u8FDB\u7A0B?",initial:true});if(n){let r=t.background?Ee.killProcessGroup(e):Ee.kill(e,"SIGTERM",true);b(""),r?b(v.success(` \u2713 \u5DF2\u7EC8\u6B62\u8FDB\u7A0B ${e}`)):b(v.error(` \u2717 \u65E0\u6CD5\u7EC8\u6B62\u8FDB\u7A0B ${e}`)),b("");}else b(v.dim(" \u5DF2\u53D6\u6D88"));}function ii(s){let e=s.getProviders();if(e.length===0){s.logInfo("No providers configured","Use /provider add to create one.");return}let n=s.getDefaultProvider()?.id,i=`${e.map((o,a)=>{let l=[];o.id===s.providerId&&l.push("current"),o.id===n&&l.push("default");let c=ln[o.protocol]||"OpenAI",u=o.models.length>0?o.models.map(p=>p.name).join(", "):"none",d=o.baseUrl||As[o.protocol];return [`${a+1}. ${o.name}${ri(l)}`,` id: ${o.id}`,` protocol: ${c}`,` base url: ${d}`,` models: ${u}`].join(`
1850
+ `)}).join(`
1851
+
1852
+ `)}
1853
+
1854
+ Commands:
1855
+ /provider use <id> switch provider
1856
+ /provider add add provider
1857
+ /provider edit <id> edit provider
1858
+ /provider remove <id> remove provider
1859
+ /provider default <id> set default provider`;s.logInfo("Available providers",i);}async function ou(s,e){if(!e){ii(s);return}let t=s.getProvider(e)||s.getProviders().find(n=>n.protocol===e);if(!t){s.logInfo("Provider not found",`Unknown provider "${e}".`);return}if(t.id===s.providerId){s.logInfo("Provider unchanged",`${t.name} is already active.`);return}try{let n=s.resolveModel(t.id);if(!n)throw new Error(`Provider "${t.name}" does not have any models configured.`);s.setLastSelectedModel(t.id,n),s.setDefaultProvider(t.id),await s.applyProviderState({providerId:t.id,provider:t.protocol,model:n,providerSettings:t}),s.updateProviderDisplay(s.getProviderDisplayName(),n),s.logInfo("Provider updated",`Provider: ${s.getProviderDisplayName()}
1860
+ Model: ${n}`);}catch(n){s.logInfo("Failed to switch provider",n.message);}}var Of=[{label:"claude-sonnet-4-5-20250929",value:"claude-sonnet-4-5-20250929",description:"Claude Sonnet 4.5"},{label:"claude-sonnet-4-20250514-thinking",value:"claude-sonnet-4-20250514-thinking",description:"Claude Sonnet 4 Thinking"},{label:"claude-opus-4-5-20251101",value:"claude-opus-4-5-20251101",description:"Claude Opus 4.5"},{label:"claude-haiku-4-5-20251001",value:"claude-haiku-4-5-20251001",description:"Claude Haiku 4.5"}],$T={openai:[],"openai-responses":[],anthropic:Of,"anthropic-openai":Of,doubao:[],gemini:[]};async function Df(s){try{s.logInfo("\u6DFB\u52A0\u65B0\u7684 Provider","\u8BF7\u6309\u6B65\u9AA4\u5B8C\u6210\u914D\u7F6E"),s.logInfo("Step 1/4","Provider \u540D\u79F0\u548C\u5730\u5740");let e=await s.promptText("Provider \u663E\u793A\u540D\u79F0",{allowEmpty:!1,hint:"\u4F8B\u5982: OpenAI, Claude API, \u79C1\u6709\u4EE3\u7406"}),t=await s.promptSelect("\u534F\u8BAE\u683C\u5F0F",[{label:"OpenAI (Chat Completions)",value:"openai",description:"GPT-4, GPT-4o \u7B49\u6807\u51C6\u6A21\u578B"},{label:"OpenAI (Responses API)",value:"openai-responses",description:"o3, o4-mini \u7B49\u63A8\u7406\u6A21\u578B"},{label:"Anthropic (Claude)",value:"anthropic",description:"Claude \u539F\u751F\u683C\u5F0F"},{label:"Anthropic (OpenAI \u683C\u5F0F)",value:"anthropic-openai",description:"\u4EE3\u7406\u670D\u52A1\u5E38\u7528"},{label:"\u8C46\u5305 (Doubao)",value:"doubao",description:"\u706B\u5C71\u65B9\u821F\u8C46\u5305\uFF0C\u652F\u6301\u6DF1\u5EA6\u601D\u8003"},{label:"Google Gemini",value:"gemini",description:"Gemini 2.5 \u7CFB\u5217"}],"anthropic"),n=As[t],r=await s.promptText("Base URL",{defaultValue:n,hint:"\u76F4\u63A5\u56DE\u8F66\u4F7F\u7528\u9ED8\u8BA4\u503C\uFF0C\u6216\u8F93\u5165\u81EA\u5B9A\u4E49\u4EE3\u7406\u5730\u5740"});s.logInfo("Step 2/4","\u9009\u62E9\u6A21\u578B");let i=$T[t]||[],o=[],a="";if(i.length>0){let m=[...i,{label:"\u81EA\u5B9A\u4E49\u6A21\u578B\u540D\u79F0",value:"__custom__",description:"\u624B\u52A8\u8F93\u5165\u6A21\u578B\u540D\u79F0"}],h=await s.promptSelect("\u9009\u62E9\u9ED8\u8BA4\u6A21\u578B",m,i[0]?.value);if(h==="__custom__"?a=await s.promptText("\u8F93\u5165\u6A21\u578B\u540D\u79F0",{allowEmpty:!1}):a=h,o.push(a),await s.promptYesNo("\u662F\u5426\u6DFB\u52A0\u66F4\u591A\u6A21\u578B?",!1)){let y=await s.promptText("\u8F93\u5165\u66F4\u591A\u6A21\u578B\u540D\u79F0",{allowEmpty:!0,hint:"\u591A\u4E2A\u6A21\u578B\u7528\u9017\u53F7\u5206\u9694\uFF0C\u4F8B\u5982: gpt-4o,gpt-4-turbo"});if(y.trim()){let x=y.split(",").map(S=>S.trim()).filter(S=>S);for(let S of x)o.includes(S)||o.push(S);}}}else {a=await s.promptText("\u8F93\u5165\u9ED8\u8BA4\u6A21\u578B\u540D\u79F0",{allowEmpty:!1}),o.push(a);let m=await s.promptText("\u8F93\u5165\u66F4\u591A\u6A21\u578B\u540D\u79F0 (\u53EF\u9009)",{allowEmpty:!0,hint:"\u591A\u4E2A\u6A21\u578B\u7528\u9017\u53F7\u5206\u9694"});if(m.trim()){let h=m.split(",").map(g=>g.trim()).filter(g=>g);for(let g of h)o.includes(g)||o.push(g);}}s.logInfo("Step 3/4","API \u5BC6\u94A5");let l=await s.promptText("API Key",{allowEmpty:!1,hint:"\u8F93\u5165\u4F60\u7684 API \u5BC6\u94A5\u6216 Token"});s.logInfo("Step 4/4","\u786E\u8BA4\u914D\u7F6E");let c=[`\u540D\u79F0: ${e}`,`\u534F\u8BAE: ${ln[t]}`,`\u5730\u5740: ${r}`,`\u6A21\u578B: ${o.join(", ")}`,`\u9ED8\u8BA4: ${a}`].join(`
1861
+ `);s.logInfo("\u914D\u7F6E\u9884\u89C8",c);let u=await s.promptYesNo("\u8BBE\u4E3A\u9ED8\u8BA4 Provider?",s.getProviderCount()===0),d=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32),p=s.addProvider({id:d||void 0,name:e,protocol:t,apiKey:l,baseUrl:r,defaultModel:a,models:o,setAsDefault:u});s.setLastSelectedModel(p.id,p.defaultModel||a),await s.applyProviderState({providerId:p.id,provider:p.protocol,model:p.defaultModel||a,providerSettings:p}),s.updateProviderDisplay(s.getProviderDisplayName(),p.defaultModel||a),s.logInfo("\u2713 Provider \u521B\u5EFA\u6210\u529F",[`Provider: ${s.getProviderDisplayName()}`,`Model: ${p.defaultModel||a}`,`ID: ${p.id}`].join(`
1862
+ `)),ii(s);}catch(e){e.message==="cancelled"?s.logInfo("\u5DF2\u53D6\u6D88","Provider \u8BBE\u7F6E\u5DF2\u53D6\u6D88"):s.logInfo("\u521B\u5EFA\u5931\u8D25",e.message);}}async function $f(s,e){let t=s.getProviderByIdentifier(e);if(!t&&(t=await s.selectProviderFromList("Select provider to edit"),!t)||!t)return;let n=t;try{let i=(await s.promptText("Provider ID",{defaultValue:n.id,hint:"\u4EC5\u9650\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF08-\uFF09\uFF0C\u6700\u957F 48 \u4E2A\u5B57\u7B26"})).trim()||n.id,o=n.id;if(i!==o){let y=s.renameProvider(o,i);n=y,s.providerId===o&&(await s.applyProviderState({providerId:y.id,provider:y.protocol,model:s.model,providerSettings:y}),s.updateProviderDisplay(s.getProviderDisplayName(),s.model));}let a=await s.promptText("Provider display name",{defaultValue:n.name}),l=await s.promptSelect("Protocol format",[{label:"OpenAI (Chat Completions)",value:"openai",description:"GPT-4, GPT-3.5 \u7B49\u6807\u51C6\u6A21\u578B"},{label:"OpenAI (Responses API)",value:"openai-responses",description:"GPT-5, o3 \u7B49\u652F\u6301\u63A8\u7406\u7684\u6A21\u578B"},{label:"Anthropic (Claude)",value:"anthropic"},{label:"Anthropic (OpenAI \u683C\u5F0F)",value:"anthropic-openai",description:"\u4F7F\u7528 OpenAI \u517C\u5BB9\u683C\u5F0F\u8C03\u7528 Claude"},{label:"\u8C46\u5305 (Doubao)",value:"doubao",description:"\u706B\u5C71\u65B9\u821F\u8C46\u5305\u6A21\u578B\uFF0C\u652F\u6301\u6DF1\u5EA6\u601D\u8003"}],n.protocol),c=n.baseUrl||As[n.protocol],d=await s.promptSelect("Base URL",[{label:`\u4FDD\u6301\u5F53\u524D (${c})`,value:"keep"},{label:"\u4FEE\u6539 Base URL",value:"custom"}],"keep")==="custom"?await s.promptText("New Base URL",{defaultValue:c}):void 0,m=await s.promptYesNo("Update API key / token?",!1)?await s.promptText("New API key / token",{allowEmpty:!1}):void 0,h;n.models.length>0&&await s.promptYesNo("Update default model?",!1)&&(h=await s.promptSelect("Select default model",n.models.map(x=>({label:x.name===n.defaultModel?`${x.name} (current)`:x.name,value:x.name})),n.defaultModel||n.models[0].name));let g=s.updateProvider(n.id,{name:a,protocol:l,baseUrl:d,apiKey:m,defaultModel:h});if(g.id===s.providerId){let y=h||s.model;h&&s.setLastSelectedModel(s.providerId,y),await s.applyProviderState({providerId:g.id,provider:g.protocol,model:y,providerSettings:g}),s.updateProviderDisplay(s.getProviderDisplayName(),y);}s.logInfo("Provider updated",`${g.name} (${g.protocol})`),ii(s);}catch(r){r.message==="cancelled"?s.logInfo("Provider update cancelled"):s.logInfo("Failed to update provider",r.message);}}async function Nf(s,e){let t=s.getProviderByIdentifier(e);if(!(!t&&(t=await s.selectProviderFromList("Select provider to delete"),!t))){if(s.getProviderCount()<=1){s.logInfo("Cannot delete provider","At least one provider is required.");return}try{if(!await s.promptConfirmKeyword(`Type DELETE to remove provider "${t.name}"`,"delete")){s.logInfo("Deletion cancelled","Provider was not removed.");return}let r=t.id===s.providerId;if(s.deleteProvider(t.id),s.refreshProviderSettings(),r){let i=s.getDefaultProvider();if(!i){s.logInfo("Provider deleted",`Removed ${t.name}. Add a new provider with /provider add.`);return}let o=s.resolveModel(i.id);if(!o){s.logInfo("Provider deleted",`Removed ${t.name}. Configure models for ${i.name} via /model add.`);return}s.setLastSelectedModel(i.id,o),await s.applyProviderState({providerId:i.id,provider:i.protocol,model:o,providerSettings:i}),s.updateProviderDisplay(s.getProviderDisplayName(),o);}s.logInfo("Provider deleted",`Removed ${t.name}.`);}catch(n){n.message==="cancelled"?s.logInfo("Deletion cancelled"):s.logInfo("Failed to delete provider",n.message);}}}async function Uf(s,e){let t=s.getProviderByIdentifier(e);if(!(!t&&(t=await s.selectProviderFromList("Select provider to set as default"),!t)))try{s.setDefaultProvider(t.id),s.logInfo("Default provider updated",`${t.name} is now the default provider.`);}catch(n){s.logInfo("Failed to set default provider",n.message);}}async function Ff(s){let e=s.getProviders();if(!e||e.length===0){s.logInfo("No providers configured","Use /provider add to create one.");return}try{let t=await s.selectProviderFromList("Select provider");if(!t)return;if(t.id===s.providerId){s.logInfo("Provider",`${t.name} is already active.`);return}let n=s.resolveModel(t.id);if(!n){s.logInfo("Provider has no models",`Configure models for ${t.name} via /model add.`);return}s.setLastSelectedModel(t.id,n),s.setDefaultProvider(t.id),await s.applyProviderState({providerId:t.id,provider:t.protocol,model:n,providerSettings:t}),s.updateProviderDisplay(s.getProviderDisplayName(),n),s.logInfo("Provider updated",`${s.getProviderDisplayName()} / ${n}`);}catch(t){t.message==="cancelled"?s.logInfo("Selection cancelled"):s.logInfo("Selection failed",t.message);}}function NT(s){let e=s.getProviders();if(!e||e.length===0){s.logInfo("No provider configured","Add a provider before managing models.");return}UT(s,e);}function UT(s,e){let t=[];t.push(""),t.push(v.highlight(" Available Models")),t.push("");for(let r of e){let i=ln[r.protocol]||"OpenAI",o=r.id===s.providerId,a=o?v.success(" [current]"):"";t.push(v.primary(` \u25B8 ${r.name} (${r.id})`)+a),t.push(v.dim(` Protocol: ${i}`)),r.models.length===0?t.push(v.dim(" No models configured")):r.models.forEach((l,c)=>{let u=[];o&&l.name===s.model&&u.push("current"),l.name===r.defaultModel&&u.push("default"),t.push(` ${v.dim(`${c+1}.`)} ${l.name}${ri(u)}`);}),t.push("");}if(t.push(v.dim(" Commands:")),t.push(v.dim(" /model use [providerId] <name> switch model")),t.push(v.dim(" /model add add model")),t.push(v.dim(" /model remove <name> remove model")),t.push(v.dim(" /model default <name> set default model")),t.push(v.dim(" /model list <providerId> list provider models")),t.push(""),s.outputFn){for(let r of t)s.outputFn(r);return}let n=t.slice(1,-1);s.logInfo("Available models",n.join(`
1863
+ `));}function Bf(s,e){if(!e||e.models.length===0){s.logInfo(`No models for ${e?.name||"provider"}`,"Use /model add to register a model.");return}let t=e.defaultModel,n=ln[e.protocol]||"OpenAI",r=[];if(r.push(""),r.push(v.highlight(` Available Models - ${e.name} (${e.id})`)),r.push(v.dim(` Protocol: ${n}`)),r.push(""),e.models.forEach((o,a)=>{let l=[];e.id===s.providerId&&o.name===s.model&&l.push("current"),o.name===t&&l.push("default"),r.push(` ${v.primary(`${a+1}.`)} ${o.name}${ri(l)}`);}),r.push(""),r.push(v.dim(" Commands:")),r.push(v.dim(" /model use [providerId] <name> switch model")),r.push(v.dim(" /model add add model")),r.push(v.dim(" /model remove <name> remove model")),r.push(v.dim(" /model default <name> set default model")),r.push(v.dim(" /model list <providerId> list other provider models")),r.push(""),s.outputFn){for(let o of r)s.outputFn(o);return}let i=r.slice(1,-1);s.logInfo("Available models",i.join(`
1864
+ `));}async function jf(s,e){if(e){let t=s.getProvider(e);if(!t){s.logInfo("Provider not found",`Unknown provider "${e}".`);return}Bf(s,t);return}NT(s);}async function au(s,e){if(!s.providerSettings){s.logInfo("No provider configured","Set up a provider before selecting models.");return}if(!s.providerSettings.models.some(t=>t.name===e)){let t=s.providerSettings.models.map(n=>n.name).join(", ");s.logInfo("Invalid model",t?`Available models: ${t}`:"No models configured.");return}if(e===s.model){s.logInfo("Model unchanged",`${e} is already active.`);return}try{s.setLastSelectedModel(s.providerId,e),await s.applyProviderState({providerId:s.providerId,provider:s.provider,model:e,providerSettings:s.providerSettings}),s.updateProviderDisplay(s.getProviderDisplayName(),e),s.logInfo("Model updated",`Model set to ${e}`);}catch(t){s.logInfo("Failed to change model",t.message);}}async function Gf(s,e){if(!s.providerSettings){s.logInfo("No provider configured","Add a provider before managing models.");return}try{let t=await s.promptText("Model name",{defaultValue:e?.trim()}),n=await s.promptYesNo("Set as default model?",!1),r=await s.promptYesNo("Use this model immediately?",!0),i=s.addModel(s.providerId,t,n);s.refreshProviderSettings(),s.logInfo("Model added",`Model "${t}" added to provider ${i.name}.`),(r||n)&&await au(s,t);}catch(t){t.message==="cancelled"?s.logInfo("Model addition cancelled"):s.logInfo("Failed to add model",t.message);}}async function lu(s,e,t){let n=null,r=t;if(e){let i=s.getProvider(e);if(i)n=i;else if(!r)r=e;else {s.logInfo("Provider not found",`Unknown provider "${e}".`);return}}if(!n)if(s.getProviderCount()<=1&&s.providerSettings)n=s.providerSettings;else {let i=await s.selectProviderFromList("Select provider for model");if(!i)return;n=i;}if(r){if(!n.models.some(o=>o.name===r)){s.logInfo("Model not found",`Model "${r}" does not exist for ${n.name}.`);return}}else if(r=await s.selectModelFromProvider(n,`Select model for ${n.name}`)||void 0,!r)return;if(n.id!==s.providerId){if(!s.resolveModel(n.id)){s.logInfo("Provider has no models",`Configure models for ${n.name} via /model add.`);return}s.setLastSelectedModel(n.id,r),s.setDefaultProvider(n.id),await s.applyProviderState({providerId:n.id,provider:n.protocol,model:r,providerSettings:n}),s.updateProviderDisplay(s.getProviderDisplayName(),r),s.logInfo("Provider and model updated",`Provider: ${s.getProviderDisplayName()}
1865
+ Model: ${r}`);}else await au(s,r);Bf(s,n);}async function Wf(s,e){if(!s.providerSettings){s.logInfo("No provider configured","Add a provider before managing models.");return}let t=e?e.trim():"";if(!(!t&&(t=await s.selectModelFromCurrentProvider("Select a model to remove"),!t))){if(!s.providerSettings.models.some(n=>n.name===t)){s.logInfo("Model not found",`Model "${t}" does not exist for ${s.providerSettings.name}.`);return}try{if(!await s.promptConfirmKeyword(`Type REMOVE to delete model "${t}"`,"remove")){s.logInfo("Model removal cancelled");return}let r=s.removeModel(s.providerId,t);if(s.model===t){let o=s.resolveModel(s.providerId);if(!o){s.logInfo("Model removed",`Removed ${t}. Add another model with /model add.`);return}s.setLastSelectedModel(s.providerId,o),await s.applyProviderState({providerId:s.providerId,provider:s.provider,model:o,providerSettings:r}),s.updateProviderDisplay(s.getProviderDisplayName(),o),s.logInfo("Model removed",`Removed ${t}. Switched to ${o}.`);}else s.refreshProviderSettings(),s.logInfo("Model removed",`Removed ${t}.`);}catch(n){n.message==="cancelled"?s.logInfo("Model removal cancelled"):s.logInfo("Failed to remove model",n.message);}}}async function Hf(s,e){if(!s.providerSettings){s.logInfo("No provider configured","Add a provider before managing models.");return}let t=e?e.trim():"";if(!(!t&&(t=await s.selectModelFromCurrentProvider("Select a model to set as default"),!t))){if(!s.providerSettings.models.some(n=>n.name===t)){s.logInfo("Model not found",`Model "${t}" does not exist for ${s.providerSettings.name}.`);return}try{let n=s.updateProvider(s.providerId,{defaultModel:t});s.setLastSelectedModel(s.providerId,t),await s.applyProviderState({providerId:s.providerId,provider:s.provider,model:t,providerSettings:n}),s.updateProviderDisplay(s.getProviderDisplayName(),t),s.logInfo("Default model updated",`${t} is now default for ${n.name}.`);}catch(n){s.logInfo("Failed to set default model",n.message);}}}async function Jf(s){let e=s.getProviders();if(!e||e.length===0){s.logInfo("No provider configured","Add a provider with /provider add first.");return}try{let t;if(e.length===1)t=e[0];else {let r=await s.selectProviderFromList("Select provider");if(!r)return;t=r;}if(t.models.length===0){s.logInfo("No models",`Provider "${t.name}" has no models. Use /model add to add one.`);return}let n=await s.selectModelFromProvider(t,`Select model (${t.name})`);if(!n)return;t.id!==s.providerId?(s.setLastSelectedModel(t.id,n),s.setDefaultProvider(t.id),await s.applyProviderState({providerId:t.id,provider:t.protocol,model:n,providerSettings:t}),s.updateProviderDisplay(s.getProviderDisplayName(),n),s.logInfo("Provider and model updated",`${s.getProviderDisplayName()} / ${n}`)):await au(s,n);}catch(t){t.message==="cancelled"?s.logInfo("Selection cancelled"):s.logInfo("Selection failed",t.message);}}async function zf(s,e){let n=(e.trim().split(/\s+/)[1]||"").toLowerCase(),r=s.logInfo||((o,a)=>{b(""),b(v.info(` ${o}`)),a&&b(v.dim(` ${a}`)),b("");});if(n==="on"||n==="enable"){let o=!!s.agentLogger;o||s.initializeAgentLogger(true,false)?(oe.setEnabled(true),s.updateTracingPreference(true),r("Tracing enabled",o?"\u5DF2\u5728\u542F\u7528\u72B6\u6001":`\u65E5\u5FD7\u76EE\u5F55: ${s.getTracingLogDir()}`)):r("Failed to enable tracing","\u68C0\u67E5\u76EE\u5F55\u6743\u9650\u6216\u78C1\u76D8\u7A7A\u95F4");return}if(n==="off"||n==="disable"){await s.disableTracing(false),r("Tracing disabled","\u8FFD\u8E2A\u529F\u80FD\u5DF2\u5173\u95ED");return}if(s.promptSelect&&n!=="status"){let o=!!s.agentLogger;try{let a=await s.promptSelect("Tracing",[{label:"Off",value:"off",description:"\u5173\u95ED\u8FFD\u8E2A\u529F\u80FD"},{label:"On",value:"on",description:"\u8BB0\u5F55 LLM/\u5DE5\u5177\u8C03\u7528\u8BE6\u60C5\u7528\u4E8E\u8C03\u8BD5"}],o?"on":"off");a==="on"&&!o?s.initializeAgentLogger(!0,!1)&&(oe.setEnabled(!0),s.updateTracingPreference(!0),r("Tracing enabled",`\u65E5\u5FD7\u76EE\u5F55: ${s.getTracingLogDir()}`)):a==="off"&&o?(await s.disableTracing(!1),r("Tracing disabled","\u8FFD\u8E2A\u529F\u80FD\u5DF2\u5173\u95ED")):r("Tracing",`\u5F53\u524D\u72B6\u6001: ${o?"\u5DF2\u542F\u7528":"\u5DF2\u7981\u7528"}`);}catch(a){a.message!=="cancelled"&&r("Tracing selection failed",a.message);}return}let i=!!s.agentLogger;r("Tracing Status",`\u72B6\u6001: ${i?"\u5DF2\u542F\u7528":"\u5DF2\u7981\u7528"}
1866
+ \u65E5\u5FD7\u76EE\u5F55: ${s.getTracingLogDir()}`);}function qf(s){if(!s.agentLogger){b(""),b(v.error(" [x] Tracing is not enabled")),b(v.dim(" Run /tracing on to enable tracing")),b("");return}let e=s.agentLogger.getCurrentSession();if(!e){b(""),b(v.dim(" No active session")),b("");return}b(""),b(v.highlight(" Current Session Trace:")),b(""),b(v.dim(" Session ID: ")+v.info(e.session_id)),b(v.dim(" User Input: ")+v.info(e.user_input)),b(v.dim(" Iterations: ")+v.info(e.iterations.length.toString())),b(""),e.iterations.forEach((t,n)=>{b(j.blue(` \u250C\u2500 Iteration ${n+1}`)),t.spans.filter(r=>r.type==="thinking").forEach(r=>{"content_preview"in r&&b(v.dim(" \u2502 ")+j.magenta("\u{1F4AD} ")+r.content_preview);}),t.spans.filter(r=>r.type==="tool_call").forEach(r=>{if("tool_name"in r&&"success"in r){let i=r.success?"[*]":"[x]",o=r.success?j.cyan:j.red;b(v.dim(" \u2502 ")+o(`${i} ${r.tool_name}`));}}),t.spans.filter(r=>r.type==="response").forEach(r=>{"content_preview"in r&&b(v.dim(" \u2502 ")+j.green("\u2713 ")+r.content_preview);}),b(j.blue(" \u2514\u2500"));}),b("");}async function Kf(s){if(!s.agentLogger){b(""),b(v.error(" [x] Tracing is not enabled")),b(v.dim(" Run /tracing on to enable tracing")),b("");return}let e=te.join(ti.homedir(),".neox","traces"),t=te.join(e,`${wn()}.jsonl`);if(!an.existsSync(t)){b(""),b(v.dim(" No trace history found")),b(v.dim(` Expected: ${t}`)),b("");return}b(""),b(v.highlight(" Recent Session History:")),b("");try{let r=await new ei({showTimestamp:!0,showSessionId:!1,verbose:!1,useColors:!0}).getSessionSummaries(t);if(r.length===0){b(v.dim(" No sessions found in today's log")),b("");return}r.slice(-10).reverse().forEach((o,a)=>{let l=o.result==="success"?j.green:o.result==="error"?j.red:j.yellow,c=new Date(o.timestamp).toLocaleTimeString(),u=o.result||"unknown",d=o.total_tokens?` \u2022 ${o.total_tokens} tokens`:"",p=o.duration_ms?` \u2022 ${Math.round(o.duration_ms/1e3)}s`:"";b(v.dim(` ${a+1}. `)+j.gray(`[${c}] `)+o.user_input),b(v.dim(" ")+l(`${u}`)+j.gray(d+p)),b("");});}catch(n){b(v.error(" [x] Failed to read trace history: ")+n.message),b("");}}async function Vf(s){if(!s.agentLogger){b(""),b(v.error(" [x] Tracing is not enabled")),b(v.dim(" Run /tracing on to enable tracing")),b("");return}let e=te.join(ti.homedir(),".neox","traces"),t=te.join(e,`${wn()}.jsonl`);if(!an.existsSync(t)){b(""),b(v.dim(" No trace data found")),b(v.dim(` Expected: ${t}`)),b("");return}b(""),b(v.highlight(" Analyzing trace data...")),b("");try{let n=await Wc(t),r=Hc(n);b(r);}catch(n){b(v.error(" [x] Failed to analyze trace data: ")+n.message),b("");}}async function Yf(s){if(!s.agentLogger){b(""),b(v.error(" [x] Tracing is not enabled")),b(v.dim(" Run /tracing on to enable tracing")),b("");return}let e=te.join(ti.homedir(),".neox","traces");b(""),b(v.highlight(" Current Trace Logs:")),b("");try{let t=await Gc(e);if(t.totalFiles===0){b(v.dim(" No trace logs found")),b("");return}b(v.dim(" Total files: ")+v.info(t.totalFiles.toString())),b(v.dim(" Total size: ")+v.info(qo(t.totalSize))),t.oldestFile&&b(v.dim(" Oldest: ")+v.info(t.oldestFile)),t.newestFile&&b(v.dim(" Newest: ")+v.info(t.newestFile)),b(""),process.stdin.isTTY&&process.stdin.setRawMode(!1);let n=await kn({type:"number",name:"days",message:"Keep logs from the last N days",initial:7,min:1});if(process.stdin.isTTY&&process.stdin.setRawMode(!0),n.days){b(""),b(v.highlight(" Cleaning up old logs...")),b("");let r=await jc({logDir:e,retentionDays:n.days});r.filesDeleted===0?b(v.success(" \u2713 No old files to delete")):(b(v.success(` \u2713 Deleted ${r.filesDeleted} old log file(s)`)),b(v.dim(` Freed: ${qo(r.bytesFreed)}`)),b(v.dim(` Retained: ${r.filesRetained} file(s)`)),r.deletedFiles.length>0&&(b(""),b(v.dim(" Deleted files:")),r.deletedFiles.forEach(i=>{b(v.dim(` - ${i}`));}))),b("");}}catch(t){b(v.error(" [x] Failed to clean up logs: ")+t.message),b("");}}async function Xf(s,e){let n=(e.trim().split(/\s+/)[1]||"").toLowerCase(),r=s.logInfo||((u,d)=>{b(""),b(v.info(` ${u}`)),d&&b(v.dim(` ${d}`)),b("");}),i=s.providerSettings.protocol==="anthropic",o=s.model.includes("opus-4-5")||s.model.includes("opus-4.5")||s.model.endsWith("-thinking");if(!i){r("Extended thinking","\u4EC5\u9002\u7528\u4E8E Claude (Anthropic) \u6A21\u578B");return}let a=()=>{s.setThinkingMode("enabled"),s.llmProvider&&"setThinking"in s.llmProvider&&s.llmProvider.setThinking({type:"enabled"});let u=o?"":`
1867
+ \u26A0 \u5F53\u524D\u6A21\u578B\u53EF\u80FD\u4E0D\u5B8C\u5168\u9002\u914D`;r("Extended thinking enabled",`\u6A21\u578B: ${s.model}${u}`);},l=()=>{s.setThinkingMode("disabled"),s.llmProvider&&"setThinking"in s.llmProvider&&s.llmProvider.setThinking({type:"disabled"}),r("Extended thinking disabled",`\u6A21\u578B: ${s.model}`);};if(n==="on"||n==="enable"||n==="enabled"){a();return}if(n==="off"||n==="disable"||n==="disabled"){l();return}if(s.promptSelect&&n!=="status"){let u=s.thinkingMode==="enabled"?"on":"off";try{let d=await s.promptSelect("Extended Thinking",[{label:"Off",value:"off",description:"\u5173\u95ED\u6DF1\u5EA6\u601D\u8003"},{label:"On",value:"on",description:"\u5F00\u542F\u6DF1\u5EA6\u601D\u8003\uFF08\u9002\u7528\u4E8E\u590D\u6742\u4EFB\u52A1\uFF09"}],u);d==="on"&&s.thinkingMode!=="enabled"?a():d==="off"&&s.thinkingMode!=="disabled"?l():r("Extended Thinking",`\u5F53\u524D\u72B6\u6001: ${s.thinkingMode==="enabled"?"\u5DF2\u5F00\u542F":"\u5DF2\u5173\u95ED"}`);}catch(d){d.message!=="cancelled"&&r("Thinking selection failed",d.message);}return}let c=s.thinkingMode==="enabled"?"\u5DF2\u5F00\u542F":s.thinkingMode==="disabled"?"\u5DF2\u5173\u95ED":"\u672A\u8BBE\u7F6E";r("Extended Thinking",`\u72B6\u6001: ${c}
1868
+ \u6A21\u578B: ${s.model}`);}Sn();async function Zf(s){if(b(""),b(v.warning(" \u26A0\uFE0F This will delete your configuration file and reset all settings.")),b(v.dim(" You will need to reconfigure providers and API keys.")),b(""),!(await kn({type:"confirm",name:"value",message:"Are you sure you want to clear the configuration?",initial:false})).value){b(""),b(v.info(" Configuration clear cancelled.")),b("");return}try{an.existsSync(lt)?(an.unlinkSync(lt),b(""),b(v.success(" \u2713 Configuration file deleted successfully!")),b(v.dim(` ${lt}`)),b(""),b(v.info(" Please restart the CLI to reconfigure.")),b(""),await s.cleanup(),process.exit(0)):(b(""),b(v.info(" No configuration file found.")),b(""));}catch(t){b(""),b(v.error(" \u2717 Failed to delete configuration file.")),b(v.dim(` ${t.message}`)),b("");}}async function Qf(s,e){let t="Usage: /approval auto | manual",n=e?e.toLowerCase():"";if(!n)try{n=await s.promptSelect("\u9009\u62E9\u5BA1\u6279\u6A21\u5F0F (Approval Mode)",[{label:"auto - \u81EA\u52A8\u6267\u884C (Default)",value:"auto",description:"\u5DE5\u5177\u65E0\u9700\u786E\u8BA4\u5373\u53EF\u8FD0\u884C"},{label:"manual - \u9700\u8981\u5BA1\u6279",value:"manual",description:"\u6BCF\u6B21\u5DE5\u5177\u8FD0\u884C\u524D\u624B\u52A8\u786E\u8BA4"}],s.approvalMode,"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4");}catch(o){o?.message!=="cancelled"&&s.logInfo("\u5BA1\u6279\u6A21\u5F0F\u5207\u6362\u5931\u8D25",o?.message);return}if(n!=="auto"&&n!=="manual"){s.logInfo("\u65E0\u6548\u7684\u5BA1\u6279\u6A21\u5F0F",`${t}`);return}if(s.approvalMode===n){s.logInfo("\u5BA1\u6279\u6A21\u5F0F\u672A\u53D8\u5316",`\u4ECD\u4E3A ${n}`);return}s.setApprovalMode(n);let r={...s.userConfig,approvalMode:n};s.updateConfig(r),ct(r);let i=n==="manual"?"\u5DF2\u5207\u6362\u4E3A\u9700\u8981\u5BA1\u6279\u6A21\u5F0F\uFF1A\u6267\u884C\u5DE5\u5177\u524D\u5C06\u5F39\u51FA Yes/No\u3002":"\u5DF2\u5207\u6362\u4E3A\u81EA\u52A8\u6A21\u5F0F\uFF1A\u5DE5\u5177\u6267\u884C\u4E0D\u518D\u63D0\u793A\u5BA1\u6279\u3002";s.logInfo("\u5BA1\u6279\u6A21\u5F0F\u5DF2\u66F4\u65B0",i);}Sn();ji();async function tg(s,e){let t=fr(s.workspacePath),n=await t.getStats();if(!e)try{e=await s.promptSelect("\u4EE3\u7801\u7D22\u5F15\u7BA1\u7406",[{label:n.hasIndex?"\u{1F4CA} \u67E5\u770B\u7D22\u5F15\u72B6\u6001":"\u{1F4CA} \u7D22\u5F15\u72B6\u6001 (\u672A\u6784\u5EFA)",value:"status",description:n.hasIndex?`${n.fileCount} \u4E2A\u6587\u4EF6, ${n.symbolCount} \u4E2A\u7B26\u53F7`:"\u5C1A\u672A\u6784\u5EFA\u7D22\u5F15"},{label:"\u{1F528} \u6784\u5EFA\u7D22\u5F15",value:"build",description:"\u89E3\u6790\u9879\u76EE\u4EE3\u7801\uFF0C\u63D0\u53D6\u51FD\u6570/\u7C7B/\u63A5\u53E3\u7B49\u7B26\u53F7"},{label:"\u{1F504} \u91CD\u5EFA\u7D22\u5F15",value:"rebuild",description:"\u5F3A\u5236\u91CD\u65B0\u6784\u5EFA\u7D22\u5F15 (\u5FFD\u7565\u7F13\u5B58)"},{label:"\u{1F5D1}\uFE0F \u6E05\u9664\u7D22\u5F15",value:"clear",description:"\u5220\u9664\u6240\u6709\u7D22\u5F15\u6587\u4EF6"},{label:"\u2699\uFE0F \u914D\u7F6E\u7D22\u5F15",value:"config",description:"\u8BBE\u7F6E\u7D22\u5F15\u8BED\u8A00\u3001\u6392\u9664\u8DEF\u5F84\u7B49"}],"status","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4");}catch(r){r?.message!=="cancelled"&&s.logInfo("\u7D22\u5F15\u64CD\u4F5C\u5931\u8D25",r?.message);return}switch(e){case "status":await jT(s,t);break;case "build":await eg(s,t,false);break;case "rebuild":await eg(s,t,true);break;case "clear":await GT(s,t);break;case "config":await WT(s);break;default:s.logInfo("\u65E0\u6548\u7684\u64CD\u4F5C","\u4F7F\u7528 /index \u67E5\u770B\u53EF\u7528\u64CD\u4F5C");}}async function jT(s,e){let t=await e.getStats(),n=[];if(!t.hasIndex)n.push(v.warning("\u72B6\u6001: \u672A\u6784\u5EFA")),n.push(""),n.push(v.dim("\u8FD0\u884C /index build \u6784\u5EFA\u7D22\u5F15"));else {n.push(v.success("\u72B6\u6001: \u5DF2\u6784\u5EFA \u2713")),n.push(`\u6587\u4EF6\u6570: ${t.fileCount}`),n.push(`\u7B26\u53F7\u6570: ${t.symbolCount}`);let r=(t.size/1024).toFixed(1),i=(t.size/(1024*1024)).toFixed(2),o=t.size>1024*1024?`${i}MB`:`${r}KB`;n.push(`\u7D22\u5F15\u5927\u5C0F: ${o}`),t.lastUpdated&&n.push(`\u6700\u540E\u66F4\u65B0: ${t.lastUpdated.toLocaleString()}`);}s.logInfo("\u{1F4CA} \u4EE3\u7801\u7D22\u5F15\u72B6\u6001",n.join(`
1869
+ `));}async function eg(s,e,t){s.logInfo(t?"\u{1F504} \u6B63\u5728\u91CD\u5EFA\u7D22\u5F15...":"\u{1F528} \u6B63\u5728\u6784\u5EFA\u7D22\u5F15...");let n=Date.now(),r=await e.buildIndex({force:t,onProgress:(c,u,d)=>{}}),i=((Date.now()-n)/1e3).toFixed(2),o=[];if(o.push(`\u6587\u4EF6\u6570: ${r.filesIndexed}`),o.push(`\u7B26\u53F7\u6570: ${r.symbolsFound}`),o.push(`\u8017\u65F6: ${i}s`),r.errors.length>0){o.push(""),o.push(v.warning("\u9519\u8BEF:"));for(let c of r.errors.slice(0,3))o.push(v.dim(` ${c.file}: ${c.error}`));r.errors.length>3&&o.push(v.dim(` ... \u8FD8\u6709 ${r.errors.length-3} \u4E2A\u9519\u8BEF`));}let a=r.success?v.success("\u2713 \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210"):v.warning("\u26A0\uFE0F \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210 (\u6709\u9519\u8BEF)");s.logInfo(a,o.join(`
1870
+ `));let l={...s.userConfig,smartRead:{...s.userConfig.smartRead,enabled:true}};s.updateConfig(l),ct(l);}async function GT(s,e){if(!(await e.getStats()).hasIndex){s.logInfo("\u7D22\u5F15\u4E0D\u5B58\u5728","\u65E0\u9700\u6E05\u9664");return}try{if(await s.promptSelect("\u26A0\uFE0F \u786E\u5B9A\u8981\u6E05\u9664\u6240\u6709\u7D22\u5F15\u6587\u4EF6\u5417?",[{label:"\u53D6\u6D88",value:"no",description:"\u4FDD\u7559\u7D22\u5F15\u6587\u4EF6"},{label:"\u786E\u5B9A\u6E05\u9664",value:"yes",description:"\u5220\u9664\u6240\u6709\u7D22\u5F15\u6587\u4EF6"}],"no","\u6309 \u2191\u2193 \u9009\u62E9")!=="yes"){s.logInfo("\u64CD\u4F5C\u5DF2\u53D6\u6D88");return}await e.clear(),s.logInfo(v.success("\u2713 \u7D22\u5F15\u5DF2\u6E05\u9664"));}catch(n){n?.message!=="cancelled"&&s.logInfo("\u6E05\u9664\u5931\u8D25",n?.message);}}async function WT(s){let e=s.userConfig.smartRead||{enabled:true},t=[{label:"Web \u5F00\u53D1 (TS + JS)",value:"web",languages:["typescript","javascript"]},{label:"Full Stack (TS + JS + Python)",value:"fullstack",languages:["typescript","javascript","python"]},{label:"\u5168\u90E8\u8BED\u8A00",value:"all",languages:["typescript","javascript","python","java","go","rust"]},{label:"\u4EC5 TypeScript",value:"ts",languages:["typescript"]},{label:"\u4EC5 Python",value:"python",languages:["python"]},{label:"\u4EC5 Go",value:"go",languages:["go"]}];try{let n=await s.promptSelect("\u9009\u62E9\u8981\u7D22\u5F15\u7684\u8BED\u8A00",t.map(o=>({label:o.label,value:o.value,description:o.languages.join(", ")})),"fullstack","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4"),r=t.find(o=>o.value===n);if(!r){s.logInfo("\u914D\u7F6E\u5DF2\u53D6\u6D88");return}let i={...s.userConfig,smartRead:{...e,enabled:!0,languages:r.languages}};s.updateConfig(i),ct(i),s.logInfo(v.success("\u2713 \u914D\u7F6E\u5DF2\u4FDD\u5B58"),`\u8BED\u8A00: ${r.languages.join(", ")}
1871
+ \u8FD0\u884C /index rebuild \u4EE5\u5E94\u7528\u65B0\u914D\u7F6E`);}catch(n){n?.message!=="cancelled"&&s.logInfo("\u914D\u7F6E\u5931\u8D25",n?.message);}}Sn();function HT(s){return {compressionMode:s.context?.compressionMode??"sync",thresholdPercent:s.context?.thresholdPercent??85}}async function ng(s,e){let t=HT(s.userConfig);if(!e)try{e=await s.promptSelect("\u4E0A\u4E0B\u6587\u7BA1\u7406",[{label:"\u{1F4CA} \u67E5\u770B\u72B6\u6001",value:"status",description:`\u538B\u7F29\u6A21\u5F0F: ${t.compressionMode}, \u9608\u503C: ${t.thresholdPercent}%`},{label:"\u{1F504} \u5207\u6362\u538B\u7F29\u6A21\u5F0F",value:"mode",description:t.compressionMode==="sync"?"\u5F53\u524D: \u540C\u6B65\u88C1\u526A":"\u5F53\u524D: \u5F02\u6B65LLM\u538B\u7F29"},{label:"\u2699\uFE0F \u8BBE\u7F6E\u538B\u7F29\u9608\u503C",value:"threshold",description:`\u89E6\u53D1\u538B\u7F29\u7684 token \u4F7F\u7528\u7387 (\u5F53\u524D: ${t.thresholdPercent}%)`}],"status","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4");}catch(n){n?.message!=="cancelled"&&s.logInfo("\u64CD\u4F5C\u5931\u8D25",n?.message);return}switch(e){case "status":JT(s,t);break;case "mode":await zT(s,t);break;case "threshold":await qT(s,t);break;default:s.logInfo("\u65E0\u6548\u7684\u64CD\u4F5C","\u4F7F\u7528 /context \u67E5\u770B\u53EF\u7528\u64CD\u4F5C");}}function JT(s,e){b(""),b(v.info(" \u{1F4CA} \u4E0A\u4E0B\u6587\u7BA1\u7406\u72B6\u6001")),b(" \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");let t=e.compressionMode==="sync"?v.success("\u540C\u6B65\u88C1\u526A (FIFO)"):v.warning("\u5F02\u6B65LLM\u538B\u7F29");b(` \u538B\u7F29\u6A21\u5F0F: ${t}`),b(` \u89E6\u53D1\u9608\u503C: ${e.thresholdPercent}%`),b(""),e.compressionMode==="sync"?(b(v.dim(" \u540C\u6B65\u6A21\u5F0F\u8BF4\u660E:")),b(v.dim(" \u2022 \u4F7F\u7528 FIFO \u7B56\u7565\u5220\u9664\u6700\u65E7\u7684\u6D88\u606F")),b(v.dim(" \u2022 \u901F\u5EA6\u5FEB\uFF0C\u65E0\u989D\u5916 API \u8C03\u7528")),b(v.dim(" \u2022 \u9002\u5408\u5927\u591A\u6570\u573A\u666F"))):(b(v.dim(" \u5F02\u6B65\u6A21\u5F0F\u8BF4\u660E:")),b(v.dim(" \u2022 \u4F7F\u7528 LLM \u667A\u80FD\u538B\u7F29\u5386\u53F2\u6D88\u606F")),b(v.dim(" \u2022 \u4FDD\u7559\u66F4\u591A\u4E0A\u4E0B\u6587\u4FE1\u606F")),b(v.dim(" \u2022 \u4F1A\u4EA7\u751F\u989D\u5916\u7684 API \u8C03\u7528"))),b("");}async function zT(s,e){try{let t=await s.promptSelect("\u9009\u62E9\u538B\u7F29\u6A21\u5F0F",[{label:"\u{1F680} \u540C\u6B65\u88C1\u526A (\u63A8\u8350)",value:"sync",description:"\u5FEB\u901F FIFO \u5220\u9664\uFF0C\u65E0\u989D\u5916 API \u8C03\u7528"},{label:"\u{1F9E0} \u5F02\u6B65LLM\u538B\u7F29",value:"async",description:"\u667A\u80FD\u538B\u7F29\uFF0C\u4FDD\u7559\u66F4\u591A\u4E0A\u4E0B\u6587\uFF0C\u6709\u989D\u5916 API \u8C03\u7528"}],e.compressionMode,"\u6309 \u2191\u2193 \u9009\u62E9");if(t===e.compressionMode){b(""),b(v.dim(" \u538B\u7F29\u6A21\u5F0F\u672A\u6539\u53D8")),b("");return}let n={...s.userConfig,context:{...e,compressionMode:t}};s.updateConfig(n),ct(n),s.runner&&s.runner.setCompressionMode(t),b(""),b(v.success(` \u2713 \u538B\u7F29\u6A21\u5F0F\u5DF2\u5207\u6362\u4E3A: ${t==="sync"?"\u540C\u6B65\u88C1\u526A":"\u5F02\u6B65LLM\u538B\u7F29"}`)),b("");}catch(t){t?.message!=="cancelled"&&s.logInfo("\u5207\u6362\u5931\u8D25",t?.message);}}async function qT(s,e){try{let t=await s.promptSelect("\u9009\u62E9\u89E6\u53D1\u538B\u7F29\u7684\u9608\u503C",[{label:"70%",value:"70",description:"\u8F83\u65E9\u89E6\u53D1\uFF0C\u66F4\u79EF\u6781\u7684\u538B\u7F29"},{label:"80%",value:"80",description:"\u5E73\u8861\u9009\u62E9"},{label:"85% (\u9ED8\u8BA4)",value:"85",description:"\u63A8\u8350\u8BBE\u7F6E"},{label:"90%",value:"90",description:"\u5EF6\u8FDF\u89E6\u53D1\uFF0C\u4FDD\u7559\u66F4\u591A\u4E0A\u4E0B\u6587"}],String(e.thresholdPercent),"\u6309 \u2191\u2193 \u9009\u62E9"),n=parseInt(t,10);if(n===e.thresholdPercent){b(""),b(v.dim(" \u9608\u503C\u672A\u6539\u53D8")),b("");return}let r={...s.userConfig,context:{...e,thresholdPercent:n}};s.updateConfig(r),ct(r),b(""),b(v.success(` \u2713 \u538B\u7F29\u9608\u503C\u5DF2\u8BBE\u7F6E\u4E3A: ${n}%`)),b("");}catch(t){t?.message!=="cancelled"&&s.logInfo("\u8BBE\u7F6E\u5931\u8D25",t?.message);}}ma();f.info("CLI","Starting Neox CLI");process.env.CLI_DEBUG==="1"&&(Je.start(5e3),f.info("CLI","Health monitor started for debugging"));var nF={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)};process.env.CLI_DEBUG==="1"&&(console.log=(...s)=>{let e=s.map(t=>typeof t=="string"?t:JSON.stringify(t)).join(" ");f.debug("CONSOLE",e);},console.error=(...s)=>{let e=s.map(t=>typeof t=="string"?t:JSON.stringify(t)).join(" ");f.error("CONSOLE",e);},console.warn=(...s)=>{let e=s.map(t=>typeof t=="string"?t:JSON.stringify(t)).join(" ");f.warn("CONSOLE",e);});setInterval(()=>{performance$1.clearMarks(),performance$1.clearMeasures();},6e4);var o0=fileURLToPath(import.meta.url);dirname(o0);var oi=false,uu=false,du=class{runner=null;memory;llmProvider;workDir;model;provider;providerId;providerSettings;providerStore;sessionRequests=0;uiController=null;useModernUI=true;useInkUI=process.env.USE_ANSI!=="1";agentLogger=null;tracingEnabled=false;userConfig={};promptLock=null;promptLockResolver=null;approvalMode="auto";structuredOutput;compatProfile=null;memoryPressure;lastMemoryPressureState="unknown";autoCompactionInProgress=false;interactionMode="agent";pendingAttachments=[];tools=[];lastToolCallArgs=new Map;toolIdToName=new Map;sessionSync=null;sessionManager;sessionEnabled=true;cliArgs;runtimeHost;runtimeEventUnsubscribe=null;isTaskRunning=false;exiting=false;runtimeInputTokens=0;runtimeOutputTokens=0;streamingTokenCount=0;currentSession;thinkingMode;permissionManager;currentMode="agent";constructor(e,t,n,r){this.cliArgs=r||Kc(),this.userConfig=Xt(),this.approvalMode=this.userConfig.approvalMode||"auto",this.providerStore=new Cs(this.userConfig),this.workDir=te.resolve(t||this.cliArgs.workDir||process.cwd()),this.structuredOutput=yf(this.cliArgs.outputSchema),this.sessionManager=new Es,this.sessionEnabled=!this.cliArgs.noSession;let i=this.resolveProvider(n);this.providerSettings=i,this.providerId=i.id,this.provider=i.protocol;let o=e||this.providerStore.resolveModel(i.id);if(!o)throw new Error(`Provider "${i.name}" does not have any models configured. Use /model add to configure one.`);this.model=o,this.providerStore.setLastSelectedModel(i.id,this.model),this.refreshProviderSettings(),process.chdir(this.workDir),process.env.NEOX_WORKDIR=this.workDir;}async init(){this.approvalMode==="auto"?this.currentMode="auto":this.approvalMode==="manual"&&(this.currentMode="agent"),this.permissionManager=up(),this.tools=await go(this.workDir),this.llmProvider=this.createProvider(),this.memory=new ds(500);let e={maxIterations:0,temperature:.7,mode:this.currentMode};this.runner=new Sr({llmProvider:this.llmProvider,model:this.model,tools:this.tools,memory:this.memory,config:e,agentName:"CLI Assistant",agentDescription:"\u547D\u4EE4\u884C\u52A9\u624B\uFF0C\u53EF\u4EE5\u641C\u7D22\u6587\u4EF6\u3001\u5206\u6790\u4EE3\u7801\u3001\u8BFB\u5199\u6587\u4EF6",instructions:this.buildSystemPrompt(),plannerMode:this.isPlannerModeEnabled(),structuredOutput:this.structuredOutput,providerName:this.providerSettings?.name,contextWindow:this.compatProfile?.contextWindow,tailTokenBudget:this.compatProfile?.tailTokenBudget,maxInputTokensOverride:this.providerSettings?.maxInputTokens,toolInputGuardrails:eu,toolOutputGuardrails:tu,compressionMode:this.userConfig.context?.compressionMode??"sync",workspacePath:this.workDir,permissionManager:this.permissionManager}),this.runtimeHost=new Qo({runner:this.runner,memory:this.memory,sessionManager:this.sessionManager,sessionEnabled:this.sessionEnabled,workDir:this.workDir,model:this.model,memoryPressure:this.memoryPressure,compatProfile:this.compatProfile,agentLogger:this.agentLogger,systemPrompt:this.buildStaticSystemPrompt(),setSandboxMode:r=>ic(r),llmProvider:this.llmProvider}),this.runtimeHost.setAgentLogger(this.agentLogger),this.runtimeHost.setSandboxMode(fo()),lp((r,i,o,a)=>this.promptSelect(r,i,o,a)),this.compatProfile&&!this.memoryPressure&&this.resetMemoryPressureMonitor(),this.useModernUI||this.setupKeyboardHandling(),this.useModernUI||this.displayHeader();let t=process.env.MARKOR_TRACING==="1",n=this.userConfig.tracingEnabled===true;t||n?(this.initializeAgentLogger(true,false),!t&&n&&this.updateTracingPreference(true)):(this.tracingEnabled=false,oe.setEnabled(false));}createProvider(){if(!this.providerSettings)throw new Error("No provider configured. Use /provider add to configure one.");if(!this.model)throw new Error("No model selected for provider.");if(process.env.CLI_DEBUG==="1"&&f.debug("PROVIDER","Creating provider",{protocol:this.providerSettings.protocol,name:this.providerSettings.name,baseUrl:this.providerSettings.baseUrl,model:this.model}),this.providerSettings.protocol==="anthropic"){let e=new Yi({authToken:this.providerSettings.apiKey,baseUrl:this.providerSettings.baseUrl,defaultModel:this.model});return (this.model.includes("opus-4-5")||this.model.includes("opus-4.5")||this.model.endsWith("-thinking"))&&(this.thinkingMode="enabled",e.setThinking({type:"enabled"}),process.env.CLI_DEBUG==="1"&&f.debug("PROVIDER",`Claude thinking auto-enabled for model: ${this.model}`)),e}else {if(this.providerSettings.protocol==="doubao")return new Xi({apiKey:this.providerSettings.apiKey,baseUrl:this.providerSettings.baseUrl||"https://ark.cn-beijing.volces.com/api/v3",defaultModel:this.model});if(this.providerSettings.protocol==="gemini")return process.env.CLI_DEBUG==="1"&&f.debug("PROVIDER","Creating GeminiProvider"),new Zi(this.providerSettings.apiKey,this.providerSettings.baseUrl||"https://generativelanguage.googleapis.com");{let e=this.providerSettings.protocol==="openai-responses";return process.env.CLI_DEBUG==="1"&&f.debug("PROVIDER",`Creating OpenAIProvider (useResponsesAPI: ${e})`),new zi({apiKey:this.providerSettings.apiKey,baseUrl:this.providerSettings.baseUrl||"https://api.openai.com/v1",defaultModel:this.model,useResponsesAPI:e})}}}initializeAgentLogger(e=false,t=true){let n=e||process.env.MARKOR_TRACING==="1";if(this.tracingEnabled=n,oe.setEnabled(n),!n)return false;if(this.agentLogger)return this.tracingEnabled=true,this.runtimeHost.setAgentLogger(this.agentLogger),true;try{let r=this.getTracingLogDir(),i=new Qr({logDir:r,autoRotate:!0,bufferSize:10});return this.agentLogger=new Zr({enabled:!0,exporters:[i]}),this.tracingEnabled=!0,this.runtimeHost.setAgentLogger(this.agentLogger),t&&f.info("TRACE",`Tracing enabled: ${r}`),!0}catch(r){return f.error("TRACE","Failed to initialize AgentLogger:",r),this.tracingEnabled=false,false}}resolveProvider(e){if(e){let n=this.providerStore.getProvider(e);if(n)return n;let r=e,i=this.providerStore.getProviders().find(o=>o.protocol===r);if(i)return i}let t=this.providerStore.getDefaultProvider();if(!t)throw new Error("No LLM providers configured. Run /provider add to set up a provider.");return t}getProviderByIdentifier(e){if(e){let t=this.providerStore.getProvider(e);if(t)return t;let n=this.providerStore.getProviders().find(r=>r.protocol===e);return n||null}return this.providerSettings||null}getProviderDisplayName(){if(!this.providerSettings)return "Not configured";let e=ln[this.providerSettings.protocol]||"OpenAI";return `${this.providerSettings.name} (${e})`}isPlannerModeEnabled(){return this.provider==="openai-responses"}async promptText(e,t={}){await this.acquirePromptLock();try{return this.useModernUI&&this.uiController?await this.uiController.promptText({message:e,defaultValue:t.defaultValue,allowEmpty:t.allowEmpty,hint:t.hint})??"":await this.promptTextLegacy(e,t)}finally{this.releasePromptLock();}}async promptSelect(e,t,n,r){if(await this.acquirePromptLock(),t.length===0)throw this.releasePromptLock(),new Error("No available options");if(this.useModernUI&&this.uiController){let i=t.map(o=>({title:o.label,value:o.value,description:o.description}));try{let o=await this.uiController.promptSelect({message:e,choices:i,initialValue:n,hint:r});return this.releasePromptLock(),o??""}catch(o){throw this.releasePromptLock(),o}}try{return await this.promptSelectLegacy(e,t,n)}finally{this.releasePromptLock();}}async promptYesNo(e,t=false){return await this.promptSelect(e,[{label:"Yes",value:"yes"},{label:"No",value:"no"}],t?"yes":"no")==="yes"}async promptConfirmKeyword(e,t){return (await this.promptText(e,{allowEmpty:false})).trim().toLowerCase()===t.toLowerCase()}async handleToolApprovalRequest(e){let t=nu(e.args||{}),n=`\u5141\u8BB8\u6267\u884C ${e.name}${t}?`,r="";try{r=JSON.stringify(e.args,null,2),r.length>600&&(r=`${r.slice(0,600)} ...`);}catch{r="";}this.uiController?(this.uiController.updateStatus(`\u9700\u8981\u5BA1\u6279: ${e.name}`,"thinking"),this.uiController.addInfo(`\u5BA1\u6279\u8BF7\u6C42 \xB7 ${e.name}`,r||void 0)):(b(""),b(v.warning(`\u26A0\uFE0F \u9700\u8981\u5BA1\u6279: ${e.name}${t}`)),r&&b(v.dim(r)),b(""));try{let i=await this.promptYesNo(n,!1);return this.uiController?this.uiController.addInfo(i?`[v] \u5DF2\u6279\u51C6 ${e.name}`:`\u26D4 \u5DF2\u62D2\u7EDD ${e.name}`):b(v.info(i?`\u5DF2\u6279\u51C6 ${e.name}`:`\u5DF2\u62D2\u7EDD ${e.name}`)),i}catch(i){return i?.message!=="cancelled"&&this.logInfo("\u5BA1\u6279\u63D0\u793A\u5931\u8D25",i?.message),this.uiController?this.uiController.addInfo(`\u26D4 \u5DF2\u62D2\u7EDD ${e.name}`,"\u5BA1\u6279\u88AB\u53D6\u6D88"):b(v.warning(`\u5BA1\u6279\u5DF2\u53D6\u6D88: ${e.name}`)),false}}async promptTextLegacy(e,t){let r=(await kn({type:"text",name:"value",message:e,initial:t.defaultValue},{onCancel:()=>{throw new Error("cancelled")}})).value??"";if(!r&&!t.allowEmpty)if(t.defaultValue)r=t.defaultValue;else throw new Error("cancelled");return r}async promptSelectLegacy(e,t,n){let r=n?Math.max(0,t.findIndex(o=>o.value===n)):0,i=await kn({type:"select",name:"value",message:e,choices:t.map(o=>({title:o.label,description:o.description,value:o.value})),initial:r},{onCancel:()=>{throw new Error("cancelled")}});if(i.value===void 0)throw new Error("cancelled");return i.value}refreshProviderSettings(){if(!this.providerId)return;let e=this.providerStore.getProvider(this.providerId);e&&(this.providerSettings=e,this.rebuildCompatProfile());}getActiveModelConfig(){return this.providerSettings?.models?.find(e=>e.name===this.model)}rebuildCompatProfile(){if(!this.model||!this.providerSettings){this.compatProfile=null,this.memoryPressure=void 0,this.lastMemoryPressureState="unknown",this.updateContextWindowDisplay();return}let e=this.getActiveModelConfig();this.compatProfile=Gh(this.model,e?.compat),this.resetMemoryPressureMonitor(),this.updateContextWindowDisplay();}resetMemoryPressureMonitor(){this.compatProfile?this.memoryPressure=new mi(this.compatProfile):this.memoryPressure=void 0,this.lastMemoryPressureState="unknown";}buildDefaultContextExtras(e){return this.compatProfile?{contextWindow:this.compatProfile.contextWindow,autoCompactLimit:this.compatProfile.autoCompactLimit,tokensUsedForContext:e?.tokensUsedForContext??0,pressure:e?.pressure??0,warningLevel:e?.warningLevel??"normal"}:e}updateContextWindowDisplay(){if(!this.uiController)return;let e=this.buildDefaultContextExtras();if(!e)return;let t=this.uiController.getTokenStats();this.uiController.setTokenStats(t.inputTokens,t.outputTokens,{...e,tokensUsedForContext:e.tokensUsedForContext??t.tokensUsedForContext??0,pressure:e.pressure??t.pressure??0,warningLevel:e.warningLevel??t.warningLevel??"normal"});}pushTokenStats(e,t,n,r){if(this.uiController){let i=this.uiController.getTokenStats(),o=n?{contextWindow:n.profile.contextWindow,autoCompactLimit:n.profile.autoCompactLimit,pressure:n.pressure,warningLevel:n.state,tokensUsedForContext:n.tokensUsed,messageCount:n.messageCount}:this.buildDefaultContextExtras({tokensUsedForContext:i.tokensUsedForContext??0,pressure:i.pressure??0,warningLevel:i.warningLevel??"normal",messageCount:i.messageCount}),a={...o,...r&&{cachedTokens:r.cachedTokens,openaiCachedTokens:r.openaiCachedTokens,anthropicCacheReadTokens:r.anthropicCacheReadTokens,anthropicCacheCreationTokens:r.anthropicCacheCreationTokens}};process.env.CLI_DEBUG&&(f.debug("MAIN","pushTokenStats calling setTokenStats:"),f.debug("MAIN",` inputTokens=${e}, outputTokens=${t}`),f.debug("MAIN",` extras.tokensUsedForContext=${o?.tokensUsedForContext}, extras.contextWindow=${o?.contextWindow}`),f.debug("MAIN",` hasSnapshot=${!!n}, hasCacheStats=${!!r}`)),this.uiController.setTokenStats(e,t,a);}}async acquirePromptLock(){for(;this.promptLock;)await this.promptLock;this.promptLock=new Promise(e=>{this.promptLockResolver=e;});}releasePromptLock(){this.promptLockResolver&&this.promptLockResolver(),this.promptLock=null,this.promptLockResolver=null;}async selectProviderFromList(e){let t=this.providerStore.getProviders();if(t.length===0)return this.logInfo("No providers configured","Use /provider add to create one."),null;let n=await this.promptSelect(e,t.map(r=>({label:`${r.name} (${ln[r.protocol]||"OpenAI"})`,value:r.id,description:r.models.length>0?r.models.map(i=>i.name).join(", "):"No models configured"})),this.providerId);return this.providerStore.getProvider(n)||null}async selectModelFromProvider(e,t){if(!e||e.models.length===0)return this.logInfo("No models configured",`Use /model add to register a model for ${e?.name||"provider"}.`),null;let n=(e.id===this.providerId?this.model:null)||e.lastSelectedModel||e.defaultModel||e.models[0].name;return this.promptSelect(t,e.models.map(r=>({label:e.id===this.providerId&&r.name===this.model?`${r.name} (current)`:r.name,value:r.name})),n)}async selectModelFromCurrentProvider(e){return this.providerSettings?this.selectModelFromProvider(this.providerSettings,e):(this.logInfo("No provider configured","Add a provider before managing models."),null)}getCompletionContext(){return {providerStore:this.providerStore,providerSettings:this.providerSettings}}getCompletionSuggestions(e){return df(this.getCompletionContext(),e)}getTracingLogDir(){return te.join(ti.homedir(),".neox","traces")}updateTracingPreference(e){this.userConfig={...this.userConfig,tracingEnabled:e},ct(this.userConfig);}async disableTracing(e=true){if(!this.agentLogger){this.tracingEnabled=false,oe.setEnabled(false),this.updateTracingPreference(false),this.runtimeHost.setAgentLogger(null),e&&(b(""),b(v.dim(" Tracing is already disabled.")),b(""));return}try{await this.agentLogger.close(),this.agentLogger=null,this.tracingEnabled=!1,oe.setEnabled(!1),this.updateTracingPreference(!1),this.runtimeHost.setAgentLogger(null),e&&(b(""),b(v.success(" \u2713 Tracing disabled")),b(v.dim(" Logs will no longer be recorded.")),b(""));}catch(t){b(v.error(" [x] Failed to disable tracing: ")+t.message),b("");}}async initializeSession(){if(this.sessionEnabled)try{let e;if(this.cliArgs.continue){let n=await this.sessionManager.getMostRecent();n?(e=n,b(v.dim(` \u21AA Continuing session: ${e.sessionId}`))):(e=await this.sessionManager.createSession({model:this.model}),b(v.dim(` \u2726 New session: ${e.sessionId}`)));}else if(this.cliArgs.resume)if(typeof this.cliArgs.resume=="string"){let n=await this.sessionManager.getSession(this.cliArgs.resume);n?(e=n,b(v.dim(` \u21AA Resuming session: ${e.sessionId}`))):(b(v.error(` [x] Session not found: ${this.cliArgs.resume}`)),e=await this.sessionManager.createSession({model:this.model}));}else {let n=await this.showSessionSelector();n?e=n:(e=await this.sessionManager.createSession({model:this.model}),b(v.dim(` \u2726 New session: ${e.sessionId}`)));}else e=await this.sessionManager.createSession({model:this.model});let t=await this.activateSession(e,{loadHistory:!!(this.cliArgs.continue||this.cliArgs.resume)});if(t>0)b(v.dim(` \u21B3 Loaded ${t} messages from history`));else {let n=await this.runtimeHost.createCheckpoint("session_start");b(v.dim(` \u2713 Checkpoint created: ${n}`));}}catch(e){b(v.warning(` \u26A0 Session initialization failed: ${e.message}`)),this.sessionEnabled=false;}}async showSessionSelector(){let e=await this.sessionManager.listSessions();if(e.length===0)return b(v.dim(" No sessions found")),null;b(""),b(v.highlight(" Select Session:")),b("");let t=e.slice(0,10).map((i,o)=>({title:`${i.sessionId} (${i.itemCount} items, ${ta(i.updatedAt)})`,value:i.sessionId}));t.push({title:"Create new session",value:"new"});let n=await kn({type:"select",name:"session",message:"Session",choices:t});if(!n.session||n.session==="new")return null;let r=await this.sessionManager.getSession(n.session);return r&&b(v.dim(` \u21AA Selected: ${r.sessionId}`)),r}async activateSession(e,t){return this.sessionSync=new Is({session:e,memory:this.memory,systemPrompt:this.buildStaticSystemPrompt()}),this.currentSession=e,this.runtimeHost.setSession(e,this.sessionSync),this.memory.clear(),t?.loadHistory===false?(this.memory.add({role:"system",content:this.buildStaticSystemPrompt()}),0):await this.sessionSync.loadHistory()}setupKeyboardHandling(){process.stdin.isTTY&&(zo.emitKeypressEvents(process.stdin),process.stdin.setRawMode(true),process.stdin.on("keypress",(e,t)=>{t.name==="escape"&&oi&&(console.log(j.magenta(`
1872
+
1873
+ \u26A0\uFE0F Session interrupted (ESC)`)),uu=true,this.runtimeHost.interrupt()),t.ctrl&&t.name==="c"&&(console.log(v.info(`
1874
+
1875
+ \u{1F44B} Goodbye!`)),this.exitWithCleanup({skipProcessCheck:true,exitCode:0,reason:"keypress"}));}));}async cleanup(e=false){if(process.env.CLI_DEBUG==="1"&&process.stderr.write(`
1876
+ [DEBUG] NeoxCLI.cleanup() called, skipProcessCheck=${e}
1877
+ `),process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] Stopping health monitor
1878
+ `),Je.stop(),this.uiController&&(process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] Calling uiController.stop()
1879
+ `),this.uiController.stop(),process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] uiController.stop() returned
1880
+ `)),process.stdin.isTTY&&!this.useModernUI&&process.stdin.setRawMode(false),this.agentLogger&&await this.disableTracing(false),!e){let t=Ee.getBackgroundRunning();if(t.length>0){console.log(),console.log(v.warning(` \u26A0\uFE0F \u6709 ${t.length} \u4E2A\u540E\u53F0\u8FDB\u7A0B\u6B63\u5728\u8FD0\u884C:`)),console.log(),t.forEach(r=>{console.log(v.dim(` PID ${r.pid}: ${r.command.substring(0,50)}${r.command.length>50?"...":""}`));}),console.log();let{action:n}=await kn({type:"select",name:"action",message:"\u5982\u4F55\u5904\u7406\u8FD9\u4E9B\u540E\u53F0\u8FDB\u7A0B?",choices:[{title:"\u7EC8\u6B62\u6240\u6709\u540E\u53F0\u8FDB\u7A0B\u5E76\u9000\u51FA",value:"kill"},{title:"\u4FDD\u6301\u8FD0\u884C\u5E76\u9000\u51FA (\u8FDB\u7A0B\u5C06\u7EE7\u7EED\u5728\u540E\u53F0\u8FD0\u884C)",value:"keep"},{title:"\u53D6\u6D88\u9000\u51FA",value:"cancel"}]});if(n==="cancel")throw process.stdin.isTTY&&!this.useModernUI&&process.stdin.setRawMode(true),new Error("exit_cancelled");if(n==="kill"){console.log(),console.log(v.info(" \u6B63\u5728\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B..."));let r=Ee.killAll(true);console.log(v.success(` \u2713 \u5DF2\u7EC8\u6B62 ${r.killed} \u4E2A\u8FDB\u7A0B`)),r.failed>0&&console.log(v.warning(` \u26A0 ${r.failed} \u4E2A\u8FDB\u7A0B\u7EC8\u6B62\u5931\u8D25`));}}}}async exitWithCleanup(e){if(this.exiting)return;this.exiting=true;let t=2e3,n=null,r=new Promise(i=>{n=setTimeout(i,t);});try{await Promise.race([this.cleanup(e.skipProcessCheck),r]);}catch(i){process.env.CLI_DEBUG==="1"&&process.stderr.write(`[DEBUG] exitWithCleanup failed (${e.reason}): ${i?.message}
1881
+ `);}finally{n&&clearTimeout(n),process.exit(e.exitCode);}}buildSystemPrompt(){return (e,t)=>{let n=e.task;return Yd({task:n,workDir:this.workDir,language:"zh",iteration:e.iteration,planMode:this.isPlannerModeEnabled()}).prompt}}buildStaticSystemPrompt(){return Xd({workDir:this.workDir})}displayHeader(){console.clear(),console.log(),console.log(v.highlight("\u256D\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\u256E")),console.log(v.highlight("\u2502")+" "+v.highlight("Neox AI Code Assistant")+" "+v.dim(`v${Ps}`)+" "+v.highlight("\u2502")),console.log(v.highlight("\u2570\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\u256F")),console.log();let e=this.workDir.replace(process.env.HOME||"","~");console.log(v.dim(" Provider: ")+v.info(this.getProviderDisplayName())),console.log(v.dim(" Model: ")+v.info(this.model)),console.log(v.dim(" Dir: ")+v.info(e)),console.log(v.dim(" Tools: ")+v.info(this.tools.length.toString())),console.log(),console.log(v.dim(" Type ")+v.highlight("/help")+v.dim(" for commands \u2502 ")+v.highlight("ESC")+v.dim(" to interrupt \u2502 ")+v.error("Ctrl+C")+v.dim(" to exit")),console.log(),console.log(v.dim("\u2500".repeat(50)));}async runModernUI(){process.env.CLI_DEBUG&&(f.info("CLI","=== runModernUI() starting ==="),Je.logStdinState("runModernUI.start"));let e=this.workDir.replace(process.env.HOME||"","~");return await this.initializeSession(),this.useInkUI?(f.info("CLI","Using Ink UI"),this.uiController=new Vr({version:Ps,provider:this.getProviderDisplayName(),model:this.model,workDir:e,commandHints:si,getCompletions:t=>this.getCompletionSuggestions(t),memory:this.memory})):(f.info("CLI","Using ANSI UI"),this.uiController=new Fr({version:Ps,provider:this.getProviderDisplayName(),model:this.model,workDir:e,commandHints:si,getCompletions:t=>this.getCompletionSuggestions(t)})),process.env.CLI_DEBUG&&(f.debug("CLI","UIController created, starting UI..."),Je.logStdinState("runModernUI.beforeStart")),this.uiController.start({onSubmit:async(t,n)=>{let r=n?.map(i=>({path:`data:${i.mediaType};base64,${i.data}`,name:"image"}));await this.handleUserInput(t,r);},onExit:()=>{process.env.CLI_DEBUG==="1"&&process.stderr.write(`
1882
+ [DEBUG] onExit callback invoked
1883
+ `),this.exitWithCleanup({skipProcessCheck:true,exitCode:0,reason:"ui-exit"});},onInterrupt:()=>{this.isTaskRunning=false,this.runtimeHost.interrupt(),this.uiController&&(this.uiController.stopTaskTimer(),this.uiController.resetStreamingState(),this.uiController.updateStatus("Ready","complete"),this.uiController.flushRenderScheduler(),this.uiController.addInfo(j.red("\u26A0\uFE0F Task interrupted by user"))),process.env.CLI_DEBUG==="1"&&f.debug("INTERRUPT","Task interrupted, isTaskRunning set to false"),Je.stop();},isTaskRunning:()=>this.isTaskRunning,onToggleThinking:t=>{this.thinkingMode=t?"enabled":"disabled";let n=this.llmProvider;n?.setThinking&&n.setThinking({type:this.thinkingMode}),process.env.CLI_DEBUG==="1"&&console.log(`[THINKING] Toggled to: ${this.thinkingMode}`);}}),this.updateContextWindowDisplay(),this.attachRuntimeHostEvents(),process.env.CLI_DEBUG&&(f.info("CLI","=== runModernUI() UI started, entering event loop ==="),Je.logStdinState("runModernUI.afterStart")),new Promise(()=>{})}getRuntimeEventContext(){return {uiController:this.uiController,lastToolCallArgs:this.lastToolCallArgs,toolIdToName:this.toolIdToName,pushTokenStats:(e,t,n,r)=>this.pushTokenStats(e,t,n,r),getRuntimeTokens:()=>({input:this.runtimeInputTokens,output:this.runtimeOutputTokens}),setRuntimeTokens:(e,t)=>{this.runtimeInputTokens=e,this.runtimeOutputTokens=t;},getStreamingTokenCount:()=>this.streamingTokenCount,setStreamingTokenCount:e=>{this.streamingTokenCount=e;}}}attachRuntimeHostEvents(){process.env.CLI_DEBUG==="1"&&f.debug("EVENTS",`attachRuntimeHostEvents() called, uiController=${!!this.uiController}`),this.runtimeEventUnsubscribe&&(this.runtimeEventUnsubscribe(),this.runtimeEventUnsubscribe=null);let e=ff(this.getRuntimeEventContext());this.runtimeEventUnsubscribe=this.runtimeHost.on(e),process.env.CLI_DEBUG==="1"&&f.debug("EVENTS","Event handler subscribed successfully");}async handleUserInput(e,t){process.env.CLI_DEBUG==="1"&&(f.debug("INPUT","========================================"),f.debug("INPUT","=== handleUserInput ENTRY ==="),f.debug("INPUT",` rawInput: "${e?.substring(0,50)}..."`),f.debug("INPUT",` uiController exists: ${!!this.uiController}`),f.debug("INPUT",` isTaskRunning: ${this.isTaskRunning}`),f.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),f.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),f.debug("INPUT",` stdin.readable: ${process.stdin.readable}`),Je.logStdinState("handleUserInput.entry")),this.isTaskRunning&&(process.env.CLI_DEBUG&&f.debug("INPUT"," \u26A0\uFE0F Task already running, interrupting..."),this.runtimeHost.interrupt(),await new Promise(a=>setTimeout(a,100)));let n=e?e.trim():"";if(n=n.replace(/\[image:[^\]]+\]/g,"").trim(),!n&&t&&t.length>0&&(n="\u8BF7\u5206\u6790\u8FD9\u5F20\u56FE\u7247"),!n&&(!t||t.length===0)){process.env.CLI_DEBUG==="1"&&f.debug("INPUT","Empty input received, ignoring");return}if(n.startsWith("/")){await this.handleCommand(n);return}if(!this.uiController)return;this.sessionRequests++,this.uiController.resetStreamingState(),this.runtimeInputTokens=0,this.runtimeOutputTokens=0,this.streamingTokenCount=0,this.uiController.startTaskTimer();let r=this.pendingAttachments.length?[...this.pendingAttachments]:[];if(r.length>0&&(this.pendingAttachments=[]),t&&t.length>0){for(let a of t)try{let l=an.readFileSync(a.path),c=te.extname(a.path).toLowerCase(),d=`data:${ea[c]||"image/png"};base64,${l.toString("base64")}`;r.push({type:"image",data:d,path:a.path,name:a.name});}catch(l){this.uiController.addInfo(`[x] Failed to read image: ${a.name}`,l?.message);}r.some(a=>a.type==="image")&&this.uiController.addInfo(`[i] ${t.length} image(s) attached`);}let i=r.length>0||this.interactionMode!=="agent"?{mode:this.interactionMode,attachments:r.length>0?r:void 0}:void 0;process.env.CLI_DEBUG==="1"&&(f.debug("INPUT","=== handleUserInput calling runTask ==="),Je.logStdinState("handleUserInput.beforeRunTask"));let o=t?.map(a=>({data:"",mediaType:"image/png",path:a.path,name:a.name}));process.env.CLI_DEBUG==="1"&&f.debug("MAIN","Calling addUserMessage",{userInput:n}),this.uiController.addUserMessage(n,o),this.isTaskRunning=true;try{await this.runtimeHost.runTask(n,i?{metadata:i}:void 0),process.env.CLI_DEBUG==="1"&&(f.debug("INPUT","=== handleUserInput runTask completed successfully ==="),Je.logStdinState("handleUserInput.afterRunTask.success"));}catch(a){let l=a?.message||String(a)||"Unknown error";f.error("Agent","Task execution failed",{error:l,stack:a?.stack,userInput:n.substring(0,200)}),process.env.CLI_DEBUG==="1"&&Je.logStdinState("handleUserInput.afterRunTask.error"),this.uiController.updateStatus(`Error: ${l}`,"error"),this.uiController.addInfo(`Error: ${l}`);}finally{this.isTaskRunning=false,process.env.CLI_DEBUG==="1"&&(f.debug("INPUT","=== handleUserInput finally block ==="),f.debug("INPUT",` stdin.isPaused: ${process.stdin.isPaused?.()}`),f.debug("INPUT",` stdin.destroyed: ${process.stdin.destroyed}`),Je.logStdinState("handleUserInput.finally")),this.memory&&process.env.INK_MEM==="1"&&this.memory.logMemoryStats(),this.uiController.stopTaskTimer(),setImmediate(()=>{if(this.uiController&&!this.exiting&&process.stdin.isTTY&&!process.stdin.destroyed)try{process.stdin.isPaused?.()&&process.stdin.resume(),process.stdin.isRaw||process.stdin.setRawMode(!0);}catch(a){process.env.CLI_DEBUG==="1"&&f.warn("INPUT","Failed to restore stdin after task",{error:a});}}),process.env.CLI_DEBUG==="1"&&f.debug("INPUT","=== handleUserInput END - input should be available now ===");}}async runInteractive(){if(this.useModernUI)return this.runModernUI();for(;;)try{uu=!1,console.log(),process.stdin.isTTY&&process.stdin.setRawMode(!1);let e=await kn({type:"text",name:"input",message:v.primary("\u25CF")},{onCancel:()=>{this.cleanup().then(()=>{console.log(v.info(`
1884
+
1885
+ \u{1F44B} Goodbye! Neox Owner`)),process.exit(0);});}});process.stdin.isTTY&&process.stdin.setRawMode(!0);let n=(e.input??"").trim();if(!n)continue;if(n.startsWith("/")){await this.handleCommand(n);continue}console.log(),console.log(j.dim("\u2500".repeat(50))),console.log(),this.sessionRequests++,oi=!0;let r=new yo({isDarkBackground:Mt});r.start(),r.updateStatus("Starting...","thinking");let i=Date.now(),o=this.interactionMode!=="agent"?{metadata:{mode:this.interactionMode}}:void 0,a=this.runtimeHost.on(l=>{switch(l.type){case "thinking":r.updateStatus(`Thinking... (iteration ${l.iteration})`,"thinking");break;case "status":l.status==="error"&&r.updateStatus(l.message,"error");break;case "context_compaction":{let c=(l.originalTokens/1e3).toFixed(1),u=(l.finalTokens/1e3).toFixed(1),d=((l.originalTokens-l.finalTokens)/1e3).toFixed(1),p=l.useLLM?"LLM\u538B\u7F29":"\u667A\u80FD\u88C1\u526A";r.updateStatus(`Context ${p}: ${c}K \u2192 ${u}K (\u8282\u7701${d}K)`,"info");break}case "tool_call_start":{let c=nu(l.args||{});r.updateStatus(`Calling: ${l.name}${c}`,"tool_call"),r.addToolCall({name:l.name,args:l.args||{},timestamp:new Date});let u=l.args||{};l.name==="readfile"&&(u.path||u.file_path)?r.addFileOperation({type:"read",path:u.path||u.file_path,lines:u.num_lines}):l.name==="write_file"&&u.file_path?r.addFileOperation({type:"write",path:u.file_path,size:u.content?.length}):(l.name==="search_files"||l.name==="search")&&r.addFileOperation({type:"search",path:u.pattern||u.query||u.directory||"files"});break}case "tool_call_end":{let c=l.resultLength??(l.output?l.output.length:0),u=c>1e3?`${Math.round(c/1e3)}KB`:`${c}B`;r.updateStatus(`${l.name} \u2192 ${u}`,"tool_result"),r.updateToolResult(l.name,u,l.duration||0),l.success===!1&&r.updateToolError(l.name,l.output||"Tool failed");break}case "error":r.updateStatus(`Error: ${l.message}`,"error");break}});try{let l=await this.runtimeHost.runTask(n,o),c=Date.now()-i;if(r.updateStatus("Complete!","complete"),setTimeout(()=>{r.displaySummary(l.iterations,l.toolCalls,l.totalTokens,c);},500),uu||l.interrupted){r.stop(),console.log(),console.log(j.magenta("\u26A0\uFE0F Task interrupted by user")),console.log();continue}console.log(),console.log(v.text(l.output)),console.log();}catch(l){throw r.stop(),l}finally{a(),oi=!1;}}catch(e){if(oi=false,e.message==="canceled"||e.name==="AbortError"){console.log(),console.log(j.magenta("\u26A0\uFE0F Request cancelled")),console.log();continue}f.error("Agent","Interactive mode error",{error:e.message,stack:e.stack}),console.log();let t=e.message;t.toLowerCase().includes("timeout")?(console.log(j.red(" [x] Request timeout")),console.log(j.dim(" The API took too long to respond"))):t.toLowerCase().includes("network")?(console.log(j.red(" [x] Network error")),console.log(j.dim(" Failed to connect to API server"))):console.log(j.red(` [x] Error: ${t}`)),console.log();}}async handleCommand(e){let t=e.trim();if(!t)return;let n=t.toLowerCase();if(n.startsWith("/tracing")){await zf(this.getTracingCommandContext(),t);return}if(n.startsWith("/thinking")){await Xf(this.getThinkingCommandContext(),t);return}let[r,...i]=t.split(/\s+/);switch(r.toLowerCase()){case "/exit":case "/quit":console.log(v.info(`
1886
+ \u{1F44B} Goodbye!`)),this.exitWithCleanup({skipProcessCheck:false,exitCode:0,reason:"command"});break;case "/help":if(this.uiController)try{switch(await this.uiController.promptSelect({message:"Select action",choices:xf(),initialValue:"model"})){case "provider":await this.handleCommand("/provider");break;case "model":await this.handleCommand("/model");break;case "session":await this.handleCommand("/sessions");break;case "mode":await this.handleCommand("/mode");break;case "sandbox":await this.handleCommand("/sandbox");break;case "tracing":await this.handleCommand("/tracing");break;case "thinking":await this.handleCommand("/thinking");break;case "approval":await this.handleCommand("/approval");break;case "index":await this.handleCommand("/index");break;case "help-text":let l=[];sa(!!this.agentLogger,c=>{l.push(c);}),this.logInfo("Neox CLI Help",l.join(`
1887
+ `));break}}catch(a){if(a.message!=="cancelled"){let l=[];sa(!!this.agentLogger,c=>l.push(c)),this.logInfo("Neox CLI Help",l.join(`
1888
+ `));}}else sa(!!this.agentLogger);break;case "/schema-example":await bf(this.workDir,i[0]);break;case "/mode":{let a=(i[0]||"").toLowerCase();if(a&&a!=="status"){if(a!=="agent"&&a!=="ask"){this.logInfo("\u65E0\u6548\u7684\u6A21\u5F0F","\u53EF\u7528\u6A21\u5F0F: agent, ask");break}if(this.interactionMode===a){this.logInfo("\u6A21\u5F0F\u672A\u53D8\u5316",`\u4ECD\u4E3A ${a}`);break}this.interactionMode=a,this.logInfo("\u4EA4\u4E92\u6A21\u5F0F\u5DF2\u66F4\u65B0",a==="ask"?"\u5C06\u4EE5\u66F4\u5BF9\u8BDD\u7684\u65B9\u5F0F\u56DE\u7B54\uFF0C\u5E76\u51CF\u5C11\u5DE5\u5177\u8C03\u7528\u3002":"\u6062\u590D\u9ED8\u8BA4\u7684 Agent \u6A21\u5F0F\uFF0C\u53EF\u81EA\u52A8\u8C03\u7528\u5DE5\u5177\u3002");break}try{let l=await this.promptSelect("Select mode",[{label:"Agent",value:"agent",description:"\u667A\u80FD\u4F53\u81EA\u52A8\u4F7F\u7528\u5DE5\u5177\uFF0C\u9002\u5408\u4EE3\u7801\u4EFB\u52A1"},{label:"Ask",value:"ask",description:"\u4EC5\u56DE\u7B54\u95EE\u9898\uFF0C\u5C3D\u91CF\u907F\u514D\u5DE5\u5177\u8C03\u7528"}],this.interactionMode);this.interactionMode!==l?(this.interactionMode=l,this.logInfo("\u4EA4\u4E92\u6A21\u5F0F\u5DF2\u66F4\u65B0",l==="ask"?"\u5C06\u4EE5\u66F4\u5BF9\u8BDD\u7684\u65B9\u5F0F\u56DE\u7B54\uFF0C\u5E76\u51CF\u5C11\u5DE5\u5177\u8C03\u7528\u3002":"\u6062\u590D\u9ED8\u8BA4\u7684 Agent \u6A21\u5F0F\uFF0C\u53EF\u81EA\u52A8\u8C03\u7528\u5DE5\u5177\u3002")):this.logInfo("\u6A21\u5F0F",`\u5F53\u524D\u6A21\u5F0F: ${l}`);}catch(l){l.message!=="cancelled"&&this.logInfo("Mode selection failed",l.message);}break}case "/attach":{if(!i.length){this.logInfo("\u7528\u6CD5","/attach <\u56FE\u7247\u8DEF\u5F84\u6216 URL>");break}if(i[0].toLowerCase()==="clear"){this.clearPendingAttachments();break}await this.addPendingAttachment(i.join(" "));break}case "/attachments":{if(!i.length||i[0].toLowerCase()==="list"){this.listPendingAttachments();break}if(i[0].toLowerCase()==="clear"){this.clearPendingAttachments();break}if(i[0].toLowerCase()==="remove"){let a=parseInt(i[1],10);if(isNaN(a)||a<1){this.logInfo("\u7528\u6CD5","/attachments remove <\u7F16\u53F7>");break}this.removePendingAttachment(a-1);break}this.logInfo("\u7528\u6CD5","/attachments [list|clear|remove <\u7F16\u53F7>]");break}case "/approval":await Qf(this.getConfigCommandContext(),i[0]);break;case "/provider":{let a=(i[0]||"").toLowerCase(),l=this.getProviderCommandContext();switch(a){case "":await Ff(l);break;case "list":ii(l);break;case "add":await Df(l);break;case "edit":case "update":await $f(l,i[1]);break;case "remove":case "delete":await Nf(l,i[1]);break;case "use":await ou(l,i[1]);break;case "default":await Uf(l,i[1]);break;default:await ou(l,a);break}break}case "/sandbox":{let a=(i[0]||"").toLowerCase(),l=fo();if(a==="on"||a==="enable"){this.runtimeHost.setSandboxMode(true),this.logInfo("Sandbox enabled","\u6C99\u7BB1\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u4EC5\u5141\u8BB8\u5B89\u5168\u547D\u4EE4");break}if(a==="off"||a==="disable"){this.runtimeHost.setSandboxMode(false),this.logInfo("Sandbox disabled","\u5168\u529F\u80FD\u6A21\u5F0F\uFF0C\u6240\u6709\u547D\u4EE4\u53EF\u6267\u884C");break}try{let u=await this.promptSelect("Sandbox mode",[{label:"Off (Full mode)",value:"off",description:"\u6240\u6709 shell \u547D\u4EE4\u90FD\u53EF\u4EE5\u6267\u884C"},{label:"On (Restricted)",value:"on",description:"\u4EC5\u5141\u8BB8 ls, pwd, cat, grep \u7B49\u5B89\u5168\u547D\u4EE4"}],l?"on":"off")==="on";u!==l?(this.runtimeHost.setSandboxMode(u),this.logInfo(u?"Sandbox enabled":"Sandbox disabled",u?"\u6C99\u7BB1\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u4EC5\u5141\u8BB8\u5B89\u5168\u547D\u4EE4":"\u5168\u529F\u80FD\u6A21\u5F0F\uFF0C\u6240\u6709\u547D\u4EE4\u53EF\u6267\u884C")):this.logInfo("Sandbox",`\u5F53\u524D\u72B6\u6001: ${u?"\u5DF2\u542F\u7528":"\u5DF2\u7981\u7528"}`);}catch(c){c.message!=="cancelled"&&this.logInfo("Sandbox selection failed",c.message);}break}case "/model":{let a=(i[0]||"").toLowerCase(),l=i.slice(1),c=this.getProviderCommandContext();switch(a){case "":await Jf(c);break;case "list":await jf(c,l[0]);break;case "add":await Gf(c,l[0]);break;case "remove":case "delete":await Wf(c,l[0]);break;case "default":await Hf(c,l[0]);break;case "use":await lu(c,l[0],l[1]);break;default:await lu(c,void 0,a);break}break}case "/clear":this.memory.clear(),this.logInfo("Conversation history cleared","\u5BF9\u8BDD\u5386\u53F2\u5DF2\u6E05\u7A7A");break;case "/config-clear":case "/config-reset":await Zf(this.getConfigCommandContext());break;case "/index":case "/index-build":case "/index-status":await tg(this.getIndexCommandContext(),i[0]);break;case "/context":await ng(this.getContextCommandContext(),i[0]);break;case "/stats":{let a=this.workDir.replace(process.env.HOME||"","~"),l=await this.runtimeHost.getSessionInfo().catch(()=>null),c=["",v.highlight(" Statistics:"),"",v.dim(" Directory: ")+v.info(a),v.dim(" Provider: ")+v.info(this.getProviderDisplayName()),v.dim(" Model: ")+v.info(this.model),v.dim(" Messages: ")+v.info(this.memory.length.toString()),v.dim(" Tools: ")+v.info(this.tools.length.toString()),v.dim(" Requests: ")+v.info(this.sessionRequests.toString())];if(l&&(c.push(v.dim(" Session: ")+v.info(l.sessionId)),c.push(v.dim(" Turns: ")+v.info(l.turnCount.toString()))),c.push(""),this.uiController)for(let u of c)this.uiController.printCommandOutput(u);else for(let u of c)b(u);break}case "/sessions":await ru(this.getCommandContext());break;case "/session":i[0]?await _f(this.getCommandContext(),i[0]):await ru(this.getCommandContext());break;case "/session-new":await Tf(this.getCommandContext(),this.model);break;case "/session-info":await wf(this.getCommandContext());break;case "/undo":await kf(this.getCommandContext(),i[0]);break;case "/checkpoint":await Cf(this.getCommandContext(),i.join(" "));break;case "/checkpoints":await Ef(this.getCommandContext());break;case "/rollback":await If(this.getCommandContext(),i[0]);break;case "/session-clear":await Rf(this.getCommandContext());break;case "/session-export":await Pf(this.getCommandContext(),i[0]);break;case "/compact":this.autoCompactionInProgress=await Af(this.getCommandContext(),oi);break;case "/processes":case "/ps":await Mf(i[0]);break;case "/kill":await Lf(i[0]);break;case "/trace":qf(this.getTracingCommandContext());break;case "/trace-history":await Kf(this.getTracingCommandContext());break;case "/trace-stats":await Vf(this.getTracingCommandContext());break;case "/trace-clean":await Yf(this.getTracingCommandContext());break;default:b(""),b(v.error(` [x] Unknown command: ${r}`)),b(v.dim(" Type /help for available commands"));}}async rebuildAgentAndRunner(){if(!this.providerSettings)throw new Error("No provider configured.");this.llmProvider=this.createProvider(),this.memory=new ds(500),this.tools=await go(this.workDir);let e={maxIterations:0,temperature:.7};if(this.runner=new Sr({llmProvider:this.llmProvider,model:this.model,tools:this.tools,memory:this.memory,config:e,agentName:"CLI Assistant",agentDescription:"\u547D\u4EE4\u884C\u52A9\u624B\uFF0C\u53EF\u4EE5\u641C\u7D22\u6587\u4EF6\u3001\u5206\u6790\u4EE3\u7801\u3001\u8BFB\u5199\u6587\u4EF6",instructions:this.buildSystemPrompt(),plannerMode:this.isPlannerModeEnabled(),providerName:this.providerSettings.name,contextWindow:this.compatProfile?.contextWindow,tailTokenBudget:this.compatProfile?.tailTokenBudget,maxInputTokensOverride:this.providerSettings.maxInputTokens,toolInputGuardrails:eu,toolOutputGuardrails:tu,compressionMode:this.userConfig.context?.compressionMode??"sync",workspacePath:this.workDir,permissionManager:this.permissionManager}),this.resetMemoryPressureMonitor(),this.runtimeHost.updateRuntime({runner:this.runner,memory:this.memory,model:this.model,systemPrompt:this.buildStaticSystemPrompt()}),this.sessionEnabled&&this.currentSession){this.sessionSync=new Is({session:this.currentSession,memory:this.memory,systemPrompt:this.buildStaticSystemPrompt()}),this.runtimeHost.setSession(this.currentSession,this.sessionSync);let t=await this.sessionSync.loadHistory();t>0&&f.info("MODEL",`Model switched, reloaded ${t} messages from session history`);}}logInfo(e,t){this.uiController?this.uiController.addInfo(e,t):(b(""),b(v.highlight(` ${e}`)),t&&b(v.dim(t)),b(""));}getCommandContext(){return {runtimeHost:this.runtimeHost,uiController:this.uiController,colors:v,sessionEnabled:this.sessionEnabled,sessionManager:this.sessionManager,sessionSync:this.sessionSync,currentSession:this.currentSession,compatProfile:this.compatProfile,autoCompactionInProgress:this.autoCompactionInProgress,isRunning:this.isTaskRunning,logInfo:(e,t)=>this.logInfo(e,t),activateSession:(e,t)=>this.activateSession(e,t),normalizeCheckpoints:vf,promptSelect:(e,t,n)=>this.promptSelect(e,t,n)}}getProviderCommandContext(){return {providerId:this.providerId,provider:this.provider,model:this.model,providerSettings:this.providerSettings,getProviders:()=>this.providerStore.getProviders(),getProvider:e=>this.providerStore.getProvider(e),getDefaultProvider:()=>this.providerStore.getDefaultProvider(),getProviderCount:()=>this.providerStore.getProviderCount(),resolveModel:e=>this.providerStore.resolveModel(e),addProvider:e=>this.providerStore.addProvider(e),updateProvider:(e,t)=>this.providerStore.updateProvider(e,t),deleteProvider:e=>this.providerStore.deleteProvider(e),renameProvider:(e,t)=>this.providerStore.renameProvider(e,t),setDefaultProvider:e=>this.providerStore.setDefaultProvider(e),setLastSelectedModel:(e,t)=>this.providerStore.setLastSelectedModel(e,t),addModel:(e,t,n)=>this.providerStore.addModel(e,t,n),removeModel:(e,t)=>this.providerStore.removeModel(e,t),promptText:(e,t)=>this.promptText(e,t),promptSelect:(e,t,n,r)=>this.promptSelect(e,t,n,r),promptYesNo:(e,t)=>this.promptYesNo(e,t),promptConfirmKeyword:(e,t)=>this.promptConfirmKeyword(e,t),selectProviderFromList:e=>this.selectProviderFromList(e),selectModelFromProvider:(e,t)=>this.selectModelFromProvider(e,t),selectModelFromCurrentProvider:e=>this.selectModelFromCurrentProvider(e),getProviderByIdentifier:e=>this.getProviderByIdentifier(e),applyProviderState:async e=>{this.providerId=e.providerId,this.provider=e.provider,this.model=e.model,this.providerSettings=e.providerSettings,this.refreshProviderSettings(),await this.rebuildAgentAndRunner();},refreshProviderSettings:()=>this.refreshProviderSettings(),getProviderDisplayName:()=>this.getProviderDisplayName(),logInfo:(e,t)=>this.logInfo(e,t),updateProviderDisplay:(e,t)=>{this.uiController&&this.uiController.updateProvider(e,t);},outputFn:this.uiController?e=>this.uiController.printCommandOutput(e):void 0}}getTracingCommandContext(){return {agentLogger:this.agentLogger,getTracingLogDir:()=>this.getTracingLogDir(),initializeAgentLogger:(e,t)=>this.initializeAgentLogger(e,t),disableTracing:e=>this.disableTracing(e),updateTracingPreference:e=>this.updateTracingPreference(e),promptSelect:(e,t,n)=>this.promptSelect(e,t,n),logInfo:(e,t)=>this.logInfo(e,t)}}getThinkingCommandContext(){return {model:this.model,providerSettings:this.providerSettings,thinkingMode:this.thinkingMode,llmProvider:this.llmProvider,setThinkingMode:e=>{this.thinkingMode=e;},promptSelect:(e,t,n)=>this.promptSelect(e,t,n),logInfo:(e,t)=>this.logInfo(e,t)}}getConfigCommandContext(){return {approvalMode:this.approvalMode,userConfig:this.userConfig,promptSelect:(e,t,n,r)=>this.promptSelect(e,t,n,r),logInfo:(e,t)=>this.logInfo(e,t),cleanup:()=>this.cleanup(),setApprovalMode:e=>{this.approvalMode=e,e==="auto"?(this.currentMode="auto",this.runner&&this.runner.setMode("auto")):e==="manual"&&(this.currentMode="agent",this.runner&&this.runner.setMode("agent"));},updateConfig:e=>{this.userConfig=e;}}}getIndexCommandContext(){return {userConfig:this.userConfig,workspacePath:this.workDir,promptSelect:(e,t,n,r)=>this.promptSelect(e,t,n,r),logInfo:(e,t)=>this.logInfo(e,t),updateConfig:e=>{this.userConfig=e;}}}getContextCommandContext(){return {userConfig:this.userConfig,promptSelect:(e,t,n,r)=>this.promptSelect(e,t,n,r),logInfo:(e,t)=>this.logInfo(e,t),updateConfig:e=>{this.userConfig=e;},runner:this.runner}}async addPendingAttachment(e){let t=e.trim();if(!t){this.logInfo("\u9644\u4EF6\u65E0\u6548","\u8BF7\u8F93\u5165\u672C\u5730\u56FE\u7247\u8DEF\u5F84\u6216 https \u94FE\u63A5");return}if(/^https?:\/\//i.test(t)){try{let o=new URL(t);this.pendingAttachments.push({type:"url",data:t,name:o.hostname}),this.logInfo("\u5DF2\u6DFB\u52A0\u94FE\u63A5\u9644\u4EF6",t);}catch{this.logInfo("\u65E0\u6548\u7684 URL",t);}return}let n=te.isAbsolute(t)?t:te.resolve(process.cwd(),t);if(!an.existsSync(n)){this.logInfo("\u6587\u4EF6\u4E0D\u5B58\u5728",n);return}let r=te.extname(n).toLowerCase(),i=ea[r];if(!i){this.logInfo("\u4EC5\u652F\u6301\u56FE\u7247\u9644\u4EF6",`\u5141\u8BB8\u7684\u7C7B\u578B: ${Object.keys(ea).join(", ")}`);return}try{let o=await an.promises.readFile(n),a=`data:${i};base64,${o.toString("base64")}`;this.pendingAttachments.push({type:"image",data:a,name:te.basename(n)}),this.logInfo("\u5DF2\u6DFB\u52A0\u56FE\u7247\u9644\u4EF6",te.basename(n));}catch(o){this.logInfo("\u8BFB\u53D6\u9644\u4EF6\u5931\u8D25",o?.message||"\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6");}}listPendingAttachments(){if(this.pendingAttachments.length===0){this.logInfo("\u9644\u4EF6\u5217\u8868","\u6CA1\u6709\u5F85\u53D1\u9001\u7684\u9644\u4EF6\u3002");return}b(""),b(v.highlight(" Pending attachments:")),this.pendingAttachments.forEach((e,t)=>{let n=e.type==="url"?e.data:e.name||`Image ${t+1}`;b(v.dim(` ${t+1}. `)+v.info(n));}),b("");}clearPendingAttachments(){if(this.pendingAttachments.length===0){this.logInfo("\u9644\u4EF6\u5217\u8868","\u6CA1\u6709\u53EF\u6E05\u9664\u7684\u9644\u4EF6\u3002");return}this.pendingAttachments=[],this.logInfo("\u9644\u4EF6\u5DF2\u6E05\u9664","\u6240\u6709\u5F85\u53D1\u9001\u9644\u4EF6\u5DF2\u79FB\u9664\u3002");}removePendingAttachment(e){if(e<0||e>=this.pendingAttachments.length){this.logInfo("\u9644\u4EF6\u7D22\u5F15\u65E0\u6548",`\u5F53\u524D\u5171\u6709 ${this.pendingAttachments.length} \u4E2A\u9644\u4EF6\u3002`);return}let[t]=this.pendingAttachments.splice(e,1),n=t.type==="url"?t.data:t.name||`Attachment #${e+1}`;this.logInfo("\u5DF2\u79FB\u9664\u9644\u4EF6",n);}};function a0(){let s=[],e=process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN;e&&e.trim()&&s.push({name:"Anthropic",protocol:"anthropic",apiKey:e.trim(),baseUrl:process.env.ANTHROPIC_BASE_URL?.trim(),models:["claude-sonnet-4-5-20250929","claude-3-5-sonnet-20241022"]});let t=process.env.OPENAI_API_KEY,n=process.env.OPENAI_BASE_URL?.trim();if(t&&t.trim()){let o=process.env.OPENAI_PROTOCOL==="responses"||process.env.OPENAI_PROTOCOL==="openai-responses"?"openai-responses":process.env.OPENAI_PROTOCOL==="anthropic"||process.env.OPENAI_PROTOCOL==="anthropic-openai"?"anthropic-openai":"openai",a=o==="openai-responses"?["gpt-5.1","o3-mini"]:["gpt-4o","gpt-4-turbo","gpt-3.5-turbo"];s.push({name:n?"OpenAI Proxy":"OpenAI",protocol:o,apiKey:t.trim(),baseUrl:n,models:a});}let r=process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY;r&&r.trim()&&s.push({name:"Gemini",protocol:"gemini",apiKey:r.trim(),baseUrl:process.env.GEMINI_BASE_URL?.trim(),models:["gemini-2.0-flash-exp","gemini-1.5-pro"]});let i=process.env.DOUBAO_API_KEY||process.env.VOLCENGINE_API_KEY;return i&&i.trim()&&s.push({name:"Doubao",protocol:"doubao",apiKey:i.trim(),baseUrl:process.env.DOUBAO_BASE_URL?.trim(),models:["doubao-pro-256k"]}),s}async function l0(){let s=Xt(),e=new Cs(s),t=e.getDefaultProvider();if(t&&t.apiKey&&t.apiKey.trim().length>0)return;let n=a0();if(n.length>0){console.log(),console.log(j.green("\u2713 Detected API credentials from environment variables:"));for(let g of n)console.log(j.cyan(` \u2022 ${g.name} (${g.protocol})`)),g.baseUrl&&console.log(j.dim(` Base URL: ${g.baseUrl}`));console.log();let{autoCreate:h}=await kn({type:"confirm",name:"autoCreate",message:"Auto-create provider(s) from environment variables?",initial:true},{onCancel:()=>{}});if(h){for(let g of n)e.addProvider({name:g.name,protocol:g.protocol,apiKey:g.apiKey,baseUrl:g.baseUrl,models:g.models,defaultModel:g.models[0],setAsDefault:n.length===1});console.log(),console.log(j.green(`\u2713 Created ${n.length} provider(s) successfully!`)),console.log(j.dim(` Config saved to: ${lt}`)),console.log();return}}if(!an.existsSync(lt)){let h={providers:{default:{id:"default",name:"My Provider",protocol:"openai",apiKey:"",baseUrl:"https://api.openai.com/v1",models:[{name:"gpt-4",createdAt:new Date().toISOString()}],defaultModel:"gpt-4",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}},defaultProviderId:"default"};ct(h);}console.log(),console.log(j.yellow("[*] No LLM provider configured yet.")),console.log(),console.log(j.dim("Config file location:")),console.log(j.cyan(` ${lt}`)),console.log();let{setupMethod:i}=await kn({type:"select",name:"setupMethod",message:"How would you like to configure?",choices:[{title:"[>] Interactive setup (recommended)",value:"interactive"},{title:"[.] Edit config file manually",value:"manual"}],initial:0},{onCancel:()=>{console.log(),console.log(j.red("Setup cancelled. Exiting.")),process.exit(1);}});i==="manual"&&(console.log(),console.log(j.yellow("Please edit the config file and fill in your API key:")),console.log(j.cyan(` ${lt}`)),console.log(),console.log(j.dim("Then restart the CLI.")),console.log(),process.exit(0)),console.log(),console.log(j.dim("You can adjust providers later via /provider commands.")),console.log();let o=await kn([{type:"text",name:"name",message:"Provider display name",initial:"My Provider",validate:h=>h.trim().length>0||"Name is required"},{type:"select",name:"protocol",message:"Protocol format",choices:[{title:"OpenAI (Chat Completions) - GPT-4, GPT-3.5 \u7B49",value:"openai"},{title:"OpenAI (Responses API) - GPT-5, o3 \u7B49\u63A8\u7406\u6A21\u578B",value:"openai-responses"},{title:"Anthropic (Claude API)",value:"anthropic"},{title:"Anthropic (OpenAI \u683C\u5F0F)",value:"anthropic-openai"},{title:"\u8C46\u5305 (Doubao) - \u706B\u5C71\u65B9\u821F\u6DF1\u5EA6\u601D\u8003\u6A21\u578B",value:"doubao"}],initial:0},{type:"text",name:"baseUrl",message:"Base URL (leave empty for default)",initial:""},{type:"password",name:"apiKey",message:"API key / token",validate:h=>h.trim().length>0||"API key is required"},{type:"autocomplete",name:"model",message:"Default model name (choose from list or type custom)",choices:[{title:"gpt-5.1",value:"gpt-5.1"},{title:"claude-sonnet-4-5-20250929",value:"claude-sonnet-4-5-20250929"},{title:"claude-haiku-4-5-20251001",value:"claude-haiku-4-5-20251001"},{title:"gemini-3-pro-preview",value:"gemini-3-pro-preview"}],suggest:(h,g)=>{if(!h)return Promise.resolve(g);let y=g.filter(x=>x.title.toLowerCase().includes(h.toLowerCase())||x.value.toLowerCase().includes(h.toLowerCase()));return Promise.resolve(y.length>0?y:[{title:h,value:h}])},validate:h=>h.trim().length>0||"Model name is required"}],{onCancel:()=>{console.log(),console.log(j.red("Provider setup cancelled. Exiting.")),process.exit(1);}}),a=o.protocol,l=o.baseUrl?.trim()||As[a],c=(o.model||"").trim(),u=[c],d=c,p={providers:{}};new Cs(p).addProvider({name:o.name.trim(),protocol:a,apiKey:o.apiKey.trim(),baseUrl:l,defaultModel:d,models:u,setAsDefault:true}),console.log(),console.log(j.green(`\u2713 Provider "${o.name.trim()}" configured successfully!`)),console.log(j.dim(` Config saved to: ${lt}`)),console.log();}async function c0(){let s=Kc();f.info("CLI","Arguments parsed",{model:s.model,provider:s.provider,workDir:s.workDir}),s.help&&(Yh(Ps),process.exit(0)),s.version&&(Xh(Ps),process.exit(0));try{await l0();let e=new du(s.model,s.workDir,s.provider,s);await e.init(),f.info("CLI","CLI initialized successfully"),await e.runInteractive();}catch(e){throw f.error("CLI","Fatal error in main",{error:e.message,stack:e.stack}),e}}process.on("SIGINT",()=>{Ee.getBackgroundRunning().length>0&&Ee.killAll(true);});var lg=Date.now(),u0=1e3,d0=5e3,p0=6e4,m0=setInterval(()=>{let s=Date.now(),e=s-lg;lg=s,e>d0&&e<p0&&Promise.resolve().then(()=>(Or(),Lr)).then(({safeTTYWriter:t})=>{t.writeStderr(`
1889
+ \u26A0\uFE0F \u4E8B\u4EF6\u5FAA\u73AF\u963B\u585E ${Math.round(e/1e3)}s\uFF0C\u6309 Ctrl+C \u4E24\u6B21\u5F3A\u5236\u9000\u51FA
1890
+ `);});},u0);m0.unref();process.on("SIGTERM",()=>{Ee.killAll(true),process.stdin.isTTY&&process.stdin.setRawMode(false),process.exit(0);});try{process.on("SIGTSTP","ignore");}catch{}try{process.on("SIGTTIN","ignore");}catch{}try{process.on("SIGTTOU","ignore");}catch{}process.on("SIGCONT",()=>{if(process.stdin.isTTY&&!process.stdin.destroyed)try{process.stdin.isRaw!==!1&&process.stdin.setRawMode(!0),process.stdin.resume(),f.debug("SIGNAL","SIGCONT: stdin recovered after resume");}catch(s){f.warn("SIGNAL","SIGCONT: failed to recover stdin",{error:s});}});process.on("exit",()=>{process.stdin.isTTY&&process.stdin.setRawMode(false);});if(process.env.NEOX_WORKER==="execute_shell"){let{runExecuteShellWorker:s}=await Promise.resolve().then(()=>(og(),ig));await s(),process.exit(0);}c0().catch(s=>{process.stdin.isTTY&&process.stdin.setRawMode(false),console.error(j.red(`
1891
+ [x] Unexpected error:`),s.message),process.exit(1);});export{nF as originalConsole};