@mk-co/neox-cli 2.0.15 → 2.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import*as vn from'fs';import vn__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,createReadStream,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import*as Y from'path';import Y__default,{join,dirname,win32,posix}from'path';import Us,{homedir,platform}from'os';import*as Z from'fs/promises';import Z__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import fi from'readline';import {createHash,randomBytes,randomUUID}from'crypto';import ic from'fast-glob';import {spawn,fork}from'child_process';import {execa,execaSync}from'execa';import Bu from'puppeteer-core';import {EventEmitter}from'events';import*as $a from'net';import {fileURLToPath}from'url';import Tl from'stream';import {StringDecoder}from'string_decoder';import tg from'ajv';import Pg from'axios';import uu from'simple-git';import*as pu from'chokidar';var mu=Object.create;var Un=Object.defineProperty;var hu=Object.getOwnPropertyDescriptor;var gu=Object.getOwnPropertyNames;var fu=Object.getPrototypeOf,yu=Object.prototype.hasOwnProperty;var na=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var bu=(r,e)=>()=>(r&&(e=r(r=0)),e);var ci=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),_u=(r,e)=>{for(var t in e)Un(r,t,{get:e[t],enumerable:true});},ra=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gu(e))!yu.call(r,n)&&n!==t&&Un(r,n,{get:()=>e[n],enumerable:!(s=hu(e,n))||s.enumerable});return r};var wu=(r,e,t)=>(t=r!=null?mu(fu(r)):{},ra(Un(t,"default",{value:r,enumerable:true}),r)),ia=r=>ra(Un({},"__esModule",{value:true}),r);var jn={};_u(jn,{cliHealthMonitor:()=>xu,cliLogger:()=>g,debugLog:()=>ue,generateCurlCommand:()=>yt,installCrashHandler:()=>Su,logCurlCommand:()=>mi});function yt(r,e,t,s=true){let n=["curl -X POST \\"];n.push(` '${r}' \\`);for(let[o,a]of Object.entries(e)){let l=a;if(s){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)}`);}n.push(` -H '${o}: ${l}' \\`);}let i=JSON.stringify(t);return n.push(` -d '${Tu(i)}'`),n.join(`
2
- `)}function Tu(r){return r.replace(/'/g,"'\\''")}function mi(r,e,t){if(process.env.CLI_DEBUG!=="1")return;let s=yt(r,e,t);g.info("CURL","=== LLM Request CURL Command ==="),g.info("CURL",s),g.info("CURL","=== End CURL Command ==="),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1
+ import*as Tn from'fs';import Tn__default,{realpathSync,readlinkSync,readdirSync,readdir as readdir$1,lstatSync,createReadStream,readFileSync,existsSync,mkdirSync,writeFileSync}from'fs';import*as Y from'path';import Y__default,{join,dirname,win32,posix}from'path';import js,{homedir,platform}from'os';import*as Z from'fs/promises';import Z__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import bo from'readline';import {createHash,randomBytes,randomUUID}from'crypto';import lc from'fast-glob';import {spawn,fork}from'child_process';import {execa,execaSync}from'execa';import qu from'puppeteer-core';import {EventEmitter}from'events';import*as Ua from'net';import {fileURLToPath}from'url';import kl from'stream';import {StringDecoder}from'string_decoder';import rg from'ajv';import Dg from'axios';import mu from'simple-git';import*as hu from'chokidar';var fu=Object.create;var jn=Object.defineProperty;var yu=Object.getOwnPropertyDescriptor;var bu=Object.getOwnPropertyNames;var _u=Object.getPrototypeOf,wu=Object.prototype.hasOwnProperty;var ra=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var vu=(r,e)=>()=>(r&&(e=r(r=0)),e);var uo=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Tu=(r,e)=>{for(var t in e)jn(r,t,{get:e[t],enumerable:true});},oa=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bu(e))!wu.call(r,n)&&n!==t&&jn(r,n,{get:()=>e[n],enumerable:!(s=yu(e,n))||s.enumerable});return r};var xu=(r,e,t)=>(t=r!=null?fu(_u(r)):{},oa(jn(t,"default",{value:r,enumerable:true}),r)),ia=r=>oa(jn({},"__esModule",{value:true}),r);var Gn={};Tu(Gn,{cliHealthMonitor:()=>Cu,cliLogger:()=>g,debugLog:()=>ue,generateCurlCommand:()=>yt,installCrashHandler:()=>Ru,logCurlCommand:()=>go});function yt(r,e,t,s=true){let n=["curl -X POST \\"];n.push(` '${r}' \\`);for(let[i,a]of Object.entries(e)){let l=a;if(s){let c=i.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)}`);}n.push(` -H '${i}: ${l}' \\`);}let o=JSON.stringify(t);return n.push(` -d '${ku(o)}'`),n.join(`
2
+ `)}function ku(r){return r.replace(/'/g,"'\\''")}function go(r,e,t){if(process.env.CLI_DEBUG!=="1")return;let s=yt(r,e,t);g.info("CURL","=== LLM Request CURL Command ==="),g.info("CURL",s),g.info("CURL","=== End CURL Command ==="),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
3
3
  [CURL] === LLM Request CURL Command ===`),console.log(s),console.log(`[CURL] === End CURL Command ===
4
- `));}function ue(r,e,t){if(process.env.CLI_DEBUG==="1"&&(g.debug(r,e,t),process.env.CLI_DEBUG_CONSOLE==="1")){let s=r?`[${r}]`:"";t!==void 0?console.log(s,e,t):console.log(s,e);}}function Su(){process.on("uncaughtException",r=>{g.error("CRASH","Uncaught Exception",{name:r.name,message:r.message,stack:r.stack}),setTimeout(()=>process.exit(1),100);}),process.on("unhandledRejection",r=>{g.error("CRASH","Unhandled Rejection",{reason:r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:r});});try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),g.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) initialized in crashHandler");}catch{}process.on("exit",()=>{g.close();});}var pi,g,di,xu,le=bu(()=>{pi=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=Y__default.join(Us.homedir(),".neox","logs");}init(){if(!this.initialized)try{vn__default.existsSync(this.logDir)||vn__default.mkdirSync(this.logDir,{recursive:!0}),this.initialized=!0;}catch{this.enabled=false;}}getLogFilePath(){let e=new Date().toISOString().split("T")[0];return Y__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=vn__default.createWriteStream(e,{flags:"a"}),this.currentLogFile=e),this.writeStream}formatLocalTime(){let e=new Date,t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=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}-${s}-${n} ${i}:${o}:${a}.${l}`}formatMessage(e,t,s,n){let i=this.formatLocalTime(),o=e.toUpperCase().padEnd(5),a=t?`[${t}]`:"",l=`${i} ${o} ${a} ${s}`;if(n!==void 0)try{let c=this.safeStringify(n);l+=` ${c}`;}catch{l+=" [Serialization Error]";}return l+`
5
- `}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n instanceof Error?{name:n.name,message:n.message,stack:n.stack}:n})}write(e,t,s,n){if(!this.enabled)return;let i=this.ensureStream();if(!i||this.backpressured&&e==="debug")return;let o=this.formatMessage(e,t,s,n);!i.write(o)&&!this.backpressured&&(this.backpressured=true,i.once("drain",()=>{this.backpressured=false;}));}debug(e,t,s){this.write("debug",e,t,s);}info(e,t,s){this.write("info",e,t,s);}warn(e,t,s){this.write("warn",e,t,s);}error(e,t,s){this.write("error",e,t,s);}log(e,...t){let s=t.map(n=>{if(typeof n=="string")return n;try{return this.safeStringify(n)}catch{return String(n)}}).join(" ");this.write("info",e,s);}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);}},g=new pi;di=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){g.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,g.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,g.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let s=this.getStdinState();if(s.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,s.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){g.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;g.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:s,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&g.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:s}),t>1e4&&g.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();g.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&g.debug("INK",`[${e}]`,t);}},xu=new di;});var Ja=ci((I0,za)=>{za.exports=Ha;function Ha(r,e,t){r instanceof RegExp&&(r=Wa(r,t)),e instanceof RegExp&&(e=Wa(e,t));var s=qa(r,e,t);return s&&{start:s[0],end:s[1],pre:t.slice(0,s[0]),body:t.slice(s[0]+r.length,s[1]),post:t.slice(s[1]+e.length)}}function Wa(r,e){var t=e.match(r);return t?t[0]:null}Ha.range=qa;function qa(r,e,t){var s,n,i,o,a,l=t.indexOf(r),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(r===e)return [l,c];for(s=[],i=t.length;u>=0&&!a;)u==l?(s.push(u),l=t.indexOf(r,u+1)):s.length==1?a=[s.pop(),c]:(n=s.pop(),n<i&&(i=n,o=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;s.length&&(a=[i,o]);}return a}});var tl=ci((M0,el)=>{var Ka=Ja();el.exports=fd;var Va="\0SLASH"+Math.random()+"\0",Ya="\0OPEN"+Math.random()+"\0",qi="\0CLOSE"+Math.random()+"\0",Xa="\0COMMA"+Math.random()+"\0",Za="\0PERIOD"+Math.random()+"\0";function Hi(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function hd(r){return r.split("\\\\").join(Va).split("\\{").join(Ya).split("\\}").join(qi).split("\\,").join(Xa).split("\\.").join(Za)}function gd(r){return r.split(Va).join("\\").split(Ya).join("{").split(qi).join("}").split(Xa).join(",").split(Za).join(".")}function Qa(r){if(!r)return [""];var e=[],t=Ka("{","}",r);if(!t)return r.split(",");var s=t.pre,n=t.body,i=t.post,o=s.split(",");o[o.length-1]+="{"+n+"}";var a=Qa(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function fd(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Ys(hd(r),true).map(gd)):[]}function yd(r){return "{"+r+"}"}function bd(r){return /^-?0\d/.test(r)}function _d(r,e){return r<=e}function wd(r,e){return r>=e}function Ys(r,e){var t=[],s=Ka("{","}",r);if(!s)return [r];var n=s.pre,i=s.post.length?Ys(s.post,false):[""];if(/\$$/.test(s.pre))for(var o=0;o<i.length;o++){var a=n+"{"+s.body+"}"+i[o];t.push(a);}else {var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),u=l||c,p=s.body.indexOf(",")>=0;if(!u&&!p)return s.post.match(/,(?!,).*\}/)?(r=s.pre+"{"+s.body+qi+s.post,Ys(r)):[r];var d;if(u)d=s.body.split(/\.\./);else if(d=Qa(s.body),d.length===1&&(d=Ys(d[0],false).map(yd),d.length===1))return i.map(function(C){return s.pre+d[0]+C});var m;if(u){var h=Hi(d[0]),f=Hi(d[1]),y=Math.max(d[0].length,d[1].length),b=d.length==3?Math.abs(Hi(d[2])):1,_=_d,v=f<h;v&&(b*=-1,_=wd);var k=d.some(bd);m=[];for(var R=h;_(R,f);R+=b){var O;if(c)O=String.fromCharCode(R),O==="\\"&&(O="");else if(O=String(R),k){var W=y-O.length;if(W>0){var F=new Array(W+1).join("0");R<0?O="-"+F+O.slice(1):O=F+O;}}m.push(O);}}else {m=[];for(var S=0;S<d.length;S++)m.push.apply(m,Ys(d[S],false));}for(var S=0;S<m.length;S++)for(var o=0;o<i.length;o++){var a=n+m[S]+i[o];(!e||u||a)&&t.push(a);}}return t}});var xc=ci((Av,Tc)=>{var wc=na("fs"),Ao=na("path"),vc=Ao.join(__dirname,"path.txt");function Yh(){let r;if(wc.existsSync(vc)&&(r=wc.readFileSync(vc,"utf-8")),process.env.ELECTRON_OVERRIDE_DIST_PATH)return Ao.join(process.env.ELECTRON_OVERRIDE_DIST_PATH,r||"electron");if(r)return Ao.join(__dirname,"dist",r);throw new Error("Electron failed to install correctly, please delete node_modules/electron and try installing again")}Tc.exports=Yh();});le();var Gn=class{hosts=new Map;hostConfigs=new Map;workspacePath=null;setWorkspace(e){this.workspacePath=e;for(let t of this.hosts.values())try{t.setWorkDir(e);}catch{}}getWorkspace(){return this.workspacePath}getHost(e){return this.hosts.get(e)}hasHost(e){return this.hosts.has(e)}getHostConfig(e){return this.hostConfigs.get(e)}clearHost(e){this.hosts.delete(e),this.hostConfigs.delete(e);}clearAll(){for(let e of this.hosts.values())try{e.interrupt();}catch{}this.hosts.clear(),this.hostConfigs.clear();}forEachHost(e){for(let[t,s]of this.hosts.entries())e(s,t);}async getOrCreateHost(e){let{sessionId:t,configKey:s,createHost:n}=e,i=this.hosts.get(t);if(i){let a=this.hostConfigs.get(t);if(a===s)return g.info("HOST_CONTROLLER",`\u{1F504} Reusing existing host for session=${t}, configKey=${s}`),i;g.info("HOST_CONTROLLER",`\u{1F5D1}\uFE0F Clearing old host: session=${t}, oldKey=${a}, newKey=${s}`),this.clearHost(t);}g.info("HOST_CONTROLLER",`\u2728 Creating NEW host: session=${t}, configKey=${s}`);let o=await n();return this.hosts.set(t,o),this.hostConfigs.set(t,s),this.workspacePath&&o.setWorkDir(this.workspacePath),o}};function ee(r){return r===null?"":typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}var ku={unknown:0,normal:1,warn:2,soft_limit:3,limit:4};function Bn(r){if(!r)return 0;let e=r.trim();return e.length?Math.ceil(e.length/4):0}function pt(r){let e=ee(r.content),t=Bn(e),s=r.tool_calls?.length?Bn(JSON.stringify(r.tool_calls)):0;return t+s}function We(r){return r.reduce((e,t)=>e+pt(t),0)}function ss(r){let e={systemTokens:0,userTokens:0,assistantTokens:0,toolCallTokens:0,toolResultTokens:0,totalTokens:0};for(let t of r){let s=ee(t.content),n=Bn(s),i=t.tool_calls?.length?Bn(JSON.stringify(t.tool_calls)):0;switch(t.role){case "system":e.systemTokens+=n;break;case "user":e.userTokens+=n;break;case "assistant":e.assistantTokens+=n,e.toolCallTokens+=i;break;case "tool":e.toolResultTokens+=n;break;default:e.userTokens+=n+i;}}return e.totalTokens=e.systemTokens+e.userTokens+e.assistantTokens+e.toolCallTokens+e.toolResultTokens,e}function Cu(r,e,t){return !r.contextWindow&&!r.autoCompactLimit?"unknown":r.autoCompactLimit&&e>=r.autoCompactLimit?"limit":t===void 0||r.contextWindow===void 0?"unknown":t>=r.warnThresholds.hard?"limit":t>=r.warnThresholds.soft?"soft_limit":t>=r.warnThresholds.warn?"warn":"normal"}var Wn=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=We(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,s){return this.promptTokensActual=e,this.completionTokensActual=t,this.promptTokensEstimate=0,this.completionTokensEstimate=0,this.getSnapshot(s)}getSnapshot(e){let t=this.promptTokensActual||this.promptTokensEstimate,s=this.completionTokensActual+this.completionTokensEstimate,n=t+s,i=this.profile.contextWindow?n/this.profile.contextWindow:void 0,o=Cu(this.profile,n,i);return {profile:this.profile,tokensUsed:n,promptTokens:t,completionTokens:s,messageCount:e,pressure:i,state:o,timestamp:Date.now()}}getStateRank(e){return ku[e]}estimateMessagesForDisplay(e){return We(e)}recordCalibration(e,t,s){if(process.env.CLI_DEBUG){let n=t+s,i=e>0?n/e:0;console.log(`[MemoryPressure] \u6821\u51C6: \u4F30\u7B97=${e}, \u5B9E\u9645=${n}, \u6BD4\u7387=${i.toFixed(3)}`);}}};function ns(){let r=new Date,e=r.toISOString().slice(0,10).replace(/-/g,""),t=r.toISOString().slice(11,19).replace(/:/g,""),s=Math.random().toString(36).slice(2,6);return `session_${e}_${t}_${s}`}var Gt=class r{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||Y__default.join(Us.homedir(),".neox","sessions"),this.filePath=Y__default.join(this.directory,`${this.sessionId}.jsonl`);}async ensureDirectory(){await Z__default.mkdir(this.directory,{recursive:true});}async ensureInitialized(){if(!this.initialized){await this.ensureDirectory();try{await Z__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=vn__default.createReadStream(this.filePath,{encoding:"utf-8"}),s=fi.createInterface({input:t,crlfDelay:1/0});for await(let n of s)if(n.trim())try{let i=JSON.parse(n);e.push(i);}catch{console.warn(`Invalid JSONL line: ${n.slice(0,50)}...`);}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,s)=>t.seq-s.seq),e}async appendItem(e){await this.ensureDirectory();let t={item:e,timestamp:Date.now(),seq:this.sequenceNumber++},s=JSON.stringify(t)+`
4
+ `));}function ue(r,e,t){if(process.env.CLI_DEBUG==="1"&&(g.debug(r,e,t),process.env.CLI_DEBUG_CONSOLE==="1")){let s=r?`[${r}]`:"";t!==void 0?console.log(s,e,t):console.log(s,e);}}function Ru(){process.on("uncaughtException",r=>{g.error("CRASH","Uncaught Exception",{name:r.name,message:r.message,stack:r.stack}),setTimeout(()=>process.exit(1),100);}),process.on("unhandledRejection",r=>{g.error("CRASH","Unhandled Rejection",{reason:r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:r});});try{process.on("SIGTTIN","ignore"),process.on("SIGTTOU","ignore"),g.info("SIGNAL","TTY control signals (SIGTTIN/SIGTTOU) initialized in crashHandler");}catch{}process.on("exit",()=>{g.close();});}var mo,g,ho,Cu,le=vu(()=>{mo=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=Y__default.join(js.homedir(),".neox","logs");}init(){if(!this.initialized)try{Tn__default.existsSync(this.logDir)||Tn__default.mkdirSync(this.logDir,{recursive:!0}),this.initialized=!0;}catch{this.enabled=false;}}getLogFilePath(){let e=new Date().toISOString().split("T")[0];return Y__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=Tn__default.createWriteStream(e,{flags:"a"}),this.currentLogFile=e),this.writeStream}formatLocalTime(){let e=new Date,t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),l=String(e.getMilliseconds()).padStart(3,"0");return `${t}-${s}-${n} ${o}:${i}:${a}.${l}`}formatMessage(e,t,s,n){let o=this.formatLocalTime(),i=e.toUpperCase().padEnd(5),a=t?`[${t}]`:"",l=`${o} ${i} ${a} ${s}`;if(n!==void 0)try{let c=this.safeStringify(n);l+=` ${c}`;}catch{l+=" [Serialization Error]";}return l+`
5
+ `}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n instanceof Error?{name:n.name,message:n.message,stack:n.stack}:n})}write(e,t,s,n){if(!this.enabled)return;let o=this.ensureStream();if(!o||this.backpressured&&e==="debug")return;let i=this.formatMessage(e,t,s,n);!o.write(i)&&!this.backpressured&&(this.backpressured=true,o.once("drain",()=>{this.backpressured=false;}));}debug(e,t,s){this.write("debug",e,t,s);}info(e,t,s){this.write("info",e,t,s);}warn(e,t,s){this.write("warn",e,t,s);}error(e,t,s){this.write("error",e,t,s);}log(e,...t){let s=t.map(n=>{if(typeof n=="string")return n;try{return this.safeStringify(n)}catch{return String(n)}}).join(" ");this.write("info",e,s);}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);}},g=new mo;ho=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){g.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,g.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,g.info("HEALTH","Health monitor stopped"));}stdinDestroyedCount=0;checkHealth(){let e=Date.now(),t=e-this.lastHeartbeat;this.lastHeartbeat=e,this.heartbeatCount++;let s=this.getStdinState();if(s.isPaused?this.stdinPausedCount++:this.stdinPausedCount=0,s.destroyed){if(this.stdinDestroyedCount++,this.stdinDestroyedCount>=3){g.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;g.debug("HEALTH",`[pid=${this.pid}] Heartbeat #${this.heartbeatCount}`,{elapsed:`${t}ms`,stdin:s,stdinPausedCount:this.stdinPausedCount}),this.stdinPausedCount>=3&&g.warn("HEALTH",`[pid=${this.pid}] \u26A0\uFE0F stdin has been paused for ${this.stdinPausedCount} consecutive checks!`,{stdin:s}),t>1e4&&g.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();g.debug("STDIN",`[${e}] stdin state`,t);}logInkState(e,t){process.env.CLI_DEBUG==="1"&&g.debug("INK",`[${e}]`,t);}},Cu=new ho;});var Ya=uo((N0,Va)=>{Va.exports=Ja;function Ja(r,e,t){r instanceof RegExp&&(r=za(r,t)),e instanceof RegExp&&(e=za(e,t));var s=Ka(r,e,t);return s&&{start:s[0],end:s[1],pre:t.slice(0,s[0]),body:t.slice(s[0]+r.length,s[1]),post:t.slice(s[1]+e.length)}}function za(r,e){var t=e.match(r);return t?t[0]:null}Ja.range=Ka;function Ka(r,e,t){var s,n,o,i,a,l=t.indexOf(r),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(r===e)return [l,c];for(s=[],o=t.length;u>=0&&!a;)u==l?(s.push(u),l=t.indexOf(r,u+1)):s.length==1?a=[s.pop(),c]:(n=s.pop(),n<o&&(o=n,i=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;s.length&&(a=[o,i]);}return a}});var rl=uo((F0,nl)=>{var Xa=Ya();nl.exports=_d;var Za="\0SLASH"+Math.random()+"\0",Qa="\0OPEN"+Math.random()+"\0",Jo="\0CLOSE"+Math.random()+"\0",el="\0COMMA"+Math.random()+"\0",tl="\0PERIOD"+Math.random()+"\0";function zo(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function yd(r){return r.split("\\\\").join(Za).split("\\{").join(Qa).split("\\}").join(Jo).split("\\,").join(el).split("\\.").join(tl)}function bd(r){return r.split(Za).join("\\").split(Qa).join("{").split(Jo).join("}").split(el).join(",").split(tl).join(".")}function sl(r){if(!r)return [""];var e=[],t=Xa("{","}",r);if(!t)return r.split(",");var s=t.pre,n=t.body,o=t.post,i=s.split(",");i[i.length-1]+="{"+n+"}";var a=sl(o);return o.length&&(i[i.length-1]+=a.shift(),i.push.apply(i,a)),e.push.apply(e,i),e}function _d(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Xs(yd(r),true).map(bd)):[]}function wd(r){return "{"+r+"}"}function vd(r){return /^-?0\d/.test(r)}function Td(r,e){return r<=e}function xd(r,e){return r>=e}function Xs(r,e){var t=[],s=Xa("{","}",r);if(!s)return [r];var n=s.pre,o=s.post.length?Xs(s.post,false):[""];if(/\$$/.test(s.pre))for(var i=0;i<o.length;i++){var a=n+"{"+s.body+"}"+o[i];t.push(a);}else {var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(s.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(s.body),u=l||c,p=s.body.indexOf(",")>=0;if(!u&&!p)return s.post.match(/,(?!,).*\}/)?(r=s.pre+"{"+s.body+Jo+s.post,Xs(r)):[r];var d;if(u)d=s.body.split(/\.\./);else if(d=sl(s.body),d.length===1&&(d=Xs(d[0],false).map(wd),d.length===1))return o.map(function(C){return s.pre+d[0]+C});var m;if(u){var h=zo(d[0]),f=zo(d[1]),y=Math.max(d[0].length,d[1].length),b=d.length==3?Math.abs(zo(d[2])):1,_=Td,v=f<h;v&&(b*=-1,_=xd);var k=d.some(vd);m=[];for(var R=h;_(R,f);R+=b){var O;if(c)O=String.fromCharCode(R),O==="\\"&&(O="");else if(O=String(R),k){var W=y-O.length;if(W>0){var F=new Array(W+1).join("0");R<0?O="-"+F+O.slice(1):O=F+O;}}m.push(O);}}else {m=[];for(var S=0;S<d.length;S++)m.push.apply(m,Xs(d[S],false));}for(var S=0;S<m.length;S++)for(var i=0;i<o.length;i++){var a=n+m[S]+o[i];(!e||u||a)&&t.push(a);}}return t}});var Cc=uo((Uv,kc)=>{var xc=ra("fs"),Pi=ra("path"),Sc=Pi.join(__dirname,"path.txt");function Qh(){let r;if(xc.existsSync(Sc)&&(r=xc.readFileSync(Sc,"utf-8")),process.env.ELECTRON_OVERRIDE_DIST_PATH)return Pi.join(process.env.ELECTRON_OVERRIDE_DIST_PATH,r||"electron");if(r)return Pi.join(__dirname,"dist",r);throw new Error("Electron failed to install correctly, please delete node_modules/electron and try installing again")}kc.exports=Qh();});le();var Bn=class{hosts=new Map;hostConfigs=new Map;workspacePath=null;setWorkspace(e){this.workspacePath=e;for(let t of this.hosts.values())try{t.setWorkDir(e);}catch{}}getWorkspace(){return this.workspacePath}getHost(e){return this.hosts.get(e)}hasHost(e){return this.hosts.has(e)}getHostConfig(e){return this.hostConfigs.get(e)}clearHost(e){this.hosts.delete(e),this.hostConfigs.delete(e);}clearAll(){for(let e of this.hosts.values())try{e.interrupt();}catch{}this.hosts.clear(),this.hostConfigs.clear();}forEachHost(e){for(let[t,s]of this.hosts.entries())e(s,t);}async getOrCreateHost(e){let{sessionId:t,configKey:s,createHost:n}=e,o=this.hosts.get(t);if(o){let a=this.hostConfigs.get(t);if(a===s)return g.info("HOST_CONTROLLER",`\u{1F504} Reusing existing host for session=${t}, configKey=${s}`),o;g.info("HOST_CONTROLLER",`\u{1F5D1}\uFE0F Clearing old host: session=${t}, oldKey=${a}, newKey=${s}`),this.clearHost(t);}g.info("HOST_CONTROLLER",`\u2728 Creating NEW host: session=${t}, configKey=${s}`);let i=await n();return this.hosts.set(t,i),this.hostConfigs.set(t,s),this.workspacePath&&i.setWorkDir(this.workspacePath),i}};function ee(r){return r===null?"":typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}var Eu={unknown:0,normal:1,warn:2,soft_limit:3,limit:4};function Wn(r){if(!r)return 0;let e=r.trim();return e.length?Math.ceil(e.length/4):0}function pt(r){let e=ee(r.content),t=Wn(e),s=r.tool_calls?.length?Wn(JSON.stringify(r.tool_calls)):0;return t+s}function We(r){return r.reduce((e,t)=>e+pt(t),0)}function ns(r){let e={systemTokens:0,userTokens:0,assistantTokens:0,toolCallTokens:0,toolResultTokens:0,totalTokens:0};for(let t of r){let s=ee(t.content),n=Wn(s),o=t.tool_calls?.length?Wn(JSON.stringify(t.tool_calls)):0;switch(t.role){case "system":e.systemTokens+=n;break;case "user":e.userTokens+=n;break;case "assistant":e.assistantTokens+=n,e.toolCallTokens+=o;break;case "tool":e.toolResultTokens+=n;break;default:e.userTokens+=n+o;}}return e.totalTokens=e.systemTokens+e.userTokens+e.assistantTokens+e.toolCallTokens+e.toolResultTokens,e}function Iu(r,e,t){return !r.contextWindow&&!r.autoCompactLimit?"unknown":r.autoCompactLimit&&e>=r.autoCompactLimit?"limit":t===void 0||r.contextWindow===void 0?"unknown":t>=r.warnThresholds.hard?"limit":t>=r.warnThresholds.soft?"soft_limit":t>=r.warnThresholds.warn?"warn":"normal"}var Hn=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=We(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,s){return this.promptTokensActual=e,this.completionTokensActual=t,this.promptTokensEstimate=0,this.completionTokensEstimate=0,this.getSnapshot(s)}getSnapshot(e){let t=this.promptTokensActual||this.promptTokensEstimate,s=this.completionTokensActual+this.completionTokensEstimate,n=t+s,o=this.profile.contextWindow?n/this.profile.contextWindow:void 0,i=Iu(this.profile,n,o);return {profile:this.profile,tokensUsed:n,promptTokens:t,completionTokens:s,messageCount:e,pressure:o,state:i,timestamp:Date.now()}}getStateRank(e){return Eu[e]}estimateMessagesForDisplay(e){return We(e)}recordCalibration(e,t,s){if(process.env.CLI_DEBUG){let n=t+s,o=e>0?n/e:0;console.log(`[MemoryPressure] \u6821\u51C6: \u4F30\u7B97=${e}, \u5B9E\u9645=${n}, \u6BD4\u7387=${o.toFixed(3)}`);}}};function rs(){let r=new Date,e=r.toISOString().slice(0,10).replace(/-/g,""),t=r.toISOString().slice(11,19).replace(/:/g,""),s=Math.random().toString(36).slice(2,6);return `session_${e}_${t}_${s}`}var Gt=class r{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||Y__default.join(js.homedir(),".neox","sessions"),this.filePath=Y__default.join(this.directory,`${this.sessionId}.jsonl`);}async ensureDirectory(){await Z__default.mkdir(this.directory,{recursive:true});}async ensureInitialized(){if(!this.initialized){await this.ensureDirectory();try{await Z__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=Tn__default.createReadStream(this.filePath,{encoding:"utf-8"}),s=bo.createInterface({input:t,crlfDelay:1/0});for await(let n of s)if(n.trim())try{let o=JSON.parse(n);e.push(o);}catch{console.warn(`Invalid JSONL line: ${n.slice(0,50)}...`);}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,s)=>t.seq-s.seq),e}async appendItem(e){await this.ensureDirectory();let t={item:e,timestamp:Date.now(),seq:this.sequenceNumber++},s=JSON.stringify(t)+`
6
6
  `;await Z__default.appendFile(this.filePath,s,"utf-8");}async writeAllItems(e){await this.ensureDirectory();let t=e.map(s=>JSON.stringify(s)).join(`
7
7
  `);await Z__default.writeFile(this.filePath,t?t+`
8
- `:"","utf-8"),e.length>0?this.sequenceNumber=Math.max(...e.map(s=>s.seq))+1:this.sequenceNumber=0;}async getItems(e){await this.ensureInitialized();let s=(await this.readAllItems()).map(n=>n.item);return e===void 0?s:s.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 s=Math.min(e,t.length),n=t.splice(-s);return await this.writeAllItems(t),n.map(i=>i.item)}async createCheckpoint(e,t){await this.ensureInitialized();let s=`cp_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,n={type:"checkpoint",data:{id:s,name:e,description:t}};return await this.appendItem(n),s}async rollbackToCheckpoint(e){await this.ensureInitialized();let t=await this.readAllItems(),s=t.findIndex(o=>o.item.type==="checkpoint"&&o.item.data.id===e);if(s===-1)throw new Error(`Checkpoint not found: ${e}`);let n=t.slice(0,s+1),i=t.length-n.length;return await this.writeAllItems(n),i}async getCheckpoints(){await this.ensureInitialized();let e=await this.readAllItems(),t=[];for(let s of e)if(s.item.type==="checkpoint"){let n=s.item;t.push({id:n.data.id,name:n.data.name,timestamp:s.timestamp});}return t}async clearSession(){try{await Z__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 s of e)s.item.type==="message"&&t.push(s.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((s,n)=>({item:s.item,timestamp:s.timestamp??Date.now(),seq:n}));await this.writeAllItems(t),this.initialized=true;}static async listSessions(e){let t=e||Y__default.join(Us.homedir(),".neox","sessions");try{return (await Z__default.readdir(t)).filter(n=>n.endsWith(".jsonl")).map(n=>n.replace(".jsonl",""))}catch{return []}}static async getMostRecentId(e){let t=e||Y__default.join(Us.homedir(),".neox","sessions");try{let n=(await Z__default.readdir(t)).filter(o=>o.endsWith(".jsonl"));if(n.length===0)return null;let i=await Promise.all(n.map(async o=>({name:o.replace(".jsonl",""),mtime:(await Z__default.stat(Y__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 s=t||Y__default.join(Us.homedir(),".neox","sessions"),n=Y__default.join(s,`${e}.jsonl`);try{return await Z__default.unlink(n),!0}catch{return false}}static async getSessionInfo(e,t){let s=t||Y__default.join(Us.homedir(),".neox","sessions"),n=Y__default.join(s,`${e}.jsonl`);try{let i=await Z__default.stat(n);return {sessionId:e,filePath:n,size:i.size,createdAt:i.birthtime,updatedAt:i.mtime}}catch{return null}}static create(e){return new r({sessionId:ns(),...e})}};le();function z(r,e,t,s){return {type:"ephemeral",status:e,tool:r,summary:t,final:e==="success"||e==="already_done",...s}}function de(r,e,t,s,n){return {type:"contextual",status:e,tool:r,summary:t,content:s,...n}}function Rt(r,e,t,s){return {type:"summarized",status:e,tool:r,summary:t,...s}}function aa(r){g.info("TOOL_RESULT",`\u{1F504} getResultForLLM input: ${r.tool}`,{type:r.type,status:r.status,tool:r.tool,hasContent:!!r.content,contentLength:r.content?.length||0,summary:r.summary?.substring(0,100)});let e;if(r.type==="ephemeral")if(r.status==="error")r.tool==="edit_file"?e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error,verify_hint:r.verify_hint,file_path:r.file_path,actual_content:r.actual_content,expected_start_line:r.expected_start_line,similar_matches:r.metadata?.similar_matches,suggestions:r.metadata?.suggestions}):e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error,verify_hint:r.verify_hint,file_path:r.file_path,similar_matches:r.metadata?.similar_matches,suggestions:r.metadata?.suggestions});else {let t=r.metadata?.edit_info;if(r.tool==="edit_file"&&t){let s=t.old_string?t.old_string.length>1e3?t.old_string.substring(0,1e3)+"...":t.old_string:void 0,n=t.new_string?t.new_string.length>1e3?t.new_string.substring(0,1e3)+"...":t.new_string:void 0;e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,final:r.final,file_path:r.file_path,old_string_preview:s,new_string_preview:n,start_line:t.start_line});}else e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,final:r.final,file_path:r.file_path});}else r.type==="summarized"?e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error}):e=JSON.stringify(r);return g.info("TOOL_RESULT",`\u2705 getResultForLLM output: ${r.tool}`,{type:r.type,tool:r.tool,llmResultLength:e.length,llmResultPreview:e.substring(0,500)}),e}var hi={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 gi(r){if(r in hi)return hi[r];let e=r.toLowerCase();for(let[t,s]of Object.entries(hi))if(t.toLowerCase()===e)return s;return "contextual"}function la(r){return gi(r)==="contextual"}le();function js(r){if(!r)return 0;let e=0;for(let t of r){let s=t.codePointAt(0)||0;s>=19968&&s<=40959||s>=12288&&s<=12351||s>=65280&&s<=65519||s>=44032&&s<=55215?e+=.67:e+=.25;}return Math.ceil(e)}var Gs=class{messages=[];maxMessages;constructor(e=500){this.maxMessages=e;}add(e){let t=typeof e.content=="string"?e.content:JSON.stringify(e.content),s=js(t),n={...e,_timestamp:Date.now(),_estimatedTokens:s};if(this.messages.push(n),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0&&process.env.CLI_DEBUG==="1"&&g.debug("MEMORY","Assistant message with tool_calls added:",{toolCallCount:e.tool_calls.length,toolCallIds:e.tool_calls.map(i=>({id:i.id,name:i.function.name}))}),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,s){let n=gi(t),i=null;try{let c=JSON.parse(s);c.type&&c.status&&c.summary&&(i=c);}catch{}let o,a=n;g.info("MEMORY","addToolResult: parsedResult\uFF1A"+i),g.info("MEMORY","addToolResult: effectiveResultType\uFF1A"+a),i?(a=i.type||n,o=aa(i),g.info("MEMORY","\u7CBE\u7B80\u7ED3\u679C: content \uFF1A"+o),g.info("MEMORY",`addToolResult: ${t} parsed as ToolResult`,{parsedResult:JSON.stringify(i).substring(0,500),contentAfter:o.substring(0,500),rawLength:s.length,contentLength:o.length})):(o=s,g.debug("MEMORY",`addToolResult: ${t} using raw output`,{rawOutput:s.substring(0,500),rawLength:s.length}));let l={role:"tool",tool_call_id:e,name:t,content:o,_resultType:a,_toolName:t,_timestamp:Date.now(),_estimatedTokens:js(o)};if(process.env.CLI_DEBUG==="1"&&g.debug("MEMORY","Tool result message added:",{toolName:t,toolCallId:e,contentLength:o.length,contentPreview:o.substring(0,200)}),this.messages.push(l),this.messages.length>this.maxMessages){let c=this.messages.filter(d=>d.role==="system"),p=this.messages.filter(d=>d.role!=="system").slice(-(this.maxMessages-c.length));this.messages=[...c,...p];}}stripMetadata(e){let{_resultType:t,_toolName:s,_timestamp:n,_estimatedTokens:i,_tag:o,...a}=e;return a}getAll(){return this.messages.map(e=>this.stripMetadata(e))}getRawMessages(){return this.messages}getMessagesForLLM(){let e=this.messages.map(t=>this.stripMetadata(t));if(process.env.CLI_DEBUG==="1"){let t=e.filter(i=>i.role==="assistant"),s=e.filter(i=>i.role==="tool");g.debug("MEMORY","Messages for LLM:",{totalMessages:e.length,assistantCount:t.length,toolCount:s.length,messageSequence:e.map(i=>i.role).join(" -> ")}),e.slice(-5).forEach((i,o)=>{i.role==="assistant"&&i.tool_calls?g.debug("MEMORY",`Message ${e.length-5+o} (assistant):`,{toolCalls:i.tool_calls.map(a=>({id:a.id,name:a.function.name}))}):i.role==="tool"&&g.debug("MEMORY",`Message ${e.length-5+o} (tool):`,{name:i.name,tool_call_id:i.tool_call_id,contentLength:typeof i.content=="string"?i.content.length:0});});}return e}hasConversationMessages(){return this.messages.some(e=>e.role==="user"||e.role==="assistant")}upsertSystemTagged(e,t){let s=t.trim();if(!s){this.removeSystemTagged(e);return}let n=this.messages.findIndex(a=>a.role==="system"&&a._tag===e);if(n>=0){let a=this.messages[n];if(a.content===s)return;this.messages[n]={...a,content:s,_timestamp:Date.now(),_estimatedTokens:js(s)};return}let i={role:"system",content:s,_tag:e,_timestamp:Date.now(),_estimatedTokens:js(s)},o=this.getSystemInsertIndex();this.messages=[...this.messages.slice(0,o),i,...this.messages.slice(o)];}removeSystemTagged(e){let t=this.messages.length;this.messages=this.messages.filter(s=>!(s.role==="system"&&s._tag===e)),t!==this.messages.length&&process.env.CLI_DEBUG==="1"&&g.debug("MEMORY",`Removed system tag: ${e}`);}getSystemInsertIndex(){let e=0;for(;e<this.messages.length&&this.messages[e].role==="system";)e+=1;return e}cleanupEphemeral(){let e=this.messages.length,t=new Set;for(let s of this.messages)if(s.role==="assistant"&&s.tool_calls)for(let n of s.tool_calls)n.id&&t.add(n.id);return this.messages=this.messages.filter(s=>s._resultType!=="ephemeral"||s.role!=="tool"||!s.tool_call_id?true:t.has(s.tool_call_id)),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,s=0,n=0;for(let a of this.messages){let l=a._estimatedTokens||js(typeof a.content=="string"?a.content:JSON.stringify(a.content));t+=l,a.role==="tool"?(n++,s+=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?s/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`),n>100?o.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8FC7\u957F\uFF08${n} \u6761\uFF09`):n>60&&o.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8F83\u957F\uFF08${n} \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:s,toolResultRatio:i,messageCount:this.messages.length,toolMessageCount:n,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,s=Math.round(t/1024*10)/10,n=this.messages.length*150,i=t+n,o=Math.round(i/1024*10)/10;return {totalKB:o,messagesKB:s,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();g.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:[],s=t.filter(a=>a.role==="system"),n=t.filter(a=>a.role!=="system"),i=Math.max(0,this.maxMessages-s.length),o=i>0?n.slice(-i):[];this.messages=[...s,...o].map(a=>({...a,_timestamp:Date.now()}));}get length(){return this.messages.length}};var Et=class{directory;options;sessionCache=new Map;constructor(e){this.options=e||{},this.directory=e?.directory||Y__default.join(Us.homedir(),".neox","sessions");}async getSession(e){if(this.sessionCache.has(e))return this.sessionCache.get(e);let t=new Gt({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 Z__default.mkdir(this.directory,{recursive:!0});let t=await Z__default.readdir(this.directory);for(let s of t){if(!s.endsWith(".jsonl"))continue;let n=s.replace(".jsonl",""),i=Y__default.join(this.directory,s);try{let o=await Z__default.stat(i),a=await this.readSessionMeta(i),l=await this.countItems(i);e.push({sessionId:n,createdAt:o.birthtime,updatedAt:o.mtime,itemCount:l,agentName:a?.agentName});}catch{}}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,s)=>s.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=Y__default.join(this.directory,`${e}.jsonl`);try{return await Z__default.unlink(t),!0}catch{return false}}async searchSessions(e){let t=await this.listSessions(),s=e.toLowerCase(),n=[];for(let i of t){if(i.sessionId.toLowerCase().includes(s)){n.push(i);continue}if(i.agentName?.toLowerCase().includes(s)){n.push(i);continue}let o=Y__default.join(this.directory,`${i.sessionId}.jsonl`);await this.searchInFile(o,s)&&n.push(i);}return n}async createSession(e){let t=e?.sessionId||ns(),s=new Gt({sessionId:t,directory:this.directory,agentName:e?.agentName||this.options.defaultAgentName,model:e?.model||this.options.defaultModel});return this.sessionCache.set(t,s),s}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(),s=Date.now()-e*24*60*60*1e3,n=0;for(let i of t)i.updatedAt.getTime()<s&&await this.deleteSession(i.sessionId)&&n++;return n}getDirectory(){return this.directory}async getSessionCount(){return (await this.listSessions()).length}async exportSession(e){let t=await this.getSession(e),s=await t.getItems(),n=await t.getMeta();return JSON.stringify({sessionId:e,meta:n,items:s,exportedAt:new Date().toISOString()},null,2)}async readSessionMeta(e){try{let t=createReadStream(e,{encoding:"utf-8"}),s=fi.createInterface({input:t,crlfDelay:1/0});for await(let n of s)if(n.trim())try{let i=JSON.parse(n);if(i.item?.type==="meta")return s.close(),i.item.data}catch{}}catch{}return null}async countItems(e){let t=0;try{let s=createReadStream(e,{encoding:"utf-8"}),n=fi.createInterface({input:s,crlfDelay:1/0});for await(let i of n)i.trim()&&t++;}catch{}return t}async searchInFile(e,t){try{let s=createReadStream(e,{encoding:"utf-8"}),n=fi.createInterface({input:s,crlfDelay:1/0});for await(let i of n)if(i.toLowerCase().includes(t))return n.close(),!0}catch{}return false}};var Lu={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}},Du={timeout:3e4,maxMemoryMB:512,maxCPUPercent:50,allowNetwork:true,allowFileSystem:true,workingDirectory:process.cwd(),env:{},captureImages:false,maxOutputSize:1e4},rt=class{config;constructor(e={}){this.config={...Du,...e};}async execute(e,t){let s=Date.now(),n=Lu[t];if(!n)return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Unsupported language: ${t}`};if(!await this.checkRuntimeAvailable(n.command))return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Runtime not found: ${n.command}. Please install it first.`};let o=null;try{n.useTempFile&&(o=await this.createTempFile(e,n.extension));let a=n.args.map(h=>h.replace("{file}",o||"")),l=o?Y__default.dirname(o):this.config.workingDirectory,c=[n.command,...a].join(" "),u={...Object.fromEntries(Object.entries(process.env).filter(([h,f])=>f!==void 0)),...this.config.env};t==="python"&&this.config.captureImages&&(u.MPLBACKEND="Agg");let p=await this.executeCommand(n.command,a,u,l),d=[];this.config.captureImages&&o&&(d=await this.captureGeneratedImages(Y__default.dirname(o)));let m=Date.now()-s;return {...p,executionTime:m,command:c,workingDirectory:l,images:d&&d.length>0?d:void 0}}catch(a){let l=Date.now()-s;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 s=await Z__default.mkdtemp(Y__default.join(Us.tmpdir(),"neox-code-")),n=Y__default.join(s,`script${t}`);return await Z__default.writeFile(n,e,"utf-8"),n}async executeCommand(e,t,s,n){try{let{stdout:i,stderr:o,exitCode:a}=await execa(e,t,{timeout:this.config.timeout,cwd:n,env:s,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)+`
8
+ `:"","utf-8"),e.length>0?this.sequenceNumber=Math.max(...e.map(s=>s.seq))+1:this.sequenceNumber=0;}async getItems(e){await this.ensureInitialized();let s=(await this.readAllItems()).map(n=>n.item);return e===void 0?s:s.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 s=Math.min(e,t.length),n=t.splice(-s);return await this.writeAllItems(t),n.map(o=>o.item)}async createCheckpoint(e,t){await this.ensureInitialized();let s=`cp_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,n={type:"checkpoint",data:{id:s,name:e,description:t}};return await this.appendItem(n),s}async rollbackToCheckpoint(e){await this.ensureInitialized();let t=await this.readAllItems(),s=t.findIndex(i=>i.item.type==="checkpoint"&&i.item.data.id===e);if(s===-1)throw new Error(`Checkpoint not found: ${e}`);let n=t.slice(0,s+1),o=t.length-n.length;return await this.writeAllItems(n),o}async getCheckpoints(){await this.ensureInitialized();let e=await this.readAllItems(),t=[];for(let s of e)if(s.item.type==="checkpoint"){let n=s.item;t.push({id:n.data.id,name:n.data.name,timestamp:s.timestamp});}return t}async clearSession(){try{await Z__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 s of e)s.item.type==="message"&&t.push(s.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((s,n)=>({item:s.item,timestamp:s.timestamp??Date.now(),seq:n}));await this.writeAllItems(t),this.initialized=true;}static async listSessions(e){let t=e||Y__default.join(js.homedir(),".neox","sessions");try{return (await Z__default.readdir(t)).filter(n=>n.endsWith(".jsonl")).map(n=>n.replace(".jsonl",""))}catch{return []}}static async getMostRecentId(e){let t=e||Y__default.join(js.homedir(),".neox","sessions");try{let n=(await Z__default.readdir(t)).filter(i=>i.endsWith(".jsonl"));if(n.length===0)return null;let o=await Promise.all(n.map(async i=>({name:i.replace(".jsonl",""),mtime:(await Z__default.stat(Y__default.join(t,i))).mtime})));return o.sort((i,a)=>a.mtime.getTime()-i.mtime.getTime()),o[0].name}catch{return null}}static async deleteSession(e,t){let s=t||Y__default.join(js.homedir(),".neox","sessions"),n=Y__default.join(s,`${e}.jsonl`);try{return await Z__default.unlink(n),!0}catch{return false}}static async getSessionInfo(e,t){let s=t||Y__default.join(js.homedir(),".neox","sessions"),n=Y__default.join(s,`${e}.jsonl`);try{let o=await Z__default.stat(n);return {sessionId:e,filePath:n,size:o.size,createdAt:o.birthtime,updatedAt:o.mtime}}catch{return null}}static create(e){return new r({sessionId:rs(),...e})}};le();function z(r,e,t,s){return {type:"ephemeral",status:e,tool:r,summary:t,final:e==="success"||e==="already_done",...s}}function de(r,e,t,s,n){return {type:"contextual",status:e,tool:r,summary:t,content:s,...n}}function Rt(r,e,t,s){return {type:"summarized",status:e,tool:r,summary:t,...s}}function la(r){g.info("TOOL_RESULT",`\u{1F504} getResultForLLM input: ${r.tool}`,{type:r.type,status:r.status,tool:r.tool,hasContent:!!r.content,contentLength:r.content?.length||0,summary:r.summary?.substring(0,100)});let e;if(r.type==="ephemeral")if(r.status==="error")r.tool==="edit_file"?e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error,verify_hint:r.verify_hint,file_path:r.file_path,actual_content:r.actual_content,expected_start_line:r.expected_start_line,similar_matches:r.metadata?.similar_matches,suggestions:r.metadata?.suggestions}):e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error,verify_hint:r.verify_hint,file_path:r.file_path,similar_matches:r.metadata?.similar_matches,suggestions:r.metadata?.suggestions});else {let t=r.metadata?.edit_info;if(r.tool==="edit_file"&&t){let s=t.old_string?t.old_string.length>1e3?t.old_string.substring(0,1e3)+"...":t.old_string:void 0,n=t.new_string?t.new_string.length>1e3?t.new_string.substring(0,1e3)+"...":t.new_string:void 0;e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,final:r.final,file_path:r.file_path,old_string_preview:s,new_string_preview:n,start_line:t.start_line});}else e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,final:r.final,file_path:r.file_path});}else r.type==="summarized"?e=JSON.stringify({status:r.status,tool:r.tool,summary:r.summary,error:r.error}):e=JSON.stringify(r);return g.info("TOOL_RESULT",`\u2705 getResultForLLM output: ${r.tool}`,{type:r.type,tool:r.tool,llmResultLength:e.length,llmResultPreview:e.substring(0,500)}),e}var fo={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 yo(r){if(r in fo)return fo[r];let e=r.toLowerCase();for(let[t,s]of Object.entries(fo))if(t.toLowerCase()===e)return s;return "contextual"}function ca(r){return yo(r)==="contextual"}le();function Gs(r){if(!r)return 0;let e=0;for(let t of r){let s=t.codePointAt(0)||0;s>=19968&&s<=40959||s>=12288&&s<=12351||s>=65280&&s<=65519||s>=44032&&s<=55215?e+=.67:e+=.25;}return Math.ceil(e)}var Bs=class{messages=[];maxMessages;constructor(e=500){this.maxMessages=e;}add(e){let t=typeof e.content=="string"?e.content:JSON.stringify(e.content),s=Gs(t),n={...e,_timestamp:Date.now(),_estimatedTokens:s};if(this.messages.push(n),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0&&process.env.CLI_DEBUG==="1"&&g.debug("MEMORY","Assistant message with tool_calls added:",{toolCallCount:e.tool_calls.length,toolCallIds:e.tool_calls.map(o=>({id:o.id,name:o.function.name}))}),this.messages.length>this.maxMessages){let o=this.messages.filter(l=>l.role==="system"),a=this.messages.filter(l=>l.role!=="system").slice(-(this.maxMessages-o.length));this.messages=[...o,...a];}}addToolResult(e,t,s){let n=yo(t),o=null;try{let c=JSON.parse(s);c.type&&c.status&&c.summary&&(o=c);}catch{}let i,a=n;g.info("MEMORY","addToolResult: parsedResult\uFF1A"+o),g.info("MEMORY","addToolResult: effectiveResultType\uFF1A"+a),o?(a=o.type||n,i=la(o),g.info("MEMORY","\u7CBE\u7B80\u7ED3\u679C: content \uFF1A"+i),g.info("MEMORY",`addToolResult: ${t} parsed as ToolResult`,{parsedResult:JSON.stringify(o).substring(0,500),contentAfter:i.substring(0,500),rawLength:s.length,contentLength:i.length})):(i=s,g.debug("MEMORY",`addToolResult: ${t} using raw output`,{rawOutput:s.substring(0,500),rawLength:s.length}));let l={role:"tool",tool_call_id:e,name:t,content:i,_resultType:a,_toolName:t,_timestamp:Date.now(),_estimatedTokens:Gs(i)};if(process.env.CLI_DEBUG==="1"&&g.debug("MEMORY","Tool result message added:",{toolName:t,toolCallId:e,contentLength:i.length,contentPreview:i.substring(0,200)}),this.messages.push(l),this.messages.length>this.maxMessages){let c=this.messages.filter(d=>d.role==="system"),p=this.messages.filter(d=>d.role!=="system").slice(-(this.maxMessages-c.length));this.messages=[...c,...p];}}stripMetadata(e){let{_resultType:t,_toolName:s,_timestamp:n,_estimatedTokens:o,_tag:i,...a}=e;return a}getAll(){return this.messages.map(e=>this.stripMetadata(e))}getRawMessages(){return this.messages}getMessagesForLLM(){let e=this.messages.map(t=>this.stripMetadata(t));if(process.env.CLI_DEBUG==="1"){let t=e.filter(o=>o.role==="assistant"),s=e.filter(o=>o.role==="tool");g.debug("MEMORY","Messages for LLM:",{totalMessages:e.length,assistantCount:t.length,toolCount:s.length,messageSequence:e.map(o=>o.role).join(" -> ")}),e.slice(-5).forEach((o,i)=>{o.role==="assistant"&&o.tool_calls?g.debug("MEMORY",`Message ${e.length-5+i} (assistant):`,{toolCalls:o.tool_calls.map(a=>({id:a.id,name:a.function.name}))}):o.role==="tool"&&g.debug("MEMORY",`Message ${e.length-5+i} (tool):`,{name:o.name,tool_call_id:o.tool_call_id,contentLength:typeof o.content=="string"?o.content.length:0});});}return e}hasConversationMessages(){return this.messages.some(e=>e.role==="user"||e.role==="assistant")}upsertSystemTagged(e,t){let s=t.trim();if(!s){this.removeSystemTagged(e);return}let n=this.messages.findIndex(a=>a.role==="system"&&a._tag===e);if(n>=0){let a=this.messages[n];if(a.content===s)return;this.messages[n]={...a,content:s,_timestamp:Date.now(),_estimatedTokens:Gs(s)};return}let o={role:"system",content:s,_tag:e,_timestamp:Date.now(),_estimatedTokens:Gs(s)},i=this.getSystemInsertIndex();this.messages=[...this.messages.slice(0,i),o,...this.messages.slice(i)];}removeSystemTagged(e){let t=this.messages.length;this.messages=this.messages.filter(s=>!(s.role==="system"&&s._tag===e)),t!==this.messages.length&&process.env.CLI_DEBUG==="1"&&g.debug("MEMORY",`Removed system tag: ${e}`);}getSystemInsertIndex(){let e=0;for(;e<this.messages.length&&this.messages[e].role==="system";)e+=1;return e}cleanupEphemeral(){let e=this.messages.length,t=new Set;for(let s of this.messages)if(s.role==="assistant"&&s.tool_calls)for(let n of s.tool_calls)n.id&&t.add(n.id);return this.messages=this.messages.filter(s=>s._resultType!=="ephemeral"||s.role!=="tool"||!s.tool_call_id?true:t.has(s.tool_call_id)),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,s=0,n=0;for(let a of this.messages){let l=a._estimatedTokens||Gs(typeof a.content=="string"?a.content:JSON.stringify(a.content));t+=l,a.role==="tool"?(n++,s+=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 o=t>0?s/t:0,i=[];return o>.5?i.push(`Tool results\u5360\u7528 ${(o*100).toFixed(1)}% \u7684\u4E0A\u4E0B\u6587\uFF08\u8D85\u8FC750%\u8B66\u6212\u7EBF\uFF09`):o>.4&&i.push(`Tool results\u5360\u7528 ${(o*100).toFixed(1)}% \u7684\u4E0A\u4E0B\u6587\uFF08\u63A5\u8FD1\u8B66\u6212\u7EBF\uFF09`),t>18e4?i.push(`\u4E0A\u4E0B\u6587\u5DF2\u8FBE ${t} tokens\uFF08\u8D85\u8FC7180k\uFF0C\u5EFA\u8BAE\u6E05\u7406\uFF09`):t>15e4&&i.push(`\u4E0A\u4E0B\u6587\u5DF2\u8FBE ${t} tokens\uFF08\u63A5\u8FD1180k\uFF09`),n>100?i.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8FC7\u957F\uFF08${n} \u6761\uFF09`):n>60&&i.push(`\u5DE5\u5177\u8C03\u7528\u5386\u53F2\u8F83\u957F\uFF08${n} \u6761\uFF09`),e.ephemeral.count>10&&i.push(`\u79EF\u7D2F\u4E86 ${e.ephemeral.count} \u6761 ephemeral \u6D88\u606F\uFF0C\u5EFA\u8BAE\u6E05\u7406`),{totalTokens:t,toolResultTokens:s,toolResultRatio:o,messageCount:this.messages.length,toolMessageCount:n,warnings:i,shouldCompress:o>.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,s=Math.round(t/1024*10)/10,n=this.messages.length*150,o=t+n,i=Math.round(o/1024*10)/10;return {totalKB:i,messagesKB:s,messageCount:this.messages.length,averageKBPerMessage:this.messages.length>0?Math.round(i/this.messages.length*10)/10:0}}logMemoryStats(){let e=this.checkContextHealth(),t=this.getMemoryFootprint();g.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:[],s=t.filter(a=>a.role==="system"),n=t.filter(a=>a.role!=="system"),o=Math.max(0,this.maxMessages-s.length),i=o>0?n.slice(-o):[];this.messages=[...s,...i].map(a=>({...a,_timestamp:Date.now()}));}get length(){return this.messages.length}};var Et=class{directory;options;sessionCache=new Map;constructor(e){this.options=e||{},this.directory=e?.directory||Y__default.join(js.homedir(),".neox","sessions");}async getSession(e){if(this.sessionCache.has(e))return this.sessionCache.get(e);let t=new Gt({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 Z__default.mkdir(this.directory,{recursive:!0});let t=await Z__default.readdir(this.directory);for(let s of t){if(!s.endsWith(".jsonl"))continue;let n=s.replace(".jsonl",""),o=Y__default.join(this.directory,s);try{let i=await Z__default.stat(o),a=await this.readSessionMeta(o),l=await this.countItems(o);e.push({sessionId:n,createdAt:i.birthtime,updatedAt:i.mtime,itemCount:l,agentName:a?.agentName});}catch{}}}catch(t){if(t.code!=="ENOENT")throw t}return e.sort((t,s)=>s.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=Y__default.join(this.directory,`${e}.jsonl`);try{return await Z__default.unlink(t),!0}catch{return false}}async searchSessions(e){let t=await this.listSessions(),s=e.toLowerCase(),n=[];for(let o of t){if(o.sessionId.toLowerCase().includes(s)){n.push(o);continue}if(o.agentName?.toLowerCase().includes(s)){n.push(o);continue}let i=Y__default.join(this.directory,`${o.sessionId}.jsonl`);await this.searchInFile(i,s)&&n.push(o);}return n}async createSession(e){let t=e?.sessionId||rs(),s=new Gt({sessionId:t,directory:this.directory,agentName:e?.agentName||this.options.defaultAgentName,model:e?.model||this.options.defaultModel});return this.sessionCache.set(t,s),s}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(),s=Date.now()-e*24*60*60*1e3,n=0;for(let o of t)o.updatedAt.getTime()<s&&await this.deleteSession(o.sessionId)&&n++;return n}getDirectory(){return this.directory}async getSessionCount(){return (await this.listSessions()).length}async exportSession(e){let t=await this.getSession(e),s=await t.getItems(),n=await t.getMeta();return JSON.stringify({sessionId:e,meta:n,items:s,exportedAt:new Date().toISOString()},null,2)}async readSessionMeta(e){try{let t=createReadStream(e,{encoding:"utf-8"}),s=bo.createInterface({input:t,crlfDelay:1/0});for await(let n of s)if(n.trim())try{let o=JSON.parse(n);if(o.item?.type==="meta")return s.close(),o.item.data}catch{}}catch{}return null}async countItems(e){let t=0;try{let s=createReadStream(e,{encoding:"utf-8"}),n=bo.createInterface({input:s,crlfDelay:1/0});for await(let o of n)o.trim()&&t++;}catch{}return t}async searchInFile(e,t){try{let s=createReadStream(e,{encoding:"utf-8"}),n=bo.createInterface({input:s,crlfDelay:1/0});for await(let o of n)if(o.toLowerCase().includes(t))return n.close(),!0}catch{}return false}};var Nu={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}},Fu={timeout:3e4,maxMemoryMB:512,maxCPUPercent:50,allowNetwork:true,allowFileSystem:true,workingDirectory:process.cwd(),env:{},captureImages:false,maxOutputSize:1e4},rt=class{config;constructor(e={}){this.config={...Fu,...e};}async execute(e,t){let s=Date.now(),n=Nu[t];if(!n)return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Unsupported language: ${t}`};if(!await this.checkRuntimeAvailable(n.command))return {success:false,stdout:"",stderr:"",exitCode:1,executionTime:0,error:`Runtime not found: ${n.command}. Please install it first.`};let i=null;try{n.useTempFile&&(i=await this.createTempFile(e,n.extension));let a=n.args.map(h=>h.replace("{file}",i||"")),l=i?Y__default.dirname(i):this.config.workingDirectory,c=[n.command,...a].join(" "),u={...Object.fromEntries(Object.entries(process.env).filter(([h,f])=>f!==void 0)),...this.config.env};t==="python"&&this.config.captureImages&&(u.MPLBACKEND="Agg");let p=await this.executeCommand(n.command,a,u,l),d=[];this.config.captureImages&&i&&(d=await this.captureGeneratedImages(Y__default.dirname(i)));let m=Date.now()-s;return {...p,executionTime:m,command:c,workingDirectory:l,images:d&&d.length>0?d:void 0}}catch(a){let l=Date.now()-s;return {success:false,stdout:a.stdout||"",stderr:a.stderr||"",exitCode:a.exitCode||1,executionTime:l,error:a.message,timedOut:a.timedOut||false}}finally{i&&await this.cleanupTempFile(i);}}async checkRuntimeAvailable(e){try{return await execa(e,["--version"],{timeout:5e3}),!0}catch{return false}}async createTempFile(e,t){let s=await Z__default.mkdtemp(Y__default.join(js.tmpdir(),"neox-code-")),n=Y__default.join(s,`script${t}`);return await Z__default.writeFile(n,e,"utf-8"),n}async executeCommand(e,t,s,n){try{let{stdout:o,stderr:i,exitCode:a}=await execa(e,t,{timeout:this.config.timeout,cwd:n,env:s,all:!0,reject:!1}),l=this.truncateOutput(o),c=this.truncateOutput(i);return {success:a===0,stdout:l,stderr:c,exitCode:a||0}}catch(o){throw o.timedOut?{stdout:o.stdout||"",stderr:o.stderr||"",exitCode:-1,message:`Execution timed out after ${this.config.timeout}ms`,timedOut:true}:{stdout:o.stdout||"",stderr:o.stderr||"",exitCode:o.exitCode||1,message:o.message}}}truncateOutput(e){if(e.length<=this.config.maxOutputSize)return e;let t=Math.floor(this.config.maxOutputSize/2);return e.slice(0,t)+`
9
9
 
10
10
  ... [Truncated ${e.length-this.config.maxOutputSize} characters] ...
11
11
 
12
- `+e.slice(-t)}async captureGeneratedImages(e){try{let s=(await Z__default.readdir(e)).filter(i=>/\.(png|jpg|jpeg|svg)$/i.test(i)),n=[];for(let i of s){let o=Y__default.join(e,i),l=(await Z__default.readFile(o)).toString("base64");n.push({type:"base64",data:l,filename:i});}return n}catch{return []}}async cleanupTempFile(e){try{let t=Y__default.dirname(e);await Z__default.rm(t,{recursive:!0,force:!0});}catch{}}static formatResult(e){let t=[];return e.success?t.push(`\u2705 Code executed successfully
12
+ `+e.slice(-t)}async captureGeneratedImages(e){try{let s=(await Z__default.readdir(e)).filter(o=>/\.(png|jpg|jpeg|svg)$/i.test(o)),n=[];for(let o of s){let i=Y__default.join(e,o),l=(await Z__default.readFile(i)).toString("base64");n.push({type:"base64",data:l,filename:o});}return n}catch{return []}}async cleanupTempFile(e){try{let t=Y__default.dirname(e);await Z__default.rm(t,{recursive:!0,force:!0});}catch{}}static formatResult(e){let t=[];return e.success?t.push(`\u2705 Code executed successfully
13
13
  `):t.push(`\u274C Code execution failed
14
14
  `),t.push(`\u23F1\uFE0F Execution time: ${e.executionTime}ms`),t.push(`\u{1F522} Exit code: ${e.exitCode}`),(e.command||e.workingDirectory)&&(t.push(`
15
15
  \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(`
@@ -17,7 +17,7 @@ import*as vn from'fs';import vn__default,{realpathSync,readlinkSync,readdirSync,
17
17
  \u26A0\uFE0F Errors/Warnings:`),t.push("```"),t.push(e.stderr),t.push("```")),e.error&&(t.push(`
18
18
  \u274C Error:`),t.push(e.error)),e.images&&e.images.length>0&&(t.push(`
19
19
  \u{1F5BC}\uFE0F Generated ${e.images.length} image(s):`),e.images.forEach((s,n)=>{t.push(` ${n+1}. ${s.filename||"image"} (${s.type})`);})),t.join(`
20
- `)}},da=new rt;async function Ws(r,e,t){return (t?new rt(t):da).execute(r,e)}function bi(r){let e=new rt(r);return {name:"execute_code",description:`Execute code in multiple languages (Python, JavaScript, TypeScript, Bash/Shell).
20
+ `)}},ma=new rt;async function Hs(r,e,t){return (t?new rt(t):ma).execute(r,e)}function wo(r){let e=new rt(r);return {name:"execute_code",description:`Execute code in multiple languages (Python, JavaScript, TypeScript, Bash/Shell).
21
21
  Supports data analysis, calculations, file operations, and more.
22
22
  Can capture generated images (matplotlib plots, etc.) if configured.
23
23
 
@@ -25,13 +25,13 @@ Configuration:
25
25
  - Timeout: ${r?.timeout||3e4}ms
26
26
  - Network access: ${r?.allowNetwork!==false?"Enabled":"Disabled"}
27
27
  - File system access: ${r?.allowFileSystem!==false?"Enabled":"Disabled"}
28
- - Image capture: ${r?.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:s}){let n=await e.execute(t,s);return rt.formatResult(n)}}}var _i={name:"execute_python",description:`Execute Python code for calculations, data analysis, and scripting.
28
+ - Image capture: ${r?.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:s}){let n=await e.execute(t,s);return rt.formatResult(n)}}}var vo={name:"execute_python",description:`Execute Python code for calculations, data analysis, and scripting.
29
29
  Useful for: math calculations, data processing, file operations, web scraping, etc.
30
- 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:r,capture_images:e=false}){let t=await Ws(r,"python",{captureImages:e});return rt.formatResult(t)}},wi={name:"execute_javascript",description:`Execute JavaScript (Node.js) code for calculations, data processing, and scripting.
30
+ 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:r,capture_images:e=false}){let t=await Hs(r,"python",{captureImages:e});return rt.formatResult(t)}},To={name:"execute_javascript",description:`Execute JavaScript (Node.js) code for calculations, data processing, and scripting.
31
31
  Useful for: JSON processing, string manipulation, async operations, etc.
32
- 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:r}){let e=await Ws(r,"javascript");return rt.formatResult(e)}},vi={name:"execute_bash",description:`Execute Bash/Shell scripts for system operations and file management.
32
+ 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:r}){let e=await Hs(r,"javascript");return rt.formatResult(e)}},xo={name:"execute_bash",description:`Execute Bash/Shell scripts for system operations and file management.
33
33
  Useful for: file operations, text processing, system commands, git operations, etc.
34
- 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:r}){let e=await Ws(r,"bash");return rt.formatResult(e)}};bi({timeout:3e4,allowNetwork:true,allowFileSystem:true,captureImages:true,maxOutputSize:1e4});bi({timeout:1e4,allowNetwork:false,allowFileSystem:false,captureImages:false,maxOutputSize:5e3});var zn={name:"debug_in_browser",capabilities:["debug"],description:`\u5728\u771F\u5B9E\u6D4F\u89C8\u5668\u73AF\u5883\u4E2D\u6253\u5F00\u6307\u5B9A URL \u5E76\u6536\u96C6\u8C03\u8BD5\u4FE1\u606F\u3002
34
+ 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:r}){let e=await Hs(r,"bash");return rt.formatResult(e)}};wo({timeout:3e4,allowNetwork:true,allowFileSystem:true,captureImages:true,maxOutputSize:1e4});wo({timeout:1e4,allowNetwork:false,allowFileSystem:false,captureImages:false,maxOutputSize:5e3});var Jn={name:"debug_in_browser",capabilities:["debug"],description:`\u5728\u771F\u5B9E\u6D4F\u89C8\u5668\u73AF\u5883\u4E2D\u6253\u5F00\u6307\u5B9A URL \u5E76\u6536\u96C6\u8C03\u8BD5\u4FE1\u606F\u3002
35
35
 
36
36
  \u8FD9\u4E2A\u5DE5\u5177\u4F1A\uFF1A
37
37
  1. \u81EA\u52A8\u542F\u52A8 Chrome \u6D4F\u89C8\u5668\uFF08headless \u6A21\u5F0F\uFF09
@@ -162,7 +162,7 @@ auto_login: { username: "admin", password: "123456" }`,properties:{username:{typ
162
162
  - \u9700\u8981\u67E5\u770B\u9875\u9762\u5B9E\u9645\u6E32\u67D3\u6548\u679C\uFF08\u5E03\u5C40\u3001\u6837\u5F0F\u3001\u5185\u5BB9\uFF09
163
163
  - \u7528\u6237\u62A5\u544A UI \u663E\u793A\u95EE\u9898\u4F46\u6CA1\u6709\u63D0\u4F9B\u622A\u56FE
164
164
 
165
- \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\u540C\u65F6\u8BBE\u7F6E open_for_login: true \u4E0E allow_manual_login: true\uFF0C\u6B64\u53C2\u6570\u4F1A\u88AB\u5FFD\u7565",default:true}},required:[]},async function(r){throw new Error("debug_in_browser tool must be created via createDebugInBrowserTool(workspacePath) to provide workspace context")}};le();var Hs=join(homedir(),".neox","browser-profile");function Ti(){return Hs}function Jn(){return existsSync(Hs)||(mkdirSync(Hs,{recursive:true}),g.info("CHROME",`Created browser profile directory: ${Hs}`)),Hs}async function ha(){let r=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"]}[r]||[];for(let s of t)if(existsSync(s))return g.info("CHROME",`Found Chrome at: ${s}`),{path:s,version:"unknown",available:true};return g.warn("CHROME","No Chrome installation found"),null}async function xi(r={}){let{headless:e=true,useProfile:t=true}=r,s=await ha();if(!s)throw new Error("Chrome not found. Please install Google Chrome from https://www.google.com/chrome/");g.info("CHROME",`Launching Chrome (headless: ${e}, useProfile: ${t})...`);let n={executablePath:s.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=Jn();n.userDataDir=o,g.info("CHROME",`Using profile directory: ${o}`);}let i=await Bu.launch(n);return g.info("CHROME","Chrome launched successfully"),i}le();var Wu=["xhr","fetch"],ga=["stylesheet","script","image","font","media"];function Hu(r,e){return r?e==="error"?r>=400:e==="4xx"?r>=400&&r<500:e==="5xx"?r>=500:e.split(",").map(s=>parseInt(s.trim(),10)).includes(r):false}async function Kn(r,e,t){let s=Date.now(),n={xhr_only:true,include_body:true,body_max_length:5e3,max_results:20,...t.network_filter},i=t.network_capture_mode||"cdp",o=[],a=[],c=new Map,u=new Map,p=`
165
+ \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\u540C\u65F6\u8BBE\u7F6E open_for_login: true \u4E0E allow_manual_login: true\uFF0C\u6B64\u53C2\u6570\u4F1A\u88AB\u5FFD\u7565",default:true}},required:[]},async function(r){throw new Error("debug_in_browser tool must be created via createDebugInBrowserTool(workspacePath) to provide workspace context")}};le();var Bt=null;function ga(){if(Bt!==null)return Bt;if(process.platform!=="linux")return Bt=false,false;if(process.env.WSL_DISTRO_NAME||process.env.WSLENV||process.env.WSL_INTEROP)return Bt=true,true;try{let r=Tn__default.readFileSync("/proc/version","utf-8").toLowerCase();if(r.includes("microsoft")||r.includes("wsl"))return Bt=!0,!0}catch{}try{if(Tn__default.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop"))return Bt=!0,!0}catch{}return Bt=false,false}var qs=join(homedir(),".neox","browser-profile");function So(){return qs}function Kn(){return existsSync(qs)||(mkdirSync(qs,{recursive:true}),g.info("CHROME",`Created browser profile directory: ${qs}`)),qs}async function ya(){let r=platform(),e={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"],wsl:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe","/mnt/c/Users/"+(process.env.USER||"")+"/AppData/Local/Google/Chrome/Application/chrome.exe"]},t;ga()?(t=[...e.linux||[],...e.wsl||[]],g.debug("CHROME","WSL detected, checking both Linux and Windows Chrome paths")):t=e[r]||[];for(let s of t)if(existsSync(s))return g.info("CHROME",`Found Chrome at: ${s}`),{path:s,version:"unknown",available:true};return g.warn("CHROME","No Chrome installation found"),null}async function ko(r={}){let{headless:e=true,useProfile:t=true}=r,s=await ya();if(!s)throw new Error("Chrome not found. Please install Google Chrome from https://www.google.com/chrome/");g.info("CHROME",`Launching Chrome (headless: ${e}, useProfile: ${t})...`);let n={executablePath:s.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 i=Kn();n.userDataDir=i,g.info("CHROME",`Using profile directory: ${i}`);}let o=await qu.launch(n);return g.info("CHROME","Chrome launched successfully"),o}le();var zu=["xhr","fetch"],ba=["stylesheet","script","image","font","media"];function Ju(r,e){return r?e==="error"?r>=400:e==="4xx"?r>=400&&r<500:e==="5xx"?r>=500:e.split(",").map(s=>parseInt(s.trim(),10)).includes(r):false}async function Vn(r,e,t){let s=Date.now(),n={xhr_only:true,include_body:true,body_max_length:5e3,max_results:20,...t.network_filter},o=t.network_capture_mode||"cdp",i=[],a=[],c=new Map,u=new Map,p=`
166
166
  (function() {
167
167
  if (window.__NEOX_INJECTED__) return;
168
168
  window.__NEOX_CONSOLE_LOGS__ = window.__NEOX_CONSOLE_LOGS__ || [];
@@ -219,14 +219,14 @@ auto_login: { username: "admin", password: "123456" }`,properties:{username:{typ
219
219
 
220
220
  window.__NEOX_INJECTED__ = true;
221
221
  })();
222
- `;(t.collect_console!==false||t.collect_errors!==false)&&(await r.evaluateOnNewDocument(p),r.on("framenavigated",async S=>{if(S===r.mainFrame())try{await S.evaluate(p),g.debug("BROWSER",`Re-injected script after navigation to ${S.url()}`);}catch{}}));let d=await r.createCDPSession();await d.send("Runtime.enable"),await d.send("Log.enable"),t.collect_network!==false&&(i==="cdp"||i==="both")&&(await d.send("Network.enable"),g.debug("BROWSER","Network domain enabled (CDP mode)"));let m=S=>{let{type:C,args:w,timestamp:T}=S,B={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[C]||"log",E=w.map(L=>L.value!==void 0?String(L.value):L.description?L.description:L.preview?.properties?JSON.stringify(L.preview.properties.reduce((N,$)=>(N[$.name]=$.value,N),{})):String(L.type)).join(" ");o.push({type:B,timestamp:T?Math.floor(T):Date.now(),message:E}),g.debug("BROWSER",`[CDP] ${B}: ${E.substring(0,100)}`);},h=S=>{let{exceptionDetails:C}=S,w=C.exception?.description||C.text||"Unknown error";a.push({type:"exception",message:w,stack:C.stackTrace?.callFrames?.map(T=>` at ${T.functionName||"(anonymous)"} (${T.url}:${T.lineNumber}:${T.columnNumber})`).join(`
222
+ `;(t.collect_console!==false||t.collect_errors!==false)&&(await r.evaluateOnNewDocument(p),r.on("framenavigated",async S=>{if(S===r.mainFrame())try{await S.evaluate(p),g.debug("BROWSER",`Re-injected script after navigation to ${S.url()}`);}catch{}}));let d=await r.createCDPSession();await d.send("Runtime.enable"),await d.send("Log.enable"),t.collect_network!==false&&(o==="cdp"||o==="both")&&(await d.send("Network.enable"),g.debug("BROWSER","Network domain enabled (CDP mode)"));let m=S=>{let{type:C,args:w,timestamp:T}=S,B={log:"log",debug:"debug",info:"info",warning:"warn",error:"error",trace:"trace",assert:"error"}[C]||"log",E=w.map(L=>L.value!==void 0?String(L.value):L.description?L.description:L.preview?.properties?JSON.stringify(L.preview.properties.reduce((N,$)=>(N[$.name]=$.value,N),{})):String(L.type)).join(" ");i.push({type:B,timestamp:T?Math.floor(T):Date.now(),message:E}),g.debug("BROWSER",`[CDP] ${B}: ${E.substring(0,100)}`);},h=S=>{let{exceptionDetails:C}=S,w=C.exception?.description||C.text||"Unknown error";a.push({type:"exception",message:w,stack:C.stackTrace?.callFrames?.map(T=>` at ${T.functionName||"(anonymous)"} (${T.url}:${T.lineNumber}:${T.columnNumber})`).join(`
223
223
  `)||"",file:C.url,line:C.lineNumber,column:C.columnNumber,timestamp:Date.now()}),g.debug("BROWSER",`[CDP Exception] ${w}`);},f=S=>{let{entry:C}=S,w=C.level;w==="error"?C.text&&(C.text.includes("Uncaught")||C.text.includes("Error"))?(a.push({type:"exception",message:C.text,stack:C.stackTrace?.callFrames?.map(T=>` at ${T.functionName||"(anonymous)"} (${T.url}:${T.lineNumber}:${T.columnNumber})`).join(`
224
- `)||"",file:C.url,line:C.lineNumber,timestamp:Date.now()}),g.debug("BROWSER",`[CDP Log Error] ${C.text}`)):(o.push({type:"error",timestamp:Date.now(),message:C.text}),g.debug("BROWSER",`[CDP Log] error: ${C.text}`)):w==="warning"&&o.push({type:"warn",timestamp:Date.now(),message:C.text});};if(t.collect_console!==false&&d.on("Runtime.consoleAPICalled",m),t.collect_errors!==false&&(d.on("Runtime.exceptionThrown",h),d.on("Log.entryAdded",f),r.on("pageerror",S=>{let C=S;a.push({type:"exception",message:C.message,stack:C.stack||"",timestamp:Date.now()}),g.debug("BROWSER",`[Puppeteer pageerror] ${C.message}`);}),r.on("requestfailed",S=>{let C=S.failure();a.push({type:"browser_error",message:`Request failed: ${C?.errorText||"Unknown error"}`,stack:"",file:S.url(),timestamp:Date.now()});})),t.collect_network!==false&&(i==="cdp"||i==="both")&&(d.on("Network.requestWillBeSent",S=>{let C={url:S.request.url,method:S.request.method,resource_type:S.type?.toLowerCase()||"other",request_headers:S.request.headers,timing:{start:S.timestamp*1e3,end:0,duration:0}},w=S.type?.toLowerCase()||"other";if(!(n.xhr_only&&!["xhr","fetch"].includes(w))&&!(!n.xhr_only&&ga.includes(w))){if(S.request.postData){let T=n.body_max_length||5e3,M=S.request.postData;M.length>T?C.request_body=M.substring(0,T)+"...[truncated]":C.request_body=M;}u.set(S.requestId,C),g.debug("BROWSER",`[CDP Network] ${w.toUpperCase()} ${C.method} ${C.url}`);}}),d.on("Network.responseReceived",S=>{let C=u.get(S.requestId);C&&C.timing&&(C.status=S.response.status,C.status_text=S.response.statusText,C.response_headers=S.response.headers,C.timing.end=S.timestamp*1e3,C.timing.duration=C.timing.end-C.timing.start,g.debug("BROWSER",`[CDP Network] Response ${C.status} ${C.url} (${C.timing.duration.toFixed(0)}ms)`));}),d.on("Network.loadingFailed",S=>{let C=u.get(S.requestId);C&&(C.error=S.errorText,C.timing&&(C.timing.end=S.timestamp*1e3,C.timing.duration=C.timing.end-C.timing.start),g.debug("BROWSER",`[CDP Network] Failed ${C.url}: ${C.error}`));})),t.collect_console!==false&&r.on("console",S=>{let C=S.type();o.push({type:C,timestamp:Date.now(),message:S.text(),args:S.args().map(w=>w.toString())}),g.debug("BROWSER",`[Puppeteer console] ${C}: ${S.text().substring(0,100)}`);}),t.collect_network!==false&&(i==="puppeteer"||i==="both")){let S=null;if(n.url_pattern)try{S=new RegExp(n.url_pattern,"i");}catch{g.warn("BROWSER",`Invalid URL pattern: ${n.url_pattern}`);}r.on("request",C=>{let w=C.url(),T=C.resourceType();if(n.xhr_only&&!Wu.includes(T)||!n.xhr_only&&ga.includes(T)||S&&!S.test(w))return;`${C.method()}-${w}-${Date.now()}`;let B={url:w,method:C.method(),resource_type:T,request_headers:C.headers(),timing:{start:Date.now(),end:0,duration:0}},E=C.postData();if(E){let L=n.body_max_length||5e3;E.length>L?B.request_body=E.substring(0,L)+"...[truncated]":B.request_body=E;}c.set(w,B),g.debug("BROWSER",`[Network] ${T.toUpperCase()} ${C.method()} ${w}`);}),r.on("response",async C=>{let w=C.url(),T=c.get(w);if(!T||!T.timing)return;T.status=C.status(),T.status_text=C.statusText(),T.response_headers=C.headers(),T.timing.end=Date.now(),T.timing.duration=T.timing.end-T.timing.start;let M=T.status>=400;if(n.include_body&&(M||n.status_filter))try{let E=C.headers()["content-type"]||"";if(E.includes("json")||E.includes("text")||E.includes("html")){let L=await C.text(),N=n.body_max_length||5e3;L.length>N?(T.response_body=L.substring(0,N),T.response_truncated=!0):T.response_body=L;}}catch(E){g.debug("BROWSER",`Failed to get response body for ${w}: ${E}`);}g.debug("BROWSER",`[Network] Response ${T.status} ${w} (${T.timing.duration}ms)`);}),r.on("requestfailed",C=>{let w=C.url(),T=c.get(w),M=C.failure();T&&(T.error=M?.errorText||"Request failed",T.timing&&(T.timing.end=Date.now(),T.timing.duration=T.timing.end-T.timing.start)),a.push({type:"browser_error",message:`Request failed: ${M?.errorText||"Unknown error"}`,stack:"",file:w,timestamp:Date.now()});});}g.info("BROWSER",`Navigating to: ${e}`),await r.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await d.send("Runtime.enable"),await d.send("Log.enable"),g.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{g.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await r.evaluate(p),g.debug("BROWSER","Ensured script injection after page.goto");}catch{g.debug("BROWSER","Script already injected or page not ready");}let y=t.wait_time||3e3;if(g.info("BROWSER",`Waiting ${y}ms for async content...`),await new Promise(S=>setTimeout(S,y)),g.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{g.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let S=await r.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));g.debug("BROWSER",`Extracted ${S.consoleLogs.length} console logs and ${S.errors.length} errors from injected script`);for(let T of S.consoleLogs)g.debug("BROWSER",` [${T.type}] ${T.message?.substring(0,100)}`);let C=new Map;for(let T of S.consoleLogs){let M=`${T.type}:${T.message}`;C.has(M)||C.set(M,{type:T.type,timestamp:T.timestamp,message:T.message});}for(let T of o){let M=`${T.type}:${T.message}`;C.has(M)||C.set(M,T);}o.length=0,o.push(...Array.from(C.values()));let w=new Map;for(let T of S.errors){let M=`${T.type}:${T.message}`;w.has(M)||w.set(M,{type:T.type,message:T.message,stack:T.stack||"",file:T.file,line:T.line,column:T.column,timestamp:T.timestamp});}for(let T of a){let M=`${T.type}:${T.message}`;w.has(M)||w.set(M,T);}a.length=0,a.push(...Array.from(w.values())),g.info("BROWSER",`Final: ${o.length} console logs, ${a.length} errors`);}catch(S){g.error("BROWSER","Failed to extract injected logs",{error:S});}let b;if(t.collect_performance!==false)try{let S=await r.metrics(),C=await r.evaluate(()=>{let w=window.performance,T=w.timing,M=w.getEntriesByType("paint"),B=document.querySelectorAll("*"),E=0,L=0,N=0,$=Math.min(1e3,B.length),G=Math.max(1,Math.floor(B.length/$));for(let A=0;A<B.length;A+=G){let P=B[A],K=window.getComputedStyle(P);K.display!=="none"&&K.visibility!=="hidden"&&K.opacity!=="0"?E++:L++;let U=0,ne=P.parentElement;for(;ne;)U++,ne=ne.parentElement;N=Math.max(N,U);}let X=B.length/$;return E=Math.round(E*X),L=Math.round(L*X),{domContentLoaded:T.domContentLoadedEventEnd-T.navigationStart,loadComplete:T.loadEventEnd-T.navigationStart,paintMetrics:{first_paint:M.find(A=>A.name==="first-paint")?.startTime||0,first_contentful_paint:M.find(A=>A.name==="first-contentful-paint")?.startTime||0},memory:w.memory?{used_heap:w.memory.usedJSHeapSize,total_heap:w.memory.totalJSHeapSize,heap_limit:w.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:E,hidden_nodes:L,max_depth:N}}});b={dom_content_loaded:C.domContentLoaded,load_complete:C.loadComplete,dom_nodes:S.Nodes||0,js_heap_size:S.JSHeapUsedSize||0,event_listeners:S.JSEventListeners||0,paint_metrics:C.paintMetrics,memory:C.memory,dom_stats:C.domStats},g.info("BROWSER",`Performance: ${b.dom_nodes} nodes, ${(b.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(S){g.error("BROWSER","Failed to collect performance metrics",{error:S});}let _;if(t.take_screenshot===true)try{_=await r.screenshot({encoding:"base64"});}catch(S){g.error("BROWSER","Failed to capture screenshot",{error:S});}try{await d.detach();}catch{}if(i==="cdp"||i==="both")for(let[S,C]of u.entries())Array.from(c.values()).find(T=>T.url===C.url)||c.set(S,C);let v=Array.from(c.values());i==="cdp"&&(v=Array.from(u.values()));let k=v.length;n.status_filter&&(v=v.filter(S=>Hu(S.status,n.status_filter)));let R=v.filter(S=>S.error||S.status&&S.status>=400).length;v.sort((S,C)=>{let w=S.error||S.status&&S.status>=400,T=C.error||C.status&&C.status>=400;return w&&!T?-1:!w&&T?1:(S.timing?.start||0)-(C.timing?.start||0)});let O=n.max_results||20;v.length>O&&(v=v.slice(0,O));let W={total_captured:k,filtered_count:v.length,error_count:R};g.info("BROWSER",`Network: ${k} captured, ${v.length} returned, ${R} errors`);let F=Date.now()-s;return {console_logs:o,errors:a,network_requests:v,network_stats:W,performance:b,screenshot:_,load_time:F}}function Vn(r){let e=[];r.errors&&r.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${r.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),r.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=r.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 s=r.console_logs?.filter(o=>o.type==="warn")||[];s.length>0&&(e.push(`\u26A0\uFE0F ${s.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),s.slice(0,3).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`);}),e.push(""));let n=r.console_logs?.filter(o=>o.type==="debug")||[];if(n.length>0&&(e.push(`\u{1F50D} ${n.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),n.slice(0,3).forEach((o,a)=>{e.push(` ${a+1}. ${o.message}`);}),e.push("")),r.errors?.length===0&&t.length===0&&s.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),r.network_stats){let o=r.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=r.network_requests?.filter(o=>o.error||o.status&&o.status>=400)||[];if(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("")),r.performance){let o=r.performance;if(o.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${o.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):o.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${o.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):o.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${o.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),o.dom_stats){let a=o.dom_stats,l=a.hidden_nodes/o.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${a.visible_nodes.toLocaleString()}, \u9690\u85CF: ${a.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${a.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),a.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${a.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(o.memory){let a=o.memory.used_heap/1024/1024,l=o.memory.heap_limit/1024/1024,c=o.memory.used_heap/o.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${a.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):a>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${a.toFixed(1)}MB`);}else o.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(o.js_heap_size/1024/1024).toFixed(1)}MB)`);o.paint_metrics&&o.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${o.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),o.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${o.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
225
- `)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}async function fa(r){let e=await qu(r);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await zu(r);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await Ju(r);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await Ku(r);return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"default"}}async function qu(r){try{let e=join(r,"vite.config.js"),s=(await readFile(e,"utf-8")).match(/server\s*:\s*\{[^}]*port\s*:\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function zu(r){try{let e=join(r,"package.json"),t=await readFile(e,"utf-8"),n=JSON.parse(t).scripts?.dev||"",i=n.match(/--port\s+(\d+)/);if(i)return parseInt(i[1]);let o=n.match(/PORT=(\d+)/);return o?parseInt(o[1]):null}catch{return null}}async function Ju(r){try{let e=join(r,".env"),s=(await readFile(e,"utf-8")).match(/(?:VITE_)?PORT\s*=\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function Ku(r){try{let e=join(r,"package.json"),t=await readFile(e,"utf-8"),s=JSON.parse(t),n={...s.dependencies,...s.devDependencies};return n.vite?5173:n.next||n["react-scripts"]?3e3:n.vue?8080:n.nuxt?3e3:n.svelte?5e3:3e3}catch{return 3e3}}async function Si(r,e=3e3){try{let t=new AbortController,s=setTimeout(()=>t.abort(),e),n=await fetch(r,{method:"HEAD",signal:t.signal});return clearTimeout(s),n.ok}catch{return false}}async function ki(r){let e=await fa(r);if(await Si(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let i=`http://localhost:${n}`;if(await Si(i))return {url:i,port:n,protocol:"http",source:"default"}}return null}le();var Qu="headers.json";function ya(r){try{return new URL(r).hostname}catch{return r}}function ba(){let r=Jn();return join(r,Qu)}function _a(){let r=ba();if(!existsSync(r))return {};try{let e=readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return g.warn("HEADERS","Failed to read headers config",{error:e}),{}}}function wa(r){let e=ba();try{let t=JSON.stringify(r,null,2);writeFileSync(e,t,"utf-8"),g.info("HEADERS","Headers config saved",{path:e});}catch(t){g.error("HEADERS","Failed to save headers config",{error:t});}}function Zn(r,e){let t=ya(r),s=_a(),n=ep(e);if(Object.keys(n).length===0){g.info("HEADERS","No headers to save for domain",{domain:t});return}s[t]={headers:n,lastUsed:Date.now(),createdAt:s[t]?.createdAt||Date.now(),url:r},wa(s),g.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(n).length});}function Ci(r){let e=ya(r),t=_a(),s=t[e];return s?(s.lastUsed=Date.now(),wa(t),g.info("HEADERS","Retrieved headers for domain",{domain:e,headerCount:Object.keys(s.headers).length}),s.headers):(g.info("HEADERS","No saved headers for domain",{domain:e}),null)}function ep(r){let e={},t=[/^authorization$/i,/^x-/i,/^cookie$/i,/^token$/i,/^auth/i,/^api-key$/i,/^api_key$/i,/^apikey$/i],s=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[n,i]of Object.entries(r)){let o=n.toLowerCase();if(s.has(o))continue;t.some(l=>l.test(n))&&(e[n]=i);}return e}var tp=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],sp=['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")'],np=['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"]'],rp=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],ip=['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"];async function va(r,e){let t={},s=false,n=o=>{if(s)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(s)return;let a=o.status();o.url();let c=o.request().resourceType();a>=200&&a<300&&(c==="xhr"||c==="fetch")&&(s=true);};return r.on("request",n),r.on("response",i),t}async function op(r,e){let t=Ci(e);return !t||Object.keys(t).length===0?false:(await r.setExtraHTTPHeaders(t),true)}async function Ri(r,e){let t=r.url(),s=t.toLowerCase();if(t!==e&&tp.some(i=>s.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 n of sp)if(await r.$(n))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"login_form",reason:`\u9875\u9762\u5305\u542B\u767B\u5F55\u8868\u5355\u5143\u7D20: ${n}`}}catch{}try{let n=await r.title(),i=n.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: "${n}"`}}catch{}return {detected:false,original_url:e}}async function ap(r,e,t){try{t?.("auto_login_start",{message:"\u6B63\u5728\u81EA\u52A8\u586B\u5199\u767B\u5F55\u8868\u5355..."});let s=null;if(e.username_selector&&(s=await r.$(e.username_selector)),!s)for(let o of np)try{if(s=await r.$(o),s)break}catch{}if(!s)return {success:!1,error:"\u627E\u4E0D\u5230\u7528\u6237\u540D\u8F93\u5165\u6846"};let n=null;if(e.password_selector&&(n=await r.$(e.password_selector)),!n)for(let o of rp)try{if(n=await r.$(o),n)break}catch{}if(!n)return {success:!1,error:"\u627E\u4E0D\u5230\u5BC6\u7801\u8F93\u5165\u6846"};let i=null;if(e.submit_selector&&(i=await r.$(e.submit_selector)),!i)for(let o of ip)try{if(i=await r.$(o),i)break}catch{}return i?(await s.click({clickCount:3}),await s.type(e.username,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u7528\u6237\u540D"}),await n.click({clickCount:3}),await n.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([r.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(s){return {success:false,error:String(s)}}}async function Qn(r,e,t){let s=null,i=r.open_for_login===true&&r.allow_manual_login===true,o=r.auto_login&&r.auto_login.username&&r.auto_login.password;try{let a=r.url||"auto";if(a==="auto"){t?.("detecting");let y=await ki(e);if(!y){let b={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:b.error}),b}a=y.url,t?.("detected",{url:a});}t?.("launching",{url:a});let l=i?!1:r.headless!==!1,c=r.use_profile!==!1;s=await xi({headless:l,useProfile:c}),t?.("loading",{url:a});let u=await s.newPage(),p=await op(u,a);p&&t?.("headers_applied",{message:"\u5DF2\u5E94\u7528\u4FDD\u5B58\u7684\u8BA4\u8BC1 headers"}),await u.goto(a,{waitUntil:"networkidle0",timeout:3e4});let d=await Ri(u,a);if(o&&d.detected){t?.("auto_login",{message:"\u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0C\u6B63\u5728\u81EA\u52A8\u767B\u5F55..."});let y=va(u,a),b=await ap(u,r.auto_login,t);if(!b.success)return await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25: ${b.error}`,login_redirect:d,needs_login:!0};let _=await Ri(u,a),v=await y;if(_.detected)return await s.close(),{success:!1,url:a,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:_,needs_login:!0};{Object.keys(v).length>0&&(Zn(a,v),t?.("headers_saved",{headerCount:Object.keys(v).length})),t?.("auto_login_success",{message:"\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F"}),t?.("collecting",{url:a});let k=await Kn(u,a,{wait_time:r.wait_time,collect_console:r.collect_console,collect_errors:r.collect_errors,collect_network:r.collect_network,collect_performance:r.collect_performance,take_screenshot:r.take_screenshot,network_capture_mode:r.network_capture_mode||"cdp",network_filter:{xhr_only:r.network_xhr_only,url_pattern:r.network_url_pattern,status_filter:r.network_status_filter,include_body:r.network_include_body,body_max_length:r.network_body_max_length,max_results:r.network_max_results}}),R=Vn({console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,network_stats:k.network_stats,performance:k.performance});return await s.close(),{success:!0,url:a,load_time:k.load_time,timestamp:Date.now(),console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,performance:k.performance,screenshot:k.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
224
+ `)||"",file:C.url,line:C.lineNumber,timestamp:Date.now()}),g.debug("BROWSER",`[CDP Log Error] ${C.text}`)):(i.push({type:"error",timestamp:Date.now(),message:C.text}),g.debug("BROWSER",`[CDP Log] error: ${C.text}`)):w==="warning"&&i.push({type:"warn",timestamp:Date.now(),message:C.text});};if(t.collect_console!==false&&d.on("Runtime.consoleAPICalled",m),t.collect_errors!==false&&(d.on("Runtime.exceptionThrown",h),d.on("Log.entryAdded",f),r.on("pageerror",S=>{let C=S;a.push({type:"exception",message:C.message,stack:C.stack||"",timestamp:Date.now()}),g.debug("BROWSER",`[Puppeteer pageerror] ${C.message}`);}),r.on("requestfailed",S=>{let C=S.failure();a.push({type:"browser_error",message:`Request failed: ${C?.errorText||"Unknown error"}`,stack:"",file:S.url(),timestamp:Date.now()});})),t.collect_network!==false&&(o==="cdp"||o==="both")&&(d.on("Network.requestWillBeSent",S=>{let C={url:S.request.url,method:S.request.method,resource_type:S.type?.toLowerCase()||"other",request_headers:S.request.headers,timing:{start:S.timestamp*1e3,end:0,duration:0}},w=S.type?.toLowerCase()||"other";if(!(n.xhr_only&&!["xhr","fetch"].includes(w))&&!(!n.xhr_only&&ba.includes(w))){if(S.request.postData){let T=n.body_max_length||5e3,M=S.request.postData;M.length>T?C.request_body=M.substring(0,T)+"...[truncated]":C.request_body=M;}u.set(S.requestId,C),g.debug("BROWSER",`[CDP Network] ${w.toUpperCase()} ${C.method} ${C.url}`);}}),d.on("Network.responseReceived",S=>{let C=u.get(S.requestId);C&&C.timing&&(C.status=S.response.status,C.status_text=S.response.statusText,C.response_headers=S.response.headers,C.timing.end=S.timestamp*1e3,C.timing.duration=C.timing.end-C.timing.start,g.debug("BROWSER",`[CDP Network] Response ${C.status} ${C.url} (${C.timing.duration.toFixed(0)}ms)`));}),d.on("Network.loadingFailed",S=>{let C=u.get(S.requestId);C&&(C.error=S.errorText,C.timing&&(C.timing.end=S.timestamp*1e3,C.timing.duration=C.timing.end-C.timing.start),g.debug("BROWSER",`[CDP Network] Failed ${C.url}: ${C.error}`));})),t.collect_console!==false&&r.on("console",S=>{let C=S.type();i.push({type:C,timestamp:Date.now(),message:S.text(),args:S.args().map(w=>w.toString())}),g.debug("BROWSER",`[Puppeteer console] ${C}: ${S.text().substring(0,100)}`);}),t.collect_network!==false&&(o==="puppeteer"||o==="both")){let S=null;if(n.url_pattern)try{S=new RegExp(n.url_pattern,"i");}catch{g.warn("BROWSER",`Invalid URL pattern: ${n.url_pattern}`);}r.on("request",C=>{let w=C.url(),T=C.resourceType();if(n.xhr_only&&!zu.includes(T)||!n.xhr_only&&ba.includes(T)||S&&!S.test(w))return;`${C.method()}-${w}-${Date.now()}`;let B={url:w,method:C.method(),resource_type:T,request_headers:C.headers(),timing:{start:Date.now(),end:0,duration:0}},E=C.postData();if(E){let L=n.body_max_length||5e3;E.length>L?B.request_body=E.substring(0,L)+"...[truncated]":B.request_body=E;}c.set(w,B),g.debug("BROWSER",`[Network] ${T.toUpperCase()} ${C.method()} ${w}`);}),r.on("response",async C=>{let w=C.url(),T=c.get(w);if(!T||!T.timing)return;T.status=C.status(),T.status_text=C.statusText(),T.response_headers=C.headers(),T.timing.end=Date.now(),T.timing.duration=T.timing.end-T.timing.start;let M=T.status>=400;if(n.include_body&&(M||n.status_filter))try{let E=C.headers()["content-type"]||"";if(E.includes("json")||E.includes("text")||E.includes("html")){let L=await C.text(),N=n.body_max_length||5e3;L.length>N?(T.response_body=L.substring(0,N),T.response_truncated=!0):T.response_body=L;}}catch(E){g.debug("BROWSER",`Failed to get response body for ${w}: ${E}`);}g.debug("BROWSER",`[Network] Response ${T.status} ${w} (${T.timing.duration}ms)`);}),r.on("requestfailed",C=>{let w=C.url(),T=c.get(w),M=C.failure();T&&(T.error=M?.errorText||"Request failed",T.timing&&(T.timing.end=Date.now(),T.timing.duration=T.timing.end-T.timing.start)),a.push({type:"browser_error",message:`Request failed: ${M?.errorText||"Unknown error"}`,stack:"",file:w,timestamp:Date.now()});});}g.info("BROWSER",`Navigating to: ${e}`),await r.goto(e,{waitUntil:"networkidle2",timeout:3e4});try{await d.send("Runtime.enable"),await d.send("Log.enable"),g.debug("BROWSER","Re-enabled Runtime and Log domains after navigation");}catch{g.debug("BROWSER","Failed to re-enable CDP domains (may already be enabled)");}if(t.collect_console!==false||t.collect_errors!==false)try{await r.evaluate(p),g.debug("BROWSER","Ensured script injection after page.goto");}catch{g.debug("BROWSER","Script already injected or page not ready");}let y=t.wait_time||3e3;if(g.info("BROWSER",`Waiting ${y}ms for async content...`),await new Promise(S=>setTimeout(S,y)),g.debug("BROWSER","Starting to extract injected logs..."),t.collect_console!==false||t.collect_errors!==false)try{g.debug("BROWSER","Calling page.evaluate to get __NEOX_CONSOLE_LOGS__...");let S=await r.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));g.debug("BROWSER",`Extracted ${S.consoleLogs.length} console logs and ${S.errors.length} errors from injected script`);for(let T of S.consoleLogs)g.debug("BROWSER",` [${T.type}] ${T.message?.substring(0,100)}`);let C=new Map;for(let T of S.consoleLogs){let M=`${T.type}:${T.message}`;C.has(M)||C.set(M,{type:T.type,timestamp:T.timestamp,message:T.message});}for(let T of i){let M=`${T.type}:${T.message}`;C.has(M)||C.set(M,T);}i.length=0,i.push(...Array.from(C.values()));let w=new Map;for(let T of S.errors){let M=`${T.type}:${T.message}`;w.has(M)||w.set(M,{type:T.type,message:T.message,stack:T.stack||"",file:T.file,line:T.line,column:T.column,timestamp:T.timestamp});}for(let T of a){let M=`${T.type}:${T.message}`;w.has(M)||w.set(M,T);}a.length=0,a.push(...Array.from(w.values())),g.info("BROWSER",`Final: ${i.length} console logs, ${a.length} errors`);}catch(S){g.error("BROWSER","Failed to extract injected logs",{error:S});}let b;if(t.collect_performance!==false)try{let S=await r.metrics(),C=await r.evaluate(()=>{let w=window.performance,T=w.timing,M=w.getEntriesByType("paint"),B=document.querySelectorAll("*"),E=0,L=0,N=0,$=Math.min(1e3,B.length),G=Math.max(1,Math.floor(B.length/$));for(let A=0;A<B.length;A+=G){let P=B[A],K=window.getComputedStyle(P);K.display!=="none"&&K.visibility!=="hidden"&&K.opacity!=="0"?E++:L++;let U=0,ne=P.parentElement;for(;ne;)U++,ne=ne.parentElement;N=Math.max(N,U);}let X=B.length/$;return E=Math.round(E*X),L=Math.round(L*X),{domContentLoaded:T.domContentLoadedEventEnd-T.navigationStart,loadComplete:T.loadEventEnd-T.navigationStart,paintMetrics:{first_paint:M.find(A=>A.name==="first-paint")?.startTime||0,first_contentful_paint:M.find(A=>A.name==="first-contentful-paint")?.startTime||0},memory:w.memory?{used_heap:w.memory.usedJSHeapSize,total_heap:w.memory.totalJSHeapSize,heap_limit:w.memory.jsHeapSizeLimit}:void 0,domStats:{visible_nodes:E,hidden_nodes:L,max_depth:N}}});b={dom_content_loaded:C.domContentLoaded,load_complete:C.loadComplete,dom_nodes:S.Nodes||0,js_heap_size:S.JSHeapUsedSize||0,event_listeners:S.JSEventListeners||0,paint_metrics:C.paintMetrics,memory:C.memory,dom_stats:C.domStats},g.info("BROWSER",`Performance: ${b.dom_nodes} nodes, ${(b.js_heap_size/1024/1024).toFixed(1)}MB heap`);}catch(S){g.error("BROWSER","Failed to collect performance metrics",{error:S});}let _;if(t.take_screenshot===true)try{_=await r.screenshot({encoding:"base64"});}catch(S){g.error("BROWSER","Failed to capture screenshot",{error:S});}try{await d.detach();}catch{}if(o==="cdp"||o==="both")for(let[S,C]of u.entries())Array.from(c.values()).find(T=>T.url===C.url)||c.set(S,C);let v=Array.from(c.values());o==="cdp"&&(v=Array.from(u.values()));let k=v.length;n.status_filter&&(v=v.filter(S=>Ju(S.status,n.status_filter)));let R=v.filter(S=>S.error||S.status&&S.status>=400).length;v.sort((S,C)=>{let w=S.error||S.status&&S.status>=400,T=C.error||C.status&&C.status>=400;return w&&!T?-1:!w&&T?1:(S.timing?.start||0)-(C.timing?.start||0)});let O=n.max_results||20;v.length>O&&(v=v.slice(0,O));let W={total_captured:k,filtered_count:v.length,error_count:R};g.info("BROWSER",`Network: ${k} captured, ${v.length} returned, ${R} errors`);let F=Date.now()-s;return {console_logs:i,errors:a,network_requests:v,network_stats:W,performance:b,screenshot:_,load_time:F}}function Yn(r){let e=[];r.errors&&r.errors.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${r.errors.length} \u4E2A JavaScript \u5F02\u5E38\uFF1A`),r.errors.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`),i.file&&e.push(` \u4F4D\u7F6E\uFF1A${i.file}:${i.line||""}`);}),e.push(""));let t=r.console_logs?.filter(i=>i.type==="error")||[];t.length>0&&(e.push(`\u{1F534} \u53D1\u73B0 ${t.length} \u4E2A console.error \u65E5\u5FD7\uFF1A`),t.slice(0,5).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let s=r.console_logs?.filter(i=>i.type==="warn")||[];s.length>0&&(e.push(`\u26A0\uFE0F ${s.length} \u4E2A console.warn \u8B66\u544A\uFF1A`),s.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push(""));let n=r.console_logs?.filter(i=>i.type==="debug")||[];if(n.length>0&&(e.push(`\u{1F50D} ${n.length} \u4E2A console.debug \u65E5\u5FD7\uFF1A`),n.slice(0,3).forEach((i,a)=>{e.push(` ${a+1}. ${i.message}`);}),e.push("")),r.errors?.length===0&&t.length===0&&s.length===0&&(e.push("\u2705 \u672A\u53D1\u73B0 JavaScript \u9519\u8BEF\u6216\u8B66\u544A"),e.push("")),r.network_stats){let i=r.network_stats;e.push(`\u{1F310} \u7F51\u7EDC\u8BF7\u6C42\uFF1A\u5171\u6355\u83B7 ${i.total_captured} \u4E2A\uFF0C\u8FD4\u56DE ${i.filtered_count} \u4E2A\uFF0C${i.error_count} \u4E2A\u9519\u8BEF`);}let o=r.network_requests?.filter(i=>i.error||i.status&&i.status>=400)||[];if(o.length>0&&(e.push(`\u{1F534} ${o.length} \u4E2A API \u9519\u8BEF\u8BF7\u6C42\uFF1A`),o.slice(0,5).forEach((i,a)=>{if(e.push(` ${a+1}. [${i.status||"Failed"}] ${i.method} ${i.url}`),i.response_body){let l=i.response_body.substring(0,200);e.push(` \u54CD\u5E94: ${l}${i.response_body.length>200?"...":""}`);}i.error&&e.push(` \u9519\u8BEF: ${i.error}`);}),e.push("")),r.performance){let i=r.performance;if(i.dom_nodes>15e3?e.push(`\u{1F534} \u4E25\u91CD\u8B66\u544A\uFF1ADOM \u8282\u70B9\u8FC7\u591A (${i.dom_nodes.toLocaleString()}), \u9875\u9762\u6027\u80FD\u6781\u5DEE`):i.dom_nodes>1e4?e.push(`\u26A0\uFE0F \u8B66\u544A\uFF1ADOM \u8282\u70B9\u504F\u591A (${i.dom_nodes.toLocaleString()}), \u53EF\u80FD\u5F71\u54CD\u6027\u80FD`):i.dom_nodes>5e3&&e.push(`\u26A1 \u63D0\u793A\uFF1ADOM \u8282\u70B9\u8F83\u591A (${i.dom_nodes.toLocaleString()}), \u5EFA\u8BAE\u4F18\u5316`),i.dom_stats){let a=i.dom_stats,l=a.hidden_nodes/i.dom_nodes*100;e.push(` \u{1F4CA} \u53EF\u89C1: ${a.visible_nodes.toLocaleString()}, \u9690\u85CF: ${a.hidden_nodes.toLocaleString()} (${l.toFixed(1)}%), \u6700\u5927\u6DF1\u5EA6: ${a.max_depth} \u5C42`),l>40&&e.push(" \u26A0\uFE0F \u9690\u85CF\u8282\u70B9\u5360\u6BD4\u8FC7\u9AD8\uFF0C\u53EF\u80FD\u5B58\u5728\u672A\u6E05\u7406\u7684 DOM \u5143\u7D20"),a.max_depth>30&&e.push(` \u26A0\uFE0F DOM \u5D4C\u5957\u5C42\u7EA7\u8FC7\u6DF1 (${a.max_depth}), \u53EF\u80FD\u5B58\u5728\u6027\u80FD\u95EE\u9898`);}if(i.memory){let a=i.memory.used_heap/1024/1024,l=i.memory.heap_limit/1024/1024,c=i.memory.used_heap/i.memory.heap_limit*100;c>80?e.push(`\u26A1 \u5185\u5B58\u8B66\u544A\uFF1A\u5806\u4F7F\u7528\u7387 ${c.toFixed(1)}% (${a.toFixed(1)}MB / ${l.toFixed(1)}MB), \u63A5\u8FD1\u9650\u5236`):a>100&&e.push(`\u26A1 \u5185\u5B58\u63D0\u793A\uFF1A\u5806\u5185\u5B58\u8F83\u5927 ${a.toFixed(1)}MB`);}else i.js_heap_size>50*1024*1024&&e.push(`\u26A1 \u6027\u80FD\u8B66\u544A\uFF1AJS \u5806\u5185\u5B58\u8FC7\u5927 (${(i.js_heap_size/1024/1024).toFixed(1)}MB)`);i.paint_metrics&&i.paint_metrics.first_contentful_paint>3e3&&e.push(`\u26A1 \u6E32\u67D3\u6162\uFF1A\u9996\u6B21\u5185\u5BB9\u7ED8\u5236 ${i.paint_metrics.first_contentful_paint.toFixed(0)}ms (\u5EFA\u8BAE < 1500ms)`),i.load_complete>5e3&&e.push(`\u26A1 \u52A0\u8F7D\u6162\uFF1A\u9875\u9762\u5B8C\u5168\u52A0\u8F7D\u8017\u65F6 ${i.load_complete.toFixed(0)}ms (\u5EFA\u8BAE < 3000ms)`);}return e.join(`
225
+ `)||"\u2705 \u9875\u9762\u8FD0\u884C\u6B63\u5E38\uFF0C\u672A\u53D1\u73B0\u660E\u663E\u95EE\u9898"}async function _a(r){let e=await Ku(r);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Vu(r);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await Yu(r);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await Xu(r);return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"default"}}async function Ku(r){try{let e=join(r,"vite.config.js"),s=(await readFile(e,"utf-8")).match(/server\s*:\s*\{[^}]*port\s*:\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function Vu(r){try{let e=join(r,"package.json"),t=await readFile(e,"utf-8"),n=JSON.parse(t).scripts?.dev||"",o=n.match(/--port\s+(\d+)/);if(o)return parseInt(o[1]);let i=n.match(/PORT=(\d+)/);return i?parseInt(i[1]):null}catch{return null}}async function Yu(r){try{let e=join(r,".env"),s=(await readFile(e,"utf-8")).match(/(?:VITE_)?PORT\s*=\s*(\d+)/);return s?parseInt(s[1]):null}catch{return null}}async function Xu(r){try{let e=join(r,"package.json"),t=await readFile(e,"utf-8"),s=JSON.parse(t),n={...s.dependencies,...s.devDependencies};return n.vite?5173:n.next||n["react-scripts"]?3e3:n.vue?8080:n.nuxt?3e3:n.svelte?5e3:3e3}catch{return 3e3}}async function Co(r,e=3e3){try{let t=new AbortController,s=setTimeout(()=>t.abort(),e),n=await fetch(r,{method:"HEAD",signal:t.signal});return clearTimeout(s),n.ok}catch{return false}}async function Ro(r){let e=await _a(r);if(await Co(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let o=`http://localhost:${n}`;if(await Co(o))return {url:o,port:n,protocol:"http",source:"default"}}return null}le();var sp="headers.json";function wa(r){try{return new URL(r).hostname}catch{return r}}function va(){let r=Kn();return join(r,sp)}function Ta(){let r=va();if(!existsSync(r))return {};try{let e=readFileSync(r,"utf-8");return JSON.parse(e)}catch(e){return g.warn("HEADERS","Failed to read headers config",{error:e}),{}}}function xa(r){let e=va();try{let t=JSON.stringify(r,null,2);writeFileSync(e,t,"utf-8"),g.info("HEADERS","Headers config saved",{path:e});}catch(t){g.error("HEADERS","Failed to save headers config",{error:t});}}function Qn(r,e){let t=wa(r),s=Ta(),n=np(e);if(Object.keys(n).length===0){g.info("HEADERS","No headers to save for domain",{domain:t});return}s[t]={headers:n,lastUsed:Date.now(),createdAt:s[t]?.createdAt||Date.now(),url:r},xa(s),g.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(n).length});}function Eo(r){let e=wa(r),t=Ta(),s=t[e];return s?(s.lastUsed=Date.now(),xa(t),g.info("HEADERS","Retrieved headers for domain",{domain:e,headerCount:Object.keys(s.headers).length}),s.headers):(g.info("HEADERS","No saved headers for domain",{domain:e}),null)}function np(r){let e={},t=[/^authorization$/i,/^x-/i,/^cookie$/i,/^token$/i,/^auth/i,/^api-key$/i,/^api_key$/i,/^apikey$/i],s=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[n,o]of Object.entries(r)){let i=n.toLowerCase();if(s.has(i))continue;t.some(l=>l.test(n))&&(e[n]=o);}return e}var rp=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],op=['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")'],ip=['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"]'],ap=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],lp=['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"];async function Sa(r,e){let t={},s=false,n=i=>{if(s)return;i.url();let l=i.resourceType();if(l==="xhr"||l==="fetch"||l==="document"){let c=i.headers();Object.assign(t,c);}},o=i=>{if(s)return;let a=i.status();i.url();let c=i.request().resourceType();a>=200&&a<300&&(c==="xhr"||c==="fetch")&&(s=true);};return r.on("request",n),r.on("response",o),t}async function cp(r,e){let t=Eo(e);return !t||Object.keys(t).length===0?false:(await r.setExtraHTTPHeaders(t),true)}async function Io(r,e){let t=r.url(),s=t.toLowerCase();if(t!==e&&rp.some(o=>s.includes(o)))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 n of op)if(await r.$(n))return {detected:!0,original_url:e,redirected_url:t,redirect_type:"login_form",reason:`\u9875\u9762\u5305\u542B\u767B\u5F55\u8868\u5355\u5143\u7D20: ${n}`}}catch{}try{let n=await r.title(),o=n.toLowerCase(),i=["login","\u767B\u5F55","sign in","\u767B\u5165","authenticate","\u8BA4\u8BC1"];for(let a of i)if(o.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: "${n}"`}}catch{}return {detected:false,original_url:e}}async function up(r,e,t){try{t?.("auto_login_start",{message:"\u6B63\u5728\u81EA\u52A8\u586B\u5199\u767B\u5F55\u8868\u5355..."});let s=null;if(e.username_selector&&(s=await r.$(e.username_selector)),!s)for(let i of ip)try{if(s=await r.$(i),s)break}catch{}if(!s)return {success:!1,error:"\u627E\u4E0D\u5230\u7528\u6237\u540D\u8F93\u5165\u6846"};let n=null;if(e.password_selector&&(n=await r.$(e.password_selector)),!n)for(let i of ap)try{if(n=await r.$(i),n)break}catch{}if(!n)return {success:!1,error:"\u627E\u4E0D\u5230\u5BC6\u7801\u8F93\u5165\u6846"};let o=null;if(e.submit_selector&&(o=await r.$(e.submit_selector)),!o)for(let i of lp)try{if(o=await r.$(i),o)break}catch{}return o?(await s.click({clickCount:3}),await s.type(e.username,{delay:50}),t?.("auto_login_progress",{message:"\u5DF2\u586B\u5199\u7528\u6237\u540D"}),await n.click({clickCount:3}),await n.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([r.waitForNavigation({waitUntil:"networkidle0",timeout:3e4}).catch(()=>{}),o.click()]),await new Promise(i=>setTimeout(i,2e3)),{success:!0}):{success:!1,error:"\u627E\u4E0D\u5230\u767B\u5F55\u6309\u94AE"}}catch(s){return {success:false,error:String(s)}}}async function er(r,e,t){let s=null,o=r.open_for_login===true&&r.allow_manual_login===true,i=r.auto_login&&r.auto_login.username&&r.auto_login.password;try{let a=r.url||"auto";if(a==="auto"){t?.("detecting");let y=await Ro(e);if(!y){let b={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:b.error}),b}a=y.url,t?.("detected",{url:a});}t?.("launching",{url:a});let l=o?!1:r.headless!==!1,c=r.use_profile!==!1;s=await ko({headless:l,useProfile:c}),t?.("loading",{url:a});let u=await s.newPage(),p=await cp(u,a);p&&t?.("headers_applied",{message:"\u5DF2\u5E94\u7528\u4FDD\u5B58\u7684\u8BA4\u8BC1 headers"}),await u.goto(a,{waitUntil:"networkidle0",timeout:3e4});let d=await Io(u,a);if(i&&d.detected){t?.("auto_login",{message:"\u68C0\u6D4B\u5230\u767B\u5F55\u9875\u9762\uFF0C\u6B63\u5728\u81EA\u52A8\u767B\u5F55..."});let y=Sa(u,a),b=await up(u,r.auto_login,t);if(!b.success)return await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u274C \u81EA\u52A8\u767B\u5F55\u5931\u8D25: ${b.error}`,login_redirect:d,needs_login:!0};let _=await Io(u,a),v=await y;if(_.detected)return await s.close(),{success:!1,url:a,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:_,needs_login:!0};{Object.keys(v).length>0&&(Qn(a,v),t?.("headers_saved",{headerCount:Object.keys(v).length})),t?.("auto_login_success",{message:"\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F"}),t?.("collecting",{url:a});let k=await Vn(u,a,{wait_time:r.wait_time,collect_console:r.collect_console,collect_errors:r.collect_errors,collect_network:r.collect_network,collect_performance:r.collect_performance,take_screenshot:r.take_screenshot,network_capture_mode:r.network_capture_mode||"cdp",network_filter:{xhr_only:r.network_xhr_only,url_pattern:r.network_url_pattern,status_filter:r.network_status_filter,include_body:r.network_include_body,body_max_length:r.network_body_max_length,max_results:r.network_max_results}}),R=Yn({console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,network_stats:k.network_stats,performance:k.performance});return await s.close(),{success:!0,url:a,load_time:k.load_time,timestamp:Date.now(),console_logs:k.console_logs,errors:k.errors,network_requests:k.network_requests,performance:k.performance,screenshot:k.screenshot,summary:`\u2705 \u81EA\u52A8\u767B\u5F55\u6210\u529F\uFF01
226
226
 
227
- ${R}`,login_redirect:{detected:!1,original_url:a},needs_login:!1,captured_headers:v}}}if(d.detected&&!i&&!o)return await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u26A0\uFE0F \u9875\u9762\u9700\u8981\u767B\u5F55: ${d.reason}
227
+ ${R}`,login_redirect:{detected:!1,original_url:a},needs_login:!1,captured_headers:v}}}if(d.detected&&!o&&!i)return await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:`\u26A0\uFE0F \u9875\u9762\u9700\u8981\u767B\u5F55: ${d.reason}
228
228
 
229
- \u{1F4A1} \u63D0\u793A\uFF1A\u5F53\u524D\u8FD0\u884C\u4E0D\u652F\u6301\u624B\u52A8\u767B\u5F55\uFF0C\u8BF7\u63D0\u4F9B\u8D26\u53F7\u5BC6\u7801\u4EE5\u81EA\u52A8\u767B\u5F55\uFF1B\u82E5\u65E0\u6CD5\u63D0\u4F9B\u5219\u653E\u5F03\u8BE5\u9875\u9762\u8C03\u8BD5\u3002`,login_redirect:d,needs_login:!0};if(i){t?.("waiting_login",{message:"\u6D4F\u89C8\u5668\u5DF2\u6253\u5F00\uFF0C\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55...",profile_path:Ti()});let y=va(u,a),b=r.login_wait_time||12e4;try{await u.waitForNavigation({timeout:b,waitUntil:"networkidle0"});}catch{}let _=await Ri(u,a),v=await y;return _.detected?(await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:"\u26A0\uFE0F \u767B\u5F55\u672A\u5B8C\u6210\u6216\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5",login_redirect:_,needs_login:!0}):(Object.keys(v).length>0&&(Zn(a,v),t?.("headers_saved",{headerCount:Object.keys(v).length})),await s.close(),{success:!0,url:a,load_time:0,timestamp:Date.now(),summary:`\u2705 \u767B\u5F55\u6210\u529F\uFF01\u540E\u7EED\u8BBF\u95EE ${a} \u5C06\u81EA\u52A8\u4FDD\u6301\u767B\u5F55\u72B6\u6001\uFF08\u5DF2\u4FDD\u5B58 ${Object.keys(v).length} \u4E2A\u8BA4\u8BC1 headers\uFF09\u3002`,login_redirect:{detected:!1,original_url:a},needs_login:!1,captured_headers:v})}t?.("collecting",{url:a});let m=await Kn(u,a,{wait_time:r.wait_time,collect_console:r.collect_console,collect_errors:r.collect_errors,collect_network:r.collect_network,collect_performance:r.collect_performance,take_screenshot:r.take_screenshot,network_capture_mode:r.network_capture_mode||"cdp",network_filter:{xhr_only:r.network_xhr_only,url_pattern:r.network_url_pattern,status_filter:r.network_status_filter,include_body:r.network_include_body,body_max_length:r.network_body_max_length,max_results:r.network_max_results}});t?.("analyzing");let h=Vn({console_logs:m.console_logs,errors:m.errors,network_requests:m.network_requests,network_stats:m.network_stats,performance:m.performance});await s.close();let f={success:!0,url:a,load_time:m.load_time,timestamp:Date.now(),console_logs:m.console_logs,errors:m.errors,network_requests:m.network_requests,performance:m.performance,screenshot:m.screenshot,summary:h,login_redirect:d,needs_login:!1,used_saved_headers:p};return t?.("completed",{result:f}),f}catch(a){if(s)try{await s.close();}catch{}let l={success:false,error:String(a),url:r.url||"",load_time:0,timestamp:Date.now(),summary:`\u9519\u8BEF\uFF1A${a}`};return t?.("error",{error:l.error}),l}}function Ei(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Terminal tools are only available in Electron UI mode")}var lp={name:"terminal_execute",description:`Execute a shell command in a terminal session and return the output.
229
+ \u{1F4A1} \u63D0\u793A\uFF1A\u5F53\u524D\u8FD0\u884C\u4E0D\u652F\u6301\u624B\u52A8\u767B\u5F55\uFF0C\u8BF7\u63D0\u4F9B\u8D26\u53F7\u5BC6\u7801\u4EE5\u81EA\u52A8\u767B\u5F55\uFF1B\u82E5\u65E0\u6CD5\u63D0\u4F9B\u5219\u653E\u5F03\u8BE5\u9875\u9762\u8C03\u8BD5\u3002`,login_redirect:d,needs_login:!0};if(o){t?.("waiting_login",{message:"\u6D4F\u89C8\u5668\u5DF2\u6253\u5F00\uFF0C\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55...",profile_path:So()});let y=Sa(u,a),b=r.login_wait_time||12e4;try{await u.waitForNavigation({timeout:b,waitUntil:"networkidle0"});}catch{}let _=await Io(u,a),v=await y;return _.detected?(await s.close(),{success:!1,url:a,load_time:0,timestamp:Date.now(),summary:"\u26A0\uFE0F \u767B\u5F55\u672A\u5B8C\u6210\u6216\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5",login_redirect:_,needs_login:!0}):(Object.keys(v).length>0&&(Qn(a,v),t?.("headers_saved",{headerCount:Object.keys(v).length})),await s.close(),{success:!0,url:a,load_time:0,timestamp:Date.now(),summary:`\u2705 \u767B\u5F55\u6210\u529F\uFF01\u540E\u7EED\u8BBF\u95EE ${a} \u5C06\u81EA\u52A8\u4FDD\u6301\u767B\u5F55\u72B6\u6001\uFF08\u5DF2\u4FDD\u5B58 ${Object.keys(v).length} \u4E2A\u8BA4\u8BC1 headers\uFF09\u3002`,login_redirect:{detected:!1,original_url:a},needs_login:!1,captured_headers:v})}t?.("collecting",{url:a});let m=await Vn(u,a,{wait_time:r.wait_time,collect_console:r.collect_console,collect_errors:r.collect_errors,collect_network:r.collect_network,collect_performance:r.collect_performance,take_screenshot:r.take_screenshot,network_capture_mode:r.network_capture_mode||"cdp",network_filter:{xhr_only:r.network_xhr_only,url_pattern:r.network_url_pattern,status_filter:r.network_status_filter,include_body:r.network_include_body,body_max_length:r.network_body_max_length,max_results:r.network_max_results}});t?.("analyzing");let h=Yn({console_logs:m.console_logs,errors:m.errors,network_requests:m.network_requests,network_stats:m.network_stats,performance:m.performance});await s.close();let f={success:!0,url:a,load_time:m.load_time,timestamp:Date.now(),console_logs:m.console_logs,errors:m.errors,network_requests:m.network_requests,performance:m.performance,screenshot:m.screenshot,summary:h,login_redirect:d,needs_login:!1,used_saved_headers:p};return t?.("completed",{result:f}),f}catch(a){if(s)try{await s.close();}catch{}let l={success:false,error:String(a),url:r.url||"",load_time:0,timestamp:Date.now(),summary:`\u9519\u8BEF\uFF1A${a}`};return t?.("error",{error:l.error}),l}}function Mo(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Terminal tools are only available in Electron UI mode")}var pp={name:"terminal_execute",description:`Execute a shell command in a terminal session and return the output.
230
230
 
231
231
  Use this tool when you need to:
232
232
  - Run shell commands (npm, git, python, etc.)
@@ -241,7 +241,7 @@ Examples:
241
241
  - Run tests: "npm test"
242
242
  - Check git status: "git status"
243
243
  - Build project: "npm run build"
244
- - List files: "ls -la"`,parameters:{type:"object",properties:{command:{type:"string",description:'The shell command to execute (e.g., "npm test", "git status")'},cwd:{type:"string",description:"Optional working directory for the command (absolute path)"},timeout:{type:"number",description:"Optional timeout in milliseconds (default: 30000)"},sessionId:{type:"string",description:"Optional terminal session ID to reuse. If not provided, a new session will be created."}},required:["command"]},function:async r=>{let{command:e,cwd:t,timeout:s=3e4,sessionId:n}=r,i=Ei();try{let o=n;o||(o=(await i.terminalCreate({cwd:t})).sessionId);let a=await i.terminalExecute(o,e,s);return n||await i.terminalDestroy(o),JSON.stringify({success:!0,output:a.stdout+a.stderr,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr},null,2)}catch(o){return JSON.stringify({success:false,error:o.message||"Failed to execute command"},null,2)}}},cp={name:"terminal_create",description:`Create a new terminal session for interactive use.
244
+ - List files: "ls -la"`,parameters:{type:"object",properties:{command:{type:"string",description:'The shell command to execute (e.g., "npm test", "git status")'},cwd:{type:"string",description:"Optional working directory for the command (absolute path)"},timeout:{type:"number",description:"Optional timeout in milliseconds (default: 30000)"},sessionId:{type:"string",description:"Optional terminal session ID to reuse. If not provided, a new session will be created."}},required:["command"]},function:async r=>{let{command:e,cwd:t,timeout:s=3e4,sessionId:n}=r,o=Mo();try{let i=n;i||(i=(await o.terminalCreate({cwd:t})).sessionId);let a=await o.terminalExecute(i,e,s);return n||await o.terminalDestroy(i),JSON.stringify({success:!0,output:a.stdout+a.stderr,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr},null,2)}catch(i){return JSON.stringify({success:false,error:i.message||"Failed to execute command"},null,2)}}},dp={name:"terminal_create",description:`Create a new terminal session for interactive use.
245
245
 
246
246
  Use this tool when you need to:
247
247
  - Start a long-running interactive process
@@ -256,10 +256,10 @@ After creating a session, you'll receive a sessionId that you can use for:
256
256
  Example workflow:
257
257
  1. Create session: terminal_create({ cwd: "/path/to/project" })
258
258
  2. Execute commands: terminal_execute({ sessionId, command: "npm start" })
259
- 3. Clean up: terminal_destroy({ sessionId })`,parameters:{type:"object",properties:{cwd:{type:"string",description:"Optional working directory for the terminal (absolute path)"},shell:{type:"string",description:'Optional shell to use (e.g., "bash", "zsh", "powershell"). Defaults to system shell.'},cols:{type:"number",description:"Optional terminal width in columns (default: 80)"},rows:{type:"number",description:"Optional terminal height in rows (default: 24)"}},required:[]},function:async r=>{let{cwd:e,shell:t,cols:s,rows:n}=r,i=Ei();try{let o=await i.terminalCreate({cwd:e,shell:t,cols:s,rows:n});return JSON.stringify({success:!0,sessionId:o.sessionId,cwd:o.cwd,shell:o.shell,message:`Terminal session created: ${o.sessionId}. Use this sessionId for subsequent operations.`},null,2)}catch(o){return JSON.stringify({success:false,error:o.message||"Failed to create terminal session"},null,2)}}},up={name:"terminal_destroy",description:`Close and clean up a terminal session.
259
+ 3. Clean up: terminal_destroy({ sessionId })`,parameters:{type:"object",properties:{cwd:{type:"string",description:"Optional working directory for the terminal (absolute path)"},shell:{type:"string",description:'Optional shell to use (e.g., "bash", "zsh", "powershell"). Defaults to system shell.'},cols:{type:"number",description:"Optional terminal width in columns (default: 80)"},rows:{type:"number",description:"Optional terminal height in rows (default: 24)"}},required:[]},function:async r=>{let{cwd:e,shell:t,cols:s,rows:n}=r,o=Mo();try{let i=await o.terminalCreate({cwd:e,shell:t,cols:s,rows:n});return JSON.stringify({success:!0,sessionId:i.sessionId,cwd:i.cwd,shell:i.shell,message:`Terminal session created: ${i.sessionId}. Use this sessionId for subsequent operations.`},null,2)}catch(i){return JSON.stringify({success:false,error:i.message||"Failed to create terminal session"},null,2)}}},mp={name:"terminal_destroy",description:`Close and clean up a terminal session.
260
260
 
261
261
  Use this tool when you're done with a terminal session to free up resources.
262
- All running processes in the session will be terminated.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The terminal session ID to destroy"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Ei();try{return await t.terminalDestroy(e),JSON.stringify({success:!0,message:`Terminal session ${e} destroyed successfully`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to destroy terminal session"},null,2)}}},Ii=[lp,cp,up],Ta=["terminal"];function er(){return Ii.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ta])):Ta}))}function Je(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Editor tools are only available in Electron UI mode")}var pp={name:"set_breakpoint",description:`Set a breakpoint at a specific line in a file.
262
+ All running processes in the session will be terminated.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The terminal session ID to destroy"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Mo();try{return await t.terminalDestroy(e),JSON.stringify({success:!0,message:`Terminal session ${e} destroyed successfully`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to destroy terminal session"},null,2)}}},Ao=[pp,dp,mp],ka=["terminal"];function tr(){return Ao.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...ka])):ka}))}function Je(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Editor tools are only available in Electron UI mode")}var hp={name:"set_breakpoint",description:`Set a breakpoint at a specific line in a file.
263
263
 
264
264
  Use this tool when you need to:
265
265
  - Pause execution at a specific line to inspect state
@@ -276,15 +276,15 @@ Examples:
276
276
  - Log point: { file: "/path/to/file.js", line: 42, logMessage: "Count: {count}", source: "llm" }
277
277
 
278
278
  IMPORTANT: Always use source: "llm" to indicate the breakpoint was set by you.
279
- This helps users distinguish between their breakpoints and yours.`,parameters:{type:"object",properties:{file:{type:"string",description:'Absolute path to the file (e.g., "/Users/name/project/src/app.js")'},line:{type:"number",description:"Line number (1-indexed) where the breakpoint should be set"},condition:{type:"string",description:`Optional condition expression (e.g., "x > 10", "user.name === 'Alice'")`},logMessage:{type:"string",description:'Optional log message for log points (e.g., "Value: {variable}")'},source:{type:"string",enum:["llm","user"],description:'MUST be "llm" to indicate this breakpoint was set by the AI'}},required:["file","line","source"]},function:async r=>{let{file:e,line:t,condition:s,logMessage:n,source:i}=r,o=Je();if(i!=="llm")return JSON.stringify({success:false,error:'Breakpoints set by AI must have source: "llm"'},null,2);try{let a=await o.debugAddBreakpoint({file:e,line:t,condition:s,logMessage:n,source:i});return JSON.stringify({success:!0,breakpointId:a.id,file:a.file,line:a.line,enabled:a.enabled,message:`Breakpoint set at ${e}:${t}${s?` (condition: ${s})`:""}`},null,2)}catch(a){return JSON.stringify({success:false,error:a.message||"Failed to set breakpoint"},null,2)}}},dp={name:"remove_breakpoint",description:`Remove a specific breakpoint by ID.
279
+ This helps users distinguish between their breakpoints and yours.`,parameters:{type:"object",properties:{file:{type:"string",description:'Absolute path to the file (e.g., "/Users/name/project/src/app.js")'},line:{type:"number",description:"Line number (1-indexed) where the breakpoint should be set"},condition:{type:"string",description:`Optional condition expression (e.g., "x > 10", "user.name === 'Alice'")`},logMessage:{type:"string",description:'Optional log message for log points (e.g., "Value: {variable}")'},source:{type:"string",enum:["llm","user"],description:'MUST be "llm" to indicate this breakpoint was set by the AI'}},required:["file","line","source"]},function:async r=>{let{file:e,line:t,condition:s,logMessage:n,source:o}=r,i=Je();if(o!=="llm")return JSON.stringify({success:false,error:'Breakpoints set by AI must have source: "llm"'},null,2);try{let a=await i.debugAddBreakpoint({file:e,line:t,condition:s,logMessage:n,source:o});return JSON.stringify({success:!0,breakpointId:a.id,file:a.file,line:a.line,enabled:a.enabled,message:`Breakpoint set at ${e}:${t}${s?` (condition: ${s})`:""}`},null,2)}catch(a){return JSON.stringify({success:false,error:a.message||"Failed to set breakpoint"},null,2)}}},gp={name:"remove_breakpoint",description:`Remove a specific breakpoint by ID.
280
280
 
281
281
  Use this tool when you're done debugging a particular location
282
- and want to clean up the breakpoint you previously set.`,parameters:{type:"object",properties:{breakpointId:{type:"string",description:"The ID of the breakpoint to remove (returned from set_breakpoint)"}},required:["breakpointId"]},function:async r=>{let{breakpointId:e}=r,t=Je();try{return await t.debugRemoveBreakpoint(e),JSON.stringify({success:!0,message:`Breakpoint ${e} removed`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to remove breakpoint"},null,2)}}},mp={name:"list_breakpoints",description:`List all breakpoints, optionally filtered by file.
282
+ and want to clean up the breakpoint you previously set.`,parameters:{type:"object",properties:{breakpointId:{type:"string",description:"The ID of the breakpoint to remove (returned from set_breakpoint)"}},required:["breakpointId"]},function:async r=>{let{breakpointId:e}=r,t=Je();try{return await t.debugRemoveBreakpoint(e),JSON.stringify({success:!0,message:`Breakpoint ${e} removed`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to remove breakpoint"},null,2)}}},fp={name:"list_breakpoints",description:`List all breakpoints, optionally filtered by file.
283
283
 
284
284
  Use this tool to:
285
285
  - See what breakpoints are currently set
286
286
  - Check if a breakpoint already exists before setting a new one
287
- - Review breakpoints set by both you and the user`,parameters:{type:"object",properties:{file:{type:"string",description:"Optional file path to filter breakpoints (absolute path)"}},required:[]},function:async r=>{let{file:e}=r,t=Je();try{let s=await t.debugGetBreakpoints(e);return JSON.stringify({success:!0,breakpoints:s.map(n=>({id:n.id,file:n.file,line:n.line,enabled:n.enabled,verified:n.verified,source:n.source,condition:n.condition,logMessage:n.logMessage})),count:s.length},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to list breakpoints"},null,2)}}},hp={name:"clear_breakpoints",description:`Clear all breakpoints in a file or globally.
287
+ - Review breakpoints set by both you and the user`,parameters:{type:"object",properties:{file:{type:"string",description:"Optional file path to filter breakpoints (absolute path)"}},required:[]},function:async r=>{let{file:e}=r,t=Je();try{let s=await t.debugGetBreakpoints(e);return JSON.stringify({success:!0,breakpoints:s.map(n=>({id:n.id,file:n.file,line:n.line,enabled:n.enabled,verified:n.verified,source:n.source,condition:n.condition,logMessage:n.logMessage})),count:s.length},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to list breakpoints"},null,2)}}},yp={name:"clear_breakpoints",description:`Clear all breakpoints in a file or globally.
288
288
 
289
289
  Use this tool when you want to:
290
290
  - Clean up all breakpoints after debugging
@@ -292,7 +292,7 @@ Use this tool when you want to:
292
292
  - Remove all breakpoints from a specific file
293
293
 
294
294
  WARNING: This will remove ALL breakpoints (both user and LLM set).
295
- Use with caution.`,parameters:{type:"object",properties:{file:{type:"string",description:"Optional file path to clear breakpoints from (absolute path). If not provided, clears ALL breakpoints."}},required:[]},function:async r=>{let{file:e}=r,t=Je();try{return await t.debugClearBreakpoints(e),JSON.stringify({success:!0,message:e?`All breakpoints cleared from ${e}`:"All breakpoints cleared globally"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to clear breakpoints"},null,2)}}},gp={name:"start_debug_session",description:`Start a debugging session for a program.
295
+ Use with caution.`,parameters:{type:"object",properties:{file:{type:"string",description:"Optional file path to clear breakpoints from (absolute path). If not provided, clears ALL breakpoints."}},required:[]},function:async r=>{let{file:e}=r,t=Je();try{return await t.debugClearBreakpoints(e),JSON.stringify({success:!0,message:e?`All breakpoints cleared from ${e}`:"All breakpoints cleared globally"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to clear breakpoints"},null,2)}}},bp={name:"start_debug_session",description:`Start a debugging session for a program.
296
296
 
297
297
  Use this tool to begin debugging a Node.js, Python, or Java application.
298
298
  After starting, the program will run until it hits a breakpoint or completes.
@@ -308,21 +308,21 @@ Example:
308
308
  program: "/path/to/app.js",
309
309
  args: ["--port", "3000"],
310
310
  cwd: "/path/to/project"
311
- }`,parameters:{type:"object",properties:{type:{type:"string",enum:["node","python","java"],description:"The type of program to debug"},program:{type:"string",description:"Absolute path to the program entry point (e.g., main.js, app.py, Main.java)"},args:{type:"array",items:{type:"string"},description:"Optional command-line arguments for the program"},cwd:{type:"string",description:"Optional working directory (defaults to program directory)"},env:{type:"object",description:'Optional environment variables (e.g., { "NODE_ENV": "development" })'}},required:["type","program"]},function:async r=>{let{type:e,program:t,args:s,cwd:n,env:i}=r,o=Je();try{let a=await o.debugStartSession({type:e,program:t,args:s,cwd:n,env:i});return JSON.stringify({success:!0,sessionId:a.id,message:`Debug session started: ${a.id}. Use this sessionId for debug operations.`},null,2)}catch(a){return JSON.stringify({success:false,error:a.message||"Failed to start debug session"},null,2)}}},fp={name:"stop_debug_session",description:`Stop a running debugging session.
311
+ }`,parameters:{type:"object",properties:{type:{type:"string",enum:["node","python","java"],description:"The type of program to debug"},program:{type:"string",description:"Absolute path to the program entry point (e.g., main.js, app.py, Main.java)"},args:{type:"array",items:{type:"string"},description:"Optional command-line arguments for the program"},cwd:{type:"string",description:"Optional working directory (defaults to program directory)"},env:{type:"object",description:'Optional environment variables (e.g., { "NODE_ENV": "development" })'}},required:["type","program"]},function:async r=>{let{type:e,program:t,args:s,cwd:n,env:o}=r,i=Je();try{let a=await i.debugStartSession({type:e,program:t,args:s,cwd:n,env:o});return JSON.stringify({success:!0,sessionId:a.id,message:`Debug session started: ${a.id}. Use this sessionId for debug operations.`},null,2)}catch(a){return JSON.stringify({success:false,error:a.message||"Failed to start debug session"},null,2)}}},_p={name:"stop_debug_session",description:`Stop a running debugging session.
312
312
 
313
313
  Use this tool when you're done debugging to clean up resources
314
- and terminate the debugged program.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID to stop"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStopSession(e),JSON.stringify({success:!0,message:`Debug session ${e} stopped`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to stop debug session"},null,2)}}},yp={name:"debug_continue",description:`Continue program execution until the next breakpoint is hit or the program completes.
314
+ and terminate the debugged program.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID to stop"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStopSession(e),JSON.stringify({success:!0,message:`Debug session ${e} stopped`},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to stop debug session"},null,2)}}},wp={name:"debug_continue",description:`Continue program execution until the next breakpoint is hit or the program completes.
315
315
 
316
- Use this tool after hitting a breakpoint to resume execution.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugContinue(e),JSON.stringify({success:!0,message:"Program execution continued"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to continue execution"},null,2)}}},bp={name:"debug_step_over",description:`Step over the current line of code.
316
+ Use this tool after hitting a breakpoint to resume execution.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugContinue(e),JSON.stringify({success:!0,message:"Program execution continued"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to continue execution"},null,2)}}},vp={name:"debug_step_over",description:`Step over the current line of code.
317
317
 
318
318
  Executes the current line and stops at the next line in the same function.
319
- Function calls are executed without stepping into them.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepOver(e),JSON.stringify({success:!0,message:"Stepped over current line"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step over"},null,2)}}},_p={name:"debug_step_into",description:`Step into the current function call.
319
+ Function calls are executed without stepping into them.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepOver(e),JSON.stringify({success:!0,message:"Stepped over current line"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step over"},null,2)}}},Tp={name:"debug_step_into",description:`Step into the current function call.
320
320
 
321
321
  If the current line contains a function call, steps into that function.
322
- Otherwise, behaves like step_over.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepInto(e),JSON.stringify({success:!0,message:"Stepped into function"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step into"},null,2)}}},wp={name:"debug_step_out",description:`Step out of the current function.
322
+ Otherwise, behaves like step_over.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepInto(e),JSON.stringify({success:!0,message:"Stepped into function"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step into"},null,2)}}},xp={name:"debug_step_out",description:`Step out of the current function.
323
323
 
324
324
  Continues execution until the current function returns,
325
- then stops at the call site.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepOut(e),JSON.stringify({success:!0,message:"Stepped out of function"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step out"},null,2)}}},vp={name:"get_variables",description:`Get the values of all variables in the current scope.
325
+ then stops at the call site.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{return await t.debugStepOut(e),JSON.stringify({success:!0,message:"Stepped out of function"},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to step out"},null,2)}}},Sp={name:"get_variables",description:`Get the values of all variables in the current scope.
326
326
 
327
327
  Use this tool when stopped at a breakpoint to inspect:
328
328
  - Local variables
@@ -330,12 +330,12 @@ Use this tool when stopped at a breakpoint to inspect:
330
330
  - Closure variables
331
331
  - Global variables
332
332
 
333
- Optionally specify a frameId to inspect a different stack frame.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},frameId:{type:"number",description:"Optional stack frame ID (0 = current frame, 1 = caller, etc.)"}},required:["sessionId"]},function:async r=>{let{sessionId:e,frameId:t}=r,s=Je();try{let n=await s.debugGetVariables(e,t);return JSON.stringify({success:!0,variables:n,count:n.length},null,2)}catch(n){return JSON.stringify({success:false,error:n.message||"Failed to get variables"},null,2)}}},Tp={name:"get_stack_trace",description:`Get the current call stack (stack trace).
333
+ Optionally specify a frameId to inspect a different stack frame.`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},frameId:{type:"number",description:"Optional stack frame ID (0 = current frame, 1 = caller, etc.)"}},required:["sessionId"]},function:async r=>{let{sessionId:e,frameId:t}=r,s=Je();try{let n=await s.debugGetVariables(e,t);return JSON.stringify({success:!0,variables:n,count:n.length},null,2)}catch(n){return JSON.stringify({success:false,error:n.message||"Failed to get variables"},null,2)}}},kp={name:"get_stack_trace",description:`Get the current call stack (stack trace).
334
334
 
335
335
  Use this tool when stopped at a breakpoint to understand:
336
336
  - How the program reached the current location
337
337
  - The chain of function calls
338
- - Which files and lines are in the call path`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{let s=await t.debugGetStackTrace(e);return JSON.stringify({success:!0,stackTrace:s,depth:s.length},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to get stack trace"},null,2)}}},xp={name:"evaluate_expression",description:`Evaluate an expression in the current debug context.
338
+ - Which files and lines are in the call path`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"}},required:["sessionId"]},function:async r=>{let{sessionId:e}=r,t=Je();try{let s=await t.debugGetStackTrace(e);return JSON.stringify({success:!0,stackTrace:s,depth:s.length},null,2)}catch(s){return JSON.stringify({success:false,error:s.message||"Failed to get stack trace"},null,2)}}},Cp={name:"evaluate_expression",description:`Evaluate an expression in the current debug context.
339
339
 
340
340
  Use this tool to:
341
341
  - Check the value of a specific variable or expression
@@ -347,9 +347,9 @@ Examples:
347
347
  - "user.name" - Get a property value
348
348
  - "count > 10" - Evaluate a condition
349
349
  - "formatDate(timestamp)" - Call a function
350
- - "arr[0] + arr[1]" - Perform calculations`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},expression:{type:"string",description:'The expression to evaluate (e.g., "user.name", "count > 10")'},frameId:{type:"number",description:"Optional stack frame ID to evaluate in (default: current frame)"}},required:["sessionId","expression"]},function:async r=>{let{sessionId:e,expression:t,frameId:s}=r,n=Je();try{let i=await n.debugEvaluate(e,t,s);return JSON.stringify({success:!0,result:i.value,type:i.type},null,2)}catch(i){return JSON.stringify({success:false,error:i.message||"Failed to evaluate expression"},null,2)}}},Mi=[pp,dp,mp,hp,gp,fp,yp,bp,_p,wp,vp,Tp,xp],xa=["editor"];function tr(){return Mi.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...xa])):xa}))}le();le();var Sp=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),kp={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"}},Cp=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);async function Rp(r){let e={types:[],skipDirs:new Set(Sp),skipPatterns:[],interestingDirs:new Set(Cp),descriptions:[]};try{let t=await Z__default.readdir(r),s=new Set(t);for(let[n,i]of Object.entries(kp))i.detectFiles.some(a=>{if(a.includes("*")){let l=a.replace("*","");return t.some(c=>c.endsWith(l)||c.startsWith(l.replace(".","")))}return s.has(a)})&&(e.types.push(n),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 Ai(r,e){if(e.skipDirs.has(r))return true;for(let t of e.skipDirs)if(t.includes("*")){let s=t.replace("*","");if(r.endsWith(s)||r.startsWith(s.replace(".","")))return true}return false}function Ep(r,e){return e.interestingDirs.has(r)}async function Sa(r,e,t){let{maxDepth:s,currentDepth:n,shallow:i,expandInteresting:o}=t;if(n>s)return [];try{let a=await Z__default.readdir(r,{withFileTypes:!0}),l=[],c=a.filter(p=>p.isDirectory()&&!p.name.startsWith(".")),u=a.filter(p=>p.isFile()&&!p.name.startsWith("."));for(let p of c){let d=Y__default.join(r,p.name);if(Ai(p.name,e)){let m=0;try{m=(await Z__default.readdir(d)).length;}catch{}l.push({name:p.name,path:d,isDirectory:!0,skipped:!0,skipReason:Ip(p.name,e),itemCount:m});}else {let m=Ep(p.name,e),f=(i?!1:o&&m||n<s)?await Sa(d,e,{maxDepth:s,currentDepth:n+1,shallow:i,expandInteresting:o}):void 0;l.push({name:p.name,path:d,isDirectory:!0,isInteresting:m,children:f});}}if(!i||n===0)for(let p of u){let d=Y__default.join(r,p.name),m=!1;for(let h of e.skipPatterns)if(h.test(p.name)){m=!0;break}if(!m)try{let h=await Z__default.stat(d);l.push({name:p.name,path:d,isDirectory:!1,size:h.size});}catch{l.push({name:p.name,path:d,isDirectory:!1});}}return l}catch{return []}}function Ip(r,e){return ["node_modules","vendor","Pods","deps",".dart_tool","packages"].includes(r)?"dependencies":["dist","build","out","target",".next",".nuxt","bin","obj"].includes(r)?"build output":r.includes("cache")||r.startsWith(".")&&r.includes("_")?"cache":["coverage","htmlcov",".nyc_output"].includes(r)?"coverage":["venv",".venv","env","virtualenv"].includes(r)?"virtual env":"auto-skipped"}function Mp(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Pi(r,e=""){let t=[];for(let s=0;s<r.length;s++){let n=r[s],i=s===r.length-1,o=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";if(n.isDirectory)if(n.skipped){let l=n.itemCount!==void 0?` (${n.itemCount} items)`:"";t.push(`${e}${o}[~] ${n.name}/ [>>] ${n.skipReason}${l}`);}else n.isInteresting?(t.push(`${e}${o}[+] ${n.name}/ [*]`),n.children&&n.children.length>0&&t.push(...Pi(n.children,e+a))):(t.push(`${e}${o}[~] ${n.name}/`),n.children&&n.children.length>0&&t.push(...Pi(n.children,e+a)));else {let l=n.size!==void 0?` (${Mp(n.size)})`:"";t.push(`${e}${o}[] ${n.name}${l}`);}}return t}async function Ap(r,e,t){try{let s=await Z__default.readdir(r,{withFileTypes:!0}),n=[],i=[];for(let c of s)c.name.startsWith(".")||(c.isDirectory()?Ai(c.name,t)||n.push(c.name):Pp(c.name)&&i.push(c.name));let o=[],a=n.find(c=>["src","lib","app","core","packages"].includes(c));if(a){let c=Y__default.join(r,a);try{let u=await Z__default.readdir(c,{withFileTypes:!0});for(let p of u)p.isDirectory()&&!p.name.startsWith(".")&&!Ai(p.name,t)&&o.push(p.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(", ")}`),n.length>0&&l.push(`\u{1F4C2} Root Directories: ${n.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(`
351
- `)}catch(s){return JSON.stringify({error:s.message})}}function Pp(r){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(r)}var is={maxLines:500,maxChars:15e3,truncationMessage:`
352
- ... [\u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528\u66F4\u5177\u4F53\u7684 directory \u53C2\u6570\u67E5\u770B\u5B50\u76EE\u5F55]`};function Op(r){let e=0,t=[];for(let s=0;s<r.length&&s<is.maxLines;s++){let n=r[s];if(e+n.length>is.maxChars){t.push(is.truncationMessage);break}t.push(n),e+=n.length+1;}return r.length>is.maxLines&&!t.includes(is.truncationMessage)&&t.push(is.truncationMessage),t}var Lp="NEOX_WORKDIR";function ka(){let r=process.env[Lp];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Dp(r){let e=ka();return !r||r.trim()===""||r.trim()==="."?e:Y__default.isAbsolute(r)?Y__default.resolve(r):Y__default.resolve(e,r)}function $p(r){let e=ka(),t=Y__default.relative(e,r);return t&&!t.startsWith("..")&&!Y__default.isAbsolute(t)?t:r}var Ca={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
350
+ - "arr[0] + arr[1]" - Perform calculations`,parameters:{type:"object",properties:{sessionId:{type:"string",description:"The debug session ID"},expression:{type:"string",description:'The expression to evaluate (e.g., "user.name", "count > 10")'},frameId:{type:"number",description:"Optional stack frame ID to evaluate in (default: current frame)"}},required:["sessionId","expression"]},function:async r=>{let{sessionId:e,expression:t,frameId:s}=r,n=Je();try{let o=await n.debugEvaluate(e,t,s);return JSON.stringify({success:!0,result:o.value,type:o.type},null,2)}catch(o){return JSON.stringify({success:false,error:o.message||"Failed to evaluate expression"},null,2)}}},Po=[hp,gp,fp,yp,bp,_p,wp,vp,Tp,xp,Sp,kp,Cp],Ca=["editor"];function sr(){return Po.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ca])):Ca}))}le();le();var Rp=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),Ep={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"}},Ip=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);async function Mp(r){let e={types:[],skipDirs:new Set(Rp),skipPatterns:[],interestingDirs:new Set(Ip),descriptions:[]};try{let t=await Z__default.readdir(r),s=new Set(t);for(let[n,o]of Object.entries(Ep))o.detectFiles.some(a=>{if(a.includes("*")){let l=a.replace("*","");return t.some(c=>c.endsWith(l)||c.startsWith(l.replace(".","")))}return s.has(a)})&&(e.types.push(n),e.descriptions.push(o.description),o.skipDirs.forEach(a=>e.skipDirs.add(a)),o.skipPatterns&&e.skipPatterns.push(...o.skipPatterns),o.interestingDirs.forEach(a=>e.interestingDirs.add(a)));}catch{}return e}function Oo(r,e){if(e.skipDirs.has(r))return true;for(let t of e.skipDirs)if(t.includes("*")){let s=t.replace("*","");if(r.endsWith(s)||r.startsWith(s.replace(".","")))return true}return false}function Ap(r,e){return e.interestingDirs.has(r)}async function Ra(r,e,t){let{maxDepth:s,currentDepth:n,shallow:o,expandInteresting:i}=t;if(n>s)return [];try{let a=await Z__default.readdir(r,{withFileTypes:!0}),l=[],c=a.filter(p=>p.isDirectory()&&!p.name.startsWith(".")),u=a.filter(p=>p.isFile()&&!p.name.startsWith("."));for(let p of c){let d=Y__default.join(r,p.name);if(Oo(p.name,e)){let m=0;try{m=(await Z__default.readdir(d)).length;}catch{}l.push({name:p.name,path:d,isDirectory:!0,skipped:!0,skipReason:Pp(p.name,e),itemCount:m});}else {let m=Ap(p.name,e),f=(o?!1:i&&m||n<s)?await Ra(d,e,{maxDepth:s,currentDepth:n+1,shallow:o,expandInteresting:i}):void 0;l.push({name:p.name,path:d,isDirectory:!0,isInteresting:m,children:f});}}if(!o||n===0)for(let p of u){let d=Y__default.join(r,p.name),m=!1;for(let h of e.skipPatterns)if(h.test(p.name)){m=!0;break}if(!m)try{let h=await Z__default.stat(d);l.push({name:p.name,path:d,isDirectory:!1,size:h.size});}catch{l.push({name:p.name,path:d,isDirectory:!1});}}return l}catch{return []}}function Pp(r,e){return ["node_modules","vendor","Pods","deps",".dart_tool","packages"].includes(r)?"dependencies":["dist","build","out","target",".next",".nuxt","bin","obj"].includes(r)?"build output":r.includes("cache")||r.startsWith(".")&&r.includes("_")?"cache":["coverage","htmlcov",".nyc_output"].includes(r)?"coverage":["venv",".venv","env","virtualenv"].includes(r)?"virtual env":"auto-skipped"}function Op(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Lo(r,e=""){let t=[];for(let s=0;s<r.length;s++){let n=r[s],o=s===r.length-1,i=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=o?" ":"\u2502 ";if(n.isDirectory)if(n.skipped){let l=n.itemCount!==void 0?` (${n.itemCount} items)`:"";t.push(`${e}${i}[~] ${n.name}/ [>>] ${n.skipReason}${l}`);}else n.isInteresting?(t.push(`${e}${i}[+] ${n.name}/ [*]`),n.children&&n.children.length>0&&t.push(...Lo(n.children,e+a))):(t.push(`${e}${i}[~] ${n.name}/`),n.children&&n.children.length>0&&t.push(...Lo(n.children,e+a)));else {let l=n.size!==void 0?` (${Op(n.size)})`:"";t.push(`${e}${i}[] ${n.name}${l}`);}}return t}async function Lp(r,e,t){try{let s=await Z__default.readdir(r,{withFileTypes:!0}),n=[],o=[];for(let c of s)c.name.startsWith(".")||(c.isDirectory()?Oo(c.name,t)||n.push(c.name):Dp(c.name)&&o.push(c.name));let i=[],a=n.find(c=>["src","lib","app","core","packages"].includes(c));if(a){let c=Y__default.join(r,a);try{let u=await Z__default.readdir(c,{withFileTypes:!0});for(let p of u)p.isDirectory()&&!p.name.startsWith(".")&&!Oo(p.name,t)&&i.push(p.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(", ")}`),n.length>0&&l.push(`\u{1F4C2} Root Directories: ${n.sort().join(", ")}`),i.length>0&&l.push(`\u{1F527} Modules: ${i.sort().join(", ")}`),o.length>0&&l.push(`\u2699\uFE0F Config Files: ${o.slice(0,5).join(", ")}`),l.push(""),l.push('\u{1F4A1} Tip: Use search(pattern="keyword", path="src/", recursive=true) to locate code'),l.join(`
351
+ `)}catch(s){return JSON.stringify({error:s.message})}}function Dp(r){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(r)}var is={maxLines:500,maxChars:15e3,truncationMessage:`
352
+ ... [\u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528\u66F4\u5177\u4F53\u7684 directory \u53C2\u6570\u67E5\u770B\u5B50\u76EE\u5F55]`};function $p(r){let e=0,t=[];for(let s=0;s<r.length&&s<is.maxLines;s++){let n=r[s];if(e+n.length>is.maxChars){t.push(is.truncationMessage);break}t.push(n),e+=n.length+1;}return r.length>is.maxLines&&!t.includes(is.truncationMessage)&&t.push(is.truncationMessage),t}var Np="NEOX_WORKDIR";function Ea(){let r=process.env[Np];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Fp(r){let e=Ea();return !r||r.trim()===""||r.trim()==="."?e:Y__default.isAbsolute(r)?Y__default.resolve(r):Y__default.resolve(e,r)}function Up(r){let e=Ea(),t=Y__default.relative(e,r);return t&&!t.startsWith("..")&&!Y__default.isAbsolute(t)?t:r}var Ia={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
353
353
 
354
354
  \u3010\u5206\u5C42\u641C\u7D22\u7B56\u7565\u3011
355
355
  \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
@@ -366,11 +366,11 @@ Examples:
366
366
  - deep: \u5B8C\u5168\u5C55\u5F00\u6240\u6709\u76EE\u5F55
367
367
 
368
368
  \u793A\u4F8B:
369
- {"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:r=".",mode:e="structure",max_depth:t}){try{let s=Dp(r),n=$p(s);if(!(await Z__default.stat(s)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${n}`;let o=await Rp(s);if(e==="structure")return await Ap(s,n,o);let a=e==="shallow",l=t??(a?1:e==="deep"?5:3),u=await Sa(s,o,{maxDepth:l,currentDepth:0,shallow:a,expandInteresting:e!=="shallow"}),p=[];p.push(`[~] ${n}/`),p.push(""),o.types.length>0?p.push(`[?] \u68C0\u6D4B\u5230\u9879\u76EE\u7C7B\u578B: ${o.descriptions.join(", ")}`):p.push("[?] \u672A\u68C0\u6D4B\u5230\u7279\u5B9A\u9879\u76EE\u7C7B\u578B"),p.push(`\u{1F4CA} \u626B\u63CF\u6A21\u5F0F: ${e} | \u6700\u5927\u6DF1\u5EA6: ${l}`),p.push(""),p.push("\u56FE\u4F8B: [+][*] \u91CD\u70B9\u76EE\u5F55 | [~][>>] \u5DF2\u8DF3\u8FC7 | [~] \u666E\u901A\u76EE\u5F55"),p.push("\u2500".repeat(50)),p.push(""),u.length===0?p.push("(\u7A7A\u76EE\u5F55)"):p.push(...Pi(u));let d=Ra(u),m=Ea(u);return p.push(""),p.push("\u2500".repeat(50)),p.push(`\u7EDF\u8BA1: ${m} \u4E2A\u91CD\u70B9\u76EE\u5F55 | ${d} \u4E2A\u5DF2\u8DF3\u8FC7\u76EE\u5F55`),a&&(p.push(""),p.push('\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 mode="normal" \u6DF1\u5165\u63A2\u7D22\u611F\u5174\u8DA3\u7684\u76EE\u5F55')),Op(p).join(`
370
- `)}catch(s){return s.code==="ENOENT"?`[x] \u76EE\u5F55\u4E0D\u5B58\u5728: ${r}`:`[x] \u626B\u63CF\u5931\u8D25: ${s.message}`}}};function Ra(r){let e=0;for(let t of r)t.skipped&&e++,t.children&&(e+=Ra(t.children));return e}function Ea(r){let e=0;for(let t of r)t.isInteresting&&e++,t.children&&(e+=Ea(t.children));return e}function Up(){return Y__default.join(Us.homedir(),".neox")}var qs=Up(),Oi=Y__default.join(qs,"config.json");Y__default.join(qs,"sounds");function Ma(r){let e=r,t=false;if(typeof e.supervisor<"u"&&(e={...e},delete e.supervisor,t=true),e.collab?.supervisorAgent){e===r&&(e={...e});let s={...e.collab};delete s.supervisorAgent,Object.keys(s).length===0?delete e.collab:e.collab={...s,workerPool:s.workerPool??[]},t=true;}return {config:e,changed:t}}function zs(){try{let r=vn__default.readFileSync(Oi,"utf-8"),e=JSON.parse(r),{config:t,changed:s}=Ma(e);if(s)try{Aa(t);}catch{}return t}catch{return {}}}function Aa(r){try{let{config:e}=Ma(r);vn__default.existsSync(qs)||vn__default.mkdirSync(qs,{recursive:!0}),vn__default.writeFileSync(Oi,JSON.stringify(e,null,2),"utf-8");}catch(e){let t=e;throw t.code==="EACCES"||t.code==="EPERM"?(console.error(`
371
- \u274C Permission denied: Cannot write to config file`),console.error(` Location: ${Oi}`),console.error(`
372
- Please check directory permissions or try:`),console.error(` sudo chown -R $USER "${qs}"
373
- `)):console.error("[Config] Failed to save configuration:",t.message),e}}var jp=/^user_([0-9a-f]{64})_account__session_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,Gp=/^[0-9a-f]{64}$/,Bp=/session_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;function Pa(r){let e=r.toString("hex");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Wp(){let r=randomBytes(16);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Pa(r)}function Hp(r){return r.match(jp)?.[1]??null}function qp(r){let e=createHash("sha256").update(r).digest(),t=Buffer.from(e.subarray(0,16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,Pa(t)}function zp(){let r=zs(),e=typeof r.anthropicClientId=="string"?r.anthropicClientId.trim().toLowerCase():"";if(e&&Gp.test(e))return e;let t=typeof r.anthropicProxyUserId=="string"?r.anthropicProxyUserId.trim().toLowerCase():"",n=(t?Hp(t):null)||randomBytes(32).toString("hex");return r.anthropicClientId=n,Aa(r),n}function Oa(r,e){let t=zp(),n=(r?r.match(Bp):null)?.[1]?.toLowerCase()||qp(r||e||Wp());return `user_${t}_account__session_${n}`}var Di={name:"web_search",description:`Search the web using Google (via Serper.dev API).
369
+ {"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:r=".",mode:e="structure",max_depth:t}){try{let s=Fp(r),n=Up(s);if(!(await Z__default.stat(s)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${n}`;let i=await Mp(s);if(e==="structure")return await Lp(s,n,i);let a=e==="shallow",l=t??(a?1:e==="deep"?5:3),u=await Ra(s,i,{maxDepth:l,currentDepth:0,shallow:a,expandInteresting:e!=="shallow"}),p=[];p.push(`[~] ${n}/`),p.push(""),i.types.length>0?p.push(`[?] \u68C0\u6D4B\u5230\u9879\u76EE\u7C7B\u578B: ${i.descriptions.join(", ")}`):p.push("[?] \u672A\u68C0\u6D4B\u5230\u7279\u5B9A\u9879\u76EE\u7C7B\u578B"),p.push(`\u{1F4CA} \u626B\u63CF\u6A21\u5F0F: ${e} | \u6700\u5927\u6DF1\u5EA6: ${l}`),p.push(""),p.push("\u56FE\u4F8B: [+][*] \u91CD\u70B9\u76EE\u5F55 | [~][>>] \u5DF2\u8DF3\u8FC7 | [~] \u666E\u901A\u76EE\u5F55"),p.push("\u2500".repeat(50)),p.push(""),u.length===0?p.push("(\u7A7A\u76EE\u5F55)"):p.push(...Lo(u));let d=Ma(u),m=Aa(u);return p.push(""),p.push("\u2500".repeat(50)),p.push(`\u7EDF\u8BA1: ${m} \u4E2A\u91CD\u70B9\u76EE\u5F55 | ${d} \u4E2A\u5DF2\u8DF3\u8FC7\u76EE\u5F55`),a&&(p.push(""),p.push('\u{1F4A1} \u63D0\u793A: \u4F7F\u7528 mode="normal" \u6DF1\u5165\u63A2\u7D22\u611F\u5174\u8DA3\u7684\u76EE\u5F55')),$p(p).join(`
370
+ `)}catch(s){return s.code==="ENOENT"?`[x] \u76EE\u5F55\u4E0D\u5B58\u5728: ${r}`:`[x] \u626B\u63CF\u5931\u8D25: ${s.message}`}}};function Ma(r){let e=0;for(let t of r)t.skipped&&e++,t.children&&(e+=Ma(t.children));return e}function Aa(r){let e=0;for(let t of r)t.isInteresting&&e++,t.children&&(e+=Aa(t.children));return e}function Bp(){return Y__default.join(js.homedir(),".neox")}var zs=Bp(),Do=Y__default.join(zs,"config.json");Y__default.join(zs,"sounds");function Oa(r){let e=r,t=false;if(typeof e.supervisor<"u"&&(e={...e},delete e.supervisor,t=true),e.collab?.supervisorAgent){e===r&&(e={...e});let s={...e.collab};delete s.supervisorAgent,Object.keys(s).length===0?delete e.collab:e.collab={...s,workerPool:s.workerPool??[]},t=true;}return {config:e,changed:t}}function Js(){try{let r=Tn__default.readFileSync(Do,"utf-8"),e=JSON.parse(r),{config:t,changed:s}=Oa(e);if(s)try{La(t);}catch{}return t}catch{return {}}}function La(r){try{let{config:e}=Oa(r);Tn__default.existsSync(zs)||Tn__default.mkdirSync(zs,{recursive:!0}),Tn__default.writeFileSync(Do,JSON.stringify(e,null,2),"utf-8");}catch(e){let t=e;throw t.code==="EACCES"||t.code==="EPERM"?(console.error(`
371
+ \u274C Permission denied: Cannot write to config file`),console.error(` Location: ${Do}`),console.error(`
372
+ Please check directory permissions or try:`),console.error(` sudo chown -R $USER "${zs}"
373
+ `)):console.error("[Config] Failed to save configuration:",t.message),e}}var Wp=/^user_([0-9a-f]{64})_account__session_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,Hp=/^[0-9a-f]{64}$/,qp=/session_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;function Da(r){let e=r.toString("hex");return `${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function zp(){let r=randomBytes(16);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Da(r)}function Jp(r){return r.match(Wp)?.[1]??null}function Kp(r){let e=createHash("sha256").update(r).digest(),t=Buffer.from(e.subarray(0,16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,Da(t)}function Vp(){let r=Js(),e=typeof r.anthropicClientId=="string"?r.anthropicClientId.trim().toLowerCase():"";if(e&&Hp.test(e))return e;let t=typeof r.anthropicProxyUserId=="string"?r.anthropicProxyUserId.trim().toLowerCase():"",n=(t?Jp(t):null)||randomBytes(32).toString("hex");return r.anthropicClientId=n,La(r),n}function $a(r,e){let t=Vp(),n=(r?r.match(qp):null)?.[1]?.toLowerCase()||Kp(r||e||zp());return `user_${t}_account__session_${n}`}var No={name:"web_search",description:`Search the web using Google (via Serper.dev API).
374
374
 
375
375
  Use cases:
376
376
  - Search for documentation: {"query": "React hooks useEffect tutorial"}
@@ -378,12 +378,12 @@ Use cases:
378
378
  - Search for latest information: {"query": "Node.js 20 new features"}
379
379
  - Search for code examples: {"query": "Python async await example"}
380
380
 
381
- 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:r,max_results:e=10}){let t=Date.now();try{if(!r||r.trim().length===0)return "\u2717 \u641C\u7D22\u5931\u8D25: \u8BF7\u63D0\u4F9B\u641C\u7D22\u5173\u952E\u8BCD";let n=zs().webSearch?.apiKey;if(!n)return `\u2717 \u641C\u7D22\u5931\u8D25: \u672A\u914D\u7F6E Serper.dev API Key
381
+ 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:r,max_results:e=10}){let t=Date.now();try{if(!r||r.trim().length===0)return "\u2717 \u641C\u7D22\u5931\u8D25: \u8BF7\u63D0\u4F9B\u641C\u7D22\u5173\u952E\u8BCD";let n=Js().webSearch?.apiKey;if(!n)return `\u2717 \u641C\u7D22\u5931\u8D25: \u672A\u914D\u7F6E Serper.dev API Key
382
382
 
383
383
  \u8BF7\u5728\u8BBE\u7F6E\u9875\u9762 \u2192 Agent \u2192 Web Search \u4E2D\u914D\u7F6E API Key
384
- \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":n,"Content-Type":"application/json"},body:JSON.stringify({q:r.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
385
- \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
386
- \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(p=>({title:p.title||"Untitled",url:p.link||"",description:p.snippet||"",hostname:(()=>{try{return new URL(p.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
384
+ \u6CE8\u518C\u5730\u5740: https://serper.dev (\u514D\u8D39 2500 \u6B21\u641C\u7D22)`;let o=await fetch("https://google.serper.dev/search",{method:"POST",headers:{"X-API-KEY":n,"Content-Type":"application/json"},body:JSON.stringify({q:r.trim(),num:Math.min(Math.max(1,e),20)})});if(!o.ok)return o.status===401?`\u2717 \u641C\u7D22\u5931\u8D25: API Key \u65E0\u6548
385
+ \u8BF7\u68C0\u67E5 Serper.dev API Key \u662F\u5426\u6B63\u786E`:o.status===429?`\u2717 \u641C\u7D22\u5931\u8D25: API \u914D\u989D\u5DF2\u7528\u5B8C
386
+ \u8BF7\u8BBF\u95EE https://serper.dev \u67E5\u770B\u4F7F\u7528\u60C5\u51B5`:`\u2717 \u641C\u7D22\u5931\u8D25: HTTP ${o.status} ${o.statusText}`;let i=await o.json(),a=Date.now()-t,c=(i.organic||[]).map(p=>({title:p.title||"Untitled",url:p.link||"",description:p.snippet||"",hostname:(()=>{try{return new URL(p.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
387
387
  [?] Web Search
388
388
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
389
389
 
@@ -411,14 +411,14 @@ Returns top search results with title, URL, and description.`,parameters:{type:"
411
411
  [@] ${p.hostname}
412
412
  `;}),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(s){let n=Date.now()-t;return s.message?.includes("ENOTFOUND")||s.message?.includes("network")?`\u2717 \u641C\u7D22\u5931\u8D25: \u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF
413
413
  \u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5`:s.message?.includes("timeout")?`\u2717 \u641C\u7D22\u5931\u8D25: \u8BF7\u6C42\u8D85\u65F6 (${n}ms)
414
- \u8BF7\u7A0D\u540E\u91CD\u8BD5`:`\u2717 \u641C\u7D22\u5931\u8D25: ${s.message||"\u672A\u77E5\u9519\u8BEF"}`}}},La={name:"web_fetch",description:`Fetch content from a URL and extract readable text.
414
+ \u8BF7\u7A0D\u540E\u91CD\u8BD5`:`\u2717 \u641C\u7D22\u5931\u8D25: ${s.message||"\u672A\u77E5\u9519\u8BEF"}`}}},Na={name:"web_fetch",description:`Fetch content from a URL and extract readable text.
415
415
 
416
416
  Use cases:
417
417
  - Read documentation pages: {"url": "https://docs.example.com/api"}
418
418
  - Extract article content: {"url": "https://blog.example.com/post"}
419
419
  - Get API documentation: {"url": "https://api.example.com/docs"}
420
420
 
421
- 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:r,max_length:e=8e3,extract_links:t=false}){let s=Date.now();try{let n;try{n=new URL(r);}catch{return `\u2717 \u83B7\u53D6\u5931\u8D25: \u65E0\u6548\u7684 URL: ${r}`}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(r,{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")||"",p=await c.text(),d=Date.now()-s,m=p.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,`
421
+ 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:r,max_length:e=8e3,extract_links:t=false}){let s=Date.now();try{let n;try{n=new URL(r);}catch{return `\u2717 \u83B7\u53D6\u5931\u8D25: \u65E0\u6548\u7684 URL: ${r}`}let o=["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"],i=o[Math.floor(Math.random()*o.length)],a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(r,{signal:a.signal,headers:{"User-Agent":i,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")||"",p=await c.text(),d=Date.now()-s,m=p.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,`
422
422
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
423
423
  `).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,`
424
424
  `).replace(/[ \t]+\n/g,`
@@ -446,23 +446,23 @@ ${m}
446
446
  \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
447
447
  `,h.forEach((_,v)=>{b+=`${v+1}. ${_.text}
448
448
  ${_.href}
449
- `;})),b+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",b}catch(n){let i=Date.now()-s;return n.name==="AbortError"?`\u2717 \u83B7\u53D6\u5931\u8D25: \u8BF7\u6C42\u8D85\u65F6 (${i}ms)
449
+ `;})),b+="\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501",b}catch(n){let o=Date.now()-s;return n.name==="AbortError"?`\u2717 \u83B7\u53D6\u5931\u8D25: \u8BF7\u6C42\u8D85\u65F6 (${o}ms)
450
450
  URL: ${r}`:n.message?.includes("ENOTFOUND")?`\u2717 \u83B7\u53D6\u5931\u8D25: \u65E0\u6CD5\u89E3\u6790\u57DF\u540D
451
451
  URL: ${r}`:n.message?.includes("ECONNREFUSED")?`\u2717 \u83B7\u53D6\u5931\u8D25: \u8FDE\u63A5\u88AB\u62D2\u7EDD
452
452
  URL: ${r}`:`\u2717 \u83B7\u53D6\u5931\u8D25: ${n.message||"\u672A\u77E5\u9519\u8BEF"}
453
- URL: ${r}`}}};le();function Da(r){return {...zn,async function(e){try{g.debug("BROWSER","Starting browser debug",{url:e.url});let t=await Qn(e,r,(n,i)=>{g.debug("BROWSER",`Status: ${n}`,i);});g.debug("BROWSER","Browser debug completed",{success:t.success});let s={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(n=>({type:n.type,message:n.message})),errors:t.errors?.slice(0,5).map(n=>({type:n.type,message:n.message,file:n.file,line:n.line}))};return t.screenshot&&(s.screenshot={format:"base64",data:t.screenshot,note:"\u9875\u9762\u622A\u56FE\uFF08base64 \u7F16\u7801\uFF09"}),JSON.stringify(s,null,2)}catch(t){return g.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 Js=class extends EventEmitter{socket=null;sequenceNumber=1;pendingRequests=new Map;buffer="";connected=false;DEFAULT_TIMEOUT=3e4;async connect(e,t,s=1e4){return new Promise((n,i)=>{this.socket=new $a.Socket;let o=setTimeout(()=>{this.socket?.destroy(),i(new Error(`Connection timeout after ${s}ms`));},s);this.socket.connect(t,e,()=>{clearTimeout(o),this.connected=true,this.emit("connected"),n();}),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,s=this.DEFAULT_TIMEOUT){if(!this.connected||!this.socket)throw new Error("Not connected to debug server");let n=this.sequenceNumber++,i={seq:n,type:"request",command:e,arguments:t};return new Promise((o,a)=>{let l=setTimeout(()=>{this.pendingRequests.delete(n),a(new Error(`Request timeout: ${e} (${s}ms)`));},s);this.pendingRequests.set(n,{resolve:o,reject:a,timeout:l}),this.send(i);})}send(e){let t=JSON.stringify(e),n=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
453
+ URL: ${r}`}}};le();function Fa(r){return {...Jn,async function(e){try{g.debug("BROWSER","Starting browser debug",{url:e.url});let t=await er(e,r,(n,o)=>{g.debug("BROWSER",`Status: ${n}`,o);});g.debug("BROWSER","Browser debug completed",{success:t.success});let s={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(n=>({type:n.type,message:n.message})),errors:t.errors?.slice(0,5).map(n=>({type:n.type,message:n.message,file:n.file,line:n.line}))};return t.screenshot&&(s.screenshot={format:"base64",data:t.screenshot,note:"\u9875\u9762\u622A\u56FE\uFF08base64 \u7F16\u7801\uFF09"}),JSON.stringify(s,null,2)}catch(t){return g.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 Ks=class extends EventEmitter{socket=null;sequenceNumber=1;pendingRequests=new Map;buffer="";connected=false;DEFAULT_TIMEOUT=3e4;async connect(e,t,s=1e4){return new Promise((n,o)=>{this.socket=new Ua.Socket;let i=setTimeout(()=>{this.socket?.destroy(),o(new Error(`Connection timeout after ${s}ms`));},s);this.socket.connect(t,e,()=>{clearTimeout(i),this.connected=true,this.emit("connected"),n();}),this.socket.on("data",a=>{this.handleData(a);}),this.socket.on("error",a=>{clearTimeout(i),this.emit("error",a),this.connected||o(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,s=this.DEFAULT_TIMEOUT){if(!this.connected||!this.socket)throw new Error("Not connected to debug server");let n=this.sequenceNumber++,o={seq:n,type:"request",command:e,arguments:t};return new Promise((i,a)=>{let l=setTimeout(()=>{this.pendingRequests.delete(n),a(new Error(`Request timeout: ${e} (${s}ms)`));},s);this.pendingRequests.set(n,{resolve:i,reject:a,timeout:l}),this.send(o);})}send(e){let t=JSON.stringify(e),n=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
454
454
  \r
455
- `,i=Buffer.concat([Buffer.from(n,"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 s=parseInt(t[1],10),n=t[0].length,i=t.index+n,o=i+s;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,s=this.pendingRequests.get(t.request_seq);s&&(clearTimeout(s.timeout),this.pendingRequests.delete(t.request_seq),t.success?s.resolve(t):s.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 nr=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 Z.access(this.config.jarPath);}catch{throw new Error(`Java Debug JAR not found at: ${this.config.jarPath}
456
- Please download it from https://github.com/microsoft/java-debug/releases`)}let e=this.getJavaCommand();return new Promise((t,s)=>{let n=this.config.startupTimeout||1e4,i="",o=setTimeout(()=>{this.isRunning||(this.stop(),s(new Error(`Java Debug Server startup timeout (${n}ms)
455
+ `,o=Buffer.concat([Buffer.from(n,"utf8"),Buffer.from(t,"utf8")]);this.socket?.write(o);}handleData(e){for(this.buffer+=e.toString("utf8");;){let t=this.buffer.match(/Content-Length: (\d+)\r\n\r\n/);if(!t)break;let s=parseInt(t[1],10),n=t[0].length,o=t.index+n,i=o+s;if(this.buffer.length<i)break;let a=this.buffer.substring(o,i);this.buffer=this.buffer.substring(i);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,s=this.pendingRequests.get(t.request_seq);s&&(clearTimeout(s.timeout),this.pendingRequests.delete(t.request_seq),t.success?s.resolve(t):s.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 rr=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 Z.access(this.config.jarPath);}catch{throw new Error(`Java Debug JAR not found at: ${this.config.jarPath}
456
+ Please download it from https://github.com/microsoft/java-debug/releases`)}let e=this.getJavaCommand();return new Promise((t,s)=>{let n=this.config.startupTimeout||1e4,o="",i=setTimeout(()=>{this.isRunning||(this.stop(),s(new Error(`Java Debug Server startup timeout (${n}ms)
457
457
  Output so far:
458
- ${i}`)));},n);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&&s(new Error(`Java Debug Server exited with code ${a}
459
- ${i}`));}),this.process.on("error",a=>{clearTimeout(o),this.isRunning=false,this.emit("error",a),s(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?Y.join(this.config.javaHome,"bin","java"):process.env.JAVA_HOME?Y.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
458
+ ${o}`)));},n);this.process=spawn(e,["-jar",this.config.jarPath],{stdio:["pipe","pipe","pipe"]}),this.process.stdout?.on("data",a=>{let l=a.toString();o+=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(i),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(i),this.emit("started",this.port),t(this.port));}),this.process.stderr?.on("data",a=>{let l=a.toString();o+=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&&s(new Error(`Java Debug Server exited with code ${a}
459
+ ${o}`));}),this.process.on("error",a=>{clearTimeout(i),this.isRunning=false,this.emit("error",a),s(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?Y.join(this.config.javaHome,"bin","java"):process.env.JAVA_HOME?Y.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),o=`Content-Length: ${Buffer.byteLength(t,"utf8")}\r
460
460
  \r
461
- `+t;this.process.stdin.write(i);}async startDAPServer(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("Timeout waiting for DAP server to start"));},5e3),n=o=>{let a=o.match(/DAP.*?port\s*(\d+)/i);if(a){let l=parseInt(a[1],10);clearTimeout(s),this.removeListener("stdout",n),e(l);}};this.on("stdout",n);let i={jsonrpc:"2.0",id:2,method:"vscode.java.startDebugSession",params:{}};this.sendLSPMessage(i);})}};var rr=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 s=new nr({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),n=await s.start(),i=new Js;await i.connect("localhost",n),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:s}),this.setupClientListeners(t,i),{sessionId:t,status:"running",message:`Debug session started for ${e.mainClass}`}}catch(s){throw new Error(`Failed to launch debug session: ${s.message}`)}}async attach(e){let t=this.generateSessionId();try{let s=new Js;await s.connect(e.hostName||"localhost",e.port),await s.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await s.attach({hostName:e.hostName||"localhost",port:e.port,timeout:e.timeout||5e3}),await s.configurationDone();let n={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:n,client:s,server:null}),this.setupClientListeners(t,s),{sessionId:t,status:"running",message:`Attached to Java process on ${e.hostName||"localhost"}:${e.port}`}}catch(s){throw new Error(`Failed to attach to process: ${s.message}`)}}async setBreakpoint(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=(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(n),{breakpointId:n.id||-1,verified:n.verified,line:n.line||e.line,message:n.verified?`Breakpoint set at line ${n.line}`:`Breakpoint not verified: ${n.message||"Unknown reason"}`}}catch(s){throw new Error(`Failed to set breakpoint: ${s.message}`)}}async continue(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1;return await t.client.continue({threadId:s}),t.session.status="running",await this.waitForStoppedOrTimeout(t,s)}catch(s){throw new Error(`Failed to continue execution: ${s.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 s=t.session.currentThreadId||1,n=e.frameId||t.session.currentFrameId||0,i=await t.client.stackTrace({threadId:s,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(s){throw new Error(`Failed to get variables: ${s.message}`)}}async getStackTrace(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1,n=await t.client.stackTrace({threadId:s,startFrame:0,levels:50});return {stackFrames:n.body.stackFrames.map(i=>({id:i.id,name:i.name,source:{path:i.source?.path||"unknown",line:i.line},presentationHint:i.presentationHint})),totalFrames:n.body.totalFrames||n.body.stackFrames.length,message:`Retrieved ${n.body.stackFrames.length} stack frames`}}catch(s){throw new Error(`Failed to get stack trace: ${s.message}`)}}async evaluate(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.frameId||t.session.currentFrameId,n=await t.client.evaluate({expression:e.expression,frameId:s,context:e.context||"repl"});return {result:n.body.result,type:n.body.type||"unknown",variablesReference:n.body.variablesReference,message:`Expression evaluated: ${n.body.result}`}}catch(s){throw new Error(`Failed to evaluate expression: ${s.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(s){return this.sessions.delete(e.sessionId),{status:"terminated",message:`Debug session stopped (with error: ${s.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",s=>{let n=this.sessions.get(e);if(n){switch(s.event){case "stopped":n.session.status="stopped",n.session.currentThreadId=s.body.threadId,n.session.stoppedReason=s.body.reason,n.session.lastActivity=Date.now();break;case "continued":n.session.status="running",n.session.lastActivity=Date.now();break;case "terminated":n.session.status="terminated",n.session.lastActivity=Date.now();break}this.emit("session:event",{sessionId:e,event:s.event,body:s.body});}});}async waitForStoppedOrTimeout(e,t,s=5e3){return new Promise(n=>{let i=setTimeout(()=>{e.client.off("event:stopped",o),e.client.off("event:terminated",o),n({status:"running",message:"Program is running"});},s),o=a=>{clearTimeout(i),e.client.off("event:stopped",o),e.client.off("event:terminated",o),a.reason?n({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}`}):n({status:"terminated",message:"Program terminated"});};e.client.once("event:stopped",o),e.client.once("event:terminated",o);})}async performStep(e,t){let s=this.getSessionContext(e.sessionId);s.session.lastActivity=Date.now();try{let n=e.threadId||s.session.currentThreadId||1;switch(t){case "stepOver":await s.client.next({threadId:n});break;case "stepInto":await s.client.stepIn({threadId:n});break;case "stepOut":await s.client.stepOut({threadId:n});break}return new Promise((i,o)=>{let a=setTimeout(()=>{o(new Error("Step operation timeout"));},5e3);s.client.once("event:stopped",async l=>{clearTimeout(a);try{let u=(await s.client.stackTrace({threadId:n,startFrame:0,levels:1})).body.stackFrames[0];s.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(n){throw new Error(`Failed to perform step: ${n.message}`)}}cleanupInactiveSessions(){if(!this.config.sessionTimeout)return;let e=Date.now();for(let[t,s]of this.sessions.entries())e-s.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);}));}};var Zp=fileURLToPath(import.meta.url),Qp=Y.dirname(Zp);async function ed(){let r=process,e=[...r.resourcesPath?[Y.join(r.resourcesPath,"java-debug","com.microsoft.java.debug.plugin.jar")]:[],Y.join(process.cwd(),"resources","java-debug","com.microsoft.java.debug.plugin.jar"),Y.join(Qp,"..","..","..","resources","java-debug","com.microsoft.java.debug.plugin.jar")];for(let t of e)try{return await Z.access(t),console.log(`\u2713 \u627E\u5230\u5185\u7F6E Java Debug JAR: ${t}`),t}catch{}return null}async function Fa(r){if(r)try{return await Z.access(r),console.log(`\u2713 \u4F7F\u7528\u914D\u7F6E\u7684 Java Debug JAR: ${r}`),r}catch{console.warn(`\u26A0\uFE0F \u914D\u7F6E\u7684 JAR \u8DEF\u5F84\u65E0\u6548: ${r}`);}let e=await ed();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
461
+ `+t;this.process.stdin.write(o);}async startDAPServer(){return new Promise((e,t)=>{let s=setTimeout(()=>{t(new Error("Timeout waiting for DAP server to start"));},5e3),n=i=>{let a=i.match(/DAP.*?port\s*(\d+)/i);if(a){let l=parseInt(a[1],10);clearTimeout(s),this.removeListener("stdout",n),e(l);}};this.on("stdout",n);let o={jsonrpc:"2.0",id:2,method:"vscode.java.startDebugSession",params:{}};this.sendLSPMessage(o);})}};var or=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 s=new rr({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),n=await s.start(),o=new Ks;await o.connect("localhost",n),await o.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await o.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 o.configurationDone();let i={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:i,client:o,server:s}),this.setupClientListeners(t,o),{sessionId:t,status:"running",message:`Debug session started for ${e.mainClass}`}}catch(s){throw new Error(`Failed to launch debug session: ${s.message}`)}}async attach(e){let t=this.generateSessionId();try{let s=new Ks;await s.connect(e.hostName||"localhost",e.port),await s.initialize({clientID:"neox",clientName:"Neox Java Debugger",adapterID:"java",pathFormat:"path",linesStartAt1:!0,columnsStartAt1:!0}),await s.attach({hostName:e.hostName||"localhost",port:e.port,timeout:e.timeout||5e3}),await s.configurationDone();let n={id:t,status:"running",breakpoints:new Map,createdAt:Date.now(),lastActivity:Date.now()};return this.sessions.set(t,{session:n,client:s,server:null}),this.setupClientListeners(t,s),{sessionId:t,status:"running",message:`Attached to Java process on ${e.hostName||"localhost"}:${e.port}`}}catch(s){throw new Error(`Failed to attach to process: ${s.message}`)}}async setBreakpoint(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let n=(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(n),{breakpointId:n.id||-1,verified:n.verified,line:n.line||e.line,message:n.verified?`Breakpoint set at line ${n.line}`:`Breakpoint not verified: ${n.message||"Unknown reason"}`}}catch(s){throw new Error(`Failed to set breakpoint: ${s.message}`)}}async continue(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1;return await t.client.continue({threadId:s}),t.session.status="running",await this.waitForStoppedOrTimeout(t,s)}catch(s){throw new Error(`Failed to continue execution: ${s.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 s=t.session.currentThreadId||1,n=e.frameId||t.session.currentFrameId||0,o=await t.client.stackTrace({threadId:s,startFrame:0,levels:1});if(o.body.stackFrames.length===0)throw new Error("No stack frames available");let i=o.body.stackFrames[0],a=await t.client.scopes({frameId:i.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(s){throw new Error(`Failed to get variables: ${s.message}`)}}async getStackTrace(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.threadId||t.session.currentThreadId||1,n=await t.client.stackTrace({threadId:s,startFrame:0,levels:50});return {stackFrames:n.body.stackFrames.map(o=>({id:o.id,name:o.name,source:{path:o.source?.path||"unknown",line:o.line},presentationHint:o.presentationHint})),totalFrames:n.body.totalFrames||n.body.stackFrames.length,message:`Retrieved ${n.body.stackFrames.length} stack frames`}}catch(s){throw new Error(`Failed to get stack trace: ${s.message}`)}}async evaluate(e){let t=this.getSessionContext(e.sessionId);t.session.lastActivity=Date.now();try{let s=e.frameId||t.session.currentFrameId,n=await t.client.evaluate({expression:e.expression,frameId:s,context:e.context||"repl"});return {result:n.body.result,type:n.body.type||"unknown",variablesReference:n.body.variablesReference,message:`Expression evaluated: ${n.body.result}`}}catch(s){throw new Error(`Failed to evaluate expression: ${s.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(s){return this.sessions.delete(e.sessionId),{status:"terminated",message:`Debug session stopped (with error: ${s.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",s=>{let n=this.sessions.get(e);if(n){switch(s.event){case "stopped":n.session.status="stopped",n.session.currentThreadId=s.body.threadId,n.session.stoppedReason=s.body.reason,n.session.lastActivity=Date.now();break;case "continued":n.session.status="running",n.session.lastActivity=Date.now();break;case "terminated":n.session.status="terminated",n.session.lastActivity=Date.now();break}this.emit("session:event",{sessionId:e,event:s.event,body:s.body});}});}async waitForStoppedOrTimeout(e,t,s=5e3){return new Promise(n=>{let o=setTimeout(()=>{e.client.off("event:stopped",i),e.client.off("event:terminated",i),n({status:"running",message:"Program is running"});},s),i=a=>{clearTimeout(o),e.client.off("event:stopped",i),e.client.off("event:terminated",i),a.reason?n({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}`}):n({status:"terminated",message:"Program terminated"});};e.client.once("event:stopped",i),e.client.once("event:terminated",i);})}async performStep(e,t){let s=this.getSessionContext(e.sessionId);s.session.lastActivity=Date.now();try{let n=e.threadId||s.session.currentThreadId||1;switch(t){case "stepOver":await s.client.next({threadId:n});break;case "stepInto":await s.client.stepIn({threadId:n});break;case "stepOut":await s.client.stepOut({threadId:n});break}return new Promise((o,i)=>{let a=setTimeout(()=>{i(new Error("Step operation timeout"));},5e3);s.client.once("event:stopped",async l=>{clearTimeout(a);try{let u=(await s.client.stackTrace({threadId:n,startFrame:0,levels:1})).body.stackFrames[0];s.session.currentFrameId=u.id,o({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){i(c);}});})}catch(n){throw new Error(`Failed to perform step: ${n.message}`)}}cleanupInactiveSessions(){if(!this.config.sessionTimeout)return;let e=Date.now();for(let[t,s]of this.sessions.entries())e-s.session.lastActivity>this.config.sessionTimeout&&(console.log(`Cleaning up inactive session: ${t}`),this.stop({sessionId:t}).catch(o=>{console.error(`Failed to stop inactive session ${t}:`,o);}));}};var td=fileURLToPath(import.meta.url),sd=Y.dirname(td);async function nd(){let r=process,e=[...r.resourcesPath?[Y.join(r.resourcesPath,"java-debug","com.microsoft.java.debug.plugin.jar")]:[],Y.join(process.cwd(),"resources","java-debug","com.microsoft.java.debug.plugin.jar"),Y.join(sd,"..","..","..","resources","java-debug","com.microsoft.java.debug.plugin.jar")];for(let t of e)try{return await Z.access(t),console.log(`\u2713 \u627E\u5230\u5185\u7F6E Java Debug JAR: ${t}`),t}catch{}return null}async function Ga(r){if(r)try{return await Z.access(r),console.log(`\u2713 \u4F7F\u7528\u914D\u7F6E\u7684 Java Debug JAR: ${r}`),r}catch{console.warn(`\u26A0\uFE0F \u914D\u7F6E\u7684 JAR \u8DEF\u5F84\u65E0\u6548: ${r}`);}let e=await nd();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
462
462
  \u8BF7\u6267\u884C\u4EE5\u4E0B\u6B65\u9AA4\u4E4B\u4E00\uFF1A
463
463
  1. \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D
464
464
  2. \u5728\u914D\u7F6E\u4E2D\u6307\u5B9A JAR \u8DEF\u5F84
465
- 3. \u624B\u52A8\u4E0B\u8F7D\u5E76\u7F16\u8BD1\uFF1Ahttps://github.com/microsoft/java-debug`)}var Fi=null;function it(){if(!Fi)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Fi}async function Ui(r){let e=await Fa(r);Fi=new rr({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[td,sd,nd,rd,id,od,ad,ld,cd,ud,pd],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var td={name:"java_debug_launch",description:`Launch a Java application in debug mode.
465
+ 3. \u624B\u52A8\u4E0B\u8F7D\u5E76\u7F16\u8BD1\uFF1Ahttps://github.com/microsoft/java-debug`)}var jo=null;function ot(){if(!jo)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return jo}async function Go(r){let e=await Ga(r);jo=new or({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[rd,od,id,ad,ld,cd,ud,pd,dd,md,hd],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var rd={name:"java_debug_launch",description:`Launch a Java application in debug mode.
466
466
 
467
467
  Use this tool when you need to start debugging a Java program from the beginning.
468
468
 
@@ -471,7 +471,7 @@ Examples:
471
471
  - Debug a standalone Java program
472
472
  - Debug with specific JVM arguments or classpath
473
473
 
474
- 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(r){try{let t=await it().launch(r);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)}}},sd={name:"java_debug_attach",description:`Attach to a running Java process for debugging.
474
+ 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(r){try{let t=await ot().launch(r);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)}}},od={name:"java_debug_attach",description:`Attach to a running Java process for debugging.
475
475
 
476
476
  Use this tool when the Java application is already running with JDWP enabled.
477
477
 
@@ -483,7 +483,7 @@ Common JDWP ports:
483
483
  - 8000
484
484
  - Custom port specified by the application
485
485
 
486
- 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(r){try{let t=await it().attach(r);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)}}},nd={name:"java_debug_set_breakpoint",description:`Set a breakpoint at a specific line in a Java source file.
486
+ 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(r){try{let t=await ot().attach(r);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)}}},id={name:"java_debug_set_breakpoint",description:`Set a breakpoint at a specific line in a Java source file.
487
487
 
488
488
  The program will pause when execution reaches this line, allowing you to inspect variables and stack trace.
489
489
 
@@ -495,7 +495,7 @@ You can set:
495
495
 
496
496
  Examples:
497
497
  - Set breakpoint at line 25: {"sessionId": "...", "filePath": "/path/Main.java", "line": 25}
498
- - 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(r){try{let t=await it().setBreakpoint(r);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)}}},rd={name:"java_debug_continue",description:`Continue program execution until the next breakpoint or program termination.
498
+ - 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(r){try{let t=await ot().setBreakpoint(r);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)}}},ad={name:"java_debug_continue",description:`Continue program execution until the next breakpoint or program termination.
499
499
 
500
500
  Use this tool to:
501
501
  - Resume execution after hitting a breakpoint
@@ -510,7 +510,7 @@ The tool will return:
510
510
  When the program stops at a breakpoint, you can then use:
511
511
  - java_debug_get_variables to inspect variables
512
512
  - java_debug_get_stack_trace to see the call stack
513
- - 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(r){try{let t=await it().continue(r);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)}}},id={name:"java_debug_step_over",description:`Execute the current line and move to the next line (step over).
513
+ - 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(r){try{let t=await ot().continue(r);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)}}},ld={name:"java_debug_step_over",description:`Execute the current line and move to the next line (step over).
514
514
 
515
515
  If the current line contains a method call, the entire method executes without stopping inside it.
516
516
 
@@ -522,7 +522,7 @@ Use this when:
522
522
  Example workflow:
523
523
  1. Set breakpoint at line 20
524
524
  2. Continue execution (stops at line 20)
525
- 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(r){try{let t=await it().stepOver(r);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)}}},od={name:"java_debug_step_into",description:`Execute the current line and step into method calls.
525
+ 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(r){try{let t=await ot().stepOver(r);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)}}},cd={name:"java_debug_step_into",description:`Execute the current line and step into method calls.
526
526
 
527
527
  If the current line contains a method call, execution stops at the first line inside that method.
528
528
 
@@ -534,7 +534,7 @@ Use this when:
534
534
  Example:
535
535
  Line 20: result = processData(input);
536
536
 
537
- 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(r){try{let t=await it().stepInto(r);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)}}},ad={name:"java_debug_step_out",description:`Execute until the current method returns (step out).
537
+ 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(r){try{let t=await ot().stepInto(r);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)}}},ud={name:"java_debug_step_out",description:`Execute until the current method returns (step out).
538
538
 
539
539
  Execution continues until the current method completes and returns to its caller.
540
540
 
@@ -545,7 +545,7 @@ Use this when:
545
545
 
546
546
  Example:
547
547
  You're at line 15 inside processData() method.
548
- 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(r){try{let t=await it().stepOut(r);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)}}},ld={name:"java_debug_get_variables",description:`Get the values of variables in the current scope.
548
+ 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(r){try{let t=await ot().stepOut(r);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)}}},pd={name:"java_debug_get_variables",description:`Get the values of variables in the current scope.
549
549
 
550
550
  Use this tool when the program is paused (at a breakpoint or after stepping) to inspect:
551
551
  - Local variables
@@ -564,7 +564,7 @@ Example use case:
564
564
  1. Program stops at breakpoint line 25
565
565
  2. Call java_debug_get_variables to see all variable values
566
566
  3. Analyze which variables have unexpected values
567
- 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(r){try{let t=await it().getVariables(r);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)}}},cd={name:"java_debug_get_stack_trace",description:`Get the current call stack (stack trace).
567
+ 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(r){try{let t=await ot().getVariables(r);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)}}},dd={name:"java_debug_get_stack_trace",description:`Get the current call stack (stack trace).
568
568
 
569
569
  The stack trace shows the sequence of method calls that led to the current point of execution.
570
570
 
@@ -583,7 +583,7 @@ Frame 2: The method that called Frame 1
583
583
  Example output:
584
584
  Frame 0: processUser() at UserService.java:42
585
585
  Frame 1: handleRequest() at RequestHandler.java:28
586
- 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(r){try{let t=await it().getStackTrace(r);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)}}},ud={name:"java_debug_evaluate",description:`Evaluate a Java expression in the current debug context.
586
+ 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(r){try{let t=await ot().getStackTrace(r);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)}}},md={name:"java_debug_evaluate",description:`Evaluate a Java expression in the current debug context.
587
587
 
588
588
  This is an extremely powerful tool that lets you:
589
589
  - Check variable values with custom logic
@@ -606,47 +606,47 @@ Example debugging workflow:
606
606
  2. Evaluate: "user != null" -> false
607
607
  3. Look at stack trace to see where user was initialized
608
608
  4. Evaluate: "getUserFromCache(userId)" to test if cache has the user
609
- 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(r){try{let t=await it().evaluate(r);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)}}},pd={name:"java_debug_stop",description:`Stop the debug session and optionally terminate the debugged program.
609
+ 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(r){try{let t=await ot().evaluate(r);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)}}},hd={name:"java_debug_stop",description:`Stop the debug session and optionally terminate the debugged program.
610
610
 
611
611
  Always call this tool when you're done debugging to clean up resources.
612
612
 
613
- 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(r){try{let t=await it().stop(r);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 Ua={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},Ks=200,ir=10,or=4e3,as=700;function ja(r){return createHash("md5").update(r).digest("hex")}async function Ga(r){try{return await Z.access(r),!0}catch{return false}}async function Vs(r){try{await Z.mkdir(r,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async function ji(r,e,t){let n=(await Z.readFile(r,"utf-8")).split(`
614
- `),i=n.length,o=Math.max(0,e-1),a=Math.min(n.length,t);return {lines:n.slice(o,a),totalLines:i}}function Le(r,e){return r.map((t,s)=>`${String(e+s).padStart(6)} \u2502 ${t}`).join(`
615
- `)}function us(r,e){let s=Y.relative(e,r).split(Y.sep),n=s.findIndex(i=>["src","lib","app","core","packages","modules"].includes(i));return n>=0&&n+1<s.length?s[n+1]:s[0]||"root"}function Gi(r){let e=Y.extname(r).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 It(r,e,t="{([",s="})]"){let n=[],i=false;for(let o=e;o<r.length;o++){let a=r[o];for(let l of a){let c=t.indexOf(l),u=s.indexOf(l);c!==-1?(n.push(s[c]),i=true):u!==-1&&n.length>0&&n[n.length-1]===l&&n.pop();}if(i&&n.length===0)return o+1}return Math.min(e+500,r.length)}function Ba(r,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 s=t.map(n=>new RegExp(n));for(let n=e;n>=0;n--){let i=r[n];for(let o of s)if(o.test(i))return n;if(n<e&&i.trim()===""){let o=r.slice(0,n).reverse().findIndex(a=>a.trim()!=="");if(o>=0){let a=r[n-1-o];if(!a.trim().startsWith("@")&&!a.trim().startsWith("#")&&!a.trim().startsWith("//")&&!a.trim().startsWith("/*"))break}}}return Math.max(0,e-5)}function Bi(r,e){let t=r.length>e.length?r:e,s=r.length>e.length?e:r;if(t.length===0)return 1;let n=md(t,s);return (t.length-n)/t.length}function md(r,e){let t=r.length,s=e.length,n=Array(t+1).fill(null).map(()=>Array(s+1).fill(0));for(let i=0;i<=t;i++)n[i][0]=i;for(let i=0;i<=s;i++)n[0][i]=i;for(let i=1;i<=t;i++)for(let o=1;o<=s;o++)r[i-1]===e[o-1]?n[i][o]=n[i-1][o-1]:n[i][o]=Math.min(n[i-1][o]+1,n[i][o-1]+1,n[i-1][o-1]+1);return n[t][s]}function ps(r){return r.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var ar=class{workspacePath;indexManager=null;constructor(e){this.workspacePath=e;}setIndexManager(e){this.indexManager=e;}async read(e){let{path:t,locator:s,mode:n="smart",autoFullThreshold:i,chunkSize:o=Ks,expandContext:a=ir,maxLines:l=or,useIndex:c=true}=e;try{let u=this.resolvePath(t);if((await Z.stat(u)).isDirectory())return this.errorResult(t,"\u8FD9\u662F\u4E00\u4E2A\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6");switch(n){case "full":return this.readFull(u,t,l);case "chunk":return !s||s.type!=="line"?this.readChunk(u,t,1,o):this.readChunk(u,t,s.start,s.end?s.end-s.start+1:o);default:return this.smartRead(u,t,s,{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,s,n){let{autoFullThreshold:i,chunkSize:o,expandContext:a,maxLines:l,useIndex:c}=n;if(!s){if(typeof i=="number"&&i>0){let u=await Z.readFile(e,"utf-8"),p=ps(u).split(`
616
- `),d=p.length;if(d<=i){let f=Math.min(d,l),y=p.slice(0,f);return {success:true,path:t,totalLines:d,startLine:1,endLine:f,content:Le(y,1),truncated:f<d,strategy:"full"}}let m=Math.min(o,d),h=p.slice(0,m);return {success:true,path:t,totalLines:d,startLine:1,endLine:m,content:Le(h,1),truncated:m<d,strategy:"chunk"}}return this.readChunk(e,t,1,o)}switch(s.type){case "line":return this.readByLine(e,t,s.start,s.end,o);case "pattern":return this.readByPattern(e,t,s.regex,{matchIndex:s.matchIndex||1,context:s.context||a,chunkSize:o});case "symbol":return this.readBySymbol(e,t,s.name,{kind:s.kind,fuzzy:s.fuzzy,chunkSize:o,useIndex:c});case "function":return this.readBySymbol(e,t,s.name,{kind:"function",className:s.className,chunkSize:o,useIndex:c});case "class":return this.readBySymbol(e,t,s.name,{kind:"class",chunkSize:o,useIndex:c});case "range":return this.readByRange(e,t,s.startPattern,s.endPattern,o);default:return this.readChunk(e,t,1,o)}}async readByLine(e,t,s,n,i){let o=n||s+i-1,{lines:a,totalLines:l}=await ji(e,s,o);return {success:true,path:t,totalLines:l,startLine:s,endLine:Math.min(o,l),content:Le(a,s),truncated:o<l,strategy:"chunk"}}async readByPattern(e,t,s,n){let{matchIndex:i,context:o,chunkSize:a}=n,c=(await Z.readFile(e,"utf-8")).split(`
613
+ 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(r){try{let t=await ot().stop(r);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 Ba={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},Vs=200,ir=10,ar=4e3,ls=700;function Wa(r){return createHash("md5").update(r).digest("hex")}async function Ha(r){try{return await Z.access(r),!0}catch{return false}}async function Ys(r){try{await Z.mkdir(r,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async function Bo(r,e,t){let n=(await Z.readFile(r,"utf-8")).split(`
614
+ `),o=n.length,i=Math.max(0,e-1),a=Math.min(n.length,t);return {lines:n.slice(i,a),totalLines:o}}function Le(r,e){return r.map((t,s)=>`${String(e+s).padStart(6)} \u2502 ${t}`).join(`
615
+ `)}function ps(r,e){let s=Y.relative(e,r).split(Y.sep),n=s.findIndex(o=>["src","lib","app","core","packages","modules"].includes(o));return n>=0&&n+1<s.length?s[n+1]:s[0]||"root"}function Wo(r){let e=Y.extname(r).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 It(r,e,t="{([",s="})]"){let n=[],o=false;for(let i=e;i<r.length;i++){let a=r[i];for(let l of a){let c=t.indexOf(l),u=s.indexOf(l);c!==-1?(n.push(s[c]),o=true):u!==-1&&n.length>0&&n[n.length-1]===l&&n.pop();}if(o&&n.length===0)return i+1}return Math.min(e+500,r.length)}function qa(r,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 s=t.map(n=>new RegExp(n));for(let n=e;n>=0;n--){let o=r[n];for(let i of s)if(i.test(o))return n;if(n<e&&o.trim()===""){let i=r.slice(0,n).reverse().findIndex(a=>a.trim()!=="");if(i>=0){let a=r[n-1-i];if(!a.trim().startsWith("@")&&!a.trim().startsWith("#")&&!a.trim().startsWith("//")&&!a.trim().startsWith("/*"))break}}}return Math.max(0,e-5)}function Ho(r,e){let t=r.length>e.length?r:e,s=r.length>e.length?e:r;if(t.length===0)return 1;let n=fd(t,s);return (t.length-n)/t.length}function fd(r,e){let t=r.length,s=e.length,n=Array(t+1).fill(null).map(()=>Array(s+1).fill(0));for(let o=0;o<=t;o++)n[o][0]=o;for(let o=0;o<=s;o++)n[0][o]=o;for(let o=1;o<=t;o++)for(let i=1;i<=s;i++)r[o-1]===e[i-1]?n[o][i]=n[o-1][i-1]:n[o][i]=Math.min(n[o-1][i]+1,n[o][i-1]+1,n[o-1][i-1]+1);return n[t][s]}function ds(r){return r.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var lr=class{workspacePath;indexManager=null;constructor(e){this.workspacePath=e;}setIndexManager(e){this.indexManager=e;}async read(e){let{path:t,locator:s,mode:n="smart",autoFullThreshold:o,chunkSize:i=Vs,expandContext:a=ir,maxLines:l=ar,useIndex:c=true}=e;try{let u=this.resolvePath(t);if((await Z.stat(u)).isDirectory())return this.errorResult(t,"\u8FD9\u662F\u4E00\u4E2A\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6");switch(n){case "full":return this.readFull(u,t,l);case "chunk":return !s||s.type!=="line"?this.readChunk(u,t,1,i):this.readChunk(u,t,s.start,s.end?s.end-s.start+1:i);default:return this.smartRead(u,t,s,{autoFullThreshold:o,chunkSize:i,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,s,n){let{autoFullThreshold:o,chunkSize:i,expandContext:a,maxLines:l,useIndex:c}=n;if(!s){if(typeof o=="number"&&o>0){let u=await Z.readFile(e,"utf-8"),p=ds(u).split(`
616
+ `),d=p.length;if(d<=o){let f=Math.min(d,l),y=p.slice(0,f);return {success:true,path:t,totalLines:d,startLine:1,endLine:f,content:Le(y,1),truncated:f<d,strategy:"full"}}let m=Math.min(i,d),h=p.slice(0,m);return {success:true,path:t,totalLines:d,startLine:1,endLine:m,content:Le(h,1),truncated:m<d,strategy:"chunk"}}return this.readChunk(e,t,1,i)}switch(s.type){case "line":return this.readByLine(e,t,s.start,s.end,i);case "pattern":return this.readByPattern(e,t,s.regex,{matchIndex:s.matchIndex||1,context:s.context||a,chunkSize:i});case "symbol":return this.readBySymbol(e,t,s.name,{kind:s.kind,fuzzy:s.fuzzy,chunkSize:i,useIndex:c});case "function":return this.readBySymbol(e,t,s.name,{kind:"function",className:s.className,chunkSize:i,useIndex:c});case "class":return this.readBySymbol(e,t,s.name,{kind:"class",chunkSize:i,useIndex:c});case "range":return this.readByRange(e,t,s.startPattern,s.endPattern,i);default:return this.readChunk(e,t,1,i)}}async readByLine(e,t,s,n,o){let i=n||s+o-1,{lines:a,totalLines:l}=await Bo(e,s,i);return {success:true,path:t,totalLines:l,startLine:s,endLine:Math.min(i,l),content:Le(a,s),truncated:i<l,strategy:"chunk"}}async readByPattern(e,t,s,n){let{matchIndex:o,context:i,chunkSize:a}=n,c=(await Z.readFile(e,"utf-8")).split(`
617
617
  `),u=c.length,p;try{p=new RegExp(s,"gi");}catch(b){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${b.message}`)}let d=[];if(c.forEach((b,_)=>{p.test(b)&&d.push(_+1),p.lastIndex=0;}),d.length===0)return {success:true,path:t,totalLines:u,startLine:1,endLine:Math.min(a,u),content:`\u672A\u627E\u5230\u5339\u914D: "${s}"
618
618
 
619
- `+Le(c.slice(0,Math.min(50,u)),1),truncated:false,strategy:"grep",metadata:{module:us(e,this.workspacePath)}};let m=d[Math.min(i-1,d.length-1)],h=Math.max(1,m-o),f=Math.min(u,m+a-o),y=c.slice(h-1,f);return {success:true,path:t,totalLines:u,startLine:h,endLine:f,content:Le(y,h),truncated:f<u,strategy:"grep",metadata:{matchedLine:m,module:us(e,this.workspacePath)}}}async readBySymbol(e,t,s,n){let{kind:i,className:o,fuzzy:a,chunkSize:l,useIndex:c}=n;if(c&&this.indexManager){let p=await this.readBySymbolFromIndex(e,t,s,i,o);if(p)return p}let u=this.buildSymbolPattern(s,i,o);return this.readSymbolBlock(e,t,u,s,l)}async readBySymbolFromIndex(e,t,s,n,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(p=>p.kind==="class"&&p.name===i);u?.children&&(a=u.children.find(p=>p.name===s));}else a=o.symbols.find(u=>n&&u.kind!==n?!1:u.name===s);if(!a)return null;let{lines:l,totalLines:c}=await ji(e,a.startLine,a.endLine);return {success:!0,path:t,totalLines:c,startLine:a.startLine,endLine:a.endLine,content:Le(l,a.startLine),truncated:!1,strategy:"index",metadata:{symbol:a,module:us(e,this.workspacePath)}}}catch{return null}}async readSymbolBlock(e,t,s,n,i){let a=(await Z.readFile(e,"utf-8")).split(`
620
- `),l=a.length,c;try{c=new RegExp(s,"i");}catch{c=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");}let u=-1;for(let f=0;f<a.length;f++)if(c.test(a[f])){u=f;break}if(u===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(i,l),content:`\u672A\u627E\u5230\u7B26\u53F7: "${n}"
619
+ `+Le(c.slice(0,Math.min(50,u)),1),truncated:false,strategy:"grep",metadata:{module:ps(e,this.workspacePath)}};let m=d[Math.min(o-1,d.length-1)],h=Math.max(1,m-i),f=Math.min(u,m+a-i),y=c.slice(h-1,f);return {success:true,path:t,totalLines:u,startLine:h,endLine:f,content:Le(y,h),truncated:f<u,strategy:"grep",metadata:{matchedLine:m,module:ps(e,this.workspacePath)}}}async readBySymbol(e,t,s,n){let{kind:o,className:i,fuzzy:a,chunkSize:l,useIndex:c}=n;if(c&&this.indexManager){let p=await this.readBySymbolFromIndex(e,t,s,o,i);if(p)return p}let u=this.buildSymbolPattern(s,o,i);return this.readSymbolBlock(e,t,u,s,l)}async readBySymbolFromIndex(e,t,s,n,o){if(!this.indexManager)return null;try{let i=await this.indexManager.getFileIndex(e);if(!i)return null;let a;if(o){let u=i.symbols.find(p=>p.kind==="class"&&p.name===o);u?.children&&(a=u.children.find(p=>p.name===s));}else a=i.symbols.find(u=>n&&u.kind!==n?!1:u.name===s);if(!a)return null;let{lines:l,totalLines:c}=await Bo(e,a.startLine,a.endLine);return {success:!0,path:t,totalLines:c,startLine:a.startLine,endLine:a.endLine,content:Le(l,a.startLine),truncated:!1,strategy:"index",metadata:{symbol:a,module:ps(e,this.workspacePath)}}}catch{return null}}async readSymbolBlock(e,t,s,n,o){let a=(await Z.readFile(e,"utf-8")).split(`
620
+ `),l=a.length,c;try{c=new RegExp(s,"i");}catch{c=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");}let u=-1;for(let f=0;f<a.length;f++)if(c.test(a[f])){u=f;break}if(u===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(o,l),content:`\u672A\u627E\u5230\u7B26\u53F7: "${n}"
621
621
 
622
- `+Le(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};let p=Ba(a,u),d=It(a,p),m=Math.min(d,p+i),h=a.slice(p,m);return {success:true,path:t,totalLines:l,startLine:p+1,endLine:m,content:Le(h,p+1),truncated:m<d,strategy:"grep",metadata:{matchedLine:u+1,module:us(e,this.workspacePath)}}}async readByRange(e,t,s,n,i){let a=(await Z.readFile(e,"utf-8")).split(`
623
- `),l=a.length,c,u;try{c=new RegExp(s,"i"),u=new RegExp(n,"i");}catch(f){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${f.message}`)}let p=-1,d=-1;for(let f=0;f<a.length;f++)if(p===-1&&c.test(a[f])&&(p=f),p!==-1&&u.test(a[f])){d=f;break}if(p===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(i,l),content:`\u672A\u627E\u5230\u8D77\u59CB\u6A21\u5F0F: "${s}"
622
+ `+Le(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};let p=qa(a,u),d=It(a,p),m=Math.min(d,p+o),h=a.slice(p,m);return {success:true,path:t,totalLines:l,startLine:p+1,endLine:m,content:Le(h,p+1),truncated:m<d,strategy:"grep",metadata:{matchedLine:u+1,module:ps(e,this.workspacePath)}}}async readByRange(e,t,s,n,o){let a=(await Z.readFile(e,"utf-8")).split(`
623
+ `),l=a.length,c,u;try{c=new RegExp(s,"i"),u=new RegExp(n,"i");}catch(f){return this.errorResult(t,`\u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${f.message}`)}let p=-1,d=-1;for(let f=0;f<a.length;f++)if(p===-1&&c.test(a[f])&&(p=f),p!==-1&&u.test(a[f])){d=f;break}if(p===-1)return {success:true,path:t,totalLines:l,startLine:1,endLine:Math.min(o,l),content:`\u672A\u627E\u5230\u8D77\u59CB\u6A21\u5F0F: "${s}"
624
624
 
625
- `+Le(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};d===-1&&(d=Math.min(p+i-1,l-1));let m=Math.min(d+1,p+i),h=a.slice(p,m);return {success:true,path:t,totalLines:l,startLine:p+1,endLine:m,content:Le(h,p+1),truncated:m<d+1,strategy:"grep",metadata:{module:us(e,this.workspacePath)}}}async readChunk(e,t,s,n){let i=await Z.readFile(e,"utf-8"),o=ps(i).split(`
626
- `),a=o.length,l=Math.max(1,s),c=Math.min(l+n-1,a),u=o.slice(l-1,c);return {success:true,path:t,totalLines:a,startLine:l,endLine:c,content:Le(u,l),truncated:c<a,strategy:"chunk"}}async readFull(e,t,s){let n=await Z.readFile(e,"utf-8"),i=ps(n).split(`
627
- `),o=i.length,a=Math.min(o,s),l=i.slice(0,a);return {success:true,path:t,totalLines:o,startLine:1,endLine:a,content:Le(l,1),truncated:a<o,strategy:"full"}}buildSymbolPattern(e,t,s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i={function:`(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`,class:`class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${n}(\\s+extends|\\s*\\{|\\s*$)`,method:s?`(${n}|${s}\\.${n})\\s*\\(`:`${n}\\s*\\(`,variable:`(const|let|var)\\s+${n}\\s*[=:]`,type:`type\\s+${n}\\s*[=<]`,enum:`enum\\s+${n}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${n}`};return t&&i[t]?i[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${n}|${n}\\s*(=|\\()`}resolvePath(e){return Y.isAbsolute(e)?e:Y.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}}};function Wi(r){return new ar(r)}var cl=wu(tl());var Xs=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var vd={"[: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]},Zs=r=>r.replace(/[[\]\\-]/g,"\\$&"),Td=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),sl=r=>r.join(""),nl=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let s=[],n=[],i=t+1,o=false,a=false,l=false,c=false,u=t,p="";e:for(;i<r.length;){let f=r.charAt(i);if((f==="!"||f==="^")&&i===t+1){c=true,i++;continue}if(f==="]"&&o&&!l){u=i+1;break}if(o=true,f==="\\"&&!l){l=true,i++;continue}if(f==="["&&!l){for(let[y,[b,_,v]]of Object.entries(vd))if(r.startsWith(y,i)){if(p)return ["$.",false,r.length-t,true];i+=y.length,v?n.push(b):s.push(b),a=a||_;continue e}}if(l=false,p){f>p?s.push(Zs(p)+"-"+Zs(f)):f===p&&s.push(Zs(f)),p="",i++;continue}if(r.startsWith("-]",i+1)){s.push(Zs(f+"-")),i+=2;continue}if(r.startsWith("-",i+1)){p=f,i+=2;continue}s.push(Zs(f)),i++;}if(u<i)return ["",false,0,false];if(!s.length&&!n.length)return ["$.",false,r.length-t,true];if(n.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let f=s[0].length===2?s[0].slice(-1):s[0];return [Td(f),false,u-t,false]}let d="["+(c?"^":"")+sl(s)+"]",m="["+(c?"":"^")+sl(n)+"]";return [s.length&&n.length?"("+d+"|"+m+")":s.length?d:m,a,u-t,true]};var ot=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var xd=new Set(["!","?","+","*","@"]),rl=r=>xd.has(r),Sd="(?!(?:^|/)\\.\\.?(?:$|/))",cr="(?!\\.)",kd=new Set(["[","."]),Cd=new Set(["..","."]),Rd=new Set("().*{}+?[]^$\\!"),Ed=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zi="[^/]",il=zi+"*?",ol=zi+"+?",ds=class r{type;#e;#t;#i=false;#n=[];#o;#w;#c;#p=false;#a;#l;#r=false;constructor(e,t,s={}){this.type=e,e&&(this.#t=true),this.#o=t,this.#e=this.#o?this.#o.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#o?this.#o.#n.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)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.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,s=t.#o;for(;s;){for(let n=t.#w+1;!s.type&&n<s.#n.length;n++)for(let i of e.#n){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(s.#n[n]);}t=s,s=t.#o;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#o===this))throw new Error("invalid part: "+t);this.#n.push(t);}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#o?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#o?.isStart())return false;if(this.#w===0)return true;let e=this.#o;for(let t=0;t<this.#w;t++){let s=e.#n[t];if(!(s instanceof r&&s.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.#n.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new r(this.type,e);for(let s of this.#n)t.copyIn(s);return t}static#y(e,t,s,n){let i=false,o=false,a=-1,l=false;if(t.type===null){let m=s,h="";for(;m<e.length;){let f=e.charAt(m++);if(i||f==="\\"){i=!i,h+=f;continue}if(o){m===a+1?(f==="^"||f==="!")&&(l=true):f==="]"&&!(m===a+2&&l)&&(o=false),h+=f;continue}else if(f==="["){o=true,a=m,l=false,h+=f;continue}if(!n.noext&&rl(f)&&e.charAt(m)==="("){t.push(h),h="";let y=new r(f,t);m=r.#y(e,y,m,n),t.push(y);continue}h+=f;}return t.push(h),m}let c=s+1,u=new r(null,t),p=[],d="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,d+=m;continue}if(o){c===a+1?(m==="^"||m==="!")&&(l=true):m==="]"&&!(c===a+2&&l)&&(o=false),d+=m;continue}else if(m==="["){o=true,a=c,l=false,d+=m;continue}if(rl(m)&&e.charAt(c)==="("){u.push(d),d="";let h=new r(m,u);u.push(h),c=r.#y(e,h,c,n);continue}if(m==="|"){u.push(d),d="",p.push(u),u=new r(null,t);continue}if(m===")")return d===""&&t.#n.length===0&&(t.#r=true),u.push(d),d="",t.push(...p,u),c;d+=m;}return t.type=null,t.#t=void 0,t.#n=[e.substring(s-1)],c}static fromGlob(e,t={}){let s=new r(null,void 0,t);return r.#y(e,s,0,t),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,s,n,i]=this.toRegExpSource();if(!(n||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;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.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(m=>{let[h,f,y,b]=typeof m=="string"?r.#d(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||y,this.#i=this.#i||b,h}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&Cd.has(this.#n[0]))){let h=kd,f=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=f?Sd:y?cr:"";}let p="";return this.isEnd()&&this.#e.#p&&this.#o?.type==="!"&&(p="(?:$|\\/)"),[u+c+p,ot(c),this.#t=!!this.#t,this.#i]}let s=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,ot(this.toString()),false,false]}let o=!s||e||t||!cr?"":this.#m(true);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let a="";if(this.type==="!"&&this.#r)a=(this.isStart()&&!t?cr:"")+ol;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?cr:"")+il+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=n+i+l;}return [a,ot(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[s,n,i,o]=t.toRegExpSource(e);return this.#i=this.#i||o,s}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#d(e,t,s=false){let n=false,i="",o=false;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(n){n=false,i+=(Rd.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":n=true;continue}if(l==="["){let[c,u,p,d]=nl(e,a);if(p){i+=c,o=o||u,a+=p-1,t=t||d;continue}}if(l==="*"){s&&e==="*"?i+=ol:i+=il,t=true;continue}if(l==="?"){i+=zi,t=true;continue}i+=Ed(l);}return [i,ot(e),!!t,o]}};var ms=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var Ue=(r,e,t={})=>(Xs(e),!t.nocomment&&e.charAt(0)==="#"?false:new Ke(e,t).match(r)),Id=/^\*+([^+@!?\*\[\(]*)$/,Md=r=>e=>!e.startsWith(".")&&e.endsWith(r),Ad=r=>e=>e.endsWith(r),Pd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),Od=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Ld=/^\*+\.\*+$/,Dd=r=>!r.startsWith(".")&&r.includes("."),$d=r=>r!=="."&&r!==".."&&r.includes("."),Nd=/^\.\*+$/,Fd=r=>r!=="."&&r!==".."&&r.startsWith("."),Ud=/^\*+$/,jd=r=>r.length!==0&&!r.startsWith("."),Gd=r=>r.length!==0&&r!=="."&&r!=="..",Bd=/^\?+([^+@!?\*\[\(]*)?$/,Wd=([r,e=""])=>{let t=ul([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Hd=([r,e=""])=>{let t=pl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},qd=([r,e=""])=>{let t=pl([r]);return e?s=>t(s)&&s.endsWith(e):t},zd=([r,e=""])=>{let t=ul([r]);return e?s=>t(s)&&s.endsWith(e):t},ul=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},pl=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},dl=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",al={win32:{sep:"\\"},posix:{sep:"/"}},Jd=dl==="win32"?al.win32.sep:al.posix.sep;Ue.sep=Jd;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var Kd="[^/]",Vd=Kd+"*?",Yd="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",Xd="(?:(?!(?:\\/|^)\\.).)*?",Zd=(r,e={})=>t=>Ue(t,r,e);Ue.filter=Zd;var Ze=(r,e={})=>Object.assign({},r,e),Qd=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return Ue;let e=Ue;return Object.assign((s,n,i={})=>e(s,n,Ze(r,i)),{Minimatch:class extends e.Minimatch{constructor(n,i={}){super(n,Ze(r,i));}static defaults(n){return e.defaults(Ze(r,n)).Minimatch}},AST:class extends e.AST{constructor(n,i,o={}){super(n,i,Ze(r,o));}static fromGlob(n,i={}){return e.AST.fromGlob(n,Ze(r,i))}},unescape:(s,n={})=>e.unescape(s,Ze(r,n)),escape:(s,n={})=>e.escape(s,Ze(r,n)),filter:(s,n={})=>e.filter(s,Ze(r,n)),defaults:s=>e.defaults(Ze(r,s)),makeRe:(s,n={})=>e.makeRe(s,Ze(r,n)),braceExpand:(s,n={})=>e.braceExpand(s,Ze(r,n)),match:(s,n,i={})=>e.match(s,n,Ze(r,i)),sep:e.sep,GLOBSTAR:Ae})};Ue.defaults=Qd;var ml=(r,e={})=>(Xs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, cl.default)(r));Ue.braceExpand=ml;var em=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=em;var tm=(r,e,t={})=>{let s=new Ke(e,t);return r=r.filter(n=>s.match(n)),s.options.nonull&&!r.length&&r.push(e),r};Ue.match=tm;var ll=/[?*]|[+@!]\(.*?\)|\[|\]/,sm=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ke=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Xs(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||dl,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 s=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let n=this.globParts.map((i,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!ll.test(i[2]))&&!ll.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,n),this.set=n.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 s=0;s<e.length;s++)for(let n=0;n<e[s].length;n++)e[s][n]==="**"&&(e[s][n]="*");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 s=-1;for(;(s=t.indexOf("**",s+1))!==-1;){let n=s;for(;t[n+1]==="**";)n++;n!==s&&t.splice(s,n-s);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((s,n)=>{let i=s[s.length-1];return n==="**"&&i==="**"?s:n===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(s.pop(),s):(s.push(n),s)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let i=e[n];n===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=true,e.splice(n,1),n--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let s=0;for(;(s=e.indexOf("..",s+1))!==-1;){let n=e[s-1];n&&n!=="."&&n!==".."&&n!=="**"&&(t=true,e.splice(s-1,2),s-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let s of e){let n=-1;for(;(n=s.indexOf("**",n+1))!==-1;){let o=n;for(;s[o+1]==="**";)o++;o>n&&s.splice(n+1,o-n);let a=s[n+1],l=s[n+2],c=s[n+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,s.splice(n,1);let u=s.slice(0);u[n]="**",e.push(u),n--;}if(!this.preserveMultipleSlashes){for(let o=1;o<s.length-1;o++){let a=s[o];o===1&&a===""&&s[0]===""||(a==="."||a==="")&&(t=true,s.splice(o,1),o--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(t=true,s.pop());}let i=0;for(;(i=s.indexOf("..",i+1))!==-1;){let o=s[i-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=true;let l=i===1&&s[i+1]==="**"?["."]:[];s.splice(i-1,2,...l),s.length===0&&s.push(""),i-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++){let n=this.partsMatch(e[t],e[s],!this.preserveMultipleSlashes);if(n){e[t]=[],e[s]=n;break}}return e.filter(t=>t.length)}partsMatch(e,t,s=false){let n=0,i=0,o=[],a="";for(;n<e.length&&i<t.length;)if(e[n]===t[i])o.push(a==="b"?t[i]:e[n]),n++,i++;else if(s&&e[n]==="**"&&t[i]===e[n+1])o.push(e[n]),n++;else if(s&&t[i]==="**"&&e[n]===t[i+1])o.push(t[i]),i++;else if(e[n]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return false;a="a",o.push(e[n]),n++,i++;}else if(t[i]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(a==="a")return false;a="b",o.push(t[i]),n++,i++;}else return false;return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,s=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)t=!t,s++;s&&(this.pattern=e.slice(s)),this.negate=t;}matchOne(e,t,s=false){let n=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),b=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),_=!b&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),v=y?3:f?0:void 0,k=_?3:b?0:void 0;if(typeof v=="number"&&typeof k=="number"){let[R,O]=[e[v],t[k]];R.toLowerCase()===O.toLowerCase()&&(t[k]=R,k>v?t=t.slice(k):v>k&&(e=e.slice(v)));}}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],p=e[o];if(this.debug(t,u,p),u===false)return false;if(u===Ae){this.debug("GLOBSTAR",[t,u,p]);var d=o,m=a+1;if(m===c){for(this.debug("** at the end");o<l;o++)if(e[o]==="."||e[o]===".."||!n.dot&&e[o].charAt(0)===".")return false;return true}for(;d<l;){var h=e[d];if(this.debug(`
625
+ `+Le(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};d===-1&&(d=Math.min(p+o-1,l-1));let m=Math.min(d+1,p+o),h=a.slice(p,m);return {success:true,path:t,totalLines:l,startLine:p+1,endLine:m,content:Le(h,p+1),truncated:m<d+1,strategy:"grep",metadata:{module:ps(e,this.workspacePath)}}}async readChunk(e,t,s,n){let o=await Z.readFile(e,"utf-8"),i=ds(o).split(`
626
+ `),a=i.length,l=Math.max(1,s),c=Math.min(l+n-1,a),u=i.slice(l-1,c);return {success:true,path:t,totalLines:a,startLine:l,endLine:c,content:Le(u,l),truncated:c<a,strategy:"chunk"}}async readFull(e,t,s){let n=await Z.readFile(e,"utf-8"),o=ds(n).split(`
627
+ `),i=o.length,a=Math.min(i,s),l=o.slice(0,a);return {success:true,path:t,totalLines:i,startLine:1,endLine:a,content:Le(l,1),truncated:a<i,strategy:"full"}}buildSymbolPattern(e,t,s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o={function:`(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`,class:`class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${n}(\\s+extends|\\s*\\{|\\s*$)`,method:s?`(${n}|${s}\\.${n})\\s*\\(`:`${n}\\s*\\(`,variable:`(const|let|var)\\s+${n}\\s*[=:]`,type:`type\\s+${n}\\s*[=<]`,enum:`enum\\s+${n}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${n}`};return t&&o[t]?o[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${n}|${n}\\s*(=|\\()`}resolvePath(e){return Y.isAbsolute(e)?e:Y.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}}};function qo(r){return new lr(r)}var dl=xu(rl());var Zs=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var Sd={"[: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]},Qs=r=>r.replace(/[[\]\\-]/g,"\\$&"),kd=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ol=r=>r.join(""),il=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let s=[],n=[],o=t+1,i=false,a=false,l=false,c=false,u=t,p="";e:for(;o<r.length;){let f=r.charAt(o);if((f==="!"||f==="^")&&o===t+1){c=true,o++;continue}if(f==="]"&&i&&!l){u=o+1;break}if(i=true,f==="\\"&&!l){l=true,o++;continue}if(f==="["&&!l){for(let[y,[b,_,v]]of Object.entries(Sd))if(r.startsWith(y,o)){if(p)return ["$.",false,r.length-t,true];o+=y.length,v?n.push(b):s.push(b),a=a||_;continue e}}if(l=false,p){f>p?s.push(Qs(p)+"-"+Qs(f)):f===p&&s.push(Qs(f)),p="",o++;continue}if(r.startsWith("-]",o+1)){s.push(Qs(f+"-")),o+=2;continue}if(r.startsWith("-",o+1)){p=f,o+=2;continue}s.push(Qs(f)),o++;}if(u<o)return ["",false,0,false];if(!s.length&&!n.length)return ["$.",false,r.length-t,true];if(n.length===0&&s.length===1&&/^\\?.$/.test(s[0])&&!c){let f=s[0].length===2?s[0].slice(-1):s[0];return [kd(f),false,u-t,false]}let d="["+(c?"^":"")+ol(s)+"]",m="["+(c?"":"^")+ol(n)+"]";return [s.length&&n.length?"("+d+"|"+m+")":s.length?d:m,a,u-t,true]};var it=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Cd=new Set(["!","?","+","*","@"]),al=r=>Cd.has(r),Rd="(?!(?:^|/)\\.\\.?(?:$|/))",ur="(?!\\.)",Ed=new Set(["[","."]),Id=new Set(["..","."]),Md=new Set("().*{}+?[]^$\\!"),Ad=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ko="[^/]",ll=Ko+"*?",cl=Ko+"+?",ms=class r{type;#e;#t;#o=false;#n=[];#i;#w;#c;#p=false;#a;#l;#r=false;constructor(e,t,s={}){this.type=e,e&&(this.#t=true),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?s:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#i?this.#i.#n.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)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.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,s=t.#i;for(;s;){for(let n=t.#w+1;!s.type&&n<s.#n.length;n++)for(let o of e.#n){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(s.#n[n]);}t=s,s=t.#i;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#i===this))throw new Error("invalid part: "+t);this.#n.push(t);}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#i?.isStart())return false;if(this.#w===0)return true;let e=this.#i;for(let t=0;t<this.#w;t++){let s=e.#n[t];if(!(s instanceof r&&s.type==="!"))return false}return true}isEnd(){if(this.#e===this||this.#i?.type==="!")return true;if(!this.#i?.isEnd())return false;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#n.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this));}clone(e){let t=new r(this.type,e);for(let s of this.#n)t.copyIn(s);return t}static#y(e,t,s,n){let o=false,i=false,a=-1,l=false;if(t.type===null){let m=s,h="";for(;m<e.length;){let f=e.charAt(m++);if(o||f==="\\"){o=!o,h+=f;continue}if(i){m===a+1?(f==="^"||f==="!")&&(l=true):f==="]"&&!(m===a+2&&l)&&(i=false),h+=f;continue}else if(f==="["){i=true,a=m,l=false,h+=f;continue}if(!n.noext&&al(f)&&e.charAt(m)==="("){t.push(h),h="";let y=new r(f,t);m=r.#y(e,y,m,n),t.push(y);continue}h+=f;}return t.push(h),m}let c=s+1,u=new r(null,t),p=[],d="";for(;c<e.length;){let m=e.charAt(c++);if(o||m==="\\"){o=!o,d+=m;continue}if(i){c===a+1?(m==="^"||m==="!")&&(l=true):m==="]"&&!(c===a+2&&l)&&(i=false),d+=m;continue}else if(m==="["){i=true,a=c,l=false,d+=m;continue}if(al(m)&&e.charAt(c)==="("){u.push(d),d="";let h=new r(m,u);u.push(h),c=r.#y(e,h,c,n);continue}if(m==="|"){u.push(d),d="",p.push(u),u=new r(null,t);continue}if(m===")")return d===""&&t.#n.length===0&&(t.#r=true),u.push(d),d="",t.push(...p,u),c;d+=m;}return t.type=null,t.#t=void 0,t.#n=[e.substring(s-1)],c}static fromGlob(e,t={}){let s=new r(null,void 0,t);return r.#y(e,s,0,t),s}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,s,n,o]=this.toRegExpSource();if(!(n||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return s;let a=(this.#a.nocase?"i":"")+(o?"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.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(m=>{let[h,f,y,b]=typeof m=="string"?r.#d(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||y,this.#o=this.#o||b,h}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&Id.has(this.#n[0]))){let h=Ed,f=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=f?Rd:y?ur:"";}let p="";return this.isEnd()&&this.#e.#p&&this.#i?.type==="!"&&(p="(?:$|\\/)"),[u+c+p,it(c),this.#t=!!this.#t,this.#o]}let s=this.type==="*"||this.type==="+",n=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#m(t);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,it(this.toString()),false,false]}let i=!s||e||t||!ur?"":this.#m(true);i===o&&(i=""),i&&(o=`(?:${o})(?:${i})*?`);let a="";if(this.type==="!"&&this.#r)a=(this.isStart()&&!t?ur:"")+cl;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?ur:"")+ll+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;a=n+o+l;}return [a,it(o),this.#t=!!this.#t,this.#o]}#m(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[s,n,o,i]=t.toRegExpSource(e);return this.#o=this.#o||i,s}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#d(e,t,s=false){let n=false,o="",i=false;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(n){n=false,o+=(Md.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?o+="\\\\":n=true;continue}if(l==="["){let[c,u,p,d]=il(e,a);if(p){o+=c,i=i||u,a+=p-1,t=t||d;continue}}if(l==="*"){s&&e==="*"?o+=cl:o+=ll,t=true;continue}if(l==="?"){o+=Ko,t=true;continue}o+=Ad(l);}return [o,it(e),!!t,i]}};var hs=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var Ue=(r,e,t={})=>(Zs(e),!t.nocomment&&e.charAt(0)==="#"?false:new Ke(e,t).match(r)),Pd=/^\*+([^+@!?\*\[\(]*)$/,Od=r=>e=>!e.startsWith(".")&&e.endsWith(r),Ld=r=>e=>e.endsWith(r),Dd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),$d=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Nd=/^\*+\.\*+$/,Fd=r=>!r.startsWith(".")&&r.includes("."),Ud=r=>r!=="."&&r!==".."&&r.includes("."),jd=/^\.\*+$/,Gd=r=>r!=="."&&r!==".."&&r.startsWith("."),Bd=/^\*+$/,Wd=r=>r.length!==0&&!r.startsWith("."),Hd=r=>r.length!==0&&r!=="."&&r!=="..",qd=/^\?+([^+@!?\*\[\(]*)?$/,zd=([r,e=""])=>{let t=ml([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Jd=([r,e=""])=>{let t=hl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Kd=([r,e=""])=>{let t=hl([r]);return e?s=>t(s)&&s.endsWith(e):t},Vd=([r,e=""])=>{let t=ml([r]);return e?s=>t(s)&&s.endsWith(e):t},ml=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},hl=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},gl=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",ul={win32:{sep:"\\"},posix:{sep:"/"}},Yd=gl==="win32"?ul.win32.sep:ul.posix.sep;Ue.sep=Yd;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var Xd="[^/]",Zd=Xd+"*?",Qd="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",em="(?:(?!(?:\\/|^)\\.).)*?",tm=(r,e={})=>t=>Ue(t,r,e);Ue.filter=tm;var Ze=(r,e={})=>Object.assign({},r,e),sm=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return Ue;let e=Ue;return Object.assign((s,n,o={})=>e(s,n,Ze(r,o)),{Minimatch:class extends e.Minimatch{constructor(n,o={}){super(n,Ze(r,o));}static defaults(n){return e.defaults(Ze(r,n)).Minimatch}},AST:class extends e.AST{constructor(n,o,i={}){super(n,o,Ze(r,i));}static fromGlob(n,o={}){return e.AST.fromGlob(n,Ze(r,o))}},unescape:(s,n={})=>e.unescape(s,Ze(r,n)),escape:(s,n={})=>e.escape(s,Ze(r,n)),filter:(s,n={})=>e.filter(s,Ze(r,n)),defaults:s=>e.defaults(Ze(r,s)),makeRe:(s,n={})=>e.makeRe(s,Ze(r,n)),braceExpand:(s,n={})=>e.braceExpand(s,Ze(r,n)),match:(s,n,o={})=>e.match(s,n,Ze(r,o)),sep:e.sep,GLOBSTAR:Ae})};Ue.defaults=sm;var fl=(r,e={})=>(Zs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, dl.default)(r));Ue.braceExpand=fl;var nm=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=nm;var rm=(r,e,t={})=>{let s=new Ke(e,t);return r=r.filter(n=>s.match(n)),s.options.nonull&&!r.length&&r.push(e),r};Ue.match=rm;var pl=/[?*]|[+@!]\(.*?\)|\[|\]/,om=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ke=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Zs(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||gl,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=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let n=this.globParts.map((o,i,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!pl.test(o[2]))&&!pl.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return [...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return [o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,n),this.set=n.filter(o=>o.indexOf(false)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let i=this.set[o];i[0]===""&&i[1]===""&&this.globParts[o][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let s=0;s<e.length;s++)for(let n=0;n<e[s].length;n++)e[s][n]==="**"&&(e[s][n]="*");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 s=-1;for(;(s=t.indexOf("**",s+1))!==-1;){let n=s;for(;t[n+1]==="**";)n++;n!==s&&t.splice(s,n-s);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((s,n)=>{let o=s[s.length-1];return n==="**"&&o==="**"?s:n===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(s.pop(),s):(s.push(n),s)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let n=1;n<e.length-1;n++){let o=e[n];n===1&&o===""&&e[0]===""||(o==="."||o==="")&&(t=true,e.splice(n,1),n--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let s=0;for(;(s=e.indexOf("..",s+1))!==-1;){let n=e[s-1];n&&n!=="."&&n!==".."&&n!=="**"&&(t=true,e.splice(s-1,2),s-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let s of e){let n=-1;for(;(n=s.indexOf("**",n+1))!==-1;){let i=n;for(;s[i+1]==="**";)i++;i>n&&s.splice(n+1,i-n);let a=s[n+1],l=s[n+2],c=s[n+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,s.splice(n,1);let u=s.slice(0);u[n]="**",e.push(u),n--;}if(!this.preserveMultipleSlashes){for(let i=1;i<s.length-1;i++){let a=s[i];i===1&&a===""&&s[0]===""||(a==="."||a==="")&&(t=true,s.splice(i,1),i--);}s[0]==="."&&s.length===2&&(s[1]==="."||s[1]==="")&&(t=true,s.pop());}let o=0;for(;(o=s.indexOf("..",o+1))!==-1;){let i=s[o-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=true;let l=o===1&&s[o+1]==="**"?["."]:[];s.splice(o-1,2,...l),s.length===0&&s.push(""),o-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let s=t+1;s<e.length;s++){let n=this.partsMatch(e[t],e[s],!this.preserveMultipleSlashes);if(n){e[t]=[],e[s]=n;break}}return e.filter(t=>t.length)}partsMatch(e,t,s=false){let n=0,o=0,i=[],a="";for(;n<e.length&&o<t.length;)if(e[n]===t[o])i.push(a==="b"?t[o]:e[n]),n++,o++;else if(s&&e[n]==="**"&&t[o]===e[n+1])i.push(e[n]),n++;else if(s&&t[o]==="**"&&e[n]===t[o+1])i.push(t[o]),o++;else if(e[n]==="*"&&t[o]&&(this.options.dot||!t[o].startsWith("."))&&t[o]!=="**"){if(a==="b")return false;a="a",i.push(e[n]),n++,o++;}else if(t[o]==="*"&&e[n]&&(this.options.dot||!e[n].startsWith("."))&&e[n]!=="**"){if(a==="a")return false;a="b",i.push(t[o]),n++,o++;}else return false;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,s=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)t=!t,s++;s&&(this.pattern=e.slice(s)),this.negate=t;}matchOne(e,t,s=false){let n=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),y=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),b=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),_=!b&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),v=y?3:f?0:void 0,k=_?3:b?0:void 0;if(typeof v=="number"&&typeof k=="number"){let[R,O]=[e[v],t[k]];R.toLowerCase()===O.toLowerCase()&&(t[k]=R,k>v?t=t.slice(k):v>k&&(e=e.slice(v)));}}let{optimizationLevel:o=1}=this.options;o>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,a=0,l=e.length,c=t.length;i<l&&a<c;i++,a++){this.debug("matchOne loop");var u=t[a],p=e[i];if(this.debug(t,u,p),u===false)return false;if(u===Ae){this.debug("GLOBSTAR",[t,u,p]);var d=i,m=a+1;if(m===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!n.dot&&e[i].charAt(0)===".")return false;return true}for(;d<l;){var h=e[d];if(this.debug(`
628
628
  globstar while`,e,d,t,m,h),this.matchOne(e.slice(d),t.slice(m),s))return this.debug("globstar found match!",d,l,h),true;if(h==="."||h===".."||!n.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,d,t,m);break}this.debug("globstar swallow a segment, and continue"),d++;}return !!(s&&(this.debug(`
629
- >>> no match, partial?`,e,d,t,m),d===l))}let f;if(typeof u=="string"?(f=p===u,this.debug("string match",u,p,f)):(f=u.test(p),this.debug("pattern match",u,p,f)),!f)return false}if(o===l&&a===c)return true;if(o===l)return s;if(a===c)return o===l-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return ml(this.pattern,this.options)}parse(e){Xs(e);let t=this.options;if(e==="**")return Ae;if(e==="")return "";let s,n=null;(s=e.match(Ud))?n=t.dot?Gd:jd:(s=e.match(Id))?n=(t.nocase?t.dot?Od:Pd:t.dot?Ad:Md)(s[1]):(s=e.match(Bd))?n=(t.nocase?t.dot?Hd:Wd:t.dot?qd:zd)(s):(s=e.match(Ld))?n=t.dot?$d:Dd:(s=e.match(Nd))&&(n=Fd);let i=ds.fromGlob(e,this.options).toMMPattern();return n&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:n}),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,s=t.noglobstar?Vd:t.dot?Yd:Xd,n=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let p of u.flags.split(""))n.add(p);return typeof u=="string"?sm(u):u===Ae?Ae:u._src});return c.forEach((u,p)=>{let d=c[p+1],m=c[p-1];u!==Ae||m===Ae||(m===void 0?d!==void 0&&d!==Ae?c[p+1]="(?:\\/|"+s+"\\/)?"+d:c[p]=s:d===void 0?c[p-1]=m+"(?:\\/|"+s+")?":d!==Ae&&(c[p-1]=m+"(?:\\/|\\/"+s+"\\/)"+d,c[p+1]=Ae));}),c.filter(u=>u!==Ae).join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+a+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...n].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 s=this.options;this.isWindows&&(e=e.split("\\").join("/"));let n=this.slashSplit(e);this.debug(this.pattern,"split",n);let i=this.set;this.debug(this.pattern,"set",i);let o=n[n.length-1];if(!o)for(let a=n.length-2;!o&&a>=0;a--)o=n[a];for(let a=0;a<i.length;a++){let l=i[a],c=n;if(s.matchBase&&l.length===1&&(c=[o]),this.matchOne(c,l,t))return s.flipNegate?true:!this.negate}return s.flipNegate?false:this.negate}static defaults(e){return Ue.defaults(e).Minimatch}};Ue.AST=ds;Ue.Minimatch=Ke;Ue.escape=ms;Ue.unescape=ot;var hs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,gl=new Set,Ji=typeof process=="object"&&process?process:{},fl=(r,e,t,s)=>{typeof Ji.emitWarning=="function"?Ji.emitWarning(r,e,t,s):console.error(`[${t}] ${e}: ${r}`);},ur=globalThis.AbortController,hl=globalThis.AbortSignal;if(typeof ur>"u"){hl=class{onabort;_onabort=[];reason;aborted=false;addEventListener(s,n){this._onabort.push(n);}},ur=class{constructor(){e();}signal=new hl;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=true;for(let n of this.signal._onabort)n(s);this.signal.onabort?.(s);}}};let r=Ji.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=false,fl("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));};}var nm=r=>!gl.has(r);var Mt=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),yl=r=>Mt(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?gs:null:null,gs=class extends Array{constructor(e){super(e),this.fill(0);}},Ki=class r{heap;length;static#e=false;static create(e){let t=yl(e);if(!t)return [];r.#e=true;let s=new r(e,t);return r.#e=false,s}constructor(e,t){if(!r.#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]}},Qs=class r{#e;#t;#i;#n;#o;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#a;#l;#r;#f;#y;#m;#d;#x;#g;#S;#k;#_;#v;#T;#h;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#_,sizes:e.#S,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#d},free:e.#x,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,s,n,i)=>e.#F(t,s,n,i),moveToTail:t=>e.#j(t),indexes:t=>e.#R(t),rindexes:t=>e.#E(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#o}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:s,ttlResolution:n=1,ttlAutopurge:i,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:d,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:y,memoMethod:b,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:R,ignoreFetchAbort:O}=e;if(t!==0&&!Mt(t))throw new TypeError("max option must be a nonnegative integer");let W=t?yl(t):Array;if(!W)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,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(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=b,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#o=y,this.#T=!!y,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new W(t),this.#y=new W(t),this.#m=0,this.#d=0,this.#x=Ki.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof u=="function"?(this.#n=u,this.#g=[]):(this.#n=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#n,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!O,this.maxEntrySize!==0){if(this.#t!==0&&!Mt(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#M();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=Mt(n)||n===0?n:1,this.ttlAutopurge=!!i,this.ttl=s||0,this.ttl){if(!Mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#I();}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 F="LRU_CACHE_UNBOUNDED";nm(F)&&(gl.add(F),fl("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",F,r));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#I(){let e=new gs(this.#e),t=new gs(this.#e);this.#_=e,this.#k=t,this.#P=(i,o,a=hs.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?hs.now():0;},this.#s=(i,o)=>{if(e[o]){let a=e[o],l=t[o];if(!a||!l)return;i.ttl=a,i.start=l,i.now=s||n();let c=i.now-l;i.remainingTTL=a-c;}};let s=0,n=()=>{let i=hs.now();if(this.ttlResolution>0){s=i;let o=setTimeout(()=>s=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=(s||n())-l;return a-c},this.#b=i=>{let o=t[i],a=e[i];return !!a&&!!o&&(s||n())-o>a};}#C=()=>{};#s=()=>{};#P=()=>{};#b=()=>false;#M(){let e=new gs(this.#e);this.#p=0,this.#S=e,this.#O=t=>{this.#p-=e[t],e[t]=0;},this.#D=(t,s,n,i)=>{if(this.#u(s))return 0;if(!Mt(n))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(n=i(s,t),!Mt(n))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 n},this.#L=(t,s,n)=>{if(e[t]=s,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#N(true);}this.#p+=e[t],n&&(n.entrySize=s,n.totalCalculatedSize=this.#p);};}#O=e=>{};#L=(e,t,s)=>{};#D=(e,t,s,n)=>{if(s||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#d;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#E({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#d));)t=this.#f[t];}#$(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())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.#E())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.#R()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*rkeys(){for(let e of this.#E()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*values(){for(let e of this.#R())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}*rvalues(){for(let e of this.#E())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 s of this.#R()){let n=this.#r[s],i=this.#u(n)?n.__staleWhileFetching:n;if(i!==void 0&&e(i,this.#l[s],this))return this.get(this.#l[s],t)}}forEach(e,t=this){for(let s of this.#R()){let n=this.#r[s],i=this.#u(n)?n.__staleWhileFetching:n;i!==void 0&&e.call(t,i,this.#l[s],this);}}rforEach(e,t=this){for(let s of this.#E()){let n=this.#r[s],i=this.#u(n)?n.__staleWhileFetching:n;i!==void 0&&e.call(t,i,this.#l[s],this);}}purgeStale(){let e=false;for(let t of this.#E({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 s=this.#r[t],n=this.#u(s)?s.__staleWhileFetching:s;if(n===void 0)return;let i={value:n};if(this.#_&&this.#k){let o=this.#_[t],a=this.#k[t];if(o&&a){let l=o-(hs.now()-a);i.ttl=l,i.start=Date.now();}}return this.#S&&(i.size=this.#S[t]),i}dump(){let e=[];for(let t of this.#R({allowStale:true})){let s=this.#l[t],n=this.#r[t],i=this.#u(n)?n.__staleWhileFetching:n;if(i===void 0||s===void 0)continue;let o={value:i};if(this.#_&&this.#k){o.ttl=this.#_[t];let a=hs.now()-this.#k[t];o.start=Math.floor(Date.now()-a);}this.#S&&(o.size=this.#S[t]),e.unshift([s,o]);}return e}load(e){this.clear();for(let[t,s]of e){if(s.start){let n=Date.now()-s.start;s.start=hs.now()-n;}this.set(t,s.value,s);}}set(e,t,s={}){if(t===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#D(e,t,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#A(e,"set"),this;let p=this.#c===0?void 0:this.#a.get(e);if(p===void 0)p=this.#c===0?this.#d:this.#x.length!==0?this.#x.pop():this.#c===this.#e?this.#N(false):this.#c,this.#l[p]=e,this.#r[p]=t,this.#a.set(e,p),this.#f[this.#d]=p,this.#y[p]=this.#d,this.#d=p,this.#c++,this.#L(p,u,l),l&&(l.set="add"),c=false;else {this.#j(p);let d=this.#r[p];if(t!==d){if(this.#T&&this.#u(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=d;m!==void 0&&!o&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]));}else o||(this.#v&&this.#i?.(d,e,"set"),this.#h&&this.#g?.push([d,e,"set"]));if(this.#O(p),this.#L(p,u,l),this.#r[p]=t,l){l.set="replace";let m=d&&this.#u(d)?d.__staleWhileFetching:d;m!==void 0&&(l.oldValue=m);}}else l&&(l.set="update");}if(n!==0&&!this.#_&&this.#I(),this.#_&&(c||this.#P(p,n,i),l&&this.#s(l,p)),!o&&this.#h&&this.#g){let d=this.#g,m;for(;m=d?.shift();)this.#n?.(...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.#g){let e=this.#g,t;for(;t=e?.shift();)this.#n?.(...t);}}}#N(e){let t=this.#m,s=this.#l[t],n=this.#r[t];return this.#T&&this.#u(n)?n.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(n,s,"evict"),this.#h&&this.#g?.push([n,s,"evict"])),this.#O(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#x.push(t)),this.#c===1?(this.#m=this.#d=0,this.#x.length=0):this.#m=this.#f[t],this.#a.delete(s),this.#c--,t}has(e,t={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:n}=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))n&&(n.has="stale",this.#s(n,i));else return s&&this.#C(i),n&&(n.has="hit",this.#s(n,i)),true}else n&&(n.has="miss");return false}peek(e,t={}){let{allowStale:s=this.allowStale}=t,n=this.#a.get(e);if(n===void 0||!s&&this.#b(n))return;let i=this.#r[n];return this.#u(i)?i.__staleWhileFetching:i}#F(e,t,s,n){let i=t===void 0?void 0:this.#r[t];if(this.#u(i))return i;let o=new ur,{signal:a}=s;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let l={signal:o.signal,options:s,context:n},c=(f,y=false)=>{let{aborted:b}=o.signal,_=s.ignoreFetchAbort&&f!==void 0;if(s.status&&(b&&!y?(s.status.fetchAborted=true,s.status.fetchError=o.signal.reason,_&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),b&&!_&&!y)return p(o.signal.reason);let v=m;return this.#r[t]===m&&(f===void 0?v.__staleWhileFetching?this.#r[t]=v.__staleWhileFetching:this.#A(e,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=f),p(f)),p=f=>{let{aborted:y}=o.signal,b=y&&s.allowStaleOnFetchAbort,_=b||s.allowStaleOnFetchRejection,v=_||s.noDeleteOnFetchRejection,k=m;if(this.#r[t]===m&&(!v||k.__staleWhileFetching===void 0?this.#A(e,"fetch"):b||(this.#r[t]=k.__staleWhileFetching)),_)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),k.__staleWhileFetching;if(k.__returned===k)throw f},d=(f,y)=>{let b=this.#o?.(e,i,l);b&&b instanceof Promise&&b.then(_=>f(_===void 0?void 0:_),y),o.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(f(void 0),s.allowStaleOnFetchAbort&&(f=_=>c(_,true)));});};s.status&&(s.status.fetchDispatched=true);let m=new Promise(d).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.#T)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof ur}async fetch(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=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:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:y=false,status:b,signal:_}=t;if(!this.#T)return b&&(b.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:b});let v={allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:b,signal:_},k=this.#a.get(e);if(k===void 0){b&&(b.fetch="miss");let R=this.#F(e,k,v,f);return R.__returned=R}else {let R=this.#r[k];if(this.#u(R)){let C=s&&R.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",C&&(b.returnedStale=true)),C?R.__staleWhileFetching:R.__returned=R}let O=this.#b(k);if(!y&&!O)return b&&(b.fetch="hit"),this.#j(k),n&&this.#C(k),b&&this.#s(b,k),R;let W=this.#F(e,k,v,f),S=W.__staleWhileFetching!==void 0&&s;return b&&(b.fetch=O?"stale":"refresh",S&&O&&(b.returnedStale=true)),S?W.__staleWhileFetching:W.__returned=W}}async forceFetch(e,t={}){let s=await this.fetch(e,t);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,t={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:i,...o}=t,a=this.get(e,o);if(!i&&a!==void 0)return a;let l=s(e,a,{options:o,context:n});return this.set(e,l,o),l}get(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=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.#s(o,a),this.#b(a)?(o&&(o.get="stale"),c?(o&&s&&l.__staleWhileFetching!==void 0&&(o.returnedStale=true),s?l.__staleWhileFetching:void 0):(i||this.#A(e,"expire"),o&&s&&(o.returnedStale=true),s?l:void 0)):(o&&(o.get="hit"),c?l.__staleWhileFetching:(this.#j(a),n&&this.#C(a),l))}else o&&(o.get="miss");}#U(e,t){this.#y[t]=e,this.#f[e]=t;}#j(e){e!==this.#d&&(e===this.#m?this.#m=this.#f[e]:this.#U(this.#y[e],this.#f[e]),this.#U(this.#d,e),this.#d=e);}delete(e){return this.#A(e,"delete")}#A(e,t){let s=false;if(this.#c!==0){let n=this.#a.get(e);if(n!==void 0)if(s=true,this.#c===1)this.#G(t);else {this.#O(n);let i=this.#r[n];if(this.#u(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#a.delete(e),this.#l[n]=void 0,this.#r[n]=void 0,n===this.#d)this.#d=this.#y[n];else if(n===this.#m)this.#m=this.#f[n];else {let o=this.#y[n];this.#f[o]=this.#f[n];let a=this.#f[n];this.#y[a]=this.#y[n];}this.#c--,this.#x.push(n);}}if(this.#h&&this.#g?.length){let n=this.#g,i;for(;i=n?.shift();)this.#n?.(...i);}return s}clear(){return this.#G("delete")}#G(e){for(let t of this.#E({allowStale:true})){let s=this.#r[t];if(this.#u(s))s.__abortController.abort(new Error("deleted"));else {let n=this.#l[t];this.#v&&this.#i?.(s,n,e),this.#h&&this.#g?.push([s,n,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#_&&this.#k&&(this.#_.fill(0),this.#k.fill(0)),this.#S&&this.#S.fill(0),this.#m=0,this.#d=0,this.#x.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,s;for(;s=t?.shift();)this.#n?.(...s);}}};var bl=typeof process=="object"&&process?process:{stdout:null,stderr:null},im=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof Tl||om(r)||am(r)),om=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Tl.Writable.prototype.pipe,am=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.write=="function"&&typeof r.end=="function",vt=Symbol("EOF"),Tt=Symbol("maybeEmitEnd"),At=Symbol("emittedEnd"),pr=Symbol("emittingEnd"),en=Symbol("emittedError"),dr=Symbol("closed"),_l=Symbol("read"),mr=Symbol("flush"),wl=Symbol("flushChunk"),at=Symbol("encoding"),fs=Symbol("decoder"),Ee=Symbol("flowing"),tn=Symbol("paused"),ys=Symbol("resume"),Ie=Symbol("buffer"),je=Symbol("pipes"),Me=Symbol("bufferLength"),Vi=Symbol("bufferPush"),hr=Symbol("bufferShift"),De=Symbol("objectMode"),ke=Symbol("destroyed"),Yi=Symbol("error"),Xi=Symbol("emitData"),vl=Symbol("emitEnd"),Zi=Symbol("emitEnd2"),mt=Symbol("async"),Qi=Symbol("abort"),gr=Symbol("aborted"),sn=Symbol("signal"),Wt=Symbol("dataListeners"),Ve=Symbol("discarded"),nn=r=>Promise.resolve().then(r),lm=r=>r(),cm=r=>r==="end"||r==="finish"||r==="prefinish",um=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,pm=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),fr=class{src;dest;opts;ondrain;constructor(e,t,s){this.src=e,this.dest=t,this.opts=s,this.ondrain=()=>e[ys](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},eo=class extends fr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,s){super(e,t,s),this.proxyErrors=n=>t.emit("error",n),e.on("error",this.proxyErrors);}},dm=r=>!!r.objectMode,mm=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",Pt=class extends EventEmitter{[Ee]=false;[tn]=false;[je]=[];[Ie]=[];[De];[at];[mt];[fs];[vt]=false;[At]=false;[pr]=false;[dr]=false;[en]=null;[Me]=0;[ke]=false;[sn];[gr]=false;[Wt]=0;[Ve]=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");dm(t)?(this[De]=true,this[at]=null):mm(t)?(this[at]=t.encoding,this[De]=false):(this[De]=false,this[at]=null),this[mt]=!!t.async,this[fs]=this[at]?new StringDecoder(this[at]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[Ie]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[je]});let{signal:s}=t;s&&(this[sn]=s,s.aborted?this[Qi]():s.addEventListener("abort",()=>this[Qi]()));}get bufferLength(){return this[Me]}get encoding(){return this[at]}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[De]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[mt]}set async(e){this[mt]=this[mt]||!!e;}[Qi](){this[gr]=true,this.emit("abort",this[sn]?.reason),this.destroy(this[sn]?.reason);}get aborted(){return this[gr]}set aborted(e){}write(e,t,s){if(this[gr])return false;if(this[vt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(s=t,t="utf8"),t||(t="utf8");let n=this[mt]?nn:lm;if(!this[De]&&!Buffer.isBuffer(e)){if(pm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(um(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[De]?(this[Ee]&&this[Me]!==0&&this[mr](true),this[Ee]?this.emit("data",e):this[Vi](e),this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee]):e.length?(typeof e=="string"&&!(t===this[at]&&!this[fs]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[at]&&(e=this[fs].write(e)),this[Ee]&&this[Me]!==0&&this[mr](true),this[Ee]?this.emit("data",e):this[Vi](e),this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee]):(this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee])}read(e){if(this[ke])return null;if(this[Ve]=false,this[Me]===0||e===0||e&&e>this[Me])return this[Tt](),null;this[De]&&(e=null),this[Ie].length>1&&!this[De]&&(this[Ie]=[this[at]?this[Ie].join(""):Buffer.concat(this[Ie],this[Me])]);let t=this[_l](e||null,this[Ie][0]);return this[Tt](),t}[_l](e,t){if(this[De])this[hr]();else {let s=t;e===s.length||e===null?this[hr]():typeof s=="string"?(this[Ie][0]=s.slice(e),t=s.slice(0,e),this[Me]-=e):(this[Ie][0]=s.subarray(e),t=s.subarray(0,e),this[Me]-=e);}return this.emit("data",t),!this[Ie].length&&!this[vt]&&this.emit("drain"),t}end(e,t,s){return typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t="utf8"),e!==void 0&&this.write(e,t),s&&this.once("end",s),this[vt]=true,this.writable=false,(this[Ee]||!this[tn])&&this[Tt](),this}[ys](){this[ke]||(!this[Wt]&&!this[je].length&&(this[Ve]=true),this[tn]=false,this[Ee]=true,this.emit("resume"),this[Ie].length?this[mr]():this[vt]?this[Tt]():this.emit("drain"));}resume(){return this[ys]()}pause(){this[Ee]=false,this[tn]=true,this[Ve]=false;}get destroyed(){return this[ke]}get flowing(){return this[Ee]}get paused(){return this[tn]}[Vi](e){this[De]?this[Me]+=1:this[Me]+=e.length,this[Ie].push(e);}[hr](){return this[De]?this[Me]-=1:this[Me]-=this[Ie][0].length,this[Ie].shift()}[mr](e=false){do;while(this[wl](this[hr]())&&this[Ie].length);!e&&!this[Ie].length&&!this[vt]&&this.emit("drain");}[wl](e){return this.emit("data",e),this[Ee]}pipe(e,t){if(this[ke])return e;this[Ve]=false;let s=this[At];return t=t||{},e===bl.stdout||e===bl.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,s?t.end&&e.end():(this[je].push(t.proxyErrors?new eo(this,e,t):new fr(this,e,t)),this[mt]?nn(()=>this[ys]()):this[ys]()),e}unpipe(e){let t=this[je].find(s=>s.dest===e);t&&(this[je].length===1?(this[Ee]&&this[Wt]===0&&(this[Ee]=false),this[je]=[]):this[je].splice(this[je].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let s=super.on(e,t);if(e==="data")this[Ve]=false,this[Wt]++,!this[je].length&&!this[Ee]&&this[ys]();else if(e==="readable"&&this[Me]!==0)super.emit("readable");else if(cm(e)&&this[At])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[en]){let n=t;this[mt]?nn(()=>n.call(this,this[en])):n.call(this,this[en]);}return s}removeListener(e,t){return this.off(e,t)}off(e,t){let s=super.off(e,t);return e==="data"&&(this[Wt]=this.listeners("data").length,this[Wt]===0&&!this[Ve]&&!this[je].length&&(this[Ee]=false)),s}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Wt]=0,!this[Ve]&&!this[je].length&&(this[Ee]=false)),t}get emittedEnd(){return this[At]}[Tt](){!this[pr]&&!this[At]&&!this[ke]&&this[Ie].length===0&&this[vt]&&(this[pr]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[dr]&&this.emit("close"),this[pr]=false);}emit(e,...t){let s=t[0];if(e!=="error"&&e!=="close"&&e!==ke&&this[ke])return false;if(e==="data")return !this[De]&&!s?false:this[mt]?(nn(()=>this[Xi](s)),true):this[Xi](s);if(e==="end")return this[vl]();if(e==="close"){if(this[dr]=true,!this[At]&&!this[ke])return false;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[en]=s,super.emit(Yi,s);let i=!this[sn]||this.listeners("error").length?super.emit("error",s):false;return this[Tt](),i}else if(e==="resume"){let i=super.emit("resume");return this[Tt](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let n=super.emit(e,...t);return this[Tt](),n}[Xi](e){for(let s of this[je])s.dest.write(e)===false&&this.pause();let t=this[Ve]?false:super.emit("data",e);return this[Tt](),t}[vl](){return this[At]?false:(this[At]=true,this.readable=false,this[mt]?(nn(()=>this[Zi]()),true):this[Zi]())}[Zi](){if(this[fs]){let t=this[fs].end();if(t){for(let s of this[je])s.dest.write(t);this[Ve]||super.emit("data",t);}}for(let t of this[je])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[De]||(e.dataLength=0);let t=this.promise();return this.on("data",s=>{e.push(s),this[De]||(e.dataLength+=s.length);}),await t,e}async concat(){if(this[De])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[at]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(ke,()=>t(new Error("stream destroyed"))),this.on("error",s=>t(s)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[Ve]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:false,value:n});if(this[vt])return t();let i,o,a=p=>{this.off("data",l),this.off("end",c),this.off(ke,u),t(),o(p);},l=p=>{this.off("error",a),this.off("end",c),this.off(ke,u),this.pause(),i({value:p,done:!!this[vt]});},c=()=>{this.off("error",a),this.off("data",l),this.off(ke,u),t(),i({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((p,d)=>{o=d,i=p,this.once(ke,u),this.once("error",a),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ve]=false;let e=false,t=()=>(this.pause(),this.off(Yi,t),this.off(ke,t),this.off("end",t),e=true,{done:true,value:void 0}),s=()=>{if(e)return t();let n=this.read();return n===null?t():{done:false,value:n}};return this.once("end",t),this.once(Yi,t),this.once(ke,t),{next:s,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[ke])return e?this.emit("error",e):this.emit(ke),this;this[ke]=true,this[Ve]=true,this[Ie].length=0,this[Me]=0;let t=this;return typeof t.close=="function"&&!this[dr]&&t.close(),e?this.emit("error",e):this.emit(ke),this}static get isStream(){return im}};var Tm=realpathSync.native,on={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Tm,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Rl=r=>!r||r===on||r===vn?on:{...on,...r,promises:{...on.promises,...r.promises||{}}},El=/^\\\\\?\\([a-z]:)\\?$/i,Rm=r=>r.replace(/\//g,"\\").replace(El,"$1\\"),Em=/[\\\/]/,et=0,Il=1,Ml=2,ht=4,Al=6,Pl=8,Ht=10,Ol=12,Qe=15,rn=~Qe,so=16,xl=32,an=64,lt=128,yr=256,_r=512,Sl=an|lt|_r,Im=1023,no=r=>r.isFile()?Pl:r.isDirectory()?ht:r.isSymbolicLink()?Ht:r.isCharacterDevice()?Ml:r.isBlockDevice()?Al:r.isSocket()?Ol:r.isFIFO()?Il:et,kl=new Map,ln=r=>{let e=kl.get(r);if(e)return e;let t=r.normalize("NFKD");return kl.set(r,t),t},Cl=new Map,br=r=>{let e=Cl.get(r);if(e)return e;let t=ln(r.toLowerCase());return Cl.set(r,t),t},wr=class extends Qs{constructor(){super({max:256});}},io=class extends Qs{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Ll=Symbol("PathScurry setAsCwd"),$e=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#n;get nlink(){return this.#n}#o;get uid(){return this.#o}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#d;get birthtimeMs(){return this.#d}#x;get atime(){return this.#x}#g;get mtime(){return this.#g}#S;get ctime(){return this.#S}#k;get birthtime(){return this.#k}#_;#v;#T;#h;#I;#C;#s;#P;#b;#M;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=et,s,n,i,o,a){this.name=e,this.#_=i?br(e):ln(e),this.#s=t&Im,this.nocase=i,this.roots=n,this.root=s||this,this.#P=o,this.#T=a.fullpath,this.#I=a.relative,this.#C=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Rl(a.fs);}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#P}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#O(n):this.#O(n)}#O(e){let t=this;for(let s of e)t=t.child(s);return t}children(){let e=this.#P.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#P.set(this,t),this.#s&=~so,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let s=this.children(),n=this.nocase?br(e):ln(e);for(let l of s)if(l.#_===n)return l;let i=this.parent?this.sep:"",o=this.#T?this.#T+i+e:void 0,a=this.newChild(e,et,{...t,parent:this,fullpath:o});return this.canReaddir()||(a.#s|=lt),s.push(a),a}relative(){if(this.isCWD)return "";if(this.#I!==void 0)return this.#I;let e=this.name,t=this.parent;if(!t)return this.#I=this.name;let s=t.relative();return s+(!s||!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 s=t.relativePosix();return s+(!s||!t.parent?"":"/")+e}fullpath(){if(this.#T!==void 0)return this.#T;let e=this.name,t=this.parent;if(!t)return this.#T=this.name;let n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#T=n}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#h=`//?/${n}`:this.#h=n}let e=this.parent,t=e.fullpathPosix(),s=t+(!t||!e.parent?"":"/")+this.name;return this.#h=s}isUnknown(){return (this.#s&Qe)===et}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.#s&Qe)===Pl}isDirectory(){return (this.#s&Qe)===ht}isCharacterDevice(){return (this.#s&Qe)===Ml}isBlockDevice(){return (this.#s&Qe)===Al}isFIFO(){return (this.#s&Qe)===Il}isSocket(){return (this.#s&Qe)===Ol}isSymbolicLink(){return (this.#s&Ht)===Ht}lstatCached(){return this.#s&xl?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#M}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.#s&Qe;return !(e!==et&&e!==Ht||this.#s&yr||this.#s&lt)}calledReaddir(){return !!(this.#s&so)}isENOENT(){return !!(this.#s&lt)}isNamed(e){return this.nocase?this.#_===br(e):this.#_===ln(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()),s=(await this.parent.realpath())?.resolve(t);if(s)return this.#b=s}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()),s=this.parent.realpathSync()?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}#L(e){this.#s|=so;for(let t=e.provisional;t<e.length;t++){let s=e[t];s&&s.#D();}}#D(){this.#s&lt||(this.#s=(this.#s|lt)&rn,this.#R());}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#D();}#E(){this.#s|=_r,this.#$();}#$(){if(this.#s&an)return;let e=this.#s;(e&Qe)===ht&&(e&=rn),this.#s=e|an,this.#R();}#N(e=""){e==="ENOTDIR"||e==="EPERM"?this.#$():e==="ENOENT"?this.#D():this.children().provisional=0;}#F(e=""){e==="ENOTDIR"?this.parent.#$():e==="ENOENT"&&this.#D();}#u(e=""){let t=this.#s;t|=yr,e==="ENOENT"&&(t|=lt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=rn),this.#s=t,e==="ENOTDIR"&&this.parent&&this.parent.#$();}#U(e,t){return this.#A(e,t)||this.#j(e,t)}#j(e,t){let s=no(e),n=this.newChild(e.name,s,{parent:this}),i=n.#s&Qe;return i!==ht&&i!==Ht&&i!==et&&(n.#s|=an),t.unshift(n),t.provisional++,n}#A(e,t){for(let s=t.provisional;s<t.length;s++){let n=t[s];if((this.nocase?br(e.name):ln(e.name))===n.#_)return this.#G(e,n,s,t)}}#G(e,t,s,n){let i=t.name;return t.#s=t.#s&rn|no(e),i!==e.name&&(t.name=e.name),s!==n.provisional&&(s===n.length-1?n.pop():n.splice(s,1),n.unshift(t)),n.provisional++,t}async lstat(){if((this.#s&lt)===0)try{return this.#q(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s&lt)===0)try{return this.#q(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#F(e.code);}}#q(e){let{atime:t,atimeMs:s,birthtime:n,birthtimeMs:i,blksize:o,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:p,ino:d,mode:m,mtime:h,mtimeMs:f,nlink:y,rdev:b,size:_,uid:v}=e;this.#x=t,this.#f=s,this.#k=n,this.#d=i,this.#p=o,this.#r=a,this.#S=l,this.#m=c,this.#t=u,this.#w=p,this.#a=d,this.#i=m,this.#g=h,this.#y=f,this.#n=y,this.#c=b,this.#l=_,this.#o=v;let k=no(e);this.#s=this.#s&rn|k|xl,k!==et&&k!==ht&&k!==Ht&&(this.#s|=an);}#W=[];#H=false;#z(e){this.#H=false;let t=this.#W.slice();this.#W.length=0,t.forEach(s=>s(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let s=this.children();if(this.calledReaddir()){let i=s.slice(0,s.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#W.push(e),this.#H)return;this.#H=true;let n=this.fullpath();this.#e.readdir(n,{withFileTypes:true},(i,o)=>{if(i)this.#N(i.code),s.provisional=0;else {for(let a of o)this.#U(a,s);this.#L(s);}this.#z(s.slice(0,s.provisional));});}#B;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.#B)await this.#B;else {let s=()=>{};this.#B=new Promise(n=>s=n);try{for(let n of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#U(n,e);this.#L(e);}catch(n){this.#N(n.code),e.provisional=0;}this.#B=void 0,s();}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 s of this.#e.readdirSync(t,{withFileTypes:!0}))this.#U(s,e);this.#L(e);}catch(s){this.#N(s.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#s&Sl)return false;let e=Qe&this.#s;return e===et||e===ht||e===Ht}shouldWalk(e,t){return (this.#s&ht)===ht&&!(this.#s&Sl)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#M)return this.#M;if(!((_r|yr|lt)&this.#s))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}realpathSync(){if(this.#M)return this.#M;if(!((_r|yr|lt)&this.#s))try{let e=this.#e.realpathSync(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}[Ll](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),s=[],n=this;for(;n&&n.parent;)t.add(n),n.#I=s.join(this.sep),n.#C=s.join("/"),n=n.parent,s.push("..");for(n=e;n&&n.parent&&!t.has(n);)n.#I=void 0,n.#C=void 0,n=n.parent;}},vr=class r extends $e{sep="\\";splitSep=Em;constructor(e,t=et,s,n,i,o,a){super(e,t,s,n,i,o,a);}newChild(e,t=et,s={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=Rm(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,s]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=s;return this.roots[e]=new bs(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(El,"$1\\"),e===t}},Tr=class r extends $e{splitSep="/";sep="/";constructor(e,t=et,s,n,i,o,a){super(e,t,s,n,i,o,a);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=et,s={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}},xr=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:i=16*1024,fs:o=on}={}){this.#n=Rl(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 wr,this.#t=new wr,this.#i=new io(i);let l=a.substring(this.rootPath.length).split(s);if(l.length===1&&!l[0]&&l.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,p=t.sep,d=this.rootPath,m=false;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(p),relativePosix:new Array(f).fill("..").join("/"),fullpath:d+=(m?"":p)+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 s=this.#e.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpath();return this.#e.set(t,n),n}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 s=this.#t.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,n),n}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 $e||(t=e,e=this.cwd);let{withFileTypes:s}=t;if(e.canReaddir()){let n=await e.readdir();return s?n:n.map(i=>i.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true}=t;return e.canReaddir()?s?e.readdirSync():e.readdirSync().map(n=>n.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 $e||(t=e.withFileTypes,e=this.cwd);let s=await e.readlink();return t?s:s?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=e.readlinkSync();return t?s:s?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=await e.realpath();return t?s:s?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=e.realpathSync();return t?s:s?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:i,walkFilter:o}=t,a=[];(!i||i(e))&&a.push(s?e:e.fullpath());let l=new Set,c=(p,d)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return d(m);let f=h.length;if(!f)return d();let y=()=>{--f===0&&d();};for(let b of h)(!i||i(b))&&a.push(s?b:b.fullpath()),n&&b.isSymbolicLink()?b.realpath().then(_=>_?.isUnknown()?_.lstat():_).then(_=>_?.shouldWalk(l,o)?c(_,y):y()):b.shouldWalk(l,o)?c(b,y):y();},true);},u=e;return new Promise((p,d)=>{c(u,m=>{if(m)return d(m);p(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:i,walkFilter:o}=t,a=[];(!i||i(e))&&a.push(s?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let p of u){(!i||i(p))&&a.push(s?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(n&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(l,o)&&l.add(d);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(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 $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:i,walkFilter:o}=t;(!i||i(e))&&(yield s?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 s?u:u.fullpath());let p=u;if(u.isSymbolicLink()){if(!(n&&(p=u.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(a,o)&&a.add(p);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:i,walkFilter:o}=t,a=new Pt({objectMode:true});(!i||i(e))&&a.write(s?e:e.fullpath());let l=new Set,c=[e],u=0,p=()=>{let d=false;for(;!d;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=(y,b,_=false)=>{if(y)return a.emit("error",y);if(n&&!_){let v=[];for(let k of b)k.isSymbolicLink()&&v.push(k.realpath().then(R=>R?.isUnknown()?R.lstat():R));if(v.length){Promise.all(v).then(()=>h(null,b,true));return}}for(let v of b)v&&(!i||i(v))&&(a.write(s?v:v.fullpath())||(d=true));u--;for(let v of b){let k=v.realpathCached()||v;k.shouldWalk(l,o)&&c.push(k);}d&&!a.flowing?a.once("drain",p):f||p();},f=true;m.readdirCB(h,true),f=false;}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:i,walkFilter:o}=t,a=new Pt({objectMode:true}),l=new Set;(!i||i(e))&&a.write(s?e:e.fullpath());let c=[e],u=0,p=()=>{let d=false;for(;!d;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=m.readdirSync();for(let f of h)(!i||i(f))&&(a.write(s?f:f.fullpath())||(d=true));u--;for(let f of h){let y=f;if(f.isSymbolicLink()){if(!(n&&(y=f.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(l,o)&&c.push(y);}}d&&!a.flowing&&a.once("drain",p);};return p(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Ll](t);}},bs=class extends xr{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,win32,"\\",{...t,nocase:s}),this.nocase=s;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new vr(this.rootPath,ht,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},_s=class extends xr{sep="/";constructor(e=process.cwd(),t={}){let{nocase:s=false}=t;super(e,posix,"/",{...t,nocase:s}),this.nocase=s;}parseRootPath(e){return "/"}newRoot(e){return new Tr(this.rootPath,ht,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},cn=class extends _s{constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,{...t,nocase:s});}};process.platform==="win32"?vr:Tr;var Dl=process.platform==="win32"?bs:process.platform==="darwin"?cn:_s;var Mm=r=>r.length>=1,Am=r=>r.length>=1,ws=class r{#e;#t;#i;length;#n;#o;#w;#c;#p;#a;#l=true;constructor(e,t,s,n){if(!Mm(e))throw new TypeError("empty pattern list");if(!Am(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,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=s,this.#n=n,this.#i===0){if(this.isUNC()){let[i,o,a,l,...c]=this.#e,[u,p,d,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[i,o,a,l,""].join("/"),y=[u,p,d,m,""].join("/");this.#e=[f,...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]===Ae}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(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 r(this.#e,this.#t,this.#i+1,this.#n),this.#o.#a=this.#a,this.#o.#p=this.#p,this.#o.#c=this.#c,this.#o):this.#o=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#n==="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.#n==="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 Pm=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",vs=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:s,noext:n,noglobstar:i,platform:o=Pm}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=o,this.mmopts={dot:true,nobrace:t,nocase:s,noext:n,noglobstar:i,optimizationLevel:2,platform:o,nocomment:true,nonegate:true};for(let a of e)this.add(a);}add(e){let t=new Ke(e,this.mmopts);for(let s=0;s<t.set.length;s++){let n=t.set[s],i=t.globParts[s];if(!n||!i)throw new Error("invalid pattern object");for(;n[0]==="."&&i[0]===".";)n.shift(),i.shift();let o=new ws(n,i,0,this.platform),a=new Ke(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(),s=`${t}/`,n=e.relative()||".",i=`${n}/`;for(let o of this.relative)if(o.match(n)||o.match(i))return true;for(let o of this.absolute)if(o.match(t)||o.match(s))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",s=(e.relative()||".")+"/";for(let n of this.relativeChildren)if(n.match(s))return true;for(let n of this.absoluteChildren)if(n.match(t))return true;return false}};var oo=class r{store;constructor(e=new Map){this.store=e;}copy(){return new r(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let s=e.fullpath(),n=this.store.get(s);n?n.add(t.globString()):this.store.set(s,new Set([t.globString()]));}},ao=class{store=new Map;add(e,t,s){let n=(t?2:0)|(s?1:0),i=this.store.get(e);this.store.set(e,i===void 0?n:n&i);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},lo=class{store=new Map;add(e,t){if(!e.canReaddir())return;let s=this.store.get(e);s?s.find(n=>n.globString()===t.globString())||s.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())}},un=class r{hasWalkedCache;matches=new ao;subwalks=new lo;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new oo;}processPatterns(e,t){this.patterns=t;let s=t.map(n=>[e,n]);for(let[n,i]of s){this.hasWalkedCache.storeWalked(n,i);let o=i.root(),a=i.isAbsolute()&&this.opts.absolute!==false;if(o){n=n.resolve(o==="/"&&this.opts.root!==void 0?this.opts.root:o);let p=i.rest();if(p)i=p;else {this.matches.add(n,true,false);continue}}if(n.isENOENT())continue;let l,c,u=false;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)n=n.resolve(l),i=c,u=true;if(l=i.pattern(),c=i.rest(),u){if(this.hasWalkedCache.hasWalked(n,i))continue;this.hasWalkedCache.storeWalked(n,i);}if(typeof l=="string"){let p=l===".."||l===""||l===".";this.matches.add(n.resolve(l),a,p);continue}else if(l===Ae){(!n.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(n,i);let p=c?.pattern(),d=c?.rest();if(!c||(p===""||p===".")&&!d)this.matches.add(n,a,p===""||p===".");else if(p===".."){let m=n.parent||n;d?this.hasWalkedCache.hasWalked(m,d)||this.subwalks.add(m,d):this.matches.add(m,a,true);}}else l instanceof RegExp&&this.subwalks.add(n,i);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let s=this.subwalks.get(e),n=this.child();for(let i of t)for(let o of s){let a=o.isAbsolute(),l=o.pattern(),c=o.rest();l===Ae?n.testGlobstar(i,o,c,a):l instanceof RegExp?n.testRegExp(i,l,c,a):n.testString(i,l,c,a);}return n}testGlobstar(e,t,s,n){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,n,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(s&&t.checkFollowGlobstar()?this.subwalks.add(e,s):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),s){let i=s.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,s.rest(),n);else if(i===".."){let o=e.parent||e;this.subwalks.add(o,s);}else i instanceof RegExp&&this.testRegExp(e,i,s.rest(),n);}}testRegExp(e,t,s,n){t.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}testString(e,t,s,n){e.isNamed(t)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}};var Om=(r,e)=>typeof r=="string"?new vs([r],e):Array.isArray(r)?new vs(r,e):r,Sr=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,s){if(this.patterns=e,this.path=t,this.opts=s,this.#i=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==false,(s.ignore||!this.includeChildMatches)&&(this.#t=Om(s.ignore??[],s),!this.includeChildMatches&&typeof this.#t.add!="function")){let n="cannot ignore child matches, ignore lacks add() method.";throw new Error(n)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#n(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 s;if(this.opts.realpath){if(s=e.realpathCached()||await e.realpath(),!s)return;e=s;}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.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||e.realpathSync(),!s)return;e=s;}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.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i);}let s=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let n=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(s){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+n);}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+n:"."+n);}}async match(e,t,s){let n=await this.matchCheck(e,s);n&&this.matchFinish(n,t);}matchSync(e,t,s){let n=this.matchCheckSync(e,s);n&&this.matchFinish(n,t);}walkCB(e,t,s){this.signal?.aborted&&s(),this.walkCB2(e,t,new un(this.opts),s);}walkCB2(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(e,t,s,n));return}s.processPatterns(e,t);let i=1,o=()=>{--i===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||(i++,this.match(a,l,c).then(()=>o()));for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,s,o):a.readdirCB((c,u)=>this.walkCB3(a,u,s,o),true);}o();}walkCB3(e,t,s,n){s=s.filterEntries(e,t);let i=1,o=()=>{--i===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||(i++,this.match(a,l,c).then(()=>o()));for(let[a,l]of s.subwalks.entries())i++,this.walkCB2(a,l,s.child(),o);o();}walkCBSync(e,t,s){this.signal?.aborted&&s(),this.walkCB2Sync(e,t,new un(this.opts),s);}walkCB2Sync(e,t,s,n){if(this.#o(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,s,n));return}s.processPatterns(e,t);let i=1,o=()=>{--i===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;i++;let l=a.readdirSync();this.walkCB3Sync(a,l,s,o);}o();}walkCB3Sync(e,t,s,n){s=s.filterEntries(e,t);let i=1,o=()=>{--i===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let[a,l]of s.subwalks.entries())i++,this.walkCB2Sync(a,l,s.child(),o);o();}},pn=class extends Sr{matches=new Set;constructor(e,t,s){super(e,t,s);}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}},dn=class extends Sr{results;constructor(e,t,s){super(e,t,s),this.results=new Pt({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 Dm=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ct=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||Dm,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"?bs:t.platform==="darwin"?cn:t.platform?_s:Dl;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",n={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,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 Ke(l,n)),[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 ws(l,u,0,this.platform)});}async walk(){return [...await new pn(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 pn(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 dn(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 dn(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 co=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Ke(t,e).hasMagic())return true;return false};function kr(r,e={}){return new ct(r,e).streamSync()}function Nl(r,e={}){return new ct(r,e).stream()}function Fl(r,e={}){return new ct(r,e).walkSync()}async function $l(r,e={}){return new ct(r,e).walk()}function Cr(r,e={}){return new ct(r,e).iterateSync()}function Ul(r,e={}){return new ct(r,e).iterate()}var $m=kr,Nm=Object.assign(Nl,{sync:kr}),Fm=Cr,Um=Object.assign(Ul,{sync:Cr}),jm=Object.assign(Fl,{stream:kr,iterate:Cr}),Ts=Object.assign($l,{glob:$l,globSync:Fl,sync:jm,globStream:Nl,stream:Nm,globStreamSync:kr,streamSync:$m,globIterate:Ul,iterate:Um,globIterateSync:Cr,iterateSync:Fm,Glob:ct,hasMagic:co,escape:ms,unescape:ot});Ts.glob=Ts;var mn=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
630
- `),n=[],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<s.length;l++){let c=s[l],u=l+1;if(o){let f=c.match(/^(\s*)/)?.[1].length||0;c.trim()&&f<=a&&!c.match(/^\s*[})\]]/)&&(o.endLine=l,n.push(o),o=null);}if(c.trim().startsWith("//")||c.trim().startsWith("/*")||!c.trim())continue;let p=c.match(i.class);if(p){if(o&&(o.endLine=l,n.push(o)),a=p[1].length,o={name:p[4],kind:"class",startLine:u,endLine:this.findSymbolEnd(s,l),children:[]},l>0){let f=s[l-1].trim();f.startsWith("/**")||f.startsWith("/*")?o.docstring=this.extractDocstring(s,l-1):f.startsWith("//")&&(o.docstring=f.replace(/^\/\/\s*/,""));}continue}let d=c.match(i.interface);if(d){n.push({name:d[3],kind:"interface",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let m=c.match(i.type);if(m){n.push({name:m[3],kind:"type",startLine:u,endLine:this.findTypeEnd(s,l)});continue}let h=c.match(i.enum);if(h){n.push({name:h[3],kind:"enum",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}if(!o){let f=c.match(i.function);if(f){n.push({name:f[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let y=c.match(i.constFunction);if(y){n.push({name:y[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let b=c.match(i.variable);if(b&&!i.constFunction.test(c)){n.push({name:b[4],kind:"variable",startLine:u,endLine:u});continue}}if(o){let f=c.match(i.method);if(f&&!["if","for","while","switch","catch","constructor"].includes(f[5])){let b={name:f[5],kind:(f[5]==="constructor","method"),startLine:u,endLine:this.findSymbolEnd(s,l),parent:o.name};o.children.push(b);continue}let y=c.match(i.property);if(y&&!["if","for","while","switch","catch","return","const","let","var"].includes(y[5])){let b={name:y[5],kind:"variable",startLine:u,endLine:u,parent:o.name};o.children.push(b);}}}return o&&(o.endLine=s.length,n.push(o)),n}findSymbolEnd(e,t){return It(e,t)}findTypeEnd(e,t){for(let s=t;s<e.length;s++){let n=e[s];if(n.includes(";")||s>t&&/^(export|type|interface|class|function|const|let|var)/.test(n.trim()))return s+1}return t+1}extractDocstring(e,t){let s=[],n=t;for(;n>=0;){let i=e[n].trim();if(i.startsWith("/**")||i.startsWith("/*"))break;n--;}for(let i=n;i<=t;i++){let o=e[i].trim();o=o.replace(/^\/\*\*?\s*/,"").replace(/\*\/\s*$/,"").replace(/^\*\s?/,""),o&&s.push(o);}return s.join(`
631
- `)}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|async\\s+function|const|let|var)\\s+${s}\\s*[=(<]`;case "class":return `class\\s+${s}(\\s+extends|\\s+implements|\\s*\\{)`;case "interface":return `interface\\s+${s}(\\s+extends|\\s*\\{)`;case "type":return `type\\s+${s}\\s*[=<]`;case "enum":return `enum\\s+${s}\\s*\\{`;case "method":return `(async\\s+)?${s}\\s*\\(`;case "variable":return `(const|let|var)\\s+${s}\\s*[=:]`;default:return `(function|class|interface|type|enum|const|let|var)\\s+${s}|${s}\\s*(=|\\()`}}};var hn=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let s=e.split(`
632
- `),n=[],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<s.length;l++){let c=s[l],u=l+1,p=c.match(/^(\s*)/)?.[1].length||0;if(o&&c.trim()&&p<=a&&(o.endLine=l,n.push(o),o=null,a=-1),c.trim().startsWith("#")||!c.trim())continue;let d=c.match(i.class);if(d){o&&(o.endLine=l,n.push(o)),a=d[1].length,o={name:d[2],kind:"class",startLine:u,endLine:this.findClassEnd(s,l,a),children:[],docstring:this.extractDocstring(s,l+1)};continue}let m=c.match(i.function);if(m){let h=m[1].length,f=m[3],y=o&&h>a,b={name:f,kind:y?"method":"function",startLine:u,endLine:this.findFunctionEnd(s,l,h),docstring:this.extractDocstring(s,l+1)};y&&o?(b.parent=o.name,o.children.push(b)):n.push(b);continue}if(!o&&c.match(i.variable)){let h=c.match(i.variable);h&&n.push({name:h[1],kind:"constant",startLine:u,endLine:u});}}return o&&(o.endLine=s.length,n.push(o)),n}findClassEnd(e,t,s){for(let n=t+1;n<e.length;n++){let i=e[n];if(!i.trim())continue;if((i.match(/^(\s*)/)?.[1].length||0)<=s)return n}return e.length}findFunctionEnd(e,t,s){let n=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>s){n=true;continue}if(n&&a<=s)return i}return e.length}extractDocstring(e,t){if(t>=e.length)return;let s=e[t].trim();if(s.startsWith('"""')||s.startsWith("'''")){let n=s.startsWith('"""')?'"""':"'''";if(s.endsWith(n)&&s.length>6)return s.slice(3,-3);let i=[s.slice(3)];for(let o=t+1;o<e.length;o++){let a=e[o].trim();if(a.endsWith(n)){i.push(a.slice(0,-3));break}i.push(a);}return i.join(`
633
- `).trim()}}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":case "method":return `(async\\s+)?def\\s+${s}\\s*\\(`;case "class":return `class\\s+${s}(\\s*\\(|\\s*:)`;case "variable":case "constant":return `^${s}\\s*[=:]`;default:return `(def|class)\\s+${s}|^${s}\\s*[=:]`}}};var gn=class{languageId="generic";extensions=["*"];async parse(e,t){let s=e.split(`
634
- `),n=[],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<s.length;o++){let a=s[o],l=o+1;if(!this.isComment(a)){for(let c of i.function){let u=a.match(c);if(u){let p=this.extractName(u);p&&!this.isKeyword(p)&&n.push({name:p,kind:"function",startLine:l,endLine:It(s,o)});break}}for(let c of i.class){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"class",startLine:l,endLine:It(s,o)});break}}for(let c of i.interface){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"interface",startLine:l,endLine:It(s,o)});break}}for(let c of i.constant){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"constant",startLine:l,endLine:l});break}}}}return n}extractName(e){for(let t=e.length-1;t>0;t--){let s=e[t];if(s&&/^\w+$/.test(s)&&!this.isModifier(s))return s}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 s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|func|fn|def)\\s+${s}|${s}\\s*\\(`;case "class":return `(class|struct|type)\\s+${s}`;case "interface":return `(interface|trait)\\s+${s}`;default:return `(function|class|interface|struct|type|func|fn|def)\\s+${s}|${s}\\s*[=(]`}}};var fn=class{parsers=new Map;constructor(){this.register(new mn),this.register(new hn),this.register(new gn);}register(e){this.parsers.set(e.languageId,e);for(let t of e.extensions){let s=this.getLanguageFromExtension(t);s&&this.parsers.has(s);}}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")}};var Gm="1.0.0",Rr=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Ua,...t},this.parserRegistry=new fn;}get indexDir(){return Y.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=Y.join(this.indexDir,"meta.json");return Ga(e)}async loadMetadata(){if(this.metadata)return this.metadata;let e=Y.join(this.indexDir,"meta.json");try{let t=await Z.readFile(e,"utf-8");return this.metadata=JSON.parse(t),this.metadata}catch{return null}}async saveMetadata(){if(!this.metadata)return;await Vs(this.indexDir);let e=Y.join(this.indexDir,"meta.json");await Z.writeFile(e,JSON.stringify(this.metadata,null,2));}async buildIndex(e={}){let t=Date.now(),s=[],{paths:n=this.config.include,languages:i=this.config.languages,force:o=false,onProgress:a}=e;await Vs(this.indexDir),await Vs(Y.join(this.indexDir,"files"));let l=[];for(let p of n){let d=await Ts(p,{cwd:this.workspacePath,absolute:true,ignore:this.config.exclude});for(let m of d){let h=Gi(m);h&&i.includes(h)&&l.push(m);}}let c=0,u=0;for(let p=0;p<l.length;p++){let d=l[p];a?.(p+1,l.length,d);try{if(!o){let h=await this.getFileIndex(d);if(h){let f=await Z.stat(d);if(h.mtime>=f.mtimeMs){u+=h.symbols.length,c++;continue}}}let m=await this.indexFile(d);m&&(await this.saveFileIndex(m),this.fileIndexCache.set(d,m),u+=m.symbols.length,c++);}catch(m){s.push({file:d,error:m.message});}}return this.metadata={version:Gm,createdAt:this.metadata?.createdAt||Date.now(),updatedAt:Date.now(),fileCount:c,symbolCount:u,languages:i,indexDir:this.config.cacheDir},await this.saveMetadata(),{success:s.length===0,filesIndexed:c,symbolsFound:u,timeMs:Date.now()-t,errors:s}}async indexFile(e){let t=Gi(e);if(!t)return null;let s=this.parserRegistry.getParser(t);if(!s)return null;try{let n=await Z.readFile(e,"utf-8"),i=await Z.stat(e),o=await s.parse(n,e),a=this.extractImports(n,t),l=this.extractExports(n,t);return {path:e,hash:ja(n),mtime:i.mtimeMs,totalLines:n.split(`
635
- `).length,symbols:o,imports:a,exports:l}}catch{return null}}extractImports(e,t){let s=[],n=e.split(`
636
- `);if(["typescript","javascript"].includes(t)){let i=/^import\s+(?:(?:\{([^}]+)\}|(\w+))\s+from\s+)?['"]([^'"]+)['"]/;n.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[1]?.split(",").map(u=>u.trim())||(l[2]?[l[2]]:[]);s.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+))/;n.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[1]||l[3],u=l[2]?.split(",").map(p=>p.trim())||[];s.push({module:c,line:a+1,names:u});}});}return s}extractExports(e,t){let s=[],n=e.split(`
637
- `);if(["typescript","javascript"].includes(t)){let i=/^export\s+(?:(default)\s+)?(?:(class|function|const|let|var|interface|type|enum)\s+)?(\w+)?/;n.forEach((o,a)=>{let l=o.match(i);if(l){let c=l[2],u=l[3]||(l[1]?"default":"");u&&s.push({name:u,line:a+1,kind:c});}});}return s}async getFileIndex(e){if(this.fileIndexCache.has(e))return this.fileIndexCache.get(e);let t=this.getFileIndexPath(e);try{let s=await Z.readFile(t,"utf-8"),n=JSON.parse(s);return this.fileIndexCache.set(e,n),n}catch{return null}}async saveFileIndex(e){let t=this.getFileIndexPath(e.path);await Vs(Y.dirname(t)),await Z.writeFile(t,JSON.stringify(e,null,2));}getFileIndexPath(e){let s=Y.relative(this.workspacePath,e).replace(/[/\\]/g,"_").replace(/\./g,"_");return Y.join(this.indexDir,"files",`${s}.json`)}async searchSymbol(e){let{query:t,kind:s,fuzzy:n=false,limit:i=20}=e,o=[],a=Y.join(this.indexDir,"files");try{let l=await Z.readdir(a);for(let c of l)if(c.endsWith(".json"))try{let u=await Z.readFile(Y.join(a,c),"utf-8"),p=JSON.parse(u);for(let d of p.symbols){if(s&&d.kind!==s)continue;let m=0;if(n){if(m=Bi(t.toLowerCase(),d.name.toLowerCase()),m<.5)continue}else {if(!d.name.toLowerCase().includes(t.toLowerCase()))continue;m=d.name.toLowerCase()===t.toLowerCase()?1:.8;}if(o.push({symbol:d,file:p.path,score:m}),d.children)for(let h of d.children){if(s&&h.kind!==s)continue;let f=0;if(n){if(f=Bi(t.toLowerCase(),h.name.toLowerCase()),f<.5)continue}else {if(!h.name.toLowerCase().includes(t.toLowerCase()))continue;f=h.name.toLowerCase()===t.toLowerCase()?1:.8;}o.push({symbol:{...h,parent:d.name},file:p.path,score:f});}}}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 Z.unlink(t);}catch{}}async clear(){this.fileIndexCache.clear(),this.metadata=null;try{await Z.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 s=Y.join(this.indexDir,"files"),n=await Z.readdir(s);for(let i of n){let o=await Z.stat(Y.join(s,i));t+=o.size;}}catch{}return {hasIndex:true,fileCount:e.fileCount,symbolCount:e.symbolCount,lastUpdated:new Date(e.updatedAt),size:t}}};function uo(r,e){return new Rr(r,e)}var xs=null,Ss=null,Ir=null,qt={small:as,large:1e3},jl=12e3,Bm=120,Er=20,Wm=3,Hm=200,po=200;function qm(r){return (!xs||Ir!==r)&&(xs=Wi(r),Ir=r,Ss&&xs.setIndexManager(Ss)),xs}function yn(r){return (!Ss||Ir!==r)&&(Ss=uo(r),Ir=r,xs&&xs.setIndexManager(Ss)),Ss}function zm(r){return process.cwd()}function gt(r){let e=zm();return Y.relative(e,r)||r}function Gl(r,e){let t=Y.relative(r,e);return t===""?true:!t.startsWith("..")&&!Y.isAbsolute(t)}function Jm(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function ho(r){let e=r||process.cwd(),s=await yn(e).getStats();return {hasIndex:s.hasIndex,fileCount:s.fileCount,symbolCount:s.symbolCount,lastUpdated:s.lastUpdated}}async function Bl(r){let e=await ho(r);return e.hasIndex?`
629
+ >>> no match, partial?`,e,d,t,m),d===l))}let f;if(typeof u=="string"?(f=p===u,this.debug("string match",u,p,f)):(f=u.test(p),this.debug("pattern match",u,p,f)),!f)return false}if(i===l&&a===c)return true;if(i===l)return s;if(a===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return fl(this.pattern,this.options)}parse(e){Zs(e);let t=this.options;if(e==="**")return Ae;if(e==="")return "";let s,n=null;(s=e.match(Bd))?n=t.dot?Hd:Wd:(s=e.match(Pd))?n=(t.nocase?t.dot?$d:Dd:t.dot?Ld:Od)(s[1]):(s=e.match(qd))?n=(t.nocase?t.dot?Jd:zd:t.dot?Kd:Vd)(s):(s=e.match(Nd))?n=t.dot?Ud:Fd:(s=e.match(jd))&&(n=Gd);let o=ms.fromGlob(e,this.options).toMMPattern();return n&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:n}),o}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,s=t.noglobstar?Zd:t.dot?Qd:em,n=new Set(t.nocase?["i"]:[]),o=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let p of u.flags.split(""))n.add(p);return typeof u=="string"?om(u):u===Ae?Ae:u._src});return c.forEach((u,p)=>{let d=c[p+1],m=c[p-1];u!==Ae||m===Ae||(m===void 0?d!==void 0&&d!==Ae?c[p+1]="(?:\\/|"+s+"\\/)?"+d:c[p]=s:d===void 0?c[p-1]=m+"(?:\\/|"+s+")?":d!==Ae&&(c[p-1]=m+"(?:\\/|\\/"+s+"\\/)"+d,c[p+1]=Ae));}),c.filter(u=>u!==Ae).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];o="^"+i+o+a+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...n].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 s=this.options;this.isWindows&&(e=e.split("\\").join("/"));let n=this.slashSplit(e);this.debug(this.pattern,"split",n);let o=this.set;this.debug(this.pattern,"set",o);let i=n[n.length-1];if(!i)for(let a=n.length-2;!i&&a>=0;a--)i=n[a];for(let a=0;a<o.length;a++){let l=o[a],c=n;if(s.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return s.flipNegate?true:!this.negate}return s.flipNegate?false:this.negate}static defaults(e){return Ue.defaults(e).Minimatch}};Ue.AST=ms;Ue.Minimatch=Ke;Ue.escape=hs;Ue.unescape=it;var gs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,bl=new Set,Vo=typeof process=="object"&&process?process:{},_l=(r,e,t,s)=>{typeof Vo.emitWarning=="function"?Vo.emitWarning(r,e,t,s):console.error(`[${t}] ${e}: ${r}`);},pr=globalThis.AbortController,yl=globalThis.AbortSignal;if(typeof pr>"u"){yl=class{onabort;_onabort=[];reason;aborted=false;addEventListener(s,n){this._onabort.push(n);}},pr=class{constructor(){e();}signal=new yl;abort(s){if(!this.signal.aborted){this.signal.reason=s,this.signal.aborted=true;for(let n of this.signal._onabort)n(s);this.signal.onabort?.(s);}}};let r=Vo.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=false,_l("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));};}var im=r=>!bl.has(r);var Mt=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),wl=r=>Mt(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?fs:null:null,fs=class extends Array{constructor(e){super(e),this.fill(0);}},Yo=class r{heap;length;static#e=false;static create(e){let t=wl(e);if(!t)return [];r.#e=true;let s=new r(e,t);return r.#e=false,s}constructor(e,t){if(!r.#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]}},en=class r{#e;#t;#o;#n;#i;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#a;#l;#r;#f;#y;#m;#d;#x;#g;#S;#k;#_;#v;#T;#h;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#_,sizes:e.#S,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#d},free:e.#x,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,s,n,o)=>e.#F(t,s,n,o),moveToTail:t=>e.#j(t),indexes:t=>e.#R(t),rindexes:t=>e.#E(t),isStale:t=>e.#b(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#w}get dispose(){return this.#o}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:s,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:p,noUpdateTTL:d,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:y,memoMethod:b,noDeleteOnFetchRejection:_,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:R,ignoreFetchAbort:O}=e;if(t!==0&&!Mt(t))throw new TypeError("max option must be a nonnegative integer");let W=t?wl(t):Array;if(!W)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,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(b!==void 0&&typeof b!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=b,y!==void 0&&typeof y!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=y,this.#T=!!y,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new W(t),this.#y=new W(t),this.#m=0,this.#d=0,this.#x=Yo.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#o=c),typeof u=="function"?(this.#n=u,this.#g=[]):(this.#n=void 0,this.#g=void 0),this.#v=!!this.#o,this.#h=!!this.#n,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!d,this.noDeleteOnFetchRejection=!!_,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!R,this.ignoreFetchAbort=!!O,this.maxEntrySize!==0){if(this.#t!==0&&!Mt(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!Mt(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#M();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=Mt(n)||n===0?n:1,this.ttlAutopurge=!!o,this.ttl=s||0,this.ttl){if(!Mt(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#I();}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 F="LRU_CACHE_UNBOUNDED";im(F)&&(bl.add(F),_l("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",F,r));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#I(){let e=new fs(this.#e),t=new fs(this.#e);this.#_=e,this.#k=t,this.#P=(o,i,a=gs.now())=>{if(t[o]=i!==0?a:0,e[o]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(o)&&this.#A(this.#l[o],"expire");},i+1);l.unref&&l.unref();}},this.#C=o=>{t[o]=e[o]!==0?gs.now():0;},this.#s=(o,i)=>{if(e[i]){let a=e[i],l=t[i];if(!a||!l)return;o.ttl=a,o.start=l,o.now=s||n();let c=o.now-l;o.remainingTTL=a-c;}};let s=0,n=()=>{let o=gs.now();if(this.ttlResolution>0){s=o;let i=setTimeout(()=>s=0,this.ttlResolution);i.unref&&i.unref();}return o};this.getRemainingTTL=o=>{let i=this.#a.get(o);if(i===void 0)return 0;let a=e[i],l=t[i];if(!a||!l)return 1/0;let c=(s||n())-l;return a-c},this.#b=o=>{let i=t[o],a=e[o];return !!a&&!!i&&(s||n())-i>a};}#C=()=>{};#s=()=>{};#P=()=>{};#b=()=>false;#M(){let e=new fs(this.#e);this.#p=0,this.#S=e,this.#O=t=>{this.#p-=e[t],e[t]=0;},this.#D=(t,s,n,o)=>{if(this.#u(s))return 0;if(!Mt(n))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(n=o(s,t),!Mt(n))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 n},this.#L=(t,s,n)=>{if(e[t]=s,this.#t){let o=this.#t-e[t];for(;this.#p>o;)this.#N(true);}this.#p+=e[t],n&&(n.entrySize=s,n.totalCalculatedSize=this.#p);};}#O=e=>{};#L=(e,t,s)=>{};#D=(e,t,s,n)=>{if(s||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#d;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#E({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#d));)t=this.#f[t];}#$(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())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.#E())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.#R()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*rkeys(){for(let e of this.#E()){let t=this.#l[e];t!==void 0&&!this.#u(this.#r[e])&&(yield t);}}*values(){for(let e of this.#R())this.#r[e]!==void 0&&!this.#u(this.#r[e])&&(yield this.#r[e]);}*rvalues(){for(let e of this.#E())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 s of this.#R()){let n=this.#r[s],o=this.#u(n)?n.__staleWhileFetching:n;if(o!==void 0&&e(o,this.#l[s],this))return this.get(this.#l[s],t)}}forEach(e,t=this){for(let s of this.#R()){let n=this.#r[s],o=this.#u(n)?n.__staleWhileFetching:n;o!==void 0&&e.call(t,o,this.#l[s],this);}}rforEach(e,t=this){for(let s of this.#E()){let n=this.#r[s],o=this.#u(n)?n.__staleWhileFetching:n;o!==void 0&&e.call(t,o,this.#l[s],this);}}purgeStale(){let e=false;for(let t of this.#E({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 s=this.#r[t],n=this.#u(s)?s.__staleWhileFetching:s;if(n===void 0)return;let o={value:n};if(this.#_&&this.#k){let i=this.#_[t],a=this.#k[t];if(i&&a){let l=i-(gs.now()-a);o.ttl=l,o.start=Date.now();}}return this.#S&&(o.size=this.#S[t]),o}dump(){let e=[];for(let t of this.#R({allowStale:true})){let s=this.#l[t],n=this.#r[t],o=this.#u(n)?n.__staleWhileFetching:n;if(o===void 0||s===void 0)continue;let i={value:o};if(this.#_&&this.#k){i.ttl=this.#_[t];let a=gs.now()-this.#k[t];i.start=Math.floor(Date.now()-a);}this.#S&&(i.size=this.#S[t]),e.unshift([s,i]);}return e}load(e){this.clear();for(let[t,s]of e){if(s.start){let n=Date.now()-s.start;s.start=gs.now()-n;}this.set(t,s.value,s);}}set(e,t,s={}){if(t===void 0)return this.delete(e),this;let{ttl:n=this.ttl,start:o,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=s,{noUpdateTTL:c=this.noUpdateTTL}=s,u=this.#D(e,t,s.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#A(e,"set"),this;let p=this.#c===0?void 0:this.#a.get(e);if(p===void 0)p=this.#c===0?this.#d:this.#x.length!==0?this.#x.pop():this.#c===this.#e?this.#N(false):this.#c,this.#l[p]=e,this.#r[p]=t,this.#a.set(e,p),this.#f[this.#d]=p,this.#y[p]=this.#d,this.#d=p,this.#c++,this.#L(p,u,l),l&&(l.set="add"),c=false;else {this.#j(p);let d=this.#r[p];if(t!==d){if(this.#T&&this.#u(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=d;m!==void 0&&!i&&(this.#v&&this.#o?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]));}else i||(this.#v&&this.#o?.(d,e,"set"),this.#h&&this.#g?.push([d,e,"set"]));if(this.#O(p),this.#L(p,u,l),this.#r[p]=t,l){l.set="replace";let m=d&&this.#u(d)?d.__staleWhileFetching:d;m!==void 0&&(l.oldValue=m);}}else l&&(l.set="update");}if(n!==0&&!this.#_&&this.#I(),this.#_&&(c||this.#P(p,n,o),l&&this.#s(l,p)),!i&&this.#h&&this.#g){let d=this.#g,m;for(;m=d?.shift();)this.#n?.(...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.#g){let e=this.#g,t;for(;t=e?.shift();)this.#n?.(...t);}}}#N(e){let t=this.#m,s=this.#l[t],n=this.#r[t];return this.#T&&this.#u(n)?n.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#o?.(n,s,"evict"),this.#h&&this.#g?.push([n,s,"evict"])),this.#O(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#x.push(t)),this.#c===1?(this.#m=this.#d=0,this.#x.length=0):this.#m=this.#f[t],this.#a.delete(s),this.#c--,t}has(e,t={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:n}=t,o=this.#a.get(e);if(o!==void 0){let i=this.#r[o];if(this.#u(i)&&i.__staleWhileFetching===void 0)return false;if(this.#b(o))n&&(n.has="stale",this.#s(n,o));else return s&&this.#C(o),n&&(n.has="hit",this.#s(n,o)),true}else n&&(n.has="miss");return false}peek(e,t={}){let{allowStale:s=this.allowStale}=t,n=this.#a.get(e);if(n===void 0||!s&&this.#b(n))return;let o=this.#r[n];return this.#u(o)?o.__staleWhileFetching:o}#F(e,t,s,n){let o=t===void 0?void 0:this.#r[t];if(this.#u(o))return o;let i=new pr,{signal:a}=s;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let l={signal:i.signal,options:s,context:n},c=(f,y=false)=>{let{aborted:b}=i.signal,_=s.ignoreFetchAbort&&f!==void 0;if(s.status&&(b&&!y?(s.status.fetchAborted=true,s.status.fetchError=i.signal.reason,_&&(s.status.fetchAbortIgnored=true)):s.status.fetchResolved=true),b&&!_&&!y)return p(i.signal.reason);let v=m;return this.#r[t]===m&&(f===void 0?v.__staleWhileFetching?this.#r[t]=v.__staleWhileFetching:this.#A(e,"fetch"):(s.status&&(s.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(s.status&&(s.status.fetchRejected=true,s.status.fetchError=f),p(f)),p=f=>{let{aborted:y}=i.signal,b=y&&s.allowStaleOnFetchAbort,_=b||s.allowStaleOnFetchRejection,v=_||s.noDeleteOnFetchRejection,k=m;if(this.#r[t]===m&&(!v||k.__staleWhileFetching===void 0?this.#A(e,"fetch"):b||(this.#r[t]=k.__staleWhileFetching)),_)return s.status&&k.__staleWhileFetching!==void 0&&(s.status.returnedStale=true),k.__staleWhileFetching;if(k.__returned===k)throw f},d=(f,y)=>{let b=this.#i?.(e,o,l);b&&b instanceof Promise&&b.then(_=>f(_===void 0?void 0:_),y),i.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(f(void 0),s.allowStaleOnFetchAbort&&(f=_=>c(_,true)));});};s.status&&(s.status.fetchDispatched=true);let m=new Promise(d).then(c,u),h=Object.assign(m,{__abortController:i,__staleWhileFetching:o,__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.#T)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof pr}async fetch(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:y=false,status:b,signal:_}=t;if(!this.#T)return b&&(b.fetch="get"),this.get(e,{allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:b});let v={allowStale:s,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:b,signal:_},k=this.#a.get(e);if(k===void 0){b&&(b.fetch="miss");let R=this.#F(e,k,v,f);return R.__returned=R}else {let R=this.#r[k];if(this.#u(R)){let C=s&&R.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",C&&(b.returnedStale=true)),C?R.__staleWhileFetching:R.__returned=R}let O=this.#b(k);if(!y&&!O)return b&&(b.fetch="hit"),this.#j(k),n&&this.#C(k),b&&this.#s(b,k),R;let W=this.#F(e,k,v,f),S=W.__staleWhileFetching!==void 0&&s;return b&&(b.fetch=O?"stale":"refresh",S&&O&&(b.returnedStale=true)),S?W.__staleWhileFetching:W.__returned=W}}async forceFetch(e,t={}){let s=await this.fetch(e,t);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(e,t={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:n,forceRefresh:o,...i}=t,a=this.get(e,i);if(!o&&a!==void 0)return a;let l=s(e,a,{options:i,context:n});return this.set(e,l,i),l}get(e,t={}){let{allowStale:s=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#r[a],c=this.#u(l);return i&&this.#s(i,a),this.#b(a)?(i&&(i.get="stale"),c?(i&&s&&l.__staleWhileFetching!==void 0&&(i.returnedStale=true),s?l.__staleWhileFetching:void 0):(o||this.#A(e,"expire"),i&&s&&(i.returnedStale=true),s?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#j(a),n&&this.#C(a),l))}else i&&(i.get="miss");}#U(e,t){this.#y[t]=e,this.#f[e]=t;}#j(e){e!==this.#d&&(e===this.#m?this.#m=this.#f[e]:this.#U(this.#y[e],this.#f[e]),this.#U(this.#d,e),this.#d=e);}delete(e){return this.#A(e,"delete")}#A(e,t){let s=false;if(this.#c!==0){let n=this.#a.get(e);if(n!==void 0)if(s=true,this.#c===1)this.#G(t);else {this.#O(n);let o=this.#r[n];if(this.#u(o)?o.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#o?.(o,e,t),this.#h&&this.#g?.push([o,e,t])),this.#a.delete(e),this.#l[n]=void 0,this.#r[n]=void 0,n===this.#d)this.#d=this.#y[n];else if(n===this.#m)this.#m=this.#f[n];else {let i=this.#y[n];this.#f[i]=this.#f[n];let a=this.#f[n];this.#y[a]=this.#y[n];}this.#c--,this.#x.push(n);}}if(this.#h&&this.#g?.length){let n=this.#g,o;for(;o=n?.shift();)this.#n?.(...o);}return s}clear(){return this.#G("delete")}#G(e){for(let t of this.#E({allowStale:true})){let s=this.#r[t];if(this.#u(s))s.__abortController.abort(new Error("deleted"));else {let n=this.#l[t];this.#v&&this.#o?.(s,n,e),this.#h&&this.#g?.push([s,n,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#_&&this.#k&&(this.#_.fill(0),this.#k.fill(0)),this.#S&&this.#S.fill(0),this.#m=0,this.#d=0,this.#x.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,s;for(;s=t?.shift();)this.#n?.(...s);}}};var vl=typeof process=="object"&&process?process:{stdout:null,stderr:null},lm=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof kl||cm(r)||um(r)),cm=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==kl.Writable.prototype.pipe,um=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.write=="function"&&typeof r.end=="function",vt=Symbol("EOF"),Tt=Symbol("maybeEmitEnd"),At=Symbol("emittedEnd"),dr=Symbol("emittingEnd"),tn=Symbol("emittedError"),mr=Symbol("closed"),Tl=Symbol("read"),hr=Symbol("flush"),xl=Symbol("flushChunk"),at=Symbol("encoding"),ys=Symbol("decoder"),Ee=Symbol("flowing"),sn=Symbol("paused"),bs=Symbol("resume"),Ie=Symbol("buffer"),je=Symbol("pipes"),Me=Symbol("bufferLength"),Xo=Symbol("bufferPush"),gr=Symbol("bufferShift"),De=Symbol("objectMode"),ke=Symbol("destroyed"),Zo=Symbol("error"),Qo=Symbol("emitData"),Sl=Symbol("emitEnd"),ei=Symbol("emitEnd2"),mt=Symbol("async"),ti=Symbol("abort"),fr=Symbol("aborted"),nn=Symbol("signal"),Ht=Symbol("dataListeners"),Ve=Symbol("discarded"),rn=r=>Promise.resolve().then(r),pm=r=>r(),dm=r=>r==="end"||r==="finish"||r==="prefinish",mm=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,hm=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),yr=class{src;dest;opts;ondrain;constructor(e,t,s){this.src=e,this.dest=t,this.opts=s,this.ondrain=()=>e[bs](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},si=class extends yr{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,s){super(e,t,s),this.proxyErrors=n=>t.emit("error",n),e.on("error",this.proxyErrors);}},gm=r=>!!r.objectMode,fm=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",Pt=class extends EventEmitter{[Ee]=false;[sn]=false;[je]=[];[Ie]=[];[De];[at];[mt];[ys];[vt]=false;[At]=false;[dr]=false;[mr]=false;[tn]=null;[Me]=0;[ke]=false;[nn];[fr]=false;[Ht]=0;[Ve]=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");gm(t)?(this[De]=true,this[at]=null):fm(t)?(this[at]=t.encoding,this[De]=false):(this[De]=false,this[at]=null),this[mt]=!!t.async,this[ys]=this[at]?new StringDecoder(this[at]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[Ie]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[je]});let{signal:s}=t;s&&(this[nn]=s,s.aborted?this[ti]():s.addEventListener("abort",()=>this[ti]()));}get bufferLength(){return this[Me]}get encoding(){return this[at]}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[De]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[mt]}set async(e){this[mt]=this[mt]||!!e;}[ti](){this[fr]=true,this.emit("abort",this[nn]?.reason),this.destroy(this[nn]?.reason);}get aborted(){return this[fr]}set aborted(e){}write(e,t,s){if(this[fr])return false;if(this[vt])throw new Error("write after end");if(this[ke])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(s=t,t="utf8"),t||(t="utf8");let n=this[mt]?rn:pm;if(!this[De]&&!Buffer.isBuffer(e)){if(hm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(mm(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[De]?(this[Ee]&&this[Me]!==0&&this[hr](true),this[Ee]?this.emit("data",e):this[Xo](e),this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee]):e.length?(typeof e=="string"&&!(t===this[at]&&!this[ys]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[at]&&(e=this[ys].write(e)),this[Ee]&&this[Me]!==0&&this[hr](true),this[Ee]?this.emit("data",e):this[Xo](e),this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee]):(this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee])}read(e){if(this[ke])return null;if(this[Ve]=false,this[Me]===0||e===0||e&&e>this[Me])return this[Tt](),null;this[De]&&(e=null),this[Ie].length>1&&!this[De]&&(this[Ie]=[this[at]?this[Ie].join(""):Buffer.concat(this[Ie],this[Me])]);let t=this[Tl](e||null,this[Ie][0]);return this[Tt](),t}[Tl](e,t){if(this[De])this[gr]();else {let s=t;e===s.length||e===null?this[gr]():typeof s=="string"?(this[Ie][0]=s.slice(e),t=s.slice(0,e),this[Me]-=e):(this[Ie][0]=s.subarray(e),t=s.subarray(0,e),this[Me]-=e);}return this.emit("data",t),!this[Ie].length&&!this[vt]&&this.emit("drain"),t}end(e,t,s){return typeof e=="function"&&(s=e,e=void 0),typeof t=="function"&&(s=t,t="utf8"),e!==void 0&&this.write(e,t),s&&this.once("end",s),this[vt]=true,this.writable=false,(this[Ee]||!this[sn])&&this[Tt](),this}[bs](){this[ke]||(!this[Ht]&&!this[je].length&&(this[Ve]=true),this[sn]=false,this[Ee]=true,this.emit("resume"),this[Ie].length?this[hr]():this[vt]?this[Tt]():this.emit("drain"));}resume(){return this[bs]()}pause(){this[Ee]=false,this[sn]=true,this[Ve]=false;}get destroyed(){return this[ke]}get flowing(){return this[Ee]}get paused(){return this[sn]}[Xo](e){this[De]?this[Me]+=1:this[Me]+=e.length,this[Ie].push(e);}[gr](){return this[De]?this[Me]-=1:this[Me]-=this[Ie][0].length,this[Ie].shift()}[hr](e=false){do;while(this[xl](this[gr]())&&this[Ie].length);!e&&!this[Ie].length&&!this[vt]&&this.emit("drain");}[xl](e){return this.emit("data",e),this[Ee]}pipe(e,t){if(this[ke])return e;this[Ve]=false;let s=this[At];return t=t||{},e===vl.stdout||e===vl.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,s?t.end&&e.end():(this[je].push(t.proxyErrors?new si(this,e,t):new yr(this,e,t)),this[mt]?rn(()=>this[bs]()):this[bs]()),e}unpipe(e){let t=this[je].find(s=>s.dest===e);t&&(this[je].length===1?(this[Ee]&&this[Ht]===0&&(this[Ee]=false),this[je]=[]):this[je].splice(this[je].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let s=super.on(e,t);if(e==="data")this[Ve]=false,this[Ht]++,!this[je].length&&!this[Ee]&&this[bs]();else if(e==="readable"&&this[Me]!==0)super.emit("readable");else if(dm(e)&&this[At])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[tn]){let n=t;this[mt]?rn(()=>n.call(this,this[tn])):n.call(this,this[tn]);}return s}removeListener(e,t){return this.off(e,t)}off(e,t){let s=super.off(e,t);return e==="data"&&(this[Ht]=this.listeners("data").length,this[Ht]===0&&!this[Ve]&&!this[je].length&&(this[Ee]=false)),s}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Ht]=0,!this[Ve]&&!this[je].length&&(this[Ee]=false)),t}get emittedEnd(){return this[At]}[Tt](){!this[dr]&&!this[At]&&!this[ke]&&this[Ie].length===0&&this[vt]&&(this[dr]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[mr]&&this.emit("close"),this[dr]=false);}emit(e,...t){let s=t[0];if(e!=="error"&&e!=="close"&&e!==ke&&this[ke])return false;if(e==="data")return !this[De]&&!s?false:this[mt]?(rn(()=>this[Qo](s)),true):this[Qo](s);if(e==="end")return this[Sl]();if(e==="close"){if(this[mr]=true,!this[At]&&!this[ke])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[tn]=s,super.emit(Zo,s);let o=!this[nn]||this.listeners("error").length?super.emit("error",s):false;return this[Tt](),o}else if(e==="resume"){let o=super.emit("resume");return this[Tt](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let n=super.emit(e,...t);return this[Tt](),n}[Qo](e){for(let s of this[je])s.dest.write(e)===false&&this.pause();let t=this[Ve]?false:super.emit("data",e);return this[Tt](),t}[Sl](){return this[At]?false:(this[At]=true,this.readable=false,this[mt]?(rn(()=>this[ei]()),true):this[ei]())}[ei](){if(this[ys]){let t=this[ys].end();if(t){for(let s of this[je])s.dest.write(t);this[Ve]||super.emit("data",t);}}for(let t of this[je])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[De]||(e.dataLength=0);let t=this.promise();return this.on("data",s=>{e.push(s),this[De]||(e.dataLength+=s.length);}),await t,e}async concat(){if(this[De])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[at]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(ke,()=>t(new Error("stream destroyed"))),this.on("error",s=>t(s)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[Ve]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:false,value:n});if(this[vt])return t();let o,i,a=p=>{this.off("data",l),this.off("end",c),this.off(ke,u),t(),i(p);},l=p=>{this.off("error",a),this.off("end",c),this.off(ke,u),this.pause(),o({value:p,done:!!this[vt]});},c=()=>{this.off("error",a),this.off("data",l),this.off(ke,u),t(),o({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((p,d)=>{i=d,o=p,this.once(ke,u),this.once("error",a),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ve]=false;let e=false,t=()=>(this.pause(),this.off(Zo,t),this.off(ke,t),this.off("end",t),e=true,{done:true,value:void 0}),s=()=>{if(e)return t();let n=this.read();return n===null?t():{done:false,value:n}};return this.once("end",t),this.once(Zo,t),this.once(ke,t),{next:s,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[ke])return e?this.emit("error",e):this.emit(ke),this;this[ke]=true,this[Ve]=true,this[Ie].length=0,this[Me]=0;let t=this;return typeof t.close=="function"&&!this[mr]&&t.close(),e?this.emit("error",e):this.emit(ke),this}static get isStream(){return lm}};var km=realpathSync.native,an={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:km,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Ml=r=>!r||r===an||r===Tn?an:{...an,...r,promises:{...an.promises,...r.promises||{}}},Al=/^\\\\\?\\([a-z]:)\\?$/i,Mm=r=>r.replace(/\//g,"\\").replace(Al,"$1\\"),Am=/[\\\/]/,et=0,Pl=1,Ol=2,ht=4,Ll=6,Dl=8,qt=10,$l=12,Qe=15,on=~Qe,ri=16,Cl=32,ln=64,lt=128,br=256,wr=512,Rl=ln|lt|wr,Pm=1023,oi=r=>r.isFile()?Dl:r.isDirectory()?ht:r.isSymbolicLink()?qt:r.isCharacterDevice()?Ol:r.isBlockDevice()?Ll:r.isSocket()?$l:r.isFIFO()?Pl:et,El=new Map,cn=r=>{let e=El.get(r);if(e)return e;let t=r.normalize("NFKD");return El.set(r,t),t},Il=new Map,_r=r=>{let e=Il.get(r);if(e)return e;let t=cn(r.toLowerCase());return Il.set(r,t),t},vr=class extends en{constructor(){super({max:256});}},ai=class extends en{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Nl=Symbol("PathScurry setAsCwd"),$e=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#o;get mode(){return this.#o}#n;get nlink(){return this.#n}#i;get uid(){return this.#i}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#d;get birthtimeMs(){return this.#d}#x;get atime(){return this.#x}#g;get mtime(){return this.#g}#S;get ctime(){return this.#S}#k;get birthtime(){return this.#k}#_;#v;#T;#h;#I;#C;#s;#P;#b;#M;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=et,s,n,o,i,a){this.name=e,this.#_=o?_r(e):cn(e),this.#s=t&Pm,this.nocase=o,this.roots=n,this.root=s||this,this.#P=i,this.#T=a.fullpath,this.#I=a.relative,this.#C=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Ml(a.fs);}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#P}resolve(e){if(!e)return this;let t=this.getRootString(e),n=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#O(n):this.#O(n)}#O(e){let t=this;for(let s of e)t=t.child(s);return t}children(){let e=this.#P.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#P.set(this,t),this.#s&=~ri,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let s=this.children(),n=this.nocase?_r(e):cn(e);for(let l of s)if(l.#_===n)return l;let o=this.parent?this.sep:"",i=this.#T?this.#T+o+e:void 0,a=this.newChild(e,et,{...t,parent:this,fullpath:i});return this.canReaddir()||(a.#s|=lt),s.push(a),a}relative(){if(this.isCWD)return "";if(this.#I!==void 0)return this.#I;let e=this.name,t=this.parent;if(!t)return this.#I=this.name;let s=t.relative();return s+(!s||!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 s=t.relativePosix();return s+(!s||!t.parent?"":"/")+e}fullpath(){if(this.#T!==void 0)return this.#T;let e=this.name,t=this.parent;if(!t)return this.#T=this.name;let n=t.fullpath()+(t.parent?this.sep:"")+e;return this.#T=n}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let n=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(n)?this.#h=`//?/${n}`:this.#h=n}let e=this.parent,t=e.fullpathPosix(),s=t+(!t||!e.parent?"":"/")+this.name;return this.#h=s}isUnknown(){return (this.#s&Qe)===et}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.#s&Qe)===Dl}isDirectory(){return (this.#s&Qe)===ht}isCharacterDevice(){return (this.#s&Qe)===Ol}isBlockDevice(){return (this.#s&Qe)===Ll}isFIFO(){return (this.#s&Qe)===Pl}isSocket(){return (this.#s&Qe)===$l}isSymbolicLink(){return (this.#s&qt)===qt}lstatCached(){return this.#s&Cl?this:void 0}readlinkCached(){return this.#b}realpathCached(){return this.#M}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.#s&Qe;return !(e!==et&&e!==qt||this.#s&br||this.#s&lt)}calledReaddir(){return !!(this.#s&ri)}isENOENT(){return !!(this.#s&lt)}isNamed(e){return this.nocase?this.#_===_r(e):this.#_===cn(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()),s=(await this.parent.realpath())?.resolve(t);if(s)return this.#b=s}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()),s=this.parent.realpathSync()?.resolve(t);if(s)return this.#b=s}catch(t){this.#u(t.code);return}}#L(e){this.#s|=ri;for(let t=e.provisional;t<e.length;t++){let s=e[t];s&&s.#D();}}#D(){this.#s&lt||(this.#s=(this.#s|lt)&on,this.#R());}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#D();}#E(){this.#s|=wr,this.#$();}#$(){if(this.#s&ln)return;let e=this.#s;(e&Qe)===ht&&(e&=on),this.#s=e|ln,this.#R();}#N(e=""){e==="ENOTDIR"||e==="EPERM"?this.#$():e==="ENOENT"?this.#D():this.children().provisional=0;}#F(e=""){e==="ENOTDIR"?this.parent.#$():e==="ENOENT"&&this.#D();}#u(e=""){let t=this.#s;t|=br,e==="ENOENT"&&(t|=lt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=on),this.#s=t,e==="ENOTDIR"&&this.parent&&this.parent.#$();}#U(e,t){return this.#A(e,t)||this.#j(e,t)}#j(e,t){let s=oi(e),n=this.newChild(e.name,s,{parent:this}),o=n.#s&Qe;return o!==ht&&o!==qt&&o!==et&&(n.#s|=ln),t.unshift(n),t.provisional++,n}#A(e,t){for(let s=t.provisional;s<t.length;s++){let n=t[s];if((this.nocase?_r(e.name):cn(e.name))===n.#_)return this.#G(e,n,s,t)}}#G(e,t,s,n){let o=t.name;return t.#s=t.#s&on|oi(e),o!==e.name&&(t.name=e.name),s!==n.provisional&&(s===n.length-1?n.pop():n.splice(s,1),n.unshift(t)),n.provisional++,t}async lstat(){if((this.#s&lt)===0)try{return this.#q(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s&lt)===0)try{return this.#q(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#F(e.code);}}#q(e){let{atime:t,atimeMs:s,birthtime:n,birthtimeMs:o,blksize:i,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:p,ino:d,mode:m,mtime:h,mtimeMs:f,nlink:y,rdev:b,size:_,uid:v}=e;this.#x=t,this.#f=s,this.#k=n,this.#d=o,this.#p=i,this.#r=a,this.#S=l,this.#m=c,this.#t=u,this.#w=p,this.#a=d,this.#o=m,this.#g=h,this.#y=f,this.#n=y,this.#c=b,this.#l=_,this.#i=v;let k=oi(e);this.#s=this.#s&on|k|Cl,k!==et&&k!==ht&&k!==qt&&(this.#s|=ln);}#W=[];#H=false;#z(e){this.#H=false;let t=this.#W.slice();this.#W.length=0,t.forEach(s=>s(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let s=this.children();if(this.calledReaddir()){let o=s.slice(0,s.provisional);t?e(null,o):queueMicrotask(()=>e(null,o));return}if(this.#W.push(e),this.#H)return;this.#H=true;let n=this.fullpath();this.#e.readdir(n,{withFileTypes:true},(o,i)=>{if(o)this.#N(o.code),s.provisional=0;else {for(let a of i)this.#U(a,s);this.#L(s);}this.#z(s.slice(0,s.provisional));});}#B;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.#B)await this.#B;else {let s=()=>{};this.#B=new Promise(n=>s=n);try{for(let n of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#U(n,e);this.#L(e);}catch(n){this.#N(n.code),e.provisional=0;}this.#B=void 0,s();}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 s of this.#e.readdirSync(t,{withFileTypes:!0}))this.#U(s,e);this.#L(e);}catch(s){this.#N(s.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#s&Rl)return false;let e=Qe&this.#s;return e===et||e===ht||e===qt}shouldWalk(e,t){return (this.#s&ht)===ht&&!(this.#s&Rl)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#M)return this.#M;if(!((wr|br|lt)&this.#s))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}realpathSync(){if(this.#M)return this.#M;if(!((wr|br|lt)&this.#s))try{let e=this.#e.realpathSync(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}[Nl](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),s=[],n=this;for(;n&&n.parent;)t.add(n),n.#I=s.join(this.sep),n.#C=s.join("/"),n=n.parent,s.push("..");for(n=e;n&&n.parent&&!t.has(n);)n.#I=void 0,n.#C=void 0,n=n.parent;}},Tr=class r extends $e{sep="\\";splitSep=Am;constructor(e,t=et,s,n,o,i,a){super(e,t,s,n,o,i,a);}newChild(e,t=et,s={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=Mm(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,s]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=s;return this.roots[e]=new _s(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Al,"$1\\"),e===t}},xr=class r extends $e{splitSep="/";sep="/";constructor(e,t=et,s,n,o,i,a){super(e,t,s,n,o,i,a);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=et,s={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),s)}},Sr=class{root;rootPath;roots;cwd;#e;#t;#o;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:o=16*1024,fs:i=an}={}){this.#n=Ml(i),(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 vr,this.#t=new vr,this.#o=new ai(o);let l=a.substring(this.rootPath.length).split(s);if(l.length===1&&!l[0]&&l.pop(),n===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=n,this.root=this.newRoot(this.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,p=t.sep,d=this.rootPath,m=false;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(p),relativePosix:new Array(f).fill("..").join("/"),fullpath:d+=(m?"":p)+h}),m=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#o}resolve(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#e.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpath();return this.#e.set(t,n),n}resolvePosix(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let s=this.#t.get(t);if(s!==void 0)return s;let n=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,n),n}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 $e||(t=e,e=this.cwd);let{withFileTypes:s}=t;if(e.canReaddir()){let n=await e.readdir();return s?n:n.map(o=>o.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true}=t;return e.canReaddir()?s?e.readdirSync():e.readdirSync().map(n=>n.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 $e||(t=e.withFileTypes,e=this.cwd);let s=await e.readlink();return t?s:s?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=e.readlinkSync();return t?s:s?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=await e.realpath();return t?s:s?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e.withFileTypes,e=this.cwd);let s=e.realpathSync();return t?s:s?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(s?e:e.fullpath());let l=new Set,c=(p,d)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return d(m);let f=h.length;if(!f)return d();let y=()=>{--f===0&&d();};for(let b of h)(!o||o(b))&&a.push(s?b:b.fullpath()),n&&b.isSymbolicLink()?b.realpath().then(_=>_?.isUnknown()?_.lstat():_).then(_=>_?.shouldWalk(l,i)?c(_,y):y()):b.shouldWalk(l,i)?c(b,y):y();},true);},u=e;return new Promise((p,d)=>{c(u,m=>{if(m)return d(m);p(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(s?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let p of u){(!o||o(p))&&a.push(s?p:p.fullpath());let d=p;if(p.isSymbolicLink()){if(!(n&&(d=p.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(l,i)&&l.add(d);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(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 $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:o,walkFilter:i}=t;(!o||o(e))&&(yield s?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!o||o(u))&&(yield s?u:u.fullpath());let p=u;if(u.isSymbolicLink()){if(!(n&&(p=u.realpathSync())))continue;p.isUnknown()&&p.lstatSync();}p.shouldWalk(a,i)&&a.add(p);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:o,walkFilter:i}=t,a=new Pt({objectMode:true});(!o||o(e))&&a.write(s?e:e.fullpath());let l=new Set,c=[e],u=0,p=()=>{let d=false;for(;!d;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=(y,b,_=false)=>{if(y)return a.emit("error",y);if(n&&!_){let v=[];for(let k of b)k.isSymbolicLink()&&v.push(k.realpath().then(R=>R?.isUnknown()?R.lstat():R));if(v.length){Promise.all(v).then(()=>h(null,b,true));return}}for(let v of b)v&&(!o||o(v))&&(a.write(s?v:v.fullpath())||(d=true));u--;for(let v of b){let k=v.realpathCached()||v;k.shouldWalk(l,i)&&c.push(k);}d&&!a.flowing?a.once("drain",p):f||p();},f=true;m.readdirCB(h,true),f=false;}};return p(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof $e||(t=e,e=this.cwd);let{withFileTypes:s=true,follow:n=false,filter:o,walkFilter:i}=t,a=new Pt({objectMode:true}),l=new Set;(!o||o(e))&&a.write(s?e:e.fullpath());let c=[e],u=0,p=()=>{let d=false;for(;!d;){let m=c.shift();if(!m){u===0&&a.end();return}u++,l.add(m);let h=m.readdirSync();for(let f of h)(!o||o(f))&&(a.write(s?f:f.fullpath())||(d=true));u--;for(let f of h){let y=f;if(f.isSymbolicLink()){if(!(n&&(y=f.realpathSync())))continue;y.isUnknown()&&y.lstatSync();}y.shouldWalk(l,i)&&c.push(y);}}d&&!a.flowing&&a.once("drain",p);};return p(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Nl](t);}},_s=class extends Sr{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,win32,"\\",{...t,nocase:s}),this.nocase=s;for(let n=this.cwd;n;n=n.parent)n.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new Tr(this.rootPath,ht,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},ws=class extends Sr{sep="/";constructor(e=process.cwd(),t={}){let{nocase:s=false}=t;super(e,posix,"/",{...t,nocase:s}),this.nocase=s;}parseRootPath(e){return "/"}newRoot(e){return new xr(this.rootPath,ht,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},un=class extends ws{constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,{...t,nocase:s});}};process.platform==="win32"?Tr:xr;var Fl=process.platform==="win32"?_s:process.platform==="darwin"?un:ws;var Om=r=>r.length>=1,Lm=r=>r.length>=1,vs=class r{#e;#t;#o;length;#n;#i;#w;#c;#p;#a;#l=true;constructor(e,t,s,n){if(!Om(e))throw new TypeError("empty pattern list");if(!Lm(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,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#o=s,this.#n=n,this.#o===0){if(this.isUNC()){let[o,i,a,l,...c]=this.#e,[u,p,d,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[o,i,a,l,""].join("/"),y=[u,p,d,m,""].join("/");this.#e=[f,...c],this.#t=[y,...h],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[o,...i]=this.#e,[a,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=o+"/",u=a+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#o]}isString(){return typeof this.#e[this.#o]=="string"}isGlobstar(){return this.#e[this.#o]===Ae}isRegExp(){return this.#e[this.#o]instanceof RegExp}globString(){return this.#w=this.#w||(this.#o===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#o).join("/"))}hasMore(){return this.length>this.#o+1}rest(){return this.#i!==void 0?this.#i:this.hasMore()?(this.#i=new r(this.#e,this.#t,this.#o+1,this.#n),this.#i.#a=this.#a,this.#i.#p=this.#p,this.#i.#c=this.#c,this.#i):this.#i=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#n==="win32"&&this.#o===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.#n==="win32"&&this.#o===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.#o===0?e:""}checkFollowGlobstar(){return !(this.#o===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#o===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};var Dm=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ts=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:s,noext:n,noglobstar:o,platform:i=Dm}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:true,nobrace:t,nocase:s,noext:n,noglobstar:o,optimizationLevel:2,platform:i,nocomment:true,nonegate:true};for(let a of e)this.add(a);}add(e){let t=new Ke(e,this.mmopts);for(let s=0;s<t.set.length;s++){let n=t.set[s],o=t.globParts[s];if(!n||!o)throw new Error("invalid pattern object");for(;n[0]==="."&&o[0]===".";)n.shift(),o.shift();let i=new vs(n,o,0,this.platform),a=new Ke(i.globString(),this.mmopts),l=o[o.length-1]==="**",c=i.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(),s=`${t}/`,n=e.relative()||".",o=`${n}/`;for(let i of this.relative)if(i.match(n)||i.match(o))return true;for(let i of this.absolute)if(i.match(t)||i.match(s))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",s=(e.relative()||".")+"/";for(let n of this.relativeChildren)if(n.match(s))return true;for(let n of this.absoluteChildren)if(n.match(t))return true;return false}};var li=class r{store;constructor(e=new Map){this.store=e;}copy(){return new r(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let s=e.fullpath(),n=this.store.get(s);n?n.add(t.globString()):this.store.set(s,new Set([t.globString()]));}},ci=class{store=new Map;add(e,t,s){let n=(t?2:0)|(s?1:0),o=this.store.get(e);this.store.set(e,o===void 0?n:n&o);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},ui=class{store=new Map;add(e,t){if(!e.canReaddir())return;let s=this.store.get(e);s?s.find(n=>n.globString()===t.globString())||s.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())}},pn=class r{hasWalkedCache;matches=new ci;subwalks=new ui;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new li;}processPatterns(e,t){this.patterns=t;let s=t.map(n=>[e,n]);for(let[n,o]of s){this.hasWalkedCache.storeWalked(n,o);let i=o.root(),a=o.isAbsolute()&&this.opts.absolute!==false;if(i){n=n.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let p=o.rest();if(p)o=p;else {this.matches.add(n,true,false);continue}}if(n.isENOENT())continue;let l,c,u=false;for(;typeof(l=o.pattern())=="string"&&(c=o.rest());)n=n.resolve(l),o=c,u=true;if(l=o.pattern(),c=o.rest(),u){if(this.hasWalkedCache.hasWalked(n,o))continue;this.hasWalkedCache.storeWalked(n,o);}if(typeof l=="string"){let p=l===".."||l===""||l===".";this.matches.add(n.resolve(l),a,p);continue}else if(l===Ae){(!n.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(n,o);let p=c?.pattern(),d=c?.rest();if(!c||(p===""||p===".")&&!d)this.matches.add(n,a,p===""||p===".");else if(p===".."){let m=n.parent||n;d?this.hasWalkedCache.hasWalked(m,d)||this.subwalks.add(m,d):this.matches.add(m,a,true);}}else l instanceof RegExp&&this.subwalks.add(n,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let s=this.subwalks.get(e),n=this.child();for(let o of t)for(let i of s){let a=i.isAbsolute(),l=i.pattern(),c=i.rest();l===Ae?n.testGlobstar(o,i,c,a):l instanceof RegExp?n.testRegExp(o,l,c,a):n.testString(o,l,c,a);}return n}testGlobstar(e,t,s,n){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,n,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(s&&t.checkFollowGlobstar()?this.subwalks.add(e,s):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),s){let o=s.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(e,o,s.rest(),n);else if(o===".."){let i=e.parent||e;this.subwalks.add(i,s);}else o instanceof RegExp&&this.testRegExp(e,o,s.rest(),n);}}testRegExp(e,t,s,n){t.test(e.name)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}testString(e,t,s,n){e.isNamed(t)&&(s?this.subwalks.add(e,s):this.matches.add(e,n,false));}};var $m=(r,e)=>typeof r=="string"?new Ts([r],e):Array.isArray(r)?new Ts(r,e):r,kr=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#o;signal;maxDepth;includeChildMatches;constructor(e,t,s){if(this.patterns=e,this.path=t,this.opts=s,this.#o=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==false,(s.ignore||!this.includeChildMatches)&&(this.#t=$m(s.ignore??[],s),!this.includeChildMatches&&typeof this.#t.add!="function")){let n="cannot ignore child matches, ignore lacks add() method.";throw new Error(n)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#n(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(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 s;if(this.opts.realpath){if(s=e.realpathCached()||await e.realpath(),!s)return;e=s;}let o=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=await o.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat();}return this.matchCheckTest(o,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.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=e.realpathCached()||e.realpathSync(),!s)return;e=s;}let o=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=o.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync();}return this.matchCheckTest(o,t)}matchFinish(e,t){if(this.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let o=`${e.relativePosix()}/**`;this.#t.add(o);}let s=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let n=this.opts.mark&&e.isDirectory()?this.#o:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(s){let o=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(o+n);}else {let o=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!o.startsWith(".."+this.#o)?"."+this.#o:"";this.matchEmit(o?i+o+n:"."+n);}}async match(e,t,s){let n=await this.matchCheck(e,s);n&&this.matchFinish(n,t);}matchSync(e,t,s){let n=this.matchCheckSync(e,s);n&&this.matchFinish(n,t);}walkCB(e,t,s){this.signal?.aborted&&s(),this.walkCB2(e,t,new pn(this.opts),s);}walkCB2(e,t,s,n){if(this.#i(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2(e,t,s,n));return}s.processPatterns(e,t);let o=1,i=()=>{--o===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||(o++,this.match(a,l,c).then(()=>i()));for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,s,i):a.readdirCB((c,u)=>this.walkCB3(a,u,s,i),true);}i();}walkCB3(e,t,s,n){s=s.filterEntries(e,t);let o=1,i=()=>{--o===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||(o++,this.match(a,l,c).then(()=>i()));for(let[a,l]of s.subwalks.entries())o++,this.walkCB2(a,l,s.child(),i);i();}walkCBSync(e,t,s){this.signal?.aborted&&s(),this.walkCB2Sync(e,t,new pn(this.opts),s);}walkCB2Sync(e,t,s,n){if(this.#i(e))return n();if(this.signal?.aborted&&n(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,s,n));return}s.processPatterns(e,t);let o=1,i=()=>{--o===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let a of s.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirSync();this.walkCB3Sync(a,l,s,i);}i();}walkCB3Sync(e,t,s,n){s=s.filterEntries(e,t);let o=1,i=()=>{--o===0&&n();};for(let[a,l,c]of s.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let[a,l]of s.subwalks.entries())o++,this.walkCB2Sync(a,l,s.child(),i);i();}},dn=class extends kr{matches=new Set;constructor(e,t,s){super(e,t,s);}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}},mn=class extends kr{results;constructor(e,t,s){super(e,t,s),this.results=new Pt({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 Fm=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ct=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||Fm,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"?_s:t.platform==="darwin"?un:t.platform?ws:Fl;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",n={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},o=this.pattern.map(l=>new Ke(l,n)),[i,a]=o.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new vs(l,u,0,this.platform)});}async walk(){return [...await new dn(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 dn(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 mn(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 mn(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 pi=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Ke(t,e).hasMagic())return true;return false};function Cr(r,e={}){return new ct(r,e).streamSync()}function jl(r,e={}){return new ct(r,e).stream()}function Gl(r,e={}){return new ct(r,e).walkSync()}async function Ul(r,e={}){return new ct(r,e).walk()}function Rr(r,e={}){return new ct(r,e).iterateSync()}function Bl(r,e={}){return new ct(r,e).iterate()}var Um=Cr,jm=Object.assign(jl,{sync:Cr}),Gm=Rr,Bm=Object.assign(Bl,{sync:Rr}),Wm=Object.assign(Gl,{stream:Cr,iterate:Rr}),xs=Object.assign(Ul,{glob:Ul,globSync:Gl,sync:Wm,globStream:jl,stream:jm,globStreamSync:Cr,streamSync:Um,globIterate:Bl,iterate:Bm,globIterateSync:Rr,iterateSync:Gm,Glob:ct,hasMagic:pi,escape:hs,unescape:it});xs.glob=xs;var hn=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
630
+ `),n=[],o={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*[=:?]/},i=null,a=0;for(let l=0;l<s.length;l++){let c=s[l],u=l+1;if(i){let f=c.match(/^(\s*)/)?.[1].length||0;c.trim()&&f<=a&&!c.match(/^\s*[})\]]/)&&(i.endLine=l,n.push(i),i=null);}if(c.trim().startsWith("//")||c.trim().startsWith("/*")||!c.trim())continue;let p=c.match(o.class);if(p){if(i&&(i.endLine=l,n.push(i)),a=p[1].length,i={name:p[4],kind:"class",startLine:u,endLine:this.findSymbolEnd(s,l),children:[]},l>0){let f=s[l-1].trim();f.startsWith("/**")||f.startsWith("/*")?i.docstring=this.extractDocstring(s,l-1):f.startsWith("//")&&(i.docstring=f.replace(/^\/\/\s*/,""));}continue}let d=c.match(o.interface);if(d){n.push({name:d[3],kind:"interface",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let m=c.match(o.type);if(m){n.push({name:m[3],kind:"type",startLine:u,endLine:this.findTypeEnd(s,l)});continue}let h=c.match(o.enum);if(h){n.push({name:h[3],kind:"enum",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}if(!i){let f=c.match(o.function);if(f){n.push({name:f[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let y=c.match(o.constFunction);if(y){n.push({name:y[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(s,l)});continue}let b=c.match(o.variable);if(b&&!o.constFunction.test(c)){n.push({name:b[4],kind:"variable",startLine:u,endLine:u});continue}}if(i){let f=c.match(o.method);if(f&&!["if","for","while","switch","catch","constructor"].includes(f[5])){let b={name:f[5],kind:(f[5]==="constructor","method"),startLine:u,endLine:this.findSymbolEnd(s,l),parent:i.name};i.children.push(b);continue}let y=c.match(o.property);if(y&&!["if","for","while","switch","catch","return","const","let","var"].includes(y[5])){let b={name:y[5],kind:"variable",startLine:u,endLine:u,parent:i.name};i.children.push(b);}}}return i&&(i.endLine=s.length,n.push(i)),n}findSymbolEnd(e,t){return It(e,t)}findTypeEnd(e,t){for(let s=t;s<e.length;s++){let n=e[s];if(n.includes(";")||s>t&&/^(export|type|interface|class|function|const|let|var)/.test(n.trim()))return s+1}return t+1}extractDocstring(e,t){let s=[],n=t;for(;n>=0;){let o=e[n].trim();if(o.startsWith("/**")||o.startsWith("/*"))break;n--;}for(let o=n;o<=t;o++){let i=e[o].trim();i=i.replace(/^\/\*\*?\s*/,"").replace(/\*\/\s*$/,"").replace(/^\*\s?/,""),i&&s.push(i);}return s.join(`
631
+ `)}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|async\\s+function|const|let|var)\\s+${s}\\s*[=(<]`;case "class":return `class\\s+${s}(\\s+extends|\\s+implements|\\s*\\{)`;case "interface":return `interface\\s+${s}(\\s+extends|\\s*\\{)`;case "type":return `type\\s+${s}\\s*[=<]`;case "enum":return `enum\\s+${s}\\s*\\{`;case "method":return `(async\\s+)?${s}\\s*\\(`;case "variable":return `(const|let|var)\\s+${s}\\s*[=:]`;default:return `(function|class|interface|type|enum|const|let|var)\\s+${s}|${s}\\s*(=|\\()`}}};var gn=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let s=e.split(`
632
+ `),n=[],o={class:/^(\s*)class\s+(\w+)(\s*\([^)]*\))?\s*:/,function:/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,variable:/^([A-Z][A-Z0-9_]*)\s*[=:]/},i=null,a=-1;for(let l=0;l<s.length;l++){let c=s[l],u=l+1,p=c.match(/^(\s*)/)?.[1].length||0;if(i&&c.trim()&&p<=a&&(i.endLine=l,n.push(i),i=null,a=-1),c.trim().startsWith("#")||!c.trim())continue;let d=c.match(o.class);if(d){i&&(i.endLine=l,n.push(i)),a=d[1].length,i={name:d[2],kind:"class",startLine:u,endLine:this.findClassEnd(s,l,a),children:[],docstring:this.extractDocstring(s,l+1)};continue}let m=c.match(o.function);if(m){let h=m[1].length,f=m[3],y=i&&h>a,b={name:f,kind:y?"method":"function",startLine:u,endLine:this.findFunctionEnd(s,l,h),docstring:this.extractDocstring(s,l+1)};y&&i?(b.parent=i.name,i.children.push(b)):n.push(b);continue}if(!i&&c.match(o.variable)){let h=c.match(o.variable);h&&n.push({name:h[1],kind:"constant",startLine:u,endLine:u});}}return i&&(i.endLine=s.length,n.push(i)),n}findClassEnd(e,t,s){for(let n=t+1;n<e.length;n++){let o=e[n];if(!o.trim())continue;if((o.match(/^(\s*)/)?.[1].length||0)<=s)return n}return e.length}findFunctionEnd(e,t,s){let n=false;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i.trim())continue;let a=i.match(/^(\s*)/)?.[1].length||0;if(a>s){n=true;continue}if(n&&a<=s)return o}return e.length}extractDocstring(e,t){if(t>=e.length)return;let s=e[t].trim();if(s.startsWith('"""')||s.startsWith("'''")){let n=s.startsWith('"""')?'"""':"'''";if(s.endsWith(n)&&s.length>6)return s.slice(3,-3);let o=[s.slice(3)];for(let i=t+1;i<e.length;i++){let a=e[i].trim();if(a.endsWith(n)){o.push(a.slice(0,-3));break}o.push(a);}return o.join(`
633
+ `).trim()}}buildSymbolPattern(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":case "method":return `(async\\s+)?def\\s+${s}\\s*\\(`;case "class":return `class\\s+${s}(\\s*\\(|\\s*:)`;case "variable":case "constant":return `^${s}\\s*[=:]`;default:return `(def|class)\\s+${s}|^${s}\\s*[=:]`}}};var fn=class{languageId="generic";extensions=["*"];async parse(e,t){let s=e.split(`
634
+ `),n=[],o={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 i=0;i<s.length;i++){let a=s[i],l=i+1;if(!this.isComment(a)){for(let c of o.function){let u=a.match(c);if(u){let p=this.extractName(u);p&&!this.isKeyword(p)&&n.push({name:p,kind:"function",startLine:l,endLine:It(s,i)});break}}for(let c of o.class){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"class",startLine:l,endLine:It(s,i)});break}}for(let c of o.interface){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"interface",startLine:l,endLine:It(s,i)});break}}for(let c of o.constant){let u=a.match(c);if(u){let p=this.extractName(u);p&&n.push({name:p,kind:"constant",startLine:l,endLine:l});break}}}}return n}extractName(e){for(let t=e.length-1;t>0;t--){let s=e[t];if(s&&/^\w+$/.test(s)&&!this.isModifier(s))return s}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 s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|func|fn|def)\\s+${s}|${s}\\s*\\(`;case "class":return `(class|struct|type)\\s+${s}`;case "interface":return `(interface|trait)\\s+${s}`;default:return `(function|class|interface|struct|type|func|fn|def)\\s+${s}|${s}\\s*[=(]`}}};var yn=class{parsers=new Map;constructor(){this.register(new hn),this.register(new gn),this.register(new fn);}register(e){this.parsers.set(e.languageId,e);for(let t of e.extensions){let s=this.getLanguageFromExtension(t);s&&this.parsers.has(s);}}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")}};var Hm="1.0.0",Er=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Ba,...t},this.parserRegistry=new yn;}get indexDir(){return Y.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=Y.join(this.indexDir,"meta.json");return Ha(e)}async loadMetadata(){if(this.metadata)return this.metadata;let e=Y.join(this.indexDir,"meta.json");try{let t=await Z.readFile(e,"utf-8");return this.metadata=JSON.parse(t),this.metadata}catch{return null}}async saveMetadata(){if(!this.metadata)return;await Ys(this.indexDir);let e=Y.join(this.indexDir,"meta.json");await Z.writeFile(e,JSON.stringify(this.metadata,null,2));}async buildIndex(e={}){let t=Date.now(),s=[],{paths:n=this.config.include,languages:o=this.config.languages,force:i=false,onProgress:a}=e;await Ys(this.indexDir),await Ys(Y.join(this.indexDir,"files"));let l=[];for(let p of n){let d=await xs(p,{cwd:this.workspacePath,absolute:true,ignore:this.config.exclude});for(let m of d){let h=Wo(m);h&&o.includes(h)&&l.push(m);}}let c=0,u=0;for(let p=0;p<l.length;p++){let d=l[p];a?.(p+1,l.length,d);try{if(!i){let h=await this.getFileIndex(d);if(h){let f=await Z.stat(d);if(h.mtime>=f.mtimeMs){u+=h.symbols.length,c++;continue}}}let m=await this.indexFile(d);m&&(await this.saveFileIndex(m),this.fileIndexCache.set(d,m),u+=m.symbols.length,c++);}catch(m){s.push({file:d,error:m.message});}}return this.metadata={version:Hm,createdAt:this.metadata?.createdAt||Date.now(),updatedAt:Date.now(),fileCount:c,symbolCount:u,languages:o,indexDir:this.config.cacheDir},await this.saveMetadata(),{success:s.length===0,filesIndexed:c,symbolsFound:u,timeMs:Date.now()-t,errors:s}}async indexFile(e){let t=Wo(e);if(!t)return null;let s=this.parserRegistry.getParser(t);if(!s)return null;try{let n=await Z.readFile(e,"utf-8"),o=await Z.stat(e),i=await s.parse(n,e),a=this.extractImports(n,t),l=this.extractExports(n,t);return {path:e,hash:Wa(n),mtime:o.mtimeMs,totalLines:n.split(`
635
+ `).length,symbols:i,imports:a,exports:l}}catch{return null}}extractImports(e,t){let s=[],n=e.split(`
636
+ `);if(["typescript","javascript"].includes(t)){let o=/^import\s+(?:(?:\{([^}]+)\}|(\w+))\s+from\s+)?['"]([^'"]+)['"]/;n.forEach((i,a)=>{let l=i.match(o);if(l){let c=l[1]?.split(",").map(u=>u.trim())||(l[2]?[l[2]]:[]);s.push({module:l[3],line:a+1,names:c.filter(Boolean)});}});}if(t==="python"){let o=/^(?:from\s+(\S+)\s+import\s+(.+)|import\s+(\S+))/;n.forEach((i,a)=>{let l=i.match(o);if(l){let c=l[1]||l[3],u=l[2]?.split(",").map(p=>p.trim())||[];s.push({module:c,line:a+1,names:u});}});}return s}extractExports(e,t){let s=[],n=e.split(`
637
+ `);if(["typescript","javascript"].includes(t)){let o=/^export\s+(?:(default)\s+)?(?:(class|function|const|let|var|interface|type|enum)\s+)?(\w+)?/;n.forEach((i,a)=>{let l=i.match(o);if(l){let c=l[2],u=l[3]||(l[1]?"default":"");u&&s.push({name:u,line:a+1,kind:c});}});}return s}async getFileIndex(e){if(this.fileIndexCache.has(e))return this.fileIndexCache.get(e);let t=this.getFileIndexPath(e);try{let s=await Z.readFile(t,"utf-8"),n=JSON.parse(s);return this.fileIndexCache.set(e,n),n}catch{return null}}async saveFileIndex(e){let t=this.getFileIndexPath(e.path);await Ys(Y.dirname(t)),await Z.writeFile(t,JSON.stringify(e,null,2));}getFileIndexPath(e){let s=Y.relative(this.workspacePath,e).replace(/[/\\]/g,"_").replace(/\./g,"_");return Y.join(this.indexDir,"files",`${s}.json`)}async searchSymbol(e){let{query:t,kind:s,fuzzy:n=false,limit:o=20}=e,i=[],a=Y.join(this.indexDir,"files");try{let l=await Z.readdir(a);for(let c of l)if(c.endsWith(".json"))try{let u=await Z.readFile(Y.join(a,c),"utf-8"),p=JSON.parse(u);for(let d of p.symbols){if(s&&d.kind!==s)continue;let m=0;if(n){if(m=Ho(t.toLowerCase(),d.name.toLowerCase()),m<.5)continue}else {if(!d.name.toLowerCase().includes(t.toLowerCase()))continue;m=d.name.toLowerCase()===t.toLowerCase()?1:.8;}if(i.push({symbol:d,file:p.path,score:m}),d.children)for(let h of d.children){if(s&&h.kind!==s)continue;let f=0;if(n){if(f=Ho(t.toLowerCase(),h.name.toLowerCase()),f<.5)continue}else {if(!h.name.toLowerCase().includes(t.toLowerCase()))continue;f=h.name.toLowerCase()===t.toLowerCase()?1:.8;}i.push({symbol:{...h,parent:d.name},file:p.path,score:f});}}}catch{continue}}catch{}return i.sort((l,c)=>c.score-l.score).slice(0,o)}async invalidate(e){this.fileIndexCache.delete(e);let t=this.getFileIndexPath(e);try{await Z.unlink(t);}catch{}}async clear(){this.fileIndexCache.clear(),this.metadata=null;try{await Z.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 s=Y.join(this.indexDir,"files"),n=await Z.readdir(s);for(let o of n){let i=await Z.stat(Y.join(s,o));t+=i.size;}}catch{}return {hasIndex:true,fileCount:e.fileCount,symbolCount:e.symbolCount,lastUpdated:new Date(e.updatedAt),size:t}}};function di(r,e){return new Er(r,e)}var Ss=null,ks=null,Mr=null,zt={small:ls,large:1e3},Wl=12e3,qm=120,Ir=20,zm=3,Jm=200,mi=200;function Km(r){return (!Ss||Mr!==r)&&(Ss=qo(r),Mr=r,ks&&Ss.setIndexManager(ks)),Ss}function bn(r){return (!ks||Mr!==r)&&(ks=di(r),Mr=r,Ss&&Ss.setIndexManager(ks)),ks}function Vm(r){return process.cwd()}function gt(r){let e=Vm();return Y.relative(e,r)||r}function Hl(r,e){let t=Y.relative(r,e);return t===""?true:!t.startsWith("..")&&!Y.isAbsolute(t)}function Ym(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function gi(r){let e=r||process.cwd(),s=await bn(e).getStats();return {hasIndex:s.hasIndex,fileCount:s.fileCount,symbolCount:s.symbolCount,lastUpdated:s.lastUpdated}}async function ql(r){let e=await gi(r);return e.hasIndex?`
638
638
  \u{1F4D6} readfile \u7B56\u7565\u63D0\u793A (\u7D22\u5F15\u5DF2\u542F\u7528, ${e.symbolCount} \u7B26\u53F7):
639
- - \u5C0F\u6587\u4EF6 (\u2264${qt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
640
- - \u5927\u6587\u4EF6 (>${qt.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
639
+ - \u5C0F\u6587\u4EF6 (\u2264${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
640
+ - \u5927\u6587\u4EF6 (>${zt.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
641
641
  \u2713 readfile(path="big.ts", function="handleClick") - \u7CBE\u51C6\u5B9A\u4F4D\u51FD\u6570
642
642
  \u2713 readfile(path="big.ts", class="UserService") - \u7CBE\u51C6\u5B9A\u4F4D\u7C7B
643
643
  - \u4E2D\u7B49\u6587\u4EF6: pattern \u548C symbol \u5747\u53EF\uFF0C\u6309\u9700\u9009\u62E9`:`
644
644
  \u{1F4D6} readfile \u7B56\u7565\u63D0\u793A:
645
645
  - \u7D22\u5F15\u672A\u6784\u5EFA\uFF0C\u4F7F\u7528 pattern/grep \u5B9A\u4F4D
646
- - \u5C0F\u6587\u4EF6 (\u2264${qt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
646
+ - \u5C0F\u6587\u4EF6 (\u2264${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
647
647
  - \u5927\u6587\u4EF6: \u5148\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
648
- - \u{1F4A1} \u8FD0\u884C build_index() \u53EF\u4EE5\u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD`}async function go(r){let e=await ho(r);await Bl(r);let s=["## readfile \u6587\u4EF6\u8BFB\u53D6\u7B56\u7565",""];return e.hasIndex?(s.push(`\u2705 \u4EE3\u7801\u7D22\u5F15\u5DF2\u542F\u7528 (${e.fileCount} \u6587\u4EF6, ${e.symbolCount} \u7B26\u53F7)`),s.push(""),s.push("### \u6309\u6587\u4EF6\u5927\u5C0F\u9009\u62E9\u7B56\u7565:"),s.push(""),s.push("| \u6587\u4EF6\u5927\u5C0F | \u63A8\u8350\u7B56\u7565 | \u793A\u4F8B |"),s.push("|---------|---------|------|"),s.push(`| \u2264${qt.small}\u884C | full \u81EA\u52A8\u8BFB\u53D6 | \`readfile(path)\` |`),s.push(`| ${qt.small}-${qt.large}\u884C | \u5747\u53EF | \u6309\u9700\u9009\u62E9 |`),s.push(`| >${qt.large}\u884C | **symbol/function** | \`readfile(path, function="xxx")\` |`)):(s.push("\u26A0\uFE0F \u4EE3\u7801\u7D22\u5F15\u672A\u6784\u5EFA"),s.push(""),s.push("\u5F53\u524D\u53EF\u7528\u7B56\u7565:"),s.push("- `start_line`: \u6309\u884C\u53F7\u8BFB\u53D6"),s.push("- `pattern`: \u6B63\u5219\u5339\u914D\u5B9A\u4F4D\uFF08\u53EF\u914D\u5408 list_matches\uFF09"),s.push("- `range_start/end`: \u8303\u56F4\u8BFB\u53D6"),s.push(""),s.push("\u{1F4A1} \u8FD0\u884C `build_index()` \u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD")),s.join(`
649
- `)}function fo(r){let e=()=>r||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
648
+ - \u{1F4A1} \u8FD0\u884C build_index() \u53EF\u4EE5\u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD`}async function fi(r){let e=await gi(r);await ql(r);let s=["## readfile \u6587\u4EF6\u8BFB\u53D6\u7B56\u7565",""];return e.hasIndex?(s.push(`\u2705 \u4EE3\u7801\u7D22\u5F15\u5DF2\u542F\u7528 (${e.fileCount} \u6587\u4EF6, ${e.symbolCount} \u7B26\u53F7)`),s.push(""),s.push("### \u6309\u6587\u4EF6\u5927\u5C0F\u9009\u62E9\u7B56\u7565:"),s.push(""),s.push("| \u6587\u4EF6\u5927\u5C0F | \u63A8\u8350\u7B56\u7565 | \u793A\u4F8B |"),s.push("|---------|---------|------|"),s.push(`| \u2264${zt.small}\u884C | full \u81EA\u52A8\u8BFB\u53D6 | \`readfile(path)\` |`),s.push(`| ${zt.small}-${zt.large}\u884C | \u5747\u53EF | \u6309\u9700\u9009\u62E9 |`),s.push(`| >${zt.large}\u884C | **symbol/function** | \`readfile(path, function="xxx")\` |`)):(s.push("\u26A0\uFE0F \u4EE3\u7801\u7D22\u5F15\u672A\u6784\u5EFA"),s.push(""),s.push("\u5F53\u524D\u53EF\u7528\u7B56\u7565:"),s.push("- `start_line`: \u6309\u884C\u53F7\u8BFB\u53D6"),s.push("- `pattern`: \u6B63\u5219\u5339\u914D\u5B9A\u4F4D\uFF08\u53EF\u914D\u5408 list_matches\uFF09"),s.push("- `range_start/end`: \u8303\u56F4\u8BFB\u53D6"),s.push(""),s.push("\u{1F4A1} \u8FD0\u884C `build_index()` \u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD")),s.join(`
649
+ `)}function yi(r){let e=()=>r||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
650
650
 
651
651
  \u{1F525} \u57FA\u7840\u7528\u6CD5:
652
652
  readfile(path="src/main.ts") \u2192 \u8BFB\u53D6\u6587\u4EF6\u5F00\u5934 200 \u884C
@@ -655,8 +655,8 @@ readfile(path="src/main.ts", start_line=100, end_line=500) \u2192 \u8BFB\u53D6 1
655
655
  readfile(path="src/main.ts", num_lines=2000) \u2192 \u8BFB\u53D6\u524D 2000 \u884C
656
656
 
657
657
  \u{1F9E0} \u81EA\u9002\u5E94:
658
- - \u2264${as} \u884C\u9ED8\u8BA4 full
659
- - >${as} \u884C\u5EFA\u8BAE pattern/list_matches \u518D\u6309\u884C\u6279\u91CF\u8BFB\u53D6
658
+ - \u2264${ls} \u884C\u9ED8\u8BA4 full
659
+ - >${ls} \u884C\u5EFA\u8BAE pattern/list_matches \u518D\u6309\u884C\u6279\u91CF\u8BFB\u53D6
660
660
 
661
661
  \u{1F3AF} \u667A\u80FD\u5B9A\u4F4D (\u65E0\u9700\u77E5\u9053\u884C\u53F7):
662
662
  readfile(path="src/main.ts", symbol="handleClick") \u2192 \u5B9A\u4F4D\u5230 handleClick \u51FD\u6570
@@ -688,24 +688,24 @@ readfile(path="src/main.ts", range_start="// BEGIN CONFIG", range_end="// END CO
688
688
  - \u{1F525} edit_file \u524D\u5FC5\u987B\u5148 readfile(..., for_edit=true) - old_string \u987B\u4ECE\u8F93\u51FA\u7CBE\u786E\u590D\u5236
689
689
  - for_edit=true \u4F1A\u5305\u542B COPY \u533A\u5757\uFF08\u8F93\u51FA\u66F4\u5927\uFF09
690
690
  - max_output_chars \u53EF\u9650\u5236\u8F93\u51FA\u957F\u5EA6
691
- - \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: ${Ks})`},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: ${jl})`}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:p,num_lines:d,symbol:m,symbol_kind:h,class_name:f,function:y,class:b,pattern:_,match_index:v,list_matches:k,range_start:R,range_end:O,ranges:W,anchor_lines:F,context:S,use_index:C=true,for_edit:w,max_output_chars:T}=l,M=e(),B=qm(M),E=w===true,L=typeof S=="number"?Math.max(0,S):ir,N=typeof T=="number"&&T>0?Math.floor(T):jl,$=d||(E?Bm:Ks);$=Math.min($,or),!d&&_&&($=Math.max(Er,L*2+1));let G=Array.isArray(W)&&W.length>0,X=Array.isArray(F)&&F.length>0,A=k===true;if(E&&(G||X||A))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 P=()=>Y.isAbsolute(c)?c:Y.resolve(M,c),K=async()=>{let J=P(),pe=await Z.readFile(J,"utf-8"),D=ps(pe).split(`
691
+ - \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: ${Vs})`},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: ${Wl})`}},required:["path"]},async function(l){let{path:c,start_line:u,end_line:p,num_lines:d,symbol:m,symbol_kind:h,class_name:f,function:y,class:b,pattern:_,match_index:v,list_matches:k,range_start:R,range_end:O,ranges:W,anchor_lines:F,context:S,use_index:C=true,for_edit:w,max_output_chars:T}=l,M=e(),B=Km(M),E=w===true,L=typeof S=="number"?Math.max(0,S):ir,N=typeof T=="number"&&T>0?Math.floor(T):Wl,$=d||(E?qm:Vs);$=Math.min($,ar),!d&&_&&($=Math.max(Ir,L*2+1));let G=Array.isArray(W)&&W.length>0,X=Array.isArray(F)&&F.length>0,A=k===true;if(E&&(G||X||A))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 P=()=>Y.isAbsolute(c)?c:Y.resolve(M,c),K=async()=>{let J=P(),pe=await Z.readFile(J,"utf-8"),D=ds(pe).split(`
692
692
  `);return {absPath:J,lines:D,totalLines:D.length}},U=(J,pe,x)=>{let D=Math.max(1,Math.floor(J)),H=typeof pe=="number"?Math.floor(pe):D+$-1,V=Math.min(x,Math.max(H,D));return {start:D,end:V}},ne=J=>{let pe=J.filter(D=>Number.isFinite(D.start)&&Number.isFinite(D.end)).sort((D,H)=>D.start-H.start),x=[];for(let D of pe){let H=x[x.length-1];!H||D.start>H.end+1?x.push({...D}):H.end=Math.max(H.end,D.end);}return x};if(A){if(!_)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:J,lines:pe,totalLines:x}=await K(),D;try{D=new RegExp(_,"gi");}catch(ge){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${ge.message}`}let H=[];pe.forEach((ge,fe)=>{D.test(ge)&&H.push({line:fe+1,text:ge}),D.lastIndex=0;});let V=gt(J);if(H.length===0){let ge=Le(pe.slice(0,Math.min(50,x)),1);return [`\u2713 \u6587\u4EF6: ${V}`,`\u603B\u884C\u6570: ${x} | \u5339\u914D: 0`,"\u7B56\u7565: grep-list","",`\u672A\u627E\u5230\u5339\u914D: "${_}"`,"","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---",ge].join(`
693
- `)}let we=po+12,xe=Math.max(5,Math.min(Hm,Math.floor(N/we))),I=H.slice(0,xe),j=I.map(ge=>{let fe=ge.text.length>po?`${ge.text.slice(0,po)}...`:ge.text;return `${String(ge.line).padStart(6)} \u2502 ${fe}`}),q=[`\u2713 \u6587\u4EF6: ${V}`,`\u603B\u884C\u6570: ${x} | \u5339\u914D: ${H.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${j.length}/${H.length}\uFF09---`,...j];j.length<H.length&&q.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let ye=I.slice(0,5).map(ge=>ge.line).join(", ");return q.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${V}", anchor_lines=[${ye}], num_lines=${Math.min(200,$)})`),q.join(`
693
+ `)}let we=mi+12,xe=Math.max(5,Math.min(Jm,Math.floor(N/we))),I=H.slice(0,xe),j=I.map(ge=>{let fe=ge.text.length>mi?`${ge.text.slice(0,mi)}...`:ge.text;return `${String(ge.line).padStart(6)} \u2502 ${fe}`}),q=[`\u2713 \u6587\u4EF6: ${V}`,`\u603B\u884C\u6570: ${x} | \u5339\u914D: ${H.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${j.length}/${H.length}\uFF09---`,...j];j.length<H.length&&q.push("","\u26A0\uFE0F \u6458\u8981\u5DF2\u622A\u65AD\uFF0C\u8C03\u6574 max_output_chars \u6216\u7F29\u5C0F pattern");let ye=I.slice(0,5).map(ge=>ge.line).join(", ");return q.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${V}", anchor_lines=[${ye}], num_lines=${Math.min(200,$)})`),q.join(`
694
694
  `)}catch(J){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.message}`}}if(G||X)try{let{absPath:J,lines:pe,totalLines:x}=await K(),D=[];if(G)for(let j of W)!j||typeof j.start!="number"||D.push(U(j.start,j.end,x));else if(X){let j=Math.max(1,d||L*2+1);for(let q of F){if(typeof q!="number"||Number.isNaN(q))continue;let ye=Math.max(1,Math.floor(q-Math.floor(j/2))),ge=Math.min(x,ye+j-1);D.push({start:ye,end:ge});}}if(D.length===0)return "\u2717 ranges/anchor_lines \u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8BFB\u53D6";let H=ne(D),we=[`\u2713 \u6587\u4EF6: ${gt(J)}`,`\u603B\u884C\u6570: ${x} | \u533A\u5757: ${H.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],xe=we.join(`
695
695
  `).length,I=0;for(let[j,q]of H.entries()){let ye=Le(pe.slice(q.start-1,q.end),q.start),fe=`${`# \u533A\u5757 ${j+1}: ${q.start}-${q.end}`}
696
696
  ${ye}`;if(xe+fe.length+2>N&&I>0)break;we.push(fe,""),xe+=fe.length+2,I+=1;}return I<H.length&&we.push(`\u26A0\uFE0F \u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4EC5\u663E\u793A\u524D ${I} \u4E2A\u533A\u5757`),we.join(`
697
697
  `).trimEnd()}catch(J){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.message}`}let Te;u?Te={type:"line",start:u,end:p}:y?Te={type:"function",name:y,className:f}:b?Te={type:"class",name:b}:m?Te={type:"symbol",name:m,kind:h}:_?Te={type:"pattern",regex:_,matchIndex:v,context:L}:R&&O&&(Te={type:"range",startPattern:R,endPattern:O});let Q=J=>{let x=[`\u2713 \u6587\u4EF6: ${gt(J.path)}`,`\u603B\u884C\u6570: ${J.totalLines} | \u663E\u793A: \u7B2C ${J.startLine}-${J.endLine} \u884C`,`\u7B56\u7565: ${J.strategy}${J.metadata?.matchedLine?` | \u5339\u914D\u884C: ${J.metadata.matchedLine}`:""}`];if(J.metadata?.symbol&&x.push(`\u7B26\u53F7: ${J.metadata.symbol.name} (${J.metadata.symbol.kind})`),J.truncated&&(x.push(""),x.push(`\u26A0\uFE0F \u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528 start_line=${J.endLine+1} \u7EE7\u7EED\u8BFB\u53D6`)),x.push(""),x.push("--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"),x.push(J.content),E){let V=J.content.split(`
698
698
  `).map(we=>{let xe=we.match(/^\s*\d+\s*│\s?(.*)$/);return xe?xe[1]:we}).join(`
699
699
  `);x.push(""),x.push("--- \u{1F525} COPY THIS FOR edit_file old_string (\u4E0D\u5E26\u884C\u53F7) ---"),x.push(V),x.push("--- END ---");}return x.join(`
700
- `)},ie=0,se="",ae=!d;for(;;){let J=await B.read({path:c,locator:Te,mode:"smart",autoFullThreshold:ae?as:void 0,chunkSize:$,expandContext:L,useIndex:C});if(!J.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.error}
700
+ `)},oe=0,se="",ae=!d;for(;;){let J=await B.read({path:c,locator:Te,mode:"smart",autoFullThreshold:ae?ls:void 0,chunkSize:$,expandContext:L,useIndex:C});if(!J.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.error}
701
701
 
702
702
  \u{1F4A1} \u63D0\u793A:
703
703
  - \u68C0\u67E5\u6587\u4EF6\u8DEF\u5F84\u662F\u5426\u6B63\u786E
704
- - \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(se=Q(J),!Te&&J.totalLines>as&&J.strategy==="chunk"&&(se+=`
704
+ - \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(se=Q(J),!Te&&J.totalLines>ls&&J.strategy==="chunk"&&(se+=`
705
705
 
706
706
  \u{1F4A1} \u5EFA\u8BAE:
707
707
  - \u4F7F\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
708
- - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),ae&&J.strategy==="full"&&se.length>N){ae=false;let D=Math.max(.1,Math.min(.9,N/se.length));$=Math.max(Er,Math.floor($*D)),ie+=1;continue}if(d||se.length<=N||ie>=Wm||$<=Er)return se;let pe=Math.max(.1,Math.min(.9,N/se.length)),x=Math.max(Er,Math.floor($*pe));if(x>=$)return se;$=x,ie+=1;}}},s={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
708
+ - \u6216\u6307\u5B9A start_line/num_lines \u7CBE\u51C6\u8BFB\u53D6`),ae&&J.strategy==="full"&&se.length>N){ae=false;let D=Math.max(.1,Math.min(.9,N/se.length));$=Math.max(Ir,Math.floor($*D)),oe+=1;continue}if(d||se.length<=N||oe>=zm||$<=Ir)return se;let pe=Math.max(.1,Math.min(.9,N/se.length)),x=Math.max(Ir,Math.floor($*pe));if(x>=$)return se;$=x,oe+=1;}}},s={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
709
709
 
710
710
  \u26A1 \u7279\u6027:
711
711
  - \u89E3\u6790 TypeScript/JavaScript/Python \u4EE3\u7801\u7ED3\u6784
@@ -720,7 +720,7 @@ build_index(paths=["src/**/*.ts"]) \u2192 \u53EA\u7D22\u5F15\u6307\u5B9A\u8D
720
720
 
721
721
  \u{1F4CA} \u7D22\u5F15\u540E\u53EF\u4EE5\u4F7F\u7528:
722
722
  - readfile \u7684\u7B26\u53F7\u5B9A\u4F4D\u4F1A\u66F4\u5FEB\u66F4\u51C6\u786E
723
- - 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:p=false}=l,d=e(),h=await yn(d).buildIndex({paths:c,languages:u,force:p,onProgress:(y,b,_)=>{}}),f=[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){f.push(""),f.push("\u274C \u9519\u8BEF:");for(let y of h.errors.slice(0,5))f.push(` ${gt(y.file)}: ${y.error}`);h.errors.length>5&&f.push(` ... \u8FD8\u6709 ${h.errors.length-5} \u4E2A\u9519\u8BEF`);}return f.push(""),f.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"),f.join(`
723
+ - 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:p=false}=l,d=e(),h=await bn(d).buildIndex({paths:c,languages:u,force:p,onProgress:(y,b,_)=>{}}),f=[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){f.push(""),f.push("\u274C \u9519\u8BEF:");for(let y of h.errors.slice(0,5))f.push(` ${gt(y.file)}: ${y.error}`);h.errors.length>5&&f.push(` ... \u8FD8\u6709 ${h.errors.length-5} \u4E2A\u9519\u8BEF`);}return f.push(""),f.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"),f.join(`
724
724
  `)}},n={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
725
725
 
726
726
  \u26A0\uFE0F \u9700\u8981\u5148\u8FD0\u884C build_index \u6784\u5EFA\u7D22\u5F15
@@ -734,7 +734,7 @@ search_symbol(query="usr", fuzzy=true) \u2192 \u6A21\u7CCA\u641C\u7D22
734
734
  \u{1F4CB} \u8FD4\u56DE:
735
735
  - \u7B26\u53F7\u540D\u79F0\u548C\u7C7B\u578B
736
736
  - \u6240\u5728\u6587\u4EF6\u548C\u884C\u53F7
737
- - \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:p=false,limit:d=20}=l,m=e(),h=yn(m);if(!await h.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
737
+ - \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:p=false,limit:d=20}=l,m=e(),h=bn(m);if(!await h.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
738
738
 
739
739
  \u{1F4A1} \u8BF7\u5148\u8FD0\u884C build_index() \u6784\u5EFA\u7D22\u5F15:
740
740
  build_index() \u2192 \u7D22\u5F15\u6574\u4E2A\u9879\u76EE
@@ -746,16 +746,16 @@ search_symbol(query="usr", fuzzy=true) \u2192 \u6A21\u7CCA\u641C\u7D22
746
746
  - \u5C1D\u8BD5 fuzzy=true \u8FDB\u884C\u6A21\u7CCA\u641C\u7D22
747
747
  - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199
748
748
  - \u8FD0\u884C build_index(force=true) \u91CD\u5EFA\u7D22\u5F15`;let b=[`\u2713 \u641C\u7D22: "${c}"${u?` (\u7C7B\u578B: ${u})`:""}${p?" (\u6A21\u7CCA\u5339\u914D)":""}`,`\u627E\u5230 ${y.length} \u4E2A\u7ED3\u679C:`,""];for(let _ of y){let v=gt(_.file),k=_.symbol.parent?`${_.symbol.parent}.`:"";b.push(`\u25B8 ${k}${_.symbol.name} (${_.symbol.kind})`,` \u{1F4C4} ${v}:${_.symbol.startLine}`,"");}if(b.push("\u{1F4A1} \u4F7F\u7528 readfile \u67E5\u770B\u8BE6\u60C5:"),y.length>0){let _=y[0];b.push(` readfile(path="${gt(_.file)}", symbol="${_.symbol.name}")`);}return b.join(`
749
- `)}},i={name:"get_definitions",description:`\u3010\u7B26\u53F7\u5B9A\u4E49\u3011\u5728\u7D22\u5F15\u4E2D\u67E5\u627E\u7B26\u53F7\u5B9A\u4E49\u4F4D\u7F6E\u3002
749
+ `)}},o={name:"get_definitions",description:`\u3010\u7B26\u53F7\u5B9A\u4E49\u3011\u5728\u7D22\u5F15\u4E2D\u67E5\u627E\u7B26\u53F7\u5B9A\u4E49\u4F4D\u7F6E\u3002
750
750
 
751
751
  \u26A0\uFE0F \u9700\u8981\u5148\u8FD0\u884C build_index \u6784\u5EFA\u7D22\u5F15
752
752
 
753
753
  \u793A\u4F8B:
754
754
  get_definitions(query="UserService") \u2192 \u67E5\u627E\u5B9A\u4E49
755
755
  get_definitions(symbol="handleLogin", kind="function")
756
- 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(),p=yn(u);if(!await p.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
756
+ 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(),p=bn(u);if(!await p.hasIndex())return `\u2717 \u7D22\u5F15\u4E0D\u5B58\u5728
757
757
 
758
- \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,f=!!l.fuzzy,y=await p.searchSymbol({query:c,kind:h,fuzzy:f,limit:m});if(l.path){let _=Y.resolve(u,l.path);if(!Gl(u,_))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";y=y.filter(v=>{let k=Y.resolve(v.file);return k===_||k.startsWith(_+Y.sep)});}if(y.length===0)return `\u2713 \u67E5\u627E: "${c}"
758
+ \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,f=!!l.fuzzy,y=await p.searchSymbol({query:c,kind:h,fuzzy:f,limit:m});if(l.path){let _=Y.resolve(u,l.path);if(!Hl(u,_))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";y=y.filter(v=>{let k=Y.resolve(v.file);return k===_||k.startsWith(_+Y.sep)});}if(y.length===0)return `\u2713 \u67E5\u627E: "${c}"
759
759
 
760
760
  \u672A\u627E\u5230\u5B9A\u4E49
761
761
 
@@ -763,15 +763,15 @@ get_definitions(query="User", path="src/auth") \u2192 \u9650\u5B9A\u76EE\u5F55`
763
763
  - \u5C1D\u8BD5 fuzzy=true \u8FDB\u884C\u6A21\u7CCA\u641C\u7D22
764
764
  - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199
765
765
  - \u8FD0\u884C build_index(force=true) \u91CD\u5EFA\u7D22\u5F15`;let b=[`\u2713 \u5B9A\u4E49: "${c}"${h?` (\u7C7B\u578B: ${h})`:""}${f?" (\u6A21\u7CCA\u5339\u914D)":""}`,`\u627E\u5230 ${y.length} \u4E2A\u7ED3\u679C:`,""];for(let _ of y){let v=gt(_.file),k=_.symbol.parent?`${_.symbol.parent}.`:"";b.push(`\u25B8 ${k}${_.symbol.name} (${_.symbol.kind})`,` \u{1F4C4} ${v}:${_.symbol.startLine}`,"");}if(b.push("\u{1F4A1} \u4F7F\u7528 readfile \u67E5\u770B\u8BE6\u60C5:"),y.length>0){let _=y[0];b.push(` readfile(path="${gt(_.file)}", symbol="${_.symbol.name}")`);}return b.join(`
766
- `)}},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
766
+ `)}},i={name:"get_references",description:`\u3010\u7B26\u53F7\u5F15\u7528\u3011\u5728\u5DE5\u4F5C\u533A\u4E2D\u67E5\u627E\u7B26\u53F7\u5F15\u7528\u4F4D\u7F6E\u3002
767
767
 
768
768
  \u793A\u4F8B:
769
769
  get_references(query="UserService")
770
770
  get_references(symbol="handleLogin", path="src/auth")
771
- 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(),p=Y.resolve(u,l.path||".");if(!Gl(u,p))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";let d;try{d=await Z.stat(p);}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,f=!!l.case_insensitive,y=!!l.regex,b;try{let S=y?c:Jm(c);b=new RegExp(S,f?"gi":"g");}catch(S){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${S.message}`}let _=[];if(d.isDirectory()){let S=l.file_pattern||"**/*";_=await Ts(S,{cwd:p,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else _=[p];if(_.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let v=[],k=0,R=0,O=0;for(let S of _){if(k>=h)break;try{let C=await Z.readFile(S,"utf-8");if(C.includes("\0"))continue;let w=C.split(`
771
+ 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(),p=Y.resolve(u,l.path||".");if(!Hl(u,p))return "\u2717 \u8DEF\u5F84\u4E0D\u5728 workspace \u5185";let d;try{d=await Z.stat(p);}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,f=!!l.case_insensitive,y=!!l.regex,b;try{let S=y?c:Ym(c);b=new RegExp(S,f?"gi":"g");}catch(S){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${S.message}`}let _=[];if(d.isDirectory()){let S=l.file_pattern||"**/*";_=await xs(S,{cwd:p,absolute:true,nodir:true,ignore:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/coverage/**","**/__pycache__/**","**/target/**","**/vendor/**"]});}else _=[p];if(_.length===0)return "\u2713 \u672A\u627E\u5230\u53EF\u641C\u7D22\u7684\u6587\u4EF6";let v=[],k=0,R=0,O=0;for(let S of _){if(k>=h)break;try{let C=await Z.readFile(S,"utf-8");if(C.includes("\0"))continue;let w=C.split(`
772
772
  `),T=new Set,M=new Map;for(let B=0;B<w.length&&!(k>=h);B++){let E=w[B],L=b.test(E);if(b.lastIndex=0,L){T.add(B),k++;let N=Math.max(0,B-m),$=Math.min(w.length-1,B+m);for(let G=N;G<=$;G++){let X=M.get(G);M.set(G,{line:w[G],isMatch:X?.isMatch||G===B});}}}if(R++,T.size>0){O++;let E=Array.from(M.keys()).sort((L,N)=>L-N).map(L=>({lineNum:L+1,line:M.get(L)?.line||"",isMatch:M.get(L)?.isMatch||!1}));v.push({file:S,matches:E,matchCount:T.size});}}catch{continue}}let W=gt(p),F=[`\u2713 \u5F15\u7528: "${c}"`,`\u25B8 \u8DEF\u5F84: ${W}`,l.file_pattern?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l.file_pattern}`:"",f?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",y?"\u25B8 \u6A21\u5F0F: \u6B63\u5219":"","",`\u6587\u4EF6: ${R} \u5DF2\u641C\u7D22, ${O} \u6709\u5339\u914D`,`\u5339\u914D: ${k}${k>=h?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(S=>S!=="");for(let S of v){let C=gt(S.file);F.push(`
773
773
  \u25B8 ${C} (${S.matchCount} \u5904)`),F.push("\u2500".repeat(50));let w=-10;for(let T of S.matches){T.lineNum>w+1&&w>0&&F.push(" \u2504\u2504\u2504");let M=T.isMatch?"\u25B6":" ";F.push(`${M}${String(T.lineNum).padStart(5)} \u2502 ${T.line}`),w=T.lineNum;}}return v.length===0&&(F.push("\u672A\u627E\u5230\u5339\u914D\u5185\u5BB9"),F.push(""),F.push("\u{1F4A1} \u5EFA\u8BAE:"),F.push(" - \u68C0\u67E5\u5173\u952E\u8BCD\u62FC\u5199"),F.push(" - \u4F7F\u7528 regex=true \u8FDB\u884C\u66F4\u7CBE\u786E\u5339\u914D"),F.push(" - \u7F29\u5C0F\u6216\u6269\u5927 path/file_pattern \u8303\u56F4")),F.join(`
774
- `)}};return [t,s,n,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 yn(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
774
+ `)}};return [t,s,n,o,i,{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 bn(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
775
775
 
776
776
  \u{1F4A1} \u8FD0\u884C build_index() \u6784\u5EFA\u7D22\u5F15\u4EE5\u83B7\u5F97\u66F4\u597D\u7684\u4EE3\u7801\u5BFC\u822A\u4F53\u9A8C`;let p=(u.size/1024).toFixed(1),d=(u.size/(1024*1024)).toFixed(2),m=u.size>1024*1024?`${d}MB`:`${p}KB`;return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u5DF2\u6784\u5EFA
777
777
 
@@ -781,8 +781,8 @@ get_references(query="FeatureFlag", file_pattern="*.ts")`,parameters:{type:"obje
781
781
  \u7D22\u5F15\u5927\u5C0F: ${m}
782
782
  \u6700\u540E\u66F4\u65B0: ${u.lastUpdated?.toLocaleString()||"N/A"}
783
783
 
784
- \u{1F4A1} \u4F7F\u7528 build_index(force=true) \u53EF\u4EE5\u91CD\u5EFA\u7D22\u5F15`}}]}le();le();var Be=null;function Wl(r,e){return {...r,...e,PATH:r.PATH||e.PATH||"",JAVA_HOME:r.JAVA_HOME||e.JAVA_HOME||"",MAVEN_HOME:r.MAVEN_HOME||e.MAVEN_HOME||"",M2_HOME:r.M2_HOME||e.M2_HOME||"",NODE_PATH:r.NODE_PATH||e.NODE_PATH||"",GOPATH:r.GOPATH||e.GOPATH||"",CARGO_HOME:r.CARGO_HOME||e.CARGO_HOME||"",RUSTUP_HOME:r.RUSTUP_HOME||e.RUSTUP_HOME||"",PYENV_ROOT:r.PYENV_ROOT||e.PYENV_ROOT||"",CONDA_PREFIX:r.CONDA_PREFIX||e.CONDA_PREFIX||""}}function Hl(r){let e={};for(let t of r.split(`
785
- `)){let s=t.indexOf("=");if(s>0){let n=t.substring(0,s),i=t.substring(s+1);e[n]=i;}}return e}async function ql(){if(Be)return;let r={...process.env};if(process.platform==="win32"){Be=r;return}try{let e=process.env.SHELL||"/bin/zsh";g.debug("SHELL","Preloading shell environment asynchronously...");let t=await execa(e,["-lc","env"],{encoding:"utf8",timeout:5e3,reject:!1,stdin:"ignore",stdout:"pipe",stderr:"ignore"});if(t.stdout){let s=Hl(t.stdout);Be=Wl(s,r),g.debug("SHELL","Preloaded shell environment successfully",{pathLength:Be.PATH?.length});}else Be=r;}catch(e){g.warn("SHELL","Failed to preload shell environment",{error:e}),Be=r;}}function zl(){if(Be)return Be;process.env.CLI_DEBUG==="1"&&g.warn("SHELL","\u26A0\uFE0F getShellEnv() cache miss - this should not happen! Call preloadShellEnv() during init.");let r={...process.env};if(process.platform==="win32")return Be=r,Be;try{let e=process.env.SHELL||"/bin/zsh",t=execaSync(e,["-ilc","env"],{encoding:"utf8",timeout:5e3,reject:!1});if(t.stdout){let s=Hl(t.stdout);Be=Wl(s,r),process.env.CLI_DEBUG==="1"&&g.debug("SHELL","Loaded shell environment (sync fallback), PATH length:",{pathLength:Be.PATH?.length});}else Be=r;}catch(e){g.warn("SHELL","Failed to load shell environment",{error:e}),Be=r;}return Be}le();var yo=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),g.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 s=this.processes.get(e);s&&(s.status=t===0?"completed":"failed",s.exitCode=t,s.endTime=new Date,g.debug("PROCESS_MGR",`Process completed PID=${e}`,{exitCode:t,duration:s.endTime.getTime()-s.startTime.getTime()}),this.emit("process:exit",s),setTimeout(()=>{this.processes.delete(e);},1e3));}unregister(e){this.processes.get(e)&&(this.processes.delete(e),g.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,s)=>s.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,g.debug("PROCESS_MGR",`Process ${e} is no longer alive, marked as completed`)));}kill(e,t="SIGTERM",s=false){let n=this.processes.get(e);try{return process.kill(e,t),g.info("PROCESS_MGR",`Sent ${t} to process PID=${e}`),s&&setTimeout(()=>{try{this.isAlive(e)&&(process.kill(e,"SIGKILL"),g.info("PROCESS_MGR",`Force killed process PID=${e}`));}catch{}},2e3),n&&(n.status="killed",n.endTime=new Date,this.emit("process:kill",n)),!0}catch(i){return i.code==="ESRCH"?(n&&(n.status="completed",n.endTime=new Date),g.debug("PROCESS_MGR",`Process ${e} not found (already exited)`),false):(g.error("PROCESS_MGR",`Failed to kill process ${e}`,{error:i.message}),false)}}killProcessGroup(e,t="SIGTERM"){try{process.kill(-e,t),g.info("PROCESS_MGR",`Sent ${t} to process group PID=${e}`);let s=this.processes.get(e);return s&&(s.status="killed",s.endTime=new Date,this.emit("process:kill",s)),!0}catch{return this.kill(e,t)}}killAll(e=false){let t=this.getRunning(),s=0,n=0;for(let i of t)(i.background?this.killProcessGroup(i.pid):this.kill(i.pid,"SIGTERM",e))?s++:n++;return g.info("PROCESS_MGR",`Killed ${s} processes, ${n} failed`),{killed:s,failed:n}}cleanup(e=20){let s=this.getAll().filter(i=>i.status!=="running");s.sort((i,o)=>{let a=i.endTime?.getTime()||0;return (o.endTime?.getTime()||0)-a});let n=0;for(let i=e;i<s.length;i++)this.processes.delete(s[i].pid),n++;return n}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(),s=this.formatDuration(t),n=this.getStatusIcon(e.status),i=e.background?" [BG]":"",o=e.command.length>40?e.command.substring(0,37)+"...":e.command;return `${n} PID ${e.pid}${i} | ${o} | ${s}`}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(),g.debug("PROCESS_MGR","Process manager reset");}},Jl=new yo;var Mr={terminal:true,editor:false,debug:true,trace:true},bo={...Mr,editor:true};le();function Xm(){let r=process.platform;if(r==="darwin")return Y__default.join(Us.homedir(),"Library","Application Support","Neox");if(r==="win32")return Y__default.join(process.env.APPDATA||Y__default.join(Us.homedir(),"AppData","Roaming"),"Neox");{let e=process.env.XDG_CONFIG_HOME||Y__default.join(Us.homedir(),".config");return Y__default.join(e,"neox")}}var Vl=Xm(),wo=Y__default.join(Vl,"token-usage.json"),Kl=3e3,vo=class{stats=null;directoriesReady;saveDebounceTimer=null;constructor(){this.directoriesReady=this.ensureDirectories();}async ensureDirectories(){await Z__default.mkdir(Vl,{recursive:true});}async ensureReady(){try{await this.directoriesReady;}catch(e){throw g.error("TokenUsage","Failed to initialize directories",{error:e.message}),e}}generateId(){return `${Date.now()}-${Math.random().toString(36).slice(2,9)}`}async load(){if(await this.ensureReady(),this.stats)return this.stats;try{let e=await Z__default.readFile(wo,"utf-8");return this.stats=JSON.parse(e),g.info("TokenUsage","Loaded usage statistics"),this.stats}catch{return g.info("TokenUsage","No existing usage file, creating new"),this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},this.stats}}async save(){this.saveDebounceTimer&&clearTimeout(this.saveDebounceTimer),this.saveDebounceTimer=setTimeout(async()=>{await this.saveImmediate();},1e3);}async saveImmediate(){if(await this.ensureReady(),!!this.stats)try{this.stats.lastUpdated=Date.now();let e=`${wo}.${Date.now()}.tmp`;await Z__default.writeFile(e,JSON.stringify(this.stats,null,2),"utf-8"),await Z__default.rename(e,wo),g.info("TokenUsage","Saved usage statistics");}catch(e){g.error("TokenUsage","Failed to save",{error:e.message});}}async recordUsage(e){let t=await this.load(),s={id:this.generateId(),...e};t.records.push(s),t.records.length>Kl&&(t.records=t.records.slice(-Kl)),t.providers[e.provider]||(t.providers[e.provider]={provider:e.provider,totalRequests:0,successRequests:0,failedRequests:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCachedTokens:0,totalOpenaiCachedTokens:0,totalAnthropicCacheReadTokens:0,totalAnthropicCacheCreationTokens:0,totalAnthropicCacheCreation5mTokens:0,totalAnthropicCacheCreation1hTokens:0,avgDuration:0,lastRequestTime:0,models:{}});let n=t.providers[e.provider];n.totalRequests++,e.success?n.successRequests++:n.failedRequests++,n.totalInputTokens+=e.inputTokens,n.totalOutputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.totalCachedTokens+=e.cachedTokens||0,n.totalOpenaiCachedTokens+=e.openaiCachedTokens||0,n.totalAnthropicCacheReadTokens+=e.anthropicCacheReadTokens||0,n.totalAnthropicCacheCreationTokens+=e.anthropicCacheCreationTokens||0,n.totalAnthropicCacheCreation5mTokens+=e.anthropicCacheCreation5mTokens||0,n.totalAnthropicCacheCreation1hTokens+=e.anthropicCacheCreation1hTokens||0,n.lastRequestTime=e.timestamp;let i=n.avgDuration*(n.totalRequests-1)+e.duration;n.avgDuration=Math.round(i/n.totalRequests),n.models[e.model]||(n.models[e.model]={requests:0,inputTokens:0,outputTokens:0,totalTokens:0,cachedTokens:0});let o=n.models[e.model];o.requests++,o.inputTokens+=e.inputTokens,o.outputTokens+=e.outputTokens,o.totalTokens+=e.totalTokens,o.cachedTokens+=e.cachedTokens||0,await this.save();}async getProviderStats(){let e=await this.load();return Object.values(e.providers).sort((t,s)=>s.lastRequestTime-t.lastRequestTime)}async getProviderRecords(e,t=100){return (await this.load()).records.filter(n=>n.provider===e).slice(-t).reverse()}async getRecentRecords(e=50){return (await this.load()).records.slice(-e).reverse()}async getSummary(){let e=await this.load(),t=Object.values(e.providers),s=t.reduce((a,l)=>a+l.totalInputTokens,0),n=t.reduce((a,l)=>a+l.totalCachedTokens,0),i=t.reduce((a,l)=>a+l.totalOpenaiCachedTokens,0),o=t.reduce((a,l)=>a+l.totalAnthropicCacheReadTokens,0);return {totalRequests:t.reduce((a,l)=>a+l.totalRequests,0),totalTokens:t.reduce((a,l)=>a+l.totalTokens,0),totalInputTokens:s,totalOutputTokens:t.reduce((a,l)=>a+l.totalOutputTokens,0),totalCachedTokens:n,totalOpenaiCachedTokens:i,totalAnthropicCacheReadTokens:o,totalAnthropicCacheCreationTokens:t.reduce((a,l)=>a+l.totalAnthropicCacheCreationTokens,0),cacheHitRate:s>0?n/s:0,providerCount:t.length,lastRequestTime:Math.max(...t.map(a=>a.lastRequestTime),0)}}async clearAll(){this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},await this.saveImmediate(),g.info("TokenUsage","Cleared all usage statistics");}async clearProvider(e){let t=await this.load();delete t.providers[e],t.records=t.records.filter(s=>s.provider!==e),await this.saveImmediate(),g.info("TokenUsage","Cleared usage for provider",{provider:e});}},Yl=new vo;function _n(){return {logger:g,shellEnv:{preloadShellEnv:ql,getShellEnv:zl},processManager:Jl,capabilities:Mr,tokenUsage:Yl}}var Pr={name:"update_plan",description:`Updates the task plan.
784
+ \u{1F4A1} \u4F7F\u7528 build_index(force=true) \u53EF\u4EE5\u91CD\u5EFA\u7D22\u5F15`}}]}le();le();var Be=null;function zl(r,e){return {...r,...e,PATH:r.PATH||e.PATH||"",JAVA_HOME:r.JAVA_HOME||e.JAVA_HOME||"",MAVEN_HOME:r.MAVEN_HOME||e.MAVEN_HOME||"",M2_HOME:r.M2_HOME||e.M2_HOME||"",NODE_PATH:r.NODE_PATH||e.NODE_PATH||"",GOPATH:r.GOPATH||e.GOPATH||"",CARGO_HOME:r.CARGO_HOME||e.CARGO_HOME||"",RUSTUP_HOME:r.RUSTUP_HOME||e.RUSTUP_HOME||"",PYENV_ROOT:r.PYENV_ROOT||e.PYENV_ROOT||"",CONDA_PREFIX:r.CONDA_PREFIX||e.CONDA_PREFIX||""}}function Jl(r){let e={};for(let t of r.split(`
785
+ `)){let s=t.indexOf("=");if(s>0){let n=t.substring(0,s),o=t.substring(s+1);e[n]=o;}}return e}async function Kl(){if(Be)return;let r={...process.env};if(process.platform==="win32"){Be=r;return}try{let e=process.env.SHELL||"/bin/zsh";g.debug("SHELL","Preloading shell environment asynchronously...");let t=await execa(e,["-lc","env"],{encoding:"utf8",timeout:5e3,reject:!1,stdin:"ignore",stdout:"pipe",stderr:"ignore"});if(t.stdout){let s=Jl(t.stdout);Be=zl(s,r),g.debug("SHELL","Preloaded shell environment successfully",{pathLength:Be.PATH?.length});}else Be=r;}catch(e){g.warn("SHELL","Failed to preload shell environment",{error:e}),Be=r;}}function Vl(){if(Be)return Be;process.env.CLI_DEBUG==="1"&&g.warn("SHELL","\u26A0\uFE0F getShellEnv() cache miss - this should not happen! Call preloadShellEnv() during init.");let r={...process.env};if(process.platform==="win32")return Be=r,Be;try{let e=process.env.SHELL||"/bin/zsh",t=execaSync(e,["-ilc","env"],{encoding:"utf8",timeout:5e3,reject:!1});if(t.stdout){let s=Jl(t.stdout);Be=zl(s,r),process.env.CLI_DEBUG==="1"&&g.debug("SHELL","Loaded shell environment (sync fallback), PATH length:",{pathLength:Be.PATH?.length});}else Be=r;}catch(e){g.warn("SHELL","Failed to load shell environment",{error:e}),Be=r;}return Be}le();var bi=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),g.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 s=this.processes.get(e);s&&(s.status=t===0?"completed":"failed",s.exitCode=t,s.endTime=new Date,g.debug("PROCESS_MGR",`Process completed PID=${e}`,{exitCode:t,duration:s.endTime.getTime()-s.startTime.getTime()}),this.emit("process:exit",s),setTimeout(()=>{this.processes.delete(e);},1e3));}unregister(e){this.processes.get(e)&&(this.processes.delete(e),g.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,s)=>s.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,g.debug("PROCESS_MGR",`Process ${e} is no longer alive, marked as completed`)));}kill(e,t="SIGTERM",s=false){let n=this.processes.get(e);try{return process.kill(e,t),g.info("PROCESS_MGR",`Sent ${t} to process PID=${e}`),s&&setTimeout(()=>{try{this.isAlive(e)&&(process.kill(e,"SIGKILL"),g.info("PROCESS_MGR",`Force killed process PID=${e}`));}catch{}},2e3),n&&(n.status="killed",n.endTime=new Date,this.emit("process:kill",n)),!0}catch(o){return o.code==="ESRCH"?(n&&(n.status="completed",n.endTime=new Date),g.debug("PROCESS_MGR",`Process ${e} not found (already exited)`),false):(g.error("PROCESS_MGR",`Failed to kill process ${e}`,{error:o.message}),false)}}killProcessGroup(e,t="SIGTERM"){try{process.kill(-e,t),g.info("PROCESS_MGR",`Sent ${t} to process group PID=${e}`);let s=this.processes.get(e);return s&&(s.status="killed",s.endTime=new Date,this.emit("process:kill",s)),!0}catch{return this.kill(e,t)}}killAll(e=false){let t=this.getRunning(),s=0,n=0;for(let o of t)(o.background?this.killProcessGroup(o.pid):this.kill(o.pid,"SIGTERM",e))?s++:n++;return g.info("PROCESS_MGR",`Killed ${s} processes, ${n} failed`),{killed:s,failed:n}}cleanup(e=20){let s=this.getAll().filter(o=>o.status!=="running");s.sort((o,i)=>{let a=o.endTime?.getTime()||0;return (i.endTime?.getTime()||0)-a});let n=0;for(let o=e;o<s.length;o++)this.processes.delete(s[o].pid),n++;return n}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(),s=this.formatDuration(t),n=this.getStatusIcon(e.status),o=e.background?" [BG]":"",i=e.command.length>40?e.command.substring(0,37)+"...":e.command;return `${n} PID ${e.pid}${o} | ${i} | ${s}`}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(),g.debug("PROCESS_MGR","Process manager reset");}},Yl=new bi;var Ar={terminal:true,editor:false,debug:true,trace:true},_i={...Ar,editor:true};le();function eh(){let r=process.platform;if(r==="darwin")return Y__default.join(js.homedir(),"Library","Application Support","Neox");if(r==="win32")return Y__default.join(process.env.APPDATA||Y__default.join(js.homedir(),"AppData","Roaming"),"Neox");{let e=process.env.XDG_CONFIG_HOME||Y__default.join(js.homedir(),".config");return Y__default.join(e,"neox")}}var Zl=eh(),vi=Y__default.join(Zl,"token-usage.json"),Xl=3e3,Ti=class{stats=null;directoriesReady;saveDebounceTimer=null;constructor(){this.directoriesReady=this.ensureDirectories();}async ensureDirectories(){await Z__default.mkdir(Zl,{recursive:true});}async ensureReady(){try{await this.directoriesReady;}catch(e){throw g.error("TokenUsage","Failed to initialize directories",{error:e.message}),e}}generateId(){return `${Date.now()}-${Math.random().toString(36).slice(2,9)}`}async load(){if(await this.ensureReady(),this.stats)return this.stats;try{let e=await Z__default.readFile(vi,"utf-8");return this.stats=JSON.parse(e),g.info("TokenUsage","Loaded usage statistics"),this.stats}catch{return g.info("TokenUsage","No existing usage file, creating new"),this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},this.stats}}async save(){this.saveDebounceTimer&&clearTimeout(this.saveDebounceTimer),this.saveDebounceTimer=setTimeout(async()=>{await this.saveImmediate();},1e3);}async saveImmediate(){if(await this.ensureReady(),!!this.stats)try{this.stats.lastUpdated=Date.now();let e=`${vi}.${Date.now()}.tmp`;await Z__default.writeFile(e,JSON.stringify(this.stats,null,2),"utf-8"),await Z__default.rename(e,vi),g.info("TokenUsage","Saved usage statistics");}catch(e){g.error("TokenUsage","Failed to save",{error:e.message});}}async recordUsage(e){let t=await this.load(),s={id:this.generateId(),...e};t.records.push(s),t.records.length>Xl&&(t.records=t.records.slice(-Xl)),t.providers[e.provider]||(t.providers[e.provider]={provider:e.provider,totalRequests:0,successRequests:0,failedRequests:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCachedTokens:0,totalOpenaiCachedTokens:0,totalAnthropicCacheReadTokens:0,totalAnthropicCacheCreationTokens:0,totalAnthropicCacheCreation5mTokens:0,totalAnthropicCacheCreation1hTokens:0,avgDuration:0,lastRequestTime:0,models:{}});let n=t.providers[e.provider];n.totalRequests++,e.success?n.successRequests++:n.failedRequests++,n.totalInputTokens+=e.inputTokens,n.totalOutputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.totalCachedTokens+=e.cachedTokens||0,n.totalOpenaiCachedTokens+=e.openaiCachedTokens||0,n.totalAnthropicCacheReadTokens+=e.anthropicCacheReadTokens||0,n.totalAnthropicCacheCreationTokens+=e.anthropicCacheCreationTokens||0,n.totalAnthropicCacheCreation5mTokens+=e.anthropicCacheCreation5mTokens||0,n.totalAnthropicCacheCreation1hTokens+=e.anthropicCacheCreation1hTokens||0,n.lastRequestTime=e.timestamp;let o=n.avgDuration*(n.totalRequests-1)+e.duration;n.avgDuration=Math.round(o/n.totalRequests),n.models[e.model]||(n.models[e.model]={requests:0,inputTokens:0,outputTokens:0,totalTokens:0,cachedTokens:0});let i=n.models[e.model];i.requests++,i.inputTokens+=e.inputTokens,i.outputTokens+=e.outputTokens,i.totalTokens+=e.totalTokens,i.cachedTokens+=e.cachedTokens||0,await this.save();}async getProviderStats(){let e=await this.load();return Object.values(e.providers).sort((t,s)=>s.lastRequestTime-t.lastRequestTime)}async getProviderRecords(e,t=100){return (await this.load()).records.filter(n=>n.provider===e).slice(-t).reverse()}async getRecentRecords(e=50){return (await this.load()).records.slice(-e).reverse()}async getSummary(){let e=await this.load(),t=Object.values(e.providers),s=t.reduce((a,l)=>a+l.totalInputTokens,0),n=t.reduce((a,l)=>a+l.totalCachedTokens,0),o=t.reduce((a,l)=>a+l.totalOpenaiCachedTokens,0),i=t.reduce((a,l)=>a+l.totalAnthropicCacheReadTokens,0);return {totalRequests:t.reduce((a,l)=>a+l.totalRequests,0),totalTokens:t.reduce((a,l)=>a+l.totalTokens,0),totalInputTokens:s,totalOutputTokens:t.reduce((a,l)=>a+l.totalOutputTokens,0),totalCachedTokens:n,totalOpenaiCachedTokens:o,totalAnthropicCacheReadTokens:i,totalAnthropicCacheCreationTokens:t.reduce((a,l)=>a+l.totalAnthropicCacheCreationTokens,0),cacheHitRate:s>0?n/s:0,providerCount:t.length,lastRequestTime:Math.max(...t.map(a=>a.lastRequestTime),0)}}async clearAll(){this.stats={version:"1.0.0",lastUpdated:Date.now(),providers:{},records:[]},await this.saveImmediate(),g.info("TokenUsage","Cleared all usage statistics");}async clearProvider(e){let t=await this.load();delete t.providers[e],t.records=t.records.filter(s=>s.provider!==e),await this.saveImmediate(),g.info("TokenUsage","Cleared usage for provider",{provider:e});}},Ql=new Ti;function wn(){return {logger:g,shellEnv:{preloadShellEnv:Kl,getShellEnv:Vl},processManager:Yl,capabilities:Ar,tokenUsage:Ql}}var Or={name:"update_plan",description:`Updates the task plan.
786
786
 
787
787
  Provide an optional explanation and a list of plan items, each with a step and status.
788
788
  At most one step can be in_progress at a time.
@@ -791,47 +791,47 @@ Rules:
791
791
  - Keep step descriptions short (5-7 words)
792
792
  - Only ONE step should be "in_progress" at any time
793
793
  - Mark completed steps as "completed"
794
- - Update the plan whenever you complete a step or start a new one`,parameters:{type:"object",properties:{explanation:{type:"string",description:"Optional explanation for the plan update"},plan:{type:"array",description:"The list of steps",items:{type:"object",properties:{step:{type:"string",description:"Step description (5-7 words)"},status:{type:"string",enum:["pending","in_progress","completed"],description:"Step status: pending, in_progress, or completed"}},required:["step","status"]}}},required:["plan"]}};function Xl(r){return r.plan.filter(t=>t.status==="in_progress").length>1?JSON.stringify({success:false,error:"At most one step can be in_progress at a time"}):JSON.stringify({success:true,message:"Plan updated"})}var th="NEOX_WORKDIR",sh="NEOX_WORKER",nh=_n(),Pe=nh,be=Pe.logger;function oc(r){Pe=r,be=r.logger;}var To=new Map,rh=300*1e3;function ih(r,e){return e?r.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):r}async function oh(r){await(r??Pe).shellEnv.preloadShellEnv();}function ah(){let r=process.env.NEOX_WORKER_ENTRY;if(r&&vn__default.existsSync(r))return r;let e=process.argv[1];if(e&&e.endsWith(".js")&&vn__default.existsSync(e))return e;let t=Y__default.resolve(process.cwd(),"dist","cli","main.js");return vn__default.existsSync(t)?t:null}async function lh(r,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=ah();return n?new Promise(i=>{let o=fork(n,[],{env:{...process.env,[sh]:"execute_shell"},stdio:["ignore","ignore","ignore","ipc"]}),a=false,l=Number(process.env.NEOX_SHELL_WORKER_WATCHDOG_MS)||6e4,c=setTimeout(()=>{be.warn("SHELL_WORKER",`execute_shell running > ${l}ms`,{command:r});},l),u=()=>{clearTimeout(c),s&&s.removeEventListener("abort",d),o.removeAllListeners();},p=m=>{a||(a=true,u(),i(m));},d=()=>{o.connected&&o.send({type:"abort"}),setTimeout(()=>{if(!a){try{o.kill("SIGTERM");}catch{}p({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
794
+ - Update the plan whenever you complete a step or start a new one`,parameters:{type:"object",properties:{explanation:{type:"string",description:"Optional explanation for the plan update"},plan:{type:"array",description:"The list of steps",items:{type:"object",properties:{step:{type:"string",description:"Step description (5-7 words)"},status:{type:"string",enum:["pending","in_progress","completed"],description:"Step status: pending, in_progress, or completed"}},required:["step","status"]}}},required:["plan"]}};function ec(r){return r.plan.filter(t=>t.status==="in_progress").length>1?JSON.stringify({success:false,error:"At most one step can be in_progress at a time"}):JSON.stringify({success:true,message:"Plan updated"})}var rh="NEOX_WORKDIR",oh="NEOX_WORKER",ih=wn(),Pe=ih,be=Pe.logger;function cc(r){Pe=r,be=r.logger;}var xi=new Map,ah=300*1e3;function lh(r,e){return e?r.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):r}async function ch(r){await(r??Pe).shellEnv.preloadShellEnv();}function uh(){let r=process.env.NEOX_WORKER_ENTRY;if(r&&Tn__default.existsSync(r))return r;let e=process.argv[1];if(e&&e.endsWith(".js")&&Tn__default.existsSync(e))return e;let t=Y__default.resolve(process.cwd(),"dist","cli","main.js");return Tn__default.existsSync(t)?t:null}async function ph(r,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=uh();return n?new Promise(o=>{let i=fork(n,[],{env:{...process.env,[oh]:"execute_shell"},stdio:["ignore","ignore","ignore","ipc"]}),a=false,l=Number(process.env.NEOX_SHELL_WORKER_WATCHDOG_MS)||6e4,c=setTimeout(()=>{be.warn("SHELL_WORKER",`execute_shell running > ${l}ms`,{command:r});},l),u=()=>{clearTimeout(c),s&&s.removeEventListener("abort",d),i.removeAllListeners();},p=m=>{a||(a=true,u(),o(m));},d=()=>{i.connected&&i.send({type:"abort"}),setTimeout(()=>{if(!a){try{i.kill("SIGTERM");}catch{}p({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
795
795
  \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${t}
796
796
  \u25B8 \u6267\u884C\u547D\u4EE4: ${r}
797
797
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
798
798
 
799
799
  \u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
800
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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);};s&&(s.aborted?d():s.addEventListener("abort",d,{once:true})),o.on("message",m=>{if(!(!m||typeof m!="object")){if(m.type==="background_exit"){typeof m.pid=="number"&&Pe.processManager.markCompleted(m.pid,m.exitCode??0);return}m.type==="result"&&p({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||(be.warn("SHELL_WORKER","Worker exited before result",{code:m,command:r}),p(null));}),o.send({type:"execute_shell",payload:{command:r,background:e,workspaceRoot:t}});}):(be.warn("SHELL_WORKER","Worker entry not found, fallback to inline execution"),null)}function Ql(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(){let r=process.env[th];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Oe(r){let e=He();if(!r||r.trim()===""||r.trim()===".")return e;let t=r.trim();if(t.startsWith("~/"))return Y__default.resolve(Y__default.join(Us.homedir(),t.slice(2)));let s=Y__default.isAbsolute(t),n=process.platform!=="win32"&&t.startsWith(`Users${Y__default.sep}`);if(s||n){let l=!s&&n?Y__default.join(Y__default.sep,t):t;return Y__default.resolve(l)}t=t.replace(/^[.\\/]+/,"");let i=t.split(/[\\/]+/).filter(Boolean),o=Y__default.basename(e);i.length>0&&i[0]===o&&i.shift();let a=Y__default.join(e,...i);return Y__default.resolve(a)}function Re(r){let e=He(),t=Y__default.relative(e,r);return t&&!t.startsWith("..")&&!Y__default.isAbsolute(t)?t:r}var ec=12e3,tc=4e3,sc=1e6;function xt(r){let e=He(),t=Y__default.relative(e,r);return t===""?true:!t.startsWith("..")&&!Y__default.isAbsolute(t)}function Or(r,e){return r.length<=e?{text:r,truncated:false}:{text:r.slice(0,e)+`
801
- ... (truncated)`,truncated:true}}async function Ne(r,e,t,s){let n=Date.now();return new Promise((i,o)=>{let a=spawn(r,e,{cwd:t,env:{...Pe.shellEnv.getShellEnv(),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 p=null;s?.timeoutMs&&(p=setTimeout(()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);},s.timeoutMs));let d=()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);};s?.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d,{once:true})),a.on("close",m=>{p&&clearTimeout(p),s?.signal&&s.signal.removeEventListener("abort",d),i({stdout:l,stderr:c,exitCode:u?-1:m??0,durationMs:Date.now()-n});}),a.on("error",m=>{p&&clearTimeout(p),s?.signal&&s.signal.removeEventListener("abort",d),i({stdout:l,stderr:c,exitCode:-1,durationMs:Date.now()-n});});})}async function Jt(r,e){try{let t=await Ne("git",["rev-parse","--show-toplevel"],r,{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 ph(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var dh={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:r,content:e,mode:t="overwrite"}){if(!r)return JSON.stringify(z("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(z("write_file","error","Missing required parameter: content",{error:"content is required",verify_hint:"Please provide the content parameter with the text to write."}));let s=typeof e=="string"?e:String(e);if(s.trim()==="")return JSON.stringify(z("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 n=Oe(r),i=createHash("sha256").update(s).digest("hex").substring(0,16),o=To.get(n),a=Date.now();if(o&&o.checksum===i&&o.success&&a-o.timestamp<rh){let l=s.split(`
802
- `).length;return JSON.stringify(z("write_file","already_done",`File already written with identical content (${l} lines, ${s.length} bytes)`,{file_path:n,checksum:i,verify_hint:`Use "readfile ${r}" to verify the content if needed.`,metadata:{lines:l,bytes:s.length}}))}try{let l=!1;try{await Z__default.access(n),l=!0;}catch{}await Z__default.mkdir(Y__default.dirname(n),{recursive:!0}),t==="append"?await Z__default.appendFile(n,s,"utf-8"):await Z__default.writeFile(n,s,"utf-8"),To.set(n,{checksum:i,timestamp:a,success:!0});let c=s.split(`
803
- `).length,u=l?"updated":"created";return JSON.stringify(z("write_file","success",`File ${u}: ${Y__default.basename(n)} (${c} lines, ${s.length} bytes)`,{file_path:n,checksum:i,verify_hint:`Use "readfile ${r}" to verify the content.`,metadata:{action:u,lines:c,bytes:s.length}}))}catch(l){return To.set(n,{checksum:i,timestamp:a,success:false}),JSON.stringify(z("write_file","error",`Failed to write file: ${l.message}`,{file_path:n,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};function mh(r){let e=r.includes(`\r
800
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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{i.kill("SIGKILL");}catch{}},2e3);};s&&(s.aborted?d():s.addEventListener("abort",d,{once:true})),i.on("message",m=>{if(!(!m||typeof m!="object")){if(m.type==="background_exit"){typeof m.pid=="number"&&Pe.processManager.markCompleted(m.pid,m.exitCode??0);return}m.type==="result"&&p({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});}}),i.on("exit",m=>{a||(be.warn("SHELL_WORKER","Worker exited before result",{code:m,command:r}),p(null));}),i.send({type:"execute_shell",payload:{command:r,background:e,workspaceRoot:t}});}):(be.warn("SHELL_WORKER","Worker entry not found, fallback to inline execution"),null)}function sc(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(){let r=process.env[rh];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Oe(r){let e=He();if(!r||r.trim()===""||r.trim()===".")return e;let t=r.trim();if(t.startsWith("~/"))return Y__default.resolve(Y__default.join(js.homedir(),t.slice(2)));let s=Y__default.isAbsolute(t),n=process.platform!=="win32"&&t.startsWith(`Users${Y__default.sep}`);if(s||n){let l=!s&&n?Y__default.join(Y__default.sep,t):t;return Y__default.resolve(l)}t=t.replace(/^[.\\/]+/,"");let o=t.split(/[\\/]+/).filter(Boolean),i=Y__default.basename(e);o.length>0&&o[0]===i&&o.shift();let a=Y__default.join(e,...o);return Y__default.resolve(a)}function Re(r){let e=He(),t=Y__default.relative(e,r);return t&&!t.startsWith("..")&&!Y__default.isAbsolute(t)?t:r}var nc=12e3,rc=4e3,oc=1e6;function xt(r){let e=He(),t=Y__default.relative(e,r);return t===""?true:!t.startsWith("..")&&!Y__default.isAbsolute(t)}function Lr(r,e){return r.length<=e?{text:r,truncated:false}:{text:r.slice(0,e)+`
801
+ ... (truncated)`,truncated:true}}async function Ne(r,e,t,s){let n=Date.now();return new Promise((o,i)=>{let a=spawn(r,e,{cwd:t,env:{...Pe.shellEnv.getShellEnv(),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 p=null;s?.timeoutMs&&(p=setTimeout(()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);},s.timeoutMs));let d=()=>{u=true,a.kill("SIGTERM"),setTimeout(()=>{a.killed||a.kill("SIGKILL");},1e3);};s?.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d,{once:true})),a.on("close",m=>{p&&clearTimeout(p),s?.signal&&s.signal.removeEventListener("abort",d),o({stdout:l,stderr:c,exitCode:u?-1:m??0,durationMs:Date.now()-n});}),a.on("error",m=>{p&&clearTimeout(p),s?.signal&&s.signal.removeEventListener("abort",d),o({stdout:l,stderr:c,exitCode:-1,durationMs:Date.now()-n});});})}async function Kt(r,e){try{let t=await Ne("git",["rev-parse","--show-toplevel"],r,{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 hh(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var gh={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:r,content:e,mode:t="overwrite"}){if(!r)return JSON.stringify(z("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(z("write_file","error","Missing required parameter: content",{error:"content is required",verify_hint:"Please provide the content parameter with the text to write."}));let s=typeof e=="string"?e:String(e);if(s.trim()==="")return JSON.stringify(z("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 n=Oe(r),o=createHash("sha256").update(s).digest("hex").substring(0,16),i=xi.get(n),a=Date.now();if(i&&i.checksum===o&&i.success&&a-i.timestamp<ah){let l=s.split(`
802
+ `).length;return JSON.stringify(z("write_file","already_done",`File already written with identical content (${l} lines, ${s.length} bytes)`,{file_path:n,checksum:o,verify_hint:`Use "readfile ${r}" to verify the content if needed.`,metadata:{lines:l,bytes:s.length}}))}try{let l=!1;try{await Z__default.access(n),l=!0;}catch{}await Z__default.mkdir(Y__default.dirname(n),{recursive:!0}),t==="append"?await Z__default.appendFile(n,s,"utf-8"):await Z__default.writeFile(n,s,"utf-8"),xi.set(n,{checksum:o,timestamp:a,success:!0});let c=s.split(`
803
+ `).length,u=l?"updated":"created";return JSON.stringify(z("write_file","success",`File ${u}: ${Y__default.basename(n)} (${c} lines, ${s.length} bytes)`,{file_path:n,checksum:o,verify_hint:`Use "readfile ${r}" to verify the content.`,metadata:{action:u,lines:c,bytes:s.length}}))}catch(l){return xi.set(n,{checksum:o,timestamp:a,success:false}),JSON.stringify(z("write_file","error",`Failed to write file: ${l.message}`,{file_path:n,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};function fh(r){let e=r.includes(`\r
804
804
  `)?`\r
805
805
  `:`
806
- `,t=r.endsWith(e),s=r.split(/\r?\n/);return t&&s[s.length-1]===""&&s.pop(),{lines:s,lineEnding:e,hasTrailingNewline:t}}function nc(r){let e=r.trim(),t="";for(let s of e)switch(s){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+=s;break}return t}function xo(r,e,t){if(e.length===0)return t;if(e.length>r.length)return null;let s=r.length-e.length;for(let n=t;n<=s;n+=1){let i=true;for(let o=0;o<e.length;o+=1)if(r[n+o]!==e[o]){i=false;break}if(i)return n}for(let n=t;n<=s;n+=1){let i=true;for(let o=0;o<e.length;o+=1)if(r[n+o].trimEnd()!==e[o].trimEnd()){i=false;break}if(i)return n}for(let n=t;n<=s;n+=1){let i=true;for(let o=0;o<e.length;o+=1)if(r[n+o].trim()!==e[o].trim()){i=false;break}if(i)return n}for(let n=t;n<=s;n+=1){let i=true;for(let o=0;o<e.length;o+=1)if(nc(r[n+o])!==nc(e[o])){i=false;break}if(i)return n}return null}var hh=2e5;function gh(r,e){let t=r.length,s=e.length;if(t*s>hh)return [...r.map(c=>({type:"delete",line:c})),...e.map(c=>({type:"insert",line:c}))];let i=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c-=1)for(let u=s-1;u>=0;u-=1)i[c][u]=r[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<s;){if(r[a]===e[l]){o.push({type:"equal",line:r[a]}),a+=1,l+=1;continue}i[a+1][l]>=i[a][l+1]?(o.push({type:"delete",line:r[a]}),a+=1):(o.push({type:"insert",line:e[l]}),l+=1);}for(;a<t;)o.push({type:"delete",line:r[a]}),a+=1;for(;l<s;)o.push({type:"insert",line:e[l]}),l+=1;return o}function fh(r,e){if(r.length===0&&e.length===0)return [];let t=gh(r,e),s=[],n=0,i=0,o=0;for(;o<t.length;){if(t[o].type==="equal"){n+=1,i+=1,o+=1;continue}let a=n,l=[],c=[];for(;o<t.length&&t[o].type!=="equal";){let u=t[o];u.type==="delete"?(l.push(u.line),n+=1):(c.push(u.line),i+=1),o+=1;}s.push({oldStart:a,oldLines:l,newLines:c});}return s}var yh={name:"edit_file",description:`Edit file by replacing a target block with a new block.
806
+ `,t=r.endsWith(e),s=r.split(/\r?\n/);return t&&s[s.length-1]===""&&s.pop(),{lines:s,lineEnding:e,hasTrailingNewline:t}}function ic(r){let e=r.trim(),t="";for(let s of e)switch(s){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+=s;break}return t}function Si(r,e,t){if(e.length===0)return t;if(e.length>r.length)return null;let s=r.length-e.length;for(let n=t;n<=s;n+=1){let o=true;for(let i=0;i<e.length;i+=1)if(r[n+i]!==e[i]){o=false;break}if(o)return n}for(let n=t;n<=s;n+=1){let o=true;for(let i=0;i<e.length;i+=1)if(r[n+i].trimEnd()!==e[i].trimEnd()){o=false;break}if(o)return n}for(let n=t;n<=s;n+=1){let o=true;for(let i=0;i<e.length;i+=1)if(r[n+i].trim()!==e[i].trim()){o=false;break}if(o)return n}for(let n=t;n<=s;n+=1){let o=true;for(let i=0;i<e.length;i+=1)if(ic(r[n+i])!==ic(e[i])){o=false;break}if(o)return n}return null}var yh=2e5;function bh(r,e){let t=r.length,s=e.length;if(t*s>yh)return [...r.map(c=>({type:"delete",line:c})),...e.map(c=>({type:"insert",line:c}))];let o=Array.from({length:t+1},()=>new Array(s+1).fill(0));for(let c=t-1;c>=0;c-=1)for(let u=s-1;u>=0;u-=1)o[c][u]=r[c]===e[u]?o[c+1][u+1]+1:Math.max(o[c+1][u],o[c][u+1]);let i=[],a=0,l=0;for(;a<t&&l<s;){if(r[a]===e[l]){i.push({type:"equal",line:r[a]}),a+=1,l+=1;continue}o[a+1][l]>=o[a][l+1]?(i.push({type:"delete",line:r[a]}),a+=1):(i.push({type:"insert",line:e[l]}),l+=1);}for(;a<t;)i.push({type:"delete",line:r[a]}),a+=1;for(;l<s;)i.push({type:"insert",line:e[l]}),l+=1;return i}function _h(r,e){if(r.length===0&&e.length===0)return [];let t=bh(r,e),s=[],n=0,o=0,i=0;for(;i<t.length;){if(t[i].type==="equal"){n+=1,o+=1,i+=1;continue}let a=n,l=[],c=[];for(;i<t.length&&t[i].type!=="equal";){let u=t[i];u.type==="delete"?(l.push(u.line),n+=1):(c.push(u.line),o+=1),i+=1;}s.push({oldStart:a,oldLines:l,newLines:c});}return s}var wh={name:"edit_file",description:`Edit file by replacing a target block with a new block.
807
807
  Edits apply line-level hunks (only changed lines are replaced).
808
808
  Matches are robust (exact -> trim_end -> trim -> normalize) to avoid brittle edits.
809
- 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(r){let e=r.file_path||r.path||r.filePath||r.file,t=r.old_string??r.old,s=r.new_string??r.new,n=r.replace_all??r.replaceAll??false,i=r.change_context??r.changeContext??r.context,o=Oe(e);Re(o);if(!e)return JSON.stringify(z("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(z("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(z("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await Z__default.readFile(o,"utf-8");}catch{return JSON.stringify(z("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:p}=mh(l),d=t.split(/\r?\n/),m=s.split(/\r?\n/);if(d.length===1&&d[0]==="")return JSON.stringify(z("edit_file","error","old_string cannot be empty",{file_path:o,error:"old_string cannot be empty"}));let h=0;if(i){let T=i.split(/\r?\n/),M=xo(c,T,0);if(M===null)return JSON.stringify(z("edit_file","error",`change_context not found in ${Y__default.basename(o)}`,{file_path:o,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));h=M+T.length;}let f=[],y=h;for(;y<=c.length;){let T=xo(c,d,y),M=d,B=m;if(T===null&&d.length>0&&d[d.length-1]===""){let E=d.slice(0,-1);E.length>0&&(T=xo(c,E,y),T!==null&&(M=E,B=m[m.length-1]===""?m.slice(0,-1):m));}if(T===null)break;f.push({start:T,oldLines:M,newLines:B}),y=T+M.length;}if(f.length===0)return JSON.stringify(z("edit_file","error",`Target block not found in ${Y__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 b=n?f:[f[0]],_=c.slice(),v=[];for(let T of b.slice().reverse()){let M=c.slice(T.start,T.start+T.oldLines.length),B=fh(M,T.newLines);if(B.length!==0){for(let E of B)v.push({startLine:T.start+E.oldStart+1,oldLines:E.oldLines,newLines:E.newLines});for(let E of B.slice().reverse())_.splice(T.start+E.oldStart,E.oldLines.length,...E.newLines);}}p&&(_=[..._,""]);let k=_.join(u);if(k===l)return JSON.stringify(z("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 Z__default.writeFile(o,k,"utf-8");let R=v.slice().sort((T,M)=>T.startLine-M.startLine),O=R[0],W=O?O.oldLines:[],F=O?O.newLines:[],S=O?O.startLine:1,C=_.length,w=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(z("edit_file","success",`Edited ${Y__default.basename(o)}: ${b.length} replacement(s) at line ${S}`,{file_path:o,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:b.length,start_line:S,old_lines:W.length,new_lines:F.length,total_lines:C,warning:w,hunks:R.map(T=>({old_string:T.oldLines.join(`
809
+ 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(r){let e=r.file_path||r.path||r.filePath||r.file,t=r.old_string??r.old,s=r.new_string??r.new,n=r.replace_all??r.replaceAll??false,o=r.change_context??r.changeContext??r.context,i=Oe(e);Re(i);if(!e)return JSON.stringify(z("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(z("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(z("edit_file","error","Missing required parameter: new_string",{error:"new_string is required"}));let l;try{l=await Z__default.readFile(i,"utf-8");}catch{return JSON.stringify(z("edit_file","error",`File not found: ${e}`,{file_path:i,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:p}=fh(l),d=t.split(/\r?\n/),m=s.split(/\r?\n/);if(d.length===1&&d[0]==="")return JSON.stringify(z("edit_file","error","old_string cannot be empty",{file_path:i,error:"old_string cannot be empty"}));let h=0;if(o){let T=o.split(/\r?\n/),M=Si(c,T,0);if(M===null)return JSON.stringify(z("edit_file","error",`change_context not found in ${Y__default.basename(i)}`,{file_path:i,error:"change_context not found",verify_hint:`Use "readfile ${e}" to verify the context lines.`}));h=M+T.length;}let f=[],y=h;for(;y<=c.length;){let T=Si(c,d,y),M=d,B=m;if(T===null&&d.length>0&&d[d.length-1]===""){let E=d.slice(0,-1);E.length>0&&(T=Si(c,E,y),T!==null&&(M=E,B=m[m.length-1]===""?m.slice(0,-1):m));}if(T===null)break;f.push({start:T,oldLines:M,newLines:B}),y=T+M.length;}if(f.length===0)return JSON.stringify(z("edit_file","error",`Target block not found in ${Y__default.basename(i)}`,{file_path:i,error:"old_string not found",verify_hint:`Use "readfile ${e}" and reduce old_string or provide change_context.`}));let b=n?f:[f[0]],_=c.slice(),v=[];for(let T of b.slice().reverse()){let M=c.slice(T.start,T.start+T.oldLines.length),B=_h(M,T.newLines);if(B.length!==0){for(let E of B)v.push({startLine:T.start+E.oldStart+1,oldLines:E.oldLines,newLines:E.newLines});for(let E of B.slice().reverse())_.splice(T.start+E.oldStart,E.oldLines.length,...E.newLines);}}p&&(_=[..._,""]);let k=_.join(u);if(k===l)return JSON.stringify(z("edit_file","already_done","No changes needed (content already matches)",{file_path:i,verify_hint:`Use "readfile ${e}" to verify the content if needed.`}));await Z__default.writeFile(i,k,"utf-8");let R=v.slice().sort((T,M)=>T.startLine-M.startLine),O=R[0],W=O?O.oldLines:[],F=O?O.newLines:[],S=O?O.startLine:1,C=_.length,w=!n&&f.length>1?`Found ${f.length} matches, only replaced the first one. Use replace_all=true to replace all.`:void 0;return JSON.stringify(z("edit_file","success",`Edited ${Y__default.basename(i)}: ${b.length} replacement(s) at line ${S}`,{file_path:i,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:b.length,start_line:S,old_lines:W.length,new_lines:F.length,total_lines:C,warning:w,hunks:R.map(T=>({old_string:T.oldLines.join(`
810
810
  `),new_string:T.newLines.join(`
811
811
  `),start_line:T.startLine,old_line_count:T.oldLines.length,new_line_count:T.newLines.length})),edit_info:{old_string:W.join(`
812
812
  `),new_string:F.join(`
813
- `),start_line:S,old_line_count:W.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(z("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."}))}}},bh={name:"search_files",description:`Fast file pattern matching tool (Glob).
813
+ `),start_line:S,old_line_count:W.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(z("edit_file","error",`Failed to edit file: ${c.message}`,{file_path:i,error:c.message,verify_hint:"Check file permissions or try using write_file to rewrite the entire file."}))}}},vh={name:"search_files",description:`Fast file pattern matching tool (Glob).
814
814
 
815
815
  Use this to find files by name patterns:
816
816
  - "**/*.ts" - all TypeScript files
817
817
  - "src/**/*.jsx" - JSX files in src
818
818
  - "**/test*.js" - test files anywhere
819
819
 
820
- 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:r,directory:e=".",include_hidden:t=false}){try{let s=Oe(e),n=await ic(r,{cwd:s,absolute:!1,dot:t,ignore:["**/node_modules/**","**/.git/**"]});if(n.length===0)return `\u2713 \u641C\u7D22: "${r}" \u5728 ${Re(s)}
820
+ 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:r,directory:e=".",include_hidden:t=false}){try{let s=Oe(e),n=await lc(r,{cwd:s,absolute:!1,dot:t,ignore:["**/node_modules/**","**/.git/**"]});if(n.length===0)return `\u2713 \u641C\u7D22: "${r}" \u5728 ${Re(s)}
821
821
  \u672A\u627E\u5230\u5339\u914D\u7684\u6587\u4EF6
822
822
 
823
823
  \u5EFA\u8BAE:
824
824
  - \u68C0\u67E5\u8DEF\u5F84\u662F\u5426\u6B63\u786E
825
- - \u5C1D\u8BD5\u66F4\u5BBD\u6CDB\u7684\u6A21\u5F0F: "**/*${r.replace(/\*\*/g,"").replace(/\*/g,"")}"`;n.sort();let i=[`\u2713 \u627E\u5230 ${n.length} \u4E2A\u6587\u4EF6`];i.push(`\u25B8 \u76EE\u5F55: ${Re(s)}`),i.push(`\u25B8 \u6A21\u5F0F: ${r}
826
- `);let o=50;return n.slice(0,o).forEach(l=>{i.push(` ${l}`);}),n.length>o&&i.push(`
827
- ... \u8FD8\u6709 ${n.length-o} \u4E2A\u6587\u4EF6`),i.join(`
828
- `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},_h={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:r=".",show_hidden:e=false}){try{let t=Oe(r),s=await Z__default.readdir(t,{withFileTypes:!0}),n=e?s:s.filter(l=>!l.name.startsWith(".")),i=n.filter(l=>l.isDirectory()).map(l=>l.name),o=n.filter(l=>l.isFile()).map(l=>l.name),a=[`\u2713 \u76EE\u5F55: ${Re(t)}
829
- `];if(i.length>0&&(a.push("\u5B50\u76EE\u5F55:"),i.forEach(l=>a.push(` - ${l}/`))),o.length>0){a.push(`
830
- \u6587\u4EF6:`);for(let l of o){let c=await Z__default.stat(Y__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(`
831
- `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},wh={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:r}){if(!r)return JSON.stringify(z("create_directory","error","Missing required parameter: directory",{error:"directory path is required",verify_hint:"Please provide the directory path to create."}));let e=Oe(r),t=Re(e);try{try{if((await Z__default.stat(e)).isDirectory())return JSON.stringify(z("create_directory","already_done",`Directory already exists: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${r}" to view contents.`}))}catch{}return await Z__default.mkdir(e,{recursive:!0}),JSON.stringify(z("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${r}" to verify.`}))}catch(s){return JSON.stringify(z("create_directory","error",`Failed to create directory: ${s.message}`,{file_path:e,error:s.message,verify_hint:"Check path validity and permissions."}))}}},vh={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:r,recursive:e=false,force:t=false}){if(!r)return JSON.stringify(z("delete_file","error","Missing required parameter: path",{error:"path is required"}));let s=Oe(r),n=Re(s),i=He();if(!xt(s))return JSON.stringify(z("delete_file","error","Path is \u062E\u0627\u0631\u062C workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:s,error:"Path is outside workspace",verify_hint:"Use a path within the workspace."}));if(s===i)return JSON.stringify(z("delete_file","error","Refusing to delete workspace root",{file_path:s,error:"Refusing to delete workspace root"}));try{let o=await Z__default.lstat(s).catch(()=>null);if(!o)return JSON.stringify(t?z("delete_file","already_done",`Path already removed: ${n}`,{file_path:s}):z("delete_file","error",`Path not found: ${n}`,{file_path:s,error:"Path not found"}));if(o.isDirectory()){if(!e)return JSON.stringify(z("delete_file","error",`Refusing to delete directory without recursive=true: ${n}`,{file_path:s,error:"Directory deletion requires recursive=true"}));await Z__default.rm(s,{recursive:!0,force:t});}else await Z__default.rm(s,{force:t});return JSON.stringify(z("delete_file","success",`Deleted: ${n}`,{file_path:s,verify_hint:`Use "list_directory ${Y__default.dirname(n)}" to verify.`}))}catch(o){return JSON.stringify(z("delete_file","error",`Failed to delete: ${n}`,{file_path:s,error:o.message}))}}},Th={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:r,destination_path:e,overwrite:t=false,create_dirs:s=true}){if(!r||!e)return JSON.stringify(z("rename_file","error","Missing required parameters: source_path, destination_path",{error:"source_path and destination_path are required"}));let n=Oe(r),i=Oe(e),o=Re(n),a=Re(i),l=He();if(!xt(n)||!xt(i))return JSON.stringify(z("rename_file","error","Path is outside workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:`${n} -> ${i}`,error:"Path is outside workspace"}));if(n===l||i===l)return JSON.stringify(z("rename_file","error","Refusing to rename workspace root",{file_path:n}));try{await Z__default.lstat(n);}catch{return JSON.stringify(z("rename_file","error",`Source not found: ${o}`,{file_path:n,error:"Source not found"}))}let c=await Z__default.lstat(i).catch(()=>null);if(c&&!t)return JSON.stringify(z("rename_file","error",`Destination already exists: ${a}`,{file_path:i,error:"Destination already exists"}));try{return c&&t&&await Z__default.rm(i,{recursive:!0,force:!0}),s&&await Z__default.mkdir(Y__default.dirname(i),{recursive:!0}),await Z__default.rename(n,i),JSON.stringify(z("rename_file","success",`Renamed: ${o} \u2192 ${a}`,{file_path:i,verify_hint:`Use "list_directory ${Y__default.dirname(a)}" to verify.`,metadata:{from:n,to:i}}))}catch(u){return JSON.stringify(z("rename_file","error",`Failed to rename: ${o}`,{file_path:n,error:u.message}))}}},xh={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:r,strip:e=0,reverse:t=false}){if(!r||typeof r!="string")return JSON.stringify(z("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(z("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(r,"utf8")>sc)return JSON.stringify(z("apply_patch","error",`Patch too large (max ${sc} bytes)`,{error:"Patch too large"}));let s=r.split(`
832
- `).filter(c=>c.startsWith("+++ ")||c.startsWith("--- "));for(let c of s){let u=c.slice(4).trim();if(u==="/dev/null")continue;let p=u.replace(/^a\//,"").replace(/^b\//,"");if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p))return JSON.stringify(z("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(p.split(/[\\/]+/).includes(".."))return JSON.stringify(z("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let n=He(),{repoRoot:i,error:o}=await Jt(n);if(!i)return JSON.stringify(z("apply_patch","error",`Not a git repository: ${o||"unknown error"}`,{error:"Not a git repository"}));let a=await Z__default.mkdtemp(Y__default.join(Us.tmpdir(),"neox-patch-")),l=Y__default.join(a,"apply.patch");try{await Z__default.writeFile(l,r,"utf8");let c=["apply"];e>0&&c.push(`-p${e}`),t&&c.push("--reverse");let u=await Ne("git",[...c,"--check",l],i);if(u.exitCode!==0){let d=[u.stdout,u.stderr].filter(Boolean).join(`
833
- `).trim();return JSON.stringify(z("apply_patch","error","Patch check failed",{error:d||"Patch check failed",verify_hint:"Ensure the patch applies cleanly to the current workspace state."}))}let p=await Ne("git",[...c,"--whitespace=nowarn",l],i);if(p.exitCode!==0){let d=[p.stdout,p.stderr].filter(Boolean).join(`
834
- `).trim();return JSON.stringify(z("apply_patch","error","Patch apply failed",{error:d||"Patch apply failed"}))}return JSON.stringify(z("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(z("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await Z__default.rm(a,{recursive:true,force:true}).catch(()=>{});}}},Sh=process.env.NEOX_SANDBOX==="on";var kh={name:"execute_shell",description:`Execute shell command with smart background process management.
825
+ - \u5C1D\u8BD5\u66F4\u5BBD\u6CDB\u7684\u6A21\u5F0F: "**/*${r.replace(/\*\*/g,"").replace(/\*/g,"")}"`;n.sort();let o=[`\u2713 \u627E\u5230 ${n.length} \u4E2A\u6587\u4EF6`];o.push(`\u25B8 \u76EE\u5F55: ${Re(s)}`),o.push(`\u25B8 \u6A21\u5F0F: ${r}
826
+ `);let i=50;return n.slice(0,i).forEach(l=>{o.push(` ${l}`);}),n.length>i&&o.push(`
827
+ ... \u8FD8\u6709 ${n.length-i} \u4E2A\u6587\u4EF6`),o.join(`
828
+ `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},Th={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:r=".",show_hidden:e=false}){try{let t=Oe(r),s=await Z__default.readdir(t,{withFileTypes:!0}),n=e?s:s.filter(l=>!l.name.startsWith(".")),o=n.filter(l=>l.isDirectory()).map(l=>l.name),i=n.filter(l=>l.isFile()).map(l=>l.name),a=[`\u2713 \u76EE\u5F55: ${Re(t)}
829
+ `];if(o.length>0&&(a.push("\u5B50\u76EE\u5F55:"),o.forEach(l=>a.push(` - ${l}/`))),i.length>0){a.push(`
830
+ \u6587\u4EF6:`);for(let l of i){let c=await Z__default.stat(Y__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 o.length===0&&i.length===0&&a.push("(\u7A7A\u76EE\u5F55)"),a.join(`
831
+ `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},xh={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:r}){if(!r)return JSON.stringify(z("create_directory","error","Missing required parameter: directory",{error:"directory path is required",verify_hint:"Please provide the directory path to create."}));let e=Oe(r),t=Re(e);try{try{if((await Z__default.stat(e)).isDirectory())return JSON.stringify(z("create_directory","already_done",`Directory already exists: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${r}" to view contents.`}))}catch{}return await Z__default.mkdir(e,{recursive:!0}),JSON.stringify(z("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${r}" to verify.`}))}catch(s){return JSON.stringify(z("create_directory","error",`Failed to create directory: ${s.message}`,{file_path:e,error:s.message,verify_hint:"Check path validity and permissions."}))}}},Sh={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:r,recursive:e=false,force:t=false}){if(!r)return JSON.stringify(z("delete_file","error","Missing required parameter: path",{error:"path is required"}));let s=Oe(r),n=Re(s),o=He();if(!xt(s))return JSON.stringify(z("delete_file","error","Path is \u062E\u0627\u0631\u062C workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:s,error:"Path is outside workspace",verify_hint:"Use a path within the workspace."}));if(s===o)return JSON.stringify(z("delete_file","error","Refusing to delete workspace root",{file_path:s,error:"Refusing to delete workspace root"}));try{let i=await Z__default.lstat(s).catch(()=>null);if(!i)return JSON.stringify(t?z("delete_file","already_done",`Path already removed: ${n}`,{file_path:s}):z("delete_file","error",`Path not found: ${n}`,{file_path:s,error:"Path not found"}));if(i.isDirectory()){if(!e)return JSON.stringify(z("delete_file","error",`Refusing to delete directory without recursive=true: ${n}`,{file_path:s,error:"Directory deletion requires recursive=true"}));await Z__default.rm(s,{recursive:!0,force:t});}else await Z__default.rm(s,{force:t});return JSON.stringify(z("delete_file","success",`Deleted: ${n}`,{file_path:s,verify_hint:`Use "list_directory ${Y__default.dirname(n)}" to verify.`}))}catch(i){return JSON.stringify(z("delete_file","error",`Failed to delete: ${n}`,{file_path:s,error:i.message}))}}},kh={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:r,destination_path:e,overwrite:t=false,create_dirs:s=true}){if(!r||!e)return JSON.stringify(z("rename_file","error","Missing required parameters: source_path, destination_path",{error:"source_path and destination_path are required"}));let n=Oe(r),o=Oe(e),i=Re(n),a=Re(o),l=He();if(!xt(n)||!xt(o))return JSON.stringify(z("rename_file","error","Path is outside workspace\uFF0C\u5DF2\u62D2\u7EDD",{file_path:`${n} -> ${o}`,error:"Path is outside workspace"}));if(n===l||o===l)return JSON.stringify(z("rename_file","error","Refusing to rename workspace root",{file_path:n}));try{await Z__default.lstat(n);}catch{return JSON.stringify(z("rename_file","error",`Source not found: ${i}`,{file_path:n,error:"Source not found"}))}let c=await Z__default.lstat(o).catch(()=>null);if(c&&!t)return JSON.stringify(z("rename_file","error",`Destination already exists: ${a}`,{file_path:o,error:"Destination already exists"}));try{return c&&t&&await Z__default.rm(o,{recursive:!0,force:!0}),s&&await Z__default.mkdir(Y__default.dirname(o),{recursive:!0}),await Z__default.rename(n,o),JSON.stringify(z("rename_file","success",`Renamed: ${i} \u2192 ${a}`,{file_path:o,verify_hint:`Use "list_directory ${Y__default.dirname(a)}" to verify.`,metadata:{from:n,to:o}}))}catch(u){return JSON.stringify(z("rename_file","error",`Failed to rename: ${i}`,{file_path:n,error:u.message}))}}},Ch={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:r,strip:e=0,reverse:t=false}){if(!r||typeof r!="string")return JSON.stringify(z("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(z("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(r,"utf8")>oc)return JSON.stringify(z("apply_patch","error",`Patch too large (max ${oc} bytes)`,{error:"Patch too large"}));let s=r.split(`
832
+ `).filter(c=>c.startsWith("+++ ")||c.startsWith("--- "));for(let c of s){let u=c.slice(4).trim();if(u==="/dev/null")continue;let p=u.replace(/^a\//,"").replace(/^b\//,"");if(p.startsWith("/")||/^[A-Za-z]:[\\/]/.test(p))return JSON.stringify(z("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(p.split(/[\\/]+/).includes(".."))return JSON.stringify(z("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let n=He(),{repoRoot:o,error:i}=await Kt(n);if(!o)return JSON.stringify(z("apply_patch","error",`Not a git repository: ${i||"unknown error"}`,{error:"Not a git repository"}));let a=await Z__default.mkdtemp(Y__default.join(js.tmpdir(),"neox-patch-")),l=Y__default.join(a,"apply.patch");try{await Z__default.writeFile(l,r,"utf8");let c=["apply"];e>0&&c.push(`-p${e}`),t&&c.push("--reverse");let u=await Ne("git",[...c,"--check",l],o);if(u.exitCode!==0){let d=[u.stdout,u.stderr].filter(Boolean).join(`
833
+ `).trim();return JSON.stringify(z("apply_patch","error","Patch check failed",{error:d||"Patch check failed",verify_hint:"Ensure the patch applies cleanly to the current workspace state."}))}let p=await Ne("git",[...c,"--whitespace=nowarn",l],o);if(p.exitCode!==0){let d=[p.stdout,p.stderr].filter(Boolean).join(`
834
+ `).trim();return JSON.stringify(z("apply_patch","error","Patch apply failed",{error:d||"Patch apply failed"}))}return JSON.stringify(z("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(z("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await Z__default.rm(a,{recursive:true,force:true}).catch(()=>{});}}},Rh=process.env.NEOX_SANDBOX==="on";var Eh={name:"execute_shell",description:`Execute shell command with smart background process management.
835
835
 
836
836
  \u{1F525} CRITICAL - Background Process Behavior:
837
837
  - background=true: For LONG-RUNNING processes (npm run dev, servers, watch modes)
@@ -857,9 +857,9 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
857
857
 
858
858
  \u{1F4CC} Process Management:
859
859
  - Use /processes to list all running background processes
860
- - 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. Use TRUE for: npm run dev, servers, watch modes, npm install (large projects), db migrations, docker builds. Use FALSE for: quick commands like ls, git status, cat. Default: false"}},required:["command"]},async function({command:r,background:e=false},t){if(Sh){let u=["ls","pwd","echo","cat","grep","find","wc","head","tail"],p=r.trim().split(" ")[0];if(!u.includes(p))return `\u2717 \u6C99\u7BB1\u6A21\u5F0F\uFF1A\u4E0D\u5141\u8BB8\u6267\u884C\u547D\u4EE4: ${p}
860
+ - 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. Use TRUE for: npm run dev, servers, watch modes, npm install (large projects), db migrations, docker builds. Use FALSE for: quick commands like ls, git status, cat. Default: false"}},required:["command"]},async function({command:r,background:e=false},t){if(Rh){let u=["ls","pwd","echo","cat","grep","find","wc","head","tail"],p=r.trim().split(" ")[0];if(!u.includes(p))return `\u2717 \u6C99\u7BB1\u6A21\u5F0F\uFF1A\u4E0D\u5141\u8BB8\u6267\u884C\u547D\u4EE4: ${p}
861
861
  \u5141\u8BB8\u7684\u547D\u4EE4: ${u.join(", ")}
862
- \u63D0\u793A: \u4F7F\u7528 /sandbox off \u5173\u95ED\u6C99\u7BB1\u6A21\u5F0F`}let n=He(),i=t?.signal,o=r.trim().endsWith("&"),a=r.includes("|");e&&(o||a)&&(be.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&&be.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&&be.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 c=await lh(r,e,n,i);if(c){if(c.background&&c.pid){Pe.processManager.get(c.pid)||Pe.processManager.register({pid:c.pid,command:r,cwd:n,background:true});let u=Pe.processManager.getBackgroundRunning().length;return c.output.replace(/当前后台进程总数:\s*\d+/,`\u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${u}`)}return c.output}if(e){let u=r.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,""),p=Pe.processManager.getBackgroundRunning().find(d=>d.command.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,"")===u);if(p){let d=Math.floor((Date.now()-p.startTime.getTime())/1e3),m=Pe.processManager.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
862
+ \u63D0\u793A: \u4F7F\u7528 /sandbox off \u5173\u95ED\u6C99\u7BB1\u6A21\u5F0F`}let n=He(),o=t?.signal,i=r.trim().endsWith("&"),a=r.includes("|");e&&(i||a)&&(be.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"),i&&be.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&&be.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 c=await ph(r,e,n,o);if(c){if(c.background&&c.pid){Pe.processManager.get(c.pid)||Pe.processManager.register({pid:c.pid,command:r,cwd:n,background:true});let u=Pe.processManager.getBackgroundRunning().length;return c.output.replace(/当前后台进程总数:\s*\d+/,`\u5F53\u524D\u540E\u53F0\u8FDB\u7A0B\u603B\u6570: ${u}`)}return c.output}if(e){let u=r.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,""),p=Pe.processManager.getBackgroundRunning().find(d=>d.command.trim().replace(/\s+/g," ").replace(/\s*&\s*$/,"")===u);if(p){let d=Math.floor((Date.now()-p.startTime.getTime())/1e3),m=Pe.processManager.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
863
863
  \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${n}
864
864
  \u25B8 \u6267\u884C\u547D\u4EE4: ${r}
865
865
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
@@ -878,7 +878,7 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
878
878
  - /processes - \u67E5\u770B\u6240\u6709\u540E\u53F0\u8FDB\u7A0B\u72B6\u6001
879
879
  - /kill ${p.pid} - \u7EC8\u6B62\u73B0\u6709\u8FDB\u7A0B\u540E\u91CD\u65B0\u542F\u52A8
880
880
  - lsof -i :\u7AEF\u53E3\u53F7 - \u68C0\u67E5\u7AEF\u53E3\u5360\u7528\u60C5\u51B5
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`}try{let d=execa(r,{shell:!0,cwd:n,detached:!0,stdio:["ignore","pipe","pipe"],env:Pe.shellEnv.getShellEnv()});d.unref();let m=d.pid;m&&(Pe.processManager.register({pid:m,command:r,cwd:n,background:!0,processRef:d}),d.on("exit",v=>{Pe.processManager.markCompleted(m,v??0);})),i&&m&&i.addEventListener("abort",()=>{be.info("SHELL",`\u6536\u5230\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B PID: ${m}`),Pe.processManager.killProcessGroup(m);});let h=[],f=8e3;d.stdout?.on("data",v=>{let k=v.toString();h.push(k),process.env.CLI_DEBUG==="1"&&be.debug("SHELL_STDOUT",k.trim());}),d.stderr?.on("data",v=>{let k=v.toString();h.push(k),process.env.CLI_DEBUG==="1"&&be.debug("SHELL_STDERR",k.trim());}),be.info("SHELL",`\u6B63\u5728\u6536\u96C6\u8FDB\u7A0B\u8F93\u51FA (${f/1e3}\u79D2)...`),await new Promise((v,k)=>{let R=setTimeout(v,f);i&&i.addEventListener("abort",()=>{clearTimeout(R),k(new Error("Command interrupted by user"));});});let y=h.join(""),b=y.length>3e3?y.slice(0,3e3)+`
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`}try{let d=execa(r,{shell:!0,cwd:n,detached:!0,stdio:["ignore","pipe","pipe"],env:Pe.shellEnv.getShellEnv()});d.unref();let m=d.pid;m&&(Pe.processManager.register({pid:m,command:r,cwd:n,background:!0,processRef:d}),d.on("exit",v=>{Pe.processManager.markCompleted(m,v??0);})),o&&m&&o.addEventListener("abort",()=>{be.info("SHELL",`\u6536\u5230\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u540E\u53F0\u8FDB\u7A0B PID: ${m}`),Pe.processManager.killProcessGroup(m);});let h=[],f=8e3;d.stdout?.on("data",v=>{let k=v.toString();h.push(k),process.env.CLI_DEBUG==="1"&&be.debug("SHELL_STDOUT",k.trim());}),d.stderr?.on("data",v=>{let k=v.toString();h.push(k),process.env.CLI_DEBUG==="1"&&be.debug("SHELL_STDERR",k.trim());}),be.info("SHELL",`\u6B63\u5728\u6536\u96C6\u8FDB\u7A0B\u8F93\u51FA (${f/1e3}\u79D2)...`),await new Promise((v,k)=>{let R=setTimeout(v,f);o&&o.addEventListener("abort",()=>{clearTimeout(R),k(new Error("Command interrupted by user"));});});let y=h.join(""),b=y.length>3e3?y.slice(0,3e3)+`
882
882
  ... (\u8F93\u51FA\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD)`:y,_=Pe.processManager.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
883
883
  \u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${n}
884
884
  \u25B8 \u6267\u884C\u547D\u4EE4: ${r}
@@ -913,7 +913,7 @@ ${b||"(\u6682\u65E0\u8F93\u51FA)"}
913
913
 
914
914
  \u2717 \u540E\u53F0\u542F\u52A8\u5931\u8D25:
915
915
  ${d.message}
916
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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:p,exitCode:d}=await execa(r,{shell:!0,timeout:12e4,cwd:n,reject:!1,signal:i,env:Pe.shellEnv.getShellEnv(),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
916
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\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:p,exitCode:d}=await execa(r,{shell:!0,timeout:12e4,cwd:n,reject:!1,signal:o,env:Pe.shellEnv.getShellEnv(),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
917
917
  `;return m+=`\u25B8 \u5DE5\u4F5C\u76EE\u5F55: ${n}
918
918
  `,m+=`\u25B8 \u6267\u884C\u547D\u4EE4: ${r}
919
919
  `,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
@@ -957,25 +957,25 @@ ${u.stderr?`\u25E6 \u9519\u8BEF\u4FE1\u606F:
957
957
  ${u.stderr}
958
958
 
959
959
  `:""}
960
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}},Ch={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:r=".",max_depth:e=3}){try{let t=Oe(r),s=[`${Re(t)}/
961
- `];async function n(i,o="",a=0){if(a>=e)return;let u=(await Z__default.readdir(i,{withFileTypes:!0})).filter(p=>!p.name.startsWith(".")).sort((p,d)=>p.isDirectory()&&!d.isDirectory()?-1:!p.isDirectory()&&d.isDirectory()?1:p.name.localeCompare(d.name));for(let p=0;p<u.length;p++){let d=u[p],m=p===u.length-1,h=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=m?" ":"\u2502 ";if(d.isDirectory())s.push(`${o}${h}${d.name}/`),await n(Y__default.join(i,d.name),o+f,a+1);else {let y=await Z__default.stat(Y__default.join(i,d.name)),b=y.size<1024?`${y.size}B`:y.size<1024*1024?`${(y.size/1024).toFixed(1)}KB`:`${(y.size/(1024*1024)).toFixed(1)}MB`;s.push(`${o}${h}${d.name} (${b})`);}}}return await n(t),s.join(`
962
- `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},Rh={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:r=".",short:e=true}){let t=Oe(r);if(!xt(t))return JSON.stringify(de("git_status","error","git status failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Jt(t);if(!s)return JSON.stringify(de("git_status","error",`git status failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let i=["status"];e&&i.push("-sb");let o=await Ne("git",i,s),a=[o.stdout,o.stderr].filter(Boolean).join(`
963
- `).trim();return o.exitCode!==0?JSON.stringify(de("git_status","error","git status failed",a||void 0,{error:a||"git status failed"})):JSON.stringify(de("git_status","success",a?"git status ok":"git status clean",a||"\u2713 clean"))}},Eh={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:r=".",staged:e=false,file_path:t}){let s=Oe(r);if(!xt(s))return JSON.stringify(de("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:i}=await Jt(s);if(!n)return JSON.stringify(de("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=Oe(t);if(!xt(c))return JSON.stringify(de("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let u=Y__default.relative(n,c);if(u.startsWith("..")||Y__default.isAbsolute(u))return JSON.stringify(de("git_diff","error","git diff failed: file outside repo",void 0,{error:"file outside repo"}));o.push("--",u);}let a=await Ne("git",o,n),l=[a.stdout,a.stderr].filter(Boolean).join(`
964
- `).trim();return a.exitCode!==0?JSON.stringify(de("git_diff","error","git diff failed",l||void 0,{error:l||"git diff failed"})):JSON.stringify(de("git_diff","success",l?"git diff ok":"no diff",l||""))}},Ih={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:r,start_line:e,end_line:t}){if(!r)return JSON.stringify(de("git_blame","error","git blame failed: file_path is required",void 0,{error:"file_path is required"}));let s=Oe(r);if(!xt(s))return JSON.stringify(de("git_blame","error","git blame failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:i}=await Jt(Y__default.dirname(s));if(!n)return JSON.stringify(de("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=Y__default.relative(n,s);if(a.startsWith("..")||Y__default.isAbsolute(a))return JSON.stringify(de("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 Ne("git",l,n),u=[c.stdout,c.stderr].filter(Boolean).join(`
965
- `).trim();return c.exitCode!==0?JSON.stringify(de("git_blame","error","git blame failed",u||void 0,{error:u||"git blame failed"})):JSON.stringify(de("git_blame","success","git blame ok",u||""))}},Mh={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:r=".",all:e=false}){let t=Oe(r);if(!xt(t))return JSON.stringify(de("git_branch_list","error","git branch failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Jt(t);if(!s)return JSON.stringify(de("git_branch_list","error",`git branch failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let i=["branch","--list"];e&&i.push("--all");let o=await Ne("git",i,s),a=[o.stdout,o.stderr].filter(Boolean).join(`
966
- `).trim();return o.exitCode!==0?JSON.stringify(de("git_branch_list","error","git branch failed",a||void 0,{error:a||"git branch failed"})):JSON.stringify(de("git_branch_list","success","git branches",a||""))}},Ah={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:r,checkout:e=false}){let t=He(),{repoRoot:s,error:n}=await Jt(t);if(!s)return JSON.stringify(z("git_branch","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));if(!r)return JSON.stringify(z("git_branch","error","Branch name is required (use git_branch_list to list branches)",{error:"name is required"}));let i=typeof r=="string"?r.trim():"",o=/^[A-Za-z0-9._\\/-]+$/.test(i);if(!i||!o||i.includes("..")||i.startsWith("/")||i.endsWith("/"))return JSON.stringify(z("git_branch","error","Invalid branch name",{error:"Invalid branch name"}));let l=await Ne("git",["branch",i],s);if(l.exitCode!==0){let c=[l.stdout,l.stderr].filter(Boolean).join(`
967
- `).trim();return JSON.stringify(z("git_branch","error","Failed to create branch",{error:c||"Failed to create branch"}))}if(e){let c=await Ne("git",["checkout",i],s);if(c.exitCode!==0){let u=[c.stdout,c.stderr].filter(Boolean).join(`
968
- `).trim();return JSON.stringify(z("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(z("git_branch","success",e?`Branch created and checked out: ${i}`:`Branch created: ${i}`,{metadata:{branch:i,checkout:e}}))}},Ph={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:r,add_all:e=false}){let t=He(),{repoRoot:s,error:n}=await Jt(t);if(!s)return JSON.stringify(z("git_commit","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));let i=typeof r=="string"?r.trim():"";if(!i||i.length<3)return JSON.stringify(z("git_commit","error","Commit message is too short",{error:"Commit message is too short"}));if(e){let a=await Ne("git",["add","-A"],s);if(a.exitCode!==0){let l=[a.stdout,a.stderr].filter(Boolean).join(`
969
- `).trim();return JSON.stringify(z("git_commit","error","git add -A failed",{error:l||"git add failed"}))}}let o=await Ne("git",["commit","-m",i],s);if(o.exitCode!==0){let a=[o.stdout,o.stderr].filter(Boolean).join(`
970
- `).trim();return JSON.stringify(z("git_commit","error","git commit failed",{error:a||"git commit failed"}))}return JSON.stringify(z("git_commit","success",`Commit created: ${i}`,{metadata:{message:i}}))}};async function Oh(r){let e=Z__default.stat(Y__default.join(r,"package.json")).then(()=>true).catch(()=>false),t=Z__default.stat(Y__default.join(r,"pnpm-lock.yaml")).then(()=>true).catch(()=>false),s=Z__default.stat(Y__default.join(r,"yarn.lock")).then(()=>true).catch(()=>false),n=Z__default.stat(Y__default.join(r,"bun.lockb")).then(()=>true).catch(()=>false),i=Z__default.stat(Y__default.join(r,"pyproject.toml")).then(()=>true).catch(()=>false),o=Z__default.stat(Y__default.join(r,"pytest.ini")).then(()=>true).catch(()=>false),a=Z__default.stat(Y__default.join(r,"go.mod")).then(()=>true).catch(()=>false),l=Z__default.stat(Y__default.join(r,"Cargo.toml")).then(()=>true).catch(()=>false),c=Z__default.stat(Y__default.join(r,"Makefile")).then(()=>true).catch(()=>false);return Promise.all([e,t,s,n,i,o,a,l,c]).then(([u,p,d,m,h,f,y,b,_])=>u?p?"pnpm":d?"yarn":m?"bun":"npm":h||f?"pytest":y?"go":b?"cargo":_?"make":null)}function Lh(r,e,t){switch(r){case "npm":case "pnpm":case "yarn":case "bun":return {command:r,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 Co(r,e,t){let s=Oe(t.cwd||".");if(!xt(s))return JSON.stringify(Rt(r,"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(Rt(r,"error","Invalid extra_args: expected an array of strings",{error:"extra_args must be an array"}));let n=Array.isArray(t.extra_args)?t.extra_args.map(l=>String(l)):[],i=t.preset||await Oh(s),o=t.command,a=[];if(o){let l=ph(o);if(!l.command)return JSON.stringify(Rt(r,"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(Rt(r,"error","Command not allowed",{error:`Allowed commands: ${Array.from(c).join(", ")}`}));let u=l.args.concat(n),p=await Ne(l.command,u,s,{timeoutMs:t.timeout_ms||3e5}),d=[p.stdout,p.stderr].filter(Boolean).join(`
971
- `),m=Or(d,ec),h=p.exitCode===0?`${r} succeeded (${p.durationMs}ms)`:`${r} failed with exit code ${p.exitCode}`;return JSON.stringify(Rt(r,p.exitCode===0?"success":"error",h,{error:p.exitCode===0?void 0:Or(d,tc).text,metadata:{command:[l.command,...u].join(" "),exit_code:p.exitCode,duration_ms:p.durationMs,output_truncated:m.truncated}}))}if(i){let l=Lh(i,e,n);a=l.args;let c=await Ne(l.command,a,s,{timeoutMs:t.timeout_ms||3e5}),u=[c.stdout,c.stderr].filter(Boolean).join(`
972
- `),p=Or(u,ec),d=c.exitCode===0?`${r} succeeded (${c.durationMs}ms)`:`${r} failed with exit code ${c.exitCode}`;return JSON.stringify(Rt(r,c.exitCode===0?"success":"error",d,{error:c.exitCode===0?void 0:Or(u,tc).text,metadata:{command:[l.command,...a].join(" "),exit_code:c.exitCode,duration_ms:c.durationMs,output_truncated:p.truncated}}))}return JSON.stringify(Rt(r,"error","Unable to detect project type for command",{error:"No preset detected. Provide preset."}))}var Dh={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(r){return Co("run_tests","test",r)}},$h={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(r){return Co("run_lint","lint",r)}},Nh={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(r){return Co("run_format","format",r)}},Fh={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:r}){try{let e=Oe(r),s=(await Z__default.readFile(e,"utf-8")).split(`
973
- `),n=s.length,i=s.filter(d=>d.trim()&&!d.trim().startsWith("//")).length,o=s.filter(d=>d.trim().startsWith("//")).length,a=n-i-o,l=s.filter(d=>d.trim().startsWith("import ")||d.trim().startsWith("from ")),c=s.filter(d=>d.trim().startsWith("function ")||d.trim().startsWith("async function")),u=s.filter(d=>d.trim().startsWith("class ")),p=[`\u2713 \u4EE3\u7801\u5206\u6790: ${r}
974
- `,"\u7EDF\u8BA1:",` \u603B\u884C\u6570: ${n}`,` \u4EE3\u7801\u884C: ${i}`,` \u6CE8\u91CA\u884C: ${o}`,` \u7A7A\u767D\u884C: ${a}`];return l.length>0&&(p.push(`
960
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}}},Ih={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:r=".",max_depth:e=3}){try{let t=Oe(r),s=[`${Re(t)}/
961
+ `];async function n(o,i="",a=0){if(a>=e)return;let u=(await Z__default.readdir(o,{withFileTypes:!0})).filter(p=>!p.name.startsWith(".")).sort((p,d)=>p.isDirectory()&&!d.isDirectory()?-1:!p.isDirectory()&&d.isDirectory()?1:p.name.localeCompare(d.name));for(let p=0;p<u.length;p++){let d=u[p],m=p===u.length-1,h=m?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",f=m?" ":"\u2502 ";if(d.isDirectory())s.push(`${i}${h}${d.name}/`),await n(Y__default.join(o,d.name),i+f,a+1);else {let y=await Z__default.stat(Y__default.join(o,d.name)),b=y.size<1024?`${y.size}B`:y.size<1024*1024?`${(y.size/1024).toFixed(1)}KB`:`${(y.size/(1024*1024)).toFixed(1)}MB`;s.push(`${i}${h}${d.name} (${b})`);}}}return await n(t),s.join(`
962
+ `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},Mh={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:r=".",short:e=true}){let t=Oe(r);if(!xt(t))return JSON.stringify(de("git_status","error","git status failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Kt(t);if(!s)return JSON.stringify(de("git_status","error",`git status failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let o=["status"];e&&o.push("-sb");let i=await Ne("git",o,s),a=[i.stdout,i.stderr].filter(Boolean).join(`
963
+ `).trim();return i.exitCode!==0?JSON.stringify(de("git_status","error","git status failed",a||void 0,{error:a||"git status failed"})):JSON.stringify(de("git_status","success",a?"git status ok":"git status clean",a||"\u2713 clean"))}},Ah={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:r=".",staged:e=false,file_path:t}){let s=Oe(r);if(!xt(s))return JSON.stringify(de("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:o}=await Kt(s);if(!n)return JSON.stringify(de("git_diff","error",`git diff failed: ${o||"not a git repository"}`,void 0,{error:o||"not a git repository"}));let i=["diff"];if(e&&i.push("--staged"),t){let c=Oe(t);if(!xt(c))return JSON.stringify(de("git_diff","error","git diff failed: path outside workspace",void 0,{error:"path outside workspace"}));let u=Y__default.relative(n,c);if(u.startsWith("..")||Y__default.isAbsolute(u))return JSON.stringify(de("git_diff","error","git diff failed: file outside repo",void 0,{error:"file outside repo"}));i.push("--",u);}let a=await Ne("git",i,n),l=[a.stdout,a.stderr].filter(Boolean).join(`
964
+ `).trim();return a.exitCode!==0?JSON.stringify(de("git_diff","error","git diff failed",l||void 0,{error:l||"git diff failed"})):JSON.stringify(de("git_diff","success",l?"git diff ok":"no diff",l||""))}},Ph={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:r,start_line:e,end_line:t}){if(!r)return JSON.stringify(de("git_blame","error","git blame failed: file_path is required",void 0,{error:"file_path is required"}));let s=Oe(r);if(!xt(s))return JSON.stringify(de("git_blame","error","git blame failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:n,error:o}=await Kt(Y__default.dirname(s));if(!n)return JSON.stringify(de("git_blame","error",`git blame failed: ${o||"not a git repository"}`,void 0,{error:o||"not a git repository"}));let i=e&&t?`${e},${t}`:void 0,a=Y__default.relative(n,s);if(a.startsWith("..")||Y__default.isAbsolute(a))return JSON.stringify(de("git_blame","error","git blame failed: file outside repo",void 0,{error:"file outside repo"}));let l=["blame","--",a];i&&l.splice(1,0,"-L",i);let c=await Ne("git",l,n),u=[c.stdout,c.stderr].filter(Boolean).join(`
965
+ `).trim();return c.exitCode!==0?JSON.stringify(de("git_blame","error","git blame failed",u||void 0,{error:u||"git blame failed"})):JSON.stringify(de("git_blame","success","git blame ok",u||""))}},Oh={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:r=".",all:e=false}){let t=Oe(r);if(!xt(t))return JSON.stringify(de("git_branch_list","error","git branch failed: path outside workspace",void 0,{error:"path outside workspace"}));let{repoRoot:s,error:n}=await Kt(t);if(!s)return JSON.stringify(de("git_branch_list","error",`git branch failed: ${n||"not a git repository"}`,void 0,{error:n||"not a git repository"}));let o=["branch","--list"];e&&o.push("--all");let i=await Ne("git",o,s),a=[i.stdout,i.stderr].filter(Boolean).join(`
966
+ `).trim();return i.exitCode!==0?JSON.stringify(de("git_branch_list","error","git branch failed",a||void 0,{error:a||"git branch failed"})):JSON.stringify(de("git_branch_list","success","git branches",a||""))}},Lh={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:r,checkout:e=false}){let t=He(),{repoRoot:s,error:n}=await Kt(t);if(!s)return JSON.stringify(z("git_branch","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));if(!r)return JSON.stringify(z("git_branch","error","Branch name is required (use git_branch_list to list branches)",{error:"name is required"}));let o=typeof r=="string"?r.trim():"",i=/^[A-Za-z0-9._\\/-]+$/.test(o);if(!o||!i||o.includes("..")||o.startsWith("/")||o.endsWith("/"))return JSON.stringify(z("git_branch","error","Invalid branch name",{error:"Invalid branch name"}));let l=await Ne("git",["branch",o],s);if(l.exitCode!==0){let c=[l.stdout,l.stderr].filter(Boolean).join(`
967
+ `).trim();return JSON.stringify(z("git_branch","error","Failed to create branch",{error:c||"Failed to create branch"}))}if(e){let c=await Ne("git",["checkout",o],s);if(c.exitCode!==0){let u=[c.stdout,c.stderr].filter(Boolean).join(`
968
+ `).trim();return JSON.stringify(z("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(z("git_branch","success",e?`Branch created and checked out: ${o}`:`Branch created: ${o}`,{metadata:{branch:o,checkout:e}}))}},Dh={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:r,add_all:e=false}){let t=He(),{repoRoot:s,error:n}=await Kt(t);if(!s)return JSON.stringify(z("git_commit","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));let o=typeof r=="string"?r.trim():"";if(!o||o.length<3)return JSON.stringify(z("git_commit","error","Commit message is too short",{error:"Commit message is too short"}));if(e){let a=await Ne("git",["add","-A"],s);if(a.exitCode!==0){let l=[a.stdout,a.stderr].filter(Boolean).join(`
969
+ `).trim();return JSON.stringify(z("git_commit","error","git add -A failed",{error:l||"git add failed"}))}}let i=await Ne("git",["commit","-m",o],s);if(i.exitCode!==0){let a=[i.stdout,i.stderr].filter(Boolean).join(`
970
+ `).trim();return JSON.stringify(z("git_commit","error","git commit failed",{error:a||"git commit failed"}))}return JSON.stringify(z("git_commit","success",`Commit created: ${o}`,{metadata:{message:o}}))}};async function $h(r){let e=Z__default.stat(Y__default.join(r,"package.json")).then(()=>true).catch(()=>false),t=Z__default.stat(Y__default.join(r,"pnpm-lock.yaml")).then(()=>true).catch(()=>false),s=Z__default.stat(Y__default.join(r,"yarn.lock")).then(()=>true).catch(()=>false),n=Z__default.stat(Y__default.join(r,"bun.lockb")).then(()=>true).catch(()=>false),o=Z__default.stat(Y__default.join(r,"pyproject.toml")).then(()=>true).catch(()=>false),i=Z__default.stat(Y__default.join(r,"pytest.ini")).then(()=>true).catch(()=>false),a=Z__default.stat(Y__default.join(r,"go.mod")).then(()=>true).catch(()=>false),l=Z__default.stat(Y__default.join(r,"Cargo.toml")).then(()=>true).catch(()=>false),c=Z__default.stat(Y__default.join(r,"Makefile")).then(()=>true).catch(()=>false);return Promise.all([e,t,s,n,o,i,a,l,c]).then(([u,p,d,m,h,f,y,b,_])=>u?p?"pnpm":d?"yarn":m?"bun":"npm":h||f?"pytest":y?"go":b?"cargo":_?"make":null)}function Nh(r,e,t){switch(r){case "npm":case "pnpm":case "yarn":case "bun":return {command:r,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 Ri(r,e,t){let s=Oe(t.cwd||".");if(!xt(s))return JSON.stringify(Rt(r,"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(Rt(r,"error","Invalid extra_args: expected an array of strings",{error:"extra_args must be an array"}));let n=Array.isArray(t.extra_args)?t.extra_args.map(l=>String(l)):[],o=t.preset||await $h(s),i=t.command,a=[];if(i){let l=hh(i);if(!l.command)return JSON.stringify(Rt(r,"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(Rt(r,"error","Command not allowed",{error:`Allowed commands: ${Array.from(c).join(", ")}`}));let u=l.args.concat(n),p=await Ne(l.command,u,s,{timeoutMs:t.timeout_ms||3e5}),d=[p.stdout,p.stderr].filter(Boolean).join(`
971
+ `),m=Lr(d,nc),h=p.exitCode===0?`${r} succeeded (${p.durationMs}ms)`:`${r} failed with exit code ${p.exitCode}`;return JSON.stringify(Rt(r,p.exitCode===0?"success":"error",h,{error:p.exitCode===0?void 0:Lr(d,rc).text,metadata:{command:[l.command,...u].join(" "),exit_code:p.exitCode,duration_ms:p.durationMs,output_truncated:m.truncated}}))}if(o){let l=Nh(o,e,n);a=l.args;let c=await Ne(l.command,a,s,{timeoutMs:t.timeout_ms||3e5}),u=[c.stdout,c.stderr].filter(Boolean).join(`
972
+ `),p=Lr(u,nc),d=c.exitCode===0?`${r} succeeded (${c.durationMs}ms)`:`${r} failed with exit code ${c.exitCode}`;return JSON.stringify(Rt(r,c.exitCode===0?"success":"error",d,{error:c.exitCode===0?void 0:Lr(u,rc).text,metadata:{command:[l.command,...a].join(" "),exit_code:c.exitCode,duration_ms:c.durationMs,output_truncated:p.truncated}}))}return JSON.stringify(Rt(r,"error","Unable to detect project type for command",{error:"No preset detected. Provide preset."}))}var Fh={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(r){return Ri("run_tests","test",r)}},Uh={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(r){return Ri("run_lint","lint",r)}},jh={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(r){return Ri("run_format","format",r)}},Gh={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:r}){try{let e=Oe(r),s=(await Z__default.readFile(e,"utf-8")).split(`
973
+ `),n=s.length,o=s.filter(d=>d.trim()&&!d.trim().startsWith("//")).length,i=s.filter(d=>d.trim().startsWith("//")).length,a=n-o-i,l=s.filter(d=>d.trim().startsWith("import ")||d.trim().startsWith("from ")),c=s.filter(d=>d.trim().startsWith("function ")||d.trim().startsWith("async function")),u=s.filter(d=>d.trim().startsWith("class ")),p=[`\u2713 \u4EE3\u7801\u5206\u6790: ${r}
974
+ `,"\u7EDF\u8BA1:",` \u603B\u884C\u6570: ${n}`,` \u4EE3\u7801\u884C: ${o}`,` \u6CE8\u91CA\u884C: ${i}`,` \u7A7A\u767D\u884C: ${a}`];return l.length>0&&(p.push(`
975
975
  \u5BFC\u5165 (${l.length} \u4E2A):`),l.slice(0,5).forEach(d=>p.push(` - ${d.trim()}`)),l.length>5&&p.push(` ... \u8FD8\u6709 ${l.length-5} \u4E2A\u5BFC\u5165`)),u.length>0&&(p.push(`
976
976
  \u7C7B\u5B9A\u4E49 (${u.length} \u4E2A):`),u.forEach(d=>p.push(` - ${d.trim()}`))),c.length>0&&(p.push(`
977
977
  \u51FD\u6570\u5B9A\u4E49 (${c.length} \u4E2A):`),c.slice(0,10).forEach(d=>p.push(` - ${d.trim()}`)),c.length>10&&p.push(` ... \u8FD8\u6709 ${c.length-10} \u4E2A\u51FD\u6570`)),p.join(`
978
- `)}catch(e){return `\u2717 \u5206\u6790\u5931\u8D25: ${e.message}`}}},So=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],wn=null,zt=null;async function ko(){if(zt!==null)return zt;try{let{rgPath:r}=await import('@vscode/ripgrep');return zt=r,be.info("SEARCH",`Using bundled ripgrep: ${r}`),zt}catch(r){be.warn("SEARCH",`Bundled ripgrep not available: ${r.message}`);try{if((await Ne("rg",["--version"],He(),{timeoutMs:2e3})).exitCode===0)return zt="rg",be.info("SEARCH","Using system ripgrep"),zt}catch{}}return zt=null,null}async function Uh(){return wn!==null||(wn=await ko()!==null,wn?be.info("SEARCH","ripgrep available"):be.warn("SEARCH","ripgrep not available, using fallback")),wn}function jh(r){let e=r.case_insensitive??true,t=[],s=(n,i,o)=>{if(!n.pattern||!n.pattern.trim())return;let a=(n.op||i).toLowerCase(),l=n.regex??o,c=n.case_insensitive??e;t.push({id:`q${t.length+1}`,pattern:n.pattern,op:a==="and"||a==="or"||a==="not"?a:i,regex:l,caseInsensitive:c});};if((r.pattern||r.query)&&s({pattern:r.pattern||r.query||"",op:r.op},"or",true),Array.isArray(r.keywords))for(let n of r.keywords)s({pattern:n},"or",false);if(Array.isArray(r.queries))for(let n of r.queries)s(n,"or",n.regex??true);return t}var Gh={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
978
+ `)}catch(e){return `\u2717 \u5206\u6790\u5931\u8D25: ${e.message}`}}},ki=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],vn=null,Jt=null;async function Ci(){if(Jt!==null)return Jt;try{let{rgPath:r}=await import('@vscode/ripgrep');return Jt=r,be.info("SEARCH",`Using bundled ripgrep: ${r}`),Jt}catch(r){be.warn("SEARCH",`Bundled ripgrep not available: ${r.message}`);try{if((await Ne("rg",["--version"],He(),{timeoutMs:2e3})).exitCode===0)return Jt="rg",be.info("SEARCH","Using system ripgrep"),Jt}catch{}}return Jt=null,null}async function Bh(){return vn!==null||(vn=await Ci()!==null,vn?be.info("SEARCH","ripgrep available"):be.warn("SEARCH","ripgrep not available, using fallback")),vn}function Wh(r){let e=r.case_insensitive??true,t=[],s=(n,o,i)=>{if(!n.pattern||!n.pattern.trim())return;let a=(n.op||o).toLowerCase(),l=n.regex??i,c=n.case_insensitive??e;t.push({id:`q${t.length+1}`,pattern:n.pattern,op:a==="and"||a==="or"||a==="not"?a:o,regex:l,caseInsensitive:c});};if((r.pattern||r.query)&&s({pattern:r.pattern||r.query||"",op:r.op},"or",true),Array.isArray(r.keywords))for(let n of r.keywords)s({pattern:n},"or",false);if(Array.isArray(r.queries))for(let n of r.queries)s(n,"or",n.regex??true);return t}var Hh={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
979
979
 
980
980
  \u{1F525} \u6781\u7B80\u7528\u6CD5\uFF1A
981
981
  search(pattern="\u767B\u5F55") \u2192 \u5168\u5C40\u5185\u5BB9\u641C\u7D22
@@ -991,26 +991,26 @@ search(mode="files", pattern="*.ts") \u2192 \u6587\u4EF6\u540D\u641C\u7D22
991
991
  \u8F93\u51FA\u7279\u70B9:
992
992
  - \u6BCF\u6761\u7ED3\u679C\u5E26 [\u6A21\u5757] \u524D\u7F00
993
993
  - \u663E\u793A\u6A21\u5757\u5206\u5E03\u7EDF\u8BA1
994
- - \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:r,query:e,keywords:t,queries:s,op:n,mode:i="content",path:o,recursive:a,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:p=2,max_matches:d=200,count_only:m=false},h){try{let f=Date.now();be.debug("SEARCH",`>>> searchTool.execute START, pattern=${r||e||t?.join(",")}`);let y=h?.signal,b=()=>{if(y?.aborted){let I=new Error("Operation cancelled");throw I.name="AbortError",I}},_=200,v=async()=>{await new Promise(I=>setImmediate(I));},R=Oe(o||"."),O="workspace",W=He();if(o&&Y__default.isAbsolute(o))O="absolute";else if(o&&!vn__default.existsSync(R)){let I=W,j=null;for(;;){let q=Y__default.resolve(I,o);if(vn__default.existsSync(q)){j=q;break}let ye=Y__default.dirname(I);if(ye===I)break;I=ye;}j&&(R=j,O="ancestor");}let F=Re(R);b();let S;try{S=await Z__default.stat(R);}catch(I){return JSON.stringify(de("search","error",`search failed: ${I.message}`,void 0,{error:I.message}))}let C=S.isDirectory(),w=a!==void 0?a:C,T=jh({pattern:r,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(b(),T.length===0)return JSON.stringify(de("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let M=T.filter(I=>I.op!=="not"),B=T.filter(I=>I.op==="and"),E=T.filter(I=>I.op==="or"),L=T.filter(I=>I.op==="not");if(M.length===0)return JSON.stringify(de("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let N=T.filter(I=>I.regex).map(I=>{try{return new RegExp(I.pattern),null}catch(j){return `${I.pattern}: ${j.message}`}}).filter(I=>!!I);if(N.length>0)return JSON.stringify(de("search","error",`search failed: invalid regex (${N[0]})`,void 0,{error:`Invalid regex: ${N.join("; ")}`}));let $=[];E.length>0&&$.push(E.map(I=>I.pattern).join(" OR ")),B.length>0&&$.push(`AND ${B.map(I=>I.pattern).join(" + ")}`),L.length>0&&$.push(`NOT ${L.map(I=>I.pattern).join(" + ")}`);let G=$.join(" ");be.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let X=await Uh();be.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let A=Math.min(200,Math.max(80,p*4+40));if(be.info("SEARCH",`Strategy: ${X?"ripgrep":"fallback"}`),!X)return JSON.stringify(de("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
995
- Please report this issue.`,{error:"ripgrep not available"}));if(b(),i==="files"){let I=await(async()=>{if(!C)return [Re(R)];if(X){let ce=await ko();if(!ce)throw new Error("ripgrep not available (this should not happen)");let ve=["--files"];c&&ve.push("--hidden"),!w&&C&&ve.push("--max-depth","1"),l&&ve.push("-g",l),So.forEach(nt=>ve.push("-g",nt)),ve.push("--",R);let Xe=await Ne(ce,ve,He(),{signal:y});if(Xe.exitCode!==0&&Xe.exitCode!==1)throw new Error(Xe.stderr||"rg files search failed");return Xe.stdout.split(`
996
- `).filter(Boolean).map(nt=>{let Ns=Y__default.isAbsolute(nt)?Y__default.resolve(nt):Y__default.resolve(He(),nt);return Re(Ns)})}let oe=l||"**/*",ze=w?oe:oe.replace("**/","");return (await ic(ze,{cwd:R,absolute:!0,dot:c,onlyFiles:!0,ignore:So.map(ce=>ce.replace("!",""))})).map(ce=>Re(ce))})();b();let j=T.map(oe=>{let ze=oe.regex?oe.pattern:Ql(oe.pattern),_e=oe.caseInsensitive?"i":"";return {query:oe,regex:new RegExp(ze,_e)}}),q=[],ye=0;for(let oe of I){b();let ze=oe,_e=j.map(Se=>({op:Se.query.op,hit:Se.regex.test(ze)})),ce=_e.some(Se=>Se.op==="or"&&Se.hit),ve=_e.filter(Se=>Se.op==="and").every(Se=>Se.hit);!_e.some(Se=>Se.op==="not"&&Se.hit)&&(B.length===0||ve)&&(E.length===0||ce)&&q.push(oe),ye++,ye%_===0&&await v();}let ge=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${G}`,`\u25B8 \u8DEF\u5F84: ${F}${w?" (\u9012\u5F52)":""}${O==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${q.length} \u4E2A\u6587\u4EF6`,""].filter(oe=>oe!==""),fe=50;return q.slice(0,fe).forEach(oe=>ge.push(` ${oe}`)),q.length>fe&&ge.push(` ... \u8FD8\u6709 ${q.length-fe} \u4E2A\u6587\u4EF6`),JSON.stringify(de("search","success",q.length>0?`search files "${G}" (${q.length} files)`:`search files "${G}" (no matches)`,ge.join(`
997
- `),{metadata:{mode:"files",strategy:X?"rg":"glob",regex:T.some(oe=>oe.regex),case_insensitive:u,path:F,resolved_from:O,files:q,queries:T}}))}let P=new Map,K=new Map,U=0,ne=L.map(I=>{let j=I.regex?I.pattern:Ql(I.pattern),q=I.caseInsensitive?"i":"";return new RegExp(j,q)}),Te=[];if(X){let I=await ko();if(!I)throw new Error("ripgrep not available (this should not happen)");for(let j of M){b();let q=["--json","--with-filename","--line-number","--column","-a"];q.push("-C",String(p)),j.caseInsensitive&&q.push("-i"),j.regex||q.push("-F"),c&&q.push("--hidden"),!w&&C&&q.push("--max-depth","1"),l&&q.push("-g",l),So.forEach(_e=>q.push("-g",_e)),q.push("--",j.pattern,R);let ye=`${I} ${q.join(" ")}`;Te.push(ye);let ge="",fe=0,oe="";try{let _e=await Ne(I,q,He(),{signal:y});ge=_e.stdout,oe=_e.stderr||"",fe=_e.exitCode;}catch(_e){if(_e?.name==="AbortError"||y?.aborted)throw _e;oe=_e?.message||_e?.stderr||String(_e),fe=_e?.exitCode||2;}if(fe!==0&&fe!==1){let _e=oe?`
998
- Error: ${oe}`:"",ce=`
994
+ - \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:r,query:e,keywords:t,queries:s,op:n,mode:o="content",path:i,recursive:a,file_pattern:l,include_hidden:c=false,case_insensitive:u=true,context_lines:p=2,max_matches:d=200,count_only:m=false},h){try{let f=Date.now();be.debug("SEARCH",`>>> searchTool.execute START, pattern=${r||e||t?.join(",")}`);let y=h?.signal,b=()=>{if(y?.aborted){let I=new Error("Operation cancelled");throw I.name="AbortError",I}},_=200,v=async()=>{await new Promise(I=>setImmediate(I));},R=Oe(i||"."),O="workspace",W=He();if(i&&Y__default.isAbsolute(i))O="absolute";else if(i&&!Tn__default.existsSync(R)){let I=W,j=null;for(;;){let q=Y__default.resolve(I,i);if(Tn__default.existsSync(q)){j=q;break}let ye=Y__default.dirname(I);if(ye===I)break;I=ye;}j&&(R=j,O="ancestor");}let F=Re(R);b();let S;try{S=await Z__default.stat(R);}catch(I){return JSON.stringify(de("search","error",`search failed: ${I.message}`,void 0,{error:I.message}))}let C=S.isDirectory(),w=a!==void 0?a:C,T=Wh({pattern:r,query:e,keywords:t,queries:s,op:n,case_insensitive:u});if(b(),T.length===0)return JSON.stringify(de("search","error","search failed: no query provided",void 0,{error:"Provide pattern/keywords/queries"}));let M=T.filter(I=>I.op!=="not"),B=T.filter(I=>I.op==="and"),E=T.filter(I=>I.op==="or"),L=T.filter(I=>I.op==="not");if(M.length===0)return JSON.stringify(de("search","error","search failed: only NOT queries provided",void 0,{error:"At least one non-NOT query is required"}));let N=T.filter(I=>I.regex).map(I=>{try{return new RegExp(I.pattern),null}catch(j){return `${I.pattern}: ${j.message}`}}).filter(I=>!!I);if(N.length>0)return JSON.stringify(de("search","error",`search failed: invalid regex (${N[0]})`,void 0,{error:`Invalid regex: ${N.join("; ")}`}));let $=[];E.length>0&&$.push(E.map(I=>I.pattern).join(" OR ")),B.length>0&&$.push(`AND ${B.map(I=>I.pattern).join(" + ")}`),L.length>0&&$.push(`NOT ${L.map(I=>I.pattern).join(" + ")}`);let G=$.join(" ");be.debug("SEARCH",`>>> Before isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let X=await Bh();be.debug("SEARCH",`<<< After isRipgrepAvailable, elapsed=${Date.now()-f}ms`);let A=Math.min(200,Math.max(80,p*4+40));if(be.info("SEARCH",`Strategy: ${X?"ripgrep":"fallback"}`),!X)return JSON.stringify(de("search","error","search failed: ripgrep not available",`Ripgrep is required for search. This is unexpected since ripgrep should be bundled.
995
+ Please report this issue.`,{error:"ripgrep not available"}));if(b(),o==="files"){let I=await(async()=>{if(!C)return [Re(R)];if(X){let ce=await Ci();if(!ce)throw new Error("ripgrep not available (this should not happen)");let ve=["--files"];c&&ve.push("--hidden"),!w&&C&&ve.push("--max-depth","1"),l&&ve.push("-g",l),ki.forEach(nt=>ve.push("-g",nt)),ve.push("--",R);let Xe=await Ne(ce,ve,He(),{signal:y});if(Xe.exitCode!==0&&Xe.exitCode!==1)throw new Error(Xe.stderr||"rg files search failed");return Xe.stdout.split(`
996
+ `).filter(Boolean).map(nt=>{let Fs=Y__default.isAbsolute(nt)?Y__default.resolve(nt):Y__default.resolve(He(),nt);return Re(Fs)})}let ie=l||"**/*",ze=w?ie:ie.replace("**/","");return (await lc(ze,{cwd:R,absolute:!0,dot:c,onlyFiles:!0,ignore:ki.map(ce=>ce.replace("!",""))})).map(ce=>Re(ce))})();b();let j=T.map(ie=>{let ze=ie.regex?ie.pattern:sc(ie.pattern),_e=ie.caseInsensitive?"i":"";return {query:ie,regex:new RegExp(ze,_e)}}),q=[],ye=0;for(let ie of I){b();let ze=ie,_e=j.map(Se=>({op:Se.query.op,hit:Se.regex.test(ze)})),ce=_e.some(Se=>Se.op==="or"&&Se.hit),ve=_e.filter(Se=>Se.op==="and").every(Se=>Se.hit);!_e.some(Se=>Se.op==="not"&&Se.hit)&&(B.length===0||ve)&&(E.length===0||ce)&&q.push(ie),ye++,ye%_===0&&await v();}let ge=[`\u2713 \u6587\u4EF6\u641C\u7D22: ${G}`,`\u25B8 \u8DEF\u5F84: ${F}${w?" (\u9012\u5F52)":""}${O==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",c?"\u25B8 \u5305\u542B\u9690\u85CF\u6587\u4EF6":"","",`\u627E\u5230 ${q.length} \u4E2A\u6587\u4EF6`,""].filter(ie=>ie!==""),fe=50;return q.slice(0,fe).forEach(ie=>ge.push(` ${ie}`)),q.length>fe&&ge.push(` ... \u8FD8\u6709 ${q.length-fe} \u4E2A\u6587\u4EF6`),JSON.stringify(de("search","success",q.length>0?`search files "${G}" (${q.length} files)`:`search files "${G}" (no matches)`,ge.join(`
997
+ `),{metadata:{mode:"files",strategy:X?"rg":"glob",regex:T.some(ie=>ie.regex),case_insensitive:u,path:F,resolved_from:O,files:q,queries:T}}))}let P=new Map,K=new Map,U=0,ne=L.map(I=>{let j=I.regex?I.pattern:sc(I.pattern),q=I.caseInsensitive?"i":"";return new RegExp(j,q)}),Te=[];if(X){let I=await Ci();if(!I)throw new Error("ripgrep not available (this should not happen)");for(let j of M){b();let q=["--json","--with-filename","--line-number","--column","-a"];q.push("-C",String(p)),j.caseInsensitive&&q.push("-i"),j.regex||q.push("-F"),c&&q.push("--hidden"),!w&&C&&q.push("--max-depth","1"),l&&q.push("-g",l),ki.forEach(_e=>q.push("-g",_e)),q.push("--",j.pattern,R);let ye=`${I} ${q.join(" ")}`;Te.push(ye);let ge="",fe=0,ie="";try{let _e=await Ne(I,q,He(),{signal:y});ge=_e.stdout,ie=_e.stderr||"",fe=_e.exitCode;}catch(_e){if(_e?.name==="AbortError"||y?.aborted)throw _e;ie=_e?.message||_e?.stderr||String(_e),fe=_e?.exitCode||2;}if(fe!==0&&fe!==1){let _e=ie?`
998
+ Error: ${ie}`:"",ce=`
999
999
  Command: ${I} ${q.join(" ")}`;throw new Error(`ripgrep failed (exit code ${fe})${_e}${ce}`)}let ze=0;for(let _e of ge.split(`
1000
- `)){if(b(),ze++,ze%_===0&&await v(),!_e.trim())continue;let ce;try{ce=JSON.parse(_e);}catch{continue}if(ce.type==="summary"){let ts=ce.data?.stats;ts&&typeof ts.searches=="number"&&(U=Math.max(U,ts.searches));continue}let ve=ce.type==="match",Xe=ce.type==="context";if(!ve&&!Xe)continue;let Se=ce.data,nt=Se?.path?.text,Ns=Se?.line_number,ea=Se?.lines?.text,ta=Array.isArray(Se?.submatches)?Se.submatches[0]:void 0;if(!nt||!Ns||typeof ea!="string")continue;let sa=ea.replace(/\n$/,""),li=P.get(nt)||new Map,Fs=li.get(Ns)||{line:sa,queryIds:new Set};if(Fs.line=sa,ve){Fs.queryIds.add(j.id),Fs.column===void 0&&ta?.start!==void 0&&(Fs.column=ta.start+1);let ts=K.get(nt)||new Set;ts.add(j.id),K.set(nt,ts);}li.set(Ns,Fs),P.set(nt,li);}}}let Q=new Set(B.map(I=>I.id)),ie=[],se=0,ae=0,J=0,pe=[],x=[],D=0;for(let[I,j]of P.entries()){if(b(),se>=d&&!m)break;D++,D%_===0&&await v();let q=K.get(I)||new Set,ye=!0;if(Q.forEach(ce=>{q.has(ce)||(ye=!1);}),!ye)continue;let fe=Array.from(j.keys()).sort((ce,ve)=>ce-ve).filter(ce=>{let ve=j.get(ce);return ve?!ne.some(Xe=>Xe.test(ve.line)):!1});if(fe.length===0)continue;ae++,se+=fe.length;let oe=Re(I);if(pe.push({file:oe,anchor_lines:fe.slice(0,20),num_lines:A}),m){ie.push({file:I,matches:[],matchCount:fe.length});continue}b();let ze=[];Array.from(j.keys()).sort((ce,ve)=>ce-ve).forEach(ce=>{let ve=j.get(ce);if(!ve)return;let Xe=fe.includes(ce);if(ze.push({lineNum:ce,line:ve.line,isMatch:Xe}),Xe&&x.length<d){for(let Se of ve.queryIds)if(x.push({file:oe,line:ce,column:ve.column,preview:ve.line,queryId:Se}),x.length>=d)break}}),ie.push({file:I,matches:ze,matchCount:fe.length});}ie.sort((I,j)=>Re(I.file).localeCompare(Re(j.file)));let H=I=>{let q=Re(I).split(Y__default.sep),ye=q.findIndex(ge=>["src","lib","app","core","packages"].includes(ge));return ye>=0&&ye+1<q.length?q[ye+1]:q[0]||"root"},V=[`\u2713 \u641C\u7D22: ${G}`,`\u25B8 \u8DEF\u5F84: ${F}${w?" (\u9012\u5F52)":""}${O==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",X?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",U>0?`\u6587\u4EF6: ${U} \u5DF2\u641C\u7D22, ${ae} \u6709\u5339\u914D`:`\u6587\u4EF6: ${ae} \u6709\u5339\u914D`,`\u5339\u914D: ${se}${se>=d?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(I=>I!==""),we=new Map,xe=0;for(let I of ie){xe++,xe%_===0&&await v();let j=H(I.file);we.set(j,(we.get(j)||0)+I.matchCount);}if(we.size>1){V.push(""),V.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let I=Array.from(we.entries()).sort((j,q)=>q[1]-j[1]);for(let[j,q]of I.slice(0,5))V.push(` ${j}: ${q}`);I.length>5&&V.push(` ... \u8FD8\u6709 ${I.length-5} \u4E2A\u6A21\u5757`);}if(V.push(""),m){V.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:");let I=0;for(let j of ie){I++,I%_===0&&await v();let q=Re(j.file),ye=H(j.file);V.push(` [${ye}] ${q}: ${j.matchCount}`);}}else {let I=0,j=100;for(let q of ie){if(b(),J>=d){V.push(`
1000
+ `)){if(b(),ze++,ze%_===0&&await v(),!_e.trim())continue;let ce;try{ce=JSON.parse(_e);}catch{continue}if(ce.type==="summary"){let ss=ce.data?.stats;ss&&typeof ss.searches=="number"&&(U=Math.max(U,ss.searches));continue}let ve=ce.type==="match",Xe=ce.type==="context";if(!ve&&!Xe)continue;let Se=ce.data,nt=Se?.path?.text,Fs=Se?.line_number,ta=Se?.lines?.text,sa=Array.isArray(Se?.submatches)?Se.submatches[0]:void 0;if(!nt||!Fs||typeof ta!="string")continue;let na=ta.replace(/\n$/,""),co=P.get(nt)||new Map,Us=co.get(Fs)||{line:na,queryIds:new Set};if(Us.line=na,ve){Us.queryIds.add(j.id),Us.column===void 0&&sa?.start!==void 0&&(Us.column=sa.start+1);let ss=K.get(nt)||new Set;ss.add(j.id),K.set(nt,ss);}co.set(Fs,Us),P.set(nt,co);}}}let Q=new Set(B.map(I=>I.id)),oe=[],se=0,ae=0,J=0,pe=[],x=[],D=0;for(let[I,j]of P.entries()){if(b(),se>=d&&!m)break;D++,D%_===0&&await v();let q=K.get(I)||new Set,ye=!0;if(Q.forEach(ce=>{q.has(ce)||(ye=!1);}),!ye)continue;let fe=Array.from(j.keys()).sort((ce,ve)=>ce-ve).filter(ce=>{let ve=j.get(ce);return ve?!ne.some(Xe=>Xe.test(ve.line)):!1});if(fe.length===0)continue;ae++,se+=fe.length;let ie=Re(I);if(pe.push({file:ie,anchor_lines:fe.slice(0,20),num_lines:A}),m){oe.push({file:I,matches:[],matchCount:fe.length});continue}b();let ze=[];Array.from(j.keys()).sort((ce,ve)=>ce-ve).forEach(ce=>{let ve=j.get(ce);if(!ve)return;let Xe=fe.includes(ce);if(ze.push({lineNum:ce,line:ve.line,isMatch:Xe}),Xe&&x.length<d){for(let Se of ve.queryIds)if(x.push({file:ie,line:ce,column:ve.column,preview:ve.line,queryId:Se}),x.length>=d)break}}),oe.push({file:I,matches:ze,matchCount:fe.length});}oe.sort((I,j)=>Re(I.file).localeCompare(Re(j.file)));let H=I=>{let q=Re(I).split(Y__default.sep),ye=q.findIndex(ge=>["src","lib","app","core","packages"].includes(ge));return ye>=0&&ye+1<q.length?q[ye+1]:q[0]||"root"},V=[`\u2713 \u641C\u7D22: ${G}`,`\u25B8 \u8DEF\u5F84: ${F}${w?" (\u9012\u5F52)":""}${O==="ancestor"?" (auto-resolved)":""}`,l?`\u25B8 \u6587\u4EF6\u8FC7\u6EE4: ${l}`:"",u?"\u25B8 \u6A21\u5F0F: \u5FFD\u7565\u5927\u5C0F\u5199":"",X?"\u25B8 \u7B56\u7565: ripgrep":"\u25B8 \u7B56\u7565: fallback","","\u2501\u2501\u2501\u2501 \u7ED3\u679C\u6458\u8981 \u2501\u2501\u2501\u2501",U>0?`\u6587\u4EF6: ${U} \u5DF2\u641C\u7D22, ${ae} \u6709\u5339\u914D`:`\u6587\u4EF6: ${ae} \u6709\u5339\u914D`,`\u5339\u914D: ${se}${se>=d?" (\u5DF2\u8FBE\u4E0A\u9650)":""}`].filter(I=>I!==""),we=new Map,xe=0;for(let I of oe){xe++,xe%_===0&&await v();let j=H(I.file);we.set(j,(we.get(j)||0)+I.matchCount);}if(we.size>1){V.push(""),V.push("\u{1F4E6} \u6A21\u5757\u5206\u5E03:");let I=Array.from(we.entries()).sort((j,q)=>q[1]-j[1]);for(let[j,q]of I.slice(0,5))V.push(` ${j}: ${q}`);I.length>5&&V.push(` ... \u8FD8\u6709 ${I.length-5} \u4E2A\u6A21\u5757`);}if(V.push(""),m){V.push("\u{1F4CB} \u6587\u4EF6\u5217\u8868:");let I=0;for(let j of oe){I++,I%_===0&&await v();let q=Re(j.file),ye=H(j.file);V.push(` [${ye}] ${q}: ${j.matchCount}`);}}else {let I=0,j=100;for(let q of oe){if(b(),J>=d){V.push(`
1001
1001
  ... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${d} \u4E0A\u9650)`);break}let ye=Re(q.file),ge=H(q.file);V.push(`
1002
- \u25B8 [${ge}] ${ye} (${q.matchCount} \u5904)`),V.push("\u2500".repeat(50));let fe=-10;for(let oe of q.matches){if(J>=d)break;I++,I%j===0&&await v(),oe.lineNum>fe+1&&fe>0&&V.push(" \u2504\u2504\u2504");let ze=oe.isMatch?"\u25B6":" ";V.push(`${ze}${String(oe.lineNum).padStart(5)} \u2502 ${oe.line}`),fe=oe.lineNum,oe.isMatch&&J++;}}}return ie.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"')):pe.length>0&&(V.push(""),V.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),pe.slice(0,3).forEach(I=>{V.push(` readfile(path="${I.file}", anchor_lines=[${I.anchor_lines.join(",")}], num_lines=${I.num_lines})`);})),JSON.stringify(de("search","success",ie.length>0?`search "${G}" (${se} matches)`:`search "${G}" (no matches)`,V.join(`
1003
- `),{metadata:{mode:"content",strategy:X?"rg":"fallback",regex:T.some(I=>I.regex),case_insensitive:u,path:F,resolved_from:O,queries:T,matches:x,read_hints:pe,files_with_matches:ae,command:Te.length>0?Te[0]:void 0}}))}catch(f){return JSON.stringify(de("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},Bh={name:Pr.name,description:Pr.description,parameters:Pr.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return Xl(r)}},ac=[dh,yh,vh,Th,xh,bh,_h,wh,Rh,Eh,Ih,Mh,Ah,Ph,Dh,$h,Nh,kh,Ch,Ca,Fh,Gh,_i,wi,vi,La,Bh];async function Ro(r,e){e&&oc(e);let t=e?.capabilities??Pe.capabilities,s=zs(),n=[...ac];if(r&&n.push(Da(r)),s.webSearch?.enabled&&n.push(Di),s.javaDebug?.enabled)try{let c=await Ui(s.javaDebug?.jarPath);n.push(...c),be.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){be.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`),be.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(s.smartRead?.enabled!==false)try{let c=fo(r);n.push(...c),be.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){be.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`);}let i=typeof process<"u"&&process.type==="renderer";t?.terminal&&i&&n.push(...er()),t?.editor&&i&&n.push(...tr());let o=ih(n,t),a=s.enabledTools||{};return o.filter(c=>a[c.name]!==false)}function Lr(r){return {output_info:r,behavior:{type:"allow"}}}function lc(r,e){return {output_info:e,behavior:{type:"reject_content",message:r}}}function Wh(r){let e=r.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=r.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function Hh(r){let e=r.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=r.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let s=r.match(/Error\s+code\s+(\d{3})/i);if(s){let i=s[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 n=r.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return n?n[1].trim():null}function qh(r){let e=r.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=r.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function Tn(r){return r.trim().startsWith("<!DOCTYPE html")||r.trim().startsWith("<html")||/<html[^>]*>/i.test(r)}function zh(r){let e=r.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Kt(r,e){let t=zh(r);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 p=a.resets_at?new Date(a.resets_at*1e3).toLocaleString():void 0,d=a.resets_in_seconds;if(d){let m=Math.floor(d/3600),h=Math.floor(d%3600/60);u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets in ${m}h ${h}m.`;}else p&&(u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets at ${p}.`);}return {code:l,message:c,detail:u}}}catch{}if(r.trim().startsWith("{"))try{let o=JSON.parse(r);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(Tn(r)){let o=Wh(r)||String(e||"UNKNOWN"),a=Hh(r)||"Server error",l=qh(r),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 s=r.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(s){let o=s[1],a=s[2];if(Tn(a)){let l=Kt(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 n=r.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let o=n[1],a=n[2].trim();return a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${o}`,message:a}}if(r.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(r.includes("ETIMEDOUT")||r.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(r.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(r)||/maximum.*context.*length/i.test(r))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(r)||r.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(r.includes("401")||/unauthorized/i.test(r))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(r.includes("403")||/forbidden/i.test(r))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let i=r;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 me=class r 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,r);}withContext(e){return new r({...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 St(r){if(!r)return;if(typeof r!="string")return typeof r=="number"&&r>0?Math.ceil(r*1e3):void 0;let e=r.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 s=parseFloat(e);if(!isNaN(s)&&s>0)return Math.ceil(s*1e3);let n=new Date(e);if(!isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}function Jh(r){switch(r){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function Dr(r){if(!r)return;let e=r["retry-after"]||r["Retry-After"];if(e){let i=St(e);if(i)return i}let t=r["retry-after-ms"]||r["Retry-After-Ms"];if(t){let i=parseFloat(t);if(!isNaN(i)&&i>0)return Math.ceil(i)}let s=r["x-ratelimit-reset-requests"];if(s){let i=St(s);if(i)return i}let n=r["anthropic-ratelimit-requests-reset"];if(n){let i=new Date(n);if(!isNaN(i.getTime())){let o=i.getTime()-Date.now();return o>0?Math.ceil(o):void 0}}}function Eo(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function cc(r){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(r))}function Kh(r){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(r))}function Vh(r){if(r){if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.error=="string")return r.error;if(r.error?.message)return r.error.message;if(r.message)return r.message}}}function tt(r){if(r instanceof me)return r;let e=r instanceof Error?r.message:String(r),t=r instanceof Error?r:void 0,s=Eo(r)?r:void 0,i=(s?Vh(s.response?.data):void 0)||e;if(s?.response?.status){let o=s.response.status,a=Dr(s.response.headers),l=s.response.headers?.["x-request-id"]||s.response.headers?.["cf-ray"];if(o===429){let c=s.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new me({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:o,requestId:l},originalError:t}):new me({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(Tn(i)){let p=Kt(i,o);c=p.message,p.detail&&(c+=`
1004
- `+p.detail);}let u=a||Jh(o);return new me({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(Tn(i)){let u=Kt(i,o);c=u.message,u.detail&&(c+=`
1005
- `+u.detail);}return new me({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 me({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 me({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 cc(e)?new me({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 me({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:i||"Proxy upstream request failed",retryable:true,context:{httpStatus:o,requestId:l},originalError:t}):new me({category:"fatal_invalid",code:"INVALID_REQUEST",message:i,retryable:false,context:{httpStatus:o,requestId:l},originalError:t});if(o>=400&&o<500)return new me({category:"fatal_invalid",code:`HTTP_${o}`,message:i,retryable:false,context:{httpStatus:o,requestId:l},originalError:t})}if(Eo(r)){let o=r.code,a=r.name;if(o==="ERR_CANCELED"||a==="CanceledError"||a==="AbortError")return new me({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ECONNRESET")return new me({category:"retryable_network",code:o,message:`Network error: ${e}`,retryable:true,originalError:t});if(o==="ETIMEDOUT"||o==="ESOCKETTIMEDOUT")return new me({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return r instanceof Error&&r.name==="AbortError"?new me({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:r}):Eo(r)&&r.code==="STREAM_INCOMPLETE"?new me({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:r.toolName,rawMessage:e},originalError:t}):r?.code==="STREAM_TIMEOUT"?new me({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 me({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):cc(e)?new me({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):Kh(e)?new me({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new me({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function uc(r,e,t){let s=e||"";return s.trim().endsWith("}")?(r==="write_file"||r==="edit_file")&&!s.includes('"content"')?new me({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new me({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t}):new me({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:r},originalError:t}):new me({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t})}function $r(r){switch(r.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${r.retryAfter?Math.ceil(r.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 kt={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function Lt(r,e){return {...kt,...r,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var Ot={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 Cs(r,e){let t=r.toLowerCase();if(t.includes("yunwu"))return Ot.yunwu;if(t.includes("azure"))return Ot.azure;if(e){let s=e.toLowerCase();if(s.includes("yunwu"))return Ot.yunwu;if(s.includes("azure"))return Ot.azure;if(!(s.includes("api.anthropic.com")||s.includes("api.openai.com")))return Ot.proxy}return t.includes("anthropic")?Ot.anthropic:t.includes("gemini")?Ot.gemini:Ot.openai}var pc=100,dc=200,mc=1800*1e3;var xn=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},Rs=class extends xn{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}}},Es=class extends xn{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}}},st=class extends xn{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 Vt=class{static async runInputGuardrails(e,t,s,n){if(e.length===0)return [];let i=e.map(async o=>{let a=Date.now();try{let l=await o.guardrail_function(t,s,n),c={guardrail:o,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Rs(c);return c}catch(l){if(l instanceof Rs)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 Rs(c)}});return await Promise.all(i)}static async runOutputGuardrails(e,t,s,n){if(e.length===0)return [];let i=e.map(async o=>{let a=Date.now();try{let l=await o.guardrail_function(t,s,n),c={guardrail:o,agent_output:n,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Es(c);return c}catch(l){if(l instanceof Es)throw l;let c={guardrail:o,agent_output:n,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 Es(c)}});return await Promise.all(i)}static async runToolInputGuardrails(e,t){let s=[];for(let n of e){let i=Date.now();try{let o=await n.guardrail_function(t),a={guardrail:n,output:o,execution_time_ms:Date.now()-i};if(s.push(a),o.behavior.type==="raise_exception")throw new st(a);if(o.behavior.type==="reject_content")return {results:s,should_execute:!1,rejection_message:o.behavior.message}}catch(o){if(o instanceof st)throw o;let a={guardrail:n,output:{output_info:{error:o instanceof Error?o.message:String(o)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-i};throw new st(a)}}return {results:s,should_execute:true}}static async runToolOutputGuardrails(e,t){let s=[];for(let n of e){let i=Date.now();try{let o=await n.guardrail_function(t),a={guardrail:n,output:o,execution_time_ms:Date.now()-i};if(s.push(a),o.behavior.type==="raise_exception")throw new st(a);if(o.behavior.type==="reject_content")return {results:s,should_use_output:!1,replacement_message:o.behavior.message}}catch(o){if(o instanceof st)throw o;let a={guardrail:n,output:{output_info:{error:o instanceof Error?o.message:String(o)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-i};throw new st(a)}}return {results:s,should_use_output:true}}};var hc=null,gc=false;function Sn(){if(!gc&&(gc=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(le(),jn)).then(r=>{hc=r.cliLogger;}).catch(()=>{});}catch{}return hc}var fc=new WeakMap,Io=null;function yc(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function bc(r){if(r){let e=fc.get(r);return e?process.env.CLI_DEBUG==="1"&&Sn()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(r).join(",")}, history: ${e.toolCallHistory.length}`):(e=yc(),fc.set(r,e),process.env.CLI_DEBUG==="1"&&Sn()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(r).join(",")}`)),e}return Io||(Io=yc()),Io}function Mo(r,e,t,s){let n=bc(r);if(process.env.CLI_DEBUG==="1"){let i=Sn();i?.debug("SESSION","recordToolCall called:"),i?.debug("SESSION",` - tool: ${e}`),i?.debug("SESSION",` - success: ${s}`),i?.debug("SESSION",` - context exists: ${!!r}`),i?.debug("SESSION",` - context identity: ${r?Object.keys(r).join(","):"none"}`),i?.debug("SESSION",` - history length before: ${n.toolCallHistory.length}`);}n.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:s}),process.env.CLI_DEBUG==="1"&&Sn()?.debug("SESSION",` - history length after: ${n.toolCallHistory.length}`),n.toolCallHistory.length>100&&n.toolCallHistory.shift();}function _c(r,e=10){let t=bc(r);if(process.env.CLI_DEBUG==="1"){let s=Sn();s?.debug("SESSION","getRecentToolCalls called:"),s?.debug("SESSION",` - context exists: ${!!r}`),s?.debug("SESSION",` - context identity: ${r?Object.keys(r).join(","):"none"}`),s?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),s?.debug("SESSION",` - limit: ${e}`),s?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var eg=fileURLToPath(import.meta.url),Oo=dirname(eg),Lo=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(Oo.includes(".asar")||Oo.includes("app.asar")){try{let{app:e}=xc();if(e&&e.getPath){let t=e.getPath("userData");return Y__default.join(t,"logs")}}catch{}return Y__default.join(Us.tmpdir(),"neox-logs")}return Y__default.join(Oo,"../../logs")}initLogDir(){try{vn__default.existsSync(this.logDir)||vn__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 Y__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let s=new Date().toISOString(),n=typeof t=="string"?{message:t}:t||{},i=this.safeStringify({timestamp:s,...n})+`
1006
- `;if(this.enabled)try{let o=this.getLogFile(e);vn__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,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n})}llmRequest(e,t,s,n,i){let o=s.tools?.map(a=>({name:a.name,description:a.description,parameters:a.parameters}));this.write("llm",{type:"REQUEST",provider:e,model:t,url:n,headers:i,messagesCount:s.messages?.length||0,messages:s.messages,toolsCount:s.tools?.length||0,tools:o,temperature:s.temperature});}llmResponse(e,t,s,n){this.write("llm",{type:"RESPONSE",provider:e,duration:`${t}ms`,usage:s,finishReason:n.finish_reason,content:n.content,contentLength:n.content?.length||0,toolCallsCount:n.tool_calls?.length||0,toolCalls:n.tool_calls});}llmError(e,t){let s={type:"ERROR",provider:e,error:t.message,status:t.response?.status};if(t.response?.data)try{let n=t.response.data;typeof n=="string"?s.data=n:typeof n=="object"&&(s.data={error:n.error,message:n.message,type:n.type,code:n.code});}catch{s.data="[Could not serialize response data]";}this.write("llm",s);}agentStart(e){this.write("agent",{type:"START",task:e});}agentIteration(e,t){this.write("agent",{type:"ITERATION",iteration:e,action:t});}agentComplete(e,t,s){this.write("agent",{type:"COMPLETE",iterations:e,toolCalls:t,usage:s});}agentError(e){this.write("agent",{type:"ERROR",error:e});}toolCall(e,t){this.write("tool",{type:"CALL",tool:e,args:t});}toolResult(e,t,s,n){this.write("tool",{type:"RESULT",tool:e,success:t,resultLength:s,duration:`${n}ms`});}toolError(e,t){this.write("tool",{type:"ERROR",tool:e,error:t});}},te=new Lo;function Sc(r,e){let t=r||"Unknown error",s=t.toLowerCase(),n=e?.providerName?.trim()||"LLM";if(s.includes("timeout")){let i=Math.round((e?.timeoutMs??12e4)/1e3);return [`\u23F1\uFE0F ${n} \u8BF7\u6C42\u8D85\u65F6 (${i}s)\u3002${n} \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(`
1007
- `)}return t}var sg=new tg({allErrors:true,strict:false});function ng(r){let e=(r||"").trim();if(e.startsWith("```")){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t&&t[1])return t[1].trim()}return e}function rg(r){return !r||r.length===0?[]:r.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 Fr=class{constructor(e){this.definition=e;this.validateFn=sg.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(`
1008
-
1009
- `)}validate(e){let t=ng(e||"");if(!t)return {ok:false,reason:"empty_output",message:"The model returned an empty response."};let s;try{s=JSON.parse(t);}catch(i){return {ok:false,reason:"parse_error",message:i?.message||"Failed to parse JSON output."}}return this.validateFn(s)?{ok:true,parsed:s,normalized:JSON.stringify(s,null,2)}:{ok:false,reason:"schema_mismatch",message:"Response does not match the required JSON schema.",errors:rg(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:
1002
+ \u25B8 [${ge}] ${ye} (${q.matchCount} \u5904)`),V.push("\u2500".repeat(50));let fe=-10;for(let ie of q.matches){if(J>=d)break;I++,I%j===0&&await v(),ie.lineNum>fe+1&&fe>0&&V.push(" \u2504\u2504\u2504");let ze=ie.isMatch?"\u25B6":" ";V.push(`${ze}${String(ie.lineNum).padStart(5)} \u2502 ${ie.line}`),fe=ie.lineNum,ie.isMatch&&J++;}}}return oe.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"')):pe.length>0&&(V.push(""),V.push("\u{1F4A1} \u6279\u91CF\u8BFB\u53D6:"),pe.slice(0,3).forEach(I=>{V.push(` readfile(path="${I.file}", anchor_lines=[${I.anchor_lines.join(",")}], num_lines=${I.num_lines})`);})),JSON.stringify(de("search","success",oe.length>0?`search "${G}" (${se} matches)`:`search "${G}" (no matches)`,V.join(`
1003
+ `),{metadata:{mode:"content",strategy:X?"rg":"fallback",regex:T.some(I=>I.regex),case_insensitive:u,path:F,resolved_from:O,queries:T,matches:x,read_hints:pe,files_with_matches:ae,command:Te.length>0?Te[0]:void 0}}))}catch(f){return JSON.stringify(de("search","error",`search failed: ${f.message}`,void 0,{error:f.message}))}}},qh={name:Or.name,description:Or.description,parameters:Or.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return ec(r)}},uc=[gh,wh,Sh,kh,Ch,vh,Th,xh,Mh,Ah,Ph,Oh,Lh,Dh,Fh,Uh,jh,Eh,Ih,Ia,Gh,Hh,vo,To,xo,Na,qh];async function Ei(r,e){e&&cc(e);let t=e?.capabilities??Pe.capabilities,s=Js(),n=[...uc];if(r&&n.push(Fa(r)),s.webSearch?.enabled&&n.push(No),s.javaDebug?.enabled)try{let c=await Go(s.javaDebug?.jarPath);n.push(...c),be.info("TOOLS",`Java Debug \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){be.error("TOOLS",`Java Debug \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`),be.error("TOOLS","\u63D0\u793A: \u8FD0\u884C npm run setup-java-debug \u81EA\u52A8\u4E0B\u8F7D JAR \u6587\u4EF6");}if(s.smartRead?.enabled!==false)try{let c=yi(r);n.push(...c),be.info("TOOLS",`readfile \u5DE5\u5177\u5DF2\u542F\u7528 (${c.length} \u4E2A\u5DE5\u5177)`);}catch(c){be.error("TOOLS",`readfile \u5DE5\u5177\u52A0\u8F7D\u5931\u8D25: ${c.message}`);}let o=typeof process<"u"&&process.type==="renderer";t?.terminal&&o&&n.push(...tr()),t?.editor&&o&&n.push(...sr());let i=lh(n,t),a=s.enabledTools||{};return i.filter(c=>a[c.name]!==false)}function Dr(r){return {output_info:r,behavior:{type:"allow"}}}function pc(r,e){return {output_info:e,behavior:{type:"reject_content",message:r}}}function zh(r){let e=r.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=r.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function Jh(r){let e=r.match(/<title>[^|]*\|\s*\d{3}:\s*([^<]+)<\/title>/i);if(e)return e[1].trim();let t=r.match(/<h1[^>]*>(?:<[^>]+>)*([^<]+?(?:\s+\d{3})?)<\/(?:[^>]+>)*<\/h1>/i);if(t)return t[1].replace(/Error code\s+\d{3}/i,"").trim();let s=r.match(/Error\s+code\s+(\d{3})/i);if(s){let o=s[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"}[o]||"Server error"}let n=r.match(/<span[^>]*class="inline-block"[^>]*>([^<]+)<\/span>/i);return n?n[1].trim():null}function Kh(r){let e=r.match(/truncate[^>]*>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})<\/span>/);if(e)return e[1];let t=r.match(/<title>([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]:null}function xn(r){return r.trim().startsWith("<!DOCTYPE html")||r.trim().startsWith("<html")||/<html[^>]*>/i.test(r)}function Vh(r){let e=r.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Vt(r,e){let t=Vh(r);if(t)try{let i=JSON.parse(t);if(i.error){let a=i.error,l=a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),c=a.message||"API error",u;if(a.type==="usage_limit_reached"){let p=a.resets_at?new Date(a.resets_at*1e3).toLocaleString():void 0,d=a.resets_in_seconds;if(d){let m=Math.floor(d/3600),h=Math.floor(d%3600/60);u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets in ${m}h ${h}m.`;}else p&&(u=`Usage limit reached (${a.plan_type||"unknown"} plan). Resets at ${p}.`);}return {code:l,message:c,detail:u}}}catch{}if(r.trim().startsWith("{"))try{let i=JSON.parse(r);if(i.error){let a=i.error;return {code:a.type||a.code||(e?`HTTP_${e}`:"API_ERROR"),message:a.message||"API error"}}}catch{}if(xn(r)){let i=zh(r)||String(e||"UNKNOWN"),a=Jh(r)||"Server error",l=Kh(r),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_${i}`,message:a,detail:c}}let s=r.match(/OpenAI.*error:\s*(\d+)\s*-\s*(.*)/i);if(s){let i=s[1],a=s[2];if(xn(a)){let l=Vt(a,parseInt(i,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_${i}`,message:a}}let n=r.match(/Anthropic.*error:\s*(\d+)\s*-\s*(.*)/i);if(n){let i=n[1],a=n[2].trim();return a.length>200&&(a=a.slice(0,200)+"..."),{code:`HTTP_${i}`,message:a}}if(r.includes("ECONNREFUSED"))return {code:"NETWORK_ERROR",message:"Connection refused",detail:"Unable to connect to the API server. Please check your network connection."};if(r.includes("ETIMEDOUT")||r.includes("timeout"))return {code:"TIMEOUT",message:"Connection timeout",detail:"The request took too long to complete. Please try again."};if(r.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(r)||/maximum.*context.*length/i.test(r))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(r)||r.includes("429"))return {code:"RATE_LIMIT",message:"Rate limit exceeded",detail:"Too many requests. Please wait a moment before trying again."};if(r.includes("401")||/unauthorized/i.test(r))return {code:"AUTH_ERROR",message:"Authentication failed",detail:"Please check your API key in settings."};if(r.includes("403")||/forbidden/i.test(r))return {code:"FORBIDDEN",message:"Access denied",detail:"Your API key does not have permission for this operation."};let o=r;return o=o.replace(/^Error:\s*/i,""),o=o.replace(/^Request failed with status code\s+\d+:\s*/i,""),o.length>300&&(o=o.slice(0,300)+"..."),{code:e?`HTTP_${e}`:"UNKNOWN",message:o}}var me=class r 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,r);}withContext(e){return new r({...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 St(r){if(!r)return;if(typeof r!="string")return typeof r=="number"&&r>0?Math.ceil(r*1e3):void 0;let e=r.trim(),t=e.match(/^(\d+(?:\.\d+)?)\s*ms$/i);if(t){let o=parseFloat(t[1]);return o>0?Math.ceil(o):void 0}let s=parseFloat(e);if(!isNaN(s)&&s>0)return Math.ceil(s*1e3);let n=new Date(e);if(!isNaN(n.getTime())){let o=n.getTime()-Date.now();return o>0?Math.ceil(o):void 0}}function Yh(r){switch(r){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function $r(r){if(!r)return;let e=r["retry-after"]||r["Retry-After"];if(e){let o=St(e);if(o)return o}let t=r["retry-after-ms"]||r["Retry-After-Ms"];if(t){let o=parseFloat(t);if(!isNaN(o)&&o>0)return Math.ceil(o)}let s=r["x-ratelimit-reset-requests"];if(s){let o=St(s);if(o)return o}let n=r["anthropic-ratelimit-requests-reset"];if(n){let o=new Date(n);if(!isNaN(o.getTime())){let i=o.getTime()-Date.now();return i>0?Math.ceil(i):void 0}}}function Ii(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function dc(r){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(r))}function Xh(r){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(r))}function Zh(r){if(r){if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.error=="string")return r.error;if(r.error?.message)return r.error.message;if(r.message)return r.message}}}function tt(r){if(r instanceof me)return r;let e=r instanceof Error?r.message:String(r),t=r instanceof Error?r:void 0,s=Ii(r)?r:void 0,o=(s?Zh(s.response?.data):void 0)||e;if(s?.response?.status){let i=s.response.status,a=$r(s.response.headers),l=s.response.headers?.["x-request-id"]||s.response.headers?.["cf-ray"];if(i===429){let c=s.response.data,u=c?.error?.type;return u==="usage_limit_reached"||u==="usage_not_included"?new me({category:"fatal_limit",code:"USAGE_LIMIT_REACHED",message:c?.error?.message||"Usage limit reached",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):new me({category:"retryable_http",code:`HTTP_${i}`,message:o,retryable:true,retryAfter:a,context:{httpStatus:i,requestId:l},originalError:t})}if(i===502||i===503||i===504){let c=o;if(xn(o)){let p=Vt(o,i);c=p.message,p.detail&&(c+=`
1004
+ `+p.detail);}let u=a||Yh(i);return new me({category:"retryable_rate_limit",code:`PROXY_${i}`,message:c||`API \u4EE3\u7406\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528 (${i})`,retryable:true,retryAfter:u,context:{httpStatus:i,requestId:l,rawMessage:o},originalError:t})}if(i>=500){let c=o;if(xn(o)){let u=Vt(o,i);c=u.message,u.detail&&(c+=`
1005
+ `+u.detail);}return new me({category:"retryable_http",code:`HTTP_${i}`,message:c,retryable:true,retryAfter:a,context:{httpStatus:i,requestId:l,rawMessage:o},originalError:t})}if(i===401)return new me({category:"fatal_auth",code:"UNAUTHORIZED",message:o||"Authentication failed. Please check your API key.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===403)return new me({category:"fatal_auth",code:"FORBIDDEN",message:o||"Access denied. Please check your API permissions.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i===400)return dc(e)?new me({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,context:{httpStatus:i,requestId:l},originalError:t}):o.includes("Upstream request failed")||o.includes("upstream")||o.includes("gateway")?new me({category:"retryable_http",code:"PROXY_UPSTREAM_FAILED",message:o||"Proxy upstream request failed",retryable:true,context:{httpStatus:i,requestId:l},originalError:t}):new me({category:"fatal_invalid",code:"INVALID_REQUEST",message:o,retryable:false,context:{httpStatus:i,requestId:l},originalError:t});if(i>=400&&i<500)return new me({category:"fatal_invalid",code:`HTTP_${i}`,message:o,retryable:false,context:{httpStatus:i,requestId:l},originalError:t})}if(Ii(r)){let i=r.code,a=r.name;if(i==="ERR_CANCELED"||a==="CanceledError"||a==="AbortError")return new me({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:t});if(i==="ECONNREFUSED"||i==="ENOTFOUND"||i==="ECONNRESET")return new me({category:"retryable_network",code:i,message:`Network error: ${e}`,retryable:true,originalError:t});if(i==="ETIMEDOUT"||i==="ESOCKETTIMEDOUT")return new me({category:"retryable_network",code:"TIMEOUT",message:`Connection timeout: ${e}`,retryable:true,originalError:t})}return r instanceof Error&&r.name==="AbortError"?new me({category:"canceled",code:"CANCELED",message:"Request was canceled",retryable:false,originalError:r}):Ii(r)&&r.code==="STREAM_INCOMPLETE"?new me({category:"retryable_stream",code:"STREAM_INCOMPLETE",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,context:{toolName:r.toolName,rawMessage:e},originalError:t}):r?.code==="STREAM_TIMEOUT"?new me({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 me({category:"retryable_stream",code:"STREAM_ERROR",message:`\u7F51\u7EDC\u4E2D\u65AD: ${e}`,retryable:true,originalError:t}):dc(e)?new me({category:"fatal_context",code:"CONTEXT_WINDOW_EXCEEDED",message:"Context window exceeded. Please start a new conversation or clear history.",retryable:false,originalError:t}):Xh(e)?new me({category:"fatal_limit",code:"QUOTA_EXCEEDED",message:e,retryable:false,originalError:t}):new me({category:"internal",code:"UNKNOWN",message:e,retryable:false,originalError:t})}function mc(r,e,t){let s=e||"";return s.trim().endsWith("}")?(r==="write_file"||r==="edit_file")&&!s.includes('"content"')?new me({category:"tool_truncated",code:"TOOL_MISSING_CONTENT",message:"The content field is missing (likely truncated)",retryable:false,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t}):t.message.includes("JSON")||t.message.includes("Unexpected")||t.message.includes("parse")?new me({category:"tool_json_invalid",code:"JSON_PARSE_ERROR",message:`Invalid JSON in tool arguments: ${t.message}`,retryable:true,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t}):new me({category:"tool_json_invalid",code:"TOOL_ERROR",message:t.message,retryable:true,context:{toolName:r},originalError:t}):new me({category:"tool_truncated",code:"TOOL_ARGS_TRUNCATED",message:"Tool arguments were truncated during streaming",retryable:false,context:{toolName:r,receivedLength:s.length,rawMessage:t.message},originalError:t})}function Nr(r){switch(r.category){case "retryable_rate_limit":return `API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${r.retryAfter?Math.ceil(r.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 kt={requestMaxRetries:10,streamMaxRetries:5,toolMaxRetries:2,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:3e4,jitterRange:.2,streamIdleTimeoutMs:3e5};function Lt(r,e){return {...kt,...r,...e?.requestMaxRetries!==void 0&&{requestMaxRetries:e.requestMaxRetries},...e?.streamMaxRetries!==void 0&&{streamMaxRetries:e.streamMaxRetries},...e?.streamIdleTimeoutMs!==void 0&&{streamIdleTimeoutMs:e.streamIdleTimeoutMs}}}var Ot={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 Rs(r,e){let t=r.toLowerCase();if(t.includes("yunwu"))return Ot.yunwu;if(t.includes("azure"))return Ot.azure;if(e){let s=e.toLowerCase();if(s.includes("yunwu"))return Ot.yunwu;if(s.includes("azure"))return Ot.azure;if(!(s.includes("api.anthropic.com")||s.includes("api.openai.com")))return Ot.proxy}return t.includes("anthropic")?Ot.anthropic:t.includes("gemini")?Ot.gemini:Ot.openai}var hc=100,gc=200,fc=1800*1e3;var Sn=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},Es=class extends Sn{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}}},Is=class extends Sn{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}}},st=class extends Sn{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 Yt=class{static async runInputGuardrails(e,t,s,n){if(e.length===0)return [];let o=e.map(async i=>{let a=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Es(c);return c}catch(l){if(l instanceof Es)throw l;let c={guardrail:i,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 Es(c)}});return await Promise.all(o)}static async runOutputGuardrails(e,t,s,n){if(e.length===0)return [];let o=e.map(async i=>{let a=Date.now();try{let l=await i.guardrail_function(t,s,n),c={guardrail:i,agent_output:n,output:l,execution_time_ms:Date.now()-a};if(l.tripwire_triggered)throw new Is(c);return c}catch(l){if(l instanceof Is)throw l;let c={guardrail:i,agent_output:n,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 Is(c)}});return await Promise.all(o)}static async runToolInputGuardrails(e,t){let s=[];for(let n of e){let o=Date.now();try{let i=await n.guardrail_function(t),a={guardrail:n,output:i,execution_time_ms:Date.now()-o};if(s.push(a),i.behavior.type==="raise_exception")throw new st(a);if(i.behavior.type==="reject_content")return {results:s,should_execute:!1,rejection_message:i.behavior.message}}catch(i){if(i instanceof st)throw i;let a={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-o};throw new st(a)}}return {results:s,should_execute:true}}static async runToolOutputGuardrails(e,t){let s=[];for(let n of e){let o=Date.now();try{let i=await n.guardrail_function(t),a={guardrail:n,output:i,execution_time_ms:Date.now()-o};if(s.push(a),i.behavior.type==="raise_exception")throw new st(a);if(i.behavior.type==="reject_content")return {results:s,should_use_output:!1,replacement_message:i.behavior.message}}catch(i){if(i instanceof st)throw i;let a={guardrail:n,output:{output_info:{error:i instanceof Error?i.message:String(i)},behavior:{type:"raise_exception"}},execution_time_ms:Date.now()-o};throw new st(a)}}return {results:s,should_use_output:true}}};var yc=null,bc=false;function kn(){if(!bc&&(bc=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(le(),Gn)).then(r=>{yc=r.cliLogger;}).catch(()=>{});}catch{}return yc}var _c=new WeakMap,Mi=null;function wc(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function vc(r){if(r){let e=_c.get(r);return e?process.env.CLI_DEBUG==="1"&&kn()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(r).join(",")}, history: ${e.toolCallHistory.length}`):(e=wc(),_c.set(r,e),process.env.CLI_DEBUG==="1"&&kn()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(r).join(",")}`)),e}return Mi||(Mi=wc()),Mi}function Ai(r,e,t,s){let n=vc(r);if(process.env.CLI_DEBUG==="1"){let o=kn();o?.debug("SESSION","recordToolCall called:"),o?.debug("SESSION",` - tool: ${e}`),o?.debug("SESSION",` - success: ${s}`),o?.debug("SESSION",` - context exists: ${!!r}`),o?.debug("SESSION",` - context identity: ${r?Object.keys(r).join(","):"none"}`),o?.debug("SESSION",` - history length before: ${n.toolCallHistory.length}`);}n.toolCallHistory.push({name:e,args:t,timestamp:Date.now(),success:s}),process.env.CLI_DEBUG==="1"&&kn()?.debug("SESSION",` - history length after: ${n.toolCallHistory.length}`),n.toolCallHistory.length>100&&n.toolCallHistory.shift();}function Tc(r,e=10){let t=vc(r);if(process.env.CLI_DEBUG==="1"){let s=kn();s?.debug("SESSION","getRecentToolCalls called:"),s?.debug("SESSION",` - context exists: ${!!r}`),s?.debug("SESSION",` - context identity: ${r?Object.keys(r).join(","):"none"}`),s?.debug("SESSION",` - total history length: ${t.toolCallHistory.length}`),s?.debug("SESSION",` - limit: ${e}`),s?.debug("SESSION",` - returning ${Math.min(t.toolCallHistory.length,e)} calls`);}return t.toolCallHistory.slice(-e)}var ng=fileURLToPath(import.meta.url),Li=dirname(ng),Di=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(Li.includes(".asar")||Li.includes("app.asar")){try{let{app:e}=Cc();if(e&&e.getPath){let t=e.getPath("userData");return Y__default.join(t,"logs")}}catch{}return Y__default.join(js.tmpdir(),"neox-logs")}return Y__default.join(Li,"../../logs")}initLogDir(){try{Tn__default.existsSync(this.logDir)||Tn__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 Y__default.join(this.logDir,`${e}-${t}.log`)}write(e,t){if(!this.enabled)return;let s=new Date().toISOString(),n=typeof t=="string"?{message:t}:t||{},o=this.safeStringify({timestamp:s,...n})+`
1006
+ `;if(this.enabled)try{let i=this.getLogFile(e);Tn__default.appendFileSync(i,o,"utf-8");}catch(i){(i.code==="EACCES"||i.code==="EPERM")&&(this.enabled=false);}}safeStringify(e){let t=new WeakSet;return JSON.stringify(e,(s,n)=>{if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return s==="parser"||s==="socket"||s==="_httpMessage"||s==="req"||s==="res"?"[Omitted]":n&&n.type==="Buffer"&&Array.isArray(n.data)?"[Buffer]":typeof n=="function"?"[Function]":n})}llmRequest(e,t,s,n,o){let i=s.tools?.map(a=>({name:a.name,description:a.description,parameters:a.parameters}));this.write("llm",{type:"REQUEST",provider:e,model:t,url:n,headers:o,messagesCount:s.messages?.length||0,messages:s.messages,toolsCount:s.tools?.length||0,tools:i,temperature:s.temperature});}llmResponse(e,t,s,n){this.write("llm",{type:"RESPONSE",provider:e,duration:`${t}ms`,usage:s,finishReason:n.finish_reason,content:n.content,contentLength:n.content?.length||0,toolCallsCount:n.tool_calls?.length||0,toolCalls:n.tool_calls});}llmError(e,t){let s={type:"ERROR",provider:e,error:t.message,status:t.response?.status};if(t.response?.data)try{let n=t.response.data;typeof n=="string"?s.data=n:typeof n=="object"&&(s.data={error:n.error,message:n.message,type:n.type,code:n.code});}catch{s.data="[Could not serialize response data]";}this.write("llm",s);}agentStart(e){this.write("agent",{type:"START",task:e});}agentIteration(e,t){this.write("agent",{type:"ITERATION",iteration:e,action:t});}agentComplete(e,t,s){this.write("agent",{type:"COMPLETE",iterations:e,toolCalls:t,usage:s});}agentError(e){this.write("agent",{type:"ERROR",error:e});}toolCall(e,t){this.write("tool",{type:"CALL",tool:e,args:t});}toolResult(e,t,s,n){this.write("tool",{type:"RESULT",tool:e,success:t,resultLength:s,duration:`${n}ms`});}toolError(e,t){this.write("tool",{type:"ERROR",tool:e,error:t});}},te=new Di;function Rc(r,e){let t=r||"Unknown error",s=t.toLowerCase(),n=e?.providerName?.trim()||"LLM";if(s.includes("timeout")){let o=Math.round((e?.timeoutMs??12e4)/1e3);return [`\u23F1\uFE0F ${n} \u8BF7\u6C42\u8D85\u65F6 (${o}s)\u3002${n} \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(`
1007
+ `)}return t}var og=new rg({allErrors:true,strict:false});function ig(r){let e=(r||"").trim();if(e.startsWith("```")){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(t&&t[1])return t[1].trim()}return e}function ag(r){return !r||r.length===0?[]:r.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 Ur=class{constructor(e){this.definition=e;this.validateFn=og.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(`
1008
+
1009
+ `)}validate(e){let t=ig(e||"");if(!t)return {ok:false,reason:"empty_output",message:"The model returned an empty response."};let s;try{s=JSON.parse(t);}catch(o){return {ok:false,reason:"parse_error",message:o?.message||"Failed to parse JSON output."}}return this.validateFn(s)?{ok:true,parsed:s,normalized:JSON.stringify(s,null,2)}:{ok:false,reason:"schema_mismatch",message:"Response does not match the required JSON schema.",errors:ag(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:
1010
1010
  - `+e.errors.join(`
1011
1011
  - `)):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(`
1012
1012
 
1013
- `)}};function $o(r,e={}){let{initialDelayMs:t=kt.initialDelayMs,backoffFactor:s=kt.backoffFactor,maxDelayMs:n=kt.maxDelayMs,jitterRange:i=kt.jitterRange}=e,o=Math.max(0,r-1),a=t*Math.pow(s,o),l=1+(Math.random()*2-1)*i,c=a*l,u=Math.min(c,n);return Math.floor(u)}function Dt(r,e,t){return r!==void 0&&r>0?r:$o(e,t)}function Is(r){return new Promise(e=>setTimeout(e,r))}function Yt(r,e){return new Promise((t,s)=>{if(e?.aborted){s(new DOMException("Aborted","AbortError"));return}let n=setTimeout(t,r),i=()=>{clearTimeout(n),s(new DOMException("Aborted","AbortError"));};e?.addEventListener("abort",i,{once:true});let o=()=>{e?.removeEventListener("abort",i);};setTimeout(()=>{o(),t();},r);})}function qe(r){if(r<1e3)return `${r}ms`;let e=r/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var ig={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},og={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function ag(r,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return $o(r,ig)}function kn(r,e,t){return r==="retryable_rate_limit"?ag(e,t):r==="retryable_stream"||r==="retryable_network"?$o(e,og):Dt(t,e)}le();le();var lg=2e3,kc={Read:"file_read",Write:"file_write",Edit:"file_edit",Glob:"file_search",Grep:"file_search",NotebookEdit:"file_edit",Bash:"bash",BashOutput:"bash",WebFetch:"web_fetch",WebSearch:"web_search",Task:"task"},cg={file_read:{system:`\u4F60\u662F\u4E00\u4E2A\u4EE3\u7801\u5206\u6790\u52A9\u624B\u3002\u8BF7\u5C06\u6587\u4EF6\u5185\u5BB9\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1013
+ `)}};function Ni(r,e={}){let{initialDelayMs:t=kt.initialDelayMs,backoffFactor:s=kt.backoffFactor,maxDelayMs:n=kt.maxDelayMs,jitterRange:o=kt.jitterRange}=e,i=Math.max(0,r-1),a=t*Math.pow(s,i),l=1+(Math.random()*2-1)*o,c=a*l,u=Math.min(c,n);return Math.floor(u)}function Dt(r,e,t){return r!==void 0&&r>0?r:Ni(e,t)}function Ms(r){return new Promise(e=>setTimeout(e,r))}function Xt(r,e){return new Promise((t,s)=>{if(e?.aborted){s(new DOMException("Aborted","AbortError"));return}let n=setTimeout(t,r),o=()=>{clearTimeout(n),s(new DOMException("Aborted","AbortError"));};e?.addEventListener("abort",o,{once:true});let i=()=>{e?.removeEventListener("abort",o);};setTimeout(()=>{i(),t();},r);})}function qe(r){if(r<1e3)return `${r}ms`;let e=r/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var lg={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},cg={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function ug(r,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return Ni(r,lg)}function Cn(r,e,t){return r==="retryable_rate_limit"?ug(e,t):r==="retryable_stream"||r==="retryable_network"?Ni(e,cg):Dt(t,e)}le();le();var pg=2e3,Ec={Read:"file_read",Write:"file_write",Edit:"file_edit",Glob:"file_search",Grep:"file_search",NotebookEdit:"file_edit",Bash:"bash",BashOutput:"bash",WebFetch:"web_fetch",WebSearch:"web_search",Task:"task"},dg={file_read:{system:`\u4F60\u662F\u4E00\u4E2A\u4EE3\u7801\u5206\u6790\u52A9\u624B\u3002\u8BF7\u5C06\u6587\u4EF6\u5185\u5BB9\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1014
1014
  1. \u6587\u4EF6\u7C7B\u578B\u548C\u4E3B\u8981\u529F\u80FD
1015
1015
  2. \u5173\u952E\u7684\u51FD\u6570/\u7C7B/\u63A5\u53E3\u5B9A\u4E49\uFF08\u53EA\u4FDD\u7559\u7B7E\u540D\uFF09
1016
1016
  3. \u91CD\u8981\u7684\u914D\u7F6E\u9879\u6216\u5E38\u91CF
@@ -1075,39 +1075,39 @@ ${r}
1075
1075
  \u683C\u5F0F\uFF1A[\u4EFB\u52A1\u7C7B\u578B] \u7ED3\u8BBA: \u6458\u8981`,user:r=>`\u4EFB\u52A1\u7ED3\u679C:
1076
1076
  ${r}
1077
1077
 
1078
- \u8BF7\u538B\u7F29\u8FD9\u4E2A\u4EFB\u52A1\u7ED3\u679C\u3002`}},$t=class{supportedTools=Object.keys(kc);debug;llmProvider;model;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.llmProvider=e?.llmProvider,this.model=e?.model;}getToolType(e){return e.startsWith("mcp__")?"mcp":kc[e]||"other"}needsLLMCompression(e,t,s){let n=this.getToolType(e);if(["web_fetch","web_search","task"].includes(n))return true;let o=128e3,a=2e5,l=s||o,c=Math.max(.3,Math.min(2,l/a)),p={file_read:2e4,file_write:8e3,file_edit:5e3,file_search:1e4,bash:15e3,web_fetch:0,web_search:0,image_analysis:3e3,mcp:1e4,task:0,other:15e3}[n]??15e3,d=Math.floor(p*c);return this.debug&&g.debug("ToolCompressor",`[${e}] contextWindow=${l}${s?"":"(default)"}, scaleFactor=${c.toFixed(2)}, threshold=${d}`),t.length>d}async compress(e,t,s){let n=this.getToolType(e),i=t.length,o=this.extractMetadata(n,t,e),a=this.needsLLMCompression(e,t,s.contextWindow),l=s.llmProvider||this.llmProvider,c,u=false;if(a&&l&&s.enableLLMCompression!==false){let p=await this.compressWithLLM(n,t,l,s.model||this.model,o);p?(c=p,u=true):c=this.compressWithRules(n,t,o);}else c=this.compressWithRules(n,t,o);if(this.debug){let p=((1-c.length/i)*100).toFixed(1);g.debug("ToolCompressor",`[${e}] ${i} \u2192 ${c.length} chars (${p}% saved, LLM: ${u})`);}return {content:c,originalLength:i,compressedLength:c.length,strategy:n,usedLLM:u,metadata:o}}extractMetadata(e,t,s){let n={};switch(e){case "file_read":case "file_write":case "file_edit":let i=t.match(/(?:file|path)[:\s]+([^\n]+)/i);i&&(n.filePath=i[1].trim());break;case "bash":let o=t.match(/(?:command|cmd)[:\s]+([^\n]+)/i);o&&(n.command=o[1].trim()),/error|failed|exit code [1-9]/i.test(t)&&(n.exitCode=1);break;case "web_fetch":case "web_search":let a=t.match(/https?:\/\/[^\s\)]+/g);a&&(n.urls=[...new Set(a)].slice(0,10));break}return n}async compressWithLLM(e,t,s,n,i){let o=cg[e];if(!o)return null;try{let l=t.length>8e3?t.slice(0,8e3)+`
1078
+ \u8BF7\u538B\u7F29\u8FD9\u4E2A\u4EFB\u52A1\u7ED3\u679C\u3002`}},$t=class{supportedTools=Object.keys(Ec);debug;llmProvider;model;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.llmProvider=e?.llmProvider,this.model=e?.model;}getToolType(e){return e.startsWith("mcp__")?"mcp":Ec[e]||"other"}needsLLMCompression(e,t,s){let n=this.getToolType(e);if(["web_fetch","web_search","task"].includes(n))return true;let i=128e3,a=2e5,l=s||i,c=Math.max(.3,Math.min(2,l/a)),p={file_read:2e4,file_write:8e3,file_edit:5e3,file_search:1e4,bash:15e3,web_fetch:0,web_search:0,image_analysis:3e3,mcp:1e4,task:0,other:15e3}[n]??15e3,d=Math.floor(p*c);return this.debug&&g.debug("ToolCompressor",`[${e}] contextWindow=${l}${s?"":"(default)"}, scaleFactor=${c.toFixed(2)}, threshold=${d}`),t.length>d}async compress(e,t,s){let n=this.getToolType(e),o=t.length,i=this.extractMetadata(n,t,e),a=this.needsLLMCompression(e,t,s.contextWindow),l=s.llmProvider||this.llmProvider,c,u=false;if(a&&l&&s.enableLLMCompression!==false){let p=await this.compressWithLLM(n,t,l,s.model||this.model,i);p?(c=p,u=true):c=this.compressWithRules(n,t,i);}else c=this.compressWithRules(n,t,i);if(this.debug){let p=((1-c.length/o)*100).toFixed(1);g.debug("ToolCompressor",`[${e}] ${o} \u2192 ${c.length} chars (${p}% saved, LLM: ${u})`);}return {content:c,originalLength:o,compressedLength:c.length,strategy:n,usedLLM:u,metadata:i}}extractMetadata(e,t,s){let n={};switch(e){case "file_read":case "file_write":case "file_edit":let o=t.match(/(?:file|path)[:\s]+([^\n]+)/i);o&&(n.filePath=o[1].trim());break;case "bash":let i=t.match(/(?:command|cmd)[:\s]+([^\n]+)/i);i&&(n.command=i[1].trim()),/error|failed|exit code [1-9]/i.test(t)&&(n.exitCode=1);break;case "web_fetch":case "web_search":let a=t.match(/https?:\/\/[^\s\)]+/g);a&&(n.urls=[...new Set(a)].slice(0,10));break}return n}async compressWithLLM(e,t,s,n,o){let i=dg[e];if(!i)return null;try{let l=t.length>8e3?t.slice(0,8e3)+`
1079
1079
 
1080
- ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:t,c=await s.chat([{role:"system",content:o.system},{role:"user",content:o.user(l,i?.filePath)}],{model:n,temperature:.2});return ee(c.choices[0]?.message?.content)?.trim()||null}catch(a){return g.warn("ToolCompressor",`LLM compression failed: ${a.message}`),null}}compressWithRules(e,t,s){let n=lg;switch(e){case "file_read":return this.compressFileRead(t,s?.filePath,n);case "file_edit":return this.compressFileEdit(t,n);case "bash":return this.compressBash(t,s?.command,n);case "web_fetch":case "web_search":return this.compressWebContent(t,s?.urls,n);case "file_search":return this.compressSearchResult(t,n);default:return this.truncateWithContext(t,n)}}compressFileRead(e,t,s=2e3){let n=e.split(`
1081
- `),i=t?`\u{1F4C4} ${t}
1082
- `:"";if(e.length<=s)return i+e;let o=Math.floor(s*.6/80),a=Math.floor(s*.3/80),l=n.slice(0,o).join(`
1080
+ ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:t,c=await s.chat([{role:"system",content:i.system},{role:"user",content:i.user(l,o?.filePath)}],{model:n,temperature:.2});return ee(c.choices[0]?.message?.content)?.trim()||null}catch(a){return g.warn("ToolCompressor",`LLM compression failed: ${a.message}`),null}}compressWithRules(e,t,s){let n=pg;switch(e){case "file_read":return this.compressFileRead(t,s?.filePath,n);case "file_edit":return this.compressFileEdit(t,n);case "bash":return this.compressBash(t,s?.command,n);case "web_fetch":case "web_search":return this.compressWebContent(t,s?.urls,n);case "file_search":return this.compressSearchResult(t,n);default:return this.truncateWithContext(t,n)}}compressFileRead(e,t,s=2e3){let n=e.split(`
1081
+ `),o=t?`\u{1F4C4} ${t}
1082
+ `:"";if(e.length<=s)return o+e;let i=Math.floor(s*.6/80),a=Math.floor(s*.3/80),l=n.slice(0,i).join(`
1083
1083
  `),c=n.slice(-a).join(`
1084
- `),u=n.length-o-a;return `${i}${l}
1084
+ `),u=n.length-i-a;return `${o}${l}
1085
1085
 
1086
1086
  ... [\u7701\u7565 ${u} \u884C] ...
1087
1087
 
1088
- ${c}`}compressFileEdit(e,t=1500){let s=e.match(/file[:\s]+([^\n]+)/i),n=e.match(/old_string[:\s]+([\s\S]*?)(?=new_string|$)/i),i=e.match(/new_string[:\s]+([\s\S]*?)$/i);if(s){let o=s[1].trim(),a=n?this.truncate(n[1].trim(),200):"",l=i?this.truncate(i[1].trim(),200):"";return `\u{1F4DD} \u7F16\u8F91: ${o}
1088
+ ${c}`}compressFileEdit(e,t=1500){let s=e.match(/file[:\s]+([^\n]+)/i),n=e.match(/old_string[:\s]+([\s\S]*?)(?=new_string|$)/i),o=e.match(/new_string[:\s]+([\s\S]*?)$/i);if(s){let i=s[1].trim(),a=n?this.truncate(n[1].trim(),200):"",l=o?this.truncate(o[1].trim(),200):"";return `\u{1F4DD} \u7F16\u8F91: ${i}
1089
1089
  \u65E7\u5185\u5BB9: ${a}
1090
1090
  \u65B0\u5185\u5BB9: ${l}`}return this.truncateWithContext(e,t)}compressBash(e,t,s=2e3){let n=e.split(`
1091
- `),i=t?`$ ${t}
1092
- `:"";if(/error|failed|exception/i.test(e))return i+this.truncateWithContext(e,s*1.5);if(e.length<=s)return i+e;let a=10,l=20,c=n.slice(0,a).join(`
1091
+ `),o=t?`$ ${t}
1092
+ `:"";if(/error|failed|exception/i.test(e))return o+this.truncateWithContext(e,s*1.5);if(e.length<=s)return o+e;let a=10,l=20,c=n.slice(0,a).join(`
1093
1093
  `),u=n.slice(-l).join(`
1094
- `),p=n.length-a-l;return `${i}${c}
1094
+ `),p=n.length-a-l;return `${o}${c}
1095
1095
 
1096
1096
  ... [\u7701\u7565 ${p} \u884C] ...
1097
1097
 
1098
- ${u}`}compressWebContent(e,t,s=2e3){let n=e.replace(/<[^>]+>/g," ");n=n.replace(/\s+/g," ").trim();let i=t?.length?`
1098
+ ${u}`}compressWebContent(e,t,s=2e3){let n=e.replace(/<[^>]+>/g," ");n=n.replace(/\s+/g," ").trim();let o=t?.length?`
1099
1099
 
1100
1100
  \u76F8\u5173\u94FE\u63A5:
1101
- ${t.slice(0,5).map(o=>`- ${o}`).join(`
1102
- `)}`:"";return this.truncate(n,s-i.length)+i}compressSearchResult(e,t=2e3){let s=e.split(`
1101
+ ${t.slice(0,5).map(i=>`- ${i}`).join(`
1102
+ `)}`:"";return this.truncate(n,s-o.length)+o}compressSearchResult(e,t=2e3){let s=e.split(`
1103
1103
  `).filter(n=>n.trim());return s.length<=30?e:s.slice(0,30).join(`
1104
1104
  `)+`
1105
1105
 
1106
- ... [\u8FD8\u6709 ${s.length-30} \u4E2A\u7ED3\u679C] ...`}truncateWithContext(e,t){if(e.length<=t)return e;let s=Math.floor(t*.7),n=Math.floor(t*.25),i=e.slice(0,s),o=e.slice(-n),a=e.length-s-n;return `${i}
1106
+ ... [\u8FD8\u6709 ${s.length-30} \u4E2A\u7ED3\u679C] ...`}truncateWithContext(e,t){if(e.length<=t)return e;let s=Math.floor(t*.7),n=Math.floor(t*.25),o=e.slice(0,s),i=e.slice(-n),a=e.length-s-n;return `${o}
1107
1107
 
1108
1108
  ... [\u7701\u7565 ${a} \u5B57\u7B26] ...
1109
1109
 
1110
- ${o}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new $t;le();var ug=15,pg=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],Cn={system:`\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u52A9\u624B\u3002\u8BF7\u5C06\u5BF9\u8BDD\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1110
+ ${i}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new $t;le();var mg=15,hg=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],Rn={system:`\u4F60\u662F\u4E00\u4E2A\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u52A9\u624B\u3002\u8BF7\u5C06\u5BF9\u8BDD\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\uFF1A
1111
1111
  1. \u7528\u6237\u7684\u6838\u5FC3\u9700\u6C42\u548C\u76EE\u6807
1112
1112
  2. \u5173\u952E\u51B3\u7B56\u548C\u5176\u7406\u7531
1113
1113
  3. \u91CD\u8981\u7684\u4EE3\u7801\u53D8\u66F4\uFF08\u6587\u4EF6\u8DEF\u5F84\u3001\u51FD\u6570\u540D\uFF09
@@ -1132,14 +1132,14 @@ ${o}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new $t;le();var
1132
1132
  - \u4FDD\u7559\u6280\u672F\u7EC6\u8282\uFF08\u6587\u4EF6\u540D\u3001\u51FD\u6570\u540D\u3001\u9519\u8BEF\u4FE1\u606F\uFF09
1133
1133
  - \u603B\u957F\u5EA6\u63A7\u5236\u5728 800 \u5B57\u4EE5\u5185`,user:r=>`\u8BF7\u538B\u7F29\u4EE5\u4E0B\u5BF9\u8BDD\u5386\u53F2:
1134
1134
 
1135
- ${r}`},Ms=class{debug;toolCompressor;minRecentMessages;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.toolCompressor=e?.toolCompressor??new $t({debug:this.debug}),this.minRecentMessages=e?.minRecentMessages??ug;}async compressMessage(e,t){let s=pt(e),n=this.getMessageType(e);if(n==="system")return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve_system"};if(n==="tool_result"&&e.role==="tool"){let o=e.name||"unknown",a=ee(e.content),l=await this.toolCompressor.compress(o,a,t),c={...e,content:l.content},u=pt(c);return {message:c,originalTokens:s,compressedTokens:u,compressionRatio:u/s,usedLLM:l.usedLLM,strategy:`tool_${l.strategy}`}}let i=ee(e.content);if(i.length>3e3&&t.llmProvider&&t.enableLLMCompression!==false){let o=await this.compressLongContent(i,t);if(o){let a={...e,content:o},l=pt(a);return {message:a,originalTokens:s,compressedTokens:l,compressionRatio:l/s,usedLLM:true,strategy:"llm_content_compression"}}}return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve"}}async compressMessages(e,t){let s=[],n=We(e),i=t.tokenBudget||n;return this.debug&&(s.push(`[MessageCompressor] \u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${n} tokens`),s.push(`[MessageCompressor] Token \u9884\u7B97: ${i}`)),n<=i?this.compressLargeMessages(e,t,s):this.compressWithPriority(e,i,t,s)}async compressLargeMessages(e,t,s){let n=We(e),i=[],o=0,a=0;for(let c of e)if(pt(c)>2e3&&c.role!=="system"){let p=await this.compressMessage(c,t);i.push(p.message),p.usedLLM?o++:p.compressionRatio<1&&a++;}else i.push(c);let l=We(i);return this.debug&&s.push(`[MessageCompressor] \u5927\u6D88\u606F\u538B\u7F29\u5B8C\u6210: LLM=${o}, \u622A\u65AD=${a}`),{messages:i,originalCount:e.length,compressedCount:i.length,originalTokens:n,compressedTokens:l,savedTokens:n-l,stats:{droppedMessages:0,llmCompressedMessages:o,truncatedMessages:a,preservedMessages:e.length-o-a},debugInfo:this.debug?s:void 0}}async compressWithPriority(e,t,s,n){let i=We(e),o=this.prioritizeMessages(e);if(this.debug){let _=this.countPriorities(o);n.push(`[MessageCompressor] \u4F18\u5148\u7EA7\u5206\u5E03: CRITICAL=${_.critical}, HIGH=${_.high}, MEDIUM=${_.medium}, LOW=${_.low}`);}let a=[],l=0;for(let _ of o)_.priority===0&&(a.push(_),l+=_.tokens);this.debug&&n.push(`[MessageCompressor] CRITICAL \u4FDD\u7559\u540E: ${a.length} \u6761, ${l} tokens`);let c=o.filter(_=>_.priority===1&&!a.includes(_));for(let _ of c){let v=await this.compressMessage(_.message,s),k=v.compressedTokens;l+k<=t&&(a.push({..._,message:v.message,tokens:k}),l+=k);}this.debug&&n.push(`[MessageCompressor] HIGH \u4FDD\u7559\u540E: ${a.length} \u6761, ${l} tokens`);let u=t-l,p=o.filter(_=>(_.priority===2||_.priority===3)&&!a.includes(_));if(p.reduce((_,v)=>_+v.tokens,0)<=u)for(let _ of p){let v=await this.compressMessage(_.message,s);a.push({..._,message:v.message,tokens:v.compressedTokens}),l+=v.compressedTokens;}else {if(s.llmProvider&&s.enableLLMCompression!==false&&p.length>=5){let _=await this.compressBatchWithLLM(p.map(v=>v.message),s);if(_){let v={role:"user",content:`[\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55]
1136
- ${_}`,name:"CompressedHistory"},k=pt(v);l+k<=t&&(a.push({message:v,priority:2,tokens:k,index:-1,type:"user",reason:"LLM batch compressed"}),l+=k,this.debug&&n.push(`[MessageCompressor] LLM \u6279\u91CF\u538B\u7F29: ${p.length} \u6761 \u2192 1 \u6761\u6458\u8981`));}}if(!a.find(_=>_.reason==="LLM batch compressed")){let _=[...p].sort((v,k)=>k.index-v.index);for(let v of _){let k=await this.compressMessage(v.message,s);l+k.compressedTokens<=t&&(a.push({...v,message:k.message,tokens:k.compressedTokens}),l+=k.compressedTokens);}}}let h=[...a].sort((_,v)=>_.index===-1||v.index===-1?0:_.index-v.index).map(_=>_.message),f=We(h),y=e.length-a.length,b=a.filter(_=>_.reason.includes("LLM")).length;return this.debug&&(n.push(`[MessageCompressor] \u6700\u7EC8: ${h.length} \u6761, ${f} tokens`),n.push(`[MessageCompressor] \u8282\u7701: ${i-f} tokens`)),{messages:h,originalCount:e.length,compressedCount:h.length,originalTokens:i,compressedTokens:f,savedTokens:i-f,stats:{droppedMessages:y,llmCompressedMessages:b,truncatedMessages:0,preservedMessages:a.length-b},debugInfo:this.debug?n:void 0}}getMessageType(e){return e.role==="system"?"system":e.role==="user"?"user":e.role==="tool"?"tool_result":e.role==="assistant"?e.tool_calls&&e.tool_calls.length>0?"tool_call":"assistant":"user"}prioritizeMessages(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s],i=pt(n),o=this.getMessageType(n),a=e.length-s,l,c;o==="system"?(l=0,c="system message"):a<=this.minRecentMessages?(l=0,c=`recent message (${a} from end)`):this.containsError(n)?(l=1,c="contains error"):o==="tool_call"?(l=1,c="tool calls"):o==="tool_result"?(l=1,c="tool result"):o==="user"?(l=2,c="user message"):o==="assistant"?(l=2,c="assistant message"):(l=3,c="default"),t.push({message:n,priority:l,tokens:i,index:s,type:o,reason:c});}return t}containsError(e){let t=ee(e.content);return pg.some(s=>s.test(t))}countPriorities(e){return {critical:e.filter(t=>t.priority===0).length,high:e.filter(t=>t.priority===1).length,medium:e.filter(t=>t.priority===2).length,low:e.filter(t=>t.priority===3).length}}async compressLongContent(e,t){if(!t.llmProvider)return null;try{let n=/[\u4e00-\u9fa5]/.test(e)?Cn.systemZh:Cn.system,i=6e3,o=e.length>i?e.slice(0,i)+`
1135
+ ${r}`},As=class{debug;toolCompressor;minRecentMessages;constructor(e){this.debug=e?.debug??process.env.CLI_DEBUG==="1",this.toolCompressor=e?.toolCompressor??new $t({debug:this.debug}),this.minRecentMessages=e?.minRecentMessages??mg;}async compressMessage(e,t){let s=pt(e),n=this.getMessageType(e);if(n==="system")return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve_system"};if(n==="tool_result"&&e.role==="tool"){let i=e.name||"unknown",a=ee(e.content),l=await this.toolCompressor.compress(i,a,t),c={...e,content:l.content},u=pt(c);return {message:c,originalTokens:s,compressedTokens:u,compressionRatio:u/s,usedLLM:l.usedLLM,strategy:`tool_${l.strategy}`}}let o=ee(e.content);if(o.length>3e3&&t.llmProvider&&t.enableLLMCompression!==false){let i=await this.compressLongContent(o,t);if(i){let a={...e,content:i},l=pt(a);return {message:a,originalTokens:s,compressedTokens:l,compressionRatio:l/s,usedLLM:true,strategy:"llm_content_compression"}}}return {message:e,originalTokens:s,compressedTokens:s,compressionRatio:1,usedLLM:false,strategy:"preserve"}}async compressMessages(e,t){let s=[],n=We(e),o=t.tokenBudget||n;return this.debug&&(s.push(`[MessageCompressor] \u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${n} tokens`),s.push(`[MessageCompressor] Token \u9884\u7B97: ${o}`)),n<=o?this.compressLargeMessages(e,t,s):this.compressWithPriority(e,o,t,s)}async compressLargeMessages(e,t,s){let n=We(e),o=[],i=0,a=0;for(let c of e)if(pt(c)>2e3&&c.role!=="system"){let p=await this.compressMessage(c,t);o.push(p.message),p.usedLLM?i++:p.compressionRatio<1&&a++;}else o.push(c);let l=We(o);return this.debug&&s.push(`[MessageCompressor] \u5927\u6D88\u606F\u538B\u7F29\u5B8C\u6210: LLM=${i}, \u622A\u65AD=${a}`),{messages:o,originalCount:e.length,compressedCount:o.length,originalTokens:n,compressedTokens:l,savedTokens:n-l,stats:{droppedMessages:0,llmCompressedMessages:i,truncatedMessages:a,preservedMessages:e.length-i-a},debugInfo:this.debug?s:void 0}}async compressWithPriority(e,t,s,n){let o=We(e),i=this.prioritizeMessages(e);if(this.debug){let _=this.countPriorities(i);n.push(`[MessageCompressor] \u4F18\u5148\u7EA7\u5206\u5E03: CRITICAL=${_.critical}, HIGH=${_.high}, MEDIUM=${_.medium}, LOW=${_.low}`);}let a=[],l=0;for(let _ of i)_.priority===0&&(a.push(_),l+=_.tokens);this.debug&&n.push(`[MessageCompressor] CRITICAL \u4FDD\u7559\u540E: ${a.length} \u6761, ${l} tokens`);let c=i.filter(_=>_.priority===1&&!a.includes(_));for(let _ of c){let v=await this.compressMessage(_.message,s),k=v.compressedTokens;l+k<=t&&(a.push({..._,message:v.message,tokens:k}),l+=k);}this.debug&&n.push(`[MessageCompressor] HIGH \u4FDD\u7559\u540E: ${a.length} \u6761, ${l} tokens`);let u=t-l,p=i.filter(_=>(_.priority===2||_.priority===3)&&!a.includes(_));if(p.reduce((_,v)=>_+v.tokens,0)<=u)for(let _ of p){let v=await this.compressMessage(_.message,s);a.push({..._,message:v.message,tokens:v.compressedTokens}),l+=v.compressedTokens;}else {if(s.llmProvider&&s.enableLLMCompression!==false&&p.length>=5){let _=await this.compressBatchWithLLM(p.map(v=>v.message),s);if(_){let v={role:"user",content:`[\u538B\u7F29\u7684\u5386\u53F2\u8BB0\u5F55]
1136
+ ${_}`,name:"CompressedHistory"},k=pt(v);l+k<=t&&(a.push({message:v,priority:2,tokens:k,index:-1,type:"user",reason:"LLM batch compressed"}),l+=k,this.debug&&n.push(`[MessageCompressor] LLM \u6279\u91CF\u538B\u7F29: ${p.length} \u6761 \u2192 1 \u6761\u6458\u8981`));}}if(!a.find(_=>_.reason==="LLM batch compressed")){let _=[...p].sort((v,k)=>k.index-v.index);for(let v of _){let k=await this.compressMessage(v.message,s);l+k.compressedTokens<=t&&(a.push({...v,message:k.message,tokens:k.compressedTokens}),l+=k.compressedTokens);}}}let h=[...a].sort((_,v)=>_.index===-1||v.index===-1?0:_.index-v.index).map(_=>_.message),f=We(h),y=e.length-a.length,b=a.filter(_=>_.reason.includes("LLM")).length;return this.debug&&(n.push(`[MessageCompressor] \u6700\u7EC8: ${h.length} \u6761, ${f} tokens`),n.push(`[MessageCompressor] \u8282\u7701: ${o-f} tokens`)),{messages:h,originalCount:e.length,compressedCount:h.length,originalTokens:o,compressedTokens:f,savedTokens:o-f,stats:{droppedMessages:y,llmCompressedMessages:b,truncatedMessages:0,preservedMessages:a.length-b},debugInfo:this.debug?n:void 0}}getMessageType(e){return e.role==="system"?"system":e.role==="user"?"user":e.role==="tool"?"tool_result":e.role==="assistant"?e.tool_calls&&e.tool_calls.length>0?"tool_call":"assistant":"user"}prioritizeMessages(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s],o=pt(n),i=this.getMessageType(n),a=e.length-s,l,c;i==="system"?(l=0,c="system message"):a<=this.minRecentMessages?(l=0,c=`recent message (${a} from end)`):this.containsError(n)?(l=1,c="contains error"):i==="tool_call"?(l=1,c="tool calls"):i==="tool_result"?(l=1,c="tool result"):i==="user"?(l=2,c="user message"):i==="assistant"?(l=2,c="assistant message"):(l=3,c="default"),t.push({message:n,priority:l,tokens:o,index:s,type:i,reason:c});}return t}containsError(e){let t=ee(e.content);return hg.some(s=>s.test(t))}countPriorities(e){return {critical:e.filter(t=>t.priority===0).length,high:e.filter(t=>t.priority===1).length,medium:e.filter(t=>t.priority===2).length,low:e.filter(t=>t.priority===3).length}}async compressLongContent(e,t){if(!t.llmProvider)return null;try{let n=/[\u4e00-\u9fa5]/.test(e)?Rn.systemZh:Rn.system,o=6e3,i=e.length>o?e.slice(0,o)+`
1137
1137
 
1138
1138
  ...[\u5185\u5BB9\u8FC7\u957F\uFF0C\u5DF2\u622A\u65AD]...`:e,a=await t.llmProvider.chat([{role:"system",content:n},{role:"user",content:`\u8BF7\u538B\u7F29\u4EE5\u4E0B\u5185\u5BB9:
1139
1139
 
1140
- ${o}`}],{model:t.model,temperature:.2});return ee(a.choices[0]?.message?.content)||null}catch(s){return g.warn("MessageCompressor",`LLM compression failed: ${s.message}`),null}}async compressBatchWithLLM(e,t){if(!t.llmProvider)return null;try{let s=e.map(a=>{let l=a.role==="assistant"?"Assistant":a.role==="user"?"User":a.role==="tool"?"Tool":a.role,c=ee(a.content),u=c.length>800?c.slice(0,800)+"...":c;return `[${l}] ${u}`}).join(`
1140
+ ${i}`}],{model:t.model,temperature:.2});return ee(a.choices[0]?.message?.content)||null}catch(s){return g.warn("MessageCompressor",`LLM compression failed: ${s.message}`),null}}async compressBatchWithLLM(e,t){if(!t.llmProvider)return null;try{let s=e.map(a=>{let l=a.role==="assistant"?"Assistant":a.role==="user"?"User":a.role==="tool"?"Tool":a.role,c=ee(a.content),u=c.length>800?c.slice(0,800)+"...":c;return `[${l}] ${u}`}).join(`
1141
1141
 
1142
- `),i=/[\u4e00-\u9fa5]/.test(s)?Cn.systemZh:Cn.system,o=await t.llmProvider.chat([{role:"system",content:i},{role:"user",content:Cn.user(s)}],{model:t.model,temperature:.3});return ee(o.choices[0]?.message?.content)||null}catch(s){return g.warn("MessageCompressor",`Batch LLM compression failed: ${s.message}`),null}}};new Ms;var dg={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},Ur=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...dg,...e},this.config.debug=this.config.debug||process.env.CLI_DEBUG==="1",this.toolCompressor=new $t({debug:this.config.debug}),this.messageCompressor=new Ms({debug:this.config.debug,toolCompressor:this.toolCompressor,minRecentMessages:this.config.minRecentMessages});}setLLMProvider(e,t){this.llmProvider=e,this.model=t;}setContextWindow(e){this.contextWindow=e,this.config.debug&&g.info("UnifiedCompressor",`Context window set to: ${e}`);}registerToolCompressor(e){g.info("UnifiedCompressor","Custom tool compressor registered");}setMessageCompressor(e){this.messageCompressor=e,g.info("UnifiedCompressor","Custom message compressor set");}async compressHistory(e,t,s){let n=Date.now(),i=We(e),o={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,tokenBudget:t,contextWindow:s?.contextWindow||this.contextWindow,iteration:s?.iteration,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,signal:s?.signal,debug:this.config.debug};if(this.config.debug&&g.debug("UnifiedCompressor",`\u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${i} tokens \u2192 \u9884\u7B97 ${t} tokens`),i<=t){let c=await this.compressLargeMessagesOnly(e,o);return this.config.debug&&g.debug("UnifiedCompressor",`\u5728\u9884\u7B97\u5185\uFF0C\u4EC5\u538B\u7F29\u5927\u6D88\u606F: ${c.savedTokens} tokens \u8282\u7701`),c}let a=await this.messageCompressor.compressMessages(e,o),l=Date.now()-n;return this.config.debug&&g.debug("UnifiedCompressor",`\u538B\u7F29\u5B8C\u6210 (${l}ms): ${a.originalCount} \u2192 ${a.compressedCount} \u6761, ${a.originalTokens} \u2192 ${a.compressedTokens} tokens (\u8282\u7701 ${a.savedTokens} tokens, ${(a.savedTokens/a.originalTokens*100).toFixed(1)}%)`),a}async compressLargeMessagesOnly(e,t){let s=We(e),n=[],i=0,o=0;for(let l of e)if(pt(l)>2e3&&l.role!=="system"){let u=await this.messageCompressor.compressMessage(l,t);n.push(u.message),u.usedLLM?i++:u.compressionRatio<1&&o++;}else n.push(l);let a=We(n);return {messages:n,originalCount:e.length,compressedCount:n.length,originalTokens:s,compressedTokens:a,savedTokens:s-a,stats:{droppedMessages:0,llmCompressedMessages:i,truncatedMessages:o,preservedMessages:e.length-i-o}}}async compressToolResult(e,t,s){let n={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,debug:this.config.debug};return (await this.toolCompressor.compress(e,t,n)).content}getStats(){return {config:this.config,hasLLMProvider:!!this.llmProvider}}};function mg(r,e){if(typeof r!="string")return null;let t=r.trim();if(!t.startsWith("{"))return null;try{let s=JSON.parse(t);return !s||typeof s!="object"||s.tool!==e||typeof s.status!="string"?null:s.status}catch{return null}}var jr=class r{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 r.READ_ONLY_TOOLS.has(e)}static isStateModifying(e){return r.STATE_MODIFYING_TOOLS.has(e)}static getMetadata(e){return r.TOOL_METADATA.get(e)}analyzePlan(e){let t=[],s=[];for(let n of e){let i=n.function.name;r.isReadOnly(i)?t.push(n):s.push(n);}return {parallel:t,sequential:s,totalTools:e.length,parallelCount:t.length,sequentialCount:s.length}}async executeSingleTool(e,t,s){let n=Date.now();if(s?.aborted)return {id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n};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()-n};try{let o=e.function.arguments.trim(),a=o?JSON.parse(o):{},l=await i.function(a,{signal:s}),c=!0;return mg(l,e.function.name)==="error"&&(c=!1),s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:!1,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:l,success:c,executionTime:Date.now()-n}}catch(o){return o.name==="AbortError"||s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:`Error: ${o.message}`,success:false,executionTime:Date.now()-n}}}async execute(e,t,s,n){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 b=o.parallel.map(v=>this.executeSingleTool(v,t,n).then(k=>(s&&s(k),k))),_=await Promise.all(b);l=Date.now()-y;for(let v of _)a.set(v.id,v);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 b of o.sequential){if(n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted before ${b.function.name}`);break}let _=await this.executeSingleTool(b,t,n);if(s&&s(_),a.set(_.id,_),n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted after ${b.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 b=a.get(y.id);return b||{id:y.id,name:y.function.name,output:"Error: Result not found",success:false}}),p=Date.now()-i,d=u.reduce((y,b)=>y+(b.executionTime||0),0),m=d-p,h=d>0?d/p:1,f={totalTime:p,parallelTime:l,sequentialTime:c,timeSaved:m,speedup:h};return process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Performance Stats:"),console.log(` Total time: ${p}ms`),console.log(` Parallel time: ${l}ms`),console.log(` Sequential time: ${c}ms`),console.log(` Estimated sequential time: ${d}ms`),console.log(` Time saved: ${m}ms`),console.log(` Speedup: ${h.toFixed(2)}x`)),{results:u,stats:f}}getToolClassification(e){let t=r.isReadOnly(e),s=r.getMetadata(e);return {isReadOnly:t,category:s?.category||"unknown",canParallel:t}}static canExecuteInParallel(e){return e.every(t=>r.READ_ONLY_TOOLS.has(t))}static getReadOnlyTools(){return Array.from(r.READ_ONLY_TOOLS)}static getStateModifyingTools(){return Array.from(r.STATE_MODIFYING_TOOLS)}};var Xt={environment:{zh:r=>`## \u73AF\u5883
1142
+ `),o=/[\u4e00-\u9fa5]/.test(s)?Rn.systemZh:Rn.system,i=await t.llmProvider.chat([{role:"system",content:o},{role:"user",content:Rn.user(s)}],{model:t.model,temperature:.3});return ee(i.choices[0]?.message?.content)||null}catch(s){return g.warn("MessageCompressor",`Batch LLM compression failed: ${s.message}`),null}}};new As;var gg={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},jr=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...gg,...e},this.config.debug=this.config.debug||process.env.CLI_DEBUG==="1",this.toolCompressor=new $t({debug:this.config.debug}),this.messageCompressor=new As({debug:this.config.debug,toolCompressor:this.toolCompressor,minRecentMessages:this.config.minRecentMessages});}setLLMProvider(e,t){this.llmProvider=e,this.model=t;}setContextWindow(e){this.contextWindow=e,this.config.debug&&g.info("UnifiedCompressor",`Context window set to: ${e}`);}registerToolCompressor(e){g.info("UnifiedCompressor","Custom tool compressor registered");}setMessageCompressor(e){this.messageCompressor=e,g.info("UnifiedCompressor","Custom message compressor set");}async compressHistory(e,t,s){let n=Date.now(),o=We(e),i={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,tokenBudget:t,contextWindow:s?.contextWindow||this.contextWindow,iteration:s?.iteration,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,signal:s?.signal,debug:this.config.debug};if(this.config.debug&&g.debug("UnifiedCompressor",`\u5F00\u59CB\u538B\u7F29: ${e.length} \u6761\u6D88\u606F, ${o} tokens \u2192 \u9884\u7B97 ${t} tokens`),o<=t){let c=await this.compressLargeMessagesOnly(e,i);return this.config.debug&&g.debug("UnifiedCompressor",`\u5728\u9884\u7B97\u5185\uFF0C\u4EC5\u538B\u7F29\u5927\u6D88\u606F: ${c.savedTokens} tokens \u8282\u7701`),c}let a=await this.messageCompressor.compressMessages(e,i),l=Date.now()-n;return this.config.debug&&g.debug("UnifiedCompressor",`\u538B\u7F29\u5B8C\u6210 (${l}ms): ${a.originalCount} \u2192 ${a.compressedCount} \u6761, ${a.originalTokens} \u2192 ${a.compressedTokens} tokens (\u8282\u7701 ${a.savedTokens} tokens, ${(a.savedTokens/a.originalTokens*100).toFixed(1)}%)`),a}async compressLargeMessagesOnly(e,t){let s=We(e),n=[],o=0,i=0;for(let l of e)if(pt(l)>2e3&&l.role!=="system"){let u=await this.messageCompressor.compressMessage(l,t);n.push(u.message),u.usedLLM?o++:u.compressionRatio<1&&i++;}else n.push(l);let a=We(n);return {messages:n,originalCount:e.length,compressedCount:n.length,originalTokens:s,compressedTokens:a,savedTokens:s-a,stats:{droppedMessages:0,llmCompressedMessages:o,truncatedMessages:i,preservedMessages:e.length-o-i}}}async compressToolResult(e,t,s){let n={llmProvider:s?.llmProvider||this.llmProvider,model:s?.model||this.model,enableLLMCompression:s?.enableLLMCompression??this.config.enableLLMCompression,timeout:s?.timeout??this.config.llmTimeout,debug:this.config.debug};return (await this.toolCompressor.compress(e,t,n)).content}getStats(){return {config:this.config,hasLLMProvider:!!this.llmProvider}}};function fg(r,e){if(typeof r!="string")return null;let t=r.trim();if(!t.startsWith("{"))return null;try{let s=JSON.parse(t);return !s||typeof s!="object"||s.tool!==e||typeof s.status!="string"?null:s.status}catch{return null}}var Gr=class r{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 r.READ_ONLY_TOOLS.has(e)}static isStateModifying(e){return r.STATE_MODIFYING_TOOLS.has(e)}static getMetadata(e){return r.TOOL_METADATA.get(e)}analyzePlan(e){let t=[],s=[];for(let n of e){let o=n.function.name;r.isReadOnly(o)?t.push(n):s.push(n);}return {parallel:t,sequential:s,totalTools:e.length,parallelCount:t.length,sequentialCount:s.length}}async executeSingleTool(e,t,s){let n=Date.now();if(s?.aborted)return {id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n};let o=t.find(i=>i.name===e.function.name);if(!o)return {id:e.id,name:e.function.name,output:`Error: Tool ${e.function.name} not found`,success:false,executionTime:Date.now()-n};try{let i=e.function.arguments.trim(),a=i?JSON.parse(i):{},l=await o.function(a,{signal:s}),c=!0;return fg(l,e.function.name)==="error"&&(c=!1),s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:!1,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:l,success:c,executionTime:Date.now()-n}}catch(i){return i.name==="AbortError"||s?.aborted?{id:e.id,name:e.function.name,output:"Error: Operation cancelled",success:false,executionTime:Date.now()-n}:{id:e.id,name:e.function.name,output:`Error: ${i.message}`,success:false,executionTime:Date.now()-n}}}async execute(e,t,s,n){let o=Date.now(),i=this.analyzePlan(e);process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Execution Plan:"),console.log(` Total: ${i.totalTools} tools`),console.log(` Parallel (read-only): ${i.parallelCount} tools`),console.log(` Sequential (state-modifying): ${i.sequentialCount} tools`));let a=new Map,l=0,c=0;if(i.parallel.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${i.parallel.length} read-only tools in parallel...`);let b=i.parallel.map(v=>this.executeSingleTool(v,t,n).then(k=>(s&&s(k),k))),_=await Promise.all(b);l=Date.now()-y;for(let v of _)a.set(v.id,v);process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Parallel execution completed in ${l}ms`);}if(i.sequential.length>0){let y=Date.now();process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Executing ${i.sequential.length} state-modifying tools sequentially...`);for(let b of i.sequential){if(n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted before ${b.function.name}`);break}let _=await this.executeSingleTool(b,t,n);if(s&&s(_),a.set(_.id,_),n?.aborted){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[ParallelExecutor] Execution interrupted after ${b.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 b=a.get(y.id);return b||{id:y.id,name:y.function.name,output:"Error: Result not found",success:false}}),p=Date.now()-o,d=u.reduce((y,b)=>y+(b.executionTime||0),0),m=d-p,h=d>0?d/p:1,f={totalTime:p,parallelTime:l,sequentialTime:c,timeSaved:m,speedup:h};return process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log("[ParallelExecutor] Performance Stats:"),console.log(` Total time: ${p}ms`),console.log(` Parallel time: ${l}ms`),console.log(` Sequential time: ${c}ms`),console.log(` Estimated sequential time: ${d}ms`),console.log(` Time saved: ${m}ms`),console.log(` Speedup: ${h.toFixed(2)}x`)),{results:u,stats:f}}getToolClassification(e){let t=r.isReadOnly(e),s=r.getMetadata(e);return {isReadOnly:t,category:s?.category||"unknown",canParallel:t}}static canExecuteInParallel(e){return e.every(t=>r.READ_ONLY_TOOLS.has(t))}static getReadOnlyTools(){return Array.from(r.READ_ONLY_TOOLS)}static getStateModifyingTools(){return Array.from(r.STATE_MODIFYING_TOOLS)}};var Zt={environment:{zh:r=>`## \u73AF\u5883
1143
1143
  - \u5DE5\u4F5C\u76EE\u5F55: ${r}
1144
1144
  - Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED`,en:r=>`## Environment
1145
1145
  - Working directory: ${r}
@@ -1175,8 +1175,8 @@ ${o}`}],{model:t.model,temperature:.2});return ee(a.choices[0]?.message?.content
1175
1175
  - Reply in English
1176
1176
  - Brief confirmation after operations
1177
1177
  - Don't create unrequested files
1178
- - When encountering errors, verify with readfile first, don't blindly repeat operations`}};function Cc(r,e="zh"){let t=[];return t.push(Xt.environment[e](r)),t.push(""),t.push(Xt.toolUsage[e]),t.push(""),t.push(Xt.editRules[e]),t.push(""),t.push(Xt.toolResults[e]),t.push(""),t.push(Xt.specializedTools[e]),t.push(""),t.push(Xt.errorRecovery[e]),t.push(""),t.push(Xt.outputFormat[e]),t.join(`
1179
- `)}var hg={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1178
+ - When encountering errors, verify with readfile first, don't blindly repeat operations`}};function Ic(r,e="zh"){let t=[];return t.push(Zt.environment[e](r)),t.push(""),t.push(Zt.toolUsage[e]),t.push(""),t.push(Zt.editRules[e]),t.push(""),t.push(Zt.toolResults[e]),t.push(""),t.push(Zt.specializedTools[e]),t.push(""),t.push(Zt.errorRecovery[e]),t.push(""),t.push(Zt.outputFormat[e]),t.join(`
1179
+ `)}var yg={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1180
1180
 
1181
1181
  **\u6838\u5FC3\u539F\u5219**\uFF1A
1182
1182
  - \u5FEB\u901F\u7406\u89E3\u7528\u6237\u610F\u56FE
@@ -1222,10 +1222,10 @@ For complex multi-step tasks, use the update_plan tool to create an execution pl
1222
1222
  - Only one step can be in_progress at a time
1223
1223
  - Update plan status as work progresses
1224
1224
 
1225
- Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function Rc(r="zh"){return hg.identity[r]}function Gr(r){let{workDir:e,language:t="zh"}=r,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1225
+ Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function Mc(r="zh"){return yg.identity[r]}function Br(r){let{workDir:e,language:t="zh"}=r,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1226
1226
  Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED`:`Working directory: ${e}
1227
- Shell calls are independent; cd does not persist across calls`;return s.push(n),s.push(""),s.push(Rc(t)),s.push(""),s.push(Cc(e,t)),s.push(""),s.push(t==="zh"?"\u5F00\u59CB\u5DE5\u4F5C\u3002":"Start working."),s.join(`
1228
- `)}var gg=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1227
+ Shell calls are independent; cd does not persist across calls`;return s.push(n),s.push(""),s.push(Mc(t)),s.push(""),s.push(Ic(e,t)),s.push(""),s.push(t==="zh"?"\u5F00\u59CB\u5DE5\u4F5C\u3002":"Start working."),s.join(`
1228
+ `)}var bg=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1229
1229
 
1230
1230
  ## General
1231
1231
 
@@ -1341,7 +1341,7 @@ You are producing plain text that will later be styled by the CLI. Follow these
1341
1341
  * Optionally include line/column (1\u2011based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
1342
1342
  * Do not use URIs like file://, vscode://, or https://.
1343
1343
  * Do not provide range of lines
1344
- * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function No(r){let{workDir:e,language:t="zh",useCodexStyle:s=false}=r;return s?gg:Gr({workDir:e,language:t})}function Ec(r,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${r}
1344
+ * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function Fi(r){let{workDir:e,language:t="zh",useCodexStyle:s=false}=r;return s?bg:Br({workDir:e,language:t})}function Ac(r,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${r}
1345
1345
 
1346
1346
  \u9519\u8BEF\u4FE1\u606F: ${e}
1347
1347
 
@@ -1355,21 +1355,21 @@ Error: ${e}
1355
1355
  Suggestions:
1356
1356
  1. Re-read with readfile(path, for_edit=true)
1357
1357
  2. Ensure old_string matches exactly (spaces, newlines)
1358
- 3. If failing repeatedly, consider rewriting with write_file`}le();var Fo=class{history=[];maxHistory=20;interventionCount=0;hashArgs(e,t){let s={};e==="readfile"?Object.assign(s,t):e==="edit_file"||e==="Edit"?(s.file_path=t.file_path||t.path,t.old_string&&typeof t.old_string=="string"&&(s.old_string_prefix=t.old_string.substring(0,200))):e==="write_file"||e==="Write"?s.file_path=t.file_path||t.path:t.file_path?s.file_path=t.file_path:t.path?s.path=t.path:t.directory?s.directory=t.directory:Object.assign(s,t);let n=`${e}:${JSON.stringify(s)}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}record(e,t,s){let n=this.hashArgs(e,t),i=t.file_path||t.path||t.directory;if(process.env.CLI_DEBUG==="1"){let{cliLogger:o}=(le(),ia(jn));o.debug("LOOP_DETECTOR",`Recording ${e}:`,{hash:n.substring(0,8),argsPreview:JSON.stringify(t).substring(0,150),historyLengthBefore:this.history.length});}this.history.push({hash:n,toolName:e,args:t,timestamp:Date.now(),resultStatus:s,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 s=this.hashArgs(e,t),n=this.history.filter(i=>i.hash===s);if(process.env.CLI_DEBUG==="1"){let{cliLogger:i}=(le(),ia(jn));i.debug("LOOP_DETECTOR",`Detecting loop for ${e}:`,{hash:s.substring(0,8),historyCount:this.history.length,sameHashCount:n.length,args:JSON.stringify(t).substring(0,100)});}return n.length>=4?4:n.length>=3?3:n.length>=2?2:0}wasLastSuccessful(e,t){let s=this.hashArgs(e,t),n=[...this.history].reverse().find(i=>i.hash===s);return n?.resultStatus==="success"||n?.resultStatus==="already_done"}getLastFilePath(e,t){let s=this.hashArgs(e,t);return [...this.history].reverse().find(i=>i.hash===s)?.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,s){let n=this.getLastFilePath(t,s)||s.file_path||s.path||s.directory,i=this.wasLastSuccessful(t,s),o=this.getVerifyCommand(t,n),a=this.getAlternativeAction(t,n);switch(e){case 2:return {level:e,wasSuccessful:i,shouldTerminate:false,message:`
1358
+ 3. If failing repeatedly, consider rewriting with write_file`}le();var Ui=class{history=[];maxHistory=20;interventionCount=0;hashArgs(e,t){let s={};e==="readfile"?Object.assign(s,t):e==="edit_file"||e==="Edit"?(s.file_path=t.file_path||t.path,t.old_string&&typeof t.old_string=="string"&&(s.old_string_prefix=t.old_string.substring(0,200))):e==="write_file"||e==="Write"?s.file_path=t.file_path||t.path:t.file_path?s.file_path=t.file_path:t.path?s.path=t.path:t.directory?s.directory=t.directory:Object.assign(s,t);let n=`${e}:${JSON.stringify(s)}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}record(e,t,s){let n=this.hashArgs(e,t),o=t.file_path||t.path||t.directory;if(process.env.CLI_DEBUG==="1"){let{cliLogger:i}=(le(),ia(Gn));i.debug("LOOP_DETECTOR",`Recording ${e}:`,{hash:n.substring(0,8),argsPreview:JSON.stringify(t).substring(0,150),historyLengthBefore:this.history.length});}this.history.push({hash:n,toolName:e,args:t,timestamp:Date.now(),resultStatus:s,filePath:o}),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 s=this.hashArgs(e,t),n=this.history.filter(o=>o.hash===s);if(process.env.CLI_DEBUG==="1"){let{cliLogger:o}=(le(),ia(Gn));o.debug("LOOP_DETECTOR",`Detecting loop for ${e}:`,{hash:s.substring(0,8),historyCount:this.history.length,sameHashCount:n.length,args:JSON.stringify(t).substring(0,100)});}return n.length>=4?4:n.length>=3?3:n.length>=2?2:0}wasLastSuccessful(e,t){let s=this.hashArgs(e,t),n=[...this.history].reverse().find(o=>o.hash===s);return n?.resultStatus==="success"||n?.resultStatus==="already_done"}getLastFilePath(e,t){let s=this.hashArgs(e,t);return [...this.history].reverse().find(o=>o.hash===s)?.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,s){let n=this.getLastFilePath(t,s)||s.file_path||s.path||s.directory,o=this.wasLastSuccessful(t,s),i=this.getVerifyCommand(t,n),a=this.getAlternativeAction(t,n);switch(e){case 2:return {level:e,wasSuccessful:o,shouldTerminate:false,message:`
1359
1359
  [SYSTEM NOTICE]
1360
1360
  You have called "${t}" ${this.getCallCount(t,s)} times with similar arguments.
1361
- ${i?"\u26A0\uFE0F Previous calls already returned SUCCESS.":""}
1361
+ ${o?"\u26A0\uFE0F Previous calls already returned SUCCESS.":""}
1362
1362
 
1363
1363
  STOP and think:
1364
1364
  1. ${a}
1365
1365
  2. If you already have the information you need, proceed with your task
1366
1366
  3. Do NOT call ${t} again with the same arguments
1367
1367
 
1368
- ${o?`To verify: ${o}`:""}
1369
- `.trim()};case 3:return {level:e,wasSuccessful:i,shouldTerminate:false,message:`
1368
+ ${i?`To verify: ${i}`:""}
1369
+ `.trim()};case 3:return {level:e,wasSuccessful:o,shouldTerminate:false,message:`
1370
1370
  [SYSTEM WARNING]
1371
1371
  You have called "${t}" ${this.getCallCount(t,s)} times with identical arguments.
1372
- ${i?"\u2705 Previous calls returned SUCCESS - the operation already completed!":""}
1372
+ ${o?"\u2705 Previous calls returned SUCCESS - the operation already completed!":""}
1373
1373
 
1374
1374
  \u{1F6D1} REQUIRED ACTION:
1375
1375
  1. STOP calling ${t}
@@ -1377,7 +1377,7 @@ ${i?"\u2705 Previous calls returned SUCCESS - the operation already completed!":
1377
1377
  3. If stuck, ask the user for help
1378
1378
 
1379
1379
  Next ${t} call with same arguments will TERMINATE the task.
1380
- `.trim()};case 4:return {level:e,wasSuccessful:i,shouldTerminate:true,message:i?`
1380
+ `.trim()};case 4:return {level:e,wasSuccessful:o,shouldTerminate:true,message:o?`
1381
1381
  [TASK COMPLETED]
1382
1382
  The "${t}" operation has already succeeded (called ${this.getCallCount(t,s)} times).
1383
1383
 
@@ -1391,7 +1391,7 @@ Please:
1391
1391
  - Check if the file/path exists
1392
1392
  - Verify your approach
1393
1393
  - Try a different method
1394
- `.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 s=this.hashArgs(e,t);return this.history.filter(n=>n.hash===s).length}reset(){this.history=[],this.interventionCount=0;}getHistory(){return [...this.history]}getRecentDuplicates(){let e=new Map;for(let t of this.history){let s=`${t.toolName}:${t.hash}`;e.set(s,(e.get(s)||0)+1);}return e}};function Ic(){return new Fo}var As=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 s=e.name,n=this.getToolCategory(e),i=this.getToolPermission(e);if(i==="deny")return {allowed:false,source:"config",reason:this.toolPermissions.get(s)?.reason||`Tool "${s}" is denied`};if(i==="allow")return {allowed:true,source:"config"};let o=this.checkMemory(s);if(o)return {allowed:o.decision,source:"remembered",reason:o.decision?void 0:"User previously denied this tool"};if(!this.config.approvalHandler)return {allowed:true,source:"config",reason:"No approval handler configured - auto-approved"};try{let a=this.toolPermissions.get(s),l=await this.config.approvalHandler({toolName:s,toolCategory:n,args:t,reason:a?.reason,allowRemember:a?.allowRemember??!0});return l.remember&&this.saveMemory(s,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 s=this.config.memoryExpirationMs?Date.now()+this.config.memoryExpirationMs:void 0;this.permissionMemory.set(e,{toolName:e,decision:t,timestamp:Date.now(),expiresAt:s});}clearMemory(e){e?this.permissionMemory.delete(e):this.permissionMemory.clear();}setApprovalHandler(e){this.config.approvalHandler=e;}};var Nt=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())}};var Rn=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1394
+ `.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 s=this.hashArgs(e,t);return this.history.filter(n=>n.hash===s).length}reset(){this.history=[],this.interventionCount=0;}getHistory(){return [...this.history]}getRecentDuplicates(){let e=new Map;for(let t of this.history){let s=`${t.toolName}:${t.hash}`;e.set(s,(e.get(s)||0)+1);}return e}};function Pc(){return new Ui}var Ps=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 s=e.name,n=this.getToolCategory(e),o=this.getToolPermission(e);if(o==="deny")return {allowed:false,source:"config",reason:this.toolPermissions.get(s)?.reason||`Tool "${s}" is denied`};if(o==="allow")return {allowed:true,source:"config"};let i=this.checkMemory(s);if(i)return {allowed:i.decision,source:"remembered",reason:i.decision?void 0:"User previously denied this tool"};if(!this.config.approvalHandler)return {allowed:true,source:"config",reason:"No approval handler configured - auto-approved"};try{let a=this.toolPermissions.get(s),l=await this.config.approvalHandler({toolName:s,toolCategory:n,args:t,reason:a?.reason,allowRemember:a?.allowRemember??!0});return l.remember&&this.saveMemory(s,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 s=this.config.memoryExpirationMs?Date.now()+this.config.memoryExpirationMs:void 0;this.permissionMemory.set(e,{toolName:e,decision:t,timestamp:Date.now(),expiresAt:s});}clearMemory(e){e?this.permissionMemory.delete(e):this.permissionMemory.clear();}setApprovalHandler(e){this.config.approvalHandler=e;}};var Nt=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())}};var En=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1395
1395
  - Read files and search code
1396
1396
  - Analyze and understand the codebase
1397
1397
  - Answer questions about the project
@@ -1399,7 +1399,7 @@ Please:
1399
1399
 
1400
1400
  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.
1401
1401
 
1402
- 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(n=>t.includes(n))}};var In=class{mode="agent";filterTools(e){return e}getSystemPrompt(){return `You are in AGENT mode (standard). You have access to:
1402
+ 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(n=>t.includes(n))}};var Mn=class{mode="agent";filterTools(e){return e}getSystemPrompt(){return `You are in AGENT mode (standard). You have access to:
1403
1403
  - Read and analyze the codebase
1404
1404
  - Make file edits and create new files
1405
1405
  - Run commands and scripts
@@ -1410,7 +1410,7 @@ Some dangerous operations may require user approval before execution. When reque
1410
1410
  - Mention any potential risks
1411
1411
  - Wait for user confirmation before proceeding
1412
1412
 
1413
- 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"}};var Mn=class{mode="auto";filterTools(e){return e}getSystemPrompt(){return `You are in AUTO mode (automatic). You have full access to:
1413
+ 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"}};var An=class{mode="auto";filterTools(e){return e}getSystemPrompt(){return `You are in AUTO mode (automatic). You have full access to:
1414
1414
  - Read and write files
1415
1415
  - Execute commands
1416
1416
  - Make changes to the project
@@ -1424,33 +1424,33 @@ All operations will execute automatically without user confirmation. You should:
1424
1424
 
1425
1425
  \u26A0\uFE0F Important: Since there's no approval step, double-check your actions before executing.
1426
1426
 
1427
- Available operations: All tools (auto-approved).`}shouldAutoApprove(){return true}getDescription(){return "Automatic mode - All operations execute without approval (use with caution)"}getIcon(){return "\u26A1"}};Nt.register(new Rn);Nt.register(new In);Nt.register(new Mn);function Uo(r){return Nt.getStrategy(r)}var Ac=2e4,yg=15e3;function Dc(r,e){let t=process.env[r];if(!t)return e;let s=Number(t);return !Number.isFinite(s)||s<=0?e:Math.floor(s)}function Pc(r,e){let t=r??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function Br(){let r=new Error("Request aborted");return r.name="AbortError",r.code="ERR_CANCELED",r.category="canceled",r}async function Oc(r,e){if(r?.aborted)throw Br();return e()}function bg(r,e){let t=Math.round(e/1e3),s=new Error(r==="first_chunk"?`Stream timeout: no response for ${t}s`:`Stream timeout: no data for ${t}s`);return s.code="STREAM_TIMEOUT",s.category="retryable_network",s.isNetworkInterrupt=true,s.streamTimeoutPhase=r,s.timeoutMs=e,s}var _g=Dc("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),wg=Dc("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),vg=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Lc(r,e=yg){if(!r||r.length<=e)return r;let t=r.split(`
1428
- `).length,s=r.length,n=Math.floor(e*.4),i=Math.floor(e*.4),o=n,a=r.length-i;for(;o>0&&(r.charCodeAt(o)&192)===128;)o--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,o),c=r.slice(a),p=`
1427
+ Available operations: All tools (auto-approved).`}shouldAutoApprove(){return true}getDescription(){return "Automatic mode - All operations execute without approval (use with caution)"}getIcon(){return "\u26A1"}};Nt.register(new En);Nt.register(new Mn);Nt.register(new An);function ji(r){return Nt.getStrategy(r)}var Lc=2e4,wg=15e3;function Fc(r,e){let t=process.env[r];if(!t)return e;let s=Number(t);return !Number.isFinite(s)||s<=0?e:Math.floor(s)}function Dc(r,e){let t=r??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function Wr(){let r=new Error("Request aborted");return r.name="AbortError",r.code="ERR_CANCELED",r.category="canceled",r}async function $c(r,e){if(r?.aborted)throw Wr();return e()}function vg(r,e){let t=Math.round(e/1e3),s=new Error(r==="first_chunk"?`Stream timeout: no response for ${t}s`:`Stream timeout: no data for ${t}s`);return s.code="STREAM_TIMEOUT",s.category="retryable_network",s.isNetworkInterrupt=true,s.streamTimeoutPhase=r,s.timeoutMs=e,s}var Tg=Fc("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),xg=Fc("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Sg=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Nc(r,e=wg){if(!r||r.length<=e)return r;let t=r.split(`
1428
+ `).length,s=r.length,n=Math.floor(e*.4),o=Math.floor(e*.4),i=n,a=r.length-o;for(;i>0&&(r.charCodeAt(i)&192)===128;)i--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,i),c=r.slice(a),p=`
1429
1429
 
1430
1430
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1431
1431
 
1432
- `;return l+p+c}var Wr=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;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.contextInjection=e.contextInjection,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 Fr(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new jr,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new Ur({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=Uo(this.currentMode),this.permissionManager=e.permissionManager??new As({defaultPermission:"ask"}),this.loopDetector=Ic(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async s=>({approved:await t({id:"",name:s.toolName,args:s.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=Uo(e),g.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,s){if(s&&s>0)return s;let i=e&&e>0?e:19e4,o=.7,a=Math.floor(i*o),l=Math.min(t??Ac,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=${s}, tailBudget=${t??Ac}, safety=${o})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(vg){for await(let o of e)yield o;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((o,a)=>{t.aborted?a(Br()):t.addEventListener("abort",()=>a(Br()),{once:true});}):null,i=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Br()}let o=i?wg:_g,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(bg(i?"idle":"first_chunk",o));},o);});try{let c=await Promise.race(n?[s.next(),l,n]:[s.next(),l]);if(a&&clearTimeout(a),c.done)return;i=!0,yield c.value;}catch(c){if(a&&clearTimeout(a),s.return)try{await s.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&g.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),s=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(s.stats.droppedMessages>0||s.stats.llmCompressedMessages>0){this.memory.setMessages(s.messages);let n=this.compressionMode==="async"?"Async":"Sync",i=(s.originalTokens/1e3).toFixed(1),o=(s.compressedTokens/1e3).toFixed(1),a=(s.savedTokens/1e3).toFixed(1),l=s.originalCount,c=s.compressedCount;g.info("Context",`[${n}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${i}K \u2192 ${c}\u6761/${o}K (\u8282\u7701 ${a}K, \u4E22\u5F03${s.stats.droppedMessages}\u6761, LLM\u538B\u7F29${s.stats.llmCompressedMessages}\u6761)`),s.debugInfo&&s.debugInfo.forEach(u=>g.debug("Context",u));}return s}setCompressionMode(e){this.compressionMode=e,g.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)}async getContextInjection(e){if(!this.contextInjection)return null;let s=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return s||null}shouldIncludeLastRun(e){let t=e.trim().toLowerCase();return t?/上次|之前|前面|上一步|上轮|继续|回顾|resume|continue|previous|last time/.test(t):false}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,s){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(g.debug("MK",` hasSignal: ${!!s}`),g.debug("RUNNER","========================================"),g.debug("RUNNER","=== runner.run ENTRY ==="),g.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),g.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),g.debug("RUNNER",` hasSignal: ${!!s}`)),te.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let n=this.createRunContext(e,0),i=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(C=>C.role==="user"||C.role==="assistant"),o=!i||this.shouldIncludeLastRun(e);n.userData={...n.userData??{},hasConversation:i,includeLastRun:o},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 Vt.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let a=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",a?.length||0),console.log("[RUNNER] dynamicInstructions START:",a?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",a?.substring(a.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",a?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",a?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(C=>C.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),a&&this.memory.add({role:"system",content:a});else if(!u){let C=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:C}),this.memory.add({role:"system",content:a}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let w=await go(this.workspacePath);w&&this.memory.add({role:"system",content:w});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let C=[{type:"text",text:e},...t.map(w=>({type:"image_url",image_url:{url:w,detail:"auto"}}))];this.memory.add({role:"user",content:C});}else this.memory.add({role:"user",content:e});let p=Date.now(),d=0,m="",h=0,f={totalTokens:0,promptTokens:0,completionTokens:0},y=false,b=0,_=null,v=new Map,k=0,R=kt.streamMaxRetries,O=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:pc,W=O===0||O===1/0,F=Pc(this.config.maxToolCalls,dc),S=Pc(this.config.maxRuntimeMs,mc);for(;W||d<O;){if(s?.aborted){_="interrupted",y=true,yield {type:"error",error:"Task interrupted by user."};break}if(S!==null&&Date.now()-p>=S){_="runtime_limit",y=true,yield {type:"error",error:`Reached max runtime (${qe(S)}). Please summarize progress and ask whether to continue.`};break}if(F!==null&&h>=F){_="tool_call_limit",y=true,yield {type:"error",error:`Reached max tool calls (${F}). Please summarize progress and ask whether to continue.`};break}d++;let C=null;if(this.maxInputTokens){let T=We(this.memory.getMessagesForLLM()),M=this.maxInputTokens*.97;T>M&&(C=await this.applyContextWindow(d));}C&&(C.stats.droppedMessages>0||C.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:C.originalCount,keptMessages:C.messages.length,droppedMessages:C.stats.droppedMessages,compressedMessages:C.stats.llmCompressedMessages,originalTokens:C.originalTokens,finalTokens:C.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:C.stats.llmCompressedMessages>0,timestamp:Date.now()});let w=this.memory.checkContextHealth();if((w.warnings.length>0||w.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:w.totalTokens,toolResultTokens:w.toolResultTokens,toolResultRatio:w.toolResultRatio,messageCount:w.messageCount,toolMessageCount:w.toolMessageCount,warnings:w.warnings,shouldCompress:w.shouldCompress,shouldCleanup:w.shouldCleanup,byType:w.byType},event_type:"context_health"},w.shouldCleanup&&w.byType.ephemeral.count>5)){let T=this.memory.cleanupEphemeral();T>0&&g.info("Runner",`Cleaned ${T} ephemeral messages`);}g.debug("Runner",this.memory.getTokenSummary()),te.agentIteration(d,"thinking"),yield {type:"iteration_start",iteration:d};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let T=this.memory.getMessagesForLLM();if(g.info("LLM",`Request: model=${this.model}, messages=${T.length}, tools=${this.tools.length}`),g.debug("LLM","Request messages",{messageCount:T.length,lastMessage:T[T.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let P=T.filter(K=>K.role==="system");console.log("[RUNNER] System messages count:",P.length);for(let K=0;K<P.length;K++){let U=P[K].content,ne=typeof U=="string"?U:JSON.stringify(U);console.log(`[RUNNER] System[${K}] length:`,ne?.length||0),console.log(`[RUNNER] System[${K}] contains \u534F\u4F5C\u6A21\u5F0F:`,ne?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${K}] contains delegate_task:`,ne?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${K}] preview:`,ne?.substring(0,300)||"");}}let M=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${M.length}/${this.tools.length}`);let B=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:M,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,signal:s}),E="",L="",N=[],$=[],G="",X={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let P of this.withStreamWatchdog(B,s)){if(P.type==="stream_retry"){yield P;continue}if(P.type==="stream_recovered"){yield {type:"stream_recovered",attempt:P.attempt,maxRetries:P.maxRetries};continue}yield {type:"raw_response_event",data:P,event_type:P.choices?.[0]?.delta?"response.delta":"response.chunk"};let K=P.choices?.[0]?.delta;if(P.usage){X={prompt_tokens:P.usage.prompt_tokens||X.prompt_tokens,completion_tokens:P.usage.completion_tokens||X.completion_tokens,total_tokens:P.usage.total_tokens||X.total_tokens,cached_tokens:P.usage.cached_tokens,cache_read_input_tokens:P.usage.cache_read_input_tokens,cache_creation_input_tokens:P.usage.cache_creation_input_tokens,prompt_tokens_details:P.usage.prompt_tokens_details},f={promptTokens:X.prompt_tokens,completionTokens:X.completion_tokens,totalTokens:X.total_tokens};let U=!!P.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:X,is_final:U};}if(K){if(K.reasoning_content&&(L+=K.reasoning_content,yield {type:"reasoning_delta",delta:K.reasoning_content}),K.reasoning_complete&&(yield {type:"reasoning_complete"}),K.content&&(E+=K.content,m=E,yield {type:"text_delta",delta:K.content}),K.tool_calls)for(let U of K.tool_calls){let ne=U.index;$[ne]||($[ne]={id:U.id||`call_${Math.floor(Date.now())}_${ne}`,type:"function",function:{name:"",arguments:""}}),U.id&&($[ne].id=U.id),U.function?.name&&($[ne].function.name=U.function.name),U.function?.arguments&&($[ne].function.arguments+=U.function.arguments,yield {type:"tool_call_delta",id:$[ne].id,name:$[ne].function.name,arguments_delta:U.function.arguments}),U.thoughtSignature&&($[ne].thoughtSignature=U.thoughtSignature);}P.choices?.[0]?.finish_reason&&(G=P.choices[0].finish_reason),P.thinking_blocks&&Array.isArray(P.thinking_blocks)&&(N=P.thinking_blocks.map(U=>({type:U.type,thinking:U.thinking,signature:U.signature,data:U.data})));}}E&&(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 A={role:"assistant",content:(E||"").trimEnd()};if(L&&(A.reasoning_content=L),N.length>0&&(A.thinking_blocks=N),$.length>0&&(A.tool_calls=$.map(P=>({...P,function:{...P.function,arguments:P.function.arguments}}))),this.memory.add(A),process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${$.length}, fullContent.length=${E.length}`),$.length>0){let P=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let x of $){let D=x.function.arguments||"";if(P.test(D)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${x.function.name}`),console.error(`[Runner] Arguments preview: ${D.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:x.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.'},y=!0;break}}if(y)break;if(F!==null&&h+$.length>F){_="tool_call_limit",y=!0,yield {type:"error",error:`Tool call budget exceeded (max ${F}, requested ${$.length}). Please summarize progress and ask whether to continue.`};break}if($.length>1){let x=$.map(H=>H.function.name),D=[...new Set(x)];D.length===1&&x.length>1?g.info("RUNNER",`\u{1F504} Parallel calls: ${x.length}x ${D[0]} (different parameters)`):g.info("RUNNER",`\u{1F504} Parallel calls: ${x.join(", ")}`);}for(let x of $){h++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:x.id,name:x.function.name,arguments:x.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:x.id,name:x.function.name};let H=!1;try{x.function.arguments&&(JSON.parse(x.function.arguments),H=!0);}catch(V){te.toolError(x.function.name,`Invalid JSON arguments (${V.message}): ${x.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${x.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${x.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${x.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${x.function.arguments.substring(Math.max(0,x.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:x.id,name:x.function.name,arguments:x.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:x.id,name:x.function.name,arguments:x.function.arguments},event_type:"response.function_call_arguments.done"};}let K=new Set,U=null,ne=$.length>1;process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`Processing ${$.length} tool call(s)`,{isParallel:ne,tools:$.map(x=>x.function.name)});for(let x of $){let D={};try{let I=x.function.arguments?.trim()||"";D=I?JSON.parse(I):{};}catch(I){te.toolError(x.function.name,`Loop detection skipped: invalid JSON (${I.message})`);continue}let H=this.loopDetector.detect(x.function.name,D);if(this.loopDetector.record(x.function.name,D),H===0)continue;let V=this.loopDetector.generateIntervention(H,x.function.name,D);if(this.memory.add({role:"system",content:V.message}),H===2&&la(x.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.function.name,output:V.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:x.function.name,output:V.message,success:!1},this.memory.addToolResult(x.id,x.function.name,V.message),this.loopDetector.updateLastStatus("error"),K.add(x.id),V.shouldTerminate){U=V;break}}if(U&&(yield {type:"error",error:U.message},y=!0),y)break;let Te=K.size>0?$.filter(x=>!K.has(x.id)):$,Q=new Set(this.modeStrategy.filterTools(this.tools).map(x=>x.name)),ie=x=>x.replace(/["\s/>]+$/g,"").trim(),se=[];for(let x of Te){let D=ie(x.function.name);if(Q.has(D)||Q.has(x.function.name)){se.push(x);continue}let H=`Tool "${x.function.name}" is not allowed in ${this.currentMode} mode`;te.toolError(x.function.name,H),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.function.name,output:H,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:x.function.name,output:H,success:!1},this.memory.addToolResult(x.id,x.function.name,H),g.info("PERMISSION",`Tool blocked by mode: ${x.function.name} - ${H}`);}if(se.length===0)continue;let ae=se.map(x=>({id:x.id,type:"function",function:{name:x.function.name,arguments:x.function.arguments}})),J=!1;if(process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${ae.length}`),!this.modeStrategy.shouldAutoApprove()){let x=new Set;try{for(let D of se)try{let H=D.function.arguments.trim(),V=H?JSON.parse(H):{},we=this.tools.find(I=>I.name===D.function.name);if(!we){g.warn("RUNNER",`Tool not found: ${D.function.name}`);continue}let xe=await Oc(s,async()=>this.permissionManager.checkPermission(we,V));if(!xe.allowed){x.add(D.id);let I=xe.reason||`Tool "${D.function.name}" was denied`;te.toolError(D.function.name,I),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:D.id,name:D.function.name,output:I,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:D.function.name,output:I,success:!1};let q=JSON.stringify({type:"ephemeral",status:"error",tool:D.function.name,summary:"Tool execution denied by user",error:I,final:!0});this.memory.addToolResult(D.id,D.function.name,q),g.info("PERMISSION",`Tool denied: ${D.function.name} - ${I}`),J=!0;}}catch(H){if(H?.name==="AbortError"||H?.code==="ERR_CANCELED")throw H;te.toolError(D.function.name,H?.message||"permission check failed");}}catch(D){if(D?.name==="AbortError"||D?.code==="ERR_CANCELED"){g.info("RUNNER","Interrupt detected during permission check"),y=!0;break}throw D}if(se=se.filter(D=>!x.has(D.id)),ae=ae.filter(D=>!x.has(D.id)),J){g.info("RUNNER","User denied tool - terminating current turn");break}if(ae.length===0)continue}if(process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${ae.length}, userDeniedTool=${J}`),this.toolInputGuardrails.length>0){let x=new Set;try{for(let D of se)try{let H=D.function.arguments.trim(),V=H?JSON.parse(H):{},we={tool_name:D.function.name,tool_input:V,tool_call_id:D.id},xe=this.tools.find(j=>j.name===D.function.name);if(!xe)continue;this.runContext.iteration=d;let I=await Oc(s,async()=>Vt.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:we,agent_name:this.agentName,tool:xe}));if(!I.should_execute){x.add(D.id);let j=I.rejection_message||`Tool ${D.function.name} was blocked by guardrail`;te.toolError(D.function.name,`Blocked by guardrail: ${j}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:D.id,name:D.function.name,output:j,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:D.function.name,output:j,success:!1},this.memory.addToolResult(D.id,D.function.name,j),Mo(this.runContext,D.function.name,V,!1);}}catch(H){if(H?.name==="AbortError"||H?.code==="ERR_CANCELED")throw H;if(H instanceof st){te.toolError(D.function.name,`Guardrail tripwire triggered: ${H.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${D.function.name}: ${H.message}`},y=!0;break}te.toolError(D.function.name,`Guardrail check failed: ${H?.message}`);}}catch(D){if(D?.name==="AbortError"||D?.code==="ERR_CANCELED"){g.info("RUNNER","Interrupt detected during guardrails check"),y=!0;break}throw D}if(y)break;if(se=se.filter(D=>!x.has(D.id)),ae=ae.filter(D=>!x.has(D.id)),ae.length===0)continue}process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${ae.length}`);let pe=await this.parallelExecutor.execute(ae,this.tools,x=>{if(te.toolCall(x.name,{}),x.success){let H=typeof x.output=="string"?x.output.length:JSON.stringify(x.output).length;te.toolResult(x.name,!0,H,x.executionTime||0);}else te.toolError(x.name,x.output);let D={type:"tool_call_output_item",id:x.id,name:x.name,output:x.output,success:x.success,timestamp:Date.now()};},s);for(let x of pe.results){if(this.toolMetricsHistory.push({name:x.name,duration:x.executionTime||0,success:x.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.name,output:x.output,success:x.success,timestamp:Date.now()}},yield {type:"tool_output",name:x.name,output:x.output,success:x.success},x.name==="update_plan"&&x.success)try{g.info("PLAN_UPDATE","\u{1F525} Detected update_plan tool call",{resultId:x.id,toolCallsCount:$.length});let I=$.find(j=>j.id===x.id);if(I){g.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:I.id,argsLength:I.function.arguments?.length});let j=JSON.parse(I.function.arguments||"{}");g.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!j.explanation,planSteps:j.plan?.length}),yield {type:"plan_update",explanation:j.explanation,plan:j.plan,timestamp:Date.now()},g.info("PLAN_UPDATE","\u2705 Emitted plan_update event");}else g.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:x.id,availableIds:$.map(j=>j.id)});}catch(I){g.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:I});}let H=typeof x.output=="string"?Lc(x.output):Lc(JSON.stringify(x.output));H=this.enrichToolResult(H,x.name,x.executionTime||0);let V=$.find(I=>I.id===x.id),we={};if(V)try{we=JSON.parse(V.function.arguments||"{}");}catch{}if(this.toolOutputGuardrails.length>0)try{let I=this.tools.find(j=>j.name===x.name);if(I){let j={tool_name:x.name,tool_input:we,tool_call_id:x.id},q=await Vt.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:j,agent_name:this.agentName,tool:I,output:x.output});q.should_use_output||(H=q.replacement_message||"[Output blocked by guardrail]",te.toolError(x.name,"Output blocked by guardrail"));}}catch(I){I instanceof st&&te.toolError(x.name,`Output guardrail tripwire triggered: ${I.message}`);}if(!x.success&&typeof x.output=="string"){let I=x.output.toLowerCase();if(I.includes("operation cancelled")||I.includes("command interrupted")||I.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),g.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),y=!0;break}}Mo(this.runContext,x.name,we,x.success),g.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${x.name}`,{toolName:x.name,success:x.success,rawLength:typeof x.output=="string"?x.output.length:JSON.stringify(x.output).length,truncatedLength:H.length,outputPreview:H.substring(0,500)}),this.memory.addToolResult(x.id,x.name,H);let xe=x.success?"success":"error";try{let I=typeof x.output=="string"?x.output:JSON.stringify(x.output),j=JSON.parse(I);j.status==="already_done"?xe="already_done":j.status==="success"?xe="success":j.status==="error"&&(xe="error");}catch{}if(this.loopDetector.updateLastStatus(xe),xe==="error"){let I=(v.get(x.name)||0)+1;if(v.set(x.name,I),x.name==="edit_file"&&(I===2||I===3)){let j=typeof x.output=="string"?x.output:JSON.stringify(x.output),q=x.name,ye=Ec(q,j);this.memory.add({role:"system",content:ye});}}else v.set(x.name,0);}if(d>0&&d%5===0){let x=this.buildPerformanceHint();x&&(this.memory.add({role:"system",content:x}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",x));}if(process.env.CLI_DEBUG_CONSOLE==="1"&&pe.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:pe.stats},event_type:"parallel_execution.stats"}),s?.aborted){y=!0;break}continue}else {if(this.plannerMode&&b<2&&this.shouldAutoContinuePlan(E)){b++;let P=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:E,followup_prompt:P,count:b},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:P});continue}if(E&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:E,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(g.info("RUNNER","=== Loop Exit: No Tool Calls ==="),g.info("RUNNER",`Finish Reason: ${G}`),g.info("RUNNER",`Content Length: ${E.length}`),g.info("RUNNER",`Content Preview: ${E.slice(0,300)}`),g.info("RUNNER",`Tool Calls Count: ${$.length}`),g.info("RUNNER",`Iteration: ${d}`)),this.structuredValidator){let P=this.structuredValidator.validate(E);if(P.ok)m=P.normalized||E,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:m,parsed:P.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:P.reason,message:P.message,errors:P.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(P)}),m="";continue}}else m=E;this.outputGuardrails.length>0&&m&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Vt.runOutputGuardrails(this.outputGuardrails,n,this.agentName,m),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});break}}catch(T){if(T?.type==="stream_retry"){yield T;continue}let M=T instanceof me?T:tt(T);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:M.category,code:M.code,retryable:M.retryable,message:M.message}),M.category==="canceled"){_="interrupted",y=true,yield {type:"error",error:"Task interrupted by user."};break}if(M.retryable&&k<R){k++;let N=kn(M.category,k,M.retryAfter),$=M.category==="retryable_rate_limit",G=M.code==="STREAM_TIMEOUT",X=M.category==="retryable_network"||M.category==="retryable_stream";g.warn("RUNNER",`Retrying after ${qe(N)} (attempt ${k}/${R}): ${M.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:M.message,errorCode:M.code,attempt:k,maxRetries:R,delayMs:N,isRateLimit:$,isStreamTimeout:G,isNetworkError:X},event_type:"runner.stream_retry"},await Is(N),d--;continue}let B=$r(M),E=M.message;B&&!E.includes(B)&&(E=`${E}
1432
+ `;return l+p+c}var Hr=class{llmProvider;providerName;model;tools;memory;config;agentName;agentDescription;instructions;contextInjection;userData;plannerMode;inputGuardrails=[];outputGuardrails=[];toolInputGuardrails=[];toolOutputGuardrails=[];structuredOutput;structuredValidator;maxInputTokensOverride;maxInputTokens;minHistoryMessages;parallelExecutor;unifiedCompressor;compressionMode;toolMetricsHistory=[];workspacePath;disableSystemPrompt;runContext;permissionManager;modeStrategy;currentMode;loopDetector;enablePlanMode;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.contextInjection=e.contextInjection,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 Ur(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Gr,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new jr({debug:process.env.CLI_DEBUG==="1",minRecentMessages:this.minHistoryMessages,enableLLMCompression:true}),this.disableSystemPrompt=e.disableSystemPrompt??false,this.unifiedCompressor.setLLMProvider(this.llmProvider,this.model),e.contextWindow&&this.unifiedCompressor.setContextWindow(e.contextWindow),this.currentMode=e.config.mode??"agent",this.modeStrategy=ji(this.currentMode),this.permissionManager=e.permissionManager??new Ps({defaultPermission:"ask"}),this.loopDetector=Pc(),this.enablePlanMode=e.enablePlanMode??true,e.approvalHandler){let t=e.approvalHandler;this.permissionManager.setApprovalHandler(async s=>({approved:await t({id:"",name:s.toolName,args:s.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=ji(e),g.info("Runner",`Mode switched to: ${e}`);}getMode(){return this.currentMode}getPermissionManager(){return this.permissionManager}computeMaxInputTokens(e,t,s){if(s&&s>0)return s;let o=e&&e>0?e:19e4,i=.7,a=Math.floor(o*i),l=Math.min(t??Lc,Math.floor(o*.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=${o}, override=${s}, tailBudget=${t??Lc}, safety=${i})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Sg){for await(let i of e)yield i;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((i,a)=>{t.aborted?a(Wr()):t.addEventListener("abort",()=>a(Wr()),{once:true});}):null,o=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Wr()}let i=o?xg:Tg,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(vg(o?"idle":"first_chunk",i));},i);});try{let c=await Promise.race(n?[s.next(),l,n]:[s.next(),l]);if(a&&clearTimeout(a),c.done)return;o=!0,yield c.value;}catch(c){if(a&&clearTimeout(a),s.return)try{await s.return();}catch{}throw c?.code==="STREAM_TIMEOUT"&&g.warn("RUNNER",`[watchdog] ${c.message}`),c}}}async applyContextWindow(e=0){if(!this.maxInputTokens)return null;let t=this.memory.getMessagesForLLM(),s=await this.unifiedCompressor.compressHistory(t,this.maxInputTokens,{iteration:e,enableLLMCompression:true});if(s.stats.droppedMessages>0||s.stats.llmCompressedMessages>0){this.memory.setMessages(s.messages);let n=this.compressionMode==="async"?"Async":"Sync",o=(s.originalTokens/1e3).toFixed(1),i=(s.compressedTokens/1e3).toFixed(1),a=(s.savedTokens/1e3).toFixed(1),l=s.originalCount,c=s.compressedCount;g.info("Context",`[${n}] \u538B\u7F29\u5B8C\u6210: ${l}\u6761/${o}K \u2192 ${c}\u6761/${i}K (\u8282\u7701 ${a}K, \u4E22\u5F03${s.stats.droppedMessages}\u6761, LLM\u538B\u7F29${s.stats.llmCompressedMessages}\u6761)`),s.debugInfo&&s.debugInfo.forEach(u=>g.debug("Context",u));}return s}setCompressionMode(e){this.compressionMode=e,g.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)}async getContextInjection(e){if(!this.contextInjection)return null;let s=(typeof this.contextInjection=="string"?this.contextInjection:await this.contextInjection(e,{name:this.agentName,description:this.agentDescription}))?.trim();return s||null}shouldIncludeLastRun(e){let t=e.trim().toLowerCase();return t?/上次|之前|前面|上一步|上轮|继续|回顾|resume|continue|previous|last time/.test(t):false}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,s){this.runContext={task:e,timestamp:Date.now(),currentTime:new Date,iteration:0,userData:this.userData},this.loopDetector.reset(),process.env.CLI_DEBUG==="1"&&(g.debug("MK",` hasSignal: ${!!s}`),g.debug("RUNNER","========================================"),g.debug("RUNNER","=== runner.run ENTRY ==="),g.debug("RUNNER",` task: "${e?.substring(0,50)}..."`),g.debug("RUNNER",` hasImages: ${!!t&&t.length>0}`),g.debug("RUNNER",` hasSignal: ${!!s}`)),te.agentStart(e),yield {type:"agent_updated_stream_event",new_agent:{name:this.agentName}};let n=this.createRunContext(e,0),o=this.memory.hasConversationMessages?.()??this.memory.getMessagesForLLM().some(C=>C.role==="user"||C.role==="assistant"),i=!o||this.shouldIncludeLastRun(e);n.userData={...n.userData??{},hasConversation:o,includeLastRun:i},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 Yt.runInputGuardrails(this.inputGuardrails,n,this.agentName,e),yield {type:"raw_response_event",data:{type:"input_guardrails.check_passed"},event_type:"input_guardrails.check_passed"});let a=await this.getInstructions(n),l=await this.getContextInjection(n);process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] dynamicInstructions length:",a?.length||0),console.log("[RUNNER] dynamicInstructions START:",a?.substring(0,200)),console.log("[RUNNER] dynamicInstructions END:",a?.substring(a.length-500)),console.log("[RUNNER] contains \u534F\u4F5C\u6A21\u5F0F:",a?.includes("\u534F\u4F5C\u6A21\u5F0F")),console.log("[RUNNER] contains delegate_task:",a?.includes("delegate_task")));let c=this.memory.getMessagesForLLM(),u=c.some(C=>C.role==="system");if(process.env.CLI_DEBUG==="1"&&(console.log("[RUNNER] hasSystemPrompt:",u,"existingMessages count:",c.length),console.log("[RUNNER] disableSystemPrompt:",this.disableSystemPrompt)),this.disableSystemPrompt)u&&this.memory.clear(),a&&this.memory.add({role:"system",content:a});else if(!u){let C=this.modeStrategy.getSystemPrompt();this.memory.add({role:"system",content:C}),this.memory.add({role:"system",content:a}),this.structuredValidator&&this.memory.add({role:"system",content:this.structuredValidator.buildSystemPrompt()});try{let w=await fi(this.workspacePath);w&&this.memory.add({role:"system",content:w});}catch{}}if(l?this.memory.upsertSystemTagged?this.memory.upsertSystemTagged("context_injection",l):u||this.memory.add({role:"system",content:l}):this.memory.removeSystemTagged?.("context_injection"),t&&t.length>0){let C=[{type:"text",text:e},...t.map(w=>({type:"image_url",image_url:{url:w,detail:"auto"}}))];this.memory.add({role:"user",content:C});}else this.memory.add({role:"user",content:e});let p=Date.now(),d=0,m="",h=0,f={totalTokens:0,promptTokens:0,completionTokens:0},y=false,b=0,_=null,v=new Map,k=0,R=kt.streamMaxRetries,O=Number.isFinite(this.config.maxIterations)?this.config.maxIterations:hc,W=O===0||O===1/0,F=Dc(this.config.maxToolCalls,gc),S=Dc(this.config.maxRuntimeMs,fc);for(;W||d<O;){if(s?.aborted){_="interrupted",y=true,yield {type:"error",error:"Task interrupted by user."};break}if(S!==null&&Date.now()-p>=S){_="runtime_limit",y=true,yield {type:"error",error:`Reached max runtime (${qe(S)}). Please summarize progress and ask whether to continue.`};break}if(F!==null&&h>=F){_="tool_call_limit",y=true,yield {type:"error",error:`Reached max tool calls (${F}). Please summarize progress and ask whether to continue.`};break}d++;let C=null;if(this.maxInputTokens){let T=We(this.memory.getMessagesForLLM()),M=this.maxInputTokens*.97;T>M&&(C=await this.applyContextWindow(d));}C&&(C.stats.droppedMessages>0||C.stats.llmCompressedMessages>0)&&(yield {type:"context_compaction",status:"completed",originalMessages:C.originalCount,keptMessages:C.messages.length,droppedMessages:C.stats.droppedMessages,compressedMessages:C.stats.llmCompressedMessages,originalTokens:C.originalTokens,finalTokens:C.compressedTokens,budgetTokens:this.maxInputTokens||0,useLLM:C.stats.llmCompressedMessages>0,timestamp:Date.now()});let w=this.memory.checkContextHealth();if((w.warnings.length>0||w.shouldCleanup)&&(yield {type:"raw_response_event",data:{type:"context_health",totalTokens:w.totalTokens,toolResultTokens:w.toolResultTokens,toolResultRatio:w.toolResultRatio,messageCount:w.messageCount,toolMessageCount:w.toolMessageCount,warnings:w.warnings,shouldCompress:w.shouldCompress,shouldCleanup:w.shouldCleanup,byType:w.byType},event_type:"context_health"},w.shouldCleanup&&w.byType.ephemeral.count>5)){let T=this.memory.cleanupEphemeral();T>0&&g.info("Runner",`Cleaned ${T} ephemeral messages`);}g.debug("Runner",this.memory.getTokenSummary()),te.agentIteration(d,"thinking"),yield {type:"iteration_start",iteration:d};try{yield {type:"raw_response_event",data:{type:"response.created",response:{id:`resp_${Date.now()}`,model:this.model}},event_type:"response.created"};let T=this.memory.getMessagesForLLM();if(g.info("LLM",`Request: model=${this.model}, messages=${T.length}, tools=${this.tools.length}`),g.debug("LLM","Request messages",{messageCount:T.length,lastMessage:T[T.length-1]?.content?.toString().substring(0,200)}),process.env.CLI_DEBUG==="1"){let P=T.filter(K=>K.role==="system");console.log("[RUNNER] System messages count:",P.length);for(let K=0;K<P.length;K++){let U=P[K].content,ne=typeof U=="string"?U:JSON.stringify(U);console.log(`[RUNNER] System[${K}] length:`,ne?.length||0),console.log(`[RUNNER] System[${K}] contains \u534F\u4F5C\u6A21\u5F0F:`,ne?.includes("\u534F\u4F5C\u6A21\u5F0F")||!1),console.log(`[RUNNER] System[${K}] contains delegate_task:`,ne?.includes("delegate_task")||!1),console.log(`[RUNNER] System[${K}] preview:`,ne?.substring(0,300)||"");}}let M=this.modeStrategy.filterTools(this.tools);process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`Mode: ${this.currentMode}, Available tools: ${M.length}/${this.tools.length}`);let B=this.llmProvider.chatStreamed(this.memory.getMessagesForLLM(),{model:this.model,tools:M,temperature:this.config.temperature,structuredOutput:this.structuredOutput,maxInputTokens:this.maxInputTokens,disableSystemPrompt:this.disableSystemPrompt,signal:s}),E="",L="",N=[],$=[],G="",X={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let P of this.withStreamWatchdog(B,s)){if(P.type==="stream_retry"){yield P;continue}if(P.type==="stream_recovered"){yield {type:"stream_recovered",attempt:P.attempt,maxRetries:P.maxRetries};continue}yield {type:"raw_response_event",data:P,event_type:P.choices?.[0]?.delta?"response.delta":"response.chunk"};let K=P.choices?.[0]?.delta;if(P.usage){X={prompt_tokens:P.usage.prompt_tokens||X.prompt_tokens,completion_tokens:P.usage.completion_tokens||X.completion_tokens,total_tokens:P.usage.total_tokens||X.total_tokens,cached_tokens:P.usage.cached_tokens,cache_read_input_tokens:P.usage.cache_read_input_tokens,cache_creation_input_tokens:P.usage.cache_creation_input_tokens,prompt_tokens_details:P.usage.prompt_tokens_details},f={promptTokens:X.prompt_tokens,completionTokens:X.completion_tokens,totalTokens:X.total_tokens};let U=!!P.choices?.[0]?.finish_reason;yield {type:"token_usage",usage:X,is_final:U};}if(K){if(K.reasoning_content&&(L+=K.reasoning_content,yield {type:"reasoning_delta",delta:K.reasoning_content}),K.reasoning_complete&&(yield {type:"reasoning_complete"}),K.content&&(E+=K.content,m=E,yield {type:"text_delta",delta:K.content}),K.tool_calls)for(let U of K.tool_calls){let ne=U.index;$[ne]||($[ne]={id:U.id||`call_${Math.floor(Date.now())}_${ne}`,type:"function",function:{name:"",arguments:""}}),U.id&&($[ne].id=U.id),U.function?.name&&($[ne].function.name=U.function.name),U.function?.arguments&&($[ne].function.arguments+=U.function.arguments,yield {type:"tool_call_delta",id:$[ne].id,name:$[ne].function.name,arguments_delta:U.function.arguments}),U.thoughtSignature&&($[ne].thoughtSignature=U.thoughtSignature);}P.choices?.[0]?.finish_reason&&(G=P.choices[0].finish_reason),P.thinking_blocks&&Array.isArray(P.thinking_blocks)&&(N=P.thinking_blocks.map(U=>({type:U.type,thinking:U.thinking,signature:U.signature,data:U.data})));}}E&&(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 A={role:"assistant",content:(E||"").trimEnd()};if(L&&(A.reasoning_content=L),N.length>0&&(A.thinking_blocks=N),$.length>0&&(A.tool_calls=$.map(P=>({...P,function:{...P.function,arguments:P.function.arguments}}))),this.memory.add(A),process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Stream ended. toolCalls.length=${$.length}, fullContent.length=${E.length}`),$.length>0){let P=/\[omitted\s+\w+:\s*\d+\s*lines?,\s*\d+\s*chars?\]/i;for(let x of $){let D=x.function.arguments||"";if(P.test(D)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${x.function.name}`),console.error(`[Runner] Arguments preview: ${D.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:x.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.'},y=!0;break}}if(y)break;if(F!==null&&h+$.length>F){_="tool_call_limit",y=!0,yield {type:"error",error:`Tool call budget exceeded (max ${F}, requested ${$.length}). Please summarize progress and ask whether to continue.`};break}if($.length>1){let x=$.map(H=>H.function.name),D=[...new Set(x)];D.length===1&&x.length>1?g.info("RUNNER",`\u{1F504} Parallel calls: ${x.length}x ${D[0]} (different parameters)`):g.info("RUNNER",`\u{1F504} Parallel calls: ${x.join(", ")}`);}for(let x of $){h++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:x.id,name:x.function.name,arguments:x.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:x.id,name:x.function.name};let H=!1;try{x.function.arguments&&(JSON.parse(x.function.arguments),H=!0);}catch(V){te.toolError(x.function.name,`Invalid JSON arguments (${V.message}): ${x.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${x.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${x.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${x.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${x.function.arguments.substring(Math.max(0,x.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:x.id,name:x.function.name,arguments:x.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:x.id,name:x.function.name,arguments:x.function.arguments},event_type:"response.function_call_arguments.done"};}let K=new Set,U=null,ne=$.length>1;process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`Processing ${$.length} tool call(s)`,{isParallel:ne,tools:$.map(x=>x.function.name)});for(let x of $){let D={};try{let I=x.function.arguments?.trim()||"";D=I?JSON.parse(I):{};}catch(I){te.toolError(x.function.name,`Loop detection skipped: invalid JSON (${I.message})`);continue}let H=this.loopDetector.detect(x.function.name,D);if(this.loopDetector.record(x.function.name,D),H===0)continue;let V=this.loopDetector.generateIntervention(H,x.function.name,D);if(this.memory.add({role:"system",content:V.message}),H===2&&ca(x.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.function.name,output:V.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:x.function.name,output:V.message,success:!1},this.memory.addToolResult(x.id,x.function.name,V.message),this.loopDetector.updateLastStatus("error"),K.add(x.id),V.shouldTerminate){U=V;break}}if(U&&(yield {type:"error",error:U.message},y=!0),y)break;let Te=K.size>0?$.filter(x=>!K.has(x.id)):$,Q=new Set(this.modeStrategy.filterTools(this.tools).map(x=>x.name)),oe=x=>x.replace(/["\s/>]+$/g,"").trim(),se=[];for(let x of Te){let D=oe(x.function.name);if(Q.has(D)||Q.has(x.function.name)){se.push(x);continue}let H=`Tool "${x.function.name}" is not allowed in ${this.currentMode} mode`;te.toolError(x.function.name,H),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.function.name,output:H,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:x.function.name,output:H,success:!1},this.memory.addToolResult(x.id,x.function.name,H),g.info("PERMISSION",`Tool blocked by mode: ${x.function.name} - ${H}`);}if(se.length===0)continue;let ae=se.map(x=>({id:x.id,type:"function",function:{name:x.function.name,arguments:x.function.arguments}})),J=!1;if(process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Before permission check. shouldAutoApprove=${this.modeStrategy.shouldAutoApprove()}, parallelToolCalls=${ae.length}`),!this.modeStrategy.shouldAutoApprove()){let x=new Set;try{for(let D of se)try{let H=D.function.arguments.trim(),V=H?JSON.parse(H):{},we=this.tools.find(I=>I.name===D.function.name);if(!we){g.warn("RUNNER",`Tool not found: ${D.function.name}`);continue}let xe=await $c(s,async()=>this.permissionManager.checkPermission(we,V));if(!xe.allowed){x.add(D.id);let I=xe.reason||`Tool "${D.function.name}" was denied`;te.toolError(D.function.name,I),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:D.id,name:D.function.name,output:I,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:D.function.name,output:I,success:!1};let q=JSON.stringify({type:"ephemeral",status:"error",tool:D.function.name,summary:"Tool execution denied by user",error:I,final:!0});this.memory.addToolResult(D.id,D.function.name,q),g.info("PERMISSION",`Tool denied: ${D.function.name} - ${I}`),J=!0;}}catch(H){if(H?.name==="AbortError"||H?.code==="ERR_CANCELED")throw H;te.toolError(D.function.name,H?.message||"permission check failed");}}catch(D){if(D?.name==="AbortError"||D?.code==="ERR_CANCELED"){g.info("RUNNER","Interrupt detected during permission check"),y=!0;break}throw D}if(se=se.filter(D=>!x.has(D.id)),ae=ae.filter(D=>!x.has(D.id)),J){g.info("RUNNER","User denied tool - terminating current turn");break}if(ae.length===0)continue}if(process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} After permission check. parallelToolCalls=${ae.length}, userDeniedTool=${J}`),this.toolInputGuardrails.length>0){let x=new Set;try{for(let D of se)try{let H=D.function.arguments.trim(),V=H?JSON.parse(H):{},we={tool_name:D.function.name,tool_input:V,tool_call_id:D.id},xe=this.tools.find(j=>j.name===D.function.name);if(!xe)continue;this.runContext.iteration=d;let I=await $c(s,async()=>Yt.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:we,agent_name:this.agentName,tool:xe}));if(!I.should_execute){x.add(D.id);let j=I.rejection_message||`Tool ${D.function.name} was blocked by guardrail`;te.toolError(D.function.name,`Blocked by guardrail: ${j}`),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:D.id,name:D.function.name,output:j,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:D.function.name,output:j,success:!1},this.memory.addToolResult(D.id,D.function.name,j),Ai(this.runContext,D.function.name,V,!1);}}catch(H){if(H?.name==="AbortError"||H?.code==="ERR_CANCELED")throw H;if(H instanceof st){te.toolError(D.function.name,`Guardrail tripwire triggered: ${H.message}`),yield {type:"error",error:`Guardrail tripwire triggered for ${D.function.name}: ${H.message}`},y=!0;break}te.toolError(D.function.name,`Guardrail check failed: ${H?.message}`);}}catch(D){if(D?.name==="AbortError"||D?.code==="ERR_CANCELED"){g.info("RUNNER","Interrupt detected during guardrails check"),y=!0;break}throw D}if(y)break;if(se=se.filter(D=>!x.has(D.id)),ae=ae.filter(D=>!x.has(D.id)),ae.length===0)continue}process.env.CLI_DEBUG==="1"&&g.debug("RUNNER",`\u{1F525} Before tool execution. parallelToolCalls=${ae.length}`);let pe=await this.parallelExecutor.execute(ae,this.tools,x=>{if(te.toolCall(x.name,{}),x.success){let H=typeof x.output=="string"?x.output.length:JSON.stringify(x.output).length;te.toolResult(x.name,!0,H,x.executionTime||0);}else te.toolError(x.name,x.output);let D={type:"tool_call_output_item",id:x.id,name:x.name,output:x.output,success:x.success,timestamp:Date.now()};},s);for(let x of pe.results){if(this.toolMetricsHistory.push({name:x.name,duration:x.executionTime||0,success:x.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:x.id,name:x.name,output:x.output,success:x.success,timestamp:Date.now()}},yield {type:"tool_output",name:x.name,output:x.output,success:x.success},x.name==="update_plan"&&x.success)try{g.info("PLAN_UPDATE","\u{1F525} Detected update_plan tool call",{resultId:x.id,toolCallsCount:$.length});let I=$.find(j=>j.id===x.id);if(I){g.info("PLAN_UPDATE","\u{1F525} Found original call",{callId:I.id,argsLength:I.function.arguments?.length});let j=JSON.parse(I.function.arguments||"{}");g.info("PLAN_UPDATE","\u{1F525} Parsed plan args",{hasExplanation:!!j.explanation,planSteps:j.plan?.length}),yield {type:"plan_update",explanation:j.explanation,plan:j.plan,timestamp:Date.now()},g.info("PLAN_UPDATE","\u2705 Emitted plan_update event");}else g.warn("PLAN_UPDATE","\u274C Could not find original tool call",{resultId:x.id,availableIds:$.map(j=>j.id)});}catch(I){g.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:I});}let H=typeof x.output=="string"?Nc(x.output):Nc(JSON.stringify(x.output));H=this.enrichToolResult(H,x.name,x.executionTime||0);let V=$.find(I=>I.id===x.id),we={};if(V)try{we=JSON.parse(V.function.arguments||"{}");}catch{}if(this.toolOutputGuardrails.length>0)try{let I=this.tools.find(j=>j.name===x.name);if(I){let j={tool_name:x.name,tool_input:we,tool_call_id:x.id},q=await Yt.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:j,agent_name:this.agentName,tool:I,output:x.output});q.should_use_output||(H=q.replacement_message||"[Output blocked by guardrail]",te.toolError(x.name,"Output blocked by guardrail"));}}catch(I){I instanceof st&&te.toolError(x.name,`Output guardrail tripwire triggered: ${I.message}`);}if(!x.success&&typeof x.output=="string"){let I=x.output.toLowerCase();if(I.includes("operation cancelled")||I.includes("command interrupted")||I.includes("request aborted")){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Detected cancellation in tool output, breaking loop"),g.info("RUNNER","\u68C0\u6D4B\u5230\u5DE5\u5177\u4E2D\u65AD\u4FE1\u53F7\uFF0C\u7EC8\u6B62\u6267\u884C\u5FAA\u73AF"),y=!0;break}}Ai(this.runContext,x.name,we,x.success),g.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${x.name}`,{toolName:x.name,success:x.success,rawLength:typeof x.output=="string"?x.output.length:JSON.stringify(x.output).length,truncatedLength:H.length,outputPreview:H.substring(0,500)}),this.memory.addToolResult(x.id,x.name,H);let xe=x.success?"success":"error";try{let I=typeof x.output=="string"?x.output:JSON.stringify(x.output),j=JSON.parse(I);j.status==="already_done"?xe="already_done":j.status==="success"?xe="success":j.status==="error"&&(xe="error");}catch{}if(this.loopDetector.updateLastStatus(xe),xe==="error"){let I=(v.get(x.name)||0)+1;if(v.set(x.name,I),x.name==="edit_file"&&(I===2||I===3)){let j=typeof x.output=="string"?x.output:JSON.stringify(x.output),q=x.name,ye=Ac(q,j);this.memory.add({role:"system",content:ye});}}else v.set(x.name,0);}if(d>0&&d%5===0){let x=this.buildPerformanceHint();x&&(this.memory.add({role:"system",content:x}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",x));}if(process.env.CLI_DEBUG_CONSOLE==="1"&&pe.stats&&(yield {type:"raw_response_event",data:{type:"parallel_execution.stats",stats:pe.stats},event_type:"parallel_execution.stats"}),s?.aborted){y=!0;break}continue}else {if(this.plannerMode&&b<2&&this.shouldAutoContinuePlan(E)){b++;let P=this.buildPlanFollowupPrompt();yield {type:"raw_response_event",data:{type:"plan.auto_continue",plan_text:E,followup_prompt:P,count:b},event_type:"plan.auto_continue"},this.memory.add({role:"user",content:P});continue}if(E&&(yield {type:"run_item_stream_event",name:"message_output_created",item:{type:"message_output_item",content:E,role:"assistant",timestamp:Date.now()}}),process.env.CLI_DEBUG==="1"&&(g.info("RUNNER","=== Loop Exit: No Tool Calls ==="),g.info("RUNNER",`Finish Reason: ${G}`),g.info("RUNNER",`Content Length: ${E.length}`),g.info("RUNNER",`Content Preview: ${E.slice(0,300)}`),g.info("RUNNER",`Tool Calls Count: ${$.length}`),g.info("RUNNER",`Iteration: ${d}`)),this.structuredValidator){let P=this.structuredValidator.validate(E);if(P.ok)m=P.normalized||E,yield {type:"raw_response_event",data:{type:"structured_output.accepted",schema:this.structuredOutput?.name,normalized_text:m,parsed:P.parsed},event_type:"structured_output.accepted"};else {yield {type:"raw_response_event",data:{type:"structured_output.retry",schema:this.structuredOutput?.name,reason:P.reason,message:P.message,errors:P.errors},event_type:"structured_output.retry"},this.memory.add({role:"system",content:this.structuredValidator.buildRetryPrompt(P)}),m="";continue}}else m=E;this.outputGuardrails.length>0&&m&&(yield {type:"raw_response_event",data:{type:"output_guardrails.check_start",count:this.outputGuardrails.length},event_type:"output_guardrails.check_start"},await Yt.runOutputGuardrails(this.outputGuardrails,n,this.agentName,m),yield {type:"raw_response_event",data:{type:"output_guardrails.check_passed"},event_type:"output_guardrails.check_passed"});break}}catch(T){if(T?.type==="stream_retry"){yield T;continue}let M=T instanceof me?T:tt(T);if(process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Error classified:",{category:M.category,code:M.code,retryable:M.retryable,message:M.message}),M.category==="canceled"){_="interrupted",y=true,yield {type:"error",error:"Task interrupted by user."};break}if(M.retryable&&k<R){k++;let N=Cn(M.category,k,M.retryAfter),$=M.category==="retryable_rate_limit",G=M.code==="STREAM_TIMEOUT",X=M.category==="retryable_network"||M.category==="retryable_stream";g.warn("RUNNER",`Retrying after ${qe(N)} (attempt ${k}/${R}): ${M.message}`),yield {type:"raw_response_event",data:{type:"runner.stream_retry",error:M.message,errorCode:M.code,attempt:k,maxRetries:R,delayMs:N,isRateLimit:$,isStreamTimeout:G,isNetworkError:X},event_type:"runner.stream_retry"},await Ms(N),d--;continue}let B=Nr(M),E=M.message;B&&!E.includes(B)&&(E=`${E}
1433
1433
 
1434
- \u{1F4A1} Suggestion: ${B}`),y=true;let L=Sc(E,{providerName:this.providerName});te.agentError(L),yield {type:"raw_response_event",data:{type:"error.classified",category:M.category,code:M.code,message:M.message,retryable:M.retryable,suggestion:B,context:M.context},event_type:"error.classified"},yield {type:"error",error:L};break}}!y&&!W&&d>=O&&!m&&(_=_||"iteration_limit",y=true,yield {type:"error",error:`Reached max iterations (${O}). Please summarize progress and ask whether to continue.`}),y||(te.agentComplete(d,h,f),g.info("LLM",`Complete: iterations=${d}, toolCalls=${h}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(g.debug("RUNNER","=== runner.run COMPLETING ==="),g.debug("RUNNER",` iterations: ${d}`),g.debug("RUNNER",` toolCalls: ${h}`),g.debug("RUNNER",` encounteredError: ${y}`),_&&g.debug("RUNNER",` stoppedBy: ${_}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&g.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 s=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=>s.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,s){if(s<1e3)return e;let n=s>=1e3?`${(s/1e3).toFixed(1)}s`:`${s}ms`;return `\u23F1\uFE0F [${t} took ${n}]
1434
+ \u{1F4A1} Suggestion: ${B}`),y=true;let L=Rc(E,{providerName:this.providerName});te.agentError(L),yield {type:"raw_response_event",data:{type:"error.classified",category:M.category,code:M.code,message:M.message,retryable:M.retryable,suggestion:B,context:M.context},event_type:"error.classified"},yield {type:"error",error:L};break}}!y&&!W&&d>=O&&!m&&(_=_||"iteration_limit",y=true,yield {type:"error",error:`Reached max iterations (${O}). Please summarize progress and ask whether to continue.`}),y||(te.agentComplete(d,h,f),g.info("LLM",`Complete: iterations=${d}, toolCalls=${h}, tokens=${f.totalTokens} (prompt=${f.promptTokens}, completion=${f.completionTokens})`)),process.env.CLI_DEBUG==="1"&&(g.debug("RUNNER","=== runner.run COMPLETING ==="),g.debug("RUNNER",` iterations: ${d}`),g.debug("RUNNER",` toolCalls: ${h}`),g.debug("RUNNER",` encounteredError: ${y}`),_&&g.debug("RUNNER",` stoppedBy: ${_}`)),yield {type:"run_done"},process.env.CLI_DEBUG==="1"&&g.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 s=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=>s.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,s){if(s<1e3)return e;let n=s>=1e3?`${(s/1e3).toFixed(1)}s`:`${s}ms`;return `\u23F1\uFE0F [${t} took ${n}]
1435
1435
 
1436
- `+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 s=new Map;for(let i of e){let o=s.get(i.name)||{total:0,failed:0};s.set(i.name,{total:o.total+1,failed:o.failed+(i.success?0:1)});}let n=[];for(let[i,o]of t.entries())o.count>=3&&n.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 s.entries()){let a=o.failed/o.total;o.total>=3&&a>=.5&&n.push(`\u26A0\uFE0F Tool "${i}" has ${Math.round(a*100)}% failure rate (${o.failed}/${o.total}). Check arguments or try different approach.`);}return n.length===0?null:`
1436
+ `+e}buildPerformanceHint(){let e=this.toolMetricsHistory.slice(-15);if(e.length<5)return null;let t=new Map;for(let o of e)if(o.duration>2e3){let i=t.get(o.name)||{count:0,totalTime:0};t.set(o.name,{count:i.count+1,totalTime:i.totalTime+o.duration});}let s=new Map;for(let o of e){let i=s.get(o.name)||{total:0,failed:0};s.set(o.name,{total:i.total+1,failed:i.failed+(o.success?0:1)});}let n=[];for(let[o,i]of t.entries())i.count>=3&&n.push(`\u26A0\uFE0F Tool "${o}" is slow (>2s), called ${i.count} times, total ${(i.totalTime/1e3).toFixed(1)}s. Consider caching results or using alternatives.`);for(let[o,i]of s.entries()){let a=i.failed/i.total;i.total>=3&&a>=.5&&n.push(`\u26A0\uFE0F Tool "${o}" has ${Math.round(a*100)}% failure rate (${i.failed}/${i.total}). Check arguments or try different approach.`);}return n.length===0?null:`
1437
1437
  [Performance Notice]
1438
1438
  ${n.join(`
1439
1439
  `)}
1440
- `}};le();var xg={name:"require_read_before_edit",guardrail_function:async r=>{let{tool_name:e,tool_input:t}=r.tool_context;if(e!=="edit_file")return Lr();let s=t.file_path;if(!s)return Lr();let n=l=>Y__default.resolve(l).replace(/\\/g,"/"),i=n(s),o=_c(r.context,20);return process.env.CLI_DEBUG==="1"&&(g.debug("GUARDRAIL",`Checking edit for: ${s}`),g.debug("GUARDRAIL",`Normalized path: ${i}`),g.debug("GUARDRAIL",`Recent tool calls (${o.length}):`),o.forEach((l,c)=>{if(l.name==="readfile"){let u=l.args.path,p=u?n(u):"undefined";g.debug("GUARDRAIL",` [${c}] readfile: ${u} (normalized: ${p}) success=${l.success}`);}})),o.some(l=>{if(l.name!=="readfile"||!l.success)return false;let c=l.args.path;if(!c)return false;let p=n(c)===i||c===s;return process.env.CLI_DEBUG==="1"&&p&&g.debug("GUARDRAIL",` \u2713 Found matching readfile: ${c}`),p})?Lr():(g.warn("GUARDRAIL",`Edit without recent readfile: ${s} (abs: ${i})`),process.env.CLI_DEBUG==="1"&&g.debug("GUARDRAIL",`Available readfile calls: ${o.filter(l=>l.name==="readfile").length}`),lc(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1440
+ `}};le();var Cg={name:"require_read_before_edit",guardrail_function:async r=>{let{tool_name:e,tool_input:t}=r.tool_context;if(e!=="edit_file")return Dr();let s=t.file_path;if(!s)return Dr();let n=l=>Y__default.resolve(l).replace(/\\/g,"/"),o=n(s),i=Tc(r.context,20);return process.env.CLI_DEBUG==="1"&&(g.debug("GUARDRAIL",`Checking edit for: ${s}`),g.debug("GUARDRAIL",`Normalized path: ${o}`),g.debug("GUARDRAIL",`Recent tool calls (${i.length}):`),i.forEach((l,c)=>{if(l.name==="readfile"){let u=l.args.path,p=u?n(u):"undefined";g.debug("GUARDRAIL",` [${c}] readfile: ${u} (normalized: ${p}) success=${l.success}`);}})),i.some(l=>{if(l.name!=="readfile"||!l.success)return false;let c=l.args.path;if(!c)return false;let p=n(c)===o||c===s;return process.env.CLI_DEBUG==="1"&&p&&g.debug("GUARDRAIL",` \u2713 Found matching readfile: ${c}`),p})?Dr():(g.warn("GUARDRAIL",`Edit without recent readfile: ${s} (abs: ${o})`),process.env.CLI_DEBUG==="1"&&g.debug("GUARDRAIL",`Available readfile calls: ${i.filter(l=>l.name==="readfile").length}`),pc(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1441
1441
 
1442
1442
  \u6587\u4EF6: ${s}
1443
1443
 
1444
1444
  \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
1445
- \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:s,suggestion:"use readfile first"}))}};var $c=[xg],Nc=[];var ft=class{prepareRequest(e,t){let{model:s,temperature:n,maxInputTokens:i,disableSystemPrompt:o,systemPromptOverride:a,...l}=t,c=this.constraints.validateParams({model:s,temperature:n,max_tokens:i,...l}),u=this.constraints.normalizeParams({model:s,temperature:n,max_tokens:i,...l}),p=o?null:a&&a.trim().length>0?a:this.promptBuilder.buildSystemPrompt({workDir:process.cwd(),language:this.detectLanguage(),modelName:s}),d=o||!p?e:this.injectSystemPrompt(e,p),m={...u,model:s,maxInputTokens:this.applyTokenLimits(s,i)};return {messages:d,options:m,validation:{valid:c.valid,errors:c.errors,warnings:c.warnings}}}injectSystemPrompt(e,t){if(e.some(n=>n.role==="system")){let n=e.filter(a=>a.role==="system").map(a=>this.normalizeSystemContent(a.content)).filter(a=>a.length>0),i=n.length>0?[t,...n].join(`
1445
+ \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:s,suggestion:"use readfile first"}))}};var Uc=[Cg],jc=[];var ft=class{prepareRequest(e,t){let{model:s,temperature:n,maxInputTokens:o,disableSystemPrompt:i,systemPromptOverride:a,...l}=t,c=this.constraints.validateParams({model:s,temperature:n,max_tokens:o,...l}),u=this.constraints.normalizeParams({model:s,temperature:n,max_tokens:o,...l}),p=i?null:a&&a.trim().length>0?a:this.promptBuilder.buildSystemPrompt({workDir:process.cwd(),language:this.detectLanguage(),modelName:s}),d=i||!p?e:this.injectSystemPrompt(e,p),m={...u,model:s,maxInputTokens:this.applyTokenLimits(s,o)};return {messages:d,options:m,validation:{valid:c.valid,errors:c.errors,warnings:c.warnings}}}injectSystemPrompt(e,t){if(e.some(n=>n.role==="system")){let n=e.filter(a=>a.role==="system").map(a=>this.normalizeSystemContent(a.content)).filter(a=>a.length>0),o=n.length>0?[t,...n].join(`
1446
1446
 
1447
- `):t,o=e.filter(a=>a.role!=="system");return [{role:"system",content:i},...o]}return [{role:"system",content:t},...e]}normalizeSystemContent(e){return e?typeof e=="string"?e.trim():Array.isArray(e)?e.map(s=>!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"?s.text:"").join("").trim():String(e).trim():""}applyTokenLimits(e,t){if(!e)return t;let s=this.constraints.getTokenLimits(e);return Math.min(t||4096,s.maxOutput)}detectLanguage(){return process.env.NEOX_LANGUAGE==="en"?"en":"zh"}};var Sg={"gpt-5.2":{id:"gpt-5.2",displayName:"GPT-5.2",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:98,vision:92,creativity:94,speed:75,cost:25},releaseDate:"2025-12-11",notes:'400K \u4E0A\u4E0B\u6587\u7A97\u53E3,128K \u8F93\u51FA\u9650\u5236,\u4EE3\u53F7"Garlic"'},"gpt-5.2-codex":{id:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",provider:"openai",aliases:["gpt-5.2-codex"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:98,reasoning:97,vision:90,creativity:92,speed:70,cost:20},releaseDate:"2025-12-10",notes:"GPT-5.2 \u7684 Codex \u9ED8\u8BA4\u7248\u672C,\u4E13\u4E3A\u7F16\u7A0B\u4EFB\u52A1\u4F18\u5316"},"gpt-5.2-codex-high":{id:"gpt-5.2-codex-high",displayName:"GPT-5.2 Codex High",provider:"openai",aliases:["gpt-5.2-codex-h"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:99,reasoning:98,vision:90,creativity:93,speed:60,cost:15},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u9AD8\u6027\u80FD\u6A21\u5F0F,\u6700\u5F3A\u7F16\u7A0B\u80FD\u529B,\u66F4\u6162\u66F4\u8D35"},"gpt-5.2-codex-medium":{id:"gpt-5.2-codex-medium",displayName:"GPT-5.2 Codex Medium",provider:"openai",aliases:["gpt-5.2-codex-m"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:94,vision:88,creativity:90,speed:80,cost:40},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u5E73\u8861\u6A21\u5F0F,\u6027\u4EF7\u6BD4\u4F18\u9009"},"gpt-5.1":{id:"gpt-5.1",displayName:"GPT-5.1",provider:"openai",maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:96,vision:90,creativity:92,speed:80,cost:30},notes:"272K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA,\u9002\u5408\u957F\u4E0A\u4E0B\u6587\u4EFB\u52A1"},"gpt-5.1-codex":{id:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",provider:"openai",aliases:["gpt-5-codex","gpt-5.1-codex-max"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:97,reasoning:95,vision:88,creativity:90,speed:75,cost:25},notes:"Codex \u4F18\u5316\u7248,400K \u4E0A\u4E0B\u6587,\u4E13\u4E3A agentic \u7F16\u7A0B\u5DE5\u4F5C\u6D41\u8BBE\u8BA1"},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",displayName:"GPT-5.1 Codex Mini",provider:"openai",aliases:["gpt-5-codex-mini"],maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:85,speed:92,cost:85},notes:"\u66F4\u5FEB\u66F4\u4FBF\u5B9C\u7684 Codex \u7248\u672C"},"gpt-5":{id:"gpt-5",displayName:"GPT-5",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:94,vision:90,creativity:94,speed:80,cost:35},deprecated:true,replacedBy:"gpt-5.1",notes:"\u5DF2\u88AB GPT-5.1 \u66FF\u4EE3"},"gpt-4.1":{id:"gpt-4.1",displayName:"GPT-4.1",provider:"openai",aliases:["gpt-4.1-2025-04-14"],maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:92,vision:88,creativity:90,speed:65,cost:15},releaseDate:"2025-04-14",notes:"\u8D85\u5927 1M+ \u4E0A\u4E0B\u6587\u7A97\u53E3,\u9002\u5408\u5904\u7406\u5927\u578B\u4EE3\u7801\u5E93"},"gpt-4o":{id:"gpt-4o",displayName:"GPT-4o",provider:"openai",aliases:["gpt-4o-2024-11-20","gpt-4o-2024-08-06"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:85,vision:88,creativity:88,speed:75,cost:50}},"gpt-4o-mini":{id:"gpt-4o-mini",displayName:"GPT-4o Mini",provider:"openai",aliases:["gpt-4o-mini-2024-07-18"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:80,creativity:75,speed:92,cost:90}},o3:{id:"o3",displayName:"o3",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:99,vision:0,creativity:78,speed:40,cost:15},notes:"\u65B0\u4E00\u4EE3\u63A8\u7406\u6A21\u578B,\u63A8\u7406\u80FD\u529B\u6700\u5F3A"},"o3-mini":{id:"o3-mini",displayName:"o3 Mini",provider:"openai",aliases:["o3-mini-2025-01-31"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:65,cost:60}},"o4-mini":{id:"o4-mini",displayName:"o4 Mini",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:96,vision:0,creativity:76,speed:70,cost:55}},o1:{id:"o1",displayName:"o1",provider:"openai",aliases:["o1-2024-12-17"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:45,cost:25}},"o1-mini":{id:"o1-mini",displayName:"o1 Mini",provider:"openai",aliases:["o1-mini-2024-09-12"],maxInputTokens:128e3,maxOutputTokens:65536,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:82,reasoning:88,vision:0,creativity:70,speed:70,cost:70}},"codex-mini-latest":{id:"codex-mini-latest",displayName:"Codex Mini (Latest)",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:88,cost:80}},"gpt-4-turbo":{id:"gpt-4-turbo",displayName:"GPT-4 Turbo",provider:"openai",aliases:["gpt-4-turbo-2024-04-09"],maxInputTokens:128e3,maxOutputTokens:4096,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:87,vision:85,creativity:90,speed:70,cost:40}},"gpt-3.5-turbo":{id:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",provider:"openai",maxInputTokens:16385,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:65,reasoning:60,vision:0,creativity:70,speed:95,cost:98}}},kg={"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",provider:"anthropic",aliases:["claude-opus-4.5"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:98,reasoning:97,vision:90,creativity:95,speed:65,cost:20},releaseDate:"2025-11-24",notes:"\u6700\u5F3A Claude \u6A21\u578B,\u652F\u6301 Extended Thinking,\u4F01\u4E1A\u7248\u53EF\u6269\u5C55\u81F3 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",provider:"anthropic",aliases:["claude-sonnet-4.5","claude-sonnet-4-5-20250929-thinking"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:88,creativity:90,speed:80,cost:50},releaseDate:"2025-09-29",notes:"\u5E73\u8861\u6027\u80FD\u4E0E\u6210\u672C,beta \u7248\u672C\u652F\u6301 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-20250514":{id:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",provider:"anthropic",aliases:["claude-sonnet-4"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:88,speed:82,cost:55},notes:"2025-08-12 \u5347\u7EA7\u652F\u6301 1M beta \u4E0A\u4E0B\u6587"},"claude-opus-4-20250514":{id:"claude-opus-4-20250514",displayName:"Claude Opus 4",provider:"anthropic",aliases:["claude-opus-4"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:95,vision:88,creativity:94,speed:70,cost:25}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",provider:"anthropic",aliases:["claude-haiku-4.5"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:78,reasoning:75,vision:80,creativity:75,speed:95,cost:95},notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 4.5 \u6A21\u578B"},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",displayName:"Claude 3.5 Sonnet (New)",provider:"anthropic",aliases:["claude-3.5-sonnet-new","claude-3-5-sonnet-latest"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:85,cost:55},releaseDate:"2024-10-22",notes:"Claude 3.5 Sonnet \u5347\u7EA7\u7248"},"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",displayName:"Claude 3.5 Haiku",provider:"anthropic",aliases:["claude-3.5-haiku"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:78,creativity:73,speed:98,cost:98},releaseDate:"2024-10-22",notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 3.5 \u6A21\u578B"}},Cg={"gemini-3-pro-preview":{id:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",provider:"gemini",aliases:["gemini-3-pro","gemini-3.0-pro-preview"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:95,vision:96,creativity:94,speed:72,cost:35},releaseDate:"2026-01",notes:"Gemini 3 \u9884\u89C8\u7248,UI/\u89C6\u89C9\u8BBE\u8BA1\u4E13\u957F,1M \u4E0A\u4E0B\u6587"},"gemini-3.0-pro":{id:"gemini-3.0-pro",displayName:"Gemini 3.0 Pro",provider:"gemini",aliases:["gemini-3.0-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:96,vision:94,creativity:92,speed:70,cost:30},releaseDate:"2025-12",notes:"Flagship multimodal model with 1M context, high-precision reasoning"},"gemini-2.5-flash":{id:"gemini-2.5-flash",displayName:"Gemini 2.5 Flash",provider:"gemini",aliases:["gemini-2.5-flash-latest"],maxInputTokens:1048576,maxOutputTokens:65535,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:90,creativity:87,speed:92,cost:85},releaseDate:"2025-03",notes:"Fast and cost-efficient, ~1500 pages or 30K lines of code"},"gemini-2.5-pro":{id:"gemini-2.5-pro",displayName:"Gemini 2.5 Pro",provider:"gemini",aliases:["gemini-2.5-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:92,vision:92,creativity:90,speed:75,cost:40},releaseDate:"2025-03",notes:"Balanced performance with 1M context window"},"gemini-2.0-flash-thinking":{id:"gemini-2.0-flash-thinking",displayName:"Gemini 2.0 Flash Thinking",provider:"gemini",aliases:["gemini-2.0-flash-thinking-exp","gemini-2.0-flash-thinking-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:94,vision:90,creativity:88,speed:85,cost:50},releaseDate:"2024-12-19",notes:"Shows model thought process, 1M context window"},"gemini-2.0-flash":{id:"gemini-2.0-flash",displayName:"Gemini 2.0 Flash",provider:"gemini",aliases:["gemini-2.0-flash-exp","gemini-2.0-flash-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:89,vision:90,creativity:87,speed:95,cost:75},releaseDate:"2024-12-11",notes:"Twice as fast as Gemini 1.5 Pro, multimodal with native image generation"},"gemini-1.5-pro":{id:"gemini-1.5-pro",displayName:"Gemini 1.5 Pro",provider:"gemini",aliases:["gemini-1.5-pro-latest","gemini-pro"],maxInputTokens:2e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:87,vision:88,creativity:85,speed:70,cost:50},releaseDate:"2024-05",notes:"2M context window - largest available, supports context caching"},"gemini-1.5-flash":{id:"gemini-1.5-flash",displayName:"Gemini 1.5 Flash",provider:"gemini",aliases:["gemini-1.5-flash-latest","gemini-flash"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:83,vision:85,creativity:82,speed:90,cost:85},releaseDate:"2024-05",notes:"Fast and efficient with 1M context, supports code execution"},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",displayName:"Gemini 1.5 Flash-8B",provider:"gemini",aliases:["gemini-flash-8b"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:82,creativity:77,speed:98,cost:95},releaseDate:"2024-10",notes:"Smaller 8B model, extremely fast and cost-effective"},"gemini-1.0-pro":{id:"gemini-1.0-pro",displayName:"Gemini 1.0 Pro",provider:"gemini",aliases:["gemini-pro-1.0"],maxInputTokens:32768,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:73,vision:0,creativity:75,speed:85,cost:90},releaseDate:"2023-12",notes:"Original Gemini Pro, text-only"},"gemini-1.0-pro-vision":{id:"gemini-1.0-pro-vision",displayName:"Gemini 1.0 Pro Vision",provider:"gemini",aliases:["gemini-pro-vision"],maxInputTokens:16384,maxOutputTokens:2048,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:80,creativity:72,speed:80,cost:88},releaseDate:"2023-12",notes:"Original multimodal Gemini with vision support"}},Rg={"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",displayName:"Kimi K2 (0905 Preview)",provider:"kimi",aliases:["kimi-k2","kimi-k2-preview"],maxInputTokens:256e3,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:70},releaseDate:"2025-09",notes:"MoE \u67B6\u6784 K2 \u9884\u89C8\u7248\uFF0C256K \u4E0A\u4E0B\u6587"}},Eg={"deepseek-v3.2":{id:"deepseek-v3.2",displayName:"DeepSeek V3.2",provider:"deepseek",aliases:["deepseek-v3.2-exp"],maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:95},releaseDate:"2025-09-29",notes:"\u5B9E\u9A8C\u7248\u672C,\u6027\u80FD\u663E\u8457\u63D0\u5347"},"deepseek-v3.1":{id:"deepseek-v3.1",displayName:"DeepSeek V3.1",provider:"deepseek",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:78,speed:88,cost:96},releaseDate:"2025-08",notes:"\u6DF7\u5408\u67B6\u6784\u6A21\u578B"},"deepseek-chat":{id:"deepseek-chat",displayName:"DeepSeek Chat",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:85,cost:95},notes:"\u901A\u7528\u5BF9\u8BDD\u6A21\u578B,\u6210\u672C\u6781\u4F4E"},"deepseek-coder":{id:"deepseek-coder",displayName:"DeepSeek Coder",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:85,vision:0,creativity:70,speed:88,cost:96},notes:"\u4E13\u4E3A\u7F16\u7A0B\u4F18\u5316,\u4EE3\u7801\u80FD\u529B\u7A81\u51FA"},"deepseek-reasoner":{id:"deepseek-reasoner",displayName:"DeepSeek Reasoner",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:96,vision:0,creativity:75,speed:60,cost:90},notes:"\u63A8\u7406\u4E13\u7528\u6A21\u578B,\u652F\u6301\u957F\u8F93\u51FA"}},Ig={"minimax-text-01":{id:"minimax-text-01",displayName:"MiniMax Text-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:90,vision:0,creativity:85,speed:55,cost:70},notes:"4M \u4E0A\u4E0B\u6587\u7A97\u53E3,Lightning Attention + MoE \u67B6\u6784,\u5F00\u6E90\u53EF\u7528"},"minimax-m1-80k":{id:"minimax-m1-80k",displayName:"MiniMax M1-80K",provider:"minimax",maxInputTokens:1e6,maxOutputTokens:8e4,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:92,vision:0,creativity:82,speed:65,cost:75},notes:"1M \u4E0A\u4E0B\u6587 + 80K \u601D\u8003\u9884\u7B97"},"minimax-m2.1":{id:"minimax-m2.1",displayName:"MiniMax M2.1",provider:"minimax",maxInputTokens:2e5,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:88,vision:0,creativity:80,speed:82,cost:85},releaseDate:"2025-12",notes:"\u7F16\u7A0B\u548C Agentic \u5DE5\u4F5C\u6D41\u4F18\u5316,\u652F\u6301\u591A\u8BED\u8A00"},"minimax-vl-01":{id:"minimax-vl-01",displayName:"MiniMax VL-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:92,creativity:88,speed:60,cost:65},notes:"\u591A\u6A21\u6001\u6A21\u578B,\u652F\u6301\u6587\u672C\u548C\u56FE\u50CF"}},Mg={"glm-4.7":{id:"glm-4.7",displayName:"GLM-4.7",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:80,cost:70},releaseDate:"2025-12-22",notes:"\u6700\u65B0\u7248\u672C,200K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA"},"glm-4.6":{id:"glm-4.6",displayName:"GLM-4.6",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:83,creativity:85,speed:82,cost:75},releaseDate:"2025-09-10",notes:"\u4ECE 128K \u6269\u5C55\u81F3 200K \u4E0A\u4E0B\u6587"},"glm-4.5":{id:"glm-4.5",displayName:"GLM-4.5",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:86,reasoning:84,vision:80,creativity:83,speed:85,cost:80},releaseDate:"2025-07"},"glm-4-flash":{id:"glm-4-flash",displayName:"GLM-4 Flash",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:82,reasoning:80,vision:78,creativity:80,speed:95,cost:92},notes:"\u5FEB\u901F\u6A21\u578B,\u76F8\u5F53\u4E8E 300 \u9875\u4E66\u7684\u4E0A\u4E0B\u6587"},"glm-4-plus":{id:"glm-4-plus",displayName:"GLM-4 Plus",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:82,creativity:85,speed:78,cost:65}},"glm-4-air":{id:"glm-4-air",displayName:"GLM-4 Air",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:0,creativity:78,speed:90,cost:88}},"glm-4-long":{id:"glm-4-long",displayName:"GLM-4 Long",provider:"glm",maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:0,creativity:80,speed:50,cost:60},notes:"\u8D85\u957F\u4E0A\u4E0B\u6587\u4E13\u7528,1M tokens"},"glm-4-airx":{id:"glm-4-airx",displayName:"GLM-4 AirX",provider:"glm",maxInputTokens:8e3,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:0,creativity:70,speed:98,cost:98},notes:"\u8D85\u8F7B\u91CF\u7EA7\u6A21\u578B,\u6781\u5FEB\u901F\u5EA6"}},jo=class{models=new Map;constructor(){this.registerModels(Sg),this.registerModels(kg),this.registerModels(Cg),this.registerModels(Rg),this.registerModels(Eg),this.registerModels(Ig),this.registerModels(Mg);}registerModels(e){for(let[t,s]of Object.entries(e))if(this.models.set(t,s),s.aliases)for(let n of s.aliases)this.models.set(n,s);}getModel(e){return this.models.get(e)}getAllModels(){let e=new Map;for(let t of this.models.values())e.set(t.id,t);return Array.from(e.values())}getModelsByProvider(e){return this.getAllModels().filter(t=>t.provider===e)}hasModel(e){return this.models.has(e)}toModelCapability(e){let t=this.getModel(e);if(t)return {modelAlias:t.id,strengths:this.inferStrengths(t),scores:{coding:t.scores?.coding??50,reasoning:t.scores?.reasoning??50,vision:t.scores?.vision??0,creativity:t.scores?.creativity??50,speed:t.scores?.speed??50,cost:t.scores?.cost??50},features:{supportsVision:t.supportsVision??false,supportsTools:t.supportsTools??false,supportsFunctionCalling:t.supportsFunctionCalling??false,supportsStreaming:t.supportsStreaming??false,maxContextTokens:t.maxInputTokens,maxOutputTokens:t.maxOutputTokens}}}inferStrengths(e){let t=[],s=e.scores??{};return (s.coding??0)>=85&&t.push("coding"),(s.reasoning??0)>=85&&t.push("reasoning"),(s.vision??0)>=85&&t.push("image_analysis"),(s.creativity??0)>=85&&t.push("creative_writing"),t}},Fc=new jo;var Ft=class{validateParams(e){let t=this.getConstraints(),s=[],n=[];for(let i of Object.keys(e))t.supportedParams.has(i)||n.push(`Parameter '${i}' is not supported by this provider and will be ignored`);if(t.validators){for(let[i,o]of Object.entries(t.validators))if(e[i]!==void 0){let a=o(e[i],e);a===false?s.push(`Invalid value for parameter '${i}': ${e[i]}`):typeof a=="string"&&s.push(`Parameter '${i}': ${a}`);}}if(e.model&&e.max_tokens!==void 0){let i=this.getTokenLimits(e.model);i.found&&e.max_tokens>i.maxInput?s.push(`max_tokens (${e.max_tokens}) exceeds model context window (${i.maxInput}) for ${e.model}`):i.found&&e.max_tokens>i.maxOutput&&n.push(`max_tokens (${e.max_tokens}) exceeds recommended output limit (${i.maxOutput}) for ${e.model}, but is within context window`);}return {valid:s.length===0,errors:s,warnings:n.length>0?n:void 0}}getTokenLimits(e){let t=Fc.getModel(e);if(t)return {maxOutput:t.maxOutputTokens,maxInput:t.maxInputTokens,found:true,source:"model"};let s=this.getConstraints(),n=s.maxOutputTokens[e],i=s.maxInputTokens[e];if(n!==void 0&&i!==void 0)return {maxOutput:n,maxInput:i,found:true,source:"model"};for(let[o,a]of Object.entries(s.maxOutputTokens))if(this.matchPattern(e,o))return {maxOutput:a,maxInput:s.maxInputTokens[o]||128e3,found:true,source:"model"};return {maxOutput:4096,maxInput:128e3,found:false,source:"fallback"}}normalizeParams(e){let t=this.getConstraints(),s={};for(let[n,i]of Object.entries(e)){let o=t.paramAliases?.[n]||n;t.supportedParams.has(n)&&(s[o]=i);}if(t.defaults)for(let[n,i]of Object.entries(t.defaults))s[n]===void 0&&(s[n]=i);return s}matchPattern(e,t){return t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t}isParamSupported(e){return this.getConstraints().supportedParams.has(e)}getParamAlias(e){return this.getConstraints().paramAliases?.[e]||e}};function Fe(r,e){return t=>{let s=Number(t);return isNaN(s)?"Must be a number":s<r||s>e?`Must be between ${r} and ${e}`:true}}function Ps(r){return e=>r.includes(e)?true:`Must be one of: ${r.join(", ")}`}function Uc(r){return e=>{let t=typeof e;return t!==r?`Expected ${r}, got ${t}`:true}}function Hr(...r){return (e,t)=>{for(let s of r){let n=s(e,t);if(n!==true)return n}return true}}var Zt=class extends Ft{getConstraints(){return {maxOutputTokens:{"gpt-4o":16384,"gpt-4o-2024-11-20":16384,"gpt-4o-2024-08-06":16384,"gpt-4o-2024-05-13":4096,"gpt-4o-mini":16384,"gpt-4o-mini-2024-07-18":16384,"gpt-4-turbo":4096,"gpt-4-turbo-2024-04-09":4096,"gpt-4-turbo-preview":4096,"gpt-4-0125-preview":4096,"gpt-4-1106-preview":4096,"gpt-4":8192,"gpt-4-0613":8192,"gpt-4-0314":8192,"gpt-3.5-turbo":4096,"gpt-3.5-turbo-0125":4096,"gpt-3.5-turbo-1106":4096,o1:1e5,"o1-2024-12-17":1e5,"o1-preview":32768,"o1-preview-2024-09-12":32768,"o1-mini":65536,"o1-mini-2024-09-12":65536,o3:1e5,"o3-mini":1e5,"o3-mini-2025-01-31":1e5,"o4-mini":1e5,"gpt-5":1e5,"gpt-5.1":1e5,"gpt-5.1-codex":1e5,"gpt-5.1-codex-max":1e5,"gpt-5.1-codex-mini":1e5,"gpt-5.2":1e5,"gpt-5.2-codex":1e5,"gpt-5-codex":1e5,"gpt-5-codex-mini":1e5,"codex-mini-latest":1e5,"gpt-4.1":1e5,"gpt-4.1-2025-04-14":1e5,"gpt-4o*":16384,"gpt-4-turbo*":4096,"gpt-4.1*":1e5,"gpt-4*":8192,"gpt-3.5*":4096,"gpt-5*":1e5,"codex*":1e5,"o1*":1e5,"o3*":1e5,"o4*":1e5},maxInputTokens:{"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-2024-04-09":128e3,"gpt-4.1":1047576,"gpt-4.1-2025-04-14":1047576,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,"gpt-5":272e3,"gpt-5.1":272e3,"gpt-5.1-codex":272e3,"gpt-5.1-codex-max":272e3,"gpt-5.1-codex-mini":272e3,"gpt-5-codex":272e3,"gpt-5-codex-mini":272e3,"gpt-5.2":4e5,"gpt-5.2-codex":4e5,"codex-mini-latest":2e5,o1:2e5,"o1-preview":128e3,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"gpt-4o*":128e3,"gpt-4-turbo*":128e3,"gpt-4.1*":1047576,"gpt-5*":272e3,"gpt-5.2*":4e5,"codex*":272e3,"o1*":2e5,"o3*":2e5,"o4*":2e5},supportedParams:new Set(["model","messages","stream","stream_options","max_tokens","max_completion_tokens","temperature","top_p","top_k","frequency_penalty","presence_penalty","stop","n","seed","reasoning_effort","verbosity","tools","tool_choice","parallel_tool_calls","response_format","logprobs","top_logprobs","logit_bias","modalities","audio","user","safety_identifier","store","service_tier","prompt_cache_key","prompt_cache_retention","metadata","prediction","extra_body","search_parameters","web_search_options"]),validators:{temperature:Fe(0,2),top_p:Fe(0,1),frequency_penalty:Fe(-2,2),presence_penalty:Fe(-2,2),reasoning_effort:Ps(["low","medium","high"]),verbosity:Ps(["low","medium","high"]),tool_choice:e=>typeof e=="string"?["none","auto","required"].includes(e)||"Must be 'none', 'auto', or 'required'":typeof e=="object"&&e.type==="function"?true:"Invalid tool_choice format","response_format.type":Ps(["text","json_object","json_schema"]),stream:e=>typeof e=="boolean"||"Must be a boolean",n:Hr(e=>typeof e=="number"||"Must be a number",Fe(1,10)),max_tokens:(e,t)=>{let s=Number(e);if(isNaN(s))return "Must be a number";if(s<1)return "Must be at least 1";t?.model||"";return true}},defaults:{temperature:1,top_p:1,n:1,stream:false,max_tokens:4096}}}isResponsesAPIModel(e){return e.startsWith("o1")||e.startsWith("o3")}supportsReasoning(e){return this.isResponsesAPIModel(e)}supportsVision(e){return e.includes("gpt-4o")||e.includes("gpt-4-turbo")||e.includes("gpt-4-vision")}supportsTools(e){return e.startsWith("o1-preview")||e.startsWith("o1-mini")?false:e.includes("gpt-4")||e.includes("gpt-3.5-turbo")||e.startsWith("o3")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}};var Ut=class{combinePromptSections(e){return e.filter(s=>s.content.trim().length>0).sort((s,n)=>(s.order||0)-(n.order||0)).map(s=>s.title?`# ${s.title}
1447
+ `):t,i=e.filter(a=>a.role!=="system");return [{role:"system",content:o},...i]}return [{role:"system",content:t},...e]}normalizeSystemContent(e){return e?typeof e=="string"?e.trim():Array.isArray(e)?e.map(s=>!s||typeof s!="object"?"":s.type==="text"&&typeof s.text=="string"?s.text:"").join("").trim():String(e).trim():""}applyTokenLimits(e,t){if(!e)return t;let s=this.constraints.getTokenLimits(e);return Math.min(t||4096,s.maxOutput)}detectLanguage(){return process.env.NEOX_LANGUAGE==="en"?"en":"zh"}};var Rg={"gpt-5.2":{id:"gpt-5.2",displayName:"GPT-5.2",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:98,vision:92,creativity:94,speed:75,cost:25},releaseDate:"2025-12-11",notes:'400K \u4E0A\u4E0B\u6587\u7A97\u53E3,128K \u8F93\u51FA\u9650\u5236,\u4EE3\u53F7"Garlic"'},"gpt-5.2-codex":{id:"gpt-5.2-codex",displayName:"GPT-5.2 Codex",provider:"openai",aliases:["gpt-5.2-codex"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:98,reasoning:97,vision:90,creativity:92,speed:70,cost:20},releaseDate:"2025-12-10",notes:"GPT-5.2 \u7684 Codex \u9ED8\u8BA4\u7248\u672C,\u4E13\u4E3A\u7F16\u7A0B\u4EFB\u52A1\u4F18\u5316"},"gpt-5.2-codex-high":{id:"gpt-5.2-codex-high",displayName:"GPT-5.2 Codex High",provider:"openai",aliases:["gpt-5.2-codex-h"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:99,reasoning:98,vision:90,creativity:93,speed:60,cost:15},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u9AD8\u6027\u80FD\u6A21\u5F0F,\u6700\u5F3A\u7F16\u7A0B\u80FD\u529B,\u66F4\u6162\u66F4\u8D35"},"gpt-5.2-codex-medium":{id:"gpt-5.2-codex-medium",displayName:"GPT-5.2 Codex Medium",provider:"openai",aliases:["gpt-5.2-codex-m"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:94,vision:88,creativity:90,speed:80,cost:40},releaseDate:"2025-12-10",notes:"GPT-5.2 Codex \u5E73\u8861\u6A21\u5F0F,\u6027\u4EF7\u6BD4\u4F18\u9009"},"gpt-5.1":{id:"gpt-5.1",displayName:"GPT-5.1",provider:"openai",maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:96,vision:90,creativity:92,speed:80,cost:30},notes:"272K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA,\u9002\u5408\u957F\u4E0A\u4E0B\u6587\u4EFB\u52A1"},"gpt-5.1-codex":{id:"gpt-5.1-codex",displayName:"GPT-5.1 Codex",provider:"openai",aliases:["gpt-5-codex","gpt-5.1-codex-max"],maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:97,reasoning:95,vision:88,creativity:90,speed:75,cost:25},notes:"Codex \u4F18\u5316\u7248,400K \u4E0A\u4E0B\u6587,\u4E13\u4E3A agentic \u7F16\u7A0B\u5DE5\u4F5C\u6D41\u8BBE\u8BA1"},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",displayName:"GPT-5.1 Codex Mini",provider:"openai",aliases:["gpt-5-codex-mini"],maxInputTokens:272e3,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:85,speed:92,cost:85},notes:"\u66F4\u5FEB\u66F4\u4FBF\u5B9C\u7684 Codex \u7248\u672C"},"gpt-5":{id:"gpt-5",displayName:"GPT-5",provider:"openai",maxInputTokens:4e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:94,vision:90,creativity:94,speed:80,cost:35},deprecated:true,replacedBy:"gpt-5.1",notes:"\u5DF2\u88AB GPT-5.1 \u66FF\u4EE3"},"gpt-4.1":{id:"gpt-4.1",displayName:"GPT-4.1",provider:"openai",aliases:["gpt-4.1-2025-04-14"],maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:92,vision:88,creativity:90,speed:65,cost:15},releaseDate:"2025-04-14",notes:"\u8D85\u5927 1M+ \u4E0A\u4E0B\u6587\u7A97\u53E3,\u9002\u5408\u5904\u7406\u5927\u578B\u4EE3\u7801\u5E93"},"gpt-4o":{id:"gpt-4o",displayName:"GPT-4o",provider:"openai",aliases:["gpt-4o-2024-11-20","gpt-4o-2024-08-06"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:85,vision:88,creativity:88,speed:75,cost:50}},"gpt-4o-mini":{id:"gpt-4o-mini",displayName:"GPT-4o Mini",provider:"openai",aliases:["gpt-4o-mini-2024-07-18"],maxInputTokens:128e3,maxOutputTokens:16384,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:80,creativity:75,speed:92,cost:90}},o3:{id:"o3",displayName:"o3",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:99,vision:0,creativity:78,speed:40,cost:15},notes:"\u65B0\u4E00\u4EE3\u63A8\u7406\u6A21\u578B,\u63A8\u7406\u80FD\u529B\u6700\u5F3A"},"o3-mini":{id:"o3-mini",displayName:"o3 Mini",provider:"openai",aliases:["o3-mini-2025-01-31"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:65,cost:60}},"o4-mini":{id:"o4-mini",displayName:"o4 Mini",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:96,vision:0,creativity:76,speed:70,cost:55}},o1:{id:"o1",displayName:"o1",provider:"openai",aliases:["o1-2024-12-17"],maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:95,vision:0,creativity:75,speed:45,cost:25}},"o1-mini":{id:"o1-mini",displayName:"o1 Mini",provider:"openai",aliases:["o1-mini-2024-09-12"],maxInputTokens:128e3,maxOutputTokens:65536,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:82,reasoning:88,vision:0,creativity:70,speed:70,cost:70}},"codex-mini-latest":{id:"codex-mini-latest",displayName:"Codex Mini (Latest)",provider:"openai",maxInputTokens:2e5,maxOutputTokens:1e5,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:88,cost:80}},"gpt-4-turbo":{id:"gpt-4-turbo",displayName:"GPT-4 Turbo",provider:"openai",aliases:["gpt-4-turbo-2024-04-09"],maxInputTokens:128e3,maxOutputTokens:4096,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:87,vision:85,creativity:90,speed:70,cost:40}},"gpt-3.5-turbo":{id:"gpt-3.5-turbo",displayName:"GPT-3.5 Turbo",provider:"openai",maxInputTokens:16385,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:65,reasoning:60,vision:0,creativity:70,speed:95,cost:98}}},Eg={"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",displayName:"Claude Opus 4.5",provider:"anthropic",aliases:["claude-opus-4.5"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:98,reasoning:97,vision:90,creativity:95,speed:65,cost:20},releaseDate:"2025-11-24",notes:"\u6700\u5F3A Claude \u6A21\u578B,\u652F\u6301 Extended Thinking,\u4F01\u4E1A\u7248\u53EF\u6269\u5C55\u81F3 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",provider:"anthropic",aliases:["claude-sonnet-4.5","claude-sonnet-4-5-20250929-thinking"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:88,creativity:90,speed:80,cost:50},releaseDate:"2025-09-29",notes:"\u5E73\u8861\u6027\u80FD\u4E0E\u6210\u672C,beta \u7248\u672C\u652F\u6301 1M \u4E0A\u4E0B\u6587"},"claude-sonnet-4-20250514":{id:"claude-sonnet-4-20250514",displayName:"Claude Sonnet 4",provider:"anthropic",aliases:["claude-sonnet-4"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:88,speed:82,cost:55},notes:"2025-08-12 \u5347\u7EA7\u652F\u6301 1M beta \u4E0A\u4E0B\u6587"},"claude-opus-4-20250514":{id:"claude-opus-4-20250514",displayName:"Claude Opus 4",provider:"anthropic",aliases:["claude-opus-4"],maxInputTokens:2e5,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:96,reasoning:95,vision:88,creativity:94,speed:70,cost:25}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",provider:"anthropic",aliases:["claude-haiku-4.5"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:78,reasoning:75,vision:80,creativity:75,speed:95,cost:95},notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 4.5 \u6A21\u578B"},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",displayName:"Claude 3.5 Sonnet (New)",provider:"anthropic",aliases:["claude-3.5-sonnet-new","claude-3-5-sonnet-latest"],maxInputTokens:2e5,maxOutputTokens:16e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:85,cost:55},releaseDate:"2024-10-22",notes:"Claude 3.5 Sonnet \u5347\u7EA7\u7248"},"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",displayName:"Claude 3.5 Haiku",provider:"anthropic",aliases:["claude-3.5-haiku"],maxInputTokens:2e5,maxOutputTokens:8e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:72,vision:78,creativity:73,speed:98,cost:98},releaseDate:"2024-10-22",notes:"\u6700\u5FEB\u6700\u4FBF\u5B9C\u7684 Claude 3.5 \u6A21\u578B"}},Ig={"gemini-3-pro-preview":{id:"gemini-3-pro-preview",displayName:"Gemini 3 Pro Preview",provider:"gemini",aliases:["gemini-3-pro","gemini-3.0-pro-preview"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:94,reasoning:95,vision:96,creativity:94,speed:72,cost:35},releaseDate:"2026-01",notes:"Gemini 3 \u9884\u89C8\u7248,UI/\u89C6\u89C9\u8BBE\u8BA1\u4E13\u957F,1M \u4E0A\u4E0B\u6587"},"gemini-3.0-pro":{id:"gemini-3.0-pro",displayName:"Gemini 3.0 Pro",provider:"gemini",aliases:["gemini-3.0-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:96,vision:94,creativity:92,speed:70,cost:30},releaseDate:"2025-12",notes:"Flagship multimodal model with 1M context, high-precision reasoning"},"gemini-2.5-flash":{id:"gemini-2.5-flash",displayName:"Gemini 2.5 Flash",provider:"gemini",aliases:["gemini-2.5-flash-latest"],maxInputTokens:1048576,maxOutputTokens:65535,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:90,creativity:87,speed:92,cost:85},releaseDate:"2025-03",notes:"Fast and cost-efficient, ~1500 pages or 30K lines of code"},"gemini-2.5-pro":{id:"gemini-2.5-pro",displayName:"Gemini 2.5 Pro",provider:"gemini",aliases:["gemini-2.5-pro-latest"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:92,vision:92,creativity:90,speed:75,cost:40},releaseDate:"2025-03",notes:"Balanced performance with 1M context window"},"gemini-2.0-flash-thinking":{id:"gemini-2.0-flash-thinking",displayName:"Gemini 2.0 Flash Thinking",provider:"gemini",aliases:["gemini-2.0-flash-thinking-exp","gemini-2.0-flash-thinking-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:92,reasoning:94,vision:90,creativity:88,speed:85,cost:50},releaseDate:"2024-12-19",notes:"Shows model thought process, 1M context window"},"gemini-2.0-flash":{id:"gemini-2.0-flash",displayName:"Gemini 2.0 Flash",provider:"gemini",aliases:["gemini-2.0-flash-exp","gemini-2.0-flash-experimental"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:89,vision:90,creativity:87,speed:95,cost:75},releaseDate:"2024-12-11",notes:"Twice as fast as Gemini 1.5 Pro, multimodal with native image generation"},"gemini-1.5-pro":{id:"gemini-1.5-pro",displayName:"Gemini 1.5 Pro",provider:"gemini",aliases:["gemini-1.5-pro-latest","gemini-pro"],maxInputTokens:2e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:87,vision:88,creativity:85,speed:70,cost:50},releaseDate:"2024-05",notes:"2M context window - largest available, supports context caching"},"gemini-1.5-flash":{id:"gemini-1.5-flash",displayName:"Gemini 1.5 Flash",provider:"gemini",aliases:["gemini-1.5-flash-latest","gemini-flash"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:83,vision:85,creativity:82,speed:90,cost:85},releaseDate:"2024-05",notes:"Fast and efficient with 1M context, supports code execution"},"gemini-1.5-flash-8b":{id:"gemini-1.5-flash-8b",displayName:"Gemini 1.5 Flash-8B",provider:"gemini",aliases:["gemini-flash-8b"],maxInputTokens:1e6,maxOutputTokens:65536,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:82,creativity:77,speed:98,cost:95},releaseDate:"2024-10",notes:"Smaller 8B model, extremely fast and cost-effective"},"gemini-1.0-pro":{id:"gemini-1.0-pro",displayName:"Gemini 1.0 Pro",provider:"gemini",aliases:["gemini-pro-1.0"],maxInputTokens:32768,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:75,reasoning:73,vision:0,creativity:75,speed:85,cost:90},releaseDate:"2023-12",notes:"Original Gemini Pro, text-only"},"gemini-1.0-pro-vision":{id:"gemini-1.0-pro-vision",displayName:"Gemini 1.0 Pro Vision",provider:"gemini",aliases:["gemini-pro-vision"],maxInputTokens:16384,maxOutputTokens:2048,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:80,creativity:72,speed:80,cost:88},releaseDate:"2023-12",notes:"Original multimodal Gemini with vision support"}},Mg={"kimi-k2-0905-preview":{id:"kimi-k2-0905-preview",displayName:"Kimi K2 (0905 Preview)",provider:"kimi",aliases:["kimi-k2","kimi-k2-preview"],maxInputTokens:256e3,maxOutputTokens:8192,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:70},releaseDate:"2025-09",notes:"MoE \u67B6\u6784 K2 \u9884\u89C8\u7248\uFF0C256K \u4E0A\u4E0B\u6587"}},Ag={"deepseek-v3.2":{id:"deepseek-v3.2",displayName:"DeepSeek V3.2",provider:"deepseek",aliases:["deepseek-v3.2-exp"],maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:92,reasoning:90,vision:0,creativity:80,speed:85,cost:95},releaseDate:"2025-09-29",notes:"\u5B9E\u9A8C\u7248\u672C,\u6027\u80FD\u663E\u8457\u63D0\u5347"},"deepseek-v3.1":{id:"deepseek-v3.1",displayName:"DeepSeek V3.1",provider:"deepseek",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:0,creativity:78,speed:88,cost:96},releaseDate:"2025-08",notes:"\u6DF7\u5408\u67B6\u6784\u6A21\u578B"},"deepseek-chat":{id:"deepseek-chat",displayName:"DeepSeek Chat",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:82,vision:0,creativity:75,speed:85,cost:95},notes:"\u901A\u7528\u5BF9\u8BDD\u6A21\u578B,\u6210\u672C\u6781\u4F4E"},"deepseek-coder":{id:"deepseek-coder",displayName:"DeepSeek Coder",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:95,reasoning:85,vision:0,creativity:70,speed:88,cost:96},notes:"\u4E13\u4E3A\u7F16\u7A0B\u4F18\u5316,\u4EE3\u7801\u80FD\u529B\u7A81\u51FA"},"deepseek-reasoner":{id:"deepseek-reasoner",displayName:"DeepSeek Reasoner",provider:"deepseek",maxInputTokens:64e3,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:88,reasoning:96,vision:0,creativity:75,speed:60,cost:90},notes:"\u63A8\u7406\u4E13\u7528\u6A21\u578B,\u652F\u6301\u957F\u8F93\u51FA"}},Pg={"minimax-text-01":{id:"minimax-text-01",displayName:"MiniMax Text-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:90,vision:0,creativity:85,speed:55,cost:70},notes:"4M \u4E0A\u4E0B\u6587\u7A97\u53E3,Lightning Attention + MoE \u67B6\u6784,\u5F00\u6E90\u53EF\u7528"},"minimax-m1-80k":{id:"minimax-m1-80k",displayName:"MiniMax M1-80K",provider:"minimax",maxInputTokens:1e6,maxOutputTokens:8e4,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,supportsThinking:true,scores:{coding:90,reasoning:92,vision:0,creativity:82,speed:65,cost:75},notes:"1M \u4E0A\u4E0B\u6587 + 80K \u601D\u8003\u9884\u7B97"},"minimax-m2.1":{id:"minimax-m2.1",displayName:"MiniMax M2.1",provider:"minimax",maxInputTokens:2e5,maxOutputTokens:64e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:93,reasoning:88,vision:0,creativity:80,speed:82,cost:85},releaseDate:"2025-12",notes:"\u7F16\u7A0B\u548C Agentic \u5DE5\u4F5C\u6D41\u4F18\u5316,\u652F\u6301\u591A\u8BED\u8A00"},"minimax-vl-01":{id:"minimax-vl-01",displayName:"MiniMax VL-01",provider:"minimax",maxInputTokens:4e6,maxOutputTokens:1e6,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:92,creativity:88,speed:60,cost:65},notes:"\u591A\u6A21\u6001\u6A21\u578B,\u652F\u6301\u6587\u672C\u548C\u56FE\u50CF"}},Og={"glm-4.7":{id:"glm-4.7",displayName:"GLM-4.7",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:90,reasoning:88,vision:85,creativity:87,speed:80,cost:70},releaseDate:"2025-12-22",notes:"\u6700\u65B0\u7248\u672C,200K \u4E0A\u4E0B\u6587,128K \u8F93\u51FA"},"glm-4.6":{id:"glm-4.6",displayName:"GLM-4.6",provider:"glm",maxInputTokens:2e5,maxOutputTokens:128e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:83,creativity:85,speed:82,cost:75},releaseDate:"2025-09-10",notes:"\u4ECE 128K \u6269\u5C55\u81F3 200K \u4E0A\u4E0B\u6587"},"glm-4.5":{id:"glm-4.5",displayName:"GLM-4.5",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:86,reasoning:84,vision:80,creativity:83,speed:85,cost:80},releaseDate:"2025-07"},"glm-4-flash":{id:"glm-4-flash",displayName:"GLM-4 Flash",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:82,reasoning:80,vision:78,creativity:80,speed:95,cost:92},notes:"\u5FEB\u901F\u6A21\u578B,\u76F8\u5F53\u4E8E 300 \u9875\u4E66\u7684\u4E0A\u4E0B\u6587"},"glm-4-plus":{id:"glm-4-plus",displayName:"GLM-4 Plus",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:true,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:88,reasoning:86,vision:82,creativity:85,speed:78,cost:65}},"glm-4-air":{id:"glm-4-air",displayName:"GLM-4 Air",provider:"glm",maxInputTokens:128e3,maxOutputTokens:32e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:80,reasoning:78,vision:0,creativity:78,speed:90,cost:88}},"glm-4-long":{id:"glm-4-long",displayName:"GLM-4 Long",provider:"glm",maxInputTokens:1e6,maxOutputTokens:128e3,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:85,reasoning:88,vision:0,creativity:80,speed:50,cost:60},notes:"\u8D85\u957F\u4E0A\u4E0B\u6587\u4E13\u7528,1M tokens"},"glm-4-airx":{id:"glm-4-airx",displayName:"GLM-4 AirX",provider:"glm",maxInputTokens:8e3,maxOutputTokens:4096,supportsVision:false,supportsTools:true,supportsFunctionCalling:true,supportsStreaming:true,scores:{coding:70,reasoning:68,vision:0,creativity:70,speed:98,cost:98},notes:"\u8D85\u8F7B\u91CF\u7EA7\u6A21\u578B,\u6781\u5FEB\u901F\u5EA6"}},Gi=class{models=new Map;constructor(){this.registerModels(Rg),this.registerModels(Eg),this.registerModels(Ig),this.registerModels(Mg),this.registerModels(Ag),this.registerModels(Pg),this.registerModels(Og);}registerModels(e){for(let[t,s]of Object.entries(e))if(this.models.set(t,s),s.aliases)for(let n of s.aliases)this.models.set(n,s);}getModel(e){return this.models.get(e)}getAllModels(){let e=new Map;for(let t of this.models.values())e.set(t.id,t);return Array.from(e.values())}getModelsByProvider(e){return this.getAllModels().filter(t=>t.provider===e)}hasModel(e){return this.models.has(e)}toModelCapability(e){let t=this.getModel(e);if(t)return {modelAlias:t.id,strengths:this.inferStrengths(t),scores:{coding:t.scores?.coding??50,reasoning:t.scores?.reasoning??50,vision:t.scores?.vision??0,creativity:t.scores?.creativity??50,speed:t.scores?.speed??50,cost:t.scores?.cost??50},features:{supportsVision:t.supportsVision??false,supportsTools:t.supportsTools??false,supportsFunctionCalling:t.supportsFunctionCalling??false,supportsStreaming:t.supportsStreaming??false,maxContextTokens:t.maxInputTokens,maxOutputTokens:t.maxOutputTokens}}}inferStrengths(e){let t=[],s=e.scores??{};return (s.coding??0)>=85&&t.push("coding"),(s.reasoning??0)>=85&&t.push("reasoning"),(s.vision??0)>=85&&t.push("image_analysis"),(s.creativity??0)>=85&&t.push("creative_writing"),t}},Gc=new Gi;var Ft=class{validateParams(e){let t=this.getConstraints(),s=[],n=[];for(let o of Object.keys(e))t.supportedParams.has(o)||n.push(`Parameter '${o}' is not supported by this provider and will be ignored`);if(t.validators){for(let[o,i]of Object.entries(t.validators))if(e[o]!==void 0){let a=i(e[o],e);a===false?s.push(`Invalid value for parameter '${o}': ${e[o]}`):typeof a=="string"&&s.push(`Parameter '${o}': ${a}`);}}if(e.model&&e.max_tokens!==void 0){let o=this.getTokenLimits(e.model);o.found&&e.max_tokens>o.maxInput?s.push(`max_tokens (${e.max_tokens}) exceeds model context window (${o.maxInput}) for ${e.model}`):o.found&&e.max_tokens>o.maxOutput&&n.push(`max_tokens (${e.max_tokens}) exceeds recommended output limit (${o.maxOutput}) for ${e.model}, but is within context window`);}return {valid:s.length===0,errors:s,warnings:n.length>0?n:void 0}}getTokenLimits(e){let t=Gc.getModel(e);if(t)return {maxOutput:t.maxOutputTokens,maxInput:t.maxInputTokens,found:true,source:"model"};let s=this.getConstraints(),n=s.maxOutputTokens[e],o=s.maxInputTokens[e];if(n!==void 0&&o!==void 0)return {maxOutput:n,maxInput:o,found:true,source:"model"};for(let[i,a]of Object.entries(s.maxOutputTokens))if(this.matchPattern(e,i))return {maxOutput:a,maxInput:s.maxInputTokens[i]||128e3,found:true,source:"model"};return {maxOutput:4096,maxInput:128e3,found:false,source:"fallback"}}normalizeParams(e){let t=this.getConstraints(),s={};for(let[n,o]of Object.entries(e)){let i=t.paramAliases?.[n]||n;t.supportedParams.has(n)&&(s[i]=o);}if(t.defaults)for(let[n,o]of Object.entries(t.defaults))s[n]===void 0&&(s[n]=o);return s}matchPattern(e,t){return t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t}isParamSupported(e){return this.getConstraints().supportedParams.has(e)}getParamAlias(e){return this.getConstraints().paramAliases?.[e]||e}};function Fe(r,e){return t=>{let s=Number(t);return isNaN(s)?"Must be a number":s<r||s>e?`Must be between ${r} and ${e}`:true}}function Os(r){return e=>r.includes(e)?true:`Must be one of: ${r.join(", ")}`}function Bc(r){return e=>{let t=typeof e;return t!==r?`Expected ${r}, got ${t}`:true}}function qr(...r){return (e,t)=>{for(let s of r){let n=s(e,t);if(n!==true)return n}return true}}var Qt=class extends Ft{getConstraints(){return {maxOutputTokens:{"gpt-4o":16384,"gpt-4o-2024-11-20":16384,"gpt-4o-2024-08-06":16384,"gpt-4o-2024-05-13":4096,"gpt-4o-mini":16384,"gpt-4o-mini-2024-07-18":16384,"gpt-4-turbo":4096,"gpt-4-turbo-2024-04-09":4096,"gpt-4-turbo-preview":4096,"gpt-4-0125-preview":4096,"gpt-4-1106-preview":4096,"gpt-4":8192,"gpt-4-0613":8192,"gpt-4-0314":8192,"gpt-3.5-turbo":4096,"gpt-3.5-turbo-0125":4096,"gpt-3.5-turbo-1106":4096,o1:1e5,"o1-2024-12-17":1e5,"o1-preview":32768,"o1-preview-2024-09-12":32768,"o1-mini":65536,"o1-mini-2024-09-12":65536,o3:1e5,"o3-mini":1e5,"o3-mini-2025-01-31":1e5,"o4-mini":1e5,"gpt-5":1e5,"gpt-5.1":1e5,"gpt-5.1-codex":1e5,"gpt-5.1-codex-max":1e5,"gpt-5.1-codex-mini":1e5,"gpt-5.2":1e5,"gpt-5.2-codex":1e5,"gpt-5-codex":1e5,"gpt-5-codex-mini":1e5,"codex-mini-latest":1e5,"gpt-4.1":1e5,"gpt-4.1-2025-04-14":1e5,"gpt-4o*":16384,"gpt-4-turbo*":4096,"gpt-4.1*":1e5,"gpt-4*":8192,"gpt-3.5*":4096,"gpt-5*":1e5,"codex*":1e5,"o1*":1e5,"o3*":1e5,"o4*":1e5},maxInputTokens:{"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4-turbo-2024-04-09":128e3,"gpt-4.1":1047576,"gpt-4.1-2025-04-14":1047576,"gpt-4":8192,"gpt-4-32k":32768,"gpt-3.5-turbo":16385,"gpt-3.5-turbo-16k":16385,"gpt-5":272e3,"gpt-5.1":272e3,"gpt-5.1-codex":272e3,"gpt-5.1-codex-max":272e3,"gpt-5.1-codex-mini":272e3,"gpt-5-codex":272e3,"gpt-5-codex-mini":272e3,"gpt-5.2":4e5,"gpt-5.2-codex":4e5,"codex-mini-latest":2e5,o1:2e5,"o1-preview":128e3,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"gpt-4o*":128e3,"gpt-4-turbo*":128e3,"gpt-4.1*":1047576,"gpt-5*":272e3,"gpt-5.2*":4e5,"codex*":272e3,"o1*":2e5,"o3*":2e5,"o4*":2e5},supportedParams:new Set(["model","messages","stream","stream_options","max_tokens","max_completion_tokens","temperature","top_p","top_k","frequency_penalty","presence_penalty","stop","n","seed","reasoning_effort","verbosity","tools","tool_choice","parallel_tool_calls","response_format","logprobs","top_logprobs","logit_bias","modalities","audio","user","safety_identifier","store","service_tier","prompt_cache_key","prompt_cache_retention","metadata","prediction","extra_body","search_parameters","web_search_options"]),validators:{temperature:Fe(0,2),top_p:Fe(0,1),frequency_penalty:Fe(-2,2),presence_penalty:Fe(-2,2),reasoning_effort:Os(["low","medium","high"]),verbosity:Os(["low","medium","high"]),tool_choice:e=>typeof e=="string"?["none","auto","required"].includes(e)||"Must be 'none', 'auto', or 'required'":typeof e=="object"&&e.type==="function"?true:"Invalid tool_choice format","response_format.type":Os(["text","json_object","json_schema"]),stream:e=>typeof e=="boolean"||"Must be a boolean",n:qr(e=>typeof e=="number"||"Must be a number",Fe(1,10)),max_tokens:(e,t)=>{let s=Number(e);if(isNaN(s))return "Must be a number";if(s<1)return "Must be at least 1";t?.model||"";return true}},defaults:{temperature:1,top_p:1,n:1,stream:false,max_tokens:4096}}}isResponsesAPIModel(e){return e.startsWith("o1")||e.startsWith("o3")}supportsReasoning(e){return this.isResponsesAPIModel(e)}supportsVision(e){return e.includes("gpt-4o")||e.includes("gpt-4-turbo")||e.includes("gpt-4-vision")}supportsTools(e){return e.startsWith("o1-preview")||e.startsWith("o1-mini")?false:e.includes("gpt-4")||e.includes("gpt-3.5-turbo")||e.startsWith("o3")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}};var Ut=class{combinePromptSections(e){return e.filter(s=>s.content.trim().length>0).sort((s,n)=>(s.order||0)-(n.order||0)).map(s=>s.title?`# ${s.title}
1448
1448
 
1449
1449
  ${s.content}`:s.content).join(`
1450
1450
 
1451
- `)}getWorkingDirectorySection(e,t){return t==="zh"?{title:"\u5DE5\u4F5C\u76EE\u5F55",content:`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55: ${e}`,order:10}:{title:"Working Directory",content:`Current working directory: ${e}`,order:10}}modelMatches(e,t){return e?t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t:false}isModelType(e,...t){return e?t.some(s=>this.modelMatches(e,s)):false}};function Qt(r){return r.replace(/\n{3,}/g,`
1451
+ `)}getWorkingDirectorySection(e,t){return t==="zh"?{title:"\u5DE5\u4F5C\u76EE\u5F55",content:`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55: ${e}`,order:10}:{title:"Working Directory",content:`Current working directory: ${e}`,order:10}}modelMatches(e,t){return e?t.includes("*")?new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e):e===t:false}isModelType(e,...t){return e?t.some(s=>this.modelMatches(e,s)):false}};function es(r){return r.replace(/\n{3,}/g,`
1452
1452
 
1453
- `).trim()}var Ag=`You are Claude Code, Anthropic's official CLI for Claude.
1453
+ `).trim()}var Lg=`You are Claude Code, Anthropic's official CLI for Claude.
1454
1454
 
1455
1455
  You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
1456
1456
 
@@ -1488,11 +1488,11 @@ When planning tasks, provide concrete implementation steps without time estimate
1488
1488
  You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
1489
1489
  These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
1490
1490
 
1491
- It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.`.trim(),es=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:i}=e;return this.isResponsesAPIModel(n)?this.buildResponsesAPIPrompt(i):this.buildChatCompletionsPrompt(t,s,n,i)}buildResponsesAPIPrompt(e){let t=Ag;return e&&e.trim()&&(t+=`
1491
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.`.trim(),ts=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:o}=e;return this.isResponsesAPIModel(n)?this.buildResponsesAPIPrompt(o):this.buildChatCompletionsPrompt(t,s,n,o)}buildResponsesAPIPrompt(e){let t=Lg;return e&&e.trim()&&(t+=`
1492
1492
 
1493
1493
  # Custom Instructions
1494
1494
 
1495
- `+e.trim()),Qt(t)}buildChatCompletionsPrompt(e,t,s,n){let i=[];return i.push({content:this.getCoreInstructions(t,s),order:0}),i.push(this.getWorkingDirectorySection(e,t)),i.push({content:this.getCapabilitiesSection(t,s),order:20}),i.push({title:t==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(t,s),order:30}),i.push({title:t==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(t),order:40}),i.push({content:this.getGeneralRules(t),order:50}),n&&n.trim()&&i.push({title:t==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:n.trim(),order:60}),Qt(this.combinePromptSections(i))}getCoreInstructions(e,t){let s=this.getModelDisplayName(t);return e==="zh"?`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684 AI \u7F16\u7A0B\u52A9\u624B\uFF0C\u57FA\u4E8E ${s} \u63D0\u4F9B\u652F\u6301\u3002
1495
+ `+e.trim()),es(t)}buildChatCompletionsPrompt(e,t,s,n){let o=[];return o.push({content:this.getCoreInstructions(t,s),order:0}),o.push(this.getWorkingDirectorySection(e,t)),o.push({content:this.getCapabilitiesSection(t,s),order:20}),o.push({title:t==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(t,s),order:30}),o.push({title:t==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(t),order:40}),o.push({content:this.getGeneralRules(t),order:50}),n&&n.trim()&&o.push({title:t==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:n.trim(),order:60}),es(this.combinePromptSections(o))}getCoreInstructions(e,t){let s=this.getModelDisplayName(t);return e==="zh"?`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684 AI \u7F16\u7A0B\u52A9\u624B\uFF0C\u57FA\u4E8E ${s} \u63D0\u4F9B\u652F\u6301\u3002
1496
1496
 
1497
1497
  \u4F60\u7684\u4E3B\u8981\u804C\u8D23\u662F\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u8F6F\u4EF6\u5DE5\u7A0B\u4EFB\u52A1\uFF0C\u5305\u62EC\uFF1A
1498
1498
  - \u4EE3\u7801\u751F\u6210\u548C\u4FEE\u6539
@@ -1504,22 +1504,22 @@ Your primary responsibilities include:
1504
1504
  - Code generation and modification
1505
1505
  - Debugging and problem-solving
1506
1506
  - Technical consulting and advice
1507
- - File operations and project management`}getCapabilitiesSection(e,t){let s=this.supportsVision(t),n=this.isResponsesAPIModel(t);if(e==="zh"){let o=`# \u4F60\u7684\u80FD\u529B
1507
+ - File operations and project management`}getCapabilitiesSection(e,t){let s=this.supportsVision(t),n=this.isResponsesAPIModel(t);if(e==="zh"){let i=`# \u4F60\u7684\u80FD\u529B
1508
1508
 
1509
1509
  - **\u4EE3\u7801\u7406\u89E3**: \u9605\u8BFB\u548C\u5206\u6790\u4EE3\u7801\uFF0C\u63D0\u4F9B\u4F18\u5316\u5EFA\u8BAE
1510
1510
  - **\u4EE3\u7801\u751F\u6210**: \u6839\u636E\u9700\u6C42\u751F\u6210\u9AD8\u8D28\u91CF\u4EE3\u7801
1511
- - **\u5DE5\u5177\u8C03\u7528**: \u6267\u884C\u6587\u4EF6\u64CD\u4F5C\u3001\u8FD0\u884C\u547D\u4EE4\u7B49`;return s&&(o+=`
1512
- - **\u89C6\u89C9\u7406\u89E3**: \u5206\u6790\u56FE\u7247\u3001\u622A\u56FE\u3001\u56FE\u8868\u7B49\u89C6\u89C9\u5185\u5BB9`),n&&(o+=`
1513
- - **\u6DF1\u5EA6\u63A8\u7406**: \u4F7F\u7528 reasoning_effort \u8FDB\u884C\u590D\u6742\u95EE\u9898\u5206\u6790`),o}let i=`# Your Capabilities
1511
+ - **\u5DE5\u5177\u8C03\u7528**: \u6267\u884C\u6587\u4EF6\u64CD\u4F5C\u3001\u8FD0\u884C\u547D\u4EE4\u7B49`;return s&&(i+=`
1512
+ - **\u89C6\u89C9\u7406\u89E3**: \u5206\u6790\u56FE\u7247\u3001\u622A\u56FE\u3001\u56FE\u8868\u7B49\u89C6\u89C9\u5185\u5BB9`),n&&(i+=`
1513
+ - **\u6DF1\u5EA6\u63A8\u7406**: \u4F7F\u7528 reasoning_effort \u8FDB\u884C\u590D\u6742\u95EE\u9898\u5206\u6790`),i}let o=`# Your Capabilities
1514
1514
 
1515
1515
  - **Code Understanding**: Read and analyze code, provide optimization suggestions
1516
1516
  - **Code Generation**: Generate high-quality code based on requirements
1517
- - **Tool Execution**: Perform file operations, run commands, etc.`;return s&&(i+=`
1518
- - **Vision Understanding**: Analyze images, screenshots, charts, etc.`),n&&(i+=`
1519
- - **Deep Reasoning**: Use reasoning_effort for complex problem analysis`),i}getConstraintInstructions(e,t){let s=this.isResponsesAPIModel(t);if(e==="zh"){let i=`- **max_tokens**: \u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF08\u6839\u636E\u6A21\u578B\u4E0D\u540C\uFF09
1517
+ - **Tool Execution**: Perform file operations, run commands, etc.`;return s&&(o+=`
1518
+ - **Vision Understanding**: Analyze images, screenshots, charts, etc.`),n&&(o+=`
1519
+ - **Deep Reasoning**: Use reasoning_effort for complex problem analysis`),o}getConstraintInstructions(e,t){let s=this.isResponsesAPIModel(t);if(e==="zh"){let o=`- **max_tokens**: \u6700\u5927\u8F93\u51FA\u957F\u5EA6\uFF08\u6839\u636E\u6A21\u578B\u4E0D\u540C\uFF09
1520
1520
  - **temperature**: 0.0 - 2.0\uFF0C\u63A7\u5236\u968F\u673A\u6027
1521
- - **top_p**: 0.0 - 1.0\uFF0C\u6838\u91C7\u6837\u53C2\u6570`;return s&&(i+=`
1522
- - **reasoning_effort**: low/medium/high\uFF0C\u63A8\u7406\u5F3A\u5EA6`),i}let n=`- **max_tokens**: Maximum output length (varies by model)
1521
+ - **top_p**: 0.0 - 1.0\uFF0C\u6838\u91C7\u6837\u53C2\u6570`;return s&&(o+=`
1522
+ - **reasoning_effort**: low/medium/high\uFF0C\u63A8\u7406\u5F3A\u5EA6`),o}let n=`- **max_tokens**: Maximum output length (varies by model)
1523
1523
  - **temperature**: 0.0 - 2.0, controls randomness
1524
1524
  - **top_p**: 0.0 - 1.0, nucleus sampling parameter`;return s&&(n+=`
1525
1525
  - **reasoning_effort**: low/medium/high, reasoning intensity`),n}getToolUseInstructions(e){return e==="zh"?`\u4F7F\u7528 OpenAI Function Calling \u683C\u5F0F\u8C03\u7528\u5DE5\u5177\uFF1A
@@ -1562,26 +1562,26 @@ Tool results are returned via messages with role "tool".`}getGeneralRules(e){ret
1562
1562
  1. **Accuracy First**: Ensure correctness of code and suggestions
1563
1563
  2. **Be Concise**: Avoid redundancy, answer directly
1564
1564
  3. **Safety First**: No malicious code, be aware of security risks
1565
- 4. **Stay Professional**: Objective, technical communication style`}getModelDisplayName(e){return e?e.includes("o3")?"OpenAI o3":e.includes("o1")?"OpenAI o1":e.includes("gpt-4o")?"GPT-4o":e.includes("gpt-4")?"GPT-4":e.includes("gpt-3.5")?"GPT-3.5":e:"GPT-4"}isResponsesAPIModel(e){return this.isModelType(e,"o1*","o3*")}supportsVision(e){return this.isModelType(e,"gpt-4o*","gpt-4-turbo*","gpt-4-vision*")}};le();var Ng=16e3;function jc(r,e=Ng){if(!r||r.length<=e)return r;let t=r.split(`
1566
- `).length,s=r.length,n=Math.floor(e*.4),i=Math.floor(e*.4),o=n,a=r.length-i;for(;o>0&&(r.charCodeAt(o)&192)===128;)o--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,o),c=r.slice(a),p=`
1565
+ 4. **Stay Professional**: Objective, technical communication style`}getModelDisplayName(e){return e?e.includes("o3")?"OpenAI o3":e.includes("o1")?"OpenAI o1":e.includes("gpt-4o")?"GPT-4o":e.includes("gpt-4")?"GPT-4":e.includes("gpt-3.5")?"GPT-3.5":e:"GPT-4"}isResponsesAPIModel(e){return this.isModelType(e,"o1*","o3*")}supportsVision(e){return this.isModelType(e,"gpt-4o*","gpt-4-turbo*","gpt-4-vision*")}};le();var jg=16e3;function Wc(r,e=jg){if(!r||r.length<=e)return r;let t=r.split(`
1566
+ `).length,s=r.length,n=Math.floor(e*.4),o=Math.floor(e*.4),i=n,a=r.length-o;for(;i>0&&(r.charCodeAt(i)&192)===128;)i--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,i),c=r.slice(a),p=`
1567
1567
 
1568
1568
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1569
1569
 
1570
- `;return l+p+c}function Gc(r,e={}){let t={...r};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 Bc(r,e){if(!r)return null;if(e?.reasoning)return {effort:e.reasoning.effort||"low",verbosity:e.reasoning.verbosity||"low",summary:e.reasoning.summary||"auto"};let t=process.env.CD_REASONING_EFFORT||process.env.NEOX_REASONING_EFFORT,s=process.env.CD_REASONING_VERBOSITY||process.env.NEOX_REASONING_VERBOSITY,n=process.env.CD_REASONING_SUMMARY||process.env.NEOX_REASONING_SUMMARY;return t||s||n?{effort:t||"low",verbosity:s||"low",summary:n||"auto"}:null}var Ct=class{client;defaultModel;isProxy;useResponsesAPI;apiEndpoint;streamFormat;retryConfig;baseUrl;privacySettings;sessionId;doubaoThinking;apiKey;modelConfig;structuredOutputMode;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.apiKey=e.apiKey,this.sessionId=e.sessionId||`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,this.privacySettings=e.privacySettings||{},this.doubaoThinking=e.doubaoThinking,this.modelConfig=e.modelConfig,this.structuredOutputMode=e.structuredOutputMode||"json_schema",this.client=Pg.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=Cs("openai",this.baseUrl);this.retryConfig=Lt(void 0,{...t,...e.retry}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Initialized with:",{baseUrl:this.baseUrl,isProxy:this.isProxy,useResponsesAPI:this.useResponsesAPI,apiEndpoint:this.apiEndpoint,streamFormat:this.streamFormat});}async chat(e,t={}){let{model:s=this.defaultModel}=t;return this.shouldUseResponsesAPI(s)?this.chatWithResponsesAPI(e,t):this.chatWithChatCompletions(e,t)}async*chatStreamed(e,t={}){let{model:s=this.defaultModel}=t;this.shouldUseResponsesAPI(s)?yield*this.chatStreamedWithResponsesAPI(e,t):yield*this.chatStreamedWithChatCompletions(e,t);}async chatWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:i=.7,maxInputTokens:o}=t,a=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:o,stream:false}),l=`${this.client.defaults.baseURL}/chat/completions`;te.llmRequest("openai",s,a,l,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Request",{url:l,payload:a});let c=this.retryConfig.requestMaxRetries,u=null;for(let p=0;p<=c;p++)try{let d=Date.now(),m=await this.client.post("/chat/completions",a),h=Date.now()-d;return te.llmResponse("openai",h,m.data.usage,m.data.choices[0]),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Response",{duration:`${h}ms`,data:m.data}),m.data}catch(d){u=d;let m=tt(d);if(g.error("OpenAI",`Request Error - URL: ${l}`),g.error("OpenAI",`Error: ${d.message}`),d.response?.data)try{let b=d.response.data;if(typeof b=="string")g.error("OpenAI",`Response: ${b.substring(0,500)}`);else if(b&&typeof b=="object"){let _={error:b.error,message:b.message,type:b.type,code:b.code};g.error("OpenAI",`Response: ${JSON.stringify(_).substring(0,500)}`);}}catch{g.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Error",{url:l,message:d.message,category:m.category,retryable:m.retryable,attempt:`${p+1}/${c+1}`}),te.llmError("openai",d),!m.retryable||p===c)throw m;let h=d.response?.headers?.["retry-after"],f=St(h),y=Dt(f,p+1,this.retryConfig);g.info("OpenAI",`Request failed (${m.code}), retrying in ${qe(y)} (${p+1}/${c})...`),await Is(y);}throw u||new Error("Unknown error during retry")}async*chatStreamedWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:i=.7,maxInputTokens:o,signal:a}=t,l=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:o,stream:true}),c=`${this.client.defaults.baseURL}${this.apiEndpoint}`;te.llmRequest("openai-stream",s,l,c,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Stream Request",{url:c,endpoint:this.apiEndpoint,payload:l});let u=this.retryConfig.streamMaxRetries,p=0;for(;;)try{if(a?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let d=Date.now(),m=await this.client.post(this.apiEndpoint,l,{responseType:"stream",signal:a});if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Started",{status:m.status}),m.status!==200){let f="";for await(let y of m.data)f+=y.toString();throw new Error(`OpenAI API error: ${m.status} - ${f}`)}this.streamFormat==="anthropic"?yield*this.parseAnthropicStreamResponse(m.data):yield*this.parseOpenAIStreamResponse(m.data,a);let h=Date.now()-d;te.llmResponse("openai-stream",h,{},{}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Complete",{duration:`${h}ms`});return}catch(d){let m=tt(d);if(g.error("OpenAI",`Stream Error - Request URL: ${c}`),g.error("OpenAI",`Error: ${d.message}`),d.response?.data)try{let h=d.response.data;if(typeof h=="string")g.error("OpenAI",`Response: ${h.substring(0,500)}`);else if(h&&typeof h=="object"){let f={error:h.error,message:h.message,type:h.type,code:h.code};g.error("OpenAI",`Response: ${JSON.stringify(f).substring(0,500)}`);}}catch{g.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Error Details",{url:c,message:d.message,retryable:m.retryable,status:d.response?.status}),te.llmError("openai-stream",d),m.retryable&&p<u){p++;let h=d.response?.headers?.["retry-after"],f=St(h),y=Dt(f,p,this.retryConfig);g.info("OpenAI",`Stream failed (${m.code}), reconnecting in ${qe(y)} (${p}/${u})...`),yield {choices:[],type:"stream_retry",error:m.message,errorCode:m.code,attempt:p,maxRetries:u,delayMs:y};try{await Yt(y,a);}catch(b){throw b?.name==="AbortError",b}continue}throw m}}buildChatCompletionsPayload(e,t){let{model:s,tools:n,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:s,messages:c,stream:l};return this.doubaoThinking&&s.includes("doubao-seed")&&(m.thinking={type:this.doubaoThinking.type},process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Doubao thinking mode: ${this.doubaoThinking.type}`)),n&&n.length>0&&(m.tools=n.map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${m.tools.length} tools to Doubao payload`)),m}let p={model:s,messages:c,temperature:i,stream:l};l&&(p.stream_options={include_usage:true}),a!==void 0&&(p.max_tokens=a);let d=Bc(false);return d&&(p.reasoning_effort=d.effort,d.verbosity&&(p.verbosity=d.verbosity)),n&&n.length>0&&(p.tools=n.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${p.tools.length} tools to Chat Completions payload`)),o&&(this.structuredOutputMode==="json_object"?p.response_format={type:"json_object"}:p.response_format={type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict??true}}),Gc(p,this.privacySettings)}formatMessagesForChatCompletions(e){return e.filter(t=>{let s=t.content&&(typeof t.content=="string"?t.content.trim().length>0:Array.isArray(t.content)&&t.content.length>0),n=t.tool_calls&&t.tool_calls.length>0;return s||n}).map(t=>{let s={role:t.role,content:null};if(t.role==="tool"){let n=typeof t.content=="string"?t.content:ee(t.content);s.content=jc(n);}else Array.isArray(t.content)?s.content=t.content:t.tool_calls&&t.tool_calls.length>0?s.content=t.content||"":s.content=t.content||null;return t.name&&(s.name=t.name),t.tool_call_id&&(s.tool_call_id=t.tool_call_id),t.tool_calls&&(s.tool_calls=t.tool_calls.map(n=>({id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}))),s})}async chatWithResponsesAPI(e,t){let s="",n=[],i;for await(let o of this.chatStreamedWithResponsesAPI(e,t)){let a=o.choices?.[0]?.delta;if(a&&(a.content&&(s+=a.content),a.tool_calls))for(let l of a.tool_calls){let c=n.find(u=>u.index===l.index);c?l.function?.arguments&&(c.function.arguments+=l.function.arguments):n.push({id:l.id||`call_${n.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:s||null,...n.length>0?{tool_calls:n}:{}},finish_reason:"stop"}],usage:i||{total_tokens:0,prompt_tokens:0,completion_tokens:0}}}async*chatStreamedWithResponsesAPI(e,t){let{model:s=this.defaultModel,tools:n,temperature:i=.7,structuredOutput:o,maxInputTokens:a,signal:l}=t,c=this.buildResponsesAPIPayload(e,{model:s,tools:n,temperature:i,structuredOutput:o,maxInputTokens:a}),u=`${this.client.defaults.baseURL}/responses`;if(te.llmRequest("openai-responses-stream",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"){g.info("OpenAI","Responses API Stream Request",{url:u,toolsCount:c.tools?.length||0}),process.env.CLI_DEBUG_PAYLOAD==="1"&&g.debug("OpenAI","Full Payload",c);let p=['-H "Content-Type: application/json"','-H "Accept: text/event-stream"',`-H "Authorization: Bearer ${this.apiKey}"`,`-H "conversation_id: ${this.sessionId}"`,`-H "session_id: ${this.sessionId}"`,'-H "user-agent: neox-cli/1.0.0"'],d=[`curl -X POST "${u}"`,...p,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(` \\
1571
- `),m=[`curl -X POST "${u}"`,...p,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(" ");g.info("CURL","\u2550".repeat(80)),g.info("CURL","Multi-line CURL command:"),g.info("CURL",d),g.info("CURL","\u2550".repeat(80)),g.info("CURL","One-line CURL (copy-paste ready):"),g.info("CURL",m),g.info("CURL","\u2550".repeat(80));}try{if(l?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let p=Date.now(),d={Accept:"text/event-stream",conversation_id:this.sessionId,session_id:this.sessionId,originator:"codex_cli_rs","x-codex-beta-features":"shell_snapshot"},m=await this.client.post("/responses",c,{responseType:"stream",signal:l,headers:d});if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Responses API Stream Started",{status:m.status}),m.status!==200){let f="";for await(let b of m.data)f+=b.toString();let y=Kt(f,m.status);throw new Error(`OpenAI Responses API error: ${m.status} - ${y.message}`)}yield*this.parseResponsesAPIStream(m.data,l);let h=Date.now()-p;te.llmResponse("openai-responses-stream",h,{},{}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Responses API Stream Complete",{duration:`${h}ms`});}catch(p){let d,m=p.response?.status;if(p.response?.data){let f=p.response.data;try{if(f&&typeof f.on=="function"){let y="";try{for await(let b of f)y+=b.toString();d=y;}catch{d="[Could not read error stream]";}}else if(typeof f=="string")d=f;else if(f&&typeof f=="object"){let y={error:f.error,message:f.message,type:f.type,code:f.code};d=JSON.stringify(y);}}catch{d="[Could not parse error data]";}}process.env.CLI_DEBUG==="1"&&g.error("OpenAI","Responses API Stream Error",{status:m,errorData:d,message:p.message}),te.llmError("openai-responses-stream",p);let h;if(m&&d){let f=Kt(d,m);h=`${f.message}${f.detail?`
1572
- `+f.detail:""}`;}else h=p.message||"Unknown error";throw new Error(h)}}buildResponsesAPIPayload(e,t){let{model:s,tools:n,temperature:i,structuredOutput:o,maxInputTokens:a}=t,l=this.convertToResponsesInput(e),c=this.buildResponsesInstructions(e);if(!c)throw new Error("[OpenAI Responses API] instructions field is required but no system message found");if(!l||l.length===0)throw new Error("[OpenAI Responses API] input array is empty - at least one user message is required");if(process.env.CLI_DEBUG==="1"){g.debug("OpenAI","Building Responses API payload",{instructionsLength:c.length,instructionsPreview:c.substring(0,300),inputItems:l.length,inputPreview:JSON.stringify(l.slice(0,2),null,2)}),g.debug("OpenAI","Full input array for Response API:",{totalMessages:e.length,messageRoles:e.map(y=>y.role),inputCount:l.length,fullInput:JSON.stringify(l,null,2)});let d=l.filter(y=>y.type==="function_call"),m=l.filter(y=>y.type==="function_call_output");g.debug("OpenAI","Function call ID matching check:",{callCount:d.length,outputCount:m.length,callIds:d.map(y=>({id:y.id||y.call_id,name:y.name})),outputIds:m.map(y=>({call_id:y.call_id}))});let h=new Set(d.map(y=>y.call_id||y.id)),f=m.filter(y=>!h.has(y.call_id));f.length>0&&g.warn("OpenAI",`\u26A0\uFE0F Found ${f.length} unmatched function_call_output!`,{unmatchedCallIds:f.map(y=>y.call_id)});}let u={model:s,instructions:c,input:l};n&&n.length>0&&(u.tools=n.map(d=>this.formatResponsesFunctionTool(d)),u.tool_choice="auto",u.parallel_tool_calls=true,process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${u.tools.length} tools`));let p=Bc(true,this.modelConfig);return p&&(u.reasoning={effort:p.effort,summary:p.summary||"auto"}),u.store=false,u.stream=true,p&&(u.include=["reasoning.encrypted_content"]),u.prompt_cache_key=this.sessionId,Gc(u,this.privacySettings)}buildResponsesInstructions(e){let t=No({workDir:process.cwd(),language:"zh",useCodexStyle:true});return process.env.CLI_DEBUG==="1"&&(g.debug("OpenAI","Using official Codex instructions for Responses API"),g.debug("OpenAI",`Instructions length: ${t.length} chars`),g.debug("OpenAI",`Instructions preview: ${t.substring(0,200)}...`)),t}convertToResponsesInput(e){let s=this.filterIncompleteToolCalls(e).filter(o=>o.role!=="system").flatMap(o=>this.convertMessageToResponsesItems(o)),n=this.extractMemoryContext(e);n&&s.unshift({type:"message",role:"user",status:"completed",content:[{type:"input_text",text:`<memory_context>
1570
+ `;return l+p+c}function Hc(r,e={}){let t={...r};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 qc(r,e){if(!r)return null;if(e?.reasoning)return {effort:e.reasoning.effort||"low",verbosity:e.reasoning.verbosity||"low",summary:e.reasoning.summary||"auto"};let t=process.env.CD_REASONING_EFFORT||process.env.NEOX_REASONING_EFFORT,s=process.env.CD_REASONING_VERBOSITY||process.env.NEOX_REASONING_VERBOSITY,n=process.env.CD_REASONING_SUMMARY||process.env.NEOX_REASONING_SUMMARY;return t||s||n?{effort:t||"low",verbosity:s||"low",summary:n||"auto"}:null}var Ct=class{client;defaultModel;isProxy;useResponsesAPI;apiEndpoint;streamFormat;retryConfig;baseUrl;privacySettings;sessionId;doubaoThinking;apiKey;modelConfig;structuredOutputMode;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.apiKey=e.apiKey,this.sessionId=e.sessionId||`session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,this.privacySettings=e.privacySettings||{},this.doubaoThinking=e.doubaoThinking,this.modelConfig=e.modelConfig,this.structuredOutputMode=e.structuredOutputMode||"json_schema",this.client=Dg.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=Rs("openai",this.baseUrl);this.retryConfig=Lt(void 0,{...t,...e.retry}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Initialized with:",{baseUrl:this.baseUrl,isProxy:this.isProxy,useResponsesAPI:this.useResponsesAPI,apiEndpoint:this.apiEndpoint,streamFormat:this.streamFormat});}async chat(e,t={}){let{model:s=this.defaultModel}=t;return this.shouldUseResponsesAPI(s)?this.chatWithResponsesAPI(e,t):this.chatWithChatCompletions(e,t)}async*chatStreamed(e,t={}){let{model:s=this.defaultModel}=t;this.shouldUseResponsesAPI(s)?yield*this.chatStreamedWithResponsesAPI(e,t):yield*this.chatStreamedWithChatCompletions(e,t);}async chatWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:o=.7,maxInputTokens:i}=t,a=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:o,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:false}),l=`${this.client.defaults.baseURL}/chat/completions`;te.llmRequest("openai",s,a,l,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Request",{url:l,payload:a});let c=this.retryConfig.requestMaxRetries,u=null;for(let p=0;p<=c;p++)try{let d=Date.now(),m=await this.client.post("/chat/completions",a),h=Date.now()-d;return te.llmResponse("openai",h,m.data.usage,m.data.choices[0]),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Response",{duration:`${h}ms`,data:m.data}),m.data}catch(d){u=d;let m=tt(d);if(g.error("OpenAI",`Request Error - URL: ${l}`),g.error("OpenAI",`Error: ${d.message}`),d.response?.data)try{let b=d.response.data;if(typeof b=="string")g.error("OpenAI",`Response: ${b.substring(0,500)}`);else if(b&&typeof b=="object"){let _={error:b.error,message:b.message,type:b.type,code:b.code};g.error("OpenAI",`Response: ${JSON.stringify(_).substring(0,500)}`);}}catch{g.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Error",{url:l,message:d.message,category:m.category,retryable:m.retryable,attempt:`${p+1}/${c+1}`}),te.llmError("openai",d),!m.retryable||p===c)throw m;let h=d.response?.headers?.["retry-after"],f=St(h),y=Dt(f,p+1,this.retryConfig);g.info("OpenAI",`Request failed (${m.code}), retrying in ${qe(y)} (${p+1}/${c})...`),await Ms(y);}throw u||new Error("Unknown error during retry")}async*chatStreamedWithChatCompletions(e,t){let{model:s=this.defaultModel,tools:n,temperature:o=.7,maxInputTokens:i,signal:a}=t,l=this.buildChatCompletionsPayload(e,{model:s,tools:n,temperature:o,structuredOutput:t.structuredOutput,maxInputTokens:i,stream:true}),c=`${this.client.defaults.baseURL}${this.apiEndpoint}`;te.llmRequest("openai-stream",s,l,c,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Chat Completions Stream Request",{url:c,endpoint:this.apiEndpoint,payload:l});let u=this.retryConfig.streamMaxRetries,p=0;for(;;)try{if(a?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let d=Date.now(),m=await this.client.post(this.apiEndpoint,l,{responseType:"stream",signal:a});if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Started",{status:m.status}),m.status!==200){let f="";for await(let y of m.data)f+=y.toString();throw new Error(`OpenAI API error: ${m.status} - ${f}`)}this.streamFormat==="anthropic"?yield*this.parseAnthropicStreamResponse(m.data):yield*this.parseOpenAIStreamResponse(m.data,a);let h=Date.now()-d;te.llmResponse("openai-stream",h,{},{}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Complete",{duration:`${h}ms`});return}catch(d){let m=tt(d);if(g.error("OpenAI",`Stream Error - Request URL: ${c}`),g.error("OpenAI",`Error: ${d.message}`),d.response?.data)try{let h=d.response.data;if(typeof h=="string")g.error("OpenAI",`Response: ${h.substring(0,500)}`);else if(h&&typeof h=="object"){let f={error:h.error,message:h.message,type:h.type,code:h.code};g.error("OpenAI",`Response: ${JSON.stringify(f).substring(0,500)}`);}}catch{g.error("OpenAI","Response: [Could not serialize error data]");}if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Error Details",{url:c,message:d.message,retryable:m.retryable,status:d.response?.status}),te.llmError("openai-stream",d),m.retryable&&p<u){p++;let h=d.response?.headers?.["retry-after"],f=St(h),y=Dt(f,p,this.retryConfig);g.info("OpenAI",`Stream failed (${m.code}), reconnecting in ${qe(y)} (${p}/${u})...`),yield {choices:[],type:"stream_retry",error:m.message,errorCode:m.code,attempt:p,maxRetries:u,delayMs:y};try{await Xt(y,a);}catch(b){throw b?.name==="AbortError",b}continue}throw m}}buildChatCompletionsPayload(e,t){let{model:s,tools:n,temperature:o,structuredOutput:i,maxInputTokens:a,stream:l}=t,c=this.formatMessagesForChatCompletions(e);if(this.baseUrl.includes("ark.cn-beijing.volces.com")){let m={model:s,messages:c,stream:l};return this.doubaoThinking&&s.includes("doubao-seed")&&(m.thinking={type:this.doubaoThinking.type},process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Doubao thinking mode: ${this.doubaoThinking.type}`)),n&&n.length>0&&(m.tools=n.map(h=>({type:"function",function:{name:h.name,description:h.description,parameters:h.parameters}})),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${m.tools.length} tools to Doubao payload`)),m}let p={model:s,messages:c,temperature:o,stream:l};l&&(p.stream_options={include_usage:true}),a!==void 0&&(p.max_tokens=a);let d=qc(false);return d&&(p.reasoning_effort=d.effort,d.verbosity&&(p.verbosity=d.verbosity)),n&&n.length>0&&(p.tools=n.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${p.tools.length} tools to Chat Completions payload`)),i&&(this.structuredOutputMode==="json_object"?p.response_format={type:"json_object"}:p.response_format={type:"json_schema",json_schema:{name:i.name,schema:i.schema,strict:i.strict??true}}),Hc(p,this.privacySettings)}formatMessagesForChatCompletions(e){return e.filter(t=>{let s=t.content&&(typeof t.content=="string"?t.content.trim().length>0:Array.isArray(t.content)&&t.content.length>0),n=t.tool_calls&&t.tool_calls.length>0;return s||n}).map(t=>{let s={role:t.role,content:null};if(t.role==="tool"){let n=typeof t.content=="string"?t.content:ee(t.content);s.content=Wc(n);}else Array.isArray(t.content)?s.content=t.content:t.tool_calls&&t.tool_calls.length>0?s.content=t.content||"":s.content=t.content||null;return t.name&&(s.name=t.name),t.tool_call_id&&(s.tool_call_id=t.tool_call_id),t.tool_calls&&(s.tool_calls=t.tool_calls.map(n=>({id:n.id,type:"function",function:{name:n.function.name,arguments:n.function.arguments}}))),s})}async chatWithResponsesAPI(e,t){let s="",n=[],o;for await(let i of this.chatStreamedWithResponsesAPI(e,t)){let a=i.choices?.[0]?.delta;if(a&&(a.content&&(s+=a.content),a.tool_calls))for(let l of a.tool_calls){let c=n.find(u=>u.index===l.index);c?l.function?.arguments&&(c.function.arguments+=l.function.arguments):n.push({id:l.id||`call_${n.length}`,type:"function",function:{name:l.function?.name||"",arguments:l.function?.arguments||""},index:l.index});}i.usage&&(o=i.usage);}return {id:`chatcmpl-${Date.now()}`,choices:[{message:{role:"assistant",content:s||null,...n.length>0?{tool_calls:n}:{}},finish_reason:"stop"}],usage:o||{total_tokens:0,prompt_tokens:0,completion_tokens:0}}}async*chatStreamedWithResponsesAPI(e,t){let{model:s=this.defaultModel,tools:n,temperature:o=.7,structuredOutput:i,maxInputTokens:a,signal:l}=t,c=this.buildResponsesAPIPayload(e,{model:s,tools:n,temperature:o,structuredOutput:i,maxInputTokens:a}),u=`${this.client.defaults.baseURL}/responses`;if(te.llmRequest("openai-responses-stream",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG==="1"){g.info("OpenAI","Responses API Stream Request",{url:u,toolsCount:c.tools?.length||0}),process.env.CLI_DEBUG_PAYLOAD==="1"&&g.debug("OpenAI","Full Payload",c);let p=['-H "Content-Type: application/json"','-H "Accept: text/event-stream"',`-H "Authorization: Bearer ${this.apiKey}"`,`-H "conversation_id: ${this.sessionId}"`,`-H "session_id: ${this.sessionId}"`,'-H "user-agent: neox-cli/1.0.0"'],d=[`curl -X POST "${u}"`,...p,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(` \\
1571
+ `),m=[`curl -X POST "${u}"`,...p,`-d '${JSON.stringify(c)}'`,"--no-buffer"].join(" ");g.info("CURL","\u2550".repeat(80)),g.info("CURL","Multi-line CURL command:"),g.info("CURL",d),g.info("CURL","\u2550".repeat(80)),g.info("CURL","One-line CURL (copy-paste ready):"),g.info("CURL",m),g.info("CURL","\u2550".repeat(80));}try{if(l?.aborted){let f=new Error("Request aborted");throw f.name="AbortError",f}let p=Date.now(),d={Accept:"text/event-stream",conversation_id:this.sessionId,session_id:this.sessionId,originator:"codex_cli_rs","x-codex-beta-features":"shell_snapshot"},m=await this.client.post("/responses",c,{responseType:"stream",signal:l,headers:d});if(process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Responses API Stream Started",{status:m.status}),m.status!==200){let f="";for await(let b of m.data)f+=b.toString();let y=Vt(f,m.status);throw new Error(`OpenAI Responses API error: ${m.status} - ${y.message}`)}yield*this.parseResponsesAPIStream(m.data,l);let h=Date.now()-p;te.llmResponse("openai-responses-stream",h,{},{}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Responses API Stream Complete",{duration:`${h}ms`});}catch(p){let d,m=p.response?.status;if(p.response?.data){let f=p.response.data;try{if(f&&typeof f.on=="function"){let y="";try{for await(let b of f)y+=b.toString();d=y;}catch{d="[Could not read error stream]";}}else if(typeof f=="string")d=f;else if(f&&typeof f=="object"){let y={error:f.error,message:f.message,type:f.type,code:f.code};d=JSON.stringify(y);}}catch{d="[Could not parse error data]";}}process.env.CLI_DEBUG==="1"&&g.error("OpenAI","Responses API Stream Error",{status:m,errorData:d,message:p.message}),te.llmError("openai-responses-stream",p);let h;if(m&&d){let f=Vt(d,m);h=`${f.message}${f.detail?`
1572
+ `+f.detail:""}`;}else h=p.message||"Unknown error";throw new Error(h)}}buildResponsesAPIPayload(e,t){let{model:s,tools:n,temperature:o,structuredOutput:i,maxInputTokens:a}=t,l=this.convertToResponsesInput(e),c=this.buildResponsesInstructions(e);if(!c)throw new Error("[OpenAI Responses API] instructions field is required but no system message found");if(!l||l.length===0)throw new Error("[OpenAI Responses API] input array is empty - at least one user message is required");if(process.env.CLI_DEBUG==="1"){g.debug("OpenAI","Building Responses API payload",{instructionsLength:c.length,instructionsPreview:c.substring(0,300),inputItems:l.length,inputPreview:JSON.stringify(l.slice(0,2),null,2)}),g.debug("OpenAI","Full input array for Response API:",{totalMessages:e.length,messageRoles:e.map(y=>y.role),inputCount:l.length,fullInput:JSON.stringify(l,null,2)});let d=l.filter(y=>y.type==="function_call"),m=l.filter(y=>y.type==="function_call_output");g.debug("OpenAI","Function call ID matching check:",{callCount:d.length,outputCount:m.length,callIds:d.map(y=>({id:y.id||y.call_id,name:y.name})),outputIds:m.map(y=>({call_id:y.call_id}))});let h=new Set(d.map(y=>y.call_id||y.id)),f=m.filter(y=>!h.has(y.call_id));f.length>0&&g.warn("OpenAI",`\u26A0\uFE0F Found ${f.length} unmatched function_call_output!`,{unmatchedCallIds:f.map(y=>y.call_id)});}let u={model:s,instructions:c,input:l};n&&n.length>0&&(u.tools=n.map(d=>this.formatResponsesFunctionTool(d)),u.tool_choice="auto",u.parallel_tool_calls=true,process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Added ${u.tools.length} tools`));let p=qc(true,this.modelConfig);return p&&(u.reasoning={effort:p.effort,summary:p.summary||"auto"}),u.store=false,u.stream=true,p&&(u.include=["reasoning.encrypted_content"]),u.prompt_cache_key=this.sessionId,Hc(u,this.privacySettings)}buildResponsesInstructions(e){let t=Fi({workDir:process.cwd(),language:"zh",useCodexStyle:true});return process.env.CLI_DEBUG==="1"&&(g.debug("OpenAI","Using official Codex instructions for Responses API"),g.debug("OpenAI",`Instructions length: ${t.length} chars`),g.debug("OpenAI",`Instructions preview: ${t.substring(0,200)}...`)),t}convertToResponsesInput(e){let s=this.filterIncompleteToolCalls(e).filter(i=>i.role!=="system").flatMap(i=>this.convertMessageToResponsesItems(i)),n=this.extractMemoryContext(e);n&&s.unshift({type:"message",role:"user",status:"completed",content:[{type:"input_text",text:`<memory_context>
1573
1573
  ${n}
1574
- </memory_context>`}]});let i=this.getGPTAgentInstructions();if(i&&s.unshift({type:"message",role:"user",status:"completed",content:[{type:"input_text",text:i}]}),process.env.CLI_DEBUG==="1"){let o=s.filter(l=>l.type==="function_call"),a=s.filter(l=>l.type==="function_call_output");if(g.debug("OpenAI","Responses API input structure:",{totalItems:s.length,functionCalls:o.length,functionCallOutputs:a.length}),o.length>0||a.length>0){g.debug("OpenAI","Function calls in input:",o.map(p=>({call_id:p.call_id,name:p.name}))),g.debug("OpenAI","Function call outputs in input:",a.map(p=>({call_id:p.call_id})));let l=new Set(o.map(p=>p.call_id)),c=new Set(a.map(p=>p.call_id)),u=[...l].filter(p=>!c.has(p));u.length>0&&g.warn("OpenAI","\u26A0\uFE0F Found function_calls without outputs:",u);}}return s}extractMemoryContext(e){let t=e.filter(n=>n.role==="system"),s=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"];for(let n of t){let i=typeof n.content=="string"?n.content:ee(n.content);if(i&&s.some(o=>i.includes(o)))return i.trim()}return null}filterIncompleteToolCalls(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s];if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0&&!this.hasToolOutputsInHistory(n,e,s)){process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Filtering incomplete assistant message:",{toolCalls:n.tool_calls.map(o=>({id:o.id,name:o.function.name})),reason:"Missing tool outputs in message history"});continue}t.push(n);}return t}hasToolOutputsInHistory(e,t,s){if(!e.tool_calls)return true;let n=new Set(e.tool_calls.map(o=>o.id)),i=new Set;for(let o=s+1;o<t.length;o++){let a=t[o];if(a.role==="tool"&&a.tool_call_id&&i.add(a.tool_call_id),a.role==="assistant")break}for(let o of n)if(!i.has(o))return false;return true}convertMessageToResponsesItems(e){if(e.role==="assistant"){let s=[],n=ee(e.content);if(n.trim().length>0&&s.push({type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:n,annotations:[]}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let i of e.tool_calls){let o=i.id;process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Function call ID (no normalization):",{originalId:o,toolName:i.function.name,argsLength:i.function.arguments?.length||0}),s.push({type:"function_call",call_id:o,name:i.function.name,arguments:i.function.arguments||"",status:"completed"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Sending function_call to API:",{call_id:o,name:i.function.name});}return s}if(e.role==="tool"){let s=e.tool_call_id||e.name,n=ee(e.content),i=jc(n);return process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Sending function_call_output (no normalization):",{callId:s,toolName:e.name,outputLength:i.length,wasTruncated:n.length!==i.length}),[{type:"function_call_output",call_id:s,output:i}]}if(Array.isArray(e.content)){let s=[];for(let n of e.content)n.type==="text"&&n.text.trim()?s.push({type:"input_text",text:n.text}):n.type==="image_url"&&s.push({type:"input_image",image_url:n.image_url.url});return s.length===0?[]:[{type:"message",role:"user",content:s}]}let t=ee(e.content);return !t||t.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:t}]}]}getGPTAgentInstructions(){try{let e=fileURLToPath(import.meta.url),t=dirname(e),s=join(t,"../prompts/gpt-agents-instructions.md"),n=readFileSync(s,"utf-8"),i=`# AGENTS.md instructions for GPT models
1574
+ </memory_context>`}]});let o=this.getGPTAgentInstructions();if(o&&s.unshift({type:"message",role:"user",status:"completed",content:[{type:"input_text",text:o}]}),process.env.CLI_DEBUG==="1"){let i=s.filter(l=>l.type==="function_call"),a=s.filter(l=>l.type==="function_call_output");if(g.debug("OpenAI","Responses API input structure:",{totalItems:s.length,functionCalls:i.length,functionCallOutputs:a.length}),i.length>0||a.length>0){g.debug("OpenAI","Function calls in input:",i.map(p=>({call_id:p.call_id,name:p.name}))),g.debug("OpenAI","Function call outputs in input:",a.map(p=>({call_id:p.call_id})));let l=new Set(i.map(p=>p.call_id)),c=new Set(a.map(p=>p.call_id)),u=[...l].filter(p=>!c.has(p));u.length>0&&g.warn("OpenAI","\u26A0\uFE0F Found function_calls without outputs:",u);}}return s}extractMemoryContext(e){let t=e.filter(n=>n.role==="system"),s=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"];for(let n of t){let o=typeof n.content=="string"?n.content:ee(n.content);if(o&&s.some(i=>o.includes(i)))return o.trim()}return null}filterIncompleteToolCalls(e){let t=[];for(let s=0;s<e.length;s++){let n=e[s];if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0&&!this.hasToolOutputsInHistory(n,e,s)){process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Filtering incomplete assistant message:",{toolCalls:n.tool_calls.map(i=>({id:i.id,name:i.function.name})),reason:"Missing tool outputs in message history"});continue}t.push(n);}return t}hasToolOutputsInHistory(e,t,s){if(!e.tool_calls)return true;let n=new Set(e.tool_calls.map(i=>i.id)),o=new Set;for(let i=s+1;i<t.length;i++){let a=t[i];if(a.role==="tool"&&a.tool_call_id&&o.add(a.tool_call_id),a.role==="assistant")break}for(let i of n)if(!o.has(i))return false;return true}convertMessageToResponsesItems(e){if(e.role==="assistant"){let s=[],n=ee(e.content);if(n.trim().length>0&&s.push({type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:n,annotations:[]}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let o of e.tool_calls){let i=o.id;process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Function call ID (no normalization):",{originalId:i,toolName:o.function.name,argsLength:o.function.arguments?.length||0}),s.push({type:"function_call",call_id:i,name:o.function.name,arguments:o.function.arguments||"",status:"completed"}),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Sending function_call to API:",{call_id:i,name:o.function.name});}return s}if(e.role==="tool"){let s=e.tool_call_id||e.name,n=ee(e.content),o=Wc(n);return process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Sending function_call_output (no normalization):",{callId:s,toolName:e.name,outputLength:o.length,wasTruncated:n.length!==o.length}),[{type:"function_call_output",call_id:s,output:o}]}if(Array.isArray(e.content)){let s=[];for(let n of e.content)n.type==="text"&&n.text.trim()?s.push({type:"input_text",text:n.text}):n.type==="image_url"&&s.push({type:"input_image",image_url:n.image_url.url});return s.length===0?[]:[{type:"message",role:"user",content:s}]}let t=ee(e.content);return !t||t.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:t}]}]}getGPTAgentInstructions(){try{let e=fileURLToPath(import.meta.url),t=dirname(e),s=join(t,"../prompts/gpt-agents-instructions.md"),n=readFileSync(s,"utf-8"),o=`# AGENTS.md instructions for GPT models
1575
1575
 
1576
1576
  <INSTRUCTIONS>
1577
1577
  ${n}
1578
- </INSTRUCTIONS>`;return process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Loaded GPT Agent instructions:",{path:s,length:n.length,preview:n.substring(0,200)}),i}catch(e){return process.env.CLI_DEBUG==="1"&&g.warn("OpenAI","Failed to load GPT Agent instructions:",e),null}}formatResponsesFunctionTool(e){return {type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:false}}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(s=>this.makeSchemaNullable(s))),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(s=>this.makeSchemaNullable(s))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(s=>this.makeSchemaNullable(s))),t}async*parseOpenAIStreamResponse(e,t){let s="",n=0,i=()=>new Promise(o=>setImmediate(o));for await(let o of e){if(t?.aborted)throw process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream aborted by signal"),new Error("Request aborted");n++%20===0&&await i(),s+=o.toString();let a=s.split(`
1579
- `);s=a.pop()||"";for(let l of a){let c=l.trim();if(!c||!c.startsWith("data: "))continue;let u=c.slice(6);if(u==="[DONE]"){process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Received [DONE]");return}try{let p=JSON.parse(u);process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Chunk",p),yield p;}catch{process.env.CLI_DEBUG==="1"&&g.warn("OpenAI","Stream Invalid JSON",{data:u});}}}}async*parseResponsesAPIStream(e,t){let s=new Map,n=0,i=null,o=null,a=false,l=false,c=2e5,u=1e5,p=h=>{let f={...h};return l||(f.role="assistant",l=true),{choices:[{index:0,delta:f}]}};for await(let h of this.parseOpenAIStreamResponse(e,t))if(!(!h||typeof h!="object"))switch(h.type){case "response.output_text.delta":{let f=typeof h.delta=="string"?h.delta:"";if(!f)break;a=true,yield p({content:f});break}case "response.output_item.added":{if(h.item?.type==="function_call"){let f=h.item.id||`item_${h.output_index}`,y={id:h.item.call_id||h.item.id||`call_${Date.now()}_${n}`,name:h.item.name,index:n++,arguments:"",completed:false};s.set(f,y),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Function call added from stream:",{key:f,id:y.id,call_id:h.item.call_id,item_id:h.item.id,name:y.name,index:y.index}),a=true,yield p({tool_calls:[{index:y.index,id:y.id,type:"function",function:{name:y.name}}]});}break}case "response.function_call_arguments.delta":{let f=h.item_id?s.get(h.item_id):void 0;if(!f)break;let y=Buffer.byteLength(f.arguments,"utf8");if(y>=c){process.env.CLI_DEBUG==="1"&&g.warn("OpenAI",`Tool ${f.name} arguments exceeded maximum size (${y} bytes), truncating`);break}let b=typeof h.delta=="string"?h.delta:"";if(!b)break;y>5e4&&await new Promise(v=>setImmediate(v)),f.arguments+=b,a=true;let _=Buffer.byteLength(f.arguments,"utf8");_>u&&y<=u&&g.warn("OpenAI",`Tool ${f.name} arguments size exceeds ${u} bytes (${_} bytes)`),yield p({tool_calls:[{index:f.index,id:f.id,type:"function",function:{name:f.name,arguments:b}}]});break}case "response.output_item.done":{if(h.item?.type==="function_call"){let f=h.item.id||`item_${h.output_index}`,y=s.get(f);if(y&&(y.completed=true,process.env.CLI_DEBUG==="1")){let b=Buffer.byteLength(y.arguments,"utf8");g.debug("OpenAI",`Tool ${y.name} arguments complete (${b} bytes)`);}}break}case "response.completed":{i=h.response,o=h.response?.usage;break}case "response.error":case "response.failed":{let f=h.error?.message||h.error?.code||h.message||"Responses stream failed";throw new Error(f)}}let d=[];for(let[h,f]of s.entries())f.completed||d.push(`${f.name} (${Buffer.byteLength(f.arguments,"utf8")} bytes)`);if(d.length>0&&(g.error("OpenAI",`\u26A0\uFE0F Responses API stream ended with ${d.length} incomplete tool calls: ${d.join(", ")}`),g.error("OpenAI","This indicates a streaming issue with the API/proxy server. The tool calls received incomplete arguments and may fail execution.")),!a&&i){let h=Array.isArray(i.output)?i.output:[],f="";for(let y of h)if(y?.type==="message"&&Array.isArray(y.content))for(let b of y.content)b?.type==="output_text"&&typeof b.text=="string"&&(f+=b.text);f&&(yield {choices:[{index:0,delta:{role:"assistant",content:f}}]});}let m={choices:[{index:0,delta:{},finish_reason:"stop"}]};o&&(m.usage=this.normalizeUsage(o)),yield m;}async*parseAnthropicStreamResponse(e){let t="",s=[],n=0,i=false,o=null;for await(let l of e){t+=l.toString();let c=t.split(`
1580
- `);t=c.pop()||"";for(let u of c){let p=u.trim();if(!p||!p.startsWith("data: "))continue;let d=p.slice(6);if(d!=="[DONE]")try{let m=JSON.parse(d);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;s.push({index:n,id:h.id,type:"function",function:{name:h.name,arguments:""}}),yield {choices:[{delta:{tool_calls:[{index:n,id:h.id,type:"function",function:{name:h.name}}]},index:0}]},n++;}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(s.length>0){let f=s[s.length-1];f.function.arguments+=h,yield {choices:[{delta:{tool_calls:[{index:f.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:s.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"&&g.debug("OpenAI",`Session ID updated to: ${e}`);}getSessionId(){return this.sessionId}setDoubaoThinking(e){this.doubaoThinking=e,process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Doubao thinking updated to: ${e?.type||"undefined"}`);}getDoubaoThinking(){return this.doubaoThinking}};le();var qr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Zt,this.promptBuilder=new es,this.defaultModel=e.defaultModel||"gpt-4o";let{apiKey:t,baseUrl:s,defaultModel:n,useResponsesAPI:i,maxTokens:o,maxInputTokens:a,...l}=e;this.provider=new Ct({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,useResponsesAPI:i,maxTokens:o,maxInputTokens:a,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=this.constraints.isResponsesAPIModel(s),i=super.prepareRequest(e,{...t,model:s});return n&&i.options.temperature===void 0&&delete i.options.temperature,i}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("OpenAIAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("OpenAIAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsReasoning:this.constraints.supportsReasoning(t),isResponsesAPI:this.constraints.isResponsesAPIModel(t),tokenLimits:this.constraints.getTokenLimits(t)}}};var An=class extends Ft{getConstraints(){return {maxOutputTokens:{"claude-3-5-sonnet-20241022":8192,"claude-3-5-sonnet-20240620":8192,"claude-3-5-haiku-20241022":8192,"claude-3-opus-20240229":4096,"claude-3-sonnet-20240229":4096,"claude-3-haiku-20240307":4096,"claude-2.1":4096,"claude-2.0":4096,"claude-instant-1.2":4096,"claude-3-5*":8192,"claude-3*":4096,"claude-2*":4096},maxInputTokens:{"claude-3-5-sonnet-20241022":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-5-haiku-20241022":2e5,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-haiku-20240307":2e5,"claude-2.1":2e5,"claude-2.0":1e5,"claude-instant-1.2":1e5,"claude-3*":2e5,"claude-2*":2e5},supportedParams:new Set(["model","messages","system","stream","max_tokens","temperature","top_p","top_k","stop_sequences","tools","tool_choice","thinking","metadata"]),paramAliases:{max_completion_tokens:"max_tokens",stop:"stop_sequences"},validators:{temperature:Fe(0,1),top_p:Fe(0,1),top_k:Hr(e=>Number.isInteger(e)||"Must be an integer",Fe(1,500)),max_tokens:e=>{let t=Number(e);return isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},"thinking.type":Ps(["enabled","disabled"]),"thinking.budget_tokens":e=>{let t=Number(e);return isNaN(t)?"Must be a number":t<1024?"Budget tokens must be at least 1024":t>1e4?"Budget tokens cannot exceed 10000":true},tool_choice:e=>typeof e=="string"?["auto","any","tool"].includes(e)||"Must be 'auto', 'any', or 'tool'":typeof e=="object"&&e.type==="tool"?e.name?true:'tool_choice.name is required when type is "tool"':"Invalid tool_choice format",stop_sequences:e=>Array.isArray(e)?e.length>4?"Maximum 4 stop sequences allowed":e.every(t=>typeof t=="string")?true:"All stop sequences must be strings":"Must be an array",stream:e=>typeof e=="boolean"||"Must be a boolean","metadata.user_id":e=>typeof e!="string"?"Must be a string":e.length>64?"Maximum 64 characters":e.includes("@")||/\d{10,}/.test(e)?"user_id should not contain PII (email, phone number, etc.)":true},defaults:{temperature:1,top_p:1,stream:false}}}supportsThinking(e){return e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus")}supportsVision(e){return e.includes("claude-3")}supportsTools(e){return e.includes("claude-3")}supportsPromptCaching(e){return e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}validateSystemPrompt(e){if(typeof e=="string")return e.length===0?{valid:false,error:"System prompt cannot be empty"}:e.length>1e5?{valid:false,error:"System prompt too long (max 100K chars)"}:{valid:true};if(Array.isArray(e)){for(let t of e){if(t.type!=="text")return {valid:false,error:'System prompt blocks must be of type "text"'};if(!t.text||t.text.trim().length===0)return {valid:false,error:"System prompt text blocks cannot be empty"}}return {valid:true}}return {valid:false,error:"System prompt must be a string or array of text blocks"}}getCachingRecommendation(e,t){return this.supportsPromptCaching(e)?t<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:t<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}:{shouldUseCache:false,cacheTTL:"5m",reason:"Model does not support prompt caching"}}};var Pn=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",customInstructions:n}=e,i=Gr({workDir:t,language:s});return n&&n.trim()&&(i+=`
1578
+ </INSTRUCTIONS>`;return process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Loaded GPT Agent instructions:",{path:s,length:n.length,preview:n.substring(0,200)}),o}catch(e){return process.env.CLI_DEBUG==="1"&&g.warn("OpenAI","Failed to load GPT Agent instructions:",e),null}}formatResponsesFunctionTool(e){return {type:"function",name:e.name,description:e.description,parameters:e.parameters,strict:false}}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(s=>this.makeSchemaNullable(s))),Array.isArray(t.oneOf)&&(t.oneOf=t.oneOf.map(s=>this.makeSchemaNullable(s))),Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(s=>this.makeSchemaNullable(s))),t}async*parseOpenAIStreamResponse(e,t){let s="",n=0,o=()=>new Promise(i=>setImmediate(i));for await(let i of e){if(t?.aborted)throw process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream aborted by signal"),new Error("Request aborted");n++%20===0&&await o(),s+=i.toString();let a=s.split(`
1579
+ `);s=a.pop()||"";for(let l of a){let c=l.trim();if(!c||!c.startsWith("data: "))continue;let u=c.slice(6);if(u==="[DONE]"){process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Received [DONE]");return}try{let p=JSON.parse(u);process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Stream Chunk",p),yield p;}catch{process.env.CLI_DEBUG==="1"&&g.warn("OpenAI","Stream Invalid JSON",{data:u});}}}}async*parseResponsesAPIStream(e,t){let s=new Map,n=0,o=null,i=null,a=false,l=false,c=2e5,u=1e5,p=h=>{let f={...h};return l||(f.role="assistant",l=true),{choices:[{index:0,delta:f}]}};for await(let h of this.parseOpenAIStreamResponse(e,t))if(!(!h||typeof h!="object"))switch(h.type){case "response.output_text.delta":{let f=typeof h.delta=="string"?h.delta:"";if(!f)break;a=true,yield p({content:f});break}case "response.output_item.added":{if(h.item?.type==="function_call"){let f=h.item.id||`item_${h.output_index}`,y={id:h.item.call_id||h.item.id||`call_${Date.now()}_${n}`,name:h.item.name,index:n++,arguments:"",completed:false};s.set(f,y),process.env.CLI_DEBUG==="1"&&g.debug("OpenAI","Function call added from stream:",{key:f,id:y.id,call_id:h.item.call_id,item_id:h.item.id,name:y.name,index:y.index}),a=true,yield p({tool_calls:[{index:y.index,id:y.id,type:"function",function:{name:y.name}}]});}break}case "response.function_call_arguments.delta":{let f=h.item_id?s.get(h.item_id):void 0;if(!f)break;let y=Buffer.byteLength(f.arguments,"utf8");if(y>=c){process.env.CLI_DEBUG==="1"&&g.warn("OpenAI",`Tool ${f.name} arguments exceeded maximum size (${y} bytes), truncating`);break}let b=typeof h.delta=="string"?h.delta:"";if(!b)break;y>5e4&&await new Promise(v=>setImmediate(v)),f.arguments+=b,a=true;let _=Buffer.byteLength(f.arguments,"utf8");_>u&&y<=u&&g.warn("OpenAI",`Tool ${f.name} arguments size exceeds ${u} bytes (${_} bytes)`),yield p({tool_calls:[{index:f.index,id:f.id,type:"function",function:{name:f.name,arguments:b}}]});break}case "response.output_item.done":{if(h.item?.type==="function_call"){let f=h.item.id||`item_${h.output_index}`,y=s.get(f);if(y&&(y.completed=true,process.env.CLI_DEBUG==="1")){let b=Buffer.byteLength(y.arguments,"utf8");g.debug("OpenAI",`Tool ${y.name} arguments complete (${b} bytes)`);}}break}case "response.completed":{o=h.response,i=h.response?.usage;break}case "response.error":case "response.failed":{let f=h.error?.message||h.error?.code||h.message||"Responses stream failed";throw new Error(f)}}let d=[];for(let[h,f]of s.entries())f.completed||d.push(`${f.name} (${Buffer.byteLength(f.arguments,"utf8")} bytes)`);if(d.length>0&&(g.error("OpenAI",`\u26A0\uFE0F Responses API stream ended with ${d.length} incomplete tool calls: ${d.join(", ")}`),g.error("OpenAI","This indicates a streaming issue with the API/proxy server. The tool calls received incomplete arguments and may fail execution.")),!a&&o){let h=Array.isArray(o.output)?o.output:[],f="";for(let y of h)if(y?.type==="message"&&Array.isArray(y.content))for(let b of y.content)b?.type==="output_text"&&typeof b.text=="string"&&(f+=b.text);f&&(yield {choices:[{index:0,delta:{role:"assistant",content:f}}]});}let m={choices:[{index:0,delta:{},finish_reason:"stop"}]};i&&(m.usage=this.normalizeUsage(i)),yield m;}async*parseAnthropicStreamResponse(e){let t="",s=[],n=0,o=false,i=null;for await(let l of e){t+=l.toString();let c=t.split(`
1580
+ `);t=c.pop()||"";for(let u of c){let p=u.trim();if(!p||!p.startsWith("data: "))continue;let d=p.slice(6);if(d!=="[DONE]")try{let m=JSON.parse(d);switch(m.type){case "message_start":m.message?.usage&&(i=m.message.usage);break;case "content_block_start":if(m.content_block?.type==="text")o||(o=!0,yield {choices:[{delta:{role:"assistant"},index:0}]});else if(m.content_block?.type==="tool_use"){let h=m.content_block;s.push({index:n,id:h.id,type:"function",function:{name:h.name,arguments:""}}),yield {choices:[{delta:{tool_calls:[{index:n,id:h.id,type:"function",function:{name:h.name}}]},index:0}]},n++;}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(s.length>0){let f=s[s.length-1];f.function.arguments+=h,yield {choices:[{delta:{tool_calls:[{index:f.index,function:{arguments:h}}]},index:0}]};}}break;case "message_delta":m.usage&&(i=m.usage);break;case "error":throw new Error(m.error?.message||"Stream error")}}catch{}}}let a={choices:[{delta:{},finish_reason:s.length>0?"tool_calls":"stop",index:0}]};i&&(a.usage=this.normalizeUsage(i)),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"&&g.debug("OpenAI",`Session ID updated to: ${e}`);}getSessionId(){return this.sessionId}setDoubaoThinking(e){this.doubaoThinking=e,process.env.CLI_DEBUG==="1"&&g.debug("OpenAI",`Doubao thinking updated to: ${e?.type||"undefined"}`);}getDoubaoThinking(){return this.doubaoThinking}};le();var zr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Qt,this.promptBuilder=new ts,this.defaultModel=e.defaultModel||"gpt-4o";let{apiKey:t,baseUrl:s,defaultModel:n,useResponsesAPI:o,maxTokens:i,maxInputTokens:a,...l}=e;this.provider=new Ct({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,useResponsesAPI:o,maxTokens:i,maxInputTokens:a,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=this.constraints.isResponsesAPIModel(s),o=super.prepareRequest(e,{...t,model:s});return n&&o.options.temperature===void 0&&delete o.options.temperature,o}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("OpenAIAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("OpenAIAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsReasoning:this.constraints.supportsReasoning(t),isResponsesAPI:this.constraints.isResponsesAPIModel(t),tokenLimits:this.constraints.getTokenLimits(t)}}};var Pn=class extends Ft{getConstraints(){return {maxOutputTokens:{"claude-3-5-sonnet-20241022":8192,"claude-3-5-sonnet-20240620":8192,"claude-3-5-haiku-20241022":8192,"claude-3-opus-20240229":4096,"claude-3-sonnet-20240229":4096,"claude-3-haiku-20240307":4096,"claude-2.1":4096,"claude-2.0":4096,"claude-instant-1.2":4096,"claude-3-5*":8192,"claude-3*":4096,"claude-2*":4096},maxInputTokens:{"claude-3-5-sonnet-20241022":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-5-haiku-20241022":2e5,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-haiku-20240307":2e5,"claude-2.1":2e5,"claude-2.0":1e5,"claude-instant-1.2":1e5,"claude-3*":2e5,"claude-2*":2e5},supportedParams:new Set(["model","messages","system","stream","max_tokens","temperature","top_p","top_k","stop_sequences","tools","tool_choice","thinking","metadata"]),paramAliases:{max_completion_tokens:"max_tokens",stop:"stop_sequences"},validators:{temperature:Fe(0,1),top_p:Fe(0,1),top_k:qr(e=>Number.isInteger(e)||"Must be an integer",Fe(1,500)),max_tokens:e=>{let t=Number(e);return isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},"thinking.type":Os(["enabled","disabled"]),"thinking.budget_tokens":e=>{let t=Number(e);return isNaN(t)?"Must be a number":t<1024?"Budget tokens must be at least 1024":t>1e4?"Budget tokens cannot exceed 10000":true},tool_choice:e=>typeof e=="string"?["auto","any","tool"].includes(e)||"Must be 'auto', 'any', or 'tool'":typeof e=="object"&&e.type==="tool"?e.name?true:'tool_choice.name is required when type is "tool"':"Invalid tool_choice format",stop_sequences:e=>Array.isArray(e)?e.length>4?"Maximum 4 stop sequences allowed":e.every(t=>typeof t=="string")?true:"All stop sequences must be strings":"Must be an array",stream:e=>typeof e=="boolean"||"Must be a boolean","metadata.user_id":e=>typeof e!="string"?"Must be a string":e.length>64?"Maximum 64 characters":e.includes("@")||/\d{10,}/.test(e)?"user_id should not contain PII (email, phone number, etc.)":true},defaults:{temperature:1,top_p:1,stream:false}}}supportsThinking(e){return e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus")}supportsVision(e){return e.includes("claude-3")}supportsTools(e){return e.includes("claude-3")}supportsPromptCaching(e){return e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet")}getRecommendedMaxTokens(e,t){let s=this.getTokenLimits(e);switch(t){case "short":return Math.min(1024,s.maxOutput);case "medium":return Math.min(4096,s.maxOutput);case "long":return s.maxOutput;default:return Math.min(4096,s.maxOutput)}}validateSystemPrompt(e){if(typeof e=="string")return e.length===0?{valid:false,error:"System prompt cannot be empty"}:e.length>1e5?{valid:false,error:"System prompt too long (max 100K chars)"}:{valid:true};if(Array.isArray(e)){for(let t of e){if(t.type!=="text")return {valid:false,error:'System prompt blocks must be of type "text"'};if(!t.text||t.text.trim().length===0)return {valid:false,error:"System prompt text blocks cannot be empty"}}return {valid:true}}return {valid:false,error:"System prompt must be a string or array of text blocks"}}getCachingRecommendation(e,t){return this.supportsPromptCaching(e)?t<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:t<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}:{shouldUseCache:false,cacheTTL:"5m",reason:"Model does not support prompt caching"}}};var On=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",customInstructions:n}=e,o=Br({workDir:t,language:s});return n&&n.trim()&&(o+=`
1581
1581
 
1582
1582
  # Custom Instructions
1583
1583
 
1584
- `+n.trim()),Qt(i)}getCoreInstructions(e,t){return e==="zh"?"\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684 AI \u7F16\u7A0B\u52A9\u624B\uFF0C\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u8F6F\u4EF6\u5DE5\u7A0B\u4EFB\u52A1\u3002":"You are a professional AI coding assistant helping users with software engineering tasks."}getConstraintInstructions(e,t){let s=this.supportsExtendedThinking(t);return e==="zh"?`# Claude \u7279\u6027
1584
+ `+n.trim()),es(o)}getCoreInstructions(e,t){return e==="zh"?"\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684 AI \u7F16\u7A0B\u52A9\u624B\uFF0C\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u8F6F\u4EF6\u5DE5\u7A0B\u4EFB\u52A1\u3002":"You are a professional AI coding assistant helping users with software engineering tasks."}getConstraintInstructions(e,t){let s=this.supportsExtendedThinking(t);return e==="zh"?`# Claude \u7279\u6027
1585
1585
 
1586
1586
  - **Extended Thinking**: ${s?"\u652F\u6301\u6DF1\u5EA6\u601D\u8003\u6A21\u5F0F\uFF08thinking.type: enabled\uFF09":"\u4E0D\u652F\u6301"}
1587
1587
  - **Prompt Caching**: \u81EA\u52A8\u7F13\u5B58\u91CD\u590D\u7684\u4E0A\u4E0B\u6587\uFF0C\u8282\u7701\u6210\u672C
@@ -1631,21 +1631,21 @@ Claude uses standard tool calling format:
1631
1631
  }
1632
1632
  \`\`\`
1633
1633
 
1634
- Tool results are returned via tool_result messages.`}supportsExtendedThinking(e){return e?e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus"):false}supportsPromptCaching(e){return e?e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet"):false}getCachingRecommendation(e){return e<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:e<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}}};le();var Ug=15e3,Ln=2*1024*1024,jg=1.5*1024*1024;function Gg(r,e=Ug){if(!r||r.length<=e)return r;let t=r.split(`
1635
- `).length,s=r.length,n=Math.floor(e*.4),i=Math.floor(e*.4),o=n,a=r.length-i;for(;o>0&&(r.charCodeAt(o)&192)===128;)o--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,o),c=r.slice(a),p=`
1634
+ Tool results are returned via tool_result messages.`}supportsExtendedThinking(e){return e?e.includes("claude-3-5-sonnet")||e.includes("claude-3-opus"):false}supportsPromptCaching(e){return e?e.includes("claude-3-5")||e.includes("claude-3-opus")||e.includes("claude-3-sonnet"):false}getCachingRecommendation(e){return e<2e3?{shouldUseCache:false,cacheTTL:"5m",reason:"Prompt too short, caching overhead not worth it"}:e<1e4?{shouldUseCache:true,cacheTTL:"5m",reason:"Medium prompt, 5-minute cache recommended"}:{shouldUseCache:true,cacheTTL:"1h",reason:"Long prompt, 1-hour cache recommended for cost savings"}}};le();var Bg=15e3,Dn=2*1024*1024,Wg=1.5*1024*1024;function Hg(r,e=Bg){if(!r||r.length<=e)return r;let t=r.split(`
1635
+ `).length,s=r.length,n=Math.floor(e*.4),o=Math.floor(e*.4),i=n,a=r.length-o;for(;i>0&&(r.charCodeAt(i)&192)===128;)i--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,i),c=r.slice(a),p=`
1636
1636
 
1637
1637
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1638
1638
 
1639
- `;return l+p+c}function Wc(r,e=2e3){let t=r&&typeof r.toJSON=="function"?r.toJSON():r,s="";try{s=JSON.stringify(t??{},null,2);}catch{s=String(t??"");}return s?s.length>e?`${s.slice(0,e)}
1640
- ...[truncated ${s.length-e} chars]`:s:"No headers"}var Go="You are Claude Code, Anthropic's official CLI for Claude.",Bg=["claude-code-20250219","interleaved-thinking-2025-05-14"],Jr="2023-06-01",Kr=64,Wg=1024;var Hc=18e4,qc=6e4,zc={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"},Bo={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"},Os=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;let s=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=s?this.sanitizeUserId(s):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||Bg,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?Go:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Pg.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=Cs("anthropic",this.baseUrl);this.retryConfig=Lt(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});}setUserId(e){let t=e?.trim?.()||"";t&&(this.claudeCodeUserId=this.sanitizeUserId(t));}isCacheControlError(e){let t="";try{let s=e.response?.data;if(typeof s=="string")t=s.toLowerCase();else if(s&&typeof s=="object"){let n={error:s.error,message:s.message,type:s.type,code:s.code};t=JSON.stringify(n).toLowerCase();}else t=String(e.message||"").toLowerCase();}catch{t=String(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 s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.requestMaxRetries,i=null,o=s.disableCaching||false;for(let a=0;a<=n;a++){let l={...s,...o?{disableCaching:true}:{}},c=this.buildPayload(e,l);a===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",d=await this.client.post(p,c,{responseType:"stream",signal:t.signal});if(d.status!==200){let f="";for await(let v of d.data)f+=v.toString();let y=`${this.baseUrl}${p}`,b=yt(y,this.buildHeaders(),c,!1);g.error("CURL","=== [chat] API Error - Full Request CURL ==="),g.error("CURL",b),g.error("CURL",`=== Error Headers: ${Wc(d.headers)} ===`),g.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let _=new Error(`Anthropic API error: ${d.status}`);_.response={status:d.status,headers:d.headers,data:f};try{let v=JSON.parse(f);_.response.data=v,v.error?.message?_.message=`Anthropic API error: ${d.status} - ${v.error.message}`:v.message&&(_.message=`Anthropic API error: ${d.status} - ${v.message}`),this.debugLog("API Error Details",v);}catch{this.debugLog("API Error (non-JSON)",{status:d.status,dataLength:f.length});}throw _}let m=await this.collectStreamResponse(d.data),h=Date.now()-u;return te.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 p=tt(u);if(p.code==="PROXY_UPSTREAM_FAILED"){let y=JSON.stringify(c||{}).length,b=Array.isArray(e)?e.length:0,_=Array.isArray(e)?e.reduce((v,k)=>k?.content?typeof k.content=="string"?v+k.content.length:Array.isArray(k.content)?v+k.content.map(R=>typeof R.text=="string"?R.text.length:0).reduce((R,O)=>R+O,0):v:v,0):0;g.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${a+1}/${n+1}`,payloadSize:y,msgCount:b,promptChars:_,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:p.category,code:p.code,attempt:`${a+1}/${n+1}`}),te.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}),g.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!p.retryable||a===n)throw p;let d=Dr(u.response?.headers),m=kn(p.category,a+1,d||p.retryAfter),h=p.category==="retryable_rate_limit",f=h?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${qe(m)} \u540E\u91CD\u8BD5...`:`Retrying in ${qe(m)}...`;this.debugLog("Retrying",{delay:qe(m),attempt:a+1,isRateLimit:h,serverDelay:d?qe(d):"none",retryMsg:f});try{await Yt(m,s.signal);}catch(y){throw y?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),y}}}throw i||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",s="",n=[],i="",o=null,a="";for await(let c of e){let u=c.toString();t+=u;let p=t.split(`
1641
- `);t=p.pop()||"";for(let d of p){let m=d.trim();if(!m||!m.startsWith("data: "))continue;let h=m.slice(6);if(h!=="[DONE]")try{let f=JSON.parse(h);if(process.env.CLI_DEBUG==="1"){let y=JSON.stringify(f).substring(0,80);g.debug("SSE",`${f.type.padEnd(20)} ${y}${JSON.stringify(f).length>80?"...":""}`);}switch(f.type){case "message_start":a=f.message?.id||"",o=f.message?.usage;break;case "content_block_start":if(f.content_block?.type==="tool_use"){let y=f.content_block,b=this.isProxyMode?Bo[y.name]||this.fromClaudeCodeToolName(y.name):y.name;n.push({id:y.id,type:"function",function:{name:b,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?s+=f.delta.text||"":f.delta?.type==="input_json_delta"?n.length>0&&(n[n.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(i+=f.delta.thinking||"");break;case "message_delta":f.usage&&(o={...o,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&g.warn("Anthropic",`Stream parse error: ${f}, data: ${h.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(o);return {id:a,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...i?{reasoning_content:i}:{}},finish_reason:n.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.streamMaxRetries,i=0,o=s.disableCaching||false,a=true;for(;;){let l={...s,...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(),p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",d=await this.client.post(p,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:d.status}),d.status!==200){let T="";for await(let L of d.data)T+=L.toString();let M=`${this.baseUrl}${p}`,B=yt(M,this.buildHeaders(),c,!1);g.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),g.error("CURL",B),g.error("CURL",`=== Error Headers: ${Wc(d.headers)} ===`),g.error("CURL",`=== Error Response: ${T.substring(0,1e3)} ===`);let E=new Error(`Anthropic API error: ${d.status}`);E.response={status:d.status,headers:d.headers,data:T};try{let L=JSON.parse(T);E.response.data=L,L.error?.message?E.message=`Anthropic API error: ${d.status} - ${L.error.message}`:L.message&&(E.message=`Anthropic API error: ${d.status} - ${L.message}`),this.debugLog("API Error Details (stream)",L);}catch{this.debugLog("API Error (non-JSON, stream)",{status:d.status,dataLength:T.length});}throw E}let m="",h=[],f=0,y=!1,b=null,_=!1,v=Date.now(),k=0,R=0,O=null,W=null,F=[],S=null;for await(let T of this.createTimeoutStream(d.data,t.signal)){v=Date.now();let M=T.toString();m+=M;let B=m.split(/\n\n+/);m=B.pop()||"";for(let E of B){let L=E.split(`
1642
- `),N="";for(let $ of L){let G=$.trim();if(G&&!G.startsWith("event:"))if(G.startsWith("data:")){let X=G.slice(5);X.startsWith(" ")&&(X=X.slice(1)),N+=X;}else N+=G;}if(!(!N||N==="[DONE]"))try{let $=N.trim(),G=JSON.parse($);if(process.env.CLI_DEBUG==="1"){let P=JSON.stringify(G).substring(0,80);g.debug("SSE",`${G.type.padEnd(20)} ${P}${JSON.stringify(G).length>80?"...":""}`);}let X=Date.now(),A=this.handleStreamEvent(G,h,f,y,b);if(process.env.CLI_DEBUG==="1"){let P=Date.now()-X;P>50&&g.warn("SSE",`\u26A0\uFE0F Slow event handling: ${G.type} took ${P}ms`);}if(A.yield){let P=Date.now();if(yield A.yield,process.env.CLI_DEBUG==="1"){let K=Date.now()-P;K>100&&g.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${G.type} yield took ${K}ms`);}}if(A.roleSent!==void 0&&(y=A.roleSent),A.incrementToolIndex&&f++,A.usage&&(b=A.usage),A.error)throw new Error(A.error);A.contentBlockStart&&(R++,A.blockType&&(W=A.blockType)),A.contentBlockStop&&(k++,W==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),W=null),A.messageStop&&(_=!0),A.stopReason&&(O=A.stopReason),G.type==="content_block_start"?G.content_block?.type==="thinking"?S={type:"thinking",thinking:"",signature:""}:G.content_block?.type==="redacted_thinking"&&F.push({type:"redacted_thinking",data:G.content_block.data}):G.type==="content_block_delta"?S&&(G.delta?.type==="thinking_delta"?S.thinking+=G.delta.thinking||"":G.delta?.type==="signature_delta"&&(S.signature+=G.delta.signature||"")):G.type==="content_block_stop"&&S&&(F.push({type:S.type,thinking:S.thinking,signature:S.signature}),S=null);}catch{}}}let C=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:_,stopReason:O,contentBlocksStarted:R,contentBlocksCompleted:k,toolCallsCount:h.length,duration:`${C}ms`}),!_&&!O){let T=new Error(`Stream incomplete: message_stop not received (blocks: ${R} started, ${k} completed)`);throw T.code="STREAM_INCOMPLETE",T.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:_,stopReason:O,contentBlocksStarted:R,contentBlocksCompleted:k,toolCallsCount:h.length,duration:`${C}ms`}),T}if(R!==k)if(O==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:R,contentBlocksCompleted:k,stopReason:O}),g.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let T=new Error(`Stream incomplete: content blocks mismatch (${R} started, ${k} completed)`);throw T.code="STREAM_INCOMPLETE",T.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:R,contentBlocksCompleted:k,stopReason:O}),T}if(h.length>0&&O!=="max_tokens")for(let T of h){let M=T.function?.arguments||"";if(M&&M.trim())try{JSON.parse(M);}catch{let B=new Error(`Stream incomplete: tool arguments truncated for ${T.function?.name}`);throw B.code="STREAM_INCOMPLETE",B.isNetworkInterrupt=!0,B.toolName=T.function?.name,this.debugLog("Tool arguments truncated",{toolName:T.function?.name,argsLength:M.length,argsPreview:M.substring(0,100)}),B}}else if(O==="max_tokens"&&h.length>0){let T=h[h.length-1],M=T?.function?.arguments||"";try{JSON.parse(M);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:T?.function?.name,argsLength:M.length}),g.warn("Anthropic",`\u26A0\uFE0F Tool call ${T?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",b);let w=this.buildUsageFromRaw(b);this.debugLog("usage after build",w),!y&&h.length===0&&g.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${C}ms, usage: ${JSON.stringify(b)}`),te.llmResponse("anthropic-stream",C,w||{},{}),this.debugLog("Stream complete",{duration:`${C}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...w?{usage:w}:{},...F.length>0?{thinking_blocks:F}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let p=tt(u);this.debugLog("Stream error",{message:u.message,category:p.category,retryable:p.retryable});let d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",m=`${this.baseUrl}${d}`,h=yt(m,this.buildHeaders(),c,false);if(g.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),g.error("CURL",h),g.error("CURL",`=== Error: ${p.message} ===`),te.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}),g.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(p.retryable&&i<n){i++;let f=Dr(u.response?.headers),y=kn(p.category,i,f||p.retryAfter),b=p.category==="retryable_rate_limit",_=p.category==="retryable_stream";this.debugLog("Stream retrying",{delay:qe(y),attempt:`${i}/${n}`,isRateLimit:b,isStreamIncomplete:_}),yield {type:"stream_retry",error:p.message,errorCode:p.code,attempt:i,maxRetries:n,delayMs:y,isRateLimit:b,isNetworkError:_};try{await Yt(y,t.signal);}catch(v){throw v?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),v}this.debugLog("Stream retry starting",{attempt:i}),yield {type:"stream_recovered",attempt:i,maxRetries:n};continue}throw p}}}buildPayload(e,t){let s=t.model||this.defaultModel,{system:n,anthropicMessages:i}=this.convertMessages(e,t),o=i,a=[];if(t.disableCaching?(a.push({type:"text",text:Go}),n&&a.push({type:"text",text:`
1643
- `+n})):(a.push({type:"text",text:Go,cache_control:{type:"ephemeral"}}),n&&a.push({type:"text",text:`
1644
- `+n,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&n){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(m=>n.includes(m)),p=c.reduce((m,h)=>m>=0?m:n.indexOf(h),-1),d=p>=0?n.slice(p,p+300):void 0;g.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:n.length,snippet:d});}let l={model:this.normalizeModelName(s),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(s,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let s=JSON.stringify(e).length;if(s>Ln){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Ln,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 (${(s/1024/1024).toFixed(2)}MB) exceeds ${(Ln/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>jg&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Ln,percentage:(s/Ln*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let s=[...t],n=s.findIndex(i=>i.role==="user");if(n>=0){let i=s[n],o={type:"text",text:`<system_context>
1639
+ `;return l+p+c}function zc(r,e=2e3){let t=r&&typeof r.toJSON=="function"?r.toJSON():r,s="";try{s=JSON.stringify(t??{},null,2);}catch{s=String(t??"");}return s?s.length>e?`${s.slice(0,e)}
1640
+ ...[truncated ${s.length-e} chars]`:s:"No headers"}var Bi="You are Claude Code, Anthropic's official CLI for Claude.",qg=["claude-code-20250219","interleaved-thinking-2025-05-14"],Kr="2023-06-01",Vr=64,zg=1024;var Jc=18e4,Kc=6e4,Vc={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"},Wi={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"},Ls=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;let s=typeof e.userId=="string"?e.userId.trim():"";this.claudeCodeUserId=s?this.sanitizeUserId(s):this.generateSafeUserId(),this.betaFeatures=e.betaFeatures||qg,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?Bi:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Dg.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=Rs("anthropic",this.baseUrl);this.retryConfig=Lt(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});}setUserId(e){let t=e?.trim?.()||"";t&&(this.claudeCodeUserId=this.sanitizeUserId(t));}isCacheControlError(e){let t="";try{let s=e.response?.data;if(typeof s=="string")t=s.toLowerCase();else if(s&&typeof s=="object"){let n={error:s.error,message:s.message,type:s.type,code:s.code};t=JSON.stringify(n).toLowerCase();}else t=String(e.message||"").toLowerCase();}catch{t=String(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 s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.requestMaxRetries,o=null,i=s.disableCaching||false;for(let a=0;a<=n;a++){let l={...s,...i?{disableCaching:true}:{}},c=this.buildPayload(e,l);a===0&&this.logRequest(t.model||this.defaultModel,c);try{let u=Date.now(),p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",d=await this.client.post(p,c,{responseType:"stream",signal:t.signal});if(d.status!==200){let f="";for await(let v of d.data)f+=v.toString();let y=`${this.baseUrl}${p}`,b=yt(y,this.buildHeaders(),c,!1);g.error("CURL","=== [chat] API Error - Full Request CURL ==="),g.error("CURL",b),g.error("CURL",`=== Error Headers: ${zc(d.headers)} ===`),g.error("CURL",`=== Error Response: ${f.substring(0,1e3)} ===`);let _=new Error(`Anthropic API error: ${d.status}`);_.response={status:d.status,headers:d.headers,data:f};try{let v=JSON.parse(f);_.response.data=v,v.error?.message?_.message=`Anthropic API error: ${d.status} - ${v.error.message}`:v.message&&(_.message=`Anthropic API error: ${d.status} - ${v.message}`),this.debugLog("API Error Details",v);}catch{this.debugLog("API Error (non-JSON)",{status:d.status,dataLength:f.length});}throw _}let m=await this.collectStreamResponse(d.data),h=Date.now()-u;return te.llmResponse("anthropic",h,m.usage,m.choices[0]),this.debugLog("Response",{duration:`${h}ms`,usage:m.usage}),m}catch(u){await this.normalizeAxiosStreamError(u),o=u;let p=tt(u);if(p.code==="PROXY_UPSTREAM_FAILED"){let y=JSON.stringify(c||{}).length,b=Array.isArray(e)?e.length:0,_=Array.isArray(e)?e.reduce((v,k)=>k?.content?typeof k.content=="string"?v+k.content.length:Array.isArray(k.content)?v+k.content.map(R=>typeof R.text=="string"?R.text.length:0).reduce((R,O)=>R+O,0):v:v,0):0;g.warn("Anthropic","Upstream request failed (PROXY_UPSTREAM_FAILED)",{attempt:`${a+1}/${n+1}`,payloadSize:y,msgCount:b,promptChars:_,status:u.response?.status});}if(this.debugLog("Error",{message:u.message,category:p.category,code:p.code,attempt:`${a+1}/${n+1}`}),te.llmError("anthropic",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:a+1}),g.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(!p.retryable||a===n)throw p;let d=$r(u.response?.headers),m=Cn(p.category,a+1,d||p.retryAfter),h=p.category==="retryable_rate_limit",f=h?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${qe(m)} \u540E\u91CD\u8BD5...`:`Retrying in ${qe(m)}...`;this.debugLog("Retrying",{delay:qe(m),attempt:a+1,isRateLimit:h,serverDelay:d?qe(d):"none",retryMsg:f});try{await Xt(m,s.signal);}catch(y){throw y?.name==="AbortError"&&this.debugLog("Chat retry interrupted by user"),y}}}throw o||new Error("Unknown error during retry")}async collectStreamResponse(e){let t="",s="",n=[],o="",i=null,a="";for await(let c of e){let u=c.toString();t+=u;let p=t.split(`
1641
+ `);t=p.pop()||"";for(let d of p){let m=d.trim();if(!m||!m.startsWith("data: "))continue;let h=m.slice(6);if(h!=="[DONE]")try{let f=JSON.parse(h);if(process.env.CLI_DEBUG==="1"){let y=JSON.stringify(f).substring(0,80);g.debug("SSE",`${f.type.padEnd(20)} ${y}${JSON.stringify(f).length>80?"...":""}`);}switch(f.type){case "message_start":a=f.message?.id||"",i=f.message?.usage;break;case "content_block_start":if(f.content_block?.type==="tool_use"){let y=f.content_block,b=this.isProxyMode?Wi[y.name]||this.fromClaudeCodeToolName(y.name):y.name;n.push({id:y.id,type:"function",function:{name:b,arguments:""}});}break;case "content_block_delta":f.delta?.type==="text_delta"?s+=f.delta.text||"":f.delta?.type==="input_json_delta"?n.length>0&&(n[n.length-1].function.arguments+=f.delta.partial_json||""):f.delta?.type==="thinking_delta"&&(o+=f.delta.thinking||"");break;case "message_delta":f.usage&&(i={...i,...f.usage});break}}catch(f){process.env.CLI_DEBUG==="1"&&g.warn("Anthropic",`Stream parse error: ${f}, data: ${h.substring(0,200)}`);}}}let l=this.buildUsageFromRaw(i);return {id:a,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...o?{reasoning_content:o}:{}},finish_reason:n.length>0?"tool_calls":"stop"}],usage:l}}async*chatStreamed(e,t={}){let s={...t,disableCaching:t.disableCaching??this.disableCaching,thinking:t.thinking??this.thinkingConfig??void 0},n=this.retryConfig.streamMaxRetries,o=0,i=s.disableCaching||false,a=true;for(;;){let l={...s,...i?{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(),p=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",d=await this.client.post(p,c,{responseType:"stream",signal:t.signal});if(this.debugLog("Stream started",{status:d.status}),d.status!==200){let T="";for await(let L of d.data)T+=L.toString();let M=`${this.baseUrl}${p}`,B=yt(M,this.buildHeaders(),c,!1);g.error("CURL","=== [chatStreamed] API Error - Full Request CURL ==="),g.error("CURL",B),g.error("CURL",`=== Error Headers: ${zc(d.headers)} ===`),g.error("CURL",`=== Error Response: ${T.substring(0,1e3)} ===`);let E=new Error(`Anthropic API error: ${d.status}`);E.response={status:d.status,headers:d.headers,data:T};try{let L=JSON.parse(T);E.response.data=L,L.error?.message?E.message=`Anthropic API error: ${d.status} - ${L.error.message}`:L.message&&(E.message=`Anthropic API error: ${d.status} - ${L.message}`),this.debugLog("API Error Details (stream)",L);}catch{this.debugLog("API Error (non-JSON, stream)",{status:d.status,dataLength:T.length});}throw E}let m="",h=[],f=0,y=!1,b=null,_=!1,v=Date.now(),k=0,R=0,O=null,W=null,F=[],S=null;for await(let T of this.createTimeoutStream(d.data,t.signal)){v=Date.now();let M=T.toString();m+=M;let B=m.split(/\n\n+/);m=B.pop()||"";for(let E of B){let L=E.split(`
1642
+ `),N="";for(let $ of L){let G=$.trim();if(G&&!G.startsWith("event:"))if(G.startsWith("data:")){let X=G.slice(5);X.startsWith(" ")&&(X=X.slice(1)),N+=X;}else N+=G;}if(!(!N||N==="[DONE]"))try{let $=N.trim(),G=JSON.parse($);if(process.env.CLI_DEBUG==="1"){let P=JSON.stringify(G).substring(0,80);g.debug("SSE",`${G.type.padEnd(20)} ${P}${JSON.stringify(G).length>80?"...":""}`);}let X=Date.now(),A=this.handleStreamEvent(G,h,f,y,b);if(process.env.CLI_DEBUG==="1"){let P=Date.now()-X;P>50&&g.warn("SSE",`\u26A0\uFE0F Slow event handling: ${G.type} took ${P}ms`);}if(A.yield){let P=Date.now();if(yield A.yield,process.env.CLI_DEBUG==="1"){let K=Date.now()-P;K>100&&g.warn("SSE",`\u26A0\uFE0F Slow yield consumer: ${G.type} yield took ${K}ms`);}}if(A.roleSent!==void 0&&(y=A.roleSent),A.incrementToolIndex&&f++,A.usage&&(b=A.usage),A.error)throw new Error(A.error);A.contentBlockStart&&(R++,A.blockType&&(W=A.blockType)),A.contentBlockStop&&(k++,W==="thinking"&&(yield {choices:[{delta:{reasoning_complete:!0},index:0}]}),W=null),A.messageStop&&(_=!0),A.stopReason&&(O=A.stopReason),G.type==="content_block_start"?G.content_block?.type==="thinking"?S={type:"thinking",thinking:"",signature:""}:G.content_block?.type==="redacted_thinking"&&F.push({type:"redacted_thinking",data:G.content_block.data}):G.type==="content_block_delta"?S&&(G.delta?.type==="thinking_delta"?S.thinking+=G.delta.thinking||"":G.delta?.type==="signature_delta"&&(S.signature+=G.delta.signature||"")):G.type==="content_block_stop"&&S&&(F.push({type:S.type,thinking:S.thinking,signature:S.signature}),S=null);}catch{}}}let C=Date.now()-u;if(this.debugLog("Stream completion check",{messageStopReceived:_,stopReason:O,contentBlocksStarted:R,contentBlocksCompleted:k,toolCallsCount:h.length,duration:`${C}ms`}),!_&&!O){let T=new Error(`Stream incomplete: message_stop not received (blocks: ${R} started, ${k} completed)`);throw T.code="STREAM_INCOMPLETE",T.isNetworkInterrupt=!0,this.debugLog("Stream incomplete detected",{messageStopReceived:_,stopReason:O,contentBlocksStarted:R,contentBlocksCompleted:k,toolCallsCount:h.length,duration:`${C}ms`}),T}if(R!==k)if(O==="max_tokens")this.debugLog("Content blocks mismatch due to max_tokens (expected, not an error)",{contentBlocksStarted:R,contentBlocksCompleted:k,stopReason:O}),g.warn("Anthropic","\u26A0\uFE0F Response truncated due to max_tokens limit. Consider increasing max_tokens or breaking down the task.");else {let T=new Error(`Stream incomplete: content blocks mismatch (${R} started, ${k} completed)`);throw T.code="STREAM_INCOMPLETE",T.isNetworkInterrupt=!0,this.debugLog("Content blocks mismatch",{contentBlocksStarted:R,contentBlocksCompleted:k,stopReason:O}),T}if(h.length>0&&O!=="max_tokens")for(let T of h){let M=T.function?.arguments||"";if(M&&M.trim())try{JSON.parse(M);}catch{let B=new Error(`Stream incomplete: tool arguments truncated for ${T.function?.name}`);throw B.code="STREAM_INCOMPLETE",B.isNetworkInterrupt=!0,B.toolName=T.function?.name,this.debugLog("Tool arguments truncated",{toolName:T.function?.name,argsLength:M.length,argsPreview:M.substring(0,100)}),B}}else if(O==="max_tokens"&&h.length>0){let T=h[h.length-1],M=T?.function?.arguments||"";try{JSON.parse(M);}catch{this.debugLog("Tool arguments truncated due to max_tokens (expected)",{toolName:T?.function?.name,argsLength:M.length}),g.warn("Anthropic",`\u26A0\uFE0F Tool call ${T?.function?.name} arguments truncated due to max_tokens. The tool call will be incomplete.`);}}this.debugLog("finalUsage before build",b);let w=this.buildUsageFromRaw(b);this.debugLog("usage after build",w),!y&&h.length===0&&g.warn("Anthropic",`\u26A0\uFE0F Stream completed with no content! duration: ${C}ms, usage: ${JSON.stringify(b)}`),te.llmResponse("anthropic-stream",C,w||{},{}),this.debugLog("Stream complete",{duration:`${C}ms`}),yield {choices:[{delta:{},finish_reason:"stop",index:0}],...w?{usage:w}:{},...F.length>0?{thinking_blocks:F}:{}};return}catch(u){await this.normalizeAxiosStreamError(u);let p=tt(u);this.debugLog("Stream error",{message:u.message,category:p.category,retryable:p.retryable});let d=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",m=`${this.baseUrl}${d}`,h=yt(m,this.buildHeaders(),c,false);if(g.error("CURL","=== [chatStreamed catch] Stream Error - Full Request CURL ==="),g.error("CURL",h),g.error("CURL",`=== Error: ${p.message} ===`),te.llmError("anthropic-stream",u),this.isCacheControlError(u)&&!i){i=true,this.disableCaching=true,this.debugLog("Cache control not supported, disabling caching for retry",{errorMessage:u.message,attempt:o+1}),g.warn("Anthropic","\u26A0\uFE0F Provider \u4E0D\u652F\u6301 cache_control\uFF0C\u5DF2\u81EA\u52A8\u7981\u7528\u7F13\u5B58\u91CD\u8BD5...");continue}if(p.retryable&&o<n){o++;let f=$r(u.response?.headers),y=Cn(p.category,o,f||p.retryAfter),b=p.category==="retryable_rate_limit",_=p.category==="retryable_stream";this.debugLog("Stream retrying",{delay:qe(y),attempt:`${o}/${n}`,isRateLimit:b,isStreamIncomplete:_}),yield {type:"stream_retry",error:p.message,errorCode:p.code,attempt:o,maxRetries:n,delayMs:y,isRateLimit:b,isNetworkError:_};try{await Xt(y,t.signal);}catch(v){throw v?.name==="AbortError"&&this.debugLog("Stream retry interrupted by user"),v}this.debugLog("Stream retry starting",{attempt:o}),yield {type:"stream_recovered",attempt:o,maxRetries:n};continue}throw p}}}buildPayload(e,t){let s=t.model||this.defaultModel,{system:n,anthropicMessages:o}=this.convertMessages(e,t),i=o,a=[];if(t.disableCaching?(a.push({type:"text",text:Bi}),n&&a.push({type:"text",text:`
1643
+ `+n})):(a.push({type:"text",text:Bi,cache_control:{type:"ephemeral"}}),n&&a.push({type:"text",text:`
1644
+ `+n,cache_control:{type:"ephemeral"}})),process.env.CLI_DEBUG==="1"&&n){let c=["## \u9879\u76EE\u8BB0\u5FC6","## \u4E0A\u6B21\u4EFB\u52A1\u6458\u8981","## Project Memory","## Last Run Summary"],u=c.some(m=>n.includes(m)),p=c.reduce((m,h)=>m>=0?m:n.indexOf(h),-1),d=p>=0?n.slice(p,p+300):void 0;g.info("MEMORY_INJECT","Anthropic system memory check",{hasMemory:u,systemLength:n.length,snippet:d});}let l={model:this.normalizeModelName(s),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=i,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(s,t)&&(l.thinking=this.buildThinkingPayload(t),delete l.temperature,l.temperature=1),this.checkRequestBudget(l),l}checkRequestBudget(e){let s=JSON.stringify(e).length;if(s>Dn){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Dn,messageCount:e.messages?.length||0}),e.messages){let o=[...e.messages.map((i,a)=>({index:a,role:i.role,contentSize:JSON.stringify(i.content||"").length}))].sort((i,a)=>a.contentSize-i.contentSize);this.debugLog("Largest messages in request",{top5:o.slice(0,5)});}console.warn(`[Anthropic] \u26A0\uFE0F Request body size (${(s/1024/1024).toFixed(2)}MB) exceeds ${(Dn/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>Wg&&this.debugLog("Request body approaching limit",{bodySize:s,limit:Dn,percentage:(s/Dn*100).toFixed(1)+"%"});}mergeSystemIntoMessages(e,t){let s=[...t],n=s.findIndex(o=>o.role==="user");if(n>=0){let o=s[n],i={type:"text",text:`<system_context>
1645
1645
  ${e}
1646
- </system_context>`};Array.isArray(i.content)?s[n]={...i,content:[o,...i.content]}:typeof i.content=="string"&&(s[n]={...i,content:[o,{type:"text",text:i.content}]});}return s}buildToolsPayload(e,t){return e.map(n=>this.transformToolDefinition(n))}ensureLastToolCacheControl(e,t){if(e.length===0||t.disableCaching)return;let s=e[e.length-1];s.cache_control={type:"ephemeral"},this.debugLog("Added cache_control to last tool",{toolName:s.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,Wg)}}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 s=this.normalizeMessages(e),n=[],i=[];for(let u of s){if(u.role==="system"){let d=ee(u.content).trim();d&&n.push(d);continue}let p=this.convertSingleMessage(u);p&&i.push(p);}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:n.length>0?n.join(`
1646
+ </system_context>`};Array.isArray(o.content)?s[n]={...o,content:[i,...o.content]}:typeof o.content=="string"&&(s[n]={...o,content:[i,{type:"text",text:o.content}]});}return s}buildToolsPayload(e,t){return e.map(n=>this.transformToolDefinition(n))}ensureLastToolCacheControl(e,t){if(e.length===0||t.disableCaching)return;let s=e[e.length-1];s.cache_control={type:"ephemeral"},this.debugLog("Added cache_control to last tool",{toolName:s.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,zg)}}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 s=this.normalizeMessages(e),n=[],o=[];for(let u of s){if(u.role==="system"){let d=ee(u.content).trim();d&&n.push(d);continue}let p=this.convertSingleMessage(u);p&&o.push(p);}let i=this.mergeConsecutiveUserMessages(o),l=this.validateToolResultPairs(i);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:n.length>0?n.join(`
1647
1647
 
1648
- `):null,anthropicMessages:l}}addMessageCacheControl(e){let t=false;for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(n.role!=="user"||!Array.isArray(n.content))){for(let i=n.content.length-1;i>=0;i--){let o=n.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 s=e[t];if(s.role==="user"&&Array.isArray(s.content)){for(let n=s.content.length-1;n>=0;n--)if(s.content[n].type==="text"){s.content[n].cache_control={type:"ephemeral"},this.debugLog("Added cache_control to user text block");return}}}}validateToolResultPairs(e){let t=new Set,s=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&&s.add(a.tool_use_id);let n=new Set;for(let o of t)s.has(o)&&n.add(o);this.debugLog("Tool pairing analysis",{toolUseCount:t.size,toolResultCount:s.size,pairedCount:n.size,orphanToolUseIds:Array.from(t).filter(o=>!n.has(o)),orphanToolResultIds:Array.from(s).filter(o=>!n.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=n.has(l.id);return c||this.debugLog("Removing orphan tool_use",{id:l.id}),c}if(l.type==="tool_result"){let c=n.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 s of e){let n=t[t.length-1];if(n&&n.role==="user"&&s.role==="user"){let i=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}],o=Array.isArray(s.content)?s.content:[{type:"text",text:s.content}];n.content=[...i,...o];}else t.push(s);}return t}convertSingleMessage(e){if(e.role==="tool"){let s=ee(e.content),n=Gg(s);return s.length!==n.length&&this.debugLog("Tool output truncated",{tool_call_id:e.tool_call_id,original:s.length,truncated:n.length}),{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:n}]}}if(e.role==="assistant"){let s=[],n=false;if(e.thinking_blocks&&e.thinking_blocks.length>0){n=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),s.push(a);}else if(o.type==="redacted_thinking"){let a={type:"redacted_thinking"};o.data!==void 0&&(a.data=o.data),s.push(a);}}let i=ee(e.content);if(i){let o=i.trimEnd();s.push({type:"text",text:o||"."});}else n&&(s.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?zc[o.function.name]||this.toClaudeCodeToolName(o.function.name):o.function.name;s.push({type:"tool_use",id:o.id,name:c,input:l});}if(s.length>0){let o=s[s.length-1];this.debugLog("Assistant message final check",{contentLength:s.length,lastBlockType:o.type,hasThinkingBlocks:n,blockTypes:s.map(a=>a.type),lastBlockTextPreview:o.type==="text"?(o.text||"").substring(0,50):void 0}),o.type==="thinking"||o.type==="redacted_thinking"?(s.push({type:"text",text:"."}),this.debugLog("Fixed: Added text block after thinking")):o.type==="text"&&(!o.text||!o.text.trim())&&s.some(l=>l.type==="thinking"||l.type==="redacted_thinking")&&(o.text=".",this.debugLog("Fixed: Ensured text block has content after thinking"));}return s.length>0?{role:"assistant",content:s}:null}if(Array.isArray(e.content)){let s=e.content.filter(o=>o.type==="text");if(!e.content.some(o=>o.type!=="text")&&s.length===1){let o=s[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=ee(e.content);return t.trim()?{role:"user",content:t}:null}convertMultimodalContent(e){let t=[];for(let s of e)if(s.type==="text")t.push({type:"text",text:s.text});else if(s.type==="image_url"){let n=this.convertImageUrl(s.image_url.url);n&&t.push(n);}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(s=>{let n=s.role==="assistant"&&!!(s.tool_calls&&s.tool_calls.length>0),i=s.role==="assistant"&&!!(s.thinking_blocks&&s.thinking_blocks.length>0);return n||i?true:s.content?typeof s.content=="string"?s.content.trim().length>0:Array.isArray(s.content)?s.content.length>0:true:false});return t.length===0?[]:(this.validateMessageAlternation(t),t)}validateMessageAlternation(e){let t=e.filter(n=>n.role!=="system"),s=false;for(let n=1;n<t.length;n++)t[n].role===t[n-1].role&&(s=true,this.debugLog("Message alternation warning",{index:n,prevRole:t[n-1].role,currentRole:t[n].role}));!s&&t.length>1&&this.debugLog("Message alternation OK",{messageCount:t.length,roles:t.map(n=>n.role)});}convertResponse(e){this.debugLog("Raw response",e);let t=e.content||[],s="",n=[],i="";for(let a of t)if(a.type==="text")s+=a.text;else if(a.type==="tool_use"){let l=this.isProxyMode?Bo[a.name]||this.fromClaudeCodeToolName(a.name):a.name;n.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:s||"",tool_calls:n.length>0?n: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,s,n,i){switch(e.type){case "message_start":return this.debugLog("message_start usage",e.message?.usage),process.env.CLI_DEBUG==="1"&&e.message&&g.debug("Anthropic",`message_start full: ${JSON.stringify(e.message,null,2)}`),{usage:e.message?.usage};case "content_block_start":return {...this.handleContentBlockStart(e,t,s,n),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||e.stop_reason;if(a&&this.debugLog("message_delta stop_reason",a),e.usage&&i){let u={...i,...e.usage};return this.debugLog("merged usage",u),{usage:u,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:let l=e.type?.toLowerCase()||"";if(l==="done"||l==="stream_end"||l==="end")return this.debugLog("Alternative message stop received",{type:e.type}),{messageStop:true};let c=e.stop_reason||e.delta?.stop_reason;return c?(this.debugLog("stop_reason found in unknown event",{type:e.type,stopReason:c}),{stopReason:c}):(this.debugLog("Unknown event type",{type:e.type}),{})}}handleContentBlockStart(e,t,s,n){let i=e.content_block?.type;if(i==="text")return n?{blockType:i}:{yield:{choices:[{delta:{role:"assistant"},index:0}]},roleSent:true,blockType:i};if(i==="tool_use"){let o=e.content_block,a=this.isProxyMode?Bo[o.name]||this.fromClaudeCodeToolName(o.name):o.name,l="";return o.input&&typeof o.input=="object"&&Object.keys(o.input).length>0&&(l=JSON.stringify(o.input)),t.push({index:s,id:o.id,type:"function",function:{name:a,arguments:l}}),{yield:{choices:[{delta:{tool_calls:[{index:s,id:o.id,type:"function",function:{name:a}}]},index:0}]},incrementToolIndex:true,blockType:i}}else if(i==="thinking")return {blockType:i};return {blockType:i}}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 s=e.delta.partial_json||"";if(t.length>0){let n=t[t.length-1];return n.function.arguments+=s,{yield:{choices:[{delta:{tool_calls:[{index:n.index,function:{arguments:s}}]},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 s=this.tryFixJson(t.function.arguments);s?(t.function.arguments=s,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 s=0,n=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==="{"?s++:a==="}"?s--:a==="["?n++:a==="]"&&n--);}for(t=e,i&&(t+='"');n>0;)t+="]",n--;for(;s>0;)t+="}",s--;try{return JSON.parse(t),t}catch{return null}}transformToolDefinition(e){let t=this.isProxyMode?zc[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 s=this.truncateDescription(e.description||e.name),n=this.stripSchemaDescriptions(e.parameters);return {name:t,description:s,input_schema:n}}stripSchemaPropertyDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaPropertyDescriptions(s));let t={...e};if(t.properties&&typeof t.properties=="object"){let s={};for(let[n,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)),s[n]=o;}else s[n]=i;t.properties=s;}t.items&&(t.items=this.stripSchemaPropertyDescriptions(t.items));for(let s of ["oneOf","anyOf","allOf"])t[s]&&Array.isArray(t[s])&&(t[s]=t[s].map(n=>this.stripSchemaPropertyDescriptions(n)));return t}toClaudeCodeToolName(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}fromClaudeCodeToolName(e){return e.replace(/["\s/>]+$/g,"").trim().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(s=>this.stripSchemaDescriptions(s));let t={...e};if(delete t.description,t.properties&&typeof t.properties=="object"){let s={};for(let[n,i]of Object.entries(t.properties))s[n]=this.stripSchemaDescriptions(i);t.properties=s;}for(let s of ["items","oneOf","anyOf","allOf"])t[s]&&(t[s]=Array.isArray(t[s])?t[s].map(n=>this.stripSchemaDescriptions(n)):this.stripSchemaDescriptions(t[s]));return t}buildHeaders(){return this.isProxyMode?this.buildClaudeCodeHeaders():this.buildOfficialHeaders()}buildOfficialHeaders(){return {"anthropic-api-key":this.authToken,"anthropic-version":Jr,"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":Jr,"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 s=randomBytes(32).toString("hex"),n=this.generateUUID();return `user_${s}_account__session_${n}`}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"),s=this.generateUUID();return `user_${t}_account__session_${s}`}if(/^\+?[\d\s-]{10,}$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}return e}return e.length>Kr?createHash("sha256").update(e).digest("hex").slice(0,Kr):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Kr):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Kr):e}async normalizeAxiosStreamError(e){let t=e?.response?.data;if(!(!t||typeof t!="object"||!(typeof t.pipe=="function")))try{let n=await this.readStreamToString(t);try{e.response.data=JSON.parse(n);}catch{e.response.data=n;}}catch{}}readStreamToString(e){return new Promise((t,s)=>{let n=[];e.on("data",i=>{n.push(typeof i=="string"?Buffer.from(i):i);}),e.on("end",()=>t(Buffer.concat(n).toString("utf-8"))),e.on("error",s);})}async*createTimeoutStream(e,t){let s=false,n=Date.now(),i=0,o=e[Symbol.asyncIterator](),a=()=>new Promise(l=>setImmediate(l));for(process.env.CLI_DEBUG==="1"&&g.debug("STREAM","\u{1F30A} Stream processing started");;){if(t?.aborted)throw this.debugLog("Stream aborted by signal"),process.env.CLI_DEBUG==="1"&&g.debug("STREAM",`\u26D4 Stream aborted after ${i} chunks`),e.destroy?.(),new Error("Request aborted");await a();let l=s?Hc:qc,c;try{let u=t?new Promise((m,h)=>{let f=()=>{h(new Error("Request aborted"));};t.aborted?f():t.addEventListener("abort",f,{once:!0});}):null,p=[o.next(),new Promise((m,h)=>{c=setTimeout(()=>{h(new Error(s?`Stream idle timeout: no data for ${Hc/1e3}s`:`Stream first chunk timeout: no response for ${qc/1e3}s`));},l);})];u&&p.push(u);let d=await Promise.race(p);if(c&&clearTimeout(c),d.done){process.env.CLI_DEBUG==="1"&&g.debug("STREAM",`\u2705 Stream completed successfully (${i} chunks, ${Date.now()-n}ms)`);return}s=!0,n=Date.now(),i++,process.env.CLI_DEBUG==="1"&&i%100===0&&g.debug("STREAM",`\u{1F4E6} Processed ${i} chunks`),yield d.value;}catch(u){c&&clearTimeout(c);let p=u.message?.includes("aborted")||u.message==="Request aborted";throw this.debugLog("Stream timeout or abort",{error:u.message,isAbort:p,receivedFirstChunk:s,idleTime:`${(Date.now()-n)/1e3}s`}),e.destroy?.(),p?(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"&&g.debug("Anthropic",t?`${e} ${JSON.stringify(t,null,2)}`:e);}logRequest(e,t,s=false){process.env.CLI_DEBUG_PAYLOAD==="1"&&this.debugLog("Full payload",JSON.stringify(t,null,2));let n=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",i=`${this.baseUrl}${n}`,o=this.buildHeaders();mi(i,o,t);let a=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":Jr,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":Jr,"Content-Type":"application/json"};te.llmRequest(s?"anthropic-stream":"anthropic",e,t,i,a),this.debugLog(`${s?"Stream ":""}Request`,{url:i,model:e,isProxyMode:this.isProxyMode});}};le();var Vr=class extends ft{constraints;promptBuilder;provider;defaultModel;disableCaching;constructor(e){super(),this.constraints=new An,this.promptBuilder=new Pn,this.defaultModel=e.defaultModel||"claude-3-5-sonnet-20241022",this.disableCaching=e.disableCaching||false;let{authToken:t,baseUrl:s,defaultModel:n,maxTokens:i,disableCaching:o,userId:a,...l}=e;this.provider=new Os({authToken:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:i,disableCaching:this.disableCaching,userId:a,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=super.prepareRequest(e,{...t,model:s}),i={...n.options};if(i.maxInputTokens!==void 0&&(i.max_tokens=i.maxInputTokens,delete i.maxInputTokens),!i.max_tokens){let o=this.constraints.getTokenLimits(s);i.max_tokens=Math.min(4096,o.maxOutput);}if(!this.disableCaching&&this.constraints.supportsPromptCaching(s)){let o=n.messages[0]?.content?.length||0,a=this.promptBuilder.getCachingRecommendation(o);a.shouldUseCache&&(i.enableCaching=true,i.cacheTtl=a.cacheTTL);}return {...n,options:i}}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("AnthropicAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("AnthropicAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsThinking:this.constraints.supportsThinking?.(t)||false,supportsPromptCaching:this.constraints.supportsPromptCaching(t),tokenLimits:this.constraints.getTokenLimits(t)}}getCachingRecommendation(e){return this.promptBuilder.getCachingRecommendation(e)}};var Yr=class extends Zt{getConstraints(){let e=super.getConstraints(),t={...e.validators??{}};t.temperature=Fe(0,1);let s=t.tool_choice;t.tool_choice=i=>i==="required"?"tool_choice=required is not supported by Kimi API":typeof s=="function"?s(i):true;let n=t.n;return t.n=(i,o)=>{let a=typeof n=="function"?n(i,o):true;if(a!==true)return a;let l=o?.temperature??1,c=typeof l=="number"?l:Number(l),u=typeof i=="number"?i:Number(i);return !Number.isNaN(c)&&c<=.001&&u>1?"temperature <= 0.001 requires n=1 for Kimi API":true},{...e,validators:t}}};le();var Xr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Yr,this.promptBuilder=new es,this.defaultModel=e.defaultModel||"kimi-k2-0905-preview";let{apiKey:t,baseUrl:s,defaultModel:n,maxTokens:i,maxInputTokens:o,...a}=e;this.provider=new Ct({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:i,maxInputTokens:o,...a,structuredOutputMode:"json_object"});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("KimiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("KimiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}};var Zr=class extends Ft{getConstraints(){return {maxOutputTokens:{},maxInputTokens:{},supportedParams:new Set(["model","messages","stream","max_tokens","temperature","topP","topK","stopSequences","tools","structuredOutput","signal"]),validators:{temperature:Fe(0,2),topP:Fe(0,1),topK:Fe(1,128),max_tokens:e=>{let t=Number(e);return Number.isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},stopSequences:e=>Array.isArray(e)?e.some(s=>typeof s!="string"||s.length===0)?"All stop sequences must be non-empty strings":true:"Must be an array of strings",stream:Uc("boolean")},defaults:{temperature:1}}}};var Dn=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:i}=e,o=[];return o.push({content:this.getCoreInstructions(s,n),order:0}),o.push(this.getWorkingDirectorySection(t,s)),o.push({content:this.getCapabilitiesSection(s,n),order:20}),o.push({title:s==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(s),order:30}),o.push({title:s==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(s),order:40}),o.push({content:this.getGeneralRules(s),order:50}),i&&i.trim()&&o.push({title:s==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:i.trim(),order:60}),Qt(this.combinePromptSections(o))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1648
+ `):null,anthropicMessages:l}}addMessageCacheControl(e){let t=false;for(let s=e.length-1;s>=0;s--){let n=e[s];if(!(n.role!=="user"||!Array.isArray(n.content))){for(let o=n.content.length-1;o>=0;o--){let i=n.content[o];if(!t&&i.type==="tool_result"){i.cache_control={type:"ephemeral"},t=true,this.debugLog("Added cache_control to tool_result",{tool_use_id:i.tool_use_id});break}}if(t)break}}t||this.addTextBlockCacheControl(e);}addTextBlockCacheControl(e){for(let t=e.length-1;t>=0;t--){let s=e[t];if(s.role==="user"&&Array.isArray(s.content)){for(let n=s.content.length-1;n>=0;n--)if(s.content[n].type==="text"){s.content[n].cache_control={type:"ephemeral"},this.debugLog("Added cache_control to user text block");return}}}}validateToolResultPairs(e){let t=new Set,s=new Set;for(let i of e)if(Array.isArray(i.content))for(let a of i.content)a.type==="tool_use"&&a.id&&t.add(a.id),a.type==="tool_result"&&a.tool_use_id&&s.add(a.tool_use_id);let n=new Set;for(let i of t)s.has(i)&&n.add(i);this.debugLog("Tool pairing analysis",{toolUseCount:t.size,toolResultCount:s.size,pairedCount:n.size,orphanToolUseIds:Array.from(t).filter(i=>!n.has(i)),orphanToolResultIds:Array.from(s).filter(i=>!n.has(i))});let o=[];for(let i of e){if(!Array.isArray(i.content)){o.push(i);continue}let a=i.content.filter(l=>{if(l.type==="tool_use"){let c=n.has(l.id);return c||this.debugLog("Removing orphan tool_use",{id:l.id}),c}if(l.type==="tool_result"){let c=n.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?o.push({...i,content:a}):this.debugLog("Skipping empty message after tool pairing filter",{role:i.role});}return o}mergeConsecutiveUserMessages(e){if(e.length===0)return [];let t=[];for(let s of e){let n=t[t.length-1];if(n&&n.role==="user"&&s.role==="user"){let o=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}],i=Array.isArray(s.content)?s.content:[{type:"text",text:s.content}];n.content=[...o,...i];}else t.push(s);}return t}convertSingleMessage(e){if(e.role==="tool"){let s=ee(e.content),n=Hg(s);return s.length!==n.length&&this.debugLog("Tool output truncated",{tool_call_id:e.tool_call_id,original:s.length,truncated:n.length}),{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:n}]}}if(e.role==="assistant"){let s=[],n=false;if(e.thinking_blocks&&e.thinking_blocks.length>0){n=true;for(let i of e.thinking_blocks)if(i.type==="thinking"){let a={type:"thinking",thinking:i.thinking};i.signature!==void 0&&(a.signature=i.signature),s.push(a);}else if(i.type==="redacted_thinking"){let a={type:"redacted_thinking"};i.data!==void 0&&(a.data=i.data),s.push(a);}}let o=ee(e.content);if(o){let i=o.trimEnd();s.push({type:"text",text:i||"."});}else n&&(s.push({type:"text",text:"."}),this.debugLog("Added placeholder text after thinking (no text content)"));if(e.tool_calls)for(let i of e.tool_calls){let a=(i.function.arguments||"").trim(),l={};if(a.length>0)try{l=JSON.parse(a);}catch{this.debugLog("Failed to parse tool arguments",{tool:i.function.name});}let c=this.isProxyMode?Vc[i.function.name]||this.toClaudeCodeToolName(i.function.name):i.function.name;s.push({type:"tool_use",id:i.id,name:c,input:l});}if(s.length>0){let i=s[s.length-1];this.debugLog("Assistant message final check",{contentLength:s.length,lastBlockType:i.type,hasThinkingBlocks:n,blockTypes:s.map(a=>a.type),lastBlockTextPreview:i.type==="text"?(i.text||"").substring(0,50):void 0}),i.type==="thinking"||i.type==="redacted_thinking"?(s.push({type:"text",text:"."}),this.debugLog("Fixed: Added text block after thinking")):i.type==="text"&&(!i.text||!i.text.trim())&&s.some(l=>l.type==="thinking"||l.type==="redacted_thinking")&&(i.text=".",this.debugLog("Fixed: Ensured text block has content after thinking"));}return s.length>0?{role:"assistant",content:s}:null}if(Array.isArray(e.content)){let s=e.content.filter(i=>i.type==="text");if(!e.content.some(i=>i.type!=="text")&&s.length===1){let i=s[0].text;return i.trim()?{role:"user",content:i}:null}let o=this.convertMultimodalContent(e.content);return o.length>0?{role:"user",content:o}:null}let t=ee(e.content);return t.trim()?{role:"user",content:t}:null}convertMultimodalContent(e){let t=[];for(let s of e)if(s.type==="text")t.push({type:"text",text:s.text});else if(s.type==="image_url"){let n=this.convertImageUrl(s.image_url.url);n&&t.push(n);}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(s=>{let n=s.role==="assistant"&&!!(s.tool_calls&&s.tool_calls.length>0),o=s.role==="assistant"&&!!(s.thinking_blocks&&s.thinking_blocks.length>0);return n||o?true:s.content?typeof s.content=="string"?s.content.trim().length>0:Array.isArray(s.content)?s.content.length>0:true:false});return t.length===0?[]:(this.validateMessageAlternation(t),t)}validateMessageAlternation(e){let t=e.filter(n=>n.role!=="system"),s=false;for(let n=1;n<t.length;n++)t[n].role===t[n-1].role&&(s=true,this.debugLog("Message alternation warning",{index:n,prevRole:t[n-1].role,currentRole:t[n].role}));!s&&t.length>1&&this.debugLog("Message alternation OK",{messageCount:t.length,roles:t.map(n=>n.role)});}convertResponse(e){this.debugLog("Raw response",e);let t=e.content||[],s="",n=[],o="";for(let a of t)if(a.type==="text")s+=a.text;else if(a.type==="tool_use"){let l=this.isProxyMode?Wi[a.name]||this.fromClaudeCodeToolName(a.name):a.name;n.push({id:a.id,type:"function",function:{name:l,arguments:JSON.stringify(a.input)}});}else a.type==="thinking"&&(o=a.thinking||"");let i=this.buildUsageFromRaw(e.usage);return {id:e.id,choices:[{message:{role:"assistant",content:s||"",tool_calls:n.length>0?n:void 0,...o?{reasoning_content:o}:{}},finish_reason:this.convertStopReason(e.stop_reason)}],usage:i}}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,s,n,o){switch(e.type){case "message_start":return this.debugLog("message_start usage",e.message?.usage),process.env.CLI_DEBUG==="1"&&e.message&&g.debug("Anthropic",`message_start full: ${JSON.stringify(e.message,null,2)}`),{usage:e.message?.usage};case "content_block_start":return {...this.handleContentBlockStart(e,t,s,n),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:o});let a=e.delta?.stop_reason||e.stop_reason;if(a&&this.debugLog("message_delta stop_reason",a),e.usage&&o){let u={...o,...e.usage};return this.debugLog("merged usage",u),{usage:u,stopReason:a}}return {usage:e.usage||o,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:let l=e.type?.toLowerCase()||"";if(l==="done"||l==="stream_end"||l==="end")return this.debugLog("Alternative message stop received",{type:e.type}),{messageStop:true};let c=e.stop_reason||e.delta?.stop_reason;return c?(this.debugLog("stop_reason found in unknown event",{type:e.type,stopReason:c}),{stopReason:c}):(this.debugLog("Unknown event type",{type:e.type}),{})}}handleContentBlockStart(e,t,s,n){let o=e.content_block?.type;if(o==="text")return n?{blockType:o}:{yield:{choices:[{delta:{role:"assistant"},index:0}]},roleSent:true,blockType:o};if(o==="tool_use"){let i=e.content_block,a=this.isProxyMode?Wi[i.name]||this.fromClaudeCodeToolName(i.name):i.name,l="";return i.input&&typeof i.input=="object"&&Object.keys(i.input).length>0&&(l=JSON.stringify(i.input)),t.push({index:s,id:i.id,type:"function",function:{name:a,arguments:l}}),{yield:{choices:[{delta:{tool_calls:[{index:s,id:i.id,type:"function",function:{name:a}}]},index:0}]},incrementToolIndex:true,blockType:o}}else if(o==="thinking")return {blockType:o};return {blockType:o}}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 s=e.delta.partial_json||"";if(t.length>0){let n=t[t.length-1];return n.function.arguments+=s,{yield:{choices:[{delta:{tool_calls:[{index:n.index,function:{arguments:s}}]},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 s=this.tryFixJson(t.function.arguments);s?(t.function.arguments=s,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 s=0,n=0,o=false,i=false;for(let a of e){if(i){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"?s++:a==="}"?s--:a==="["?n++:a==="]"&&n--);}for(t=e,o&&(t+='"');n>0;)t+="]",n--;for(;s>0;)t+="}",s--;try{return JSON.parse(t),t}catch{return null}}transformToolDefinition(e){let t=this.isProxyMode?Vc[e.name]||this.toClaudeCodeToolName(e.name):e.name;if(this.isProxyMode){let o=this.stripSchemaPropertyDescriptions(e.parameters);return {name:t,description:e.description,input_schema:o}}if(!this.sanitizeToolsForProxy)return {name:t,description:e.description,input_schema:e.parameters};let s=this.truncateDescription(e.description||e.name),n=this.stripSchemaDescriptions(e.parameters);return {name:t,description:s,input_schema:n}}stripSchemaPropertyDescriptions(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(s=>this.stripSchemaPropertyDescriptions(s));let t={...e};if(t.properties&&typeof t.properties=="object"){let s={};for(let[n,o]of Object.entries(t.properties))if(o&&typeof o=="object"){let i={...o};delete i.description,i.properties&&(i.properties=this.stripSchemaPropertyDescriptions({properties:i.properties}).properties),i.items&&(i.items=this.stripSchemaPropertyDescriptions(i.items)),s[n]=i;}else s[n]=o;t.properties=s;}t.items&&(t.items=this.stripSchemaPropertyDescriptions(t.items));for(let s of ["oneOf","anyOf","allOf"])t[s]&&Array.isArray(t[s])&&(t[s]=t[s].map(n=>this.stripSchemaPropertyDescriptions(n)));return t}toClaudeCodeToolName(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}fromClaudeCodeToolName(e){return e.replace(/["\s/>]+$/g,"").trim().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(s=>this.stripSchemaDescriptions(s));let t={...e};if(delete t.description,t.properties&&typeof t.properties=="object"){let s={};for(let[n,o]of Object.entries(t.properties))s[n]=this.stripSchemaDescriptions(o);t.properties=s;}for(let s of ["items","oneOf","anyOf","allOf"])t[s]&&(t[s]=Array.isArray(t[s])?t[s].map(n=>this.stripSchemaDescriptions(n)):this.stripSchemaDescriptions(t[s]));return t}buildHeaders(){return this.isProxyMode?this.buildClaudeCodeHeaders():this.buildOfficialHeaders()}buildOfficialHeaders(){return {"anthropic-api-key":this.authToken,"anthropic-version":Kr,"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":Kr,"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 s=randomBytes(32).toString("hex"),n=this.generateUUID();return `user_${s}_account__session_${n}`}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"),s=this.generateUUID();return `user_${t}_account__session_${s}`}if(/^\+?[\d\s-]{10,}$/.test(e)){let t=createHash("sha256").update(e).digest("hex"),s=this.generateUUID();return `user_${t}_account__session_${s}`}return e}return e.length>Vr?createHash("sha256").update(e).digest("hex").slice(0,Vr):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Vr):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Vr):e}async normalizeAxiosStreamError(e){let t=e?.response?.data;if(!(!t||typeof t!="object"||!(typeof t.pipe=="function")))try{let n=await this.readStreamToString(t);try{e.response.data=JSON.parse(n);}catch{e.response.data=n;}}catch{}}readStreamToString(e){return new Promise((t,s)=>{let n=[];e.on("data",o=>{n.push(typeof o=="string"?Buffer.from(o):o);}),e.on("end",()=>t(Buffer.concat(n).toString("utf-8"))),e.on("error",s);})}async*createTimeoutStream(e,t){let s=false,n=Date.now(),o=0,i=e[Symbol.asyncIterator](),a=()=>new Promise(l=>setImmediate(l));for(process.env.CLI_DEBUG==="1"&&g.debug("STREAM","\u{1F30A} Stream processing started");;){if(t?.aborted)throw this.debugLog("Stream aborted by signal"),process.env.CLI_DEBUG==="1"&&g.debug("STREAM",`\u26D4 Stream aborted after ${o} chunks`),e.destroy?.(),new Error("Request aborted");await a();let l=s?Jc:Kc,c;try{let u=t?new Promise((m,h)=>{let f=()=>{h(new Error("Request aborted"));};t.aborted?f():t.addEventListener("abort",f,{once:!0});}):null,p=[i.next(),new Promise((m,h)=>{c=setTimeout(()=>{h(new Error(s?`Stream idle timeout: no data for ${Jc/1e3}s`:`Stream first chunk timeout: no response for ${Kc/1e3}s`));},l);})];u&&p.push(u);let d=await Promise.race(p);if(c&&clearTimeout(c),d.done){process.env.CLI_DEBUG==="1"&&g.debug("STREAM",`\u2705 Stream completed successfully (${o} chunks, ${Date.now()-n}ms)`);return}s=!0,n=Date.now(),o++,process.env.CLI_DEBUG==="1"&&o%100===0&&g.debug("STREAM",`\u{1F4E6} Processed ${o} chunks`),yield d.value;}catch(u){c&&clearTimeout(c);let p=u.message?.includes("aborted")||u.message==="Request aborted";throw this.debugLog("Stream timeout or abort",{error:u.message,isAbort:p,receivedFirstChunk:s,idleTime:`${(Date.now()-n)/1e3}s`}),e.destroy?.(),p?(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"&&g.debug("Anthropic",t?`${e} ${JSON.stringify(t,null,2)}`:e);}logRequest(e,t,s=false){process.env.CLI_DEBUG_PAYLOAD==="1"&&this.debugLog("Full payload",JSON.stringify(t,null,2));let n=this.isProxyMode?"/v1/messages?beta=true":"/v1/messages",o=`${this.baseUrl}${n}`,i=this.buildHeaders();go(o,i,t);let a=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":Kr,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":Kr,"Content-Type":"application/json"};te.llmRequest(s?"anthropic-stream":"anthropic",e,t,o,a),this.debugLog(`${s?"Stream ":""}Request`,{url:o,model:e,isProxyMode:this.isProxyMode});}};le();var Yr=class extends ft{constraints;promptBuilder;provider;defaultModel;disableCaching;constructor(e){super(),this.constraints=new Pn,this.promptBuilder=new On,this.defaultModel=e.defaultModel||"claude-3-5-sonnet-20241022",this.disableCaching=e.disableCaching||false;let{authToken:t,baseUrl:s,defaultModel:n,maxTokens:o,disableCaching:i,userId:a,...l}=e;this.provider=new Ls({authToken:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:o,disableCaching:this.disableCaching,userId:a,...l});}prepareRequest(e,t){let s=t.model||this.defaultModel,n=super.prepareRequest(e,{...t,model:s}),o={...n.options};if(o.maxInputTokens!==void 0&&(o.max_tokens=o.maxInputTokens,delete o.maxInputTokens),!o.max_tokens){let i=this.constraints.getTokenLimits(s);o.max_tokens=Math.min(4096,i.maxOutput);}if(!this.disableCaching&&this.constraints.supportsPromptCaching(s)){let i=n.messages[0]?.content?.length||0,a=this.promptBuilder.getCachingRecommendation(i);a.shouldUseCache&&(o.enableCaching=true,o.cacheTtl=a.cacheTTL);}return {...n,options:o}}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("AnthropicAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("AnthropicAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,maxInputTokens:s.options.max_tokens,enableCaching:s.options.enableCaching,cacheTtl:s.options.cacheTtl,signal:t.signal});}getProvider(){return this.provider}getModelCapabilities(e){let t=e||this.defaultModel;return {supportsVision:this.constraints.supportsVision(t),supportsTools:this.constraints.supportsTools(t),supportsThinking:this.constraints.supportsThinking?.(t)||false,supportsPromptCaching:this.constraints.supportsPromptCaching(t),tokenLimits:this.constraints.getTokenLimits(t)}}getCachingRecommendation(e){return this.promptBuilder.getCachingRecommendation(e)}};var Xr=class extends Qt{getConstraints(){let e=super.getConstraints(),t={...e.validators??{}};t.temperature=Fe(0,1);let s=t.tool_choice;t.tool_choice=o=>o==="required"?"tool_choice=required is not supported by Kimi API":typeof s=="function"?s(o):true;let n=t.n;return t.n=(o,i)=>{let a=typeof n=="function"?n(o,i):true;if(a!==true)return a;let l=i?.temperature??1,c=typeof l=="number"?l:Number(l),u=typeof o=="number"?o:Number(o);return !Number.isNaN(c)&&c<=.001&&u>1?"temperature <= 0.001 requires n=1 for Kimi API":true},{...e,validators:t}}};le();var Zr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Xr,this.promptBuilder=new ts,this.defaultModel=e.defaultModel||"kimi-k2-0905-preview";let{apiKey:t,baseUrl:s,defaultModel:n,maxTokens:o,maxInputTokens:i,...a}=e;this.provider=new Ct({apiKey:t,baseUrl:s,defaultModel:this.defaultModel,maxTokens:o,maxInputTokens:i,...a,structuredOutputMode:"json_object"});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("KimiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("KimiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,signal:t.signal});}getProvider(){return this.provider}};var Qr=class extends Ft{getConstraints(){return {maxOutputTokens:{},maxInputTokens:{},supportedParams:new Set(["model","messages","stream","max_tokens","temperature","topP","topK","stopSequences","tools","structuredOutput","signal"]),validators:{temperature:Fe(0,2),topP:Fe(0,1),topK:Fe(1,128),max_tokens:e=>{let t=Number(e);return Number.isNaN(t)?"Must be a number":t<1?"Must be at least 1":true},stopSequences:e=>Array.isArray(e)?e.some(s=>typeof s!="string"||s.length===0)?"All stop sequences must be non-empty strings":true:"Must be an array of strings",stream:Bc("boolean")},defaults:{temperature:1}}}};var $n=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",modelName:n,customInstructions:o}=e,i=[];return i.push({content:this.getCoreInstructions(s,n),order:0}),i.push(this.getWorkingDirectorySection(t,s)),i.push({content:this.getCapabilitiesSection(s,n),order:20}),i.push({title:s==="zh"?"\u53C2\u6570\u7EA6\u675F":"Parameter Constraints",content:this.getConstraintInstructions(s),order:30}),i.push({title:s==="zh"?"\u5DE5\u5177\u8C03\u7528":"Tool Usage",content:this.getToolUseInstructions(s),order:40}),i.push({content:this.getGeneralRules(s),order:50}),o&&o.trim()&&i.push({title:s==="zh"?"\u81EA\u5B9A\u4E49\u6307\u4EE4":"Custom Instructions",content:o.trim(),order:60}),es(this.combinePromptSections(i))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1649
1649
  - topP: 0.0 - 1.0
1650
1650
  - topK: >= 1
1651
1651
  - maxOutputTokens: \u63A7\u5236\u8F93\u51FA\u957F\u5EA6
@@ -1669,12 +1669,12 @@ Your primary responsibilities:
1669
1669
  - Code generation and modification
1670
1670
  - Debugging and problem-solving
1671
1671
  - Technical consulting and advice
1672
- - File operations and project management`}getCapabilitiesSection(e,t){let s=this.supportsVision(t);if(e==="zh"){let i=`# \u4F60\u7684\u80FD\u529B
1672
+ - File operations and project management`}getCapabilitiesSection(e,t){let s=this.supportsVision(t);if(e==="zh"){let o=`# \u4F60\u7684\u80FD\u529B
1673
1673
 
1674
1674
  - **\u4EE3\u7801\u7406\u89E3**: \u9605\u8BFB\u548C\u5206\u6790\u4EE3\u7801\uFF0C\u63D0\u4F9B\u4F18\u5316\u5EFA\u8BAE
1675
1675
  - **\u4EE3\u7801\u751F\u6210**: \u6839\u636E\u9700\u6C42\u751F\u6210\u9AD8\u8D28\u91CF\u4EE3\u7801
1676
- - **\u5DE5\u5177\u8C03\u7528**: \u6267\u884C\u6587\u4EF6\u64CD\u4F5C\u3001\u8FD0\u884C\u547D\u4EE4\u7B49`;return s&&(i+=`
1677
- - **\u89C6\u89C9\u7406\u89E3**: \u5206\u6790\u56FE\u7247\u3001\u622A\u56FE\u3001\u56FE\u8868\u7B49\u89C6\u89C9\u5185\u5BB9`),i}let n=`# Capabilities
1676
+ - **\u5DE5\u5177\u8C03\u7528**: \u6267\u884C\u6587\u4EF6\u64CD\u4F5C\u3001\u8FD0\u884C\u547D\u4EE4\u7B49`;return s&&(o+=`
1677
+ - **\u89C6\u89C9\u7406\u89E3**: \u5206\u6790\u56FE\u7247\u3001\u622A\u56FE\u3001\u56FE\u8868\u7B49\u89C6\u89C9\u5185\u5BB9`),o}let n=`# Capabilities
1678
1678
 
1679
1679
  - **Code understanding**: analyze code and propose improvements
1680
1680
  - **Code generation**: produce high-quality code from requirements
@@ -1689,24 +1689,24 @@ Your primary responsibilities:
1689
1689
  1. **Accuracy first**: ensure correctness
1690
1690
  2. **Be concise**: avoid redundancy
1691
1691
  3. **Safety first**: avoid destructive actions
1692
- 4. **Professional tone**: objective and technical`}getModelDisplayName(e){return e?e.includes("gemini-3")?"Gemini 3":e.includes("gemini-2.5")?"Gemini 2.5":e.includes("gemini-2.0")?"Gemini 2.0":e.includes("gemini-1.5")?"Gemini 1.5":e.includes("gemini-1.0")?"Gemini 1.0":e:"Gemini"}supportsVision(e){return e?e.includes("vision")?true:this.isModelType(e,"gemini-1.5*","gemini-2*","gemini-3*"):false}};le();function zg(r){let e="/v1beta/models";if(!r)return e;let t=r.trim();if(!t)return e;let s=t.startsWith("/")?t:`/${t}`;return s=s.replace(/\/+$/,""),s.includes("/models")||(s=`${s}/models`),s}function Jg(r){try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function Kc(r){if(r==null)return "{}";if(typeof r=="string"){let e=r.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(r)}catch{return "{}"}}var Kg="skip_thought_signature_validator",Vc=8192;function Yc(r){return r.includes("gemini-3")||r.includes("preview")}function Vg(r){let e=-1;for(let s=r.length-1;s>=0;s--){let n=r[s];if(n.role==="user"&&n.parts?.some(i=>i.text)){e=s;break}}if(e===-1)return r;let t=r.slice();for(let s=e;s<t.length;s++){let n=t[s];if(n.role==="model"&&n.parts){let i=n.parts.slice();for(let o=0;o<i.length;o++){let a=i[o];if(a.functionCall){a.thoughtSignature||(i[o]={...a,thoughtSignature:Kg},t[s]={...n,parts:i});break}}}}return t}var Ls=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",s,n){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=zg(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=Lt(Cs("gemini"),s);let i={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${Us.platform()}; ${Us.arch()})`,"x-goog-api-client":"google-genai-sdk/1.30.0 gl-node/v22.16.0","x-gemini-api-privileged-user-id":this.userId};this.authMode==="header"?i["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(i.Authorization=`Bearer ${this.apiKey}`),this.client=Pg.create({baseURL:this.baseURL,timeout:6e5,headers:i});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),s=this.apiKey.startsWith("AIza");return t||s?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&ue("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),s=[],n=[],i=[],o=()=>{i.length>0&&(n.push({parts:i,role:"user"}),i=[]);};for(let l of t)if(l.role==="system"){let c=ee(l.content);c&&s.push(c);}else if(l.role==="user"){o();let c=[];if(typeof l.content=="string")c.push({text:l.content});else if(Array.isArray(l.content)){for(let u of l.content)if(u.type==="text")c.push({text:u.text});else if(u.type==="image_url"){let p=u.image_url.url;if(p.startsWith("data:")){let d=p.match(/^data:([^;]+);base64,(.+)$/);d&&c.push({inlineData:{mimeType:d[1],data:d[2]}});}}}n.push({parts:c,role:"user"});}else if(l.role==="assistant"){o();let c=[],u=ee(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let p of l.tool_calls){let d={functionCall:{name:p.function.name,args:Jg(p.function.arguments),id:p.id}};p.thoughtSignature&&(d.thoughtSignature=p.thoughtSignature),c.push(d);}n.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=ee(l.content)||"",p={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(p.id=l.tool_call_id),i.push({functionResponse:p});}o();let a={contents:n};return s.length>0&&(a.systemInstruction={parts:s.map(l=>({text:l})),role:"user"}),a}filterIncompleteToolCalls(e){let t=[],s=0;for(;s<e.length;){let n=e[s];if(n.role==="system"){t.push(n),s++;continue}if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let i=n.tool_calls,o=i.length,a=i.every(h=>!!h.id),l=[],c=[],u=s+1;for(;u<e.length;){let h=e[u];if(h.role==="system"){l.push(h),u++;continue}if(h.role!=="tool")break;l.push(h),c.push(h),u++;}let p=c.length,d=c.every(h=>!!h.tool_call_id),m=p===o;if(m&&a&&d){let h=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of i)if(!h.has(f.id)){m=false;break}}if(m){t.push(n);for(let h of l)t.push(h);}else {process.env.CLI_DEBUG==="1"&&g.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:i.map(h=>({id:h.id,name:h.function.name})),responseCount:p});for(let h of l)h.role==="system"&&t.push(h);}s=u;continue}if(n.role==="tool"){process.env.CLI_DEBUG==="1"&&g.debug("GEMINI","Dropping orphan tool message",{toolCallId:n.tool_call_id,toolName:n.name}),s++;continue}t.push(n),s++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(s=>({name:s.name,description:s.description,parameters:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties},parametersJsonSchema:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties}}))}]}buildGenerationConfig(e){let t={temperature:e.temperature??1,topP:e.topP??.95,topK:e.topK??64};return e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.stopSequences&&e.stopSequences.length>0&&(t.stopSequences=e.stopSequences),e.structuredOutput&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema),e.enableThinking&&(t.thinkingConfig={thinkingBudget:e.thinkingBudget??Vc,includeThoughts:true}),t}parseSSELine(e){let t=e.trim();if(!t||(t.startsWith("data:")&&(t=t.slice(5).trim()),t==="[DONE]")||!t.startsWith("{"))return null;try{return JSON.parse(t)}catch{return null}}convertResponse(e,t){let s=e.candidates[0];if(!s)throw new Error("No candidate in Gemini response");let n=s.content?.parts||[],i=null,o=[];for(let c of n)c.text?i=(i||"")+c.text:c.functionCall&&o.push({id:c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:c.functionCall.name,arguments:Kc(c.functionCall.args)}});let a=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=s.finishReason==="STOP"?o.length>0?"tool_calls":"stop":(s.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:i,tool_calls:o.length>0?o:void 0},finish_reason:l}],usage:{prompt_tokens:a.promptTokenCount,completion_tokens:a.candidatesTokenCount,total_tokens:a.totalTokenCount,cached_tokens:a.cachedContentTokenCount}}}async makeRequest(e,t){let s,n=0;for(;n<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(i){s=i,n++;let o=tt(i),a=St(i.response?.headers?.["retry-after"]);if(!o.retryable||n>this.retryConfig.requestMaxRetries)break;let l=Dt(a,n,this.retryConfig);await Is(l);}throw s}async chat(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:i}=this.convertMessages(e),o=this.convertTools(t.tools||[]),a=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:n,systemInstruction:i,generationConfig:a};o.length>0&&(l.tools=o);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${s}:generateContent`,p=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let d=await this.client.post(u,l,{params:p,signal:t.signal});return this.convertResponse(d.data,c)},"chat")}async*chatStreamed(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:i}=this.convertMessages(e),o=this.convertTools(t.tools||[]),a=Yc(s),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:a,p=t.thinkingBudget??this.thinkingSettings?.budget??Vc,d=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:p}),h={contents:Yc(s)?Vg(n):n,systemInstruction:i,generationConfig:d};o.length>0&&(h.tools=o);let f=`gemini-${Date.now()}`,y=`${this.pathPrefix}/${s}:streamGenerateContent`,b=`${this.baseURL}${y}`,_=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},v=new URL(b);for(let[W,F]of Object.entries(_))v.searchParams.append(W,F);let k={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?k["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(k.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){g.info("GEMINI","=== Gemini Stream Request ==="),g.info("GEMINI",`URL: ${v.toString()}`),g.info("GEMINI",`Model: ${s}`),g.info("GEMINI",`AuthMode: ${this.authMode}`),g.info("GEMINI",`Tools: ${o.length>0?o[0].functionDeclarations.length:0}`),g.info("GEMINI",`Contents: ${n.length} messages`);let W=yt(v.toString(),k,h);g.info("GEMINI_CURL",W),g.debug("GEMINI","Request body:",{contentsCount:h.contents.length,hasSystemInstruction:!!h.systemInstruction,toolsCount:h.tools?.[0]?.functionDeclarations?.length||0,generationConfig:h.generationConfig});}if(process.env.CLI_DEBUG==="1"){ue("GEMINI","[Gemini Stream Request]"),ue("GEMINI",`URL: ${v.toString()}`),ue("GEMINI",`Model: ${s}`),ue("GEMINI",`Tools: ${o.length>0?o[0].functionDeclarations.length:0}`),ue("GEMINI",`Contents: ${n.length} messages`);let W=yt(v.toString(),k,h);ue("GEMINI_CURL",W);}let R=Date.now(),O=await this.makeRequest(async()=>{let W=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(y,h,{params:W,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(ue("GEMINI","[Gemini Stream Started]"),ue("GEMINI",`Status: ${O.status}`)),yield*this.streamGenerator(O.data,f,R);}async*streamGenerator(e,t,s){let n="",i=[],o="",a=[],l,c=u=>{let p=[],d=u.candidates?.[0];if(!d)return process.env.CLI_DEBUG==="1"&&ue("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),p;u.usageMetadata&&(l=u.usageMetadata);let m=d.content?.parts;if(!m||m.length===0)process.env.CLI_DEBUG==="1"&&ue("GEMINI",`No parts in candidate: ${JSON.stringify(d).slice(0,200)}`);else for(let h of m){if(h.thought&&!h.thoughtSignature&&h.text){process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Yielding reasoning: ${h.text.slice(0,50)}...`),p.push({choices:[{index:0,delta:{reasoning_content:h.text}}]});continue}if(h.text)h.thoughtSignature&&process.env.CLI_DEBUG==="1"?ue("GEMINI",`Yielding final answer (with signature): ${h.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Yielding content: ${h.text.slice(0,100)}...`),o+=h.text,p.push({choices:[{index:0,delta:{content:h.text}}]});else if(h.functionCall){let f={id:h.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:h.functionCall.name,arguments:Kc(h.functionCall.args)},...h.thoughtSignature?{thoughtSignature:h.thoughtSignature}:{}};a.push(f),p.push({choices:[{index:0,delta:{tool_calls:[{index:a.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(d.finishReason){let h=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let y=s?Date.now()-s:0;g.info("GEMINI","=== Gemini Stream Complete ==="),g.info("GEMINI",`Duration: ${y}ms`),g.info("GEMINI",`Finish Reason: ${d.finishReason}`),g.info("GEMINI",`Tool Calls: ${a.length}`),g.info("GEMINI",`Accumulated Content Length: ${o.length}`),g.info("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),o&&g.info("GEMINI",`Content Preview: ${o.slice(0,500)}...`),a.length>0&&g.info("GEMINI","Tool Calls Detail:",a.map(b=>({id:b.id,name:b.function.name,argsLength:b.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let y=s?Date.now()-s:0;ue("GEMINI","[Gemini Stream Complete]"),ue("GEMINI",`Duration: ${y}ms`),ue("GEMINI",`Finish Reason: ${d.finishReason}`),ue("GEMINI",`Tool Calls: ${a.length}`),ue("GEMINI",`Accumulated Content Length: ${o.length}`),ue("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),o&&ue("GEMINI",`Content Preview: ${o.slice(0,500)}`);}let f=d.finishReason==="STOP"?a.length>0?"tool_calls":"stop":d.finishReason.toLowerCase();p.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:h.promptTokenCount,completion_tokens:h.candidatesTokenCount,total_tokens:h.totalTokenCount,cached_tokens:h.cachedContentTokenCount}});}return p};try{for await(let u of e){let p=u.toString();n+=p,process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Raw chunk (${p.length} bytes): ${p.slice(0,200)}...`);let d=n.split(/\r?\n/);n=d.pop()||"";for(let m of d){let h=m.trimEnd();if(!h){if(i.length===0)continue;let y=i.join(`
1693
- `);i=[];let b=this.parseSSELine(y);if(!b){process.env.CLI_DEBUG==="1"&&y.length>0&&ue("GEMINI",`Failed to parse event: ${y.slice(0,100)}...`);continue}for(let _ of c(b))yield _;continue}if(h.startsWith("data:")){i.push(h.slice(5).trimStart());continue}let f=this.parseSSELine(h);if(!f){process.env.CLI_DEBUG==="1"&&h.length>0&&ue("GEMINI",`Failed to parse line: ${h.slice(0,100)}...`);continue}for(let y of c(f))yield y;}}if(i.length>0){let u=this.parseSSELine(i.join(`
1694
- `));if(u)for(let p of c(u))yield p;}}catch(u){if(process.env.CLI_DEBUG==="1"){let p=s?Date.now()-s:0;ue("GEMINI","[Gemini Stream Error]"),ue("GEMINI",`Duration: ${p}ms`),ue("GEMINI",`Error: ${u.message||u}`),u.response?.data&&ue("GEMINI",`Response: ${JSON.stringify(u.response.data)}`);}throw u}}};le();var Qr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Zr,this.promptBuilder=new Dn,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:s,urlSuffix:n,retry:i}=e;this.provider=new Ls(t,s,i,{pathPrefix:n});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("GeminiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("GeminiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences,signal:t.signal});}getProvider(){return this.provider}};var Ds=class r{static createAdapter(e,t){switch(e){case "openai":return r.createOpenAIAdapter(t,false);case "openai-responses":return r.createOpenAIAdapter(t,true);case "kimi":return r.createKimiAdapter(t);case "anthropic":case "anthropic-openai":return r.createAnthropicAdapter(t);case "doubao":throw new Error("Doubao adapter not yet implemented. Use Phase 5.");case "gemini":return r.createGeminiAdapter(t);default:throw new Error(`Unsupported provider protocol: ${e}`)}}static createOpenAIAdapter(e,t){let s={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,useResponsesAPI:t,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new qr(s)}static createAnthropicAdapter(e){let t={authToken:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens&&e.maxTokens<=8192?e.maxTokens:void 0,disableCaching:false};return new Vr(t)}static createKimiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new Xr(t)}static createGeminiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,urlSuffix:e.urlSuffix,defaultModel:e.defaultModel||e.lastSelectedModel,retry:e.retry};return new Qr(t)}static isProtocolSupported(e){return ["openai","openai-responses","anthropic","anthropic-openai","kimi","gemini"].includes(e)}static getProtocolDisplayName(e){return {openai:"OpenAI (Chat Completions)","openai-responses":"OpenAI (Responses API)",anthropic:"Anthropic (Claude)","anthropic-openai":"Anthropic (OpenAI Format)",doubao:"\u8C46\u5305 (Doubao)",gemini:"Google Gemini",kimi:"Kimi (Moonshot)"}[e]||e}};var Xg=16e3;function Zg(r,e=Xg){if(!r||r.length<=e)return r;let t=r.split(`
1695
- `).length,s=r.length,n=Math.floor(e*.4),i=Math.floor(e*.4),o=n,a=r.length-i;for(;o>0&&(r.charCodeAt(o)&192)===128;)o--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,o),c=r.slice(a),p=`
1692
+ 4. **Professional tone**: objective and technical`}getModelDisplayName(e){return e?e.includes("gemini-3")?"Gemini 3":e.includes("gemini-2.5")?"Gemini 2.5":e.includes("gemini-2.0")?"Gemini 2.0":e.includes("gemini-1.5")?"Gemini 1.5":e.includes("gemini-1.0")?"Gemini 1.0":e:"Gemini"}supportsVision(e){return e?e.includes("vision")?true:this.isModelType(e,"gemini-1.5*","gemini-2*","gemini-3*"):false}};le();function Vg(r){let e="/v1beta/models";if(!r)return e;let t=r.trim();if(!t)return e;let s=t.startsWith("/")?t:`/${t}`;return s=s.replace(/\/+$/,""),s.includes("/models")||(s=`${s}/models`),s}function Yg(r){try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function Xc(r){if(r==null)return "{}";if(typeof r=="string"){let e=r.trim();return e?e.startsWith("{")||e.startsWith("[")?e:JSON.stringify({value:e}):"{}"}try{return JSON.stringify(r)}catch{return "{}"}}var Xg="skip_thought_signature_validator",Zc=8192;function Qc(r){return r.includes("gemini-3")||r.includes("preview")}function Zg(r){let e=-1;for(let s=r.length-1;s>=0;s--){let n=r[s];if(n.role==="user"&&n.parts?.some(o=>o.text)){e=s;break}}if(e===-1)return r;let t=r.slice();for(let s=e;s<t.length;s++){let n=t[s];if(n.role==="model"&&n.parts){let o=n.parts.slice();for(let i=0;i<o.length;i++){let a=o[i];if(a.functionCall){a.thoughtSignature||(o[i]={...a,thoughtSignature:Xg},t[s]={...n,parts:o});break}}}}return t}var Ds=class{client;apiKey;baseURL;pathPrefix;userId;retryConfig;authMode;thinkingSettings=null;constructor(e,t="https://generativelanguage.googleapis.com",s,n){this.apiKey=e,this.baseURL=t.replace(/\/$/,""),this.pathPrefix=Vg(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=Lt(Rs("gemini"),s);let o={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${js.platform()}; ${js.arch()})`,"x-goog-api-client":"google-genai-sdk/1.30.0 gl-node/v22.16.0","x-gemini-api-privileged-user-id":this.userId};this.authMode==="header"?o["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(o.Authorization=`Bearer ${this.apiKey}`),this.client=Dg.create({baseURL:this.baseURL,timeout:6e5,headers:o});}resolveAuthMode(e){if(e&&e!=="auto")return e;let t=this.baseURL.includes("generativelanguage.googleapis.com"),s=this.apiKey.startsWith("AIza");return t||s?"query":"bearer"}setThinking(e){this.thinkingSettings=e,process.env.CLI_DEBUG==="1"&&ue("GEMINI","Thinking config updated",{config:e});}getThinking(){return this.thinkingSettings}convertMessages(e){let t=this.filterIncompleteToolCalls(e),s=[],n=[],o=[],i=()=>{o.length>0&&(n.push({parts:o,role:"user"}),o=[]);};for(let l of t)if(l.role==="system"){let c=ee(l.content);c&&s.push(c);}else if(l.role==="user"){i();let c=[];if(typeof l.content=="string")c.push({text:l.content});else if(Array.isArray(l.content)){for(let u of l.content)if(u.type==="text")c.push({text:u.text});else if(u.type==="image_url"){let p=u.image_url.url;if(p.startsWith("data:")){let d=p.match(/^data:([^;]+);base64,(.+)$/);d&&c.push({inlineData:{mimeType:d[1],data:d[2]}});}}}n.push({parts:c,role:"user"});}else if(l.role==="assistant"){i();let c=[],u=ee(l.content);if(u&&c.push({text:u}),l.tool_calls)for(let p of l.tool_calls){let d={functionCall:{name:p.function.name,args:Yg(p.function.arguments),id:p.id}};p.thoughtSignature&&(d.thoughtSignature=p.thoughtSignature),c.push(d);}n.push({parts:c,role:"model"});}else if(l.role==="tool"){let c=ee(l.content)||"",p={name:l.name||"unknown",response:{output:c}};l.tool_call_id&&(p.id=l.tool_call_id),o.push({functionResponse:p});}i();let a={contents:n};return s.length>0&&(a.systemInstruction={parts:s.map(l=>({text:l})),role:"user"}),a}filterIncompleteToolCalls(e){let t=[],s=0;for(;s<e.length;){let n=e[s];if(n.role==="system"){t.push(n),s++;continue}if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let o=n.tool_calls,i=o.length,a=o.every(h=>!!h.id),l=[],c=[],u=s+1;for(;u<e.length;){let h=e[u];if(h.role==="system"){l.push(h),u++;continue}if(h.role!=="tool")break;l.push(h),c.push(h),u++;}let p=c.length,d=c.every(h=>!!h.tool_call_id),m=p===i;if(m&&a&&d){let h=new Set(c.map(f=>f.tool_call_id).filter(f=>!!f));for(let f of o)if(!h.has(f.id)){m=false;break}}if(m){t.push(n);for(let h of l)t.push(h);}else {process.env.CLI_DEBUG==="1"&&g.debug("GEMINI","Filtering incomplete tool call turn",{toolCalls:o.map(h=>({id:h.id,name:h.function.name})),responseCount:p});for(let h of l)h.role==="system"&&t.push(h);}s=u;continue}if(n.role==="tool"){process.env.CLI_DEBUG==="1"&&g.debug("GEMINI","Dropping orphan tool message",{toolCallId:n.tool_call_id,toolName:n.name}),s++;continue}t.push(n),s++;}return t}convertTools(e){return !e||e.length===0?[]:[{functionDeclarations:e.map(s=>({name:s.name,description:s.description,parameters:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties},parametersJsonSchema:{type:s.parameters.type,properties:s.parameters.properties,required:s.parameters.required,additionalProperties:s.parameters.additionalProperties}}))}]}buildGenerationConfig(e){let t={temperature:e.temperature??1,topP:e.topP??.95,topK:e.topK??64};return e.maxOutputTokens!==void 0&&(t.maxOutputTokens=e.maxOutputTokens),e.stopSequences&&e.stopSequences.length>0&&(t.stopSequences=e.stopSequences),e.structuredOutput&&(t.responseMimeType="application/json",t.responseSchema=e.structuredOutput.schema),e.enableThinking&&(t.thinkingConfig={thinkingBudget:e.thinkingBudget??Zc,includeThoughts:true}),t}parseSSELine(e){let t=e.trim();if(!t||(t.startsWith("data:")&&(t=t.slice(5).trim()),t==="[DONE]")||!t.startsWith("{"))return null;try{return JSON.parse(t)}catch{return null}}convertResponse(e,t){let s=e.candidates[0];if(!s)throw new Error("No candidate in Gemini response");let n=s.content?.parts||[],o=null,i=[];for(let c of n)c.text?o=(o||"")+c.text:c.functionCall&&i.push({id:c.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:c.functionCall.name,arguments:Xc(c.functionCall.args)}});let a=e.usageMetadata||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0},l=s.finishReason==="STOP"?i.length>0?"tool_calls":"stop":(s.finishReason||"stop").toLowerCase();return {id:t,choices:[{message:{role:"assistant",content:o,tool_calls:i.length>0?i:void 0},finish_reason:l}],usage:{prompt_tokens:a.promptTokenCount,completion_tokens:a.candidatesTokenCount,total_tokens:a.totalTokenCount,cached_tokens:a.cachedContentTokenCount}}}async makeRequest(e,t){let s,n=0;for(;n<=this.retryConfig.requestMaxRetries;)try{return await e()}catch(o){s=o,n++;let i=tt(o),a=St(o.response?.headers?.["retry-after"]);if(!i.retryable||n>this.retryConfig.requestMaxRetries)break;let l=Dt(a,n,this.retryConfig);await Ms(l);}throw s}async chat(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens}),l={contents:n,systemInstruction:o,generationConfig:a};i.length>0&&(l.tools=i);let c=`gemini-${Date.now()}`,u=`${this.pathPrefix}/${s}:generateContent`,p=this.authMode==="query"?{key:this.apiKey}:void 0;return this.makeRequest(async()=>{let d=await this.client.post(u,l,{params:p,signal:t.signal});return this.convertResponse(d.data,c)},"chat")}async*chatStreamed(e,t){let s=t.model||"gemini-2.5-flash",{contents:n,systemInstruction:o}=this.convertMessages(e),i=this.convertTools(t.tools||[]),a=Qc(s),l=this.thinkingSettings?.type==="enabled",c=this.thinkingSettings?.type==="disabled",u=t.enableThinking!==void 0?t.enableThinking:l?true:c?false:a,p=t.thinkingBudget??this.thinkingSettings?.budget??Zc,d=this.buildGenerationConfig({temperature:t.temperature,structuredOutput:t.structuredOutput,topP:t.topP,topK:t.topK,stopSequences:t.stopSequences,maxOutputTokens:t.maxInputTokens,enableThinking:u,thinkingBudget:p}),h={contents:Qc(s)?Zg(n):n,systemInstruction:o,generationConfig:d};i.length>0&&(h.tools=i);let f=`gemini-${Date.now()}`,y=`${this.pathPrefix}/${s}:streamGenerateContent`,b=`${this.baseURL}${y}`,_=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"},v=new URL(b);for(let[W,F]of Object.entries(_))v.searchParams.append(W,F);let k={"Content-Type":"application/json",Accept:"*/*"};if(this.authMode==="header"?k["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(k.Authorization=`Bearer ${this.apiKey}`),process.env.CLI_DEBUG==="1"){g.info("GEMINI","=== Gemini Stream Request ==="),g.info("GEMINI",`URL: ${v.toString()}`),g.info("GEMINI",`Model: ${s}`),g.info("GEMINI",`AuthMode: ${this.authMode}`),g.info("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),g.info("GEMINI",`Contents: ${n.length} messages`);let W=yt(v.toString(),k,h);g.info("GEMINI_CURL",W),g.debug("GEMINI","Request body:",{contentsCount:h.contents.length,hasSystemInstruction:!!h.systemInstruction,toolsCount:h.tools?.[0]?.functionDeclarations?.length||0,generationConfig:h.generationConfig});}if(process.env.CLI_DEBUG==="1"){ue("GEMINI","[Gemini Stream Request]"),ue("GEMINI",`URL: ${v.toString()}`),ue("GEMINI",`Model: ${s}`),ue("GEMINI",`Tools: ${i.length>0?i[0].functionDeclarations.length:0}`),ue("GEMINI",`Contents: ${n.length} messages`);let W=yt(v.toString(),k,h);ue("GEMINI_CURL",W);}let R=Date.now(),O=await this.makeRequest(async()=>{let W=this.authMode==="query"?{key:this.apiKey,alt:"sse"}:{alt:"sse"};return await this.client.post(y,h,{params:W,responseType:"stream",signal:t.signal,headers:{Accept:"*/*","Accept-Language":"*","sec-fetch-mode":"cors","Accept-Encoding":"br, gzip, deflate"}})},"chatStreamed");process.env.CLI_DEBUG==="1"&&(ue("GEMINI","[Gemini Stream Started]"),ue("GEMINI",`Status: ${O.status}`)),yield*this.streamGenerator(O.data,f,R);}async*streamGenerator(e,t,s){let n="",o=[],i="",a=[],l,c=u=>{let p=[],d=u.candidates?.[0];if(!d)return process.env.CLI_DEBUG==="1"&&ue("GEMINI",`No candidate in response: ${JSON.stringify(u).slice(0,200)}`),p;u.usageMetadata&&(l=u.usageMetadata);let m=d.content?.parts;if(!m||m.length===0)process.env.CLI_DEBUG==="1"&&ue("GEMINI",`No parts in candidate: ${JSON.stringify(d).slice(0,200)}`);else for(let h of m){if(h.thought&&!h.thoughtSignature&&h.text){process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Yielding reasoning: ${h.text.slice(0,50)}...`),p.push({choices:[{index:0,delta:{reasoning_content:h.text}}]});continue}if(h.text)h.thoughtSignature&&process.env.CLI_DEBUG==="1"?ue("GEMINI",`Yielding final answer (with signature): ${h.text.slice(0,100)}...`):process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Yielding content: ${h.text.slice(0,100)}...`),i+=h.text,p.push({choices:[{index:0,delta:{content:h.text}}]});else if(h.functionCall){let f={id:h.functionCall.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:"function",function:{name:h.functionCall.name,arguments:Xc(h.functionCall.args)},...h.thoughtSignature?{thoughtSignature:h.thoughtSignature}:{}};a.push(f),p.push({choices:[{index:0,delta:{tool_calls:[{index:a.length-1,id:f.id,type:"function",function:{name:f.function.name,arguments:f.function.arguments},...f.thoughtSignature?{thoughtSignature:f.thoughtSignature}:{}}]}}]});}}if(d.finishReason){let h=l||{promptTokenCount:0,candidatesTokenCount:0,totalTokenCount:0};if(process.env.CLI_DEBUG==="1"){let y=s?Date.now()-s:0;g.info("GEMINI","=== Gemini Stream Complete ==="),g.info("GEMINI",`Duration: ${y}ms`),g.info("GEMINI",`Finish Reason: ${d.finishReason}`),g.info("GEMINI",`Tool Calls: ${a.length}`),g.info("GEMINI",`Accumulated Content Length: ${i.length}`),g.info("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&g.info("GEMINI",`Content Preview: ${i.slice(0,500)}...`),a.length>0&&g.info("GEMINI","Tool Calls Detail:",a.map(b=>({id:b.id,name:b.function.name,argsLength:b.function.arguments.length})));}if(process.env.CLI_DEBUG==="1"){let y=s?Date.now()-s:0;ue("GEMINI","[Gemini Stream Complete]"),ue("GEMINI",`Duration: ${y}ms`),ue("GEMINI",`Finish Reason: ${d.finishReason}`),ue("GEMINI",`Tool Calls: ${a.length}`),ue("GEMINI",`Accumulated Content Length: ${i.length}`),ue("GEMINI",`Usage: prompt=${h.promptTokenCount}, completion=${h.candidatesTokenCount}, total=${h.totalTokenCount}`),i&&ue("GEMINI",`Content Preview: ${i.slice(0,500)}`);}let f=d.finishReason==="STOP"?a.length>0?"tool_calls":"stop":d.finishReason.toLowerCase();p.push({id:t,choices:[{index:0,delta:{},finish_reason:f}],usage:{prompt_tokens:h.promptTokenCount,completion_tokens:h.candidatesTokenCount,total_tokens:h.totalTokenCount,cached_tokens:h.cachedContentTokenCount}});}return p};try{for await(let u of e){let p=u.toString();n+=p,process.env.CLI_DEBUG==="1"&&ue("GEMINI",`Raw chunk (${p.length} bytes): ${p.slice(0,200)}...`);let d=n.split(/\r?\n/);n=d.pop()||"";for(let m of d){let h=m.trimEnd();if(!h){if(o.length===0)continue;let y=o.join(`
1693
+ `);o=[];let b=this.parseSSELine(y);if(!b){process.env.CLI_DEBUG==="1"&&y.length>0&&ue("GEMINI",`Failed to parse event: ${y.slice(0,100)}...`);continue}for(let _ of c(b))yield _;continue}if(h.startsWith("data:")){o.push(h.slice(5).trimStart());continue}let f=this.parseSSELine(h);if(!f){process.env.CLI_DEBUG==="1"&&h.length>0&&ue("GEMINI",`Failed to parse line: ${h.slice(0,100)}...`);continue}for(let y of c(f))yield y;}}if(o.length>0){let u=this.parseSSELine(o.join(`
1694
+ `));if(u)for(let p of c(u))yield p;}}catch(u){if(process.env.CLI_DEBUG==="1"){let p=s?Date.now()-s:0;ue("GEMINI","[Gemini Stream Error]"),ue("GEMINI",`Duration: ${p}ms`),ue("GEMINI",`Error: ${u.message||u}`),u.response?.data&&ue("GEMINI",`Response: ${JSON.stringify(u.response.data)}`);}throw u}}};le();var eo=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Qr,this.promptBuilder=new $n,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:s,urlSuffix:n,retry:o}=e;this.provider=new Ds(t,s,o,{pathPrefix:n});}prepareRequest(e,t){let s=t.model||this.defaultModel;return super.prepareRequest(e,{...t,model:s})}async chat(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}return s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("GeminiAdapter","Warnings",s.validation.warnings),this.provider.chat(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences})}async*chatStreamed(e,t){let s=this.prepareRequest(e,t);if(!s.validation?.valid){let n=s.validation?.errors||[];throw new Error(`Invalid parameters: ${n.join(", ")}`)}s.validation?.warnings&&s.validation.warnings.length>0&&g.warn("GeminiAdapter","Warnings",s.validation.warnings),yield*this.provider.chatStreamed(s.messages,{model:s.options.model,tools:s.options.tools,temperature:s.options.temperature,structuredOutput:s.options.structuredOutput,maxInputTokens:s.options.maxInputTokens,topP:s.options.topP,topK:s.options.topK,stopSequences:s.options.stopSequences,signal:t.signal});}getProvider(){return this.provider}};var $s=class r{static createAdapter(e,t){switch(e){case "openai":return r.createOpenAIAdapter(t,false);case "openai-responses":return r.createOpenAIAdapter(t,true);case "kimi":return r.createKimiAdapter(t);case "anthropic":case "anthropic-openai":return r.createAnthropicAdapter(t);case "doubao":throw new Error("Doubao adapter not yet implemented. Use Phase 5.");case "gemini":return r.createGeminiAdapter(t);default:throw new Error(`Unsupported provider protocol: ${e}`)}}static createOpenAIAdapter(e,t){let s={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,useResponsesAPI:t,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new zr(s)}static createAnthropicAdapter(e){let t={authToken:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens&&e.maxTokens<=8192?e.maxTokens:void 0,disableCaching:false};return new Yr(t)}static createKimiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,defaultModel:e.defaultModel||e.lastSelectedModel,maxTokens:e.maxTokens,maxInputTokens:e.maxInputTokens};return new Zr(t)}static createGeminiAdapter(e){let t={apiKey:e.apiKey,baseUrl:e.baseUrl,urlSuffix:e.urlSuffix,defaultModel:e.defaultModel||e.lastSelectedModel,retry:e.retry};return new eo(t)}static isProtocolSupported(e){return ["openai","openai-responses","anthropic","anthropic-openai","kimi","gemini"].includes(e)}static getProtocolDisplayName(e){return {openai:"OpenAI (Chat Completions)","openai-responses":"OpenAI (Responses API)",anthropic:"Anthropic (Claude)","anthropic-openai":"Anthropic (OpenAI Format)",doubao:"\u8C46\u5305 (Doubao)",gemini:"Google Gemini",kimi:"Kimi (Moonshot)"}[e]||e}};var ef=16e3;function tf(r,e=ef){if(!r||r.length<=e)return r;let t=r.split(`
1695
+ `).length,s=r.length,n=Math.floor(e*.4),o=Math.floor(e*.4),i=n,a=r.length-o;for(;i>0&&(r.charCodeAt(i)&192)===128;)i--;for(;a<r.length&&(r.charCodeAt(a)&192)===128;)a++;let l=r.slice(0,i),c=r.slice(a),p=`
1696
1696
 
1697
1697
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1698
1698
 
1699
- `;return l+p+c}var ei=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=Pg.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:18e4}),this.retryConfig=Lt(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 s="",n="",i=[],o,a;for await(let l of this.chatStreamed(e,t)){let c=l.choices?.[0]?.delta;if(c&&(c.content&&(s+=c.content),c.reasoning_content&&(n+=c.reasoning_content),c.tool_calls))for(let u of c.tool_calls){let p=i.find(d=>d.index===u.index);p?u.function?.arguments&&(p.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:s||null,reasoning_content:n||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:s=this.defaultModel,tools:n,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:s,tools:n,temperature:i,structuredOutput:t.structuredOutput,maxInputTokens:t.maxInputTokens,previousResponseId:l}),u=`${this.baseUrl}/responses`;te.llmRequest("doubao-responses",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1699
+ `;return l+p+c}var to=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=Dg.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:18e4}),this.retryConfig=Lt(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 s="",n="",o=[],i,a;for await(let l of this.chatStreamed(e,t)){let c=l.choices?.[0]?.delta;if(c&&(c.content&&(s+=c.content),c.reasoning_content&&(n+=c.reasoning_content),c.tool_calls))for(let u of c.tool_calls){let p=o.find(d=>d.index===u.index);p?u.function?.arguments&&(p.function.arguments+=u.function.arguments):o.push({id:u.id||`call_${o.length}`,type:"function",function:{name:u.function?.name||"",arguments:u.function?.arguments||""},index:u.index});}l.usage&&(i=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:s||null,reasoning_content:n||void 0,...o.length>0?{tool_calls:o}:{}},finish_reason:o.length>0?"tool_calls":"stop"}],usage:i||{prompt_tokens:0,completion_tokens:0,total_tokens:0}}}async*chatStreamed(e,t={}){let{model:s=this.defaultModel,tools:n,temperature:o=.7,sessionId:i,signal:a}=t,l=t.previousResponseId;!l&&i&&(l=this.sessionResponseIds.get(i)),l||(l=this.lastResponseId||void 0);let c=this.buildPayload(e,{model:s,tools:n,temperature:o,structuredOutput:t.structuredOutput,maxInputTokens:t.maxInputTokens,previousResponseId:l}),u=`${this.baseUrl}/responses`;te.llmRequest("doubao-responses",s,c,u,{Authorization:"Bearer ***"}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1700
1700
  [Doubao Responses API Request]`),console.log("URL:",u),console.log("Payload:",JSON.stringify(c,null,2)));let p=this.retryConfig.streamMaxRetries,d=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(`
1701
1701
  [Doubao Stream Started]`),console.log("Status:",h.status)),h.status!==200){let y="";for await(let b of h.data)y+=b.toString();throw new Error(`Doubao API error: ${h.status} - ${y}`)}yield*this.parseStreamResponse(h.data);let f=Date.now()-m;te.llmResponse("doubao-responses",f,{},{}),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1702
1702
  [Doubao Stream Complete]`),console.log("Duration:",`${f}ms`));return}catch(m){let h="";if(m.response?.data)try{if(typeof m.response.data.on=="function"){let y=[];for await(let _ of m.response.data)y.push(Buffer.from(_));let b=Buffer.concat(y).toString("utf-8");try{let _=JSON.parse(b),v=_.error||{message:_.message,code:_.code,type:_.type};h=JSON.stringify(v,null,2);}catch{h=b;}}else if(typeof m.response.data=="string")h=m.response.data;else if(m.response.data.error){let y=m.response.data.error,b={message:y.message,code:y.code,type:y.type};h=JSON.stringify(b,null,2);}else {let y=m.response.data,b={message:y.message,code:y.code,type:y.type,error:y.error};h=JSON.stringify(b,null,2);}}catch(y){h=`HTTP ${m.response?.status||"unknown"} (\u65E0\u6CD5\u8BFB\u53D6\u54CD\u5E94\u4F53: ${y})`;}let f=tt(m);if(process.env.CLI_DEBUG_CONSOLE==="1"&&(console.log(`
1703
1703
  [Doubao Stream Error]`),console.log("Message:",m.message),console.log("Status:",m.response?.status),console.log("Error Details:",h||"none"),console.log("Retryable:",f.retryable)),h&&(f.message=`${m.message}
1704
- ${h}`),te.llmError("doubao-responses",m),f.retryable&&d<p){d++;let y=m.response?.headers?.["retry-after"],b=St(y),_=Dt(b,d,this.retryConfig);console.log(`[Doubao] Stream failed (${f.code}), reconnecting in ${qe(_)} (${d}/${p})...`),yield {choices:[],type:"stream_retry",error:f.message,errorCode:f.code,attempt:d,maxRetries:p,delayMs:_};try{await Yt(_,t.signal);}catch(v){throw v?.name==="AbortError",v}continue}throw f}}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:s,tools:n,temperature:i,structuredOutput:o,maxInputTokens:a,previousResponseId:l}=t,c=this.convertToDoubaoInput(e,l);this.extractSystemInstructions(e);let p={model:s,input:c,stream:true,temperature:i};return l&&(p.previous_response_id=l),this.thinking&&(p.thinking=this.thinking),this.reasoning&&(p.reasoning=this.reasoning),n&&n.length>0&&(p.tools=n.map(d=>({type:"function",name:d.name,description:d.description,parameters:d.parameters})),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Doubao] Added ${p.tools.length} tools`)),o&&(p.text={format:{type:"json_schema",name:o.name,schema:o.schema}}),p}extractSystemInstructions(e){let t=e.filter(s=>s.role==="system").map(s=>ee(s.content).trim()).filter(s=>s.length>0);return t.length>0?t.join(`
1704
+ ${h}`),te.llmError("doubao-responses",m),f.retryable&&d<p){d++;let y=m.response?.headers?.["retry-after"],b=St(y),_=Dt(b,d,this.retryConfig);console.log(`[Doubao] Stream failed (${f.code}), reconnecting in ${qe(_)} (${d}/${p})...`),yield {choices:[],type:"stream_retry",error:f.message,errorCode:f.code,attempt:d,maxRetries:p,delayMs:_};try{await Xt(_,t.signal);}catch(v){throw v?.name==="AbortError",v}continue}throw f}}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:s,tools:n,temperature:o,structuredOutput:i,maxInputTokens:a,previousResponseId:l}=t,c=this.convertToDoubaoInput(e,l);this.extractSystemInstructions(e);let p={model:s,input:c,stream:true,temperature:o};return l&&(p.previous_response_id=l),this.thinking&&(p.thinking=this.thinking),this.reasoning&&(p.reasoning=this.reasoning),n&&n.length>0&&(p.tools=n.map(d=>({type:"function",name:d.name,description:d.description,parameters:d.parameters})),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log(`[Doubao] Added ${p.tools.length} tools`)),i&&(p.text={format:{type:"json_schema",name:i.name,schema:i.schema}}),p}extractSystemInstructions(e){let t=e.filter(s=>s.role==="system").map(s=>ee(s.content).trim()).filter(s=>s.length>0);return t.length>0?t.join(`
1705
1705
 
1706
- `):void 0}convertToDoubaoInput(e,t){let s=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:ee(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,s)),a=true;else if(c.role==="tool"&&a)o.unshift(...this.convertMessageToInputItems(c,s));else if(a)break}return o}return i.flatMap(o=>this.convertMessageToInputItems(o,s)).filter(o=>o!==null)}convertMessageToInputItems(e,t){if(e.role==="assistant"){let n=[],i=ee(e.content);if(i.trim().length>0&&n.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);n.push({type:"function_call",id:a,call_id:a,name:o.function.name,arguments:o.function.arguments||"",status:"completed"});}return n}if(e.role==="tool"){let n=this.normalizeCallId(e.tool_call_id||e.name,t),i=ee(e.content),o=Zg(i);return [{type:"function_call_output",call_id:n,output:o}]}if(Array.isArray(e.content)){let n=[];for(let i of e.content)i.type==="text"&&i.text.trim()?n.push({type:"input_text",text:i.text}):i.type==="image_url"&&n.push({type:"input_image",image_url:i.image_url.url});return n.length===0?[]:[{type:"message",role:"user",content:n}]}let s=ee(e.content);return !s||s.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:s}]}]}normalizeCallId(e,t){if(e&&t.has(e))return t.get(e);let s;return e?s=e.startsWith("fc_")?e:`fc_${e}`:s=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,s):t.set(s,s),s}async*parseStreamResponse(e){let t="",s=new Map,n=0,i=null,o=null,a=false,l=false,c,u=d=>{let m={...d};return l||(m.role="assistant",l=true),{id:c,choices:[{index:0,delta:m}]}};for await(let d of e){t+=d.toString();let m=t.split(`
1706
+ `):void 0}convertToDoubaoInput(e,t){let s=new Map;if(!e.some(i=>i.role==="tool"||i.role==="assistant"&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0))return e.map(i=>({role:i.role,content:ee(i.content)}));let o=e.filter(i=>i.role!=="system");if(t){let i=[],a=false;for(let l=o.length-1;l>=0;l--){let c=o[l];if(c.role==="user"&&!a)i.unshift(...this.convertMessageToInputItems(c,s)),a=true;else if(c.role==="tool"&&a)i.unshift(...this.convertMessageToInputItems(c,s));else if(a)break}return i}return o.flatMap(i=>this.convertMessageToInputItems(i,s)).filter(i=>i!==null)}convertMessageToInputItems(e,t){if(e.role==="assistant"){let n=[],o=ee(e.content);if(o.trim().length>0&&n.push({type:"message",role:"assistant",status:"completed",content:[{type:"input_text",text:o}]}),Array.isArray(e.tool_calls)&&e.tool_calls.length>0)for(let i of e.tool_calls){let a=this.normalizeCallId(i.id,t);n.push({type:"function_call",id:a,call_id:a,name:i.function.name,arguments:i.function.arguments||"",status:"completed"});}return n}if(e.role==="tool"){let n=this.normalizeCallId(e.tool_call_id||e.name,t),o=ee(e.content),i=tf(o);return [{type:"function_call_output",call_id:n,output:i}]}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"&&o.text.trim()?n.push({type:"input_text",text:o.text}):o.type==="image_url"&&n.push({type:"input_image",image_url:o.image_url.url});return n.length===0?[]:[{type:"message",role:"user",content:n}]}let s=ee(e.content);return !s||s.trim().length===0?[]:[{type:"message",role:"user",content:[{type:"input_text",text:s}]}]}normalizeCallId(e,t){if(e&&t.has(e))return t.get(e);let s;return e?s=e.startsWith("fc_")?e:`fc_${e}`:s=`fc_${Math.random().toString(36).slice(2,10)}`,e?t.set(e,s):t.set(s,s),s}async*parseStreamResponse(e){let t="",s=new Map,n=0,o=null,i=null,a=false,l=false,c,u=d=>{let m={...d};return l||(m.role="assistant",l=true),{id:c,choices:[{index:0,delta:m}]}};for await(let d of e){t+=d.toString();let m=t.split(`
1707
1707
  `);t=m.pop()||"";for(let h of m){let f=h.trim();if(!f||!f.startsWith("data: "))continue;let y=f.slice(6);if(y==="[DONE]"){process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Doubao Stream] Received [DONE]");continue}let b;try{b=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]",b.type,JSON.stringify(b,null,2).slice(0,200)),b.type){case "response.created":case "response.in_progress":b.response?.id&&(c=b.response.id);break;case "response.output_text.delta":{let _=typeof b.delta=="string"?b.delta:"";if(!_)break;a=true,yield u({content:_});break}case "response.reasoning_summary_text.delta":{let _=typeof b.delta=="string"?b.delta:"";if(!_)break;a=true,yield u({reasoning_content:_});break}case "response.reasoning_summary_part.added":case "response.reasoning_summary_part.done":break;case "response.output_item.added":{if(b.item?.type==="function_call"){let _=b.item,v=_.id||`item_${b.output_index}`,k={id:_.call_id||_.id||`call_${Date.now()}_${n}`,name:_.name,index:n++,arguments:""};s.set(v,k),a=true,yield u({tool_calls:[{index:k.index,id:k.id,type:"function",function:{name:k.name}}]});}else if(b.item?.type==="reasoning"){let _=b.item;if(_.summary?.length>0){let v=_.summary.map(k=>k.text).join(`
1708
- `);v&&(yield u({reasoning_content:v}));}}break}case "response.function_call_arguments.delta":{let _=b.item_id?s.get(b.item_id):void 0;if(!_)break;let v=typeof b.delta=="string"?b.delta:"";if(!v)break;_.arguments+=v,a=true,yield u({tool_calls:[{index:_.index,id:_.id,type:"function",function:{name:_.name,arguments:v}}]});break}case "response.completed":{i=b.response||null,o=b.response?.usage||null,b.response?.id&&(c=b.response.id,this.lastResponseId=c);break}case "response.error":case "response.failed":{let _=b.error?.message||b.error?.code||"Doubao stream failed";throw new Error(_)}}}}if(!a&&i){let d=Array.isArray(i.output)?i.output:[],m="",h="";for(let f of d)if(f?.type==="message"&&Array.isArray(f.content))for(let y of f.content)y?.type==="output_text"&&typeof y.text=="string"&&(m+=y.text);else if(f?.type==="reasoning"){let y=f;y.summary?.length>0&&(h=y.summary.map(b=>b.text).join(`
1709
- `));}(m||h)&&(yield {id:c,choices:[{index:0,delta:{role:"assistant",content:m||void 0,reasoning_content:h||void 0}}]});}let p={id:c,choices:[{index:0,delta:{},finish_reason:s.size>0?"tool_calls":"stop"}]};o&&(p.usage=this.normalizeUsage(o)),yield p;}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 Wo="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",Qg=60,ef=200,tf=`You are a highly skilled assistant tasked with summarizing conversation history.
1708
+ `);v&&(yield u({reasoning_content:v}));}}break}case "response.function_call_arguments.delta":{let _=b.item_id?s.get(b.item_id):void 0;if(!_)break;let v=typeof b.delta=="string"?b.delta:"";if(!v)break;_.arguments+=v,a=true,yield u({tool_calls:[{index:_.index,id:_.id,type:"function",function:{name:_.name,arguments:v}}]});break}case "response.completed":{o=b.response||null,i=b.response?.usage||null,b.response?.id&&(c=b.response.id,this.lastResponseId=c);break}case "response.error":case "response.failed":{let _=b.error?.message||b.error?.code||"Doubao stream failed";throw new Error(_)}}}}if(!a&&o){let d=Array.isArray(o.output)?o.output:[],m="",h="";for(let f of d)if(f?.type==="message"&&Array.isArray(f.content))for(let y of f.content)y?.type==="output_text"&&typeof y.text=="string"&&(m+=y.text);else if(f?.type==="reasoning"){let y=f;y.summary?.length>0&&(h=y.summary.map(b=>b.text).join(`
1709
+ `));}(m||h)&&(yield {id:c,choices:[{index:0,delta:{role:"assistant",content:m||void 0,reasoning_content:h||void 0}}]});}let p={id:c,choices:[{index:0,delta:{},finish_reason:s.size>0?"tool_calls":"stop"}]};i&&(p.usage=this.normalizeUsage(i)),yield p;}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 Hi="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",sf=60,nf=200,rf=`You are a highly skilled assistant tasked with summarizing conversation history.
1710
1710
 
1711
1711
  Your goal is to create a concise yet comprehensive summary that captures:
1712
1712
  1. The main topics and objectives discussed
@@ -1723,7 +1723,7 @@ Guidelines:
1723
1723
  - Write in the same language as the conversation (Chinese if Chinese, English if English)
1724
1724
  - Format the summary clearly with sections if needed
1725
1725
 
1726
- Output only the summary, no additional commentary.`,sf=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1726
+ Output only the summary, no additional commentary.`,of=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1727
1727
 
1728
1728
  \u4F60\u7684\u76EE\u6807\u662F\u521B\u5EFA\u4E00\u4E2A\u7B80\u6D01\u4F46\u5168\u9762\u7684\u6458\u8981\uFF0C\u9700\u8981\u5305\u542B\uFF1A
1729
1729
  1. \u8BA8\u8BBA\u7684\u4E3B\u8981\u4E3B\u9898\u548C\u76EE\u6807
@@ -1740,8 +1740,8 @@ Output only the summary, no additional commentary.`,sf=`\u4F60\u662F\u4E00\u4E2A
1740
1740
  - \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
1741
1741
  - \u5982\u679C\u9700\u8981\uFF0C\u4F7F\u7528\u5206\u8282\u6765\u6E05\u6670\u5730\u683C\u5F0F\u5316\u6458\u8981
1742
1742
 
1743
- \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function nf(r){for(let e of r){let t=ee(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function rf(r){let e=[];for(let t of r){let s=t.role==="assistant"?"Assistant":t.role==="user"?"User":t.role==="tool"?"Tool Result":t.role,n=ee(t.content),i="";if(t.tool_calls?.length&&(i=` [Called tools: ${t.tool_calls.map(a=>a.function.name).join(", ")}]`),n||i){let o=n.length>1e3?n.slice(0,1e3)+"...[truncated]":n;e.push(`[${s}]${i}
1744
- ${o}`);}}return `Please summarize the following conversation history:
1743
+ \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function af(r){for(let e of r){let t=ee(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function lf(r){let e=[];for(let t of r){let s=t.role==="assistant"?"Assistant":t.role==="user"?"User":t.role==="tool"?"Tool Result":t.role,n=ee(t.content),o="";if(t.tool_calls?.length&&(o=` [Called tools: ${t.tool_calls.map(a=>a.function.name).join(", ")}]`),n||o){let i=n.length>1e3?n.slice(0,1e3)+"...[truncated]":n;e.push(`[${s}]${o}
1744
+ ${i}`);}}return `Please summarize the following conversation history:
1745
1745
 
1746
1746
  ---
1747
1747
  ${e.join(`
@@ -1750,18 +1750,18 @@ ${e.join(`
1750
1750
  `)}
1751
1751
  ---
1752
1752
 
1753
- Provide a comprehensive summary:`}function $n(r){let t=ee(r.content).length,s=r.tool_calls?JSON.stringify(r.tool_calls).length:0;return Math.ceil((t+s)/4)}function qo(r,e){return r.length<=e?r:r.slice(0,e-1).trimEnd()+"\u2026"}function of(r){return r.replace(/\s+/g," ").trim()}function Ho(r,e){if(r.length===0)return {summary:"",lines:0};let t=[];for(let n of r){if(t.length>=Qg)break;let i=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,o=ee(n.content),l=(o?of(o):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${i}] ${qo(l,ef)}`);}return {summary:`${e}
1753
+ Provide a comprehensive summary:`}function Nn(r){let t=ee(r.content).length,s=r.tool_calls?JSON.stringify(r.tool_calls).length:0;return Math.ceil((t+s)/4)}function zi(r,e){return r.length<=e?r:r.slice(0,e-1).trimEnd()+"\u2026"}function cf(r){return r.replace(/\s+/g," ").trim()}function qi(r,e){if(r.length===0)return {summary:"",lines:0};let t=[];for(let n of r){if(t.length>=sf)break;let o=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,i=ee(n.content),l=(i?cf(i):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${o}] ${zi(l,nf)}`);}return {summary:`${e}
1754
1754
  ${t.join(`
1755
- `)}`,lines:t.length}}async function zo(r){let{session:e,profile:t,llmProvider:s,model:n,onProgress:i,timeout:o=6e4,signal:a}=r,l=r.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;i?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((A,P)=>({entry:A,index:P})).filter(({entry:A})=>A.item.type==="message");if(u.length===0)return null;u.filter(({entry:A})=>A.item.data.role==="system");let d=u.filter(({entry:A})=>A.item.data.role!=="system");if(d.length===0)return null;let m=0,h=d.length;for(let A=d.length-1;A>=0;A--){let P=d[A].entry.item.data;if(m+=$n(P),m>=l){h=A;break}}if(h>=d.length){if(d.length<=2)return null;h=Math.floor(d.length/2);}let f=d.slice(0,h).map(({entry:A})=>A.item.data);if(f.length===0)return null;let y={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let A of f){let P=$n(A);A.role==="user"?y.userTokens+=P:A.role==="assistant"?y.assistantTokens+=P:A.role==="tool"&&(y.toolTokens+=P),y.totalTokens+=P;}let b=d.slice(h).map(({entry:A})=>A.item.data),_={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let A of b){let P=$n(A);A.role==="user"?_.userTokens+=P:A.role==="assistant"?_.assistantTokens+=P:A.role==="tool"&&(_.toolTokens+=P),_.totalTokens+=P;}let v=y.totalTokens;i?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=nf(f),R=k==="zh"?sf:tf,O=rf(f),W,F;try{let A=new AbortController,P=setTimeout(()=>A.abort(),o),K=a?AbortSignal.any([a,A.signal]):A.signal;try{let U=await s.chat([{role:"system",content:R},{role:"user",content:O}],{model:n,temperature:.3,signal:K});clearTimeout(P),W=ee(U.choices[0]?.message?.content)||"",F=U.usage?.total_tokens;}catch(U){throw clearTimeout(P),U?.name==="AbortError"||U?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",U.message),U}if(!W.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:U}=Ho(f,Wo);W=U;}}catch(A){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",A.message);let{summary:P}=Ho(f,Wo);W=P;}i?.("saving","Saving compacted history...");let C=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1755
+ `)}`,lines:t.length}}async function Ji(r){let{session:e,profile:t,llmProvider:s,model:n,onProgress:o,timeout:i=6e4,signal:a}=r,l=r.tailTokenBudget??t.tailTokenBudget??2e4;if(!l||l<=0)return null;o?.("analyzing","Analyzing conversation history...");let c=await e.getTimeline(),u=c.map((A,P)=>({entry:A,index:P})).filter(({entry:A})=>A.item.type==="message");if(u.length===0)return null;u.filter(({entry:A})=>A.item.data.role==="system");let d=u.filter(({entry:A})=>A.item.data.role!=="system");if(d.length===0)return null;let m=0,h=d.length;for(let A=d.length-1;A>=0;A--){let P=d[A].entry.item.data;if(m+=Nn(P),m>=l){h=A;break}}if(h>=d.length){if(d.length<=2)return null;h=Math.floor(d.length/2);}let f=d.slice(0,h).map(({entry:A})=>A.item.data);if(f.length===0)return null;let y={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let A of f){let P=Nn(A);A.role==="user"?y.userTokens+=P:A.role==="assistant"?y.assistantTokens+=P:A.role==="tool"&&(y.toolTokens+=P),y.totalTokens+=P;}let b=d.slice(h).map(({entry:A})=>A.item.data),_={userTokens:0,assistantTokens:0,toolTokens:0,totalTokens:0};for(let A of b){let P=Nn(A);A.role==="user"?_.userTokens+=P:A.role==="assistant"?_.assistantTokens+=P:A.role==="tool"&&(_.toolTokens+=P),_.totalTokens+=P;}let v=y.totalTokens;o?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=af(f),R=k==="zh"?of:rf,O=lf(f),W,F;try{let A=new AbortController,P=setTimeout(()=>A.abort(),i),K=a?AbortSignal.any([a,A.signal]):A.signal;try{let U=await s.chat([{role:"system",content:R},{role:"user",content:O}],{model:n,temperature:.3,signal:K});clearTimeout(P),W=ee(U.choices[0]?.message?.content)||"",F=U.usage?.total_tokens;}catch(U){throw clearTimeout(P),U?.name==="AbortError"||U?.code==="ABORT_ERR"?console.warn("[SmartCompact] LLM call timed out or was cancelled, falling back to lightweight"):console.error("[SmartCompact] LLM call failed:",U.message),U}if(!W.trim()){console.warn("[SmartCompact] LLM returned empty summary, falling back to lightweight");let{summary:U}=qi(f,Hi);W=U;}}catch(A){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",A.message);let{summary:P}=qi(f,Hi);W=P;}o?.("saving","Saving compacted history...");let C=`${k==="zh"?"# \u5BF9\u8BDD\u5386\u53F2\u6458\u8981\uFF08AI \u751F\u6210\uFF09":"# Conversation Summary (AI Generated)"}
1756
1756
 
1757
- ${W}`,w=u.length-f.length,T=u[0]?.entry.timestamp??Date.now(),M={item:{type:"message",data:{role:"user",content:C,name:"SmartCompactSummary"}},timestamp:T,seq:0},B={item:{type:"compacted",data:{summary:qo(W,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:T,seq:0},E=[],L=false,N=new Set(d.slice(0,h).map(({entry:A})=>A));for(let A of c){if(A.item.type!=="message"){E.push({...A});continue}if(A.item.data.role==="system"){E.push({...A});continue}N.has(A)?L||(E.push({...M}),E.push({...B}),L=true):E.push({...A});}if(!L)return null;let $=E.map((A,P)=>({item:A.item,timestamp:A.timestamp??Date.now(),seq:P}));await e.replaceTimeline($);let G=$n({content:C}),X={before:y,after:{userTokens:_.userTokens,assistantTokens:_.assistantTokens,toolTokens:_.toolTokens,summaryTokens:G,totalTokens:_.totalTokens+G},saved:{userTokens:y.userTokens,assistantTokens:y.assistantTokens,toolTokens:y.toolTokens,totalTokens:y.totalTokens-G}};return {removedMessages:f.length,keptMessages:w,summaryText:C,estimatedTokensSaved:v,llmTokensUsed:F,detailedStats:X}}async function Xc(r){let{session:e,profile:t}=r,s=r.tailTokenBudget??t.tailTokenBudget??2e4;if(!s||s<=0)return null;let n=await e.getTimeline(),i=n.map((R,O)=>({entry:R,index:O})).filter(({entry:R})=>R.item.type==="message");if(i.length===0)return null;i.filter(({entry:R})=>R.item.data.role==="system");let a=i.filter(({entry:R})=>R.item.data.role!=="system");if(a.length===0)return null;let l=0,c=a.length;for(let R=a.length-1;R>=0;R--){let O=a[R].entry.item.data;if(l+=$n(O),l>=s){c=R;break}}if(c>=a.length){if(a.length<=2)return null;c=Math.floor(a.length/2);}let u=a.slice(0,c).map(({entry:R})=>R.item.data);if(u.length===0)return null;let{summary:p,lines:d}=Ho(u,r.summaryHeader??Wo);if(!p.trim())return null;let m=a.length-u.length,h=a[0]?.entry.timestamp??Date.now(),f={item:{type:"message",data:{role:"user",content:p,name:"CompatSummary"}},timestamp:h,seq:0},y={item:{type:"compacted",data:{summary:qo(p,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:h,seq:0},b=[],_=false,v=new Set(a.slice(0,c).map(({entry:R})=>R));for(let R of n){if(R.item.type!=="message"){b.push({...R});continue}if(R.item.data.role==="system"){b.push({...R});continue}v.has(R)?_||(b.push({...f}),b.push({...y}),_=true):b.push({...R});}if(!_)return null;let k=b.map((R,O)=>({item:R.item,timestamp:R.timestamp??Date.now(),seq:O}));return await e.replaceTimeline(k),{removedMessages:u.length,keptMessages:m,summaryText:p,summaryLines:d}}var ti=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let s=[/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 s){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 n=t.toLowerCase(),i=e.split(/[.。!!??]/);for(let o of i)if(o.toLowerCase().includes(n)||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()}},si=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 s=e.pattern||"";t+=` "${this.escapeShellArg(s)}"`;let n=e.path||e.directory||".";return t+=` ${this.escapeShellPath(n)}`,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",s=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(s)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let n=e.patterns.map(i=>`-name "${this.escapeShellArg(i)}"`).join(" -o ");t+=` \\( ${n} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(n=>{t+=` ! -path "${this.escapeShellArg(n)}"`;}),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 s=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${s}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 s=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(s)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",s=e.content||"";return s.length<100&&!s.includes(`
1758
- `)?`echo "${this.escapeShellArg(s)}" > ${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 $s(r,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let s of t)if(e[s]&&typeof e[s]=="string")return e[s];switch(r){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let n=e.command,i=n.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return i?i[1]:n.substring(0,50)+(n.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let s=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${s} (${e.patterns.join(", ")})`:s;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 Zc(r,e){switch(r){case "readfile":let t=$s(r,e);return t?`Reading ${t}`:"Reading file";case "write_file":case "create_file":let s=$s(r,e);return s?`Writing ${s}`:"Writing file";case "edit_file":case "Edit":let n=$s(r,e);return n?`Editing ${n}`:"Editing file";case "search":let i=e.pattern||e.query;return i?`Searching for "${i}"`:"Searching code";case "list_directory":case "LS":return `Listing ${$s(r,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 ${r}`}}var ni=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,s,n,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:s,startTime:i,args:n}]),{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:s,startTime:i,args:n}]),{type:"single",merge:false};if(o.some(u=>u.targetPath===s))return {type:"single",merge:false};if(o.length===1){let u=this.createBatch(a,e,s,i);return o.push({toolId:e,toolName:t,targetPath:s,startTime:i,args:n}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(o.push({toolId:e,toolName:t,targetPath:s,startTime:i,args:n}),this.updateBatch(u,s,i),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:i,args:n}]),{type:"single",merge:false})}}recordCompletion(e,t){let s=this.findActiveBatch(e);if(s){let n=this.activeBatches.get(s);n&&(n.completed++,n.completed>=n.total&&this.completeBatch(s));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,s,n){let i=`batch-${e.toolName}-${n}`;return this.activeBatches.set(i,{batchId:i,toolName:e.toolName,targets:[e.targetPath,s],startTime:e.startTime,lastCallTime:n,completed:0,total:2}),i}updateBatch(e,t,s){let n=this.activeBatches.get(e);n&&(n.targets.push(t),n.total++,n.lastCallTime=s);}findActiveBatch(e){for(let[t,s]of this.activeBatches.entries())if(s.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,s=[];this.activeBatches.forEach((i,o)=>{e-i.lastCallTime>t&&s.push(o);}),s.forEach(i=>this.completeBatch(i));let n=[];this.pendingCalls.forEach((i,o)=>{if(i.length>0){let a=i[i.length-1];e-a.startTime>t&&n.push(o);}}),n.forEach(i=>this.pendingCalls.delete(i));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,s)=>{e.push({batchId:s,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};le();function Qc(r){if(!r||r.trim().length===0)return null;let e=r.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 n=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==="{"?n++:l==="}"?n--:l==="["?i++:l==="]"&&i--);}for(o&&(e+='"');i>0;)e+="]",i--;for(;n>0;)e+="}",n--;try{return JSON.parse(e),console.log("[JsonRepair] Fixed by force-closing structures"),e}catch{return null}}function eu(r,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(r==="write_file"||r==="edit_file"){if(!e.includes('"content"')&&!e.includes('"new_string"'))return {isTruncated:true,reason:"File content field is missing - likely truncated during streaming"};let s=e.match(/"content"\s*:\s*"([^]*)/);if(s){let n=s[1],i=0,o=false;for(let a of n){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 tu(r,e,t){let s=uc(r,e,t),n=$r(s);return {success:false,error:s.code,code:s.code,category:s.category,message:s.message,suggestion:n,retryable:s.retryable,receivedArgs:e?.substring(0,500)}}var nu=12e3,ri=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionSeed;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;compressionMode="sync";eventEmitter=new EventEmitter;descriptionExtractor=new ti;commandGenerator=new si;lastAssistantMessage="";batchDetector=new ni;toolCallIdCounter=0;recentToolCalls=new Map;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=Y__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.sessionSeed=randomBytes(16).toString("hex"),this.syncWorkspaceEnv(),this.applyAnthropicSessionUserId();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=Y__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t,this.applyAnthropicSessionUserId();}applyAnthropicSessionUserId(){let t=this.llmProvider?.getProvider?.();if(!t||typeof t.setUserId!="function")return;let s=this.session?.sessionId,n=Oa(s,this.sessionSeed);t.setUserId(n);}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){if(e.type==="plan_update"&&g.info("EMIT_EVENT","\u{1F525} Emitting plan_update via eventEmitter",{listenerCount:this.eventEmitter.listenerCount("event"),hasExplanation:!!e.explanation,planSteps:e.plan?.length}),e.type==="text"&&process.env.CLI_DEBUG==="1"){let t=e.delta||"";g.debug("EMIT_EVENT",`Emitting text event: "${t.substring(0,20)}...", listeners=${this.eventEmitter.listenerCount("event")}`);}this.eventEmitter.emit("event",e),e.type==="plan_update"&&g.info("EMIT_EVENT","\u2705 plan_update emitted");}emitLog(e,t,s){process.env.CLI_DEBUG&&(g.debug("EMIT",`emitLog: level=${e}, message="${t.substring(0,50)}..."`),g.debug("EMIT",` eventEmitter.listenerCount: ${this.eventEmitter.listenerCount("event")}`)),this.emitEvent({type:"log",level:e,message:t,detail:s});}emitCompacting(e,t){process.env.CLI_DEBUG&&g.debug("EMIT",`emitCompacting: message="${e.substring(0,50)}..."`),this.emitEvent({type:"compacting",message:e,detail:t});}updateRuntime(e){this.runner=e.runner,this.memory=e.memory,this.model=e.model,e.systemPrompt&&(this.systemPrompt=e.systemPrompt);}setCompressionMode(e){this.compressionMode=e,g.info("RUNTIME",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}prepareTaskInput(e,t){let s=e,n=t?.attachments?.filter(i=>i.type==="url")||[];return n.length>0&&(s=`Attachments:
1759
- ${n.map((o,a)=>`Attachment ${a+1}: [URL: ${o.data}]`).join(`
1757
+ ${W}`,w=u.length-f.length,T=u[0]?.entry.timestamp??Date.now(),M={item:{type:"message",data:{role:"user",content:C,name:"SmartCompactSummary"}},timestamp:T,seq:0},B={item:{type:"compacted",data:{summary:zi(W,2e3),originalCount:f.length,compactedAt:new Date().toISOString(),method:"smart",llmTokensUsed:F}},timestamp:T,seq:0},E=[],L=false,N=new Set(d.slice(0,h).map(({entry:A})=>A));for(let A of c){if(A.item.type!=="message"){E.push({...A});continue}if(A.item.data.role==="system"){E.push({...A});continue}N.has(A)?L||(E.push({...M}),E.push({...B}),L=true):E.push({...A});}if(!L)return null;let $=E.map((A,P)=>({item:A.item,timestamp:A.timestamp??Date.now(),seq:P}));await e.replaceTimeline($);let G=Nn({content:C}),X={before:y,after:{userTokens:_.userTokens,assistantTokens:_.assistantTokens,toolTokens:_.toolTokens,summaryTokens:G,totalTokens:_.totalTokens+G},saved:{userTokens:y.userTokens,assistantTokens:y.assistantTokens,toolTokens:y.toolTokens,totalTokens:y.totalTokens-G}};return {removedMessages:f.length,keptMessages:w,summaryText:C,estimatedTokensSaved:v,llmTokensUsed:F,detailedStats:X}}async function eu(r){let{session:e,profile:t}=r,s=r.tailTokenBudget??t.tailTokenBudget??2e4;if(!s||s<=0)return null;let n=await e.getTimeline(),o=n.map((R,O)=>({entry:R,index:O})).filter(({entry:R})=>R.item.type==="message");if(o.length===0)return null;o.filter(({entry:R})=>R.item.data.role==="system");let a=o.filter(({entry:R})=>R.item.data.role!=="system");if(a.length===0)return null;let l=0,c=a.length;for(let R=a.length-1;R>=0;R--){let O=a[R].entry.item.data;if(l+=Nn(O),l>=s){c=R;break}}if(c>=a.length){if(a.length<=2)return null;c=Math.floor(a.length/2);}let u=a.slice(0,c).map(({entry:R})=>R.item.data);if(u.length===0)return null;let{summary:p,lines:d}=qi(u,r.summaryHeader??Hi);if(!p.trim())return null;let m=a.length-u.length,h=a[0]?.entry.timestamp??Date.now(),f={item:{type:"message",data:{role:"user",content:p,name:"CompatSummary"}},timestamp:h,seq:0},y={item:{type:"compacted",data:{summary:zi(p,2e3),originalCount:u.length,compactedAt:new Date().toISOString()}},timestamp:h,seq:0},b=[],_=false,v=new Set(a.slice(0,c).map(({entry:R})=>R));for(let R of n){if(R.item.type!=="message"){b.push({...R});continue}if(R.item.data.role==="system"){b.push({...R});continue}v.has(R)?_||(b.push({...f}),b.push({...y}),_=true):b.push({...R});}if(!_)return null;let k=b.map((R,O)=>({item:R.item,timestamp:R.timestamp??Date.now(),seq:O}));return await e.replaceTimeline(k),{removedMessages:u.length,keptMessages:m,summaryText:p,summaryLines:d}}var so=class{extractFromAssistantMessage(e,t){if(!e||e.length===0)return;let s=[/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 i of s){let a=e.match(i);if(a){let l=a[2]||a[1];if(l&&l.length>0&&l.length<200)return l.trim()}}let n=t.toLowerCase(),o=e.split(/[.。!!??]/);for(let i of o)if(i.toLowerCase().includes(n)||i.toLowerCase().includes("read")||i.toLowerCase().includes("search")||i.toLowerCase().includes("file")){let a=i.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()}},no=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 s=e.pattern||"";t+=` "${this.escapeShellArg(s)}"`;let n=e.path||e.directory||".";return t+=` ${this.escapeShellPath(n)}`,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",s=e.folder||e.path||".";if(t+=` ${this.escapeShellPath(s)}`,e.patterns&&Array.isArray(e.patterns)&&e.patterns.length>0)if(e.patterns.length===1)t+=` -name "${this.escapeShellArg(e.patterns[0])}"`;else {let n=e.patterns.map(o=>`-name "${this.escapeShellArg(o)}"`).join(" -o ");t+=` \\( ${n} \\)`;}return e.excludePatterns&&Array.isArray(e.excludePatterns)&&e.excludePatterns.forEach(n=>{t+=` ! -path "${this.escapeShellArg(n)}"`;}),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 s=e.start_line+e.num_lines-1;return `sed -n '${e.start_line},${s}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 s=e.path||e.directory||e.directory_path||".";return t+=` ${this.escapeShellPath(s)}`,t}generateWriteCommand(e){let t=e.path||e.file_path||e.filename||"",s=e.content||"";return s.length<100&&!s.includes(`
1758
+ `)?`echo "${this.escapeShellArg(s)}" > ${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 Ns(r,e){let t=["path","file_path","filePath","filename","directory","folder","dir","file","output_path","input_path"];for(let s of t)if(e[s]&&typeof e[s]=="string")return e[s];switch(r){case "Execute":case "execute":if(e.command&&typeof e.command=="string"){let n=e.command,o=n.match(/(?:^|\s)([./~][\w/.-]+\.\w+)(?:\s|$)/);return o?o[1]:n.substring(0,50)+(n.length>50?"...":"")}break;case "search":return e.path||e.directory||".";case "Glob":case "find_files":let s=e.folder||e.path||".";return e.patterns&&Array.isArray(e.patterns)?`${s} (${e.patterns.join(", ")})`:s;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 tu(r,e){switch(r){case "readfile":let t=Ns(r,e);return t?`Reading ${t}`:"Reading file";case "write_file":case "create_file":let s=Ns(r,e);return s?`Writing ${s}`:"Writing file";case "edit_file":case "Edit":let n=Ns(r,e);return n?`Editing ${n}`:"Editing file";case "search":let o=e.pattern||e.query;return o?`Searching for "${o}"`:"Searching code";case "list_directory":case "LS":return `Listing ${Ns(r,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 ${r}`}}var ro=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,s,n,o){if(!this.isBatchable(t))return {type:"single",merge:false};let i=this.pendingCalls.get(t)||[];if(i.length===0)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:o,args:n}]),{type:"single",merge:false};let a=i[i.length-1];if(o-a.startTime>this.batchTimeWindow)return this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:o,args:n}]),{type:"single",merge:false};if(i.some(u=>u.targetPath===s))return {type:"single",merge:false};if(i.length===1){let u=this.createBatch(a,e,s,o);return i.push({toolId:e,toolName:t,targetPath:s,startTime:o,args:n}),{type:"batch",merge:false,batchId:u,shouldCreateBatch:true}}else {let u=this.findActiveBatch(t);return u?(i.push({toolId:e,toolName:t,targetPath:s,startTime:o,args:n}),this.updateBatch(u,s,o),{type:"batch",merge:true,batchId:u}):(this.pendingCalls.set(t,[{toolId:e,toolName:t,targetPath:s,startTime:o,args:n}]),{type:"single",merge:false})}}recordCompletion(e,t){let s=this.findActiveBatch(e);if(s){let n=this.activeBatches.get(s);n&&(n.completed++,n.completed>=n.total&&this.completeBatch(s));}}getBatchInfo(e){return this.activeBatches.get(e)}isBatchable(e){return this.batchableTools.has(e)}createBatch(e,t,s,n){let o=`batch-${e.toolName}-${n}`;return this.activeBatches.set(o,{batchId:o,toolName:e.toolName,targets:[e.targetPath,s],startTime:e.startTime,lastCallTime:n,completed:0,total:2}),o}updateBatch(e,t,s){let n=this.activeBatches.get(e);n&&(n.targets.push(t),n.total++,n.lastCallTime=s);}findActiveBatch(e){for(let[t,s]of this.activeBatches.entries())if(s.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,s=[];this.activeBatches.forEach((o,i)=>{e-o.lastCallTime>t&&s.push(i);}),s.forEach(o=>this.completeBatch(o));let n=[];this.pendingCalls.forEach((o,i)=>{if(o.length>0){let a=o[o.length-1];e-a.startTime>t&&n.push(i);}}),n.forEach(o=>this.pendingCalls.delete(o));}reset(){this.activeBatches.clear(),this.pendingCalls.clear();}getStats(){let e=[];return this.activeBatches.forEach((t,s)=>{e.push({batchId:s,toolName:t.toolName,total:t.total,completed:t.completed});}),{activeBatches:this.activeBatches.size,pendingCalls:this.pendingCalls.size,batches:e}}};le();function su(r){if(!r||r.trim().length===0)return null;let e=r.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 n=0,o=0,i=false,a=false;for(let l of e){if(a){a=false;continue}if(l==="\\"){a=true;continue}if(l==='"'){i=!i;continue}i||(l==="{"?n++:l==="}"?n--:l==="["?o++:l==="]"&&o--);}for(i&&(e+='"');o>0;)e+="]",o--;for(;n>0;)e+="}",n--;try{return JSON.parse(e),console.log("[JsonRepair] Fixed by force-closing structures"),e}catch{return null}}function nu(r,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(r==="write_file"||r==="edit_file"){if(!e.includes('"content"')&&!e.includes('"new_string"'))return {isTruncated:true,reason:"File content field is missing - likely truncated during streaming"};let s=e.match(/"content"\s*:\s*"([^]*)/);if(s){let n=s[1],o=0,i=false;for(let a of n){if(i){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){o++;break}}if(o===0)return {isTruncated:true,reason:"Content string is unclosed - truncated during streaming"}}}return {isTruncated:false}}function ru(r,e,t){let s=mc(r,e,t),n=Nr(s);return {success:false,error:s.code,code:s.code,category:s.category,message:s.message,suggestion:n,retryable:s.retryable,receivedArgs:e?.substring(0,500)}}var iu=12e3,oo=class{runner;memory;sessionManager;sessionSync;session;sessionEnabled;memoryPressure;compatProfile;workDir;model;systemPrompt;sandboxSetter;llmProvider;sessionSeed;sessionTotalInputTokens=0;sessionTotalOutputTokens=0;lastMemoryPressureState="unknown";autoCompactionInProgress=false;isRunning=false;shouldInterrupt=false;abortController=null;interruptResolver=null;interruptPromise=null;compressionMode="sync";eventEmitter=new EventEmitter;descriptionExtractor=new so;commandGenerator=new no;lastAssistantMessage="";batchDetector=new ro;toolCallIdCounter=0;recentToolCalls=new Map;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=Y__default.resolve(e.workDir),this.model=e.model,this.systemPrompt=e.systemPrompt,this.memoryPressure=e.memoryPressure,this.compatProfile=e.compatProfile,this.sandboxSetter=e.setSandboxMode,this.llmProvider=e.llmProvider,this.sessionSeed=randomBytes(16).toString("hex"),this.syncWorkspaceEnv(),this.applyAnthropicSessionUserId();}on(e){return this.eventEmitter.on("event",e),()=>this.eventEmitter.off("event",e)}setWorkDir(e){this.workDir=Y__default.resolve(e),this.syncWorkspaceEnv();}setSession(e,t){this.session=e||void 0,this.sessionSync=t,this.applyAnthropicSessionUserId();}applyAnthropicSessionUserId(){let t=this.llmProvider?.getProvider?.();if(!t||typeof t.setUserId!="function")return;let s=this.session?.sessionId,n=$a(s,this.sessionSeed);t.setUserId(n);}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){if(e.type==="plan_update"&&g.info("EMIT_EVENT","\u{1F525} Emitting plan_update via eventEmitter",{listenerCount:this.eventEmitter.listenerCount("event"),hasExplanation:!!e.explanation,planSteps:e.plan?.length}),e.type==="text"&&process.env.CLI_DEBUG==="1"){let t=e.delta||"";g.debug("EMIT_EVENT",`Emitting text event: "${t.substring(0,20)}...", listeners=${this.eventEmitter.listenerCount("event")}`);}this.eventEmitter.emit("event",e),e.type==="plan_update"&&g.info("EMIT_EVENT","\u2705 plan_update emitted");}emitLog(e,t,s){process.env.CLI_DEBUG&&(g.debug("EMIT",`emitLog: level=${e}, message="${t.substring(0,50)}..."`),g.debug("EMIT",` eventEmitter.listenerCount: ${this.eventEmitter.listenerCount("event")}`)),this.emitEvent({type:"log",level:e,message:t,detail:s});}emitCompacting(e,t){process.env.CLI_DEBUG&&g.debug("EMIT",`emitCompacting: message="${e.substring(0,50)}..."`),this.emitEvent({type:"compacting",message:e,detail:t});}updateRuntime(e){this.runner=e.runner,this.memory=e.memory,this.model=e.model,e.systemPrompt&&(this.systemPrompt=e.systemPrompt);}setCompressionMode(e){this.compressionMode=e,g.info("RUNTIME",`Compression mode set to: ${e}`);}getCompressionMode(){return this.compressionMode}prepareTaskInput(e,t){let s=e,n=t?.attachments?.filter(o=>o.type==="url")||[];return n.length>0&&(s=`Attachments:
1759
+ ${n.map((i,a)=>`Attachment ${a+1}: [URL: ${i.data}]`).join(`
1760
1760
  `)}
1761
1761
 
1762
1762
  ${s}`),t?.mode==="ask"&&(s=`Mode: ASK (respond conversationally and avoid unnecessary tool calls).
1763
1763
 
1764
- ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.filter(t=>t.type==="image"&&t.data).map(t=>t.data):[]}async handleMemorySnapshot(e,t=false){e&&(this.emitEvent({type:"memory_snapshot",snapshot:e}),await this.maybeAnnounceMemoryPressure(e,t));}async maybeAnnounceMemoryPressure(e,t=false){if(!e.profile.contextWindow){this.lastMemoryPressureState=e.state;return}let s={unknown:0,normal:1,warn:2,soft_limit:3,limit:4},n=s[this.lastMemoryPressureState]??0;if((s[e.state]??0)>n&&e.state!=="normal"&&e.state!=="unknown"){let o=e.pressure!==void 0?Math.round(e.pressure*100):void 0,a=`${e.tokensUsed.toLocaleString()} / ${e.profile.contextWindow.toLocaleString()} tokens`,l="\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"?l="\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"&&(l="\u4E0A\u4E0B\u6587\u5DF2\u5230\u8FBE\u6781\u9650\uFF0C\u5FC5\u987B\u6267\u884C /compact \u6216 /new \u624D\u80FD\u7EE7\u7EED\u3002");let c=o!==void 0?`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528 ${o}% (${a})`:`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528\u504F\u9AD8 (${a})`;this.emitLog("warn",c,l);}this.lastMemoryPressureState=e.state,!t&&this.shouldScheduleAutoCompaction(e.state)&&await this.runPendingAutoCompactionIfIdle();}shouldScheduleAutoCompaction(e){return this.sessionEnabled?e==="warn"||e==="soft_limit"||e==="limit":false}async runPendingAutoCompactionIfIdle(){if(!this.sessionSync||!this.compatProfile||!this.memoryPressure||this.autoCompactionInProgress)return;let e=this.sessionSync.getMemory().getMessagesForLLM(),t=this.memoryPressure.setPromptEstimateFromMessages(e),n=(await this.sessionSync.getSession().getTimeline()).filter(o=>o.item.type==="message").length,i=ss(this.sessionSync.getMemory().getAll());this.autoCompactionInProgress=true;try{let o=this.sessionSync.getSession(),a="";if(t.profile.contextWindow){let l=Math.round(t.tokensUsed/t.profile.contextWindow*100),c=Math.round(t.tokensUsed/1e3),u=Math.round(t.profile.contextWindow/1e3);a=`${c}K / ${u}K tokens (${l}%)`;}if(this.llmProvider){this.emitCompacting("\u26A1 \u6B63\u5728\u667A\u80FD\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${a}\uFF0C\u4F7F\u7528 AI \u751F\u6210\u9AD8\u8D28\u91CF\u4E0A\u4E0B\u6587\u6458\u8981...`),this.emitEvent({type:"status",status:"compacting",message:"\u26A1 Auto-compacting history..."});let l=await zo({session:o,profile:this.compatProfile,llmProvider:this.llmProvider,model:this.model,timeout:6e4,onProgress:(b,_)=>{let k={analyzing:"\u25C6 \u5206\u6790\u5BF9\u8BDD\u5386\u53F2...",summarizing:"\u26A1 AI \u6B63\u5728\u751F\u6210\u6458\u8981...",saving:"\u25B8 \u4FDD\u5B58\u538B\u7F29\u7ED3\u679C..."}[b]||_||"Compacting...";this.emitCompacting(k,_&&b?_:void 0),this.emitEvent({type:"status",status:"compacting",message:k});}});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let b=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(b,!0),b.profile.contextWindow){let _=Math.round(b.tokensUsed/b.profile.contextWindow*100),v=(b.tokensUsed/1e3).toFixed(1),k=(b.profile.contextWindow/1e3).toFixed(0);c=`${v}K / ${k}K (${_}%)`;}}let p=(await o.getTimeline()).filter(b=>b.item.type==="message"),d=ss(this.memory.getAll()),m=l.llmTokensUsed!==void 0;this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:p.length,droppedMessages:m?0:l.removedMessages,compressedMessages:m?l.removedMessages:0,originalTokens:i.totalTokens,finalTokens:d.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:m,timestamp:Date.now()});let h=(l.estimatedTokensSaved/1e3).toFixed(1),f=l.llmTokensUsed?` (LLM: ${l.llmTokensUsed} tokens)`:"",y=`\u{1F4CA} \u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\uFF0C\u8282\u7701\u7EA6 ${h}K tokens${f}`;if(a&&c&&(y+=`
1764
+ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.filter(t=>t.type==="image"&&t.data).map(t=>t.data):[]}async handleMemorySnapshot(e,t=false){e&&(this.emitEvent({type:"memory_snapshot",snapshot:e}),await this.maybeAnnounceMemoryPressure(e,t));}async maybeAnnounceMemoryPressure(e,t=false){if(!e.profile.contextWindow){this.lastMemoryPressureState=e.state;return}let s={unknown:0,normal:1,warn:2,soft_limit:3,limit:4},n=s[this.lastMemoryPressureState]??0;if((s[e.state]??0)>n&&e.state!=="normal"&&e.state!=="unknown"){let i=e.pressure!==void 0?Math.round(e.pressure*100):void 0,a=`${e.tokensUsed.toLocaleString()} / ${e.profile.contextWindow.toLocaleString()} tokens`,l="\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"?l="\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"&&(l="\u4E0A\u4E0B\u6587\u5DF2\u5230\u8FBE\u6781\u9650\uFF0C\u5FC5\u987B\u6267\u884C /compact \u6216 /new \u624D\u80FD\u7EE7\u7EED\u3002");let c=i!==void 0?`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528 ${i}% (${a})`:`\u26A0\uFE0F \u4E0A\u4E0B\u6587\u4F7F\u7528\u504F\u9AD8 (${a})`;this.emitLog("warn",c,l);}this.lastMemoryPressureState=e.state,!t&&this.shouldScheduleAutoCompaction(e.state)&&await this.runPendingAutoCompactionIfIdle();}shouldScheduleAutoCompaction(e){return this.sessionEnabled?e==="warn"||e==="soft_limit"||e==="limit":false}async runPendingAutoCompactionIfIdle(){if(!this.sessionSync||!this.compatProfile||!this.memoryPressure||this.autoCompactionInProgress)return;let e=this.sessionSync.getMemory().getMessagesForLLM(),t=this.memoryPressure.setPromptEstimateFromMessages(e),n=(await this.sessionSync.getSession().getTimeline()).filter(i=>i.item.type==="message").length,o=ns(this.sessionSync.getMemory().getAll());this.autoCompactionInProgress=true;try{let i=this.sessionSync.getSession(),a="";if(t.profile.contextWindow){let l=Math.round(t.tokensUsed/t.profile.contextWindow*100),c=Math.round(t.tokensUsed/1e3),u=Math.round(t.profile.contextWindow/1e3);a=`${c}K / ${u}K tokens (${l}%)`;}if(this.llmProvider){this.emitCompacting("\u26A1 \u6B63\u5728\u667A\u80FD\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${a}\uFF0C\u4F7F\u7528 AI \u751F\u6210\u9AD8\u8D28\u91CF\u4E0A\u4E0B\u6587\u6458\u8981...`),this.emitEvent({type:"status",status:"compacting",message:"\u26A1 Auto-compacting history..."});let l=await Ji({session:i,profile:this.compatProfile,llmProvider:this.llmProvider,model:this.model,timeout:6e4,onProgress:(b,_)=>{let k={analyzing:"\u25C6 \u5206\u6790\u5BF9\u8BDD\u5386\u53F2...",summarizing:"\u26A1 AI \u6B63\u5728\u751F\u6210\u6458\u8981...",saving:"\u25B8 \u4FDD\u5B58\u538B\u7F29\u7ED3\u679C..."}[b]||_||"Compacting...";this.emitCompacting(k,_&&b?_:void 0),this.emitEvent({type:"status",status:"compacting",message:k});}});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let b=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(b,!0),b.profile.contextWindow){let _=Math.round(b.tokensUsed/b.profile.contextWindow*100),v=(b.tokensUsed/1e3).toFixed(1),k=(b.profile.contextWindow/1e3).toFixed(0);c=`${v}K / ${k}K (${_}%)`;}}let p=(await i.getTimeline()).filter(b=>b.item.type==="message"),d=ns(this.memory.getAll()),m=l.llmTokensUsed!==void 0;this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:p.length,droppedMessages:m?0:l.removedMessages,compressedMessages:m?l.removedMessages:0,originalTokens:o.totalTokens,finalTokens:d.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:m,timestamp:Date.now()});let h=(l.estimatedTokensSaved/1e3).toFixed(1),f=l.llmTokensUsed?` (LLM: ${l.llmTokensUsed} tokens)`:"",y=`\u{1F4CA} \u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\uFF0C\u8282\u7701\u7EA6 ${h}K tokens${f}`;if(a&&c&&(y+=`
1765
1765
 
1766
1766
  \u{1F4C8} Context: ${a} \u2192 ${c}`),l.detailedStats){let{before:b,after:_,saved:v}=l.detailedStats,k=R=>(R/1e3).toFixed(1)+"K";y+=`
1767
1767
 
@@ -1775,16 +1775,16 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
1775
1775
  \u2502 \u603B\u8BA1: ${k(_.totalTokens)}`,y+=`
1776
1776
  \u2514\u2500 \u8282\u7701\uFF1A`,y+=`
1777
1777
  User: ${k(v.userTokens)} \u2022 Assistant: ${k(v.assistantTokens)} \u2022 Tool: ${k(v.toolTokens)}`,y+=`
1778
- \u51C0\u8282\u7701: ${k(v.totalTokens)}`;}this.emitCompacting("\u2713 \u667A\u80FD\u538B\u7F29\u5B8C\u6210",y),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}else {this.emitCompacting("\u25B8 \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${a}\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:"\u25B8 Auto-compacting history..."});let l=await Xc({session:o,profile:this.compatProfile});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let m=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(m,!0),m.profile.contextWindow){let h=Math.round(m.tokensUsed/m.profile.contextWindow*100);c=`
1779
- \u5F53\u524D\u4E0A\u4E0B\u6587: ${m.tokensUsed.toLocaleString()} / ${m.profile.contextWindow.toLocaleString()} tokens (${h}%)`;}}let p=(await o.getTimeline()).filter(m=>m.item.type==="message"),d=ss(this.memory.getAll());this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:p.length,droppedMessages:l.removedMessages,compressedMessages:0,originalTokens:i.totalTokens,finalTokens:d.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:!1,timestamp:Date.now()}),this.emitCompacting("\u2713 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${l.summaryLines} \u884C\uFF0C\u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${c}`),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}}catch(o){let a=o?.message||String(o);this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",`\u9519\u8BEF\u8BE6\u60C5: ${a}`),process.env.CLI_DEBUG==="1"&&g.error("[COMPACTION] Failed:",o);}finally{this.autoCompactionInProgress=false;}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(g.debug("TASK","========================================"),g.debug("TASK","=== runTask ENTRY ==="),g.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),g.debug("TASK",` isRunning: ${this.isRunning}`),g.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),g.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),g.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");if(this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController,t?.abortSignal){let _=t.abortSignal;if(_.aborted)this.shouldInterrupt=true,this.abortController.abort();else {let v=()=>{this.shouldInterrupt=true,this.abortController?.abort();};_.addEventListener("abort",v,{once:true});}}let s=t?.metadata?.mode,n=this.runner.getMode(),i=s==="ask"&&n!=="ask";i&&this.runner.setMode("ask");let o=this.prepareTaskInput(e,t?.metadata),a=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.sessionSync&&this.sessionEnabled)try{let _=this.sessionSync.getTurnCount()+1,v=await this.sessionSync.createCheckpoint(`turn_${_}`);this.emitEvent({type:"checkpoint",id:v,auto:!0});}catch(_){g.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",_),console.error("Failed to create auto checkpoint",_);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."});let l=Date.now(),c="",u=0,p=0,d=0,m="",h="",f="",y=0,b=0;try{let _=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&g.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let v=0,k=this.createInterruptPromise(),R=this.runner.run(o,a.length>0?a:void 0,_)[Symbol.asyncIterator]();for(;;){let S=R.next();S.catch(()=>{});let C=await Promise.race([S,k]);if("interrupted"in C){if(this.shouldInterrupt=!0,R.return)try{R.return(void 0)?.catch?.(()=>{});}catch{}break}if(C.done)break;let w=C.value;if(v++,process.env.CLI_DEBUG==="1"&&g.debug("TASK",` \u4E8B\u4EF6 #${v}: ${w.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&g.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(w.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=w.iteration||0,this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:`Thinking... (iteration ${u})`}),b=0,this.memoryPressure){let E=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(g.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${E.length} \u6D88\u606F`),E.forEach((L,N)=>{let $=typeof L.content=="string"?L.content.length:JSON.stringify(L.content).length;g.debug("CONTEXT",` [${N}] role=${L.role}, content_len=${$}`);}));}break;case "text_delta":if(w.delta){c+=w.delta,m+=w.delta;let E=Math.ceil(w.delta.length/4);b+=E,(w.delta.trim().length>0||w.delta.includes(`
1778
+ \u51C0\u8282\u7701: ${k(v.totalTokens)}`;}this.emitCompacting("\u2713 \u667A\u80FD\u538B\u7F29\u5B8C\u6210",y),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}else {this.emitCompacting("\u25B8 \u6B63\u5728\u81EA\u52A8\u538B\u7F29\u5386\u53F2",`\u5F53\u524D\u4E0A\u4E0B\u6587: ${a}\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:"\u25B8 Auto-compacting history..."});let l=await eu({session:i,profile:this.compatProfile});if(!l){this.emitCompacting("\u2139\uFE0F \u65E0\u9700\u538B\u7F29","\u5BF9\u8BDD\u5386\u53F2\u8F83\u77ED\uFF0C\u6240\u6709\u6D88\u606F\u90FD\u5728\u4FDD\u7559\u9884\u7B97\u5185\uFF0820K tokens\uFF09"),this.emitEvent({type:"status",status:"complete",message:"No compaction needed"});return}await this.sessionSync.loadHistory();let c="";if(this.memoryPressure){this.memoryPressure.reset();let m=this.memoryPressure.setPromptEstimateFromMessages(this.sessionSync.getMemory().getMessagesForLLM());if(this.handleMemorySnapshot(m,!0),m.profile.contextWindow){let h=Math.round(m.tokensUsed/m.profile.contextWindow*100);c=`
1779
+ \u5F53\u524D\u4E0A\u4E0B\u6587: ${m.tokensUsed.toLocaleString()} / ${m.profile.contextWindow.toLocaleString()} tokens (${h}%)`;}}let p=(await i.getTimeline()).filter(m=>m.item.type==="message"),d=ns(this.memory.getAll());this.emitEvent({type:"context_compaction",status:"completed",originalMessages:n,keptMessages:p.length,droppedMessages:l.removedMessages,compressedMessages:0,originalTokens:o.totalTokens,finalTokens:d.totalTokens,budgetTokens:t.profile.contextWindow||0,useLLM:!1,timestamp:Date.now()}),this.emitCompacting("\u2713 \u81EA\u52A8\u538B\u7F29\u5B8C\u6210",`\u6458\u8981 ${l.summaryLines} \u884C\uFF0C\u79FB\u9664 ${l.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${l.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\u3002${c}`),this.emitEvent({type:"status",status:"complete",message:"Compaction complete"});}}catch(i){let a=i?.message||String(i);this.emitLog("error","\u81EA\u52A8\u538B\u7F29\u5931\u8D25",`\u9519\u8BEF\u8BE6\u60C5: ${a}`),process.env.CLI_DEBUG==="1"&&g.error("[COMPACTION] Failed:",i);}finally{this.autoCompactionInProgress=false;}}async runTask(e,t){if(process.env.CLI_DEBUG==="1"&&(g.debug("TASK","========================================"),g.debug("TASK","=== runTask ENTRY ==="),g.debug("TASK",` userInput: "${e?.substring(0,50)}..."`),g.debug("TASK",` isRunning: ${this.isRunning}`),g.debug("TASK",` shouldInterrupt: ${this.shouldInterrupt}`),g.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`),g.debug("TASK",` stdin.destroyed: ${process.stdin.destroyed}`)),this.syncWorkspaceEnv(),!e.trim())throw new Error("Input is required");if(this.shouldInterrupt=false,this.isRunning=true,this.abortController=new AbortController,t?.abortSignal){let _=t.abortSignal;if(_.aborted)this.shouldInterrupt=true,this.abortController.abort();else {let v=()=>{this.shouldInterrupt=true,this.abortController?.abort();};_.addEventListener("abort",v,{once:true});}}let s=t?.metadata?.mode,n=this.runner.getMode(),o=s==="ask"&&n!=="ask";o&&this.runner.setMode("ask");let i=this.prepareTaskInput(e,t?.metadata),a=this.extractImageUrls(t?.metadata);if(this.currentTaskMetadata=t?.metadata,this.sessionSync&&this.sessionEnabled)try{let _=this.sessionSync.getTurnCount()+1,v=await this.sessionSync.createCheckpoint(`turn_${_}`);this.emitEvent({type:"checkpoint",id:v,auto:!0});}catch(_){g.error("TASK","\u68C0\u67E5\u70B9\u521B\u5EFA\u5931\u8D25\uFF01 \u4E8B\u4EF6\u53D1\u9001\u5931\u8D25\uFF01",_),console.error("Failed to create auto checkpoint",_);}this.emitEvent({type:"status",status:"thinking",message:"Starting..."});let l=Date.now(),c="",u=0,p=0,d=0,m="",h="",f="",y=0,b=0;try{let _=this.abortController?.signal;process.env.CLI_DEBUG==="1"&&g.debug("TASK","=== \u5F00\u59CBagent loop \u5FAA\u73AF ===");let v=0,k=this.createInterruptPromise(),R=this.runner.run(i,a.length>0?a:void 0,_)[Symbol.asyncIterator]();for(;;){let S=R.next();S.catch(()=>{});let C=await Promise.race([S,k]);if("interrupted"in C){if(this.shouldInterrupt=!0,R.return)try{R.return(void 0)?.catch?.(()=>{});}catch{}break}if(C.done)break;let w=C.value;if(v++,process.env.CLI_DEBUG==="1"&&g.debug("TASK",` \u4E8B\u4EF6 #${v}: ${w.type}`),this.shouldInterrupt){process.env.CLI_DEBUG==="1"&&g.debug("TASK"," shouldInterrupt=true, \u9000\u51FAloop");break}switch(w.type){case "iteration_start":if(this.emitEvent({type:"text_complete"}),u=w.iteration||0,this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:`Thinking... (iteration ${u})`}),b=0,this.memoryPressure){let E=this.memory.getMessagesForLLM();process.env.CLI_DEBUG&&(g.debug("CONTEXT",`\u8FED\u4EE3\u5F00\u59CB: \u77ED\u671F\u8BB0\u5FC6 \u6709 ${E.length} \u6D88\u606F`),E.forEach((L,N)=>{let $=typeof L.content=="string"?L.content.length:JSON.stringify(L.content).length;g.debug("CONTEXT",` [${N}] role=${L.role}, content_len=${$}`);}));}break;case "text_delta":if(w.delta){c+=w.delta,m+=w.delta;let E=Math.ceil(w.delta.length/4);b+=E,(w.delta.trim().length>0||w.delta.includes(`
1780
1780
  `))&&(this.emitEvent({type:"status",status:"thinking",message:"Generating response..."}),this.emitEvent({type:"text",delta:w.delta}));}break;case "reasoning_delta":w.delta&&this.emitEvent({type:"reasoning",delta:w.delta,timestamp:Date.now()});break;case "reasoning_complete":this.emitEvent({type:"reasoning_complete",timestamp:Date.now()});break;case "tool_call_start":p++,h="",y=0,f=w.name||"",this.emitEvent({type:"status",status:"tool_call",message:`Calling: ${w.name}`});break;case "tool_call_delta":if(w.arguments_delta){h+=w.arguments_delta,y+=w.arguments_delta.length;let E=Math.ceil(w.arguments_delta.length/4);if(b+=E,w.arguments_delta.trim().length>0&&this.emitEvent({type:"tool_call_delta",name:f||w.name||"unknown",argumentsDelta:w.arguments_delta}),y>1e3){let G=1-h.trim().length/y;G>.9&&(console.error(`[AgentHost] \u26A0\uFE0F Abnormal tool call: ${f} - ${(G*100).toFixed(1)}% whitespace (${y} bytes)`),this.emitLog("warn",`Model output abnormal: ${f} generating mostly whitespace content`));}if(f==="write_file"||f==="Write"||w.name==="write_file"||w.name==="Write"){let $=Math.floor(y/80),G=(y/1024).toFixed(1);this.emitEvent({type:"status",status:"tool_call",message:`\u26A1 Generating... ${G}KB (~${$} lines)`});try{let X=h.match(/"file_path"\s*:\s*"([^"]+)"/),A=h.match(/"content"\s*:\s*"/);if(X&&A){let P=X[1],K=h.indexOf('"',A.index+9+1)+1;if(K>0){let U=h.substring(K),ne=-1,Te=0;for(let x=0;x<U.length;x++)if(U[x]==="\\")Te++;else {if(U[x]==='"'&&Te%2===0){ne=x;break}Te=0;}ne>0&&(U=U.substring(0,ne));let Q=U.replace(/\\n/g,`
1781
- `).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ie=P.split(".").pop()||"",se={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"},ae=Q.split(`
1782
- `),pe=ae.length<=5;Q.length>2e3&&(Q=Q.slice(-2e3)),pe?this.emitEvent({type:"file_stream",filePath:P,content:Q,language:se[ie]||ie,description:m.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${P} (${ae.length} lines)...`});}}}catch{g.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(w.name&&w.arguments)try{let E=w.arguments.trim(),L=eu(w.name,E);if(L.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&g.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${L.reason}`);let Q=Qc(E);if(Q)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),E=Q;else throw new Error(`Tool arguments truncated: ${L.reason}`)}let N=E?JSON.parse(E):{};process.env.CLI_DEBUG_CONSOLE==="1"&&g.debug("TOOL",`\u2705 Tool call parsed: ${w.name}`,{argsLength:E.length});let $=$s(w.name,N),G=this.descriptionExtractor.extractFromAssistantMessage(m,w.name);G||(G=Zc(w.name,N));let X=this.commandGenerator.generateEquivalentCommand(w.name,N),A=`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,P=Date.now(),K=this.batchDetector.detectBatch(A,w.name,$||"",N,P);this.recentToolCalls.set(w.name,{toolId:A,batchId:K.batchId,targetPath:$,args:N});let U={targetPath:$,argsPreview:JSON.stringify(N).substring(0,200)};w.name==="search"&&N.pattern?U.pattern=N.pattern.substring(0,80):(w.name==="readfile"||w.name==="edit_file")&&N.path&&(U.file=N.path),g.info("TOOL",`\u{1F916} [AGENT] Call: ${w.name}`,U),this.emitEvent({type:"tool_call_start",name:w.name,args:N,targetPath:$,description:G,equivalentCommand:X,timestamp:P+Math.random()*.1,toolId:A,isBatch:K.type==="batch",batchId:K.batchId});let ne=w.name==="write_file"||w.name==="Write",Te=N.file_path||N.filePath||N.path;ne&&Te&&N.content&&(await this.emitFileStreamEvent(Te,N.content,m.trim()||void 0),m="");}catch(E){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",w.name),console.error("[AgentHost] Error:",E.message),console.error("[AgentHost] Arguments length:",w.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",w.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",w.arguments?.substring(Math.max(0,(w.arguments?.length||0)-200))||""));let L=tu(w.name,w.arguments||"",E),N=L.category==="tool_truncated"?`\u274C Tool ${w.name}: content truncated during streaming`:`\u274C Tool ${w.name}: ${L.code}`;this.emitEvent({type:"status",status:"error",message:N}),this.emitEvent({type:"tool_call_start",name:w.name,args:{_raw:w.arguments?.substring(0,500)||"",_error:L.code,_errorCategory:L.category,_errorMessage:L.message,_suggestion:L.suggestion,_retryable:L.retryable},timestamp:Date.now()}),this.emitEvent({type:"tool_output",name:w.name,output:JSON.stringify(L),success:!1});}break}case "tool_output":if(w.name&&w.output!==void 0){let E=typeof w.output=="string"?w.output:JSON.stringify(w.output),L=E.length,N=w.success??!0,$=E.slice(0,nu),G=E.length>nu;g.info("TOOL",`\u{1F916} [AGENT] Result: ${w.name} ${N?"\u2713":"\u2717"}`,{success:N,resultLength:L,outputString:E});let X=this.recentToolCalls.get(w.name),{toolId:A,batchId:P,targetPath:K,args:U}=X||{},ne=K||(U&&typeof U.directory=="string"?U.directory:void 0),Te=w.name==="show_tree"?`show_tree: ${ne||"."} (${L} chars)`:void 0;if(N&&ne&&this.batchDetector.recordCompletion(w.name,ne),this.emitEvent({type:"tool_call_end",name:w.name,success:N,resultLength:L,timestamp:Date.now()+Math.random()*.1,toolId:A,batchId:P,targetPath:ne,summary:Te,output:$,outputTruncated:G,args:U}),w.name==="write_file"&&w.success&&U?.file_path&&U?.content){try{let Q=U.file_path,ie=U.content,se=Q.split(".").pop()?.toLowerCase()||"",ae={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:ie,isComplete:!0,language:ae[se]||se,timestamp:Date.now()});}catch(Q){g.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",Q);}await this.handleWriteFile(U.file_path,U.content,void 0);}if(w.name==="edit_file"&&w.success&&this.sessionSync&&this.sessionEnabled)try{let Q=JSON.parse(E),ie=Q.metadata?.edit_info||Q.edit_info,se=Q.metadata?.hunks;if(g.info("TOOL","edit file\u7684\u7ED3\u679C "+Q),g.info("TOOL","edit file\u7684editInfo "+ie),Q.status==="success"&&ie){let ae=[];if(Array.isArray(se)&&se.length>0)for(let J of se)ae.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:J.old_string,newString:J.new_string,startLine:J.start_line,oldLineCount:J.old_line_count,newLineCount:J.new_line_count,replaceAll:!1,replacementCount:1}});else ae.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:ie.old_string,newString:ie.new_string,startLine:ie.start_line,oldLineCount:ie.old_line_count,newLineCount:ie.new_line_count,replaceAll:(Q.metadata?.replacements||Q.replacements)>1,replacementCount:Q.metadata?.replacements||Q.replacements}});await this.sessionSync.getSession().addItems(ae);}}catch{g.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(w.name==="edit_file"&&w.success)try{let Q=JSON.parse(E),ie=Q.metadata?.edit_info||Q.edit_info;if(Q.status==="success"&&ie){let se=Array.isArray(Q.metadata?.hunks)?Q.metadata.hunks.map(pe=>({oldString:pe.old_string,newString:pe.new_string,startLine:pe.start_line})):void 0,ae=Q.file_path.split(".").pop()?.toLowerCase()||"",J={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:ie.old_string,newString:ie.new_string,startLine:ie.start_line,hunks:se,isComplete:!0,language:J[ae]||ae,timestamp:Date.now()});}}catch{g.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:w.name,output:w.output,success:N});}break;case "token_usage":if(w.usage){d=w.usage.total_tokens;let E=w.usage.prompt_tokens||0,L=w.usage.completion_tokens||0,N=w.usage.prompt_tokens_details?.cached_tokens||0,$=w.usage.cache_read_input_tokens||0,G=w.usage.cache_creation_input_tokens||0,X=N||$||w.usage.cached_tokens||0,A=E+$+G+N;if(g.debug("CACHE","\u{1F525} Cache token calculation:"),g.debug("CACHE",` actualInputTokens=${E}`),g.debug("CACHE",` anthropicCacheReadTokens=${$}`),g.debug("CACHE",` anthropicCacheCreationTokens=${G}`),g.debug("CACHE",` openaiCachedTokens=${N}`),g.debug("CACHE",` fullContextInputTokens=${A}`),g.debug("CACHE",` formula: ${E} + ${$} + ${G} + ${N} = ${A}`),this.sessionTotalInputTokens+=A,this.sessionTotalOutputTokens+=L,process.env.CLI_DEBUG&&(g.debug("CONTEXT","token_usage event received:"),g.debug("CONTEXT",` actualInputTokens=${E}, actualOutputTokens=${L}`),g.debug("CONTEXT",` anthropicCacheReadTokens=${$}, openaiCachedTokens=${N}`),g.debug("CONTEXT",` anthropicCacheCreationTokens=${G}`),g.debug("CONTEXT",` fullContextInputTokens=${A}`),g.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),g.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let P=this.memory.getMessagesForLLM(),K=this.memoryPressure.estimateMessagesForDisplay(P);this.memoryPressure.recordCalibration(K,E,$);let U=this.memoryPressure.recordActualUsage(A,L,P.length);g.debug("SNAPSHOT","\u{1F525} Snapshot values:"),g.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${A}`),g.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${U.promptTokens}`),g.debug("SNAPSHOT",` snapshot.tokensUsed=${U.tokensUsed}`),g.debug("SNAPSHOT",` snapshot.pressure=${U.pressure}`),process.env.CLI_DEBUG&&(g.debug("CONTEXT","recordActualUsage snapshot:"),g.debug("CONTEXT",` tokensUsed=${U.tokensUsed}, promptTokens=${U.promptTokens}`),g.debug("CONTEXT",` completionTokens=${U.completionTokens}, contextWindow=${U.profile.contextWindow}`),g.debug("CONTEXT",` pressure=${U.pressure}, state=${U.state}`)),await this.handleMemorySnapshot(U);}b=0,this.emitEvent({type:"token_usage",promptTokens:A,completionTokens:L,totalTokens:A+L,cachedTokens:X>0?X:void 0,openaiCachedTokens:N>0?N:void 0,anthropicCacheReadTokens:$>0?$:void 0,anthropicCacheCreationTokens:G>0?G:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:w.status,originalMessages:w.originalMessages,keptMessages:w.keptMessages,droppedMessages:w.droppedMessages,compressedMessages:w.compressedMessages,originalTokens:w.originalTokens,finalTokens:w.finalTokens,budgetTokens:w.budgetTokens,useLLM:w.useLLM,timestamp:w.timestamp??Date.now()});break;case "raw_response_event":if(w.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(w.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(w.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let E=Array.isArray(w.data?.errors)&&w.data.errors.length>0?w.data.errors.join("; "):w.data?.message;this.emitLog("warn","Structured output validation failed",E),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(w.event_type==="structured_output.accepted")typeof w.data?.normalized_text=="string"&&(c=w.data.normalized_text),this.emitLog("info","Structured output ready",w.data?.schema?`Schema: ${w.data.schema}`:void 0);else if(w.event_type==="error.classified"){let E=w.data;this.emitEvent({type:"error_classified",category:E.category||"INTERNAL",code:E.code||"UNKNOWN_ERROR",message:E.message||"An unknown error occurred",suggestion:E.suggestion,retryable:E.retryable??!1});}else if(w.event_type==="context_compaction"){let E=w.data;if(this.memoryPressure&&E.finalTokens!==void 0){let $=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot($,!0);}let L=E.droppedMessages||0,N=E.compressedMessages||0;if(L>0||N>0){let $=(E.originalTokens||0)-(E.finalTokens||0),G=E.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${G}`,`\u79FB\u9664 ${L} \u6761\u6D88\u606F${N>0?`\uFF0C\u538B\u7F29 ${N} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${$.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${L} messages`});}}else w.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&g.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:w.data,event_type:w.event_type}));break;case "run_done":break;case "error":g.error("AGENT",`Error: ${w.error||"Unknown error"}`),this.emitEvent({type:"error",message:w.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${w.error||"Unknown error"}`});break;case "stream_retry":let T=w;this.emitEvent({type:"stream_retry",error:T.error,errorCode:T.errorCode||"STREAM_ERROR",attempt:T.attempt,maxRetries:T.maxRetries,delayMs:T.delayMs});break;case "stream_recovered":let M=w;this.emitEvent({type:"stream_recovered",attempt:M.attempt,maxRetries:M.maxRetries});break;case "plan_update":let B=w;g.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!B.explanation,planSteps:B.plan?.length}),this.emitEvent({type:"plan_update",explanation:B.explanation,plan:B.plan,timestamp:B.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(g.debug("TASK","=== runner.run loop COMPLETED ==="),g.debug("TASK",` Total events: ${v}`),g.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let O=Date.now()-l,W=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${p} tool calls, ${d} tokens, ${(O/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&W)try{await this.sessionSync.saveTurn({role:"user",content:o},{role:"assistant",content:W});}catch{}let F={output:W,totalTokens:d,durationMs:O,iterations:u,toolCalls:p,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:W,totalTokens:d,iterations:u,toolCalls:p,durationMs:O}),F}catch(_){if(_?.code==="ERR_CANCELED"||_?.name==="CanceledError"||_?.name==="AbortError"||_?.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");let R=Date.now()-l;return {output:c,totalTokens:d,durationMs:R,iterations:u,toolCalls:p,interrupted:true}}let k=_?.message||String(_)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${k}`}),this.emitLog("error",`Error: ${k}`),_}finally{process.env.CLI_DEBUG&&(g.debug("TASK","=== runTask finally block START ==="),g.debug("TASK",` isRunning was: ${this.isRunning}`)),i&&this.runner.setMode(n),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&g.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,s){let n=e.split(".").pop()||"",o={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,a=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:o,description:s,timestamp:a});}async handleWriteFile(e,t,s){let n=e.split(".").pop()||"",o={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,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 p=null,d="create";l.existsSync(u)&&(d="modify",p=null);let m={type:"file_snapshot",data:{filePath:e,originalContent:p,operation:d,newContent:t}};await this.sessionSync.getSession().addItems([m]);}catch(p){console.debug("Failed to capture file snapshot",p);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:o,description:s,timestamp:a}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
1783
- `).length} lines written to disk`);}catch(l){this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:true,language:o,description:s,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=this.memory.getAll(),s=ss(t),n=s.totalTokens,i=s.systemTokens,o=s.userTokens+s.assistantTokens+s.toolCallTokens+s.toolResultTokens,l=this.memoryPressure?.getSnapshot()?.profile?.contextWindow||2e5,c=n/l,u=Math.round(c*100),d=(await e.getTimeline()).filter(f=>f.item.type==="message");process.env.CLI_DEBUG==="1"&&g.debug("COMPACT","Compaction status",{llmProvider:!!this.llmProvider,totalContextTokens:n,systemPromptTokens:i,dialogTokens:o,breakdown:s,messageCount:d.length,memoryMessageCount:t.length,contextWindow:l,pressure:c});let m=`\u603B Context: ${n.toLocaleString()} tokens (${u}% \u4F7F\u7528)
1784
- \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${i.toLocaleString()} tokens
1785
- \u5BF9\u8BDD\u5386\u53F2: ${o.toLocaleString()} tokens (Memory: ${t.length-1} \u6761, Session: ${d.length} \u6761)`;this.emitCompacting("\u25A0 \u538B\u7F29\u524D\u72B6\u6001",m),this.emitCompacting("\u25C7 \u538B\u7F29\u65B9\u5F0F",`\u4F7F\u7528 LLM \u667A\u80FD\u538B\u7F29
1786
- \u5BF9\u8BDD\u5386\u53F2: ${(o/1e3).toFixed(1)}K tokens (${d.length} \u6761\u6D88\u606F)
1787
- \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${(i/1e3).toFixed(1)}K tokens (\u4E0D\u538B\u7F29)`);let h;if(!this.llmProvider){let f="LLM Provider \u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u8FDB\u884C\u667A\u80FD\u538B\u7F29\u3002\u8BF7\u786E\u4FDD\u5DF2\u914D\u7F6E provider\u3002";throw this.emitLog("error","\u274C \u538B\u7F29\u5931\u8D25",f),new Error(f)}try{if(h=await zo({session:e,profile:this.compatProfile,llmProvider:this.llmProvider,model:this.model,onProgress:(f,y)=>{let b={analyzing:"\u25C6 \u5206\u6790\u4E2D",summarizing:"\u26A1 \u751F\u6210\u6458\u8981",saving:"\u25B8 \u4FDD\u5B58\u4E2D"};this.emitCompacting(b[f],y||"");}}),h){await this.sessionSync.loadHistory();let y=(await e.getTimeline()).filter(O=>O.item.type==="message"),b=ss(this.memory.getAll()),_=h.llmTokensUsed!==void 0;this.emitEvent({type:"context_compaction",status:"completed",originalMessages:d.length,keptMessages:y.length,droppedMessages:_?0:h.removedMessages,compressedMessages:_?h.removedMessages:0,originalTokens:n,finalTokens:b.totalTokens,budgetTokens:l,useLLM:_,timestamp:Date.now()});let v=(h.estimatedTokensSaved/1e3).toFixed(1),k=h.llmTokensUsed?` (\u6D88\u8017 ${h.llmTokensUsed} tokens)`:"",R=`\u79FB\u9664 ${h.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${h.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\uFF0C\u8282\u7701\u7EA6 ${v}K tokens${k}`;if(h.detailedStats){let{before:O,after:W,saved:F}=h.detailedStats,S=C=>(C/1e3).toFixed(1)+"K";R+=`
1781
+ `).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),oe=P.split(".").pop()||"",se={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"},ae=Q.split(`
1782
+ `),pe=ae.length<=5;Q.length>2e3&&(Q=Q.slice(-2e3)),pe?this.emitEvent({type:"file_stream",filePath:P,content:Q,language:se[oe]||oe,description:m.trim()||"Generating code...",timestamp:Date.now()}):this.emitEvent({type:"status",status:"tool_call",message:`Writing ${P} (${ae.length} lines)...`});}}}catch{g.error("MK","\u4E0D\u5B8C\u6574\u7684json \u5904\u7406");}}}break;case "tool_call_done":{if(w.name&&w.arguments)try{let E=w.arguments.trim(),L=nu(w.name,E);if(L.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&g.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${L.reason}`);let Q=su(E);if(Q)process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[AgentHost] \u2705 JSON repaired successfully"),E=Q;else throw new Error(`Tool arguments truncated: ${L.reason}`)}let N=E?JSON.parse(E):{};process.env.CLI_DEBUG_CONSOLE==="1"&&g.debug("TOOL",`\u2705 Tool call parsed: ${w.name}`,{argsLength:E.length});let $=Ns(w.name,N),G=this.descriptionExtractor.extractFromAssistantMessage(m,w.name);G||(G=tu(w.name,N));let X=this.commandGenerator.generateEquivalentCommand(w.name,N),A=`tool-${++this.toolCallIdCounter}-${Math.floor(Date.now())}`,P=Date.now(),K=this.batchDetector.detectBatch(A,w.name,$||"",N,P);this.recentToolCalls.set(w.name,{toolId:A,batchId:K.batchId,targetPath:$,args:N});let U={targetPath:$,argsPreview:JSON.stringify(N).substring(0,200)};w.name==="search"&&N.pattern?U.pattern=N.pattern.substring(0,80):(w.name==="readfile"||w.name==="edit_file")&&N.path&&(U.file=N.path),g.info("TOOL",`\u{1F916} [AGENT] Call: ${w.name}`,U),this.emitEvent({type:"tool_call_start",name:w.name,args:N,targetPath:$,description:G,equivalentCommand:X,timestamp:P+Math.random()*.1,toolId:A,isBatch:K.type==="batch",batchId:K.batchId});let ne=w.name==="write_file"||w.name==="Write",Te=N.file_path||N.filePath||N.path;ne&&Te&&N.content&&(await this.emitFileStreamEvent(Te,N.content,m.trim()||void 0),m="");}catch(E){console.error("[AgentHost] \u274C Failed to parse tool arguments for:",w.name),console.error("[AgentHost] Error:",E.message),console.error("[AgentHost] Arguments length:",w.arguments?.length||0),process.env.CLI_DEBUG_CONSOLE==="1"&&(console.error("[AgentHost] First 200 chars:",w.arguments?.substring(0,200)||""),console.error("[AgentHost] Last 200 chars:",w.arguments?.substring(Math.max(0,(w.arguments?.length||0)-200))||""));let L=ru(w.name,w.arguments||"",E),N=L.category==="tool_truncated"?`\u274C Tool ${w.name}: content truncated during streaming`:`\u274C Tool ${w.name}: ${L.code}`;this.emitEvent({type:"status",status:"error",message:N}),this.emitEvent({type:"tool_call_start",name:w.name,args:{_raw:w.arguments?.substring(0,500)||"",_error:L.code,_errorCategory:L.category,_errorMessage:L.message,_suggestion:L.suggestion,_retryable:L.retryable},timestamp:Date.now()}),this.emitEvent({type:"tool_output",name:w.name,output:JSON.stringify(L),success:!1});}break}case "tool_output":if(w.name&&w.output!==void 0){let E=typeof w.output=="string"?w.output:JSON.stringify(w.output),L=E.length,N=w.success??!0,$=E.slice(0,iu),G=E.length>iu;g.info("TOOL",`\u{1F916} [AGENT] Result: ${w.name} ${N?"\u2713":"\u2717"}`,{success:N,resultLength:L,outputString:E});let X=this.recentToolCalls.get(w.name),{toolId:A,batchId:P,targetPath:K,args:U}=X||{},ne=K||(U&&typeof U.directory=="string"?U.directory:void 0),Te=w.name==="show_tree"?`show_tree: ${ne||"."} (${L} chars)`:void 0;if(N&&ne&&this.batchDetector.recordCompletion(w.name,ne),this.emitEvent({type:"tool_call_end",name:w.name,success:N,resultLength:L,timestamp:Date.now()+Math.random()*.1,toolId:A,batchId:P,targetPath:ne,summary:Te,output:$,outputTruncated:G,args:U}),w.name==="write_file"&&w.success&&U?.file_path&&U?.content){try{let Q=U.file_path,oe=U.content,se=Q.split(".").pop()?.toLowerCase()||"",ae={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:oe,isComplete:!0,language:ae[se]||se,timestamp:Date.now()});}catch(Q){g.error("TOOL","write_file_stream \u53D1\u9001\u5931\u8D25",Q);}await this.handleWriteFile(U.file_path,U.content,void 0);}if(w.name==="edit_file"&&w.success&&this.sessionSync&&this.sessionEnabled)try{let Q=JSON.parse(E),oe=Q.metadata?.edit_info||Q.edit_info,se=Q.metadata?.hunks;if(g.info("TOOL","edit file\u7684\u7ED3\u679C "+Q),g.info("TOOL","edit file\u7684editInfo "+oe),Q.status==="success"&&oe){let ae=[];if(Array.isArray(se)&&se.length>0)for(let J of se)ae.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:J.old_string,newString:J.new_string,startLine:J.start_line,oldLineCount:J.old_line_count,newLineCount:J.new_line_count,replaceAll:!1,replacementCount:1}});else ae.push({type:"file_edit_snapshot",data:{filePath:Q.file_path,oldString:oe.old_string,newString:oe.new_string,startLine:oe.start_line,oldLineCount:oe.old_line_count,newLineCount:oe.new_line_count,replaceAll:(Q.metadata?.replacements||Q.replacements)>1,replacementCount:Q.metadata?.replacements||Q.replacements}});await this.sessionSync.getSession().addItems(ae);}}catch{g.error("TOOL","session\u7684edit file \u4FDD\u5B58\u5931\u8D25 ");}if(w.name==="edit_file"&&w.success)try{let Q=JSON.parse(E),oe=Q.metadata?.edit_info||Q.edit_info;if(Q.status==="success"&&oe){let se=Array.isArray(Q.metadata?.hunks)?Q.metadata.hunks.map(pe=>({oldString:pe.old_string,newString:pe.new_string,startLine:pe.start_line})):void 0,ae=Q.file_path.split(".").pop()?.toLowerCase()||"",J={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:oe.old_string,newString:oe.new_string,startLine:oe.start_line,hunks:se,isComplete:!0,language:J[ae]||ae,timestamp:Date.now()});}}catch{g.error("TOOL","edit file \u4FDD\u5B58\u5931\u8D25 ");}this.emitEvent({type:"tool_output",name:w.name,output:w.output,success:N});}break;case "token_usage":if(w.usage){d=w.usage.total_tokens;let E=w.usage.prompt_tokens||0,L=w.usage.completion_tokens||0,N=w.usage.prompt_tokens_details?.cached_tokens||0,$=w.usage.cache_read_input_tokens||0,G=w.usage.cache_creation_input_tokens||0,X=N||$||w.usage.cached_tokens||0,A=E+$+G+N;if(g.debug("CACHE","\u{1F525} Cache token calculation:"),g.debug("CACHE",` actualInputTokens=${E}`),g.debug("CACHE",` anthropicCacheReadTokens=${$}`),g.debug("CACHE",` anthropicCacheCreationTokens=${G}`),g.debug("CACHE",` openaiCachedTokens=${N}`),g.debug("CACHE",` fullContextInputTokens=${A}`),g.debug("CACHE",` formula: ${E} + ${$} + ${G} + ${N} = ${A}`),this.sessionTotalInputTokens+=A,this.sessionTotalOutputTokens+=L,process.env.CLI_DEBUG&&(g.debug("CONTEXT","token_usage event received:"),g.debug("CONTEXT",` actualInputTokens=${E}, actualOutputTokens=${L}`),g.debug("CONTEXT",` anthropicCacheReadTokens=${$}, openaiCachedTokens=${N}`),g.debug("CONTEXT",` anthropicCacheCreationTokens=${G}`),g.debug("CONTEXT",` fullContextInputTokens=${A}`),g.debug("CONTEXT",` sessionTotalInput=${this.sessionTotalInputTokens}, sessionTotalOutput=${this.sessionTotalOutputTokens}`),g.debug("CONTEXT",` memoryPressure initialized: ${!!this.memoryPressure}`)),this.memoryPressure){let P=this.memory.getMessagesForLLM(),K=this.memoryPressure.estimateMessagesForDisplay(P);this.memoryPressure.recordCalibration(K,E,$);let U=this.memoryPressure.recordActualUsage(A,L,P.length);g.debug("SNAPSHOT","\u{1F525} Snapshot values:"),g.debug("SNAPSHOT",` fullContextInputTokens (passed to recordActualUsage)=${A}`),g.debug("SNAPSHOT",` snapshot.promptTokens (returned)=${U.promptTokens}`),g.debug("SNAPSHOT",` snapshot.tokensUsed=${U.tokensUsed}`),g.debug("SNAPSHOT",` snapshot.pressure=${U.pressure}`),process.env.CLI_DEBUG&&(g.debug("CONTEXT","recordActualUsage snapshot:"),g.debug("CONTEXT",` tokensUsed=${U.tokensUsed}, promptTokens=${U.promptTokens}`),g.debug("CONTEXT",` completionTokens=${U.completionTokens}, contextWindow=${U.profile.contextWindow}`),g.debug("CONTEXT",` pressure=${U.pressure}, state=${U.state}`)),await this.handleMemorySnapshot(U);}b=0,this.emitEvent({type:"token_usage",promptTokens:A,completionTokens:L,totalTokens:A+L,cachedTokens:X>0?X:void 0,openaiCachedTokens:N>0?N:void 0,anthropicCacheReadTokens:$>0?$:void 0,anthropicCacheCreationTokens:G>0?G:void 0,sessionPromptTokens:this.sessionTotalInputTokens,sessionCompletionTokens:this.sessionTotalOutputTokens});}break;case "context_compaction":this.emitEvent({type:"context_compaction",status:w.status,originalMessages:w.originalMessages,keptMessages:w.keptMessages,droppedMessages:w.droppedMessages,compressedMessages:w.compressedMessages,originalTokens:w.originalTokens,finalTokens:w.finalTokens,budgetTokens:w.budgetTokens,useLLM:w.useLLM,timestamp:w.timestamp??Date.now()});break;case "raw_response_event":if(w.event_type==="input_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking input guardrails..."});else if(w.event_type==="output_guardrails.check_start")this.emitEvent({type:"status",status:"thinking",message:"Checking output guardrails..."});else if(w.event_type==="structured_output.retry"){this.emitEvent({type:"text_complete"}),c="";let E=Array.isArray(w.data?.errors)&&w.data.errors.length>0?w.data.errors.join("; "):w.data?.message;this.emitLog("warn","Structured output validation failed",E),this.emitEvent({type:"status",status:"error",message:"Structured output invalid, retrying..."});}else if(w.event_type==="structured_output.accepted")typeof w.data?.normalized_text=="string"&&(c=w.data.normalized_text),this.emitLog("info","Structured output ready",w.data?.schema?`Schema: ${w.data.schema}`:void 0);else if(w.event_type==="error.classified"){let E=w.data;this.emitEvent({type:"error_classified",category:E.category||"INTERNAL",code:E.code||"UNKNOWN_ERROR",message:E.message||"An unknown error occurred",suggestion:E.suggestion,retryable:E.retryable??!1});}else if(w.event_type==="context_compaction"){let E=w.data;if(this.memoryPressure&&E.finalTokens!==void 0){let $=this.memoryPressure.setPromptEstimateFromMessages(this.memory.getMessagesForLLM());this.handleMemorySnapshot($,!0);}let L=E.droppedMessages||0,N=E.compressedMessages||0;if(L>0||N>0){let $=(E.originalTokens||0)-(E.finalTokens||0),G=E.useLLM?"\u667A\u80FD\u538B\u7F29":"\u88C1\u526A";this.emitLog("info",`\u25B8 \u4E0A\u4E0B\u6587${G}`,`\u79FB\u9664 ${L} \u6761\u6D88\u606F${N>0?`\uFF0C\u538B\u7F29 ${N} \u6761`:""}\uFF0C\u8282\u7701\u7EA6 ${$.toLocaleString()} tokens`),this.emitEvent({type:"status",status:"compacting",message:`Context compacted: -${L} messages`});}}else w.event_type==="response.completed"&&(process.env.CLI_DEBUG_CONSOLE==="1"&&g.debug("EVENTS","\u{1F4E4} Forwarding response.completed"),this.emitEvent({type:"raw_response_event",data:w.data,event_type:w.event_type}));break;case "run_done":break;case "error":g.error("AGENT",`Error: ${w.error||"Unknown error"}`),this.emitEvent({type:"error",message:w.error||"Unknown error"}),this.emitEvent({type:"status",status:"error",message:`Error: ${w.error||"Unknown error"}`});break;case "stream_retry":let T=w;this.emitEvent({type:"stream_retry",error:T.error,errorCode:T.errorCode||"STREAM_ERROR",attempt:T.attempt,maxRetries:T.maxRetries,delayMs:T.delayMs});break;case "stream_recovered":let M=w;this.emitEvent({type:"stream_recovered",attempt:M.attempt,maxRetries:M.maxRetries});break;case "plan_update":let B=w;g.info("RUNTIME_HOST","\u{1F525} Forwarding plan_update event",{hasExplanation:!!B.explanation,planSteps:B.plan?.length}),this.emitEvent({type:"plan_update",explanation:B.explanation,plan:B.plan,timestamp:B.timestamp||Date.now()});break}}process.env.CLI_DEBUG==="1"&&(g.debug("TASK","=== runner.run loop COMPLETED ==="),g.debug("TASK",` Total events: ${v}`),g.debug("TASK",` stdin.isPaused: ${process.stdin.isPaused?.()}`)),this.emitEvent({type:"text_complete"});let O=Date.now()-l,W=c;if(this.shouldInterrupt)this.emitEvent({type:"status",status:"error",message:"Task interrupted"});else if(this.emitEvent({type:"status",status:"complete",message:"Complete!"}),this.emitLog("info","Task complete",`${u} iterations, ${p} tool calls, ${d} tokens, ${(O/1e3).toFixed(2)}s`),this.sessionSync&&this.sessionEnabled&&W)try{await this.sessionSync.saveTurn({role:"user",content:i},{role:"assistant",content:W});}catch{}let F={output:W,totalTokens:d,durationMs:O,iterations:u,toolCalls:p,interrupted:this.shouldInterrupt};return this.emitEvent({type:"run_result",output:W,totalTokens:d,iterations:u,toolCalls:p,durationMs:O}),F}catch(_){if(_?.code==="ERR_CANCELED"||_?.name==="CanceledError"||_?.name==="AbortError"||_?.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");let R=Date.now()-l;return {output:c,totalTokens:d,durationMs:R,iterations:u,toolCalls:p,interrupted:true}}let k=_?.message||String(_)||"Unknown error";throw this.emitEvent({type:"text_complete"}),this.emitEvent({type:"status",status:"error",message:`Error: ${k}`}),this.emitLog("error",`Error: ${k}`),_}finally{process.env.CLI_DEBUG&&(g.debug("TASK","=== runTask finally block START ==="),g.debug("TASK",` isRunning was: ${this.isRunning}`)),o&&this.runner.setMode(n),this.isRunning=false,this.abortController=null,this.clearInterruptPromise(),process.env.CLI_DEBUG&&g.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,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,a=Date.now();this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:false,language:i,description:s,timestamp:a});}async handleWriteFile(e,t,s){let n=e.split(".").pop()||"",i={js:"javascript",ts:"typescript",tsx:"typescript",py:"python",html:"html",css:"css",json:"json",md:"markdown"}[n]||n,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 p=null,d="create";l.existsSync(u)&&(d="modify",p=null);let m={type:"file_snapshot",data:{filePath:e,originalContent:p,operation:d,newContent:t}};await this.sessionSync.getSession().addItems([m]);}catch(p){console.debug("Failed to capture file snapshot",p);}this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:!0,language:i,description:s,timestamp:a}),this.emitLog("info",`\u2713 Saved ${e}`,`${t.split(`
1783
+ `).length} lines written to disk`);}catch(l){this.emitEvent({type:"file_stream",filePath:e,content:t,isComplete:true,language:i,description:s,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=this.memory.getAll(),s=ns(t),n=s.totalTokens,o=s.systemTokens,i=s.userTokens+s.assistantTokens+s.toolCallTokens+s.toolResultTokens,l=this.memoryPressure?.getSnapshot()?.profile?.contextWindow||2e5,c=n/l,u=Math.round(c*100),d=(await e.getTimeline()).filter(f=>f.item.type==="message");process.env.CLI_DEBUG==="1"&&g.debug("COMPACT","Compaction status",{llmProvider:!!this.llmProvider,totalContextTokens:n,systemPromptTokens:o,dialogTokens:i,breakdown:s,messageCount:d.length,memoryMessageCount:t.length,contextWindow:l,pressure:c});let m=`\u603B Context: ${n.toLocaleString()} tokens (${u}% \u4F7F\u7528)
1784
+ \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${o.toLocaleString()} tokens
1785
+ \u5BF9\u8BDD\u5386\u53F2: ${i.toLocaleString()} tokens (Memory: ${t.length-1} \u6761, Session: ${d.length} \u6761)`;this.emitCompacting("\u25A0 \u538B\u7F29\u524D\u72B6\u6001",m),this.emitCompacting("\u25C7 \u538B\u7F29\u65B9\u5F0F",`\u4F7F\u7528 LLM \u667A\u80FD\u538B\u7F29
1786
+ \u5BF9\u8BDD\u5386\u53F2: ${(i/1e3).toFixed(1)}K tokens (${d.length} \u6761\u6D88\u606F)
1787
+ \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${(o/1e3).toFixed(1)}K tokens (\u4E0D\u538B\u7F29)`);let h;if(!this.llmProvider){let f="LLM Provider \u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u8FDB\u884C\u667A\u80FD\u538B\u7F29\u3002\u8BF7\u786E\u4FDD\u5DF2\u914D\u7F6E provider\u3002";throw this.emitLog("error","\u274C \u538B\u7F29\u5931\u8D25",f),new Error(f)}try{if(h=await Ji({session:e,profile:this.compatProfile,llmProvider:this.llmProvider,model:this.model,onProgress:(f,y)=>{let b={analyzing:"\u25C6 \u5206\u6790\u4E2D",summarizing:"\u26A1 \u751F\u6210\u6458\u8981",saving:"\u25B8 \u4FDD\u5B58\u4E2D"};this.emitCompacting(b[f],y||"");}}),h){await this.sessionSync.loadHistory();let y=(await e.getTimeline()).filter(O=>O.item.type==="message"),b=ns(this.memory.getAll()),_=h.llmTokensUsed!==void 0;this.emitEvent({type:"context_compaction",status:"completed",originalMessages:d.length,keptMessages:y.length,droppedMessages:_?0:h.removedMessages,compressedMessages:_?h.removedMessages:0,originalTokens:n,finalTokens:b.totalTokens,budgetTokens:l,useLLM:_,timestamp:Date.now()});let v=(h.estimatedTokensSaved/1e3).toFixed(1),k=h.llmTokensUsed?` (\u6D88\u8017 ${h.llmTokensUsed} tokens)`:"",R=`\u79FB\u9664 ${h.removedMessages} \u6761\u5386\u53F2\uFF0C\u4FDD\u7559 ${h.keptMessages} \u6761\u8FD1\u671F\u6D88\u606F\uFF0C\u8282\u7701\u7EA6 ${v}K tokens${k}`;if(h.detailedStats){let{before:O,after:W,saved:F}=h.detailedStats,S=C=>(C/1e3).toFixed(1)+"K";R+=`
1788
1788
 
1789
1789
  \u25A0 \u8BE6\u7EC6\u7EDF\u8BA1\uFF1A`,R+=`
1790
1790
  \u250C\u2500 \u538B\u7F29\u524D\uFF1A`,R+=`
@@ -1796,17 +1796,17 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
1796
1796
  \u2502 \u603B\u8BA1: ${S(W.totalTokens)}`,R+=`
1797
1797
  \u2514\u2500 \u8282\u7701\uFF1A`,R+=`
1798
1798
  User: ${S(F.userTokens)} \u2022 Assistant: ${S(F.assistantTokens)} \u2022 Tool: ${S(F.toolTokens)}`,R+=`
1799
- \u51C0\u8282\u7701: ${S(F.totalTokens)}`;}this.emitCompacting("\u2713 LLM \u538B\u7F29\u5B8C\u6210",R);}else this.emitCompacting("\u2139 \u65E0\u9700\u538B\u7F29","Context \u4F7F\u7528\u91CF\u5728\u9884\u7B97\u8303\u56F4\u5185");}catch(f){throw this.emitLog("error","\u274C LLM \u538B\u7F29\u5931\u8D25",f?.message||String(f)),f}}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.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};var cf="ark.cn-beijing.volces.com";function uf(r){return r.includes("opus-4-5")||r.includes("opus-4.5")||r.endsWith("-thinking")}function Jo(r){return r.includes("doubao-seed")}function Ko(r){return !!r&&r.includes(cf)}function pf(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function df(r){let e=r?.getProvider?.();return e instanceof Os?e:void 0}function mf(r){let e=r?.getProvider?.();return e instanceof Ls?e:void 0}function hf(r){let{model:e,baseUrl:t,openaiProvider:s,anthropicProvider:n,doubaoProvider:i,geminiProvider:o}=r,a={openai:s,anthropic:n,doubao:i,gemini:o},l=!!s&&Ko(t)&&Jo(e);return (n||i||l)&&(a.setThinkingMode=u=>{if(i&&i.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let p=u==="auto"?"enabled":u;n.setThinking({type:p});}}),a}function ru(r){let{provider:e,model:t,sessionId:s}=r,n=e.protocol,i=e.models?.find(m=>m.name===t),o=e.baseUrl||void 0,a,l,c,u,p;if(n==="openai"||n==="openai-responses"||n==="kimi"){let m={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:i,doubaoThinking:Ko(o)&&Jo(t)?{type:"enabled"}:void 0},h=Ds.createAdapter(n,m);a=h,l=pf(h),l&&Ko(o)&&Jo(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let m={...e,defaultModel:t,lastSelectedModel:t},h=Ds.createAdapter(n,m);a=h,c=df(h),c&&uf(t)&&c.setThinking({type:"enabled"});}else if(n==="anthropic-openai"){let m=e.urlSuffix||"/v1/messages",h={apiKey:e.apiKey,baseUrl:o,defaultModel:t,apiEndpoint:m,streamFormat:"anthropic",sessionId:s,retry:e.retry,modelConfig:i};l=new Ct(h),a=l;}else if(n==="doubao")u=new ei({apiKey:e.apiKey,baseUrl:o,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),a=u;else if(n==="gemini"){let m={...e,defaultModel:t,lastSelectedModel:t},h=Ds.createAdapter(n,m);a=h,p=mf(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=hf({model:t,baseUrl:o,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:p});return {llmProvider:a,controls:d}}function iu(r){return new Wr({llmProvider:r.llmProvider,model:r.model,tools:r.tools,memory:r.memory,config:r.config,agentName:r.agentName,agentDescription:r.agentDescription,instructions:r.instructions,contextInjection:r.contextInjection,plannerMode:r.plannerMode,structuredOutput:r.structuredOutput,providerName:r.providerName,contextWindow:r.contextWindow,tailTokenBudget:r.tailTokenBudget,maxInputTokensOverride:r.maxInputTokensOverride,toolInputGuardrails:r.toolInputGuardrails??$c,toolOutputGuardrails:r.toolOutputGuardrails??Nc,compressionMode:r.compressionMode,workspacePath:r.workspacePath,permissionManager:r.permissionManager,disableSystemPrompt:r.disableSystemPrompt})}function ou(r){return new ri({runner:r.runner,memory:r.memory,sessionManager:r.sessionManager||new Et,sessionEnabled:r.sessionEnabled??false,workDir:r.workDir,model:r.model,memoryPressure:r.memoryPressure,compatProfile:r.compatProfile,systemPrompt:r.systemPrompt,setSandboxMode:r.setSandboxMode,llmProvider:r.llmProvider})}function au(r){return new Gs(r)}le();async function Vo(r){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:i,instructions:o,systemPrompt:a,agentName:l,agentDescription:c,permissionManager:u,tools:p,memory:d,memorySize:m,agentConfig:h,contextInjection:f,plannerMode:y,structuredOutput:b,toolInputGuardrails:_,toolOutputGuardrails:v,compressionMode:k,platformServices:R,sessionManager:O,sessionEnabled:W,disableSystemPrompt:F}=r,S=d??au(m??50),C=typeof o=="string"?o:"[Function]";g.info("HOST_FACTORY",`Creating host with instructions length: ${C.length}`),g.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${C.includes("\u534F\u4F5C\u6A21\u5F0F")}`),g.info("HOST_FACTORY",`instructions contains delegate_task: ${C.includes("delegate_task")}`),g.debug("HOST_FACTORY",`instructions preview: ${C.substring(0,300)}`);let{llmProvider:w,controls:T}=ru({provider:t,model:s.model,sessionId:e}),M=s.compatProfile??null,B=M?new Wn(M):void 0,E=p??await Ro(n,R),L=h??{maxIterations:0,temperature:.7},N=iu({llmProvider:w,model:s.model,tools:E,memory:S,config:L,agentName:l,agentDescription:c,instructions:o,contextInjection:f,plannerMode:y,structuredOutput:b,providerName:s.providerName,contextWindow:M?.contextWindow,tailTokenBudget:M?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:_,toolOutputGuardrails:v,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F});return {host:ou({runner:N,memory:S,sessionManager:O??new Et,sessionEnabled:W??false,workDir:i,model:s.model,memoryPressure:B,compatProfile:M,systemPrompt:a??(typeof o=="string"?o:""),llmProvider:w}),controls:T,llmProvider:w,runner:N,memory:S}}var Yo=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new Gn;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:i,workspacePath:o,workDir:a,instructions:l,systemPrompt:c,agentName:u,agentDescription:p,permissionManager:d,tools:m,memory:h,memorySize:f,agentConfig:y,contextInjection:b,plannerMode:_,structuredOutput:v,toolInputGuardrails:k,toolOutputGuardrails:R,compressionMode:O,sessionManager:W,sessionEnabled:F,disableSystemPrompt:S,onHostCreated:C}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:w,controls:T,llmProvider:M,runner:B,memory:E}=await Vo({sessionId:t,provider:n,llmConfig:i,workspacePath:o,workDir:a,instructions:l,systemPrompt:c,agentName:u,agentDescription:p,permissionManager:d,tools:m,memory:h,memorySize:f,agentConfig:y,contextInjection:b,plannerMode:_,structuredOutput:v,toolInputGuardrails:k,toolOutputGuardrails:R,compressionMode:O,platformServices:this.platformServices,sessionManager:W,sessionEnabled:F,disableSystemPrompt:S});return C?.({host:w,controls:T,llmProvider:M,runner:B,memory:E}),w}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:i,onEvent:o,...a}=e,l=await this.getOrCreateHost(a);i?.(l);let c=o?l.on(o):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function lu(r){let e=r.initialProviderId,t=r.initialModelName,s=r.routeConfig,n=0,i=null,o=s?s.routes.filter(a=>a.enabled).length:r.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await r.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:i})}catch(a){let l=a instanceof Error?a:new Error(String(a));if(i=l,r.modelRouter&&e&&r.modelRouter.recordFailure(e,l),!!!(r.autoFailover&&r.resolvedRoute&&r.fallbackDecider&&r.modelAlias&&e))throw l;let u=r.fallbackDecider.shouldFallback(r.modelAlias,e,l,r.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(r.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(p=>p.providerId!==u.event.fromProviderId)}),r.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=o)throw r.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&r.onExhausted?.(u.reason),l}}var Nn=240,ii=2e3;function ut(r,e){return r?r.length<=e?r:r.slice(0,e).trimEnd()+"...":""}var oi=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},Xo=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:i=Date.now(),isAutoRouted:o,routeConfig:a,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:p,buildHostConfig:d,onHostReady:m,onRuntimeEvent:h,onStatus:f,onRouteResolved:y,onRetry:b}=e,_=e.providerId,v=e.modelName,k=null,R=this.actionLog?.createRunId();if(this.actionLog){let F=ut(s,Nn);this.actionLog.record({type:"run_start",sessionId:t,runId:R,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:ut(s,ii),promptLength:s.length,attachments:n?.attachments?.map(S=>({type:S.type,name:S.name,path:S.path}))}});}o&&a&&l&&(k=l.resolveProvider(a.modelAlias),k&&(_=k.providerId,v=k.modelName,y?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${_}`)));let O=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let W=false;try{let F=await lu({modelAlias:a?.modelAlias,initialProviderId:_,initialModelName:v,routeConfig:a,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:a?.autoFailover===!0,onRetry:({decision:S})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:R,actor:"system",summary:S?.event?`Fallback: ${S.event.fromProviderId} -> ${S.event.toProviderId}`:"Fallback: switching provider",data:{from:S?.event?.fromProviderId,to:S?.event?.toProviderId,reason:S?.reason}}),b?.(S);},onExhausted:S=>{f?.("error",`All providers exhausted: ${S}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`All providers exhausted: ${ut(S,Nn)}`,data:{reason:S}});},runAttempt:async S=>{let C=this.resolveProvider(S.providerId,S.modelName);if(!C.provider||!C.llmConfig)throw new oi("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${C.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:R,actor:"system",summary:S.isRetry?`Retry ${S.attempt}: ${C.llmConfig.model}`:`Run: ${C.llmConfig.model}`,data:{providerId:C.provider.id,providerName:C.llmConfig.providerName,model:C.llmConfig.model,attempt:S.attempt,isRetry:S.isRetry,previousError:S.previousError?.message}});let w=d(C.provider,C.llmConfig),T={contextUsed:0,startTime:Date.now(),provider:C.llmConfig.providerName||C.provider.id||"unknown",model:C.llmConfig.model};return {summary:await this.hostService.runTask({...w,prompt:s,metadata:O,abortSignal:p,onHostReady:m,onEvent:B=>{if(this.actionLog){let E=this.buildActionLogEntry(B,t,R);E&&this.actionLog.record(E);}u?.emit(t,B,T),h?.(B,T);}}),contextUsed:T.contextUsed,providerId:C.provider.id}}});if(k&&F.providerId&&l){let S=Date.now()-i;l.recordSuccess(F.providerId,S),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),W=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let S=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`Run error: ${ut(S,Nn)}`,data:{message:S}});}throw F}finally{if(this.checkpointService&&!W)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=i=>this.actionLog?.formatFilePath(i)??i;switch(e.type){case "tool_call_start":{let i=e.targetPath?n(e.targetPath):void 0,o=i?`Tool start: ${e.name} (${i})`:`Tool start: ${e.name}`,a=e.args?ut(JSON.stringify(e.args),ii):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:o,files:i?[i]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:i,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:a}}}case "tool_call_end":{let i=e.targetPath?n(e.targetPath):void 0,o=i?`Tool ${e.success?"done":"failed"}: ${e.name} (${i})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,a=e.output?ut(e.output,ii):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:o,files:i?[i]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:a,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:i}}}case "file_stream":{if(!e.isComplete)return null;let i=n(e.filePath),o=e.additions||e.removals?`File updated: ${i} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${i}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:o,files:[i],data:{filePath:i,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let i=n(e.filePath),o=`File edited: ${i}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:o,files:[i],data:{filePath:i,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:ut(e.oldString,200),newPreview:ut(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let i=n(e.filePath),o=`File written: ${i}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:o,files:[i],data:{filePath:i,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let i=e.plan.length,o=e.plan.filter(c=>c.status==="completed").length,a=e.plan.filter(c=>c.status==="in_progress").length,l=i-o-a;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${o} done, ${a} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:ut(e.output,ii),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${ut(e.message,Nn)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${ut(e.message,Nn)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};var gf=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".tiff",".tif",".mp3",".mp4",".avi",".mov",".wmv",".flv",".wav",".ogg",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".app",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".ttf",".otf",".woff",".woff2",".eot",".jar",".war",".class",".pyc",".pyo",".o",".a",".lib",".node",".wasm",".asar"],cu={ignoredPatterns:["**/.git/**","**/.cdundo/**","**/.svn/**","**/.hg/**","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/*.log","**/*.tmp","**/*.temp","**/*.swp","**/*.swo","**/*~","**/node_modules/**","**/bower_components/**","**/.npm/**","**/.yarn/**","**/.pnpm-store/**","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/dist/**","**/build/**","**/out/**","**/output/**","**/.output/**","**/target/**","**/bin/**","**/obj/**","**/*.bundle.js","**/*.bundle.css","**/*.min.js","**/*.min.css","**/.next/**","**/.nuxt/**","**/.svelte-kit/**","**/.astro/**","**/.vercel/**","**/.netlify/**","**/.turbo/**","**/.cache/**","**/.parcel-cache/**","**/.webpack/**","**/.vite/**","**/coverage/**","**/.nyc_output/**","**/jest_cache/**","**/.jest/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.pyd","**/.venv/**","**/venv/**","**/env/**","**/.env/**","**/virtualenv/**","**/.Python","**/pip-wheel-metadata/**","**/*.egg-info/**","**/.eggs/**","**/site-packages/**","**/target/**","**/.gradle/**","**/gradle/**","**/.m2/**","**/*.class","**/*.jar","**/*.war","**/*.ear","**/target/**","**/*.rlib","**/Cargo.lock","**/vendor/**","**/go.sum","**/bin/**","**/obj/**","**/packages/**","**/.nuget/**","**/*.dll","**/*.exe","**/*.pdb","**/vendor/bundle/**","**/.bundle/**","**/Gemfile.lock","**/vendor/**","**/composer.lock","**/.idea/**","**/.vscode/**","**/*.sublime-*","**/.project","**/.classpath","**/.settings/**","**/*.iml","**/.env.local","**/.env.*.local","**/.env.development","**/.env.production","**/*.sqlite","**/*.sqlite3","**/*.db","**/npm-debug.log*","**/yarn-debug.log*","**/yarn-error.log*","**/.pnpm-debug.log*"],maxCheckpoints:50,checkpointTTL:864e5,enabled:true,largeFileThreshold:1048576,veryLargeFileThreshold:10485760,binaryExtensions:gf};var ai=class{workspacePath;shadowDir;shadowGitDir;git;watcher=null;changeBuffer=[];isWatching=false;currentSessionId=null;currentMessageIndex=0;config;changeCallbacks=new Set;initialized=false;debounceMap=new Map;DEBOUNCE_MS=100;gitOperationLock=Promise.resolve();GIT_RETRY_ATTEMPTS=3;GIT_RETRY_DELAY_MS=500;constructor(e={}){this.config={...cu,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=uu();}async init(e){if(this.initialized&&this.workspacePath===e){console.log("[ShadowGit] Already initialized for:",e);return}this.workspacePath=e,this.shadowDir=Y.join(e,".cdundo"),this.shadowGitDir=Y.join(this.shadowDir,".git"),console.log("[ShadowGit] Initializing for workspace:",e),await Z.mkdir(this.shadowDir,{recursive:true}),await this.addToGitignore();let t=vn.existsSync(this.shadowGitDir);this.git=uu(this.shadowDir),t?console.log("[ShadowGit] Using existing shadow git repository"):(await this.git.init(),await this.git.addConfig("user.email","checkpoint@neox.local"),await this.git.addConfig("user.name","Neox Checkpoint"),console.log("[ShadowGit] Created new shadow git repository")),await this.syncWorkspaceToShadow(),await this.withGitLock(async()=>{if((await this.git.status()).files.length>0||!t){await this.git.add(".");try{await this.git.commit("Initial checkpoint - workspace sync"),console.log("[ShadowGit] Created initial checkpoint");}catch{console.log("[ShadowGit] No changes to commit for initial checkpoint");}}}),this.initialized=true,console.log("[ShadowGit] Initialization complete");}beforeCheckpointId=null;async startWatching(e,t=0){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized. Call init() first.");if(this.isWatching)return console.log("[ShadowGit] Already watching, updating session info"),console.log("[ShadowGit] Clearing changeBuffer (was:",this.changeBuffer.length,"items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[],this.beforeCheckpointId;console.log("[ShadowGit] Starting new watch, clearing changeBuffer (was:",this.changeBuffer.length,"items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[];try{await this.withGitLock(async()=>{await this.syncWorkspaceToShadow(),await this.git.add("."),(await this.git.status()).files.length>0&&await this.git.commit(`Before session ${e} - auto checkpoint`);let i=await this.git.log({maxCount:1});this.beforeCheckpointId=i.latest?.hash||null,console.log("[ShadowGit] Created before-checkpoint:",this.beforeCheckpointId);});}catch(n){console.error("[ShadowGit] Failed to create before-checkpoint:",n);try{let i=await this.git.log({maxCount:1});this.beforeCheckpointId=i.latest?.hash||null;}catch{this.beforeCheckpointId=null;}}console.log("[ShadowGit] Starting file watcher for session:",e);let s=n=>!!(n.includes(".cdundo")||n.includes("/.cdundo/")||n.includes("node_modules")||n.includes("/node_modules/")||n.includes("/.git/")||n.endsWith("/.git")||n.includes("/dist/")||n.includes("/build/")||n.includes("/.next/")||n.includes(".DS_Store")||n.includes(".swp")||n.includes(".swo")||n.endsWith("package-lock.json")||n.endsWith("yarn.lock")||n.endsWith("pnpm-lock.yaml"));return this.watcher=pu.watch(this.workspacePath,{ignored:s,persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},followSymlinks:false}),this.watcher.on("add",n=>this.handleChange("create",n)).on("change",n=>this.handleChange("modify",n)).on("unlink",n=>this.handleChange("delete",n)).on("addDir",n=>this.handleChange("mkdir",n)).on("unlinkDir",n=>this.handleChange("rmdir",n)).on("error",n=>console.error("[ShadowGit] Watcher error:",n)),this.isWatching=true,console.log("[ShadowGit] File watcher started"),this.beforeCheckpointId}getBeforeCheckpointId(){return this.beforeCheckpointId}async stopWatching(){this.watcher&&(await this.watcher.close(),this.watcher=null),this.isWatching=false,this.currentSessionId=null;for(let e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.changeBuffer=[],console.log("[ShadowGit] File watcher stopped");}handleChange(e,t){if(!this.isWatching)return;let s=Y.relative(this.workspacePath,t);if(this.shouldIgnorePath(s))return;let n=`${e}:${s}`,i=this.debounceMap.get(n);i&&clearTimeout(i),this.debounceMap.set(n,setTimeout(()=>{this.recordChange(e,s,t),this.debounceMap.delete(n);},this.DEBOUNCE_MS));}isBinaryFile(e){let t=Y.extname(e).toLowerCase();return this.config.binaryExtensions.includes(t)}async detectBinaryContent(e){try{let t=await Z.open(e,"r"),s=Buffer.alloc(8192),{bytesRead:n}=await t.read(s,0,8192,0);await t.close();for(let i=0;i<n;i++)if(s[i]===0)return !0;return !1}catch{return false}}async recordChange(e,t,s){let n={type:e,path:t,timestamp:Date.now()},i=this.isBinaryFile(t);n.isBinary=i;let o=0,a=false,l=false;if(e==="create"||e==="modify")try{let p=await Z.stat(s);if(p.isFile()&&(o=p.size,n.size=o,a=o>this.config.veryLargeFileThreshold,l=o>this.config.largeFileThreshold,n.isLargeFile=l,!i&&!l)){let d=await this.detectBinaryContent(s);n.isBinary=d;}}catch{}if((e==="delete"||e==="modify")&&!n.isBinary&&!l){let p=Y.join(this.shadowDir,t);try{let d=await Z.stat(p);d.isFile()&&d.size<this.config.largeFileThreshold&&(n.previousContent=await Z.readFile(p,"utf-8"));}catch{}}if((e==="create"||e==="modify")&&!n.isBinary&&!l)try{n.newContent=await Z.readFile(s,"utf-8");}catch{}this.changeBuffer.push(n),a?console.log(`[ShadowGit] Skipping very large file (${(o/1024/1024).toFixed(1)}MB): ${t}`):await this.syncFileToShadow(t,e,s);for(let p of this.changeCallbacks)try{p(n);}catch(d){console.error("[ShadowGit] Callback error:",d);}let c=o?` (${this.formatFileSize(o)})`:"",u=n.isBinary?" [binary]":"";console.log(`[ShadowGit] Recorded ${e}: ${t}${c}${u}`);}formatFileSize(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}async syncFileToShadow(e,t,s){let n=Y.join(this.shadowDir,e),i=Y.dirname(n);try{switch(t){case "create":case "modify":await Z.mkdir(i,{recursive:!0}),await Z.copyFile(s,n);break;case "delete":await Z.unlink(n).catch(()=>{});break;case "mkdir":await Z.mkdir(n,{recursive:!0});break;case "rmdir":await Z.rm(n,{recursive:!0,force:!0}).catch(()=>{});break}}catch(o){console.error(`[ShadowGit] Failed to sync ${e}:`,o);}}async syncWorkspaceToShadow(){console.log("[ShadowGit] Syncing workspace to shadow...");let e=0,t=0,s=0,n=async(i,o)=>{let a;try{a=await Z.readdir(i,{withFileTypes:!0});}catch{return}for(let l of a){let c=Y.join(i,l.name),u=Y.join(o,l.name),p=Y.relative(this.workspacePath,c);if(!this.shouldIgnore(p)){if(l.isDirectory())await Z.mkdir(u,{recursive:true}),await n(c,u);else if(l.isFile())try{let d=await Z.stat(c);if(d.size>this.config.veryLargeFileThreshold){t++,console.log(`[ShadowGit] Skipping very large file: ${p} (${this.formatFileSize(d.size)})`);continue}await Z.mkdir(Y.dirname(u),{recursive:!0}),await Z.copyFile(c,u),e++,s+=d.size;}catch{console.warn(`[ShadowGit] Failed to sync file: ${p}`);}}}};await n(this.workspacePath,this.shadowDir),console.log(`[ShadowGit] Workspace sync complete: ${e} files (${this.formatFileSize(s)}), ${t} large files skipped`);}shouldIgnorePath(e){return !!(e.startsWith(".cdundo")||e.includes("/.cdundo/")||e.includes("node_modules/")||e.startsWith("node_modules")||e.startsWith(".git")||e.includes("/.git/")||e.startsWith("dist/")||e.includes("/dist/")||e.startsWith("build/")||e.includes("/build/")||e.startsWith(".next/")||e.includes("/.next/")||e.includes(".DS_Store")||e.endsWith(".swp")||e.endsWith(".swo")||e.endsWith("package-lock.json")||e.endsWith("yarn.lock")||e.endsWith("pnpm-lock.yaml"))}shouldIgnore(e){if(this.shouldIgnorePath(e))return true;for(let t of this.config.ignoredPatterns)if(this.matchPattern(e,t))return true;return false}matchPattern(e,t){let s=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`).test(e)}async createCheckpoint(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");return console.log("[ShadowGit] Creating checkpoint:",e),await this.withGitLock(async()=>{if(await this.git.add("."),(await this.git.status()).files.length===0&&this.changeBuffer.length===0)return console.log("[ShadowGit] No changes to checkpoint"),{id:(await this.git.log({maxCount:1})).latest?.hash||"no-changes",label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[],stats:{created:0,modified:0,deleted:0,directories:0,total:0}};let s=this.calculateStats(),n=this.formatCommitMessage(e,s),i=await this.git.commit(n),o={id:i.commit,label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[...this.changeBuffer],stats:s};return this.changeBuffer=[],this.currentMessageIndex++,console.log(`[ShadowGit] Checkpoint created: ${i.commit} (${s.total} changes)`),await this.cleanupOldCheckpoints(),o})}lastRollbackFromId=null;getLastRollbackFromId(){return this.lastRollbackFromId}async rollbackTo(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");console.log("[ShadowGit] Rolling back to checkpoint:",e);let t=[],s=[],n;try{return await this.withGitLock(async()=>{await this.git.add(".");let i=await this.git.status();if(console.log("[ShadowGit] Current git status before rollback:",i.files.length,"files"),i.files.length>0)try{await this.git.commit("Changes before rollback (for reapply)"),console.log("[ShadowGit] Created commit for rollback comparison");}catch{console.log("[ShadowGit] No changes to commit (might be already committed)");}n=(await this.git.log({maxCount:1})).latest?.hash,this.lastRollbackFromId=n||null,console.log("[ShadowGit] Saved reapply checkpoint:",n);let a=await this.git.diff([e,"HEAD","--name-status"]),l=a.trim().split(`
1800
- `).filter(c=>c.trim());console.log("[ShadowGit] Diff output:",a),console.log("[ShadowGit] Files to rollback:",l.length);for(let c of l){let[u,...p]=c.split(" "),d=p.join(" ");if(!d)continue;let m=Y.join(this.workspacePath,d),h=Y.join(this.shadowDir,d);console.log(`[ShadowGit] Processing: status=${u}, file=${d}`);try{switch(u){case "A":console.log(`[ShadowGit] Deleting added file: ${m}`),await Z.unlink(m).catch(f=>{console.log(`[ShadowGit] Failed to delete workspace file: ${f}`);}),await Z.unlink(h).catch(()=>{}),t.push(`deleted: ${d}`);break;case "M":console.log(`[ShadowGit] Restoring modified file: ${d}`),await this.git.checkout([e,"--",d]),await Z.mkdir(Y.dirname(m),{recursive:!0}),await Z.copyFile(h,m),t.push(`restored: ${d}`);break;case "D":console.log(`[ShadowGit] Recovering deleted file: ${d}`),await this.git.checkout([e,"--",d]),await Z.mkdir(Y.dirname(m),{recursive:!0}),await Z.copyFile(h,m),t.push(`recovered: ${d}`);break;default:console.log(`[ShadowGit] Unhandled status ${u} for ${d}`);}}catch(f){console.error(`[ShadowGit] Error processing ${d}:`,f),s.push(`${d}: ${f}`);}}await this.git.reset(["--hard",e]),this.changeBuffer=[],console.log(`[ShadowGit] Rollback complete: ${t.length} restored, ${s.length} errors`);}),{success:s.length===0,restored:t,errors:s,reapplyCheckpointId:n}}catch(i){return console.error("[ShadowGit] Rollback failed:",i),{success:false,restored:t,errors:[String(i)],reapplyCheckpointId:n}}}async rollbackSingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};console.log("[ShadowGit] Rolling back single file:",e);let t=this.beforeCheckpointId;if(!t)return {success:false,error:"No before checkpoint available. Make sure startWatching() was called before this message."};let s=Y.join(this.workspacePath,e),n=Y.join(this.shadowDir,e);try{return await this.withGitLock(async()=>{let i=await this.git.diff([t,"HEAD","--name-status","--",e]);if(console.log("[ShadowGit] File diff status:",i.trim()),!i.trim())return console.log("[ShadowGit] File has no changes since before checkpoint"),{success:!0};let[o]=i.trim().split(" ");switch(o){case "A":console.log("[ShadowGit] File was added after checkpoint, deleting:",e);try{return await Z.unlink(s),await Z.unlink(n).catch(()=>{}),{success:!0}}catch(a){return {success:!1,error:`Failed to delete file: ${a}`}}case "M":case "D":console.log("[ShadowGit] Restoring file from before checkpoint:",e);try{return await this.git.checkout([t,"--",e]),await Z.mkdir(Y.dirname(s),{recursive:!0}),await Z.copyFile(n,s),console.log("[ShadowGit] Successfully rolled back file:",e),{success:!0}}catch(a){return {success:!1,error:`Failed to restore file: ${a}`}}default:return console.log("[ShadowGit] Unhandled status:",o),{success:!1,error:`Unhandled file status: ${o}`}}})}catch(i){return console.error("[ShadowGit] Failed to rollback single file:",i),{success:false,error:String(i)}}}async reapplySingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};console.log("[ShadowGit] Reapplying single file:",e);try{return await this.withGitLock(async()=>{let t=Y.join(this.workspacePath,e),s=Y.join(this.shadowDir,e);try{return await this.git.checkout(["HEAD","--",e]),await Z.mkdir(Y.dirname(t),{recursive:!0}),await Z.copyFile(s,t),console.log("[ShadowGit] Successfully reapplied file:",e),{success:!0}}catch(n){return {success:!1,error:`File not found in HEAD: ${n}`}}})}catch(t){return console.error("[ShadowGit] Failed to reapply single file:",t),{success:false,error:String(t)}}}async getCheckpoints(e=50,t){if(!this.initialized)return [];try{let s=t?e*3:e,i=(await this.git.log({maxCount:s})).all.map(o=>{let a=this.parseCommitMessage(o.message);return {id:o.hash,label:a.label,timestamp:new Date(o.date).getTime(),sessionId:a.sessionId,messageIndex:a.messageIndex,stats:a.stats}});return t&&(i=i.filter(o=>o.sessionId===t)),i.slice(0,e)}catch(s){return console.error("[ShadowGit] Failed to get checkpoints:",s),[]}}async getDiff(e,t="HEAD"){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");await this.git.diff([e,t,"--stat","--numstat"]);let n=await this.git.diffSummary([e,t]),i=n.files.map(o=>{let a="insertions"in o&&"deletions"in o;return {path:o.file,status:this.getFileStatus(o),additions:a?o.insertions:0,deletions:a?o.deletions:0,lines:[]}});return {checkpointId:e,files:i,stats:{filesChanged:n.changed,additions:n.insertions,deletions:n.deletions}}}getChangeBuffer(){return this.isWatching?[...this.changeBuffer]:(console.log("[ShadowGit] getChangeBuffer called but not watching, returning empty array"),[])}getCurrentStats(){if(!this.isWatching)return console.log("[ShadowGit] getCurrentStats called but not watching, returning empty stats"),{created:0,modified:0,deleted:0,directories:0,total:0};let e=this.calculateStats();return console.log("[ShadowGit] getCurrentStats called, changeBuffer length:",this.changeBuffer.length),this.changeBuffer.length>0&&console.log("[ShadowGit] changeBuffer contents:",this.changeBuffer.map(t=>`${t.type}: ${t.path}`)),e}onFileChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}isInitialized(){return this.initialized}isActive(){return this.isWatching}getShadowDir(){return this.shadowDir}calculateStats(){let e={created:0,modified:0,deleted:0,directories:0,total:0};for(let t of this.changeBuffer)switch(t.type){case "create":e.created++;break;case "modify":e.modified++;break;case "delete":e.deleted++;break;case "mkdir":case "rmdir":e.directories++;break}return e.total=e.created+e.modified+e.deleted+e.directories,e}formatCommitMessage(e,t){let s=this.currentSessionId?`
1799
+ \u51C0\u8282\u7701: ${S(F.totalTokens)}`;}this.emitCompacting("\u2713 LLM \u538B\u7F29\u5B8C\u6210",R);}else this.emitCompacting("\u2139 \u65E0\u9700\u538B\u7F29","Context \u4F7F\u7528\u91CF\u5728\u9884\u7B97\u8303\u56F4\u5185");}catch(f){throw this.emitLog("error","\u274C LLM \u538B\u7F29\u5931\u8D25",f?.message||String(f)),f}}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.recentToolCalls.clear(),this.batchDetector.reset(),console.log("[AgentRuntimeHost] Disposed");}};var df="ark.cn-beijing.volces.com";function mf(r){return r.includes("opus-4-5")||r.includes("opus-4.5")||r.endsWith("-thinking")}function Ki(r){return r.includes("doubao-seed")}function Vi(r){return !!r&&r.includes(df)}function hf(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function gf(r){let e=r?.getProvider?.();return e instanceof Ls?e:void 0}function ff(r){let e=r?.getProvider?.();return e instanceof Ds?e:void 0}function yf(r){let{model:e,baseUrl:t,openaiProvider:s,anthropicProvider:n,doubaoProvider:o,geminiProvider:i}=r,a={openai:s,anthropic:n,doubao:o,gemini:i},l=!!s&&Vi(t)&&Ki(e);return (n||o||l)&&(a.setThinkingMode=u=>{if(o&&o.setThinking({type:u}),l&&s&&s.setDoubaoThinking({type:u}),n){let p=u==="auto"?"enabled":u;n.setThinking({type:p});}}),a}function au(r){let{provider:e,model:t,sessionId:s}=r,n=e.protocol,o=e.models?.find(m=>m.name===t),i=e.baseUrl||void 0,a,l,c,u,p;if(n==="openai"||n==="openai-responses"||n==="kimi"){let m={...e,defaultModel:t,lastSelectedModel:t,apiEndpoint:e.urlSuffix,sessionId:s,modelConfig:o,doubaoThinking:Vi(i)&&Ki(t)?{type:"enabled"}:void 0},h=$s.createAdapter(n,m);a=h,l=hf(h),l&&Vi(i)&&Ki(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let m={...e,defaultModel:t,lastSelectedModel:t},h=$s.createAdapter(n,m);a=h,c=gf(h),c&&mf(t)&&c.setThinking({type:"enabled"});}else if(n==="anthropic-openai"){let m=e.urlSuffix||"/v1/messages",h={apiKey:e.apiKey,baseUrl:i,defaultModel:t,apiEndpoint:m,streamFormat:"anthropic",sessionId:s,retry:e.retry,modelConfig:o};l=new Ct(h),a=l;}else if(n==="doubao")u=new to({apiKey:e.apiKey,baseUrl:i,defaultModel:t,thinking:{type:"enabled"},retry:e.retry}),a=u;else if(n==="gemini"){let m={...e,defaultModel:t,lastSelectedModel:t},h=$s.createAdapter(n,m);a=h,p=ff(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=yf({model:t,baseUrl:i,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:p});return {llmProvider:a,controls:d}}function lu(r){return new Hr({llmProvider:r.llmProvider,model:r.model,tools:r.tools,memory:r.memory,config:r.config,agentName:r.agentName,agentDescription:r.agentDescription,instructions:r.instructions,contextInjection:r.contextInjection,plannerMode:r.plannerMode,structuredOutput:r.structuredOutput,providerName:r.providerName,contextWindow:r.contextWindow,tailTokenBudget:r.tailTokenBudget,maxInputTokensOverride:r.maxInputTokensOverride,toolInputGuardrails:r.toolInputGuardrails??Uc,toolOutputGuardrails:r.toolOutputGuardrails??jc,compressionMode:r.compressionMode,workspacePath:r.workspacePath,permissionManager:r.permissionManager,disableSystemPrompt:r.disableSystemPrompt})}function cu(r){return new oo({runner:r.runner,memory:r.memory,sessionManager:r.sessionManager||new Et,sessionEnabled:r.sessionEnabled??false,workDir:r.workDir,model:r.model,memoryPressure:r.memoryPressure,compatProfile:r.compatProfile,systemPrompt:r.systemPrompt,setSandboxMode:r.setSandboxMode,llmProvider:r.llmProvider})}function uu(r){return new Bs(r)}le();async function Yi(r){let{sessionId:e,provider:t,llmConfig:s,workspacePath:n,workDir:o,instructions:i,systemPrompt:a,agentName:l,agentDescription:c,permissionManager:u,tools:p,memory:d,memorySize:m,agentConfig:h,contextInjection:f,plannerMode:y,structuredOutput:b,toolInputGuardrails:_,toolOutputGuardrails:v,compressionMode:k,platformServices:R,sessionManager:O,sessionEnabled:W,disableSystemPrompt:F}=r,S=d??uu(m??50),C=typeof i=="string"?i:"[Function]";g.info("HOST_FACTORY",`Creating host with instructions length: ${C.length}`),g.info("HOST_FACTORY",`instructions contains \u534F\u4F5C\u6A21\u5F0F: ${C.includes("\u534F\u4F5C\u6A21\u5F0F")}`),g.info("HOST_FACTORY",`instructions contains delegate_task: ${C.includes("delegate_task")}`),g.debug("HOST_FACTORY",`instructions preview: ${C.substring(0,300)}`);let{llmProvider:w,controls:T}=au({provider:t,model:s.model,sessionId:e}),M=s.compatProfile??null,B=M?new Hn(M):void 0,E=p??await Ei(n,R),L=h??{maxIterations:0,temperature:.7},N=lu({llmProvider:w,model:s.model,tools:E,memory:S,config:L,agentName:l,agentDescription:c,instructions:i,contextInjection:f,plannerMode:y,structuredOutput:b,providerName:s.providerName,contextWindow:M?.contextWindow,tailTokenBudget:M?.tailTokenBudget,maxInputTokensOverride:s.maxInputTokens,toolInputGuardrails:_,toolOutputGuardrails:v,compressionMode:k,workspacePath:n,permissionManager:u,disableSystemPrompt:F});return {host:cu({runner:N,memory:S,sessionManager:O??new Et,sessionEnabled:W??false,workDir:o,model:s.model,memoryPressure:B,compatProfile:M,systemPrompt:a??(typeof i=="string"?i:""),llmProvider:w}),controls:T,llmProvider:w,runner:N,memory:S}}var Xi=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new Bn;}setWorkspace(e){this.hostController.setWorkspace(e);}getHost(e){return this.hostController.getHost(e)}hasHost(e){return this.hostController.hasHost(e)}clearHost(e){this.hostController.clearHost(e);}clearAll(){this.hostController.clearAll();}forEachHost(e){this.hostController.forEachHost(e);}async getOrCreateHost(e){let{sessionId:t,configKey:s,provider:n,llmConfig:o,workspacePath:i,workDir:a,instructions:l,systemPrompt:c,agentName:u,agentDescription:p,permissionManager:d,tools:m,memory:h,memorySize:f,agentConfig:y,contextInjection:b,plannerMode:_,structuredOutput:v,toolInputGuardrails:k,toolOutputGuardrails:R,compressionMode:O,sessionManager:W,sessionEnabled:F,disableSystemPrompt:S,onHostCreated:C}=e;return this.hostController.getOrCreateHost({sessionId:t,configKey:s,createHost:async()=>{let{host:w,controls:T,llmProvider:M,runner:B,memory:E}=await Yi({sessionId:t,provider:n,llmConfig:o,workspacePath:i,workDir:a,instructions:l,systemPrompt:c,agentName:u,agentDescription:p,permissionManager:d,tools:m,memory:h,memorySize:f,agentConfig:y,contextInjection:b,plannerMode:_,structuredOutput:v,toolInputGuardrails:k,toolOutputGuardrails:R,compressionMode:O,platformServices:this.platformServices,sessionManager:W,sessionEnabled:F,disableSystemPrompt:S});return C?.({host:w,controls:T,llmProvider:M,runner:B,memory:E}),w}})}async runTask(e){let{prompt:t,metadata:s,abortSignal:n,onHostReady:o,onEvent:i,...a}=e,l=await this.getOrCreateHost(a);o?.(l);let c=i?l.on(i):void 0;try{return await l.runTask(t,{metadata:s,abortSignal:n})}finally{c&&c();}}};async function pu(r){let e=r.initialProviderId,t=r.initialModelName,s=r.routeConfig,n=0,o=null,i=s?s.routes.filter(a=>a.enabled).length:r.resolvedRoute?.fallbackChain.length??1;for(;;)try{return await r.runAttempt({providerId:e,modelName:t,routeConfig:s,attempt:n,isRetry:n>0,previousError:o})}catch(a){let l=a instanceof Error?a:new Error(String(a));if(o=l,r.modelRouter&&e&&r.modelRouter.recordFailure(e,l),!!!(r.autoFailover&&r.resolvedRoute&&r.fallbackDecider&&r.modelAlias&&e))throw l;let u=r.fallbackDecider.shouldFallback(r.modelAlias,e,l,r.resolvedRoute.fallbackChain);if(u.shouldFallback&&u.targetProvider&&u.event){if(r.fallbackDecider.executeFallback(u),n+=1,e=u.targetProvider.providerId,t=u.targetProvider.modelName,s&&(s={...s,routes:s.routes.filter(p=>p.providerId!==u.event.fromProviderId)}),r.onRetry?.({providerId:e,modelName:t,attempt:n,decision:u}),n>=i)throw r.onExhausted?.("All providers have failed. Please try again later."),l;continue}throw u.exhausted&&r.onExhausted?.(u.reason),l}}var Fn=240,io=2e3;function ut(r,e){return r?r.length<=e?r:r.slice(0,e).trimEnd()+"...":""}var ao=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},Zi=class{hostService;checkpointService;resolveProvider;actionLog;constructor(e){this.hostService=e.hostService,this.checkpointService=e.checkpointService,this.resolveProvider=e.resolveProvider,this.actionLog=e.actionLog;}async runSession(e){let{sessionId:t,prompt:s,metadata:n,startedAt:o=Date.now(),isAutoRouted:i,routeConfig:a,modelRouter:l,fallbackDecider:c,eventHub:u,abortSignal:p,buildHostConfig:d,onHostReady:m,onRuntimeEvent:h,onStatus:f,onRouteResolved:y,onRetry:b}=e,_=e.providerId,v=e.modelName,k=null,R=this.actionLog?.createRunId();if(this.actionLog){let F=ut(s,Fn);this.actionLog.record({type:"run_start",sessionId:t,runId:R,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:ut(s,io),promptLength:s.length,attachments:n?.attachments?.map(S=>({type:S.type,name:S.name,path:S.path}))}});}i&&a&&l&&(k=l.resolveProvider(a.modelAlias),k&&(_=k.providerId,v=k.modelName,y?.(k),k.degraded&&f?.("warning",`Using degraded provider: ${_}`)));let O=n;if(this.checkpointService)try{await this.checkpointService.startMessage(t);}catch{f?.("warning","Checkpoint start failed");}let W=false;try{let F=await pu({modelAlias:a?.modelAlias,initialProviderId:_,initialModelName:v,routeConfig:a,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:a?.autoFailover===!0,onRetry:({decision:S})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:R,actor:"system",summary:S?.event?`Fallback: ${S.event.fromProviderId} -> ${S.event.toProviderId}`:"Fallback: switching provider",data:{from:S?.event?.fromProviderId,to:S?.event?.toProviderId,reason:S?.reason}}),b?.(S);},onExhausted:S=>{f?.("error",`All providers exhausted: ${S}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`All providers exhausted: ${ut(S,Fn)}`,data:{reason:S}});},runAttempt:async S=>{let C=this.resolveProvider(S.providerId,S.modelName);if(!C.provider||!C.llmConfig)throw new ao("No provider configured. Please add an API provider first.");f?.("info",`Connecting to ${C.llmConfig.model}...`),this.actionLog&&this.actionLog.record({type:"run_attempt",sessionId:t,runId:R,actor:"system",summary:S.isRetry?`Retry ${S.attempt}: ${C.llmConfig.model}`:`Run: ${C.llmConfig.model}`,data:{providerId:C.provider.id,providerName:C.llmConfig.providerName,model:C.llmConfig.model,attempt:S.attempt,isRetry:S.isRetry,previousError:S.previousError?.message}});let w=d(C.provider,C.llmConfig),T={contextUsed:0,startTime:Date.now(),provider:C.llmConfig.providerName||C.provider.id||"unknown",model:C.llmConfig.model};return {summary:await this.hostService.runTask({...w,prompt:s,metadata:O,abortSignal:p,onHostReady:m,onEvent:B=>{if(this.actionLog){let E=this.buildActionLogEntry(B,t,R);E&&this.actionLog.record(E);}u?.emit(t,B,T),h?.(B,T);}}),contextUsed:T.contextUsed,providerId:C.provider.id}}});if(k&&F.providerId&&l){let S=Date.now()-o;l.recordSuccess(F.providerId,S),c&&c.recordSuccess(F.providerId);}if(this.checkpointService)try{await this.checkpointService.finishMessage(t,"Message completed"),W=!0;}catch{f?.("warning","Checkpoint save failed");}return {summary:F.summary,contextUsed:F.contextUsed,providerId:F.providerId}}catch(F){if(this.actionLog){let S=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`Run error: ${ut(S,Fn)}`,data:{message:S}});}throw F}finally{if(this.checkpointService&&!W)try{await this.checkpointService.stopWatching();}catch{f?.("warning","Checkpoint cleanup failed");}}}buildActionLogEntry(e,t,s){if(!this.actionLog)return null;let n=o=>this.actionLog?.formatFilePath(o)??o;switch(e.type){case "tool_call_start":{let o=e.targetPath?n(e.targetPath):void 0,i=o?`Tool start: ${e.name} (${o})`:`Tool start: ${e.name}`,a=e.args?ut(JSON.stringify(e.args),io):void 0;return {type:"tool_call_start",sessionId:t,runId:s,actor:"tool",summary:i,files:o?[o]:void 0,data:{name:e.name,toolId:e.toolId,batchId:e.batchId,targetPath:o,description:e.description,equivalentCommand:e.equivalentCommand,argsPreview:a}}}case "tool_call_end":{let o=e.targetPath?n(e.targetPath):void 0,i=o?`Tool ${e.success?"done":"failed"}: ${e.name} (${o})`:`Tool ${e.success?"done":"failed"}: ${e.name}`,a=e.output?ut(e.output,io):void 0;return {type:"tool_call_end",sessionId:t,runId:s,actor:"tool",summary:i,files:o?[o]:void 0,data:{name:e.name,success:e.success,duration:e.duration,resultLength:e.resultLength,summary:e.summary,outputPreview:a,outputTruncated:e.outputTruncated,toolId:e.toolId,batchId:e.batchId,targetPath:o}}}case "file_stream":{if(!e.isComplete)return null;let o=n(e.filePath),i=e.additions||e.removals?`File updated: ${o} (+${e.additions??0}/-${e.removals??0})`:`File updated: ${o}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[o],data:{filePath:o,additions:e.additions,removals:e.removals,description:e.description,contentLength:e.content?.length??0}}}case "edit_file_stream":{if(!e.isComplete)return null;let o=n(e.filePath),i=`File edited: ${o}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[o],data:{filePath:o,startLine:e.startLine,hunks:e.hunks?.length??0,oldPreview:ut(e.oldString,200),newPreview:ut(e.newString,200),description:e.description}}}case "write_file_stream":{if(!e.isComplete)return null;let o=n(e.filePath),i=`File written: ${o}`;return {type:"file_change",sessionId:t,runId:s,actor:"tool",summary:i,files:[o],data:{filePath:o,contentLength:e.content?.length??0,description:e.description}}}case "checkpoint":return {type:"checkpoint",sessionId:t,runId:s,actor:"system",summary:`Checkpoint saved: ${e.id}`,data:{id:e.id,auto:e.auto}};case "plan_update":{let o=e.plan.length,i=e.plan.filter(c=>c.status==="completed").length,a=e.plan.filter(c=>c.status==="in_progress").length,l=o-i-a;return {type:"plan_update",sessionId:t,runId:s,actor:"assistant",summary:`Plan update: ${i} done, ${a} active, ${l} pending`,data:{explanation:e.explanation,plan:e.plan}}}case "context_compaction":return {type:"context_compaction",sessionId:t,runId:s,actor:"system",summary:`Context compacted: ${e.originalTokens} -> ${e.finalTokens} tokens`,data:{originalMessages:e.originalMessages,keptMessages:e.keptMessages,droppedMessages:e.droppedMessages,compressedMessages:e.compressedMessages,originalTokens:e.originalTokens,finalTokens:e.finalTokens,budgetTokens:e.budgetTokens,useLLM:e.useLLM}};case "stream_retry":return {type:"stream_retry",sessionId:t,runId:s,actor:"system",summary:`Stream retry ${e.attempt}/${e.maxRetries}: ${e.errorCode}`,data:{error:e.error,errorCode:e.errorCode,attempt:e.attempt,maxRetries:e.maxRetries,delayMs:e.delayMs}};case "stream_recovered":return {type:"stream_recovered",sessionId:t,runId:s,actor:"system",summary:`Stream recovered (attempt ${e.attempt})`,data:{attempt:e.attempt,maxRetries:e.maxRetries}};case "run_result":return {type:"run_result",sessionId:t,runId:s,actor:"assistant",summary:`Run completed in ${e.durationMs}ms, tokens ${e.totalTokens}`,data:{outputPreview:ut(e.output,io),totalTokens:e.totalTokens,iterations:e.iterations,toolCalls:e.toolCalls,durationMs:e.durationMs}};case "error":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Runtime error: ${ut(e.message,Fn)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${ut(e.message,Fn)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};var bf=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".tiff",".tif",".mp3",".mp4",".avi",".mov",".wmv",".flv",".wav",".ogg",".webm",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".app",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".ttf",".otf",".woff",".woff2",".eot",".jar",".war",".class",".pyc",".pyo",".o",".a",".lib",".node",".wasm",".asar"],du={ignoredPatterns:["**/.git/**","**/.cdundo/**","**/.svn/**","**/.hg/**","**/.DS_Store","**/Thumbs.db","**/desktop.ini","**/*.log","**/*.tmp","**/*.temp","**/*.swp","**/*.swo","**/*~","**/node_modules/**","**/bower_components/**","**/.npm/**","**/.yarn/**","**/.pnpm-store/**","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/dist/**","**/build/**","**/out/**","**/output/**","**/.output/**","**/target/**","**/bin/**","**/obj/**","**/*.bundle.js","**/*.bundle.css","**/*.min.js","**/*.min.css","**/.next/**","**/.nuxt/**","**/.svelte-kit/**","**/.astro/**","**/.vercel/**","**/.netlify/**","**/.turbo/**","**/.cache/**","**/.parcel-cache/**","**/.webpack/**","**/.vite/**","**/coverage/**","**/.nyc_output/**","**/jest_cache/**","**/.jest/**","**/__pycache__/**","**/*.pyc","**/*.pyo","**/*.pyd","**/.venv/**","**/venv/**","**/env/**","**/.env/**","**/virtualenv/**","**/.Python","**/pip-wheel-metadata/**","**/*.egg-info/**","**/.eggs/**","**/site-packages/**","**/target/**","**/.gradle/**","**/gradle/**","**/.m2/**","**/*.class","**/*.jar","**/*.war","**/*.ear","**/target/**","**/*.rlib","**/Cargo.lock","**/vendor/**","**/go.sum","**/bin/**","**/obj/**","**/packages/**","**/.nuget/**","**/*.dll","**/*.exe","**/*.pdb","**/vendor/bundle/**","**/.bundle/**","**/Gemfile.lock","**/vendor/**","**/composer.lock","**/.idea/**","**/.vscode/**","**/*.sublime-*","**/.project","**/.classpath","**/.settings/**","**/*.iml","**/.env.local","**/.env.*.local","**/.env.development","**/.env.production","**/*.sqlite","**/*.sqlite3","**/*.db","**/npm-debug.log*","**/yarn-debug.log*","**/yarn-error.log*","**/.pnpm-debug.log*"],maxCheckpoints:50,checkpointTTL:864e5,enabled:true,largeFileThreshold:1048576,veryLargeFileThreshold:10485760,binaryExtensions:bf};var lo=class{workspacePath;shadowDir;shadowGitDir;git;watcher=null;changeBuffer=[];isWatching=false;currentSessionId=null;currentMessageIndex=0;config;changeCallbacks=new Set;initialized=false;debounceMap=new Map;DEBOUNCE_MS=100;gitOperationLock=Promise.resolve();GIT_RETRY_ATTEMPTS=3;GIT_RETRY_DELAY_MS=500;constructor(e={}){this.config={...du,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=mu();}async init(e){if(this.initialized&&this.workspacePath===e){console.log("[ShadowGit] Already initialized for:",e);return}this.workspacePath=e,this.shadowDir=Y.join(e,".cdundo"),this.shadowGitDir=Y.join(this.shadowDir,".git"),console.log("[ShadowGit] Initializing for workspace:",e),await Z.mkdir(this.shadowDir,{recursive:true}),await this.addToGitignore();let t=Tn.existsSync(this.shadowGitDir);this.git=mu(this.shadowDir),t?console.log("[ShadowGit] Using existing shadow git repository"):(await this.git.init(),await this.git.addConfig("user.email","checkpoint@neox.local"),await this.git.addConfig("user.name","Neox Checkpoint"),console.log("[ShadowGit] Created new shadow git repository")),await this.syncWorkspaceToShadow(),await this.withGitLock(async()=>{if((await this.git.status()).files.length>0||!t){await this.git.add(".");try{await this.git.commit("Initial checkpoint - workspace sync"),console.log("[ShadowGit] Created initial checkpoint");}catch{console.log("[ShadowGit] No changes to commit for initial checkpoint");}}}),this.initialized=true,console.log("[ShadowGit] Initialization complete");}beforeCheckpointId=null;async startWatching(e,t=0){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized. Call init() first.");if(this.isWatching)return console.log("[ShadowGit] Already watching, updating session info"),console.log("[ShadowGit] Clearing changeBuffer (was:",this.changeBuffer.length,"items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[],this.beforeCheckpointId;console.log("[ShadowGit] Starting new watch, clearing changeBuffer (was:",this.changeBuffer.length,"items)"),this.currentSessionId=e,this.currentMessageIndex=t,this.changeBuffer=[];try{await this.withGitLock(async()=>{await this.syncWorkspaceToShadow(),await this.git.add("."),(await this.git.status()).files.length>0&&await this.git.commit(`Before session ${e} - auto checkpoint`);let o=await this.git.log({maxCount:1});this.beforeCheckpointId=o.latest?.hash||null,console.log("[ShadowGit] Created before-checkpoint:",this.beforeCheckpointId);});}catch(n){console.error("[ShadowGit] Failed to create before-checkpoint:",n);try{let o=await this.git.log({maxCount:1});this.beforeCheckpointId=o.latest?.hash||null;}catch{this.beforeCheckpointId=null;}}console.log("[ShadowGit] Starting file watcher for session:",e);let s=n=>!!(n.includes(".cdundo")||n.includes("/.cdundo/")||n.includes("node_modules")||n.includes("/node_modules/")||n.includes("/.git/")||n.endsWith("/.git")||n.includes("/dist/")||n.includes("/build/")||n.includes("/.next/")||n.includes(".DS_Store")||n.includes(".swp")||n.includes(".swo")||n.endsWith("package-lock.json")||n.endsWith("yarn.lock")||n.endsWith("pnpm-lock.yaml"));return this.watcher=hu.watch(this.workspacePath,{ignored:s,persistent:true,ignoreInitial:true,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},followSymlinks:false}),this.watcher.on("add",n=>this.handleChange("create",n)).on("change",n=>this.handleChange("modify",n)).on("unlink",n=>this.handleChange("delete",n)).on("addDir",n=>this.handleChange("mkdir",n)).on("unlinkDir",n=>this.handleChange("rmdir",n)).on("error",n=>console.error("[ShadowGit] Watcher error:",n)),this.isWatching=true,console.log("[ShadowGit] File watcher started"),this.beforeCheckpointId}getBeforeCheckpointId(){return this.beforeCheckpointId}async stopWatching(){this.watcher&&(await this.watcher.close(),this.watcher=null),this.isWatching=false,this.currentSessionId=null;for(let e of this.debounceMap.values())clearTimeout(e);this.debounceMap.clear(),this.changeBuffer=[],console.log("[ShadowGit] File watcher stopped");}handleChange(e,t){if(!this.isWatching)return;let s=Y.relative(this.workspacePath,t);if(this.shouldIgnorePath(s))return;let n=`${e}:${s}`,o=this.debounceMap.get(n);o&&clearTimeout(o),this.debounceMap.set(n,setTimeout(()=>{this.recordChange(e,s,t),this.debounceMap.delete(n);},this.DEBOUNCE_MS));}isBinaryFile(e){let t=Y.extname(e).toLowerCase();return this.config.binaryExtensions.includes(t)}async detectBinaryContent(e){try{let t=await Z.open(e,"r"),s=Buffer.alloc(8192),{bytesRead:n}=await t.read(s,0,8192,0);await t.close();for(let o=0;o<n;o++)if(s[o]===0)return !0;return !1}catch{return false}}async recordChange(e,t,s){let n={type:e,path:t,timestamp:Date.now()},o=this.isBinaryFile(t);n.isBinary=o;let i=0,a=false,l=false;if(e==="create"||e==="modify")try{let p=await Z.stat(s);if(p.isFile()&&(i=p.size,n.size=i,a=i>this.config.veryLargeFileThreshold,l=i>this.config.largeFileThreshold,n.isLargeFile=l,!o&&!l)){let d=await this.detectBinaryContent(s);n.isBinary=d;}}catch{}if((e==="delete"||e==="modify")&&!n.isBinary&&!l){let p=Y.join(this.shadowDir,t);try{let d=await Z.stat(p);d.isFile()&&d.size<this.config.largeFileThreshold&&(n.previousContent=await Z.readFile(p,"utf-8"));}catch{}}if((e==="create"||e==="modify")&&!n.isBinary&&!l)try{n.newContent=await Z.readFile(s,"utf-8");}catch{}this.changeBuffer.push(n),a?console.log(`[ShadowGit] Skipping very large file (${(i/1024/1024).toFixed(1)}MB): ${t}`):await this.syncFileToShadow(t,e,s);for(let p of this.changeCallbacks)try{p(n);}catch(d){console.error("[ShadowGit] Callback error:",d);}let c=i?` (${this.formatFileSize(i)})`:"",u=n.isBinary?" [binary]":"";console.log(`[ShadowGit] Recorded ${e}: ${t}${c}${u}`);}formatFileSize(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}async syncFileToShadow(e,t,s){let n=Y.join(this.shadowDir,e),o=Y.dirname(n);try{switch(t){case "create":case "modify":await Z.mkdir(o,{recursive:!0}),await Z.copyFile(s,n);break;case "delete":await Z.unlink(n).catch(()=>{});break;case "mkdir":await Z.mkdir(n,{recursive:!0});break;case "rmdir":await Z.rm(n,{recursive:!0,force:!0}).catch(()=>{});break}}catch(i){console.error(`[ShadowGit] Failed to sync ${e}:`,i);}}async syncWorkspaceToShadow(){console.log("[ShadowGit] Syncing workspace to shadow...");let e=0,t=0,s=0,n=async(o,i)=>{let a;try{a=await Z.readdir(o,{withFileTypes:!0});}catch{return}for(let l of a){let c=Y.join(o,l.name),u=Y.join(i,l.name),p=Y.relative(this.workspacePath,c);if(!this.shouldIgnore(p)){if(l.isDirectory())await Z.mkdir(u,{recursive:true}),await n(c,u);else if(l.isFile())try{let d=await Z.stat(c);if(d.size>this.config.veryLargeFileThreshold){t++,console.log(`[ShadowGit] Skipping very large file: ${p} (${this.formatFileSize(d.size)})`);continue}await Z.mkdir(Y.dirname(u),{recursive:!0}),await Z.copyFile(c,u),e++,s+=d.size;}catch{console.warn(`[ShadowGit] Failed to sync file: ${p}`);}}}};await n(this.workspacePath,this.shadowDir),console.log(`[ShadowGit] Workspace sync complete: ${e} files (${this.formatFileSize(s)}), ${t} large files skipped`);}shouldIgnorePath(e){return !!(e.startsWith(".cdundo")||e.includes("/.cdundo/")||e.includes("node_modules/")||e.startsWith("node_modules")||e.startsWith(".git")||e.includes("/.git/")||e.startsWith("dist/")||e.includes("/dist/")||e.startsWith("build/")||e.includes("/build/")||e.startsWith(".next/")||e.includes("/.next/")||e.includes(".DS_Store")||e.endsWith(".swp")||e.endsWith(".swo")||e.endsWith("package-lock.json")||e.endsWith("yarn.lock")||e.endsWith("pnpm-lock.yaml"))}shouldIgnore(e){if(this.shouldIgnorePath(e))return true;for(let t of this.config.ignoredPatterns)if(this.matchPattern(e,t))return true;return false}matchPattern(e,t){let s=t.replace(/\*\*/g,"<<<GLOBSTAR>>>").replace(/\*/g,"[^/]*").replace(/<<<GLOBSTAR>>>/g,".*").replace(/\?/g,".");return new RegExp(`^${s}$`).test(e)}async createCheckpoint(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");return console.log("[ShadowGit] Creating checkpoint:",e),await this.withGitLock(async()=>{if(await this.git.add("."),(await this.git.status()).files.length===0&&this.changeBuffer.length===0)return console.log("[ShadowGit] No changes to checkpoint"),{id:(await this.git.log({maxCount:1})).latest?.hash||"no-changes",label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[],stats:{created:0,modified:0,deleted:0,directories:0,total:0}};let s=this.calculateStats(),n=this.formatCommitMessage(e,s),o=await this.git.commit(n),i={id:o.commit,label:e,timestamp:Date.now(),sessionId:this.currentSessionId||"",messageIndex:this.currentMessageIndex,changes:[...this.changeBuffer],stats:s};return this.changeBuffer=[],this.currentMessageIndex++,console.log(`[ShadowGit] Checkpoint created: ${o.commit} (${s.total} changes)`),await this.cleanupOldCheckpoints(),i})}lastRollbackFromId=null;getLastRollbackFromId(){return this.lastRollbackFromId}async rollbackTo(e){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");console.log("[ShadowGit] Rolling back to checkpoint:",e);let t=[],s=[],n;try{return await this.withGitLock(async()=>{await this.git.add(".");let o=await this.git.status();if(console.log("[ShadowGit] Current git status before rollback:",o.files.length,"files"),o.files.length>0)try{await this.git.commit("Changes before rollback (for reapply)"),console.log("[ShadowGit] Created commit for rollback comparison");}catch{console.log("[ShadowGit] No changes to commit (might be already committed)");}n=(await this.git.log({maxCount:1})).latest?.hash,this.lastRollbackFromId=n||null,console.log("[ShadowGit] Saved reapply checkpoint:",n);let a=await this.git.diff([e,"HEAD","--name-status"]),l=a.trim().split(`
1800
+ `).filter(c=>c.trim());console.log("[ShadowGit] Diff output:",a),console.log("[ShadowGit] Files to rollback:",l.length);for(let c of l){let[u,...p]=c.split(" "),d=p.join(" ");if(!d)continue;let m=Y.join(this.workspacePath,d),h=Y.join(this.shadowDir,d);console.log(`[ShadowGit] Processing: status=${u}, file=${d}`);try{switch(u){case "A":console.log(`[ShadowGit] Deleting added file: ${m}`),await Z.unlink(m).catch(f=>{console.log(`[ShadowGit] Failed to delete workspace file: ${f}`);}),await Z.unlink(h).catch(()=>{}),t.push(`deleted: ${d}`);break;case "M":console.log(`[ShadowGit] Restoring modified file: ${d}`),await this.git.checkout([e,"--",d]),await Z.mkdir(Y.dirname(m),{recursive:!0}),await Z.copyFile(h,m),t.push(`restored: ${d}`);break;case "D":console.log(`[ShadowGit] Recovering deleted file: ${d}`),await this.git.checkout([e,"--",d]),await Z.mkdir(Y.dirname(m),{recursive:!0}),await Z.copyFile(h,m),t.push(`recovered: ${d}`);break;default:console.log(`[ShadowGit] Unhandled status ${u} for ${d}`);}}catch(f){console.error(`[ShadowGit] Error processing ${d}:`,f),s.push(`${d}: ${f}`);}}await this.git.reset(["--hard",e]),this.changeBuffer=[],console.log(`[ShadowGit] Rollback complete: ${t.length} restored, ${s.length} errors`);}),{success:s.length===0,restored:t,errors:s,reapplyCheckpointId:n}}catch(o){return console.error("[ShadowGit] Rollback failed:",o),{success:false,restored:t,errors:[String(o)],reapplyCheckpointId:n}}}async rollbackSingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};console.log("[ShadowGit] Rolling back single file:",e);let t=this.beforeCheckpointId;if(!t)return {success:false,error:"No before checkpoint available. Make sure startWatching() was called before this message."};let s=Y.join(this.workspacePath,e),n=Y.join(this.shadowDir,e);try{return await this.withGitLock(async()=>{let o=await this.git.diff([t,"HEAD","--name-status","--",e]);if(console.log("[ShadowGit] File diff status:",o.trim()),!o.trim())return console.log("[ShadowGit] File has no changes since before checkpoint"),{success:!0};let[i]=o.trim().split(" ");switch(i){case "A":console.log("[ShadowGit] File was added after checkpoint, deleting:",e);try{return await Z.unlink(s),await Z.unlink(n).catch(()=>{}),{success:!0}}catch(a){return {success:!1,error:`Failed to delete file: ${a}`}}case "M":case "D":console.log("[ShadowGit] Restoring file from before checkpoint:",e);try{return await this.git.checkout([t,"--",e]),await Z.mkdir(Y.dirname(s),{recursive:!0}),await Z.copyFile(n,s),console.log("[ShadowGit] Successfully rolled back file:",e),{success:!0}}catch(a){return {success:!1,error:`Failed to restore file: ${a}`}}default:return console.log("[ShadowGit] Unhandled status:",i),{success:!1,error:`Unhandled file status: ${i}`}}})}catch(o){return console.error("[ShadowGit] Failed to rollback single file:",o),{success:false,error:String(o)}}}async reapplySingleFile(e){if(!this.initialized)return {success:false,error:"ShadowGitCheckpoint not initialized"};console.log("[ShadowGit] Reapplying single file:",e);try{return await this.withGitLock(async()=>{let t=Y.join(this.workspacePath,e),s=Y.join(this.shadowDir,e);try{return await this.git.checkout(["HEAD","--",e]),await Z.mkdir(Y.dirname(t),{recursive:!0}),await Z.copyFile(s,t),console.log("[ShadowGit] Successfully reapplied file:",e),{success:!0}}catch(n){return {success:!1,error:`File not found in HEAD: ${n}`}}})}catch(t){return console.error("[ShadowGit] Failed to reapply single file:",t),{success:false,error:String(t)}}}async getCheckpoints(e=50,t){if(!this.initialized)return [];try{let s=t?e*3:e,o=(await this.git.log({maxCount:s})).all.map(i=>{let a=this.parseCommitMessage(i.message);return {id:i.hash,label:a.label,timestamp:new Date(i.date).getTime(),sessionId:a.sessionId,messageIndex:a.messageIndex,stats:a.stats}});return t&&(o=o.filter(i=>i.sessionId===t)),o.slice(0,e)}catch(s){return console.error("[ShadowGit] Failed to get checkpoints:",s),[]}}async getDiff(e,t="HEAD"){if(!this.initialized)throw new Error("ShadowGitCheckpoint not initialized");await this.git.diff([e,t,"--stat","--numstat"]);let n=await this.git.diffSummary([e,t]),o=n.files.map(i=>{let a="insertions"in i&&"deletions"in i;return {path:i.file,status:this.getFileStatus(i),additions:a?i.insertions:0,deletions:a?i.deletions:0,lines:[]}});return {checkpointId:e,files:o,stats:{filesChanged:n.changed,additions:n.insertions,deletions:n.deletions}}}getChangeBuffer(){return this.isWatching?[...this.changeBuffer]:(console.log("[ShadowGit] getChangeBuffer called but not watching, returning empty array"),[])}getCurrentStats(){if(!this.isWatching)return console.log("[ShadowGit] getCurrentStats called but not watching, returning empty stats"),{created:0,modified:0,deleted:0,directories:0,total:0};let e=this.calculateStats();return console.log("[ShadowGit] getCurrentStats called, changeBuffer length:",this.changeBuffer.length),this.changeBuffer.length>0&&console.log("[ShadowGit] changeBuffer contents:",this.changeBuffer.map(t=>`${t.type}: ${t.path}`)),e}onFileChange(e){return this.changeCallbacks.add(e),()=>this.changeCallbacks.delete(e)}isInitialized(){return this.initialized}isActive(){return this.isWatching}getShadowDir(){return this.shadowDir}calculateStats(){let e={created:0,modified:0,deleted:0,directories:0,total:0};for(let t of this.changeBuffer)switch(t.type){case "create":e.created++;break;case "modify":e.modified++;break;case "delete":e.deleted++;break;case "mkdir":case "rmdir":e.directories++;break}return e.total=e.created+e.modified+e.deleted+e.directories,e}formatCommitMessage(e,t){let s=this.currentSessionId?`
1801
1801
 
1802
1802
  Session: ${this.currentSessionId}
1803
1803
  Message: ${this.currentMessageIndex}`:"";return `${e}
1804
1804
 
1805
1805
  Stats: +${t.created} ~${t.modified} -${t.deleted} d${t.directories}${s}`}parseCommitMessage(e){let t=e.split(`
1806
- `),s=t[0]||"Unknown",n="",i=0,o={created:0,modified:0,deleted:0,directories:0,total:0};for(let a of t)if(a.startsWith("Session:"))n=a.replace("Session:","").trim();else if(a.startsWith("Message:"))i=parseInt(a.replace("Message:","").trim())||0;else if(a.startsWith("Stats:")){let l=a.match(/\+(\d+)\s+~(\d+)\s+-(\d+)\s+d(\d+)/);l&&(o.created=parseInt(l[1]),o.modified=parseInt(l[2]),o.deleted=parseInt(l[3]),o.directories=parseInt(l[4]),o.total=o.created+o.modified+o.deleted+o.directories);}return {label:s,sessionId:n,messageIndex:i,stats:o}}getFileStatus(e){let t=e.insertions??0,s=e.deletions??0;return t>0&&s===0?"A":s>0&&t===0?"D":"M"}async addToGitignore(){let e=Y.join(this.workspacePath,".gitignore");try{let t="";try{t=await Z.readFile(e,"utf-8");}catch{}if(!t.includes(".cdundo")){let s=t.trim()?`${t.trim()}
1806
+ `),s=t[0]||"Unknown",n="",o=0,i={created:0,modified:0,deleted:0,directories:0,total:0};for(let a of t)if(a.startsWith("Session:"))n=a.replace("Session:","").trim();else if(a.startsWith("Message:"))o=parseInt(a.replace("Message:","").trim())||0;else if(a.startsWith("Stats:")){let l=a.match(/\+(\d+)\s+~(\d+)\s+-(\d+)\s+d(\d+)/);l&&(i.created=parseInt(l[1]),i.modified=parseInt(l[2]),i.deleted=parseInt(l[3]),i.directories=parseInt(l[4]),i.total=i.created+i.modified+i.deleted+i.directories);}return {label:s,sessionId:n,messageIndex:o,stats:i}}getFileStatus(e){let t=e.insertions??0,s=e.deletions??0;return t>0&&s===0?"A":s>0&&t===0?"D":"M"}async addToGitignore(){let e=Y.join(this.workspacePath,".gitignore");try{let t="";try{t=await Z.readFile(e,"utf-8");}catch{}if(!t.includes(".cdundo")){let s=t.trim()?`${t.trim()}
1807
1807
 
1808
1808
  # Neox checkpoint directory
1809
1809
  .cdundo/
1810
1810
  `:`# Neox checkpoint directory
1811
1811
  .cdundo/
1812
- `;await Z.writeFile(e,s),console.log("[ShadowGit] Added .cdundo to .gitignore");}}catch(t){console.error("[ShadowGit] Failed to update .gitignore:",t);}}async cleanupOldCheckpoints(){try{let e=await this.getCheckpoints(this.config.maxCheckpoints+10);e.length>this.config.maxCheckpoints&&(console.log(`[ShadowGit] Cleaning up old checkpoints (${e.length} > ${this.config.maxCheckpoints})`),await this.compressRepository());}catch(e){console.error("[ShadowGit] Failed to cleanup checkpoints:",e);}}async compressRepository(){if(!this.initialized)return {success:false};try{let e=await this.getRepositorySize();console.log("[ShadowGit] Compressing repository..."),await this.git.raw(["reflog","expire","--expire=now","--all"]),await this.git.raw(["gc","--aggressive","--prune=now"]),await this.git.raw(["repack","-a","-d","--depth=250","--window=250"]);let t=await this.getRepositorySize(),s=e-t;return console.log(`[ShadowGit] Repository compressed: ${this.formatFileSize(e)} \u2192 ${this.formatFileSize(t)} (saved ${this.formatFileSize(s)})`),{success:!0,savedBytes:s}}catch(e){return console.error("[ShadowGit] Failed to compress repository:",e),{success:false}}}async getRepositorySize(){let e=0,t=async s=>{try{let n=await Z.readdir(s,{withFileTypes:!0});for(let i of n){let o=Y.join(s,i.name);if(i.isDirectory())await t(o);else if(i.isFile()){let a=await Z.stat(o);e+=a.size;}}}catch{}};return await t(this.shadowGitDir),e}async getStorageStats(){let e=await this.getRepositorySize(),t=0,s=async i=>{try{let o=await Z.readdir(i,{withFileTypes:!0});for(let a of o){let l=Y.join(i,a.name);if(a.isDirectory()&&a.name!==".git")await s(l);else if(a.isFile()){let c=await Z.stat(l);t+=c.size;}}}catch{}};await s(this.shadowDir);let n=await this.getCheckpoints(1e3);return {repositorySize:e,shadowDirSize:t,checkpointCount:n.length,oldestCheckpoint:n.length>0?{id:n[n.length-1].id,timestamp:n[n.length-1].timestamp}:void 0,newestCheckpoint:n.length>0?{id:n[0].id,timestamp:n[0].timestamp}:void 0}}async cleanStaleLocks(){let e=Y.join(this.shadowGitDir,"index.lock");try{if(vn.existsSync(e)){let s=await Z.stat(e);Date.now()-s.mtimeMs>1e4&&(await Z.unlink(e),console.log("[ShadowGit] Cleaned stale lock file"));}}catch{}}async withGitLock(e){let t=this.gitOperationLock,s=()=>{};this.gitOperationLock=new Promise(n=>{s=n;});try{await t;let n;for(let i=1;i<=this.GIT_RETRY_ATTEMPTS;i++)try{return i>1&&(await this.cleanStaleLocks(),await new Promise(a=>setTimeout(a,this.GIT_RETRY_DELAY_MS))),await e()}catch(o){if(n=o,!(o.message&&(o.message.includes("index.lock")||o.message.includes("File exists")))||i===this.GIT_RETRY_ATTEMPTS)throw o;console.warn(`[ShadowGit] Git operation failed (attempt ${i}/${this.GIT_RETRY_ATTEMPTS}), retrying...`);}throw n}finally{s();}}async destroy(){await this.stopWatching(),this.initialized=false,this.changeCallbacks.clear(),console.log("[ShadowGit] Instance destroyed");}};var Fn=class r{static instance=null;instances=new Map;config;constructor(e={}){this.config=e;}static getInstance(e){return r.instance||(r.instance=new r(e)),r.instance}async getCheckpoint(e){let t=Y.normalize(e);if(!this.instances.has(t)){let s=new ai(this.config);await s.init(t),this.instances.set(t,s);}return this.instances.get(t)}async startWatching(e,t,s=0){return (await this.getCheckpoint(e)).startWatching(t,s)}getBeforeCheckpointId(e){let t=Y.normalize(e);return this.instances.get(t)?.getBeforeCheckpointId()??null}async stopWatching(e){let t=Y.normalize(e),s=this.instances.get(t);s&&await s.stopWatching();}async createCheckpoint(e,t){return (await this.getCheckpoint(e)).createCheckpoint(t)}async rollbackTo(e,t){return (await this.getCheckpoint(e)).rollbackTo(t)}async rollbackSingleFile(e,t){return (await this.getCheckpoint(e)).rollbackSingleFile(t)}async reapplySingleFile(e,t){return (await this.getCheckpoint(e)).reapplySingleFile(t)}async getCheckpoints(e,t,s){return (await this.getCheckpoint(e)).getCheckpoints(t,s)}async getDiff(e,t,s){return (await this.getCheckpoint(e)).getDiff(t,s)}async getChangeBuffer(e){return (await this.getCheckpoint(e)).getChangeBuffer()}async getCurrentStats(e){return (await this.getCheckpoint(e)).getCurrentStats()}async onFileChange(e,t){return (await this.getCheckpoint(e)).onFileChange(t)}isWatching(e){let t=Y.normalize(e);return this.instances.get(t)?.isActive()??false}async cleanup(e){let t=Y.normalize(e),s=this.instances.get(t);s&&(await s.destroy(),this.instances.delete(t));let n=Y.join(t,".cdundo");try{await Z.rm(n,{recursive:!0,force:!0}),console.log("[CheckpointManager] Cleaned up:",n);}catch(i){console.error("[CheckpointManager] Failed to cleanup:",i);}}async destroyAll(){for(let[e,t]of this.instances)await t.destroy();this.instances.clear(),console.log("[CheckpointManager] All instances destroyed");}getActiveWorkspaces(){return Array.from(this.instances.keys()).filter(e=>this.instances.get(e)?.isActive())}getStats(){return {totalInstances:this.instances.size,activeInstances:this.getActiveWorkspaces().length,workspaces:Array.from(this.instances.keys())}}};Fn.getInstance();var Qo=class{checkpointManager;workspacePath=null;enabled=true;sessionMessageCounts=new Map;constructor(e){this.checkpointManager=e??Fn.getInstance();}setWorkspace(e){this.workspacePath=e;}setEnabled(e){this.enabled=e;}isEnabled(){return this.enabled}async startMessage(e){if(!this.enabled||!this.workspacePath)return null;let t=this.sessionMessageCounts.get(e)||0;return this.checkpointManager.startWatching(this.workspacePath,e,t)}async finishMessage(e,t){if(!this.enabled||!this.workspacePath)return null;let s=await this.createCheckpoint(e,t);return await this.checkpointManager.stopWatching(this.workspacePath),s}async stopWatching(){this.workspacePath&&await this.checkpointManager.stopWatching(this.workspacePath);}async createCheckpoint(e,t){if(!this.enabled||!this.workspacePath)return null;let s=this.sessionMessageCounts.get(e)||0,n=t||`Message #${s+1}`,i=await this.checkpointManager.createCheckpoint(this.workspacePath,n);return this.sessionMessageCounts.set(e,s+1),i}async rollbackToCheckpoint(e){return this.workspacePath?this.checkpointManager.rollbackTo(this.workspacePath,e):{success:false,restored:[],errors:["No workspace set"]}}async rollbackSingleFile(e){return this.workspacePath?this.checkpointManager.rollbackSingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async reapplySingleFile(e){return this.workspacePath?this.checkpointManager.reapplySingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async getCheckpoints(e,t){return this.workspacePath?this.checkpointManager.getCheckpoints(this.workspacePath,e,t):[]}async getCurrentStats(){return this.workspacePath?this.checkpointManager.getCurrentStats(this.workspacePath):null}async getChangeBuffer(){return this.workspacePath?this.checkpointManager.getChangeBuffer(this.workspacePath):[]}async cleanup(){this.workspacePath&&await this.checkpointManager.cleanup(this.workspacePath);}};function ff(r,e,t){if(e?.setThinkingMode)return e.setThinkingMode(r),true;let s=t;return s?.setThinking?(s.setThinking({type:r==="auto"?"enabled":r}),true):s?.setDoubaoThinking?(s.setDoubaoThinking({type:r}),true):false}function yf(){return {..._n(),capabilities:bo}}export{Qo as RuntimeCheckpointService,Yo as RuntimeHostService,Xo as RuntimeOrchestrator,oi as RuntimeOrchestratorError,ff as applyThinkingMode,No as buildInstructions,Vo as createAgentRuntimeHost,yf as createElectronServices,_n as createNodeServices,bo as electronToolCapabilities,Ro as getTools,Mr as nodeToolCapabilities,oh as preloadShellEnv,oc as setToolServices};
1812
+ `;await Z.writeFile(e,s),console.log("[ShadowGit] Added .cdundo to .gitignore");}}catch(t){console.error("[ShadowGit] Failed to update .gitignore:",t);}}async cleanupOldCheckpoints(){try{let e=await this.getCheckpoints(this.config.maxCheckpoints+10);e.length>this.config.maxCheckpoints&&(console.log(`[ShadowGit] Cleaning up old checkpoints (${e.length} > ${this.config.maxCheckpoints})`),await this.compressRepository());}catch(e){console.error("[ShadowGit] Failed to cleanup checkpoints:",e);}}async compressRepository(){if(!this.initialized)return {success:false};try{let e=await this.getRepositorySize();console.log("[ShadowGit] Compressing repository..."),await this.git.raw(["reflog","expire","--expire=now","--all"]),await this.git.raw(["gc","--aggressive","--prune=now"]),await this.git.raw(["repack","-a","-d","--depth=250","--window=250"]);let t=await this.getRepositorySize(),s=e-t;return console.log(`[ShadowGit] Repository compressed: ${this.formatFileSize(e)} \u2192 ${this.formatFileSize(t)} (saved ${this.formatFileSize(s)})`),{success:!0,savedBytes:s}}catch(e){return console.error("[ShadowGit] Failed to compress repository:",e),{success:false}}}async getRepositorySize(){let e=0,t=async s=>{try{let n=await Z.readdir(s,{withFileTypes:!0});for(let o of n){let i=Y.join(s,o.name);if(o.isDirectory())await t(i);else if(o.isFile()){let a=await Z.stat(i);e+=a.size;}}}catch{}};return await t(this.shadowGitDir),e}async getStorageStats(){let e=await this.getRepositorySize(),t=0,s=async o=>{try{let i=await Z.readdir(o,{withFileTypes:!0});for(let a of i){let l=Y.join(o,a.name);if(a.isDirectory()&&a.name!==".git")await s(l);else if(a.isFile()){let c=await Z.stat(l);t+=c.size;}}}catch{}};await s(this.shadowDir);let n=await this.getCheckpoints(1e3);return {repositorySize:e,shadowDirSize:t,checkpointCount:n.length,oldestCheckpoint:n.length>0?{id:n[n.length-1].id,timestamp:n[n.length-1].timestamp}:void 0,newestCheckpoint:n.length>0?{id:n[0].id,timestamp:n[0].timestamp}:void 0}}async cleanStaleLocks(){let e=Y.join(this.shadowGitDir,"index.lock");try{if(Tn.existsSync(e)){let s=await Z.stat(e);Date.now()-s.mtimeMs>1e4&&(await Z.unlink(e),console.log("[ShadowGit] Cleaned stale lock file"));}}catch{}}async withGitLock(e){let t=this.gitOperationLock,s=()=>{};this.gitOperationLock=new Promise(n=>{s=n;});try{await t;let n;for(let o=1;o<=this.GIT_RETRY_ATTEMPTS;o++)try{return o>1&&(await this.cleanStaleLocks(),await new Promise(a=>setTimeout(a,this.GIT_RETRY_DELAY_MS))),await e()}catch(i){if(n=i,!(i.message&&(i.message.includes("index.lock")||i.message.includes("File exists")))||o===this.GIT_RETRY_ATTEMPTS)throw i;console.warn(`[ShadowGit] Git operation failed (attempt ${o}/${this.GIT_RETRY_ATTEMPTS}), retrying...`);}throw n}finally{s();}}async destroy(){await this.stopWatching(),this.initialized=false,this.changeCallbacks.clear(),console.log("[ShadowGit] Instance destroyed");}};var Un=class r{static instance=null;instances=new Map;config;constructor(e={}){this.config=e;}static getInstance(e){return r.instance||(r.instance=new r(e)),r.instance}async getCheckpoint(e){let t=Y.normalize(e);if(!this.instances.has(t)){let s=new lo(this.config);await s.init(t),this.instances.set(t,s);}return this.instances.get(t)}async startWatching(e,t,s=0){return (await this.getCheckpoint(e)).startWatching(t,s)}getBeforeCheckpointId(e){let t=Y.normalize(e);return this.instances.get(t)?.getBeforeCheckpointId()??null}async stopWatching(e){let t=Y.normalize(e),s=this.instances.get(t);s&&await s.stopWatching();}async createCheckpoint(e,t){return (await this.getCheckpoint(e)).createCheckpoint(t)}async rollbackTo(e,t){return (await this.getCheckpoint(e)).rollbackTo(t)}async rollbackSingleFile(e,t){return (await this.getCheckpoint(e)).rollbackSingleFile(t)}async reapplySingleFile(e,t){return (await this.getCheckpoint(e)).reapplySingleFile(t)}async getCheckpoints(e,t,s){return (await this.getCheckpoint(e)).getCheckpoints(t,s)}async getDiff(e,t,s){return (await this.getCheckpoint(e)).getDiff(t,s)}async getChangeBuffer(e){return (await this.getCheckpoint(e)).getChangeBuffer()}async getCurrentStats(e){return (await this.getCheckpoint(e)).getCurrentStats()}async onFileChange(e,t){return (await this.getCheckpoint(e)).onFileChange(t)}isWatching(e){let t=Y.normalize(e);return this.instances.get(t)?.isActive()??false}async cleanup(e){let t=Y.normalize(e),s=this.instances.get(t);s&&(await s.destroy(),this.instances.delete(t));let n=Y.join(t,".cdundo");try{await Z.rm(n,{recursive:!0,force:!0}),console.log("[CheckpointManager] Cleaned up:",n);}catch(o){console.error("[CheckpointManager] Failed to cleanup:",o);}}async destroyAll(){for(let[e,t]of this.instances)await t.destroy();this.instances.clear(),console.log("[CheckpointManager] All instances destroyed");}getActiveWorkspaces(){return Array.from(this.instances.keys()).filter(e=>this.instances.get(e)?.isActive())}getStats(){return {totalInstances:this.instances.size,activeInstances:this.getActiveWorkspaces().length,workspaces:Array.from(this.instances.keys())}}};Un.getInstance();var ea=class{checkpointManager;workspacePath=null;enabled=true;sessionMessageCounts=new Map;constructor(e){this.checkpointManager=e??Un.getInstance();}setWorkspace(e){this.workspacePath=e;}setEnabled(e){this.enabled=e;}isEnabled(){return this.enabled}async startMessage(e){if(!this.enabled||!this.workspacePath)return null;let t=this.sessionMessageCounts.get(e)||0;return this.checkpointManager.startWatching(this.workspacePath,e,t)}async finishMessage(e,t){if(!this.enabled||!this.workspacePath)return null;let s=await this.createCheckpoint(e,t);return await this.checkpointManager.stopWatching(this.workspacePath),s}async stopWatching(){this.workspacePath&&await this.checkpointManager.stopWatching(this.workspacePath);}async createCheckpoint(e,t){if(!this.enabled||!this.workspacePath)return null;let s=this.sessionMessageCounts.get(e)||0,n=t||`Message #${s+1}`,o=await this.checkpointManager.createCheckpoint(this.workspacePath,n);return this.sessionMessageCounts.set(e,s+1),o}async rollbackToCheckpoint(e){return this.workspacePath?this.checkpointManager.rollbackTo(this.workspacePath,e):{success:false,restored:[],errors:["No workspace set"]}}async rollbackSingleFile(e){return this.workspacePath?this.checkpointManager.rollbackSingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async reapplySingleFile(e){return this.workspacePath?this.checkpointManager.reapplySingleFile(this.workspacePath,e):{success:false,error:"No workspace set"}}async getCheckpoints(e,t){return this.workspacePath?this.checkpointManager.getCheckpoints(this.workspacePath,e,t):[]}async getCurrentStats(){return this.workspacePath?this.checkpointManager.getCurrentStats(this.workspacePath):null}async getChangeBuffer(){return this.workspacePath?this.checkpointManager.getChangeBuffer(this.workspacePath):[]}async cleanup(){this.workspacePath&&await this.checkpointManager.cleanup(this.workspacePath);}};function _f(r,e,t){if(e?.setThinkingMode)return e.setThinkingMode(r),true;let s=t;return s?.setThinking?(s.setThinking({type:r==="auto"?"enabled":r}),true):s?.setDoubaoThinking?(s.setDoubaoThinking({type:r}),true):false}function wf(){return {...wn(),capabilities:_i}}export{ea as RuntimeCheckpointService,Xi as RuntimeHostService,Zi as RuntimeOrchestrator,ao as RuntimeOrchestratorError,_f as applyThinkingMode,Fi as buildInstructions,Yi as createAgentRuntimeHost,wf as createElectronServices,wn as createNodeServices,_i as electronToolCapabilities,Ei as getTools,Ar as nodeToolCapabilities,ch as preloadShellEnv,cc as setToolServices};