@mk-co/neox-cli 2.0.19 → 2.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk/index.js CHANGED
@@ -1,11 +1,11 @@
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 yi 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 Ju 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 og from'ajv';import Ng 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 ui=(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});},ia=(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)):{},ia(jn(t,"default",{value:r,enumerable:true}),r)),oa=r=>ia(jn({},"__esModule",{value:true}),r);var Gn={};Tu(Gn,{cliHealthMonitor:()=>Eu,cliLogger:()=>g,debugLog:()=>ue,generateCurlCommand:()=>yt,installCrashHandler:()=>Iu,logCurlCommand:()=>hi});function Cu(r,e){let t=new WeakSet;try{return JSON.stringify(r,(s,n)=>{if(e&&s){let i=s.toLowerCase();if(ku.has(i))return "[REDACTED]"}if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return n})}catch{return JSON.stringify({error:"[Unserializable payload]"})}}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=Cu(t,s);return n.push(` -d '${Ru(i)}'`),n.join(`
2
- `)}function Ru(r){return r.replace(/'/g,"'\\''")}function hi(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 Sn from'fs';import Sn__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 Gs,{homedir,platform}from'os';import*as Z from'fs/promises';import Z__default,{realpath,readlink,readdir,lstat,readFile}from'fs/promises';import wi from'readline';import {createHash,randomBytes,randomUUID}from'crypto';import uc from'fast-glob';import {spawn,fork}from'child_process';import {execa,execaSync}from'execa';import Yu from'puppeteer-core';import {EventEmitter}from'events';import*as Ga from'net';import {fileURLToPath}from'url';import Rl from'stream';import {StringDecoder}from'string_decoder';import cg from'ajv';import jg from'axios';import fu from'simple-git';import*as yu from'chokidar';var _u=Object.create;var Gn=Object.defineProperty;var wu=Object.getOwnPropertyDescriptor;var vu=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,Su=Object.prototype.hasOwnProperty;var aa=(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 xu=(r,e)=>()=>(r&&(e=r(r=0)),e);var mi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ku=(r,e)=>{for(var t in e)Gn(r,t,{get:e[t],enumerable:true});},la=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vu(e))!Su.call(r,n)&&n!==t&&Gn(r,n,{get:()=>e[n],enumerable:!(s=wu(e,n))||s.enumerable});return r};var Cu=(r,e,t)=>(t=r!=null?_u(Tu(r)):{},la(Gn(t,"default",{value:r,enumerable:true}),r)),ca=r=>la(Gn({},"__esModule",{value:true}),r);var Bn={};ku(Bn,{cliHealthMonitor:()=>Au,cliLogger:()=>g,debugLog:()=>ue,generateCurlCommand:()=>yt,installCrashHandler:()=>Pu,logCurlCommand:()=>yi});function Iu(r,e){let t=new WeakSet;try{return JSON.stringify(r,(s,n)=>{if(e&&s){let i=s.toLowerCase();if(Eu.has(i))return "[REDACTED]"}if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(t.has(n))return "[Circular]";t.add(n);}return n})}catch{return JSON.stringify({error:"[Unserializable payload]"})}}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=Iu(t,s);return n.push(` -d '${Mu(i)}'`),n.join(`
2
+ `)}function Mu(r){return r.replace(/'/g,"'\\''")}function yi(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 Iu(){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 di,g,ku,mi,Eu,le=vu(()=>{di=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.writeStream.on("error",()=>{this.enabled=false,this.currentLogFile=null;let t=this.writeStream;this.writeStream=null;try{t?.destroy();}catch{}}),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 di,ku=new Set(["api_key","apikey","authorization","token","access_token","refresh_token","password","secret"]);mi=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);}},Eu=new mi;});var Ya=ui((U0,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,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 rl=ui((j0,nl)=>{var Xa=Ya();nl.exports=vd;var Za="\0SLASH"+Math.random()+"\0",Qa="\0OPEN"+Math.random()+"\0",zi="\0CLOSE"+Math.random()+"\0",el="\0COMMA"+Math.random()+"\0",tl="\0PERIOD"+Math.random()+"\0";function qi(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function _d(r){return r.split("\\\\").join(Za).split("\\{").join(Qa).split("\\}").join(zi).split("\\,").join(el).split("\\.").join(tl)}function wd(r){return r.split(Za).join("\\").split(Qa).join("{").split(zi).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,i=t.post,o=s.split(",");o[o.length-1]+="{"+n+"}";var a=sl(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function vd(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Xs(_d(r),true).map(wd)):[]}function Td(r){return "{"+r+"}"}function xd(r){return /^-?0\d/.test(r)}function Sd(r,e){return r<=e}function kd(r,e){return r>=e}function Xs(r,e){var t=[],s=Xa("{","}",r);if(!s)return [r];var n=s.pre,i=s.post.length?Xs(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+zi+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(Td),d.length===1))return i.map(function(C){return s.pre+d[0]+C});var m;if(u){var h=qi(d[0]),f=qi(d[1]),y=Math.max(d[0].length,d[1].length),b=d.length==3?Math.abs(qi(d[2])):1,_=Sd,v=f<h;v&&(b*=-1,_=kd);var k=d.some(xd);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 o=0;o<i.length;o++){var a=n+m[S]+i[o];(!e||u||a)&&t.push(a);}}return t}});var Cc=ui((Gv,kc)=>{var xc=ra("fs"),Po=ra("path"),Sc=Po.join(__dirname,"path.txt");function tg(){let r;if(xc.existsSync(Sc)&&(r=xc.readFileSync(Sc,"utf-8")),process.env.ELECTRON_OVERRIDE_DIST_PATH)return Po.join(process.env.ELECTRON_OVERRIDE_DIST_PATH,r||"electron");if(r)return Po.join(__dirname,"dist",r);throw new Error("Electron failed to install correctly, please delete node_modules/electron and try installing again")}kc.exports=tg();});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,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 Mu={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),i=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+=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 Au(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,i=this.profile.contextWindow?n/this.profile.contextWindow:void 0,o=Au(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 Mu[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 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=yi.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 Pu(){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 gi,g,Eu,fi,Au,le=xu(()=>{gi=class{logDir;enabled=true;initialized=false;writeStream=null;currentLogFile=null;backpressured=false;constructor(){this.logDir=Y__default.join(Gs.homedir(),".neox","logs");}init(){if(!this.initialized)try{Sn__default.existsSync(this.logDir)||Sn__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=Sn__default.createWriteStream(e,{flags:"a"}),this.writeStream.on("error",()=>{this.enabled=false,this.currentLogFile=null;let t=this.writeStream;this.writeStream=null;try{t?.destroy();}catch{}}),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 gi,Eu=new Set(["api_key","apikey","authorization","token","access_token","refresh_token","password","secret"]);fi=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);}},Au=new fi;});var Za=mi((H0,Xa)=>{Xa.exports=Va;function Va(r,e,t){r instanceof RegExp&&(r=Ka(r,t)),e instanceof RegExp&&(e=Ka(e,t));var s=Ya(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 Ka(r,e){var t=e.match(r);return t?t[0]:null}Va.range=Ya;function Ya(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 ol=mi((z0,il)=>{var Qa=Za();il.exports=xd;var el="\0SLASH"+Math.random()+"\0",tl="\0OPEN"+Math.random()+"\0",Vi="\0CLOSE"+Math.random()+"\0",sl="\0COMMA"+Math.random()+"\0",nl="\0PERIOD"+Math.random()+"\0";function Ki(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function Td(r){return r.split("\\\\").join(el).split("\\{").join(tl).split("\\}").join(Vi).split("\\,").join(sl).split("\\.").join(nl)}function Sd(r){return r.split(el).join("\\").split(tl).join("{").split(Vi).join("}").split(sl).join(",").split(nl).join(".")}function rl(r){if(!r)return [""];var e=[],t=Qa("{","}",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=rl(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function xd(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Zs(Td(r),true).map(Sd)):[]}function kd(r){return "{"+r+"}"}function Cd(r){return /^-?0\d/.test(r)}function Rd(r,e){return r<=e}function Ed(r,e){return r>=e}function Zs(r,e){var t=[],s=Qa("{","}",r);if(!s)return [r];var n=s.pre,i=s.post.length?Zs(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+Vi+s.post,Zs(r)):[r];var d;if(u)d=s.body.split(/\.\./);else if(d=rl(s.body),d.length===1&&(d=Zs(d[0],false).map(kd),d.length===1))return i.map(function(C){return s.pre+d[0]+C});var m;if(u){var h=Ki(d[0]),f=Ki(d[1]),y=Math.max(d[0].length,d[1].length),b=d.length==3?Math.abs(Ki(d[2])):1,_=Rd,v=f<h;v&&(b*=-1,_=Ed);var k=d.some(Cd);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 x=0;x<d.length;x++)m.push.apply(m,Zs(d[x],false));}for(var x=0;x<m.length;x++)for(var o=0;o<i.length;o++){var a=n+m[x]+i[o];(!e||u||a)&&t.push(a);}}return t}});var Ec=mi((Jv,Rc)=>{var kc=aa("fs"),Do=aa("path"),Cc=Do.join(__dirname,"path.txt");function rg(){let r;if(kc.existsSync(Cc)&&(r=kc.readFileSync(Cc,"utf-8")),process.env.ELECTRON_OVERRIDE_DIST_PATH)return Do.join(process.env.ELECTRON_OVERRIDE_DIST_PATH,r||"electron");if(r)return Do.join(__dirname,"dist",r);throw new Error("Electron failed to install correctly, please delete node_modules/electron and try installing again")}Rc.exports=rg();});le();var Wn=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 Ou={unknown:0,normal:1,warn:2,soft_limit:3,limit:4};function Hn(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=Hn(e),s=r.tool_calls?.length?Hn(JSON.stringify(r.tool_calls)):0;return t+s}function We(r){return r.reduce((e,t)=>e+pt(t),0)}function rs(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=Hn(s),i=t.tool_calls?.length?Hn(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 Lu(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 zn=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=Lu(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 Ou[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 is(){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(Gs.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=Sn__default.createReadStream(this.filePath,{encoding:"utf-8"}),s=wi.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)+`
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(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(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(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 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: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 gi={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 fi(r){if(r in gi)return gi[r];let e=r.toLowerCase();for(let[t,s]of Object.entries(gi))if(t.toLowerCase()===e)return s;return "contextual"}function ca(r){return fi(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(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=fi(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=la(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:Gs(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:Gs(s)};return}let i={role:"system",content:s,_tag:e,_timestamp:Date.now(),_estimatedTokens:Gs(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||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 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(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",""),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||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 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=yi.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=yi.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=yi.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 Uu={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}},ju={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={...ju,...e};}async execute(e,t){let s=Date.now(),n=Uu[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(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: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(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(Gs.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(Gs.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(Gs.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(Gs.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:is(),...e})}};le();function q(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 pa(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 bi={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 _i(r){if(r in bi)return bi[r];let e=r.toLowerCase();for(let[t,s]of Object.entries(bi))if(t.toLowerCase()===e)return s;return "contextual"}function da(r){return _i(r)==="contextual"}le();function Bs(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 Ws=class{messages=[];maxMessages;constructor(e=500){this.maxMessages=e;}add(e){let t=typeof e.content=="string"?e.content:JSON.stringify(e.content),s=Bs(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=_i(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=pa(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:Bs(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:Bs(s)};return}let i={role:"system",content:s,_tag:e,_timestamp:Date.now(),_estimatedTokens:Bs(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||Bs(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(Gs.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||is(),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=wi.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=wi.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=wi.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 Bu={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}},Wu={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={...Wu,...e};}async execute(e,t){let s=Date.now(),n=Bu[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(Gs.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)+`
9
9
 
10
10
  ... [Truncated ${e.length-this.config.maxOutputSize} characters] ...
11
11
 
@@ -17,7 +17,7 @@ import*as Tn from'fs';import Tn__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
- `)}},ma=new rt;async function Hs(r,e,t){return (t?new rt(t):ma).execute(r,e)}function _i(r){let e=new rt(r);return {name:"execute_code",description:`Execute code in multiple languages (Python, JavaScript, TypeScript, Bash/Shell).
20
+ `)}},fa=new rt;async function zs(r,e,t){return (t?new rt(t):fa).execute(r,e)}function Ti(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 wi={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 Si={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 Hs(r,"python",{captureImages:e});return rt.formatResult(t)}},vi={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 zs(r,"python",{captureImages:e});return rt.formatResult(t)}},xi={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 Hs(r,"javascript");return rt.formatResult(e)}},Ti={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 zs(r,"javascript");return rt.formatResult(e)}},ki={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 Hs(r,"bash");return rt.formatResult(e)}};_i({timeout:3e4,allowNetwork:true,allowFileSystem:true,captureImages:true,maxOutputSize:1e4});_i({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
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 zs(r,"bash");return rt.formatResult(e)}};Ti({timeout:3e4,allowNetwork:true,allowFileSystem:true,captureImages:true,maxOutputSize:1e4});Ti({timeout:1e4,allowNetwork:false,allowFileSystem:false,captureImages:false,maxOutputSize:5e3});var Kn={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 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 xi(){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 Si(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 o=Kn();n.userDataDir=o,g.info("CHROME",`Using profile directory: ${o}`);}let i=await Ju.launch(n);return g.info("CHROME","Chrome launched successfully"),i}le();var Ku=["xhr","fetch"],ba=["stylesheet","script","image","font","media"];function Vu(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},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 Vn(){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=Sn__default.readFileSync("/proc/version","utf-8").toLowerCase();if(r.includes("microsoft")||r.includes("wsl"))return Bt=!0,!0}catch{}try{if(Sn__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 Ci(){return qs}function Yn(){return existsSync(qs)||(mkdirSync(qs,{recursive:true}),g.info("CHROME",`Created browser profile directory: ${qs}`)),qs}async function _a(){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;Vn()?(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 Ri(r={}){let{headless:e=true,useProfile:t=true}=r,s=await _a();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=Yn();n.userDataDir=o,g.info("CHROME",`Using profile directory: ${o}`);}let i=await Yu.launch(n);return g.info("CHROME","Chrome launched successfully"),i}le();var Xu=["xhr","fetch"],wa=["stylesheet","script","image","font","media"];function Zu(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 Xn(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=`
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(`
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&&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();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&&!Ku.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 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=>Vu(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 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((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 _a(r){let e=await Yu(r);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await Xu(r);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await Zu(r);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await Qu(r);return {url:`http://localhost:${n}`,port:n,protocol:"http",source:"default"}}async function Yu(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 Xu(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 Zu(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 Qu(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 ki(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 Ci(r){let e=await _a(r);if(await ki(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let i=`http://localhost:${n}`;if(await ki(i))return {url:i,port:n,protocol:"http",source:"default"}}return null}le();var rp="headers.json";function wa(r){try{return new URL(r).hostname}catch{return r}}function va(){let r=Kn();return join(r,rp)}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=ip(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 Ri(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 ip(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 op=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],ap=['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")'],lp=['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"]'],cp=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],up=['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=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 pp(r,e){let t=Ri(e);return !t||Object.keys(t).length===0?false:(await r.setExtraHTTPHeaders(t),true)}async function Ei(r,e){let t=r.url(),s=t.toLowerCase();if(t!==e&&op.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 ap)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 dp(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 lp)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 cp)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 up)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 er(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 Ci(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 Si({headless:l,useProfile:c}),t?.("loading",{url:a});let u=await s.newPage(),p=await pp(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 Ei(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=Sa(u,a),b=await dp(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 Ei(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
222
+ `;(t.collect_console!==false||t.collect_errors!==false)&&(await r.evaluateOnNewDocument(p),r.on("framenavigated",async x=>{if(x===r.mainFrame())try{await x.evaluate(p),g.debug("BROWSER",`Re-injected script after navigation to ${x.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=x=>{let{type:C,args:w,timestamp:T}=x,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=x=>{let{exceptionDetails:C}=x,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
+ `)||"",file:C.url,line:C.lineNumber,column:C.columnNumber,timestamp:Date.now()}),g.debug("BROWSER",`[CDP Exception] ${w}`);},f=x=>{let{entry:C}=x,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",x=>{let C=x;a.push({type:"exception",message:C.message,stack:C.stack||"",timestamp:Date.now()}),g.debug("BROWSER",`[Puppeteer pageerror] ${C.message}`);}),r.on("requestfailed",x=>{let C=x.failure();a.push({type:"browser_error",message:`Request failed: ${C?.errorText||"Unknown error"}`,stack:"",file:x.url(),timestamp:Date.now()});})),t.collect_network!==false&&(i==="cdp"||i==="both")&&(d.on("Network.requestWillBeSent",x=>{let C={url:x.request.url,method:x.request.method,resource_type:x.type?.toLowerCase()||"other",request_headers:x.request.headers,timing:{start:x.timestamp*1e3,end:0,duration:0}},w=x.type?.toLowerCase()||"other";if(!(n.xhr_only&&!["xhr","fetch"].includes(w))&&!(!n.xhr_only&&wa.includes(w))){if(x.request.postData){let T=n.body_max_length||5e3,M=x.request.postData;M.length>T?C.request_body=M.substring(0,T)+"...[truncated]":C.request_body=M;}u.set(x.requestId,C),g.debug("BROWSER",`[CDP Network] ${w.toUpperCase()} ${C.method} ${C.url}`);}}),d.on("Network.responseReceived",x=>{let C=u.get(x.requestId);C&&C.timing&&(C.status=x.response.status,C.status_text=x.response.statusText,C.response_headers=x.response.headers,C.timing.end=x.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",x=>{let C=u.get(x.requestId);C&&(C.error=x.errorText,C.timing&&(C.timing.end=x.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",x=>{let C=x.type();o.push({type:C,timestamp:Date.now(),message:x.text(),args:x.args().map(w=>w.toString())}),g.debug("BROWSER",`[Puppeteer console] ${C}: ${x.text().substring(0,100)}`);}),t.collect_network!==false&&(i==="puppeteer"||i==="both")){let x=null;if(n.url_pattern)try{x=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&&!Xu.includes(T)||!n.xhr_only&&wa.includes(T)||x&&!x.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(x=>setTimeout(x,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 x=await r.evaluate(()=>({consoleLogs:window.__NEOX_CONSOLE_LOGS__||[],errors:window.__NEOX_ERRORS__||[]}));g.debug("BROWSER",`Extracted ${x.consoleLogs.length} console logs and ${x.errors.length} errors from injected script`);for(let T of x.consoleLogs)g.debug("BROWSER",` [${T.type}] ${T.message?.substring(0,100)}`);let C=new Map;for(let T of x.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 x.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(x){g.error("BROWSER","Failed to extract injected logs",{error:x});}let b;if(t.collect_performance!==false)try{let x=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:x.Nodes||0,js_heap_size:x.JSHeapUsedSize||0,event_listeners:x.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(x){g.error("BROWSER","Failed to collect performance metrics",{error:x});}let _;if(t.take_screenshot===true)try{_=await r.screenshot({encoding:"base64"});}catch(x){g.error("BROWSER","Failed to capture screenshot",{error:x});}try{await d.detach();}catch{}if(i==="cdp"||i==="both")for(let[x,C]of u.entries())Array.from(c.values()).find(T=>T.url===C.url)||c.set(x,C);let v=Array.from(c.values());i==="cdp"&&(v=Array.from(u.values()));let k=v.length;n.status_filter&&(v=v.filter(x=>Zu(x.status,n.status_filter)));let R=v.filter(x=>x.error||x.status&&x.status>=400).length;v.sort((x,C)=>{let w=x.error||x.status&&x.status>=400,T=C.error||C.status&&C.status>=400;return w&&!T?-1:!w&&T?1:(x.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 Zn(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 va(r){let e=await Qu(r);if(e)return {url:`http://localhost:${e}`,port:e,protocol:"http",source:"vite.config"};let t=await ep(r);if(t)return {url:`http://localhost:${t}`,port:t,protocol:"http",source:"package.json"};let s=await tp(r);if(s)return {url:`http://localhost:${s}`,port:s,protocol:"http",source:"env"};let n=await sp(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 ep(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 tp(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 sp(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 Ei(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 Ii(r){let e=await va(r);if(await Ei(e.url))return e;let s=[5173,3e3,8080,5e3,4200,8e3];for(let n of s){let i=`http://localhost:${n}`;if(await Ei(i))return {url:i,port:n,protocol:"http",source:"default"}}return null}le();var ap="headers.json";function Ta(r){try{return new URL(r).hostname}catch{return r}}function Sa(){let r=Yn();return join(r,ap)}function xa(){let r=Sa();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 ka(r){let e=Sa();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 tr(r,e){let t=Ta(r),s=xa(),n=lp(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},ka(s),g.info("HEADERS","Saved headers for domain",{domain:t,headerCount:Object.keys(n).length});}function Mi(r){let e=Ta(r),t=xa(),s=t[e];return s?(s.lastUsed=Date.now(),ka(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 lp(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 cp=["login","signin","sign-in","sign_in","auth","oauth","sso","account","passport","cas","saml","oidc"],up=['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")'],pp=['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"]'],dp=['input[type="password"]','input[name="password"]','input[name="pwd"]','input[name="pass"]','input[id="password"]','input[id="pwd"]'],mp=['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 Ca(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 hp(r,e){let t=Mi(e);return !t||Object.keys(t).length===0?false:(await r.setExtraHTTPHeaders(t),true)}async function Ai(r,e){let t=r.url(),s=t.toLowerCase();if(t!==e&&cp.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 up)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 gp(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 pp)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 dp)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 mp)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 sr(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 Ii(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 Ri({headless:l,useProfile:c}),t?.("loading",{url:a});let u=await s.newPage(),p=await hp(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 Ai(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=Ca(u,a),b=await gp(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 Ai(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&&(tr(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 Xn(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=Zn({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
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}
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:xi()});let y=Sa(u,a),b=r.login_wait_time||12e4;try{await u.waitForNavigation({timeout:b,waitUntil:"networkidle0"});}catch{}let _=await Ei(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 Ii(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Terminal tools are only available in Electron UI mode")}var mp={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(i){t?.("waiting_login",{message:"\u6D4F\u89C8\u5668\u5DF2\u6253\u5F00\uFF0C\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55...",profile_path:Ci()});let y=Ca(u,a),b=r.login_wait_time||12e4;try{await u.waitForNavigation({timeout:b,waitUntil:"networkidle0"});}catch{}let _=await Ai(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&&(tr(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 Xn(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=Zn({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 Pi(){if(typeof globalThis<"u"&&globalThis.window?.electronAPI)return globalThis.window.electronAPI;throw new Error("Terminal tools are only available in Electron UI mode")}var fp={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=Ii();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)}}},hp={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,i=Pi();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)}}},yp={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=Ii();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)}}},gp={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,i=Pi();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)}}},bp={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=Ii();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)}}},Mi=[mp,hp,gp],ka=["terminal"];function tr(){return Mi.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 fp={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=Pi();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)}}},Oi=[fp,yp,bp],Ra=["terminal"];function nr(){return Oi.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ra])):Ra}))}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 _p={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)}}},yp={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: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)}}},wp={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)}}},bp={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)}}},vp={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)}}},_p={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)}}},Tp={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)}}},wp={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)}}},Sp={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)}}},vp={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: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)}}},xp={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)}}},Tp={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)}}},kp={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)}}},xp={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)}}},Cp={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)}}},Sp={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)}}},Rp={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)}}},kp={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)}}},Ep={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)}}},Cp={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)}}},Ip={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)}}},Rp={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)}}},Mp={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)}}},Ep={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)}}},Ap={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)}}},Ai=[fp,yp,bp,_p,wp,vp,Tp,xp,Sp,kp,Cp,Rp,Ep],Ca=["editor"];function sr(){return Ai.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ca])):Ca}))}le();le();var Ip=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),Mp={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"}},Ap=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);async function Pp(r){let e={types:[],skipDirs:new Set(Ip),skipPatterns:[],interestingDirs:new Set(Ap),descriptions:[]};try{let t=await Z__default.readdir(r),s=new Set(t);for(let[n,i]of Object.entries(Mp))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 Pi(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 Op(r,e){return e.interestingDirs.has(r)}async function Ra(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(Pi(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:Lp(p.name,e),itemCount:m});}else {let m=Op(p.name,e),f=(i?!1:o&&m||n<s)?await Ra(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 Lp(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 Dp(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function Oi(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(...Oi(n.children,e+a))):(t.push(`${e}${o}[~] ${n.name}/`),n.children&&n.children.length>0&&t.push(...Oi(n.children,e+a)));else {let l=n.size!==void 0?` (${Dp(n.size)})`:"";t.push(`${e}${o}[] ${n.name}${l}`);}}return t}async function $p(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()?Pi(c.name,t)||n.push(c.name):Np(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(".")&&!Pi(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 Np(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 os={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 Fp(r){let e=0,t=[];for(let s=0;s<r.length&&s<os.maxLines;s++){let n=r[s];if(e+n.length>os.maxChars){t.push(os.truncationMessage);break}t.push(n),e+=n.length+1;}return r.length>os.maxLines&&!t.includes(os.truncationMessage)&&t.push(os.truncationMessage),t}var Up="NEOX_WORKDIR";function Ea(){let r=process.env[Up];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function jp(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 Gp(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
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)}}},Li=[_p,wp,vp,Tp,Sp,xp,kp,Cp,Rp,Ep,Ip,Mp,Ap],Ea=["editor"];function rr(){return Li.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ea])):Ea}))}le();le();var Pp=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),Op={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"}},Lp=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);async function Dp(r){let e={types:[],skipDirs:new Set(Pp),skipPatterns:[],interestingDirs:new Set(Lp),descriptions:[]};try{let t=await Z__default.readdir(r),s=new Set(t);for(let[n,i]of Object.entries(Op))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 Di(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 $p(r,e){return e.interestingDirs.has(r)}async function Ia(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(Di(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:Np(p.name,e),itemCount:m});}else {let m=$p(p.name,e),f=(i?!1:o&&m||n<s)?await Ia(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 Np(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 Fp(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function $i(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(...$i(n.children,e+a))):(t.push(`${e}${o}[~] ${n.name}/`),n.children&&n.children.length>0&&t.push(...$i(n.children,e+a)));else {let l=n.size!==void 0?` (${Fp(n.size)})`:"";t.push(`${e}${o}[] ${n.name}${l}`);}}return t}async function Up(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()?Di(c.name,t)||n.push(c.name):jp(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(".")&&!Di(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 jp(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 as={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 Gp(r){let e=0,t=[];for(let s=0;s<r.length&&s<as.maxLines;s++){let n=r[s];if(e+n.length>as.maxChars){t.push(as.truncationMessage);break}t.push(n),e+=n.length+1;}return r.length>as.maxLines&&!t.includes(as.truncationMessage)&&t.push(as.truncationMessage),t}var Bp="NEOX_WORKDIR";function Ma(){let r=process.env[Bp];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Wp(r){let e=Ma();return !r||r.trim()===""||r.trim()==="."?e:Y__default.isAbsolute(r)?Y__default.resolve(r):Y__default.resolve(e,r)}function Hp(r){let e=Ma(),t=Y__default.relative(e,r);return t&&!t.startsWith("..")&&!Y__default.isAbsolute(t)?t:r}var Aa={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=jp(r),n=Gp(s);if(!(await Z__default.stat(s)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${n}`;let o=await Pp(s);if(e==="structure")return await $p(s,n,o);let a=e==="shallow",l=t??(a?1:e==="deep"?5:3),u=await Ra(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(...Oi(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')),Fp(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 Hp(){return Y__default.join(js.homedir(),".neox")}var zs=Hp(),Li=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(Li,"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(Li,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: ${Li}`),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 qp=/^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})$/,zp=/^[0-9a-f]{64}$/,Jp=/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 Kp(){let r=randomBytes(16);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Da(r)}function Vp(r){return r.match(qp)?.[1]??null}function Yp(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 Xp(){let r=Js(),e=typeof r.anthropicClientId=="string"?r.anthropicClientId.trim().toLowerCase():"";if(e&&zp.test(e))return e;let t=typeof r.anthropicProxyUserId=="string"?r.anthropicProxyUserId.trim().toLowerCase():"",n=(t?Vp(t):null)||randomBytes(32).toString("hex");return r.anthropicClientId=n,La(r),n}function $a(r,e){let t=Xp(),n=(r?r.match(Jp):null)?.[1]?.toLowerCase()||Yp(r||e||Kp());return `user_${t}_account__session_${n}`}var $i={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=Wp(r),n=Hp(s);if(!(await Z__default.stat(s)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${n}`;let o=await Dp(s);if(e==="structure")return await Up(s,n,o);let a=e==="shallow",l=t??(a?1:e==="deep"?5:3),u=await Ia(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(...$i(u));let d=Pa(u),m=Oa(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')),Gp(p).join(`
370
+ `)}catch(s){return s.code==="ENOENT"?`[x] \u76EE\u5F55\u4E0D\u5B58\u5728: ${r}`:`[x] \u626B\u63CF\u5931\u8D25: ${s.message}`}}};function Pa(r){let e=0;for(let t of r)t.skipped&&e++,t.children&&(e+=Pa(t.children));return e}function Oa(r){let e=0;for(let t of r)t.isInteresting&&e++,t.children&&(e+=Oa(t.children));return e}function Jp(){return Y__default.join(Gs.homedir(),".neox")}var Js=Jp(),Ni=Y__default.join(Js,"config.json");Y__default.join(Js,"sounds");function Da(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 Ks(){try{let r=Sn__default.readFileSync(Ni,"utf-8"),e=JSON.parse(r),{config:t,changed:s}=Da(e);if(s)try{$a(t);}catch{}return t}catch{return {}}}function $a(r){try{let{config:e}=Da(r);Sn__default.existsSync(Js)||Sn__default.mkdirSync(Js,{recursive:!0}),Sn__default.writeFileSync(Ni,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: ${Ni}`),console.error(`
372
+ Please check directory permissions or try:`),console.error(` sudo chown -R $USER "${Js}"
373
+ `)):console.error("[Config] Failed to save configuration:",t.message),e}}var Kp=/^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})$/,Vp=/^[0-9a-f]{64}$/,Yp=/session_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;function Na(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 Xp(){let r=randomBytes(16);return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Na(r)}function Zp(r){return r.match(Kp)?.[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,Na(t)}function ed(){let r=Ks(),e=typeof r.anthropicClientId=="string"?r.anthropicClientId.trim().toLowerCase():"";if(e&&Vp.test(e))return e;let t=typeof r.anthropicProxyUserId=="string"?r.anthropicProxyUserId.trim().toLowerCase():"",n=(t?Zp(t):null)||randomBytes(32).toString("hex");return r.anthropicClientId=n,$a(r),n}function Fa(r,e){let t=ed(),n=(r?r.match(Yp):null)?.[1]?.toLowerCase()||Qp(r||e||Xp());return `user_${t}_account__session_${n}`}var Ui={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,7 +378,7 @@ 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=Js().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=Ks().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
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
@@ -411,7 +411,7 @@ 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"}`}}},Na={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"}`}}},Ua={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"}
@@ -450,19 +450,19 @@ ${m}
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 Fa(r){return {...Jn,async function(e){try{g.debug("BROWSER","Starting browser debug",{url:e.url});let t=await er(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 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,i)=>{this.socket=new Ua.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 ja(r){return {...Kn,async function(e){try{g.debug("BROWSER","Starting browser debug",{url:e.url});let t=await sr(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 Vs=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 Ga.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
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 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}
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 or=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
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)
457
457
  Output so far:
458
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
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
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 ir=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(),i=new Ks;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 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,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 nd=fileURLToPath(import.meta.url),rd=Y.dirname(nd);async function id(){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(rd,"..","..","..","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 id();if(e)return e;throw new Error(`Java Debug JAR \u672A\u627E\u5230\uFF01
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 ar=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 or({jarPath:this.config.javaDebugJarPath,javaHome:this.config.javaHome,startupTimeout:this.config.defaultTimeout}),n=await s.start(),i=new Vs;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 Vs;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 od=fileURLToPath(import.meta.url),ad=Y.dirname(od);async function ld(){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(ad,"..","..","..","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 Wa(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 ld();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 Ui=null;function it(){if(!Ui)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Ui}async function ji(r){let e=await Ga(r);Ui=new ir({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[od,ad,ld,cd,ud,pd,dd,md,hd,gd,fd],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var od={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 Bi=null;function it(){if(!Bi)throw new Error("Java Debug Session Manager not initialized. Call createJavaDebugTools() first.");return Bi}async function Wi(r){let e=await Wa(r);Bi=new ar({javaDebugJarPath:e,defaultTimeout:3e4,maxSessions:5,sessionTimeout:1800*1e3});let t=[cd,ud,pd,dd,md,hd,gd,fd,yd,bd,_d],s=["debug"];return t.map(n=>({...n,capabilities:n.capabilities?Array.from(new Set([...n.capabilities,...s])):s}))}var cd={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)}}},ad={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 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)}}},ud={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)}}},ld={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 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)}}},pd={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)}}},cd={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 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)}}},dd={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)}}},ud={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 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)}}},md={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)}}},pd={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 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)}}},hd={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)}}},dd={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 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)}}},gd={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)}}},md={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 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)}}},fd={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)}}},hd={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 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)}}},yd={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)}}},gd={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 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)}}},bd={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)}}},fd={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 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)}}},_d={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 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,or=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 Gi(r,e,t){let n=(await Z.readFile(r,"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 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 Ha={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},Ys=200,lr=10,cr=4e3,cs=700;function za(r){return createHash("md5").update(r).digest("hex")}async function qa(r){try{return await Z.access(r),!0}catch{return false}}async function Xs(r){try{await Z.mkdir(r,{recursive:!0});}catch(e){if(e.code!=="EEXIST")throw e}}async function Hi(r,e,t){let n=(await Z.readFile(r,"utf-8")).split(`
614
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 ps(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 Bi(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 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 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 Wi(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=bd(t,s);return (t.length-n)/t.length}function bd(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 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:i,chunkSize:o=Vs,expandContext:a=or,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,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=ds(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 Gi(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(`
615
+ `)}function ds(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 zi(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 Ja(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 qi(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=vd(t,s);return (t.length-n)/t.length}function vd(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 ms(r){return r.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}var ur=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=Ys,expandContext:a=lr,maxLines:l=cr,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=ms(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 Hi(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(`
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:ps(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:ps(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 Gi(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,i){let a=(await Z.readFile(e,"utf-8")).split(`
619
+ `+Le(c.slice(0,Math.min(50,u)),1),truncated:false,strategy:"grep",metadata:{module:ds(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:ds(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 Hi(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:ds(e,this.workspacePath)}}}catch{return null}}async readSymbolBlock(e,t,s,n,i){let a=(await Z.readFile(e,"utf-8")).split(`
620
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}"
621
621
 
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+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:ps(e,this.workspacePath)}}}async readByRange(e,t,s,n,i){let a=(await Z.readFile(e,"utf-8")).split(`
622
+ `+Le(a.slice(0,Math.min(50,l)),1),truncated:false,strategy:"grep"};let p=Ja(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:ds(e,this.workspacePath)}}}async readByRange(e,t,s,n,i){let a=(await Z.readFile(e,"utf-8")).split(`
623
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}"
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:ps(e,this.workspacePath)}}}async readChunk(e,t,s,n){let i=await Z.readFile(e,"utf-8"),o=ds(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=ds(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 Hi(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 Cd={"[: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,"\\$&"),Rd=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),il=r=>r.join(""),ol=(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(Cd))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(Qs(p)+"-"+Qs(f)):f===p&&s.push(Qs(f)),p="",i++;continue}if(r.startsWith("-]",i+1)){s.push(Qs(f+"-")),i+=2;continue}if(r.startsWith("-",i+1)){p=f,i+=2;continue}s.push(Qs(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 [Rd(f),false,u-t,false]}let d="["+(c?"^":"")+il(s)+"]",m="["+(c?"":"^")+il(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 Ed=new Set(["!","?","+","*","@"]),al=r=>Ed.has(r),Id="(?!(?:^|/)\\.\\.?(?:$|/))",ur="(?!\\.)",Md=new Set(["[","."]),Ad=new Set(["..","."]),Pd=new Set("().*{}+?[]^$\\!"),Od=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ji="[^/]",ll=Ji+"*?",cl=Ji+"+?",ms=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&&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(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(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,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&&Ad.has(this.#n[0]))){let h=Md,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?Id:y?ur:"";}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||!ur?"":this.#m(true);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);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==="+"&&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+=(Pd.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":n=true;continue}if(l==="["){let[c,u,p,d]=ol(e,a);if(p){i+=c,o=o||u,a+=p-1,t=t||d;continue}}if(l==="*"){s&&e==="*"?i+=cl:i+=ll,t=true;continue}if(l==="?"){i+=Ji,t=true;continue}i+=Od(l);}return [i,ot(e),!!t,o]}};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)),Ld=/^\*+([^+@!?\*\[\(]*)$/,Dd=r=>e=>!e.startsWith(".")&&e.endsWith(r),$d=r=>e=>e.endsWith(r),Nd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),Fd=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Ud=/^\*+\.\*+$/,jd=r=>!r.startsWith(".")&&r.includes("."),Gd=r=>r!=="."&&r!==".."&&r.includes("."),Bd=/^\.\*+$/,Wd=r=>r!=="."&&r!==".."&&r.startsWith("."),Hd=/^\*+$/,qd=r=>r.length!==0&&!r.startsWith("."),zd=r=>r.length!==0&&r!=="."&&r!=="..",Jd=/^\?+([^+@!?\*\[\(]*)?$/,Kd=([r,e=""])=>{let t=ml([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Vd=([r,e=""])=>{let t=hl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Yd=([r,e=""])=>{let t=hl([r]);return e?s=>t(s)&&s.endsWith(e):t},Xd=([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:"/"}},Zd=gl==="win32"?ul.win32.sep:ul.posix.sep;Ue.sep=Zd;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var Qd="[^/]",em=Qd+"*?",tm="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",sm="(?:(?!(?:\\/|^)\\.).)*?",nm=(r,e={})=>t=>Ue(t,r,e);Ue.filter=nm;var Ze=(r,e={})=>Object.assign({},r,e),rm=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=rm;var fl=(r,e={})=>(Zs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, dl.default)(r));Ue.braceExpand=fl;var im=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=im;var om=(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=om;var pl=/[?*]|[+@!]\(.*?\)|\[|\]/,am=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=(...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]==="?"||!pl.test(i[2]))&&!pl.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+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:ds(e,this.workspacePath)}}}async readChunk(e,t,s,n){let i=await Z.readFile(e,"utf-8"),o=ms(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=ms(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 Ji(r){return new ur(r)}var hl=Cu(ol());var Qs=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var Id={"[: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]},en=r=>r.replace(/[[\]\\-]/g,"\\$&"),Md=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),al=r=>r.join(""),ll=(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(Id))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(en(p)+"-"+en(f)):f===p&&s.push(en(f)),p="",i++;continue}if(r.startsWith("-]",i+1)){s.push(en(f+"-")),i+=2;continue}if(r.startsWith("-",i+1)){p=f,i+=2;continue}s.push(en(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 [Md(f),false,u-t,false]}let d="["+(c?"^":"")+al(s)+"]",m="["+(c?"":"^")+al(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 Ad=new Set(["!","?","+","*","@"]),cl=r=>Ad.has(r),Pd="(?!(?:^|/)\\.\\.?(?:$|/))",dr="(?!\\.)",Od=new Set(["[","."]),Ld=new Set(["..","."]),Dd=new Set("().*{}+?[]^$\\!"),$d=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Yi="[^/]",ul=Yi+"*?",pl=Yi+"+?",hs=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&&cl(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(cl(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&&Ld.has(this.#n[0]))){let h=Od,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?Pd:y?dr:"";}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||!dr?"":this.#m(true);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let a="";if(this.type==="!"&&this.#r)a=(this.isStart()&&!t?dr:"")+pl;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?dr:"")+ul+")":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+=(Dd.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?i+="\\\\":n=true;continue}if(l==="["){let[c,u,p,d]=ll(e,a);if(p){i+=c,o=o||u,a+=p-1,t=t||d;continue}}if(l==="*"){s&&e==="*"?i+=pl:i+=ul,t=true;continue}if(l==="?"){i+=Yi,t=true;continue}i+=$d(l);}return [i,ot(e),!!t,o]}};var gs=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var Ue=(r,e,t={})=>(Qs(e),!t.nocomment&&e.charAt(0)==="#"?false:new Ke(e,t).match(r)),Nd=/^\*+([^+@!?\*\[\(]*)$/,Fd=r=>e=>!e.startsWith(".")&&e.endsWith(r),Ud=r=>e=>e.endsWith(r),jd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),Gd=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Bd=/^\*+\.\*+$/,Wd=r=>!r.startsWith(".")&&r.includes("."),Hd=r=>r!=="."&&r!==".."&&r.includes("."),zd=/^\.\*+$/,qd=r=>r!=="."&&r!==".."&&r.startsWith("."),Jd=/^\*+$/,Kd=r=>r.length!==0&&!r.startsWith("."),Vd=r=>r.length!==0&&r!=="."&&r!=="..",Yd=/^\?+([^+@!?\*\[\(]*)?$/,Xd=([r,e=""])=>{let t=gl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Zd=([r,e=""])=>{let t=fl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Qd=([r,e=""])=>{let t=fl([r]);return e?s=>t(s)&&s.endsWith(e):t},em=([r,e=""])=>{let t=gl([r]);return e?s=>t(s)&&s.endsWith(e):t},gl=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},fl=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},yl=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",dl={win32:{sep:"\\"},posix:{sep:"/"}},tm=yl==="win32"?dl.win32.sep:dl.posix.sep;Ue.sep=tm;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var sm="[^/]",nm=sm+"*?",rm="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",im="(?:(?!(?:\\/|^)\\.).)*?",om=(r,e={})=>t=>Ue(t,r,e);Ue.filter=om;var Ze=(r,e={})=>Object.assign({},r,e),am=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=am;var bl=(r,e={})=>(Qs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, hl.default)(r));Ue.braceExpand=bl;var lm=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=lm;var cm=(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=cm;var ml=/[?*]|[+@!]\(.*?\)|\[|\]/,um=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={}){Qs(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||yl,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]==="?"||!ml.test(i[2]))&&!ml.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(`
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 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(Hd))?n=t.dot?zd:qd:(s=e.match(Ld))?n=(t.nocase?t.dot?Fd:Nd:t.dot?$d:Dd)(s[1]):(s=e.match(Jd))?n=(t.nocase?t.dot?Vd:Kd:t.dot?Yd:Xd)(s):(s=e.match(Ud))?n=t.dot?Gd:jd:(s=e.match(Bd))&&(n=Wd);let i=ms.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?em:t.dot?tm:sm,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"?am(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=ms;Ue.Minimatch=Ke;Ue.escape=hs;Ue.unescape=ot;var gs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,bl=new Set,Ki=typeof process=="object"&&process?process:{},_l=(r,e,t,s)=>{typeof Ki.emitWarning=="function"?Ki.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=Ki.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 lm=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);}},Vi=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;#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?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.#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=Vi.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";lm(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=(i,o,a=gs.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?gs.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=gs.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 fs(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-(gs.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=gs.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=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: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 pr,{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 pr}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 vl=typeof process=="object"&&process?process:{stdout:null,stderr:null},um=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof kl||pm(r)||dm(r)),pm=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==kl.Writable.prototype.pipe,dm=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"),Yi=Symbol("bufferPush"),gr=Symbol("bufferShift"),De=Symbol("objectMode"),ke=Symbol("destroyed"),Xi=Symbol("error"),Zi=Symbol("emitData"),Sl=Symbol("emitEnd"),Qi=Symbol("emitEnd2"),mt=Symbol("async"),eo=Symbol("abort"),fr=Symbol("aborted"),nn=Symbol("signal"),Ht=Symbol("dataListeners"),Ve=Symbol("discarded"),rn=r=>Promise.resolve().then(r),mm=r=>r(),hm=r=>r==="end"||r==="finish"||r==="prefinish",gm=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,fm=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();}},to=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);}},ym=r=>!!r.objectMode,bm=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");ym(t)?(this[De]=true,this[at]=null):bm(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[eo]():s.addEventListener("abort",()=>this[eo]()));}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;}[eo](){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:mm;if(!this[De]&&!Buffer.isBuffer(e)){if(fm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(gm(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[Yi](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[Yi](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]}[Yi](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 to(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(hm(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[Zi](s)),true):this[Zi](s);if(e==="end")return this[Sl]();if(e==="close"){if(this[mr]=true,!this[At]&&!this[ke])return false;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[tn]=s,super.emit(Xi,s);let i=!this[nn]||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}[Zi](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[Qi]()),true):this[Qi]())}[Qi](){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 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(Xi,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(Xi,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 um}};var Rm=realpathSync.native,an={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Rm,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,Pm=r=>r.replace(/\//g,"\\").replace(Al,"$1\\"),Om=/[\\\/]/,et=0,Pl=1,Ol=2,ht=4,Ll=6,Dl=8,qt=10,$l=12,Qe=15,on=~Qe,no=16,Cl=32,ln=64,lt=128,br=256,wr=512,Rl=ln|lt|wr,Lm=1023,ro=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});}},oo=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}#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?_r(e):cn(e),this.#s=t&Lm,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=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&=~no,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 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)===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&no)}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|=no;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=ro(e),n=this.newChild(e.name,s,{parent:this}),i=n.#s&Qe;return i!==ht&&i!==qt&&i!==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 i=t.name;return t.#s=t.#s&on|ro(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=ro(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 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&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=Om;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=Pm(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,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)}},Sr=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:i=16*1024,fs:o=an}={}){this.#n=Ml(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 vr,this.#t=new vr,this.#i=new oo(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[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 Dm=r=>r.length>=1,$m=r=>r.length>=1,vs=class r{#e;#t;#i;length;#n;#o;#w;#c;#p;#a;#l=true;constructor(e,t,s,n){if(!Dm(e))throw new TypeError("empty pattern list");if(!$m(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 Nm=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:i,platform:o=Nm}){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 vs(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 ao=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()]));}},lo=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)])}},co=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 lo;subwalks=new co;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new ao;}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 Fm=(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;#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=Fm(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 pn(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 pn(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();}},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 jm=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||jm,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},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 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 uo=(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 Gm=Cr,Bm=Object.assign(jl,{sync:Cr}),Wm=Rr,Hm=Object.assign(Bl,{sync:Rr}),qm=Object.assign(Gl,{stream:Cr,iterate:Rr}),xs=Object.assign(Ul,{glob:Ul,globSync:Gl,sync:qm,globStream:jl,stream:Bm,globStreamSync:Cr,streamSync:Gm,globIterate:Bl,iterate:Hm,globIterateSync:Rr,iterateSync:Wm,Glob:ct,hasMagic:uo,escape:hs,unescape:ot});xs.glob=xs;var hn=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
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 bl(this.pattern,this.options)}parse(e){Qs(e);let t=this.options;if(e==="**")return Ae;if(e==="")return "";let s,n=null;(s=e.match(Jd))?n=t.dot?Vd:Kd:(s=e.match(Nd))?n=(t.nocase?t.dot?Gd:jd:t.dot?Ud:Fd)(s[1]):(s=e.match(Yd))?n=(t.nocase?t.dot?Zd:Xd:t.dot?Qd:em)(s):(s=e.match(Bd))?n=t.dot?Hd:Wd:(s=e.match(zd))&&(n=qd);let i=hs.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?nm:t.dot?rm:im,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"?um(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=hs;Ue.Minimatch=Ke;Ue.escape=gs;Ue.unescape=ot;var fs=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,wl=new Set,Xi=typeof process=="object"&&process?process:{},vl=(r,e,t,s)=>{typeof Xi.emitWarning=="function"?Xi.emitWarning(r,e,t,s):console.error(`[${t}] ${e}: ${r}`);},mr=globalThis.AbortController,_l=globalThis.AbortSignal;if(typeof mr>"u"){_l=class{onabort;_onabort=[];reason;aborted=false;addEventListener(s,n){this._onabort.push(n);}},mr=class{constructor(){e();}signal=new _l;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=Xi.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=false,vl("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 pm=r=>!wl.has(r);var Mt=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Tl=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?ys:null:null,ys=class extends Array{constructor(e){super(e),this.fill(0);}},Zi=class r{heap;length;static#e=false;static create(e){let t=Tl(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]}},tn=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;#S;#g;#x;#k;#_;#v;#T;#h;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#_,sizes:e.#x,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.#S,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?Tl(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.#S=Zi.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";pm(F)&&(wl.add(F),vl("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 ys(this.#e),t=new ys(this.#e);this.#_=e,this.#k=t,this.#P=(i,o,a=fs.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?fs.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=fs.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 ys(this.#e);this.#p=0,this.#x=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-(fs.now()-a);i.ttl=l,i.start=Date.now();}}return this.#x&&(i.size=this.#x[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=fs.now()-this.#k[t];o.start=Math.floor(Date.now()-a);}this.#x&&(o.size=this.#x[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=fs.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.#S.length!==0?this.#S.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.#S.push(t)),this.#c===1?(this.#m=this.#d=0,this.#S.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 mr,{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 mr}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),x=W.__staleWhileFetching!==void 0&&s;return b&&(b.fetch=O?"stale":"refresh",x&&O&&(b.returnedStale=true)),x?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.#S.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.#x&&this.#x.fill(0),this.#m=0,this.#d=0,this.#S.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 Sl=typeof process=="object"&&process?process:{stdout:null,stderr:null},mm=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof Rl||hm(r)||gm(r)),hm=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Rl.Writable.prototype.pipe,gm=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"),hr=Symbol("emittingEnd"),sn=Symbol("emittedError"),gr=Symbol("closed"),xl=Symbol("read"),fr=Symbol("flush"),kl=Symbol("flushChunk"),at=Symbol("encoding"),bs=Symbol("decoder"),Ee=Symbol("flowing"),nn=Symbol("paused"),_s=Symbol("resume"),Ie=Symbol("buffer"),je=Symbol("pipes"),Me=Symbol("bufferLength"),Qi=Symbol("bufferPush"),yr=Symbol("bufferShift"),De=Symbol("objectMode"),ke=Symbol("destroyed"),eo=Symbol("error"),to=Symbol("emitData"),Cl=Symbol("emitEnd"),so=Symbol("emitEnd2"),mt=Symbol("async"),no=Symbol("abort"),br=Symbol("aborted"),rn=Symbol("signal"),Ht=Symbol("dataListeners"),Ve=Symbol("discarded"),on=r=>Promise.resolve().then(r),fm=r=>r(),ym=r=>r==="end"||r==="finish"||r==="prefinish",bm=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,_m=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),_r=class{src;dest;opts;ondrain;constructor(e,t,s){this.src=e,this.dest=t,this.opts=s,this.ondrain=()=>e[_s](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},ro=class extends _r{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);}},wm=r=>!!r.objectMode,vm=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",Pt=class extends EventEmitter{[Ee]=false;[nn]=false;[je]=[];[Ie]=[];[De];[at];[mt];[bs];[vt]=false;[At]=false;[hr]=false;[gr]=false;[sn]=null;[Me]=0;[ke]=false;[rn];[br]=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");wm(t)?(this[De]=true,this[at]=null):vm(t)?(this[at]=t.encoding,this[De]=false):(this[De]=false,this[at]=null),this[mt]=!!t.async,this[bs]=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[rn]=s,s.aborted?this[no]():s.addEventListener("abort",()=>this[no]()));}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;}[no](){this[br]=true,this.emit("abort",this[rn]?.reason),this.destroy(this[rn]?.reason);}get aborted(){return this[br]}set aborted(e){}write(e,t,s){if(this[br])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]?on:fm;if(!this[De]&&!Buffer.isBuffer(e)){if(_m(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(bm(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[fr](true),this[Ee]?this.emit("data",e):this[Qi](e),this[Me]!==0&&this.emit("readable"),s&&n(s),this[Ee]):e.length?(typeof e=="string"&&!(t===this[at]&&!this[bs]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[at]&&(e=this[bs].write(e)),this[Ee]&&this[Me]!==0&&this[fr](true),this[Ee]?this.emit("data",e):this[Qi](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[xl](e||null,this[Ie][0]);return this[Tt](),t}[xl](e,t){if(this[De])this[yr]();else {let s=t;e===s.length||e===null?this[yr]():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[nn])&&this[Tt](),this}[_s](){this[ke]||(!this[Ht]&&!this[je].length&&(this[Ve]=true),this[nn]=false,this[Ee]=true,this.emit("resume"),this[Ie].length?this[fr]():this[vt]?this[Tt]():this.emit("drain"));}resume(){return this[_s]()}pause(){this[Ee]=false,this[nn]=true,this[Ve]=false;}get destroyed(){return this[ke]}get flowing(){return this[Ee]}get paused(){return this[nn]}[Qi](e){this[De]?this[Me]+=1:this[Me]+=e.length,this[Ie].push(e);}[yr](){return this[De]?this[Me]-=1:this[Me]-=this[Ie][0].length,this[Ie].shift()}[fr](e=false){do;while(this[kl](this[yr]())&&this[Ie].length);!e&&!this[Ie].length&&!this[vt]&&this.emit("drain");}[kl](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===Sl.stdout||e===Sl.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,s?t.end&&e.end():(this[je].push(t.proxyErrors?new ro(this,e,t):new _r(this,e,t)),this[mt]?on(()=>this[_s]()):this[_s]()),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[_s]();else if(e==="readable"&&this[Me]!==0)super.emit("readable");else if(ym(e)&&this[At])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[sn]){let n=t;this[mt]?on(()=>n.call(this,this[sn])):n.call(this,this[sn]);}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[hr]&&!this[At]&&!this[ke]&&this[Ie].length===0&&this[vt]&&(this[hr]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[gr]&&this.emit("close"),this[hr]=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]?(on(()=>this[to](s)),true):this[to](s);if(e==="end")return this[Cl]();if(e==="close"){if(this[gr]=true,!this[At]&&!this[ke])return false;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[sn]=s,super.emit(eo,s);let i=!this[rn]||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}[to](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}[Cl](){return this[At]?false:(this[At]=true,this.readable=false,this[mt]?(on(()=>this[so]()),true):this[so]())}[so](){if(this[bs]){let t=this[bs].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(eo,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(eo,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[gr]&&t.close(),e?this.emit("error",e):this.emit(ke),this}static get isStream(){return mm}};var Mm=realpathSync.native,ln={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Mm,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Pl=r=>!r||r===ln||r===Sn?ln:{...ln,...r,promises:{...ln.promises,...r.promises||{}}},Ol=/^\\\\\?\\([a-z]:)\\?$/i,Dm=r=>r.replace(/\//g,"\\").replace(Ol,"$1\\"),$m=/[\\\/]/,et=0,Ll=1,Dl=2,ht=4,$l=6,Nl=8,zt=10,Fl=12,Qe=15,an=~Qe,oo=16,El=32,cn=64,lt=128,wr=256,Tr=512,Il=cn|lt|Tr,Nm=1023,ao=r=>r.isFile()?Nl:r.isDirectory()?ht:r.isSymbolicLink()?zt:r.isCharacterDevice()?Dl:r.isBlockDevice()?$l:r.isSocket()?Fl:r.isFIFO()?Ll:et,Ml=new Map,un=r=>{let e=Ml.get(r);if(e)return e;let t=r.normalize("NFKD");return Ml.set(r,t),t},Al=new Map,vr=r=>{let e=Al.get(r);if(e)return e;let t=un(r.toLowerCase());return Al.set(r,t),t},Sr=class extends tn{constructor(){super({max:256});}},co=class extends tn{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Ul=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}#S;get atime(){return this.#S}#g;get mtime(){return this.#g}#x;get ctime(){return this.#x}#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?vr(e):un(e),this.#s=t&Nm,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=Pl(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&=~oo,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let s=this.children(),n=this.nocase?vr(e):un(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)===Nl}isDirectory(){return (this.#s&Qe)===ht}isCharacterDevice(){return (this.#s&Qe)===Dl}isBlockDevice(){return (this.#s&Qe)===$l}isFIFO(){return (this.#s&Qe)===Ll}isSocket(){return (this.#s&Qe)===Fl}isSymbolicLink(){return (this.#s&zt)===zt}lstatCached(){return this.#s&El?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!==zt||this.#s&wr||this.#s&lt)}calledReaddir(){return !!(this.#s&oo)}isENOENT(){return !!(this.#s&lt)}isNamed(e){return this.nocase?this.#_===vr(e):this.#_===un(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|=oo;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)&an,this.#R());}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#D();}#E(){this.#s|=Tr,this.#$();}#$(){if(this.#s&cn)return;let e=this.#s;(e&Qe)===ht&&(e&=an),this.#s=e|cn,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|=wr,e==="ENOENT"&&(t|=lt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=an),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=ao(e),n=this.newChild(e.name,s,{parent:this}),i=n.#s&Qe;return i!==ht&&i!==zt&&i!==et&&(n.#s|=cn),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?vr(e.name):un(e.name))===n.#_)return this.#G(e,n,s,t)}}#G(e,t,s,n){let i=t.name;return t.#s=t.#s&an|ao(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.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s&lt)===0)try{return this.#z(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#F(e.code);}}#z(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.#S=t,this.#f=s,this.#k=n,this.#d=i,this.#p=o,this.#r=a,this.#x=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=ao(e);this.#s=this.#s&an|k|El,k!==et&&k!==ht&&k!==zt&&(this.#s|=cn);}#W=[];#H=false;#q(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.#q(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&Il)return false;let e=Qe&this.#s;return e===et||e===ht||e===zt}shouldWalk(e,t){return (this.#s&ht)===ht&&!(this.#s&Il)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#M)return this.#M;if(!((Tr|wr|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(!((Tr|wr|lt)&this.#s))try{let e=this.#e.realpathSync(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}[Ul](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;}},xr=class r extends $e{sep="\\";splitSep=$m;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=Dm(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 ws(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Ol,"$1\\"),e===t}},kr=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)}},Cr=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#n;constructor(e=process.cwd(),t,s,{nocase:n,childrenCacheSize:i=16*1024,fs:o=ln}={}){this.#n=Pl(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 Sr,this.#t=new Sr,this.#i=new co(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[Ul](t);}},ws=class extends Cr{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 xr(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)}},vs=class extends Cr{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 kr(this.rootPath,ht,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},pn=class extends vs{constructor(e=process.cwd(),t={}){let{nocase:s=true}=t;super(e,{...t,nocase:s});}};process.platform==="win32"?xr:kr;var jl=process.platform==="win32"?ws:process.platform==="darwin"?pn:vs;var Fm=r=>r.length>=1,Um=r=>r.length>=1,Ts=class r{#e;#t;#i;length;#n;#o;#w;#c;#p;#a;#l=true;constructor(e,t,s,n){if(!Fm(e))throw new TypeError("empty pattern list");if(!Um(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 jm=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ss=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:s,noext:n,noglobstar:i,platform:o=jm}){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 Ts(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 uo=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()]));}},po=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)])}},mo=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())}},dn=class r{hasWalkedCache;matches=new po;subwalks=new mo;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new uo;}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 Gm=(r,e)=>typeof r=="string"?new Ss([r],e):Array.isArray(r)?new Ss(r,e):r,Rr=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=Gm(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 dn(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 dn(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();}},mn=class extends Rr{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}},hn=class extends Rr{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 Wm=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||Wm,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"?ws:t.platform==="darwin"?pn:t.platform?vs:jl;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 Ts(l,u,0,this.platform)});}async walk(){return [...await 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}).walk()]}walkSync(){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}).walkSync()]}stream(){return new hn(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 hn(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 ho=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Ke(t,e).hasMagic())return true;return false};function Er(r,e={}){return new ct(r,e).streamSync()}function Bl(r,e={}){return new ct(r,e).stream()}function Wl(r,e={}){return new ct(r,e).walkSync()}async function Gl(r,e={}){return new ct(r,e).walk()}function Ir(r,e={}){return new ct(r,e).iterateSync()}function Hl(r,e={}){return new ct(r,e).iterate()}var Hm=Er,zm=Object.assign(Bl,{sync:Er}),qm=Ir,Jm=Object.assign(Hl,{sync:Ir}),Km=Object.assign(Wl,{stream:Er,iterate:Ir}),xs=Object.assign(Gl,{glob:Gl,globSync:Wl,sync:Km,globStream:Bl,stream:zm,globStreamSync:Er,streamSync:Hm,globIterate:Hl,iterate:Jm,globIterateSync:Ir,iterateSync:qm,Glob:ct,hasMagic:ho,escape:gs,unescape:ot});xs.glob=xs;var gn=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let s=e.split(`
630
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 gn=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let s=e.split(`
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 fn=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let s=e.split(`
632
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 fn=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 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 zm="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:i=this.config.languages,force:o=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=Bi(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:zm,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=Bi(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:Wa(n),mtime:i.mtimeMs,totalLines:n.split(`
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 yn=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 bn=class{parsers=new Map;constructor(){this.register(new gn),this.register(new fn),this.register(new yn);}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 Vm="1.0.0",Mr=class{workspacePath;config;metadata=null;fileIndexCache=new Map;parserRegistry;constructor(e,t={}){this.workspacePath=e,this.config={...Ha,...t},this.parserRegistry=new bn;}get indexDir(){return Y.join(this.workspacePath,this.config.cacheDir)}async hasIndex(){let e=Y.join(this.indexDir,"meta.json");return qa(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 Xs(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 Xs(this.indexDir),await Xs(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=zi(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:Vm,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=zi(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:za(n),mtime:i.mtimeMs,totalLines:n.split(`
635
635
  `).length,symbols:o,imports:a,exports:l}}catch{return null}}extractImports(e,t){let s=[],n=e.split(`
636
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 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: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=Wi(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=Wi(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 po(r,e){return new Er(r,e)}var Ss=null,ks=null,Mr=null,zt={small:ls,large:1e3},Wl=12e3,Jm=120,Ir=20,Km=3,Vm=200,mo=200;function Ym(r){return (!Ss||Mr!==r)&&(Ss=Hi(r),Mr=r,ks&&Ss.setIndexManager(ks)),Ss}function bn(r){return (!ks||Mr!==r)&&(ks=po(r),Mr=r,Ss&&Ss.setIndexManager(ks)),ks}function Xm(r){return process.cwd()}function gt(r){let e=Xm();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 Zm(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function go(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 go(r);return e.hasIndex?`
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 Xs(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=qi(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=qi(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 go(r,e){return new Mr(r,e)}var ks=null,Cs=null,Pr=null,qt={small:cs,large:1e3},zl=12e3,Ym=120,Ar=20,Xm=3,Zm=200,fo=200;function Qm(r){return (!ks||Pr!==r)&&(ks=Ji(r),Pr=r,Cs&&ks.setIndexManager(Cs)),ks}function _n(r){return (!Cs||Pr!==r)&&(Cs=go(r),Pr=r,ks&&ks.setIndexManager(Cs)),Cs}function eh(r){return process.cwd()}function gt(r){let e=eh();return Y.relative(e,r)||r}function ql(r,e){let t=Y.relative(r,e);return t===""?true:!t.startsWith("..")&&!Y.isAbsolute(t)}function th(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function bo(r){let e=r||process.cwd(),s=await _n(e).getStats();return {hasIndex:s.hasIndex,fileCount:s.fileCount,symbolCount:s.symbolCount,lastUpdated:s.lastUpdated}}async function Jl(r){let e=await bo(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${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
640
- - \u5927\u6587\u4EF6 (>${zt.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
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
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${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
646
+ - \u5C0F\u6587\u4EF6 (\u2264${qt.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 fo(r){let e=await go(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 yo(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 _o(r){let e=await bo(r);await Jl(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 wo(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${ls} \u884C\u9ED8\u8BA4 full
659
- - >${ls} \u884C\u5EFA\u8BAE pattern/list_matches \u518D\u6309\u884C\u6279\u91CF\u8BFB\u53D6
658
+ - \u2264${cs} \u884C\u9ED8\u8BA4 full
659
+ - >${cs} \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: ${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=Ym(M),E=w===true,L=typeof S=="number"?Math.max(0,S):or,N=typeof T=="number"&&T>0?Math.floor(T):Wl,$=d||(E?Jm: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
- `);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=mo+12,xe=Math.max(5,Math.min(Vm,Math.floor(N/we))),I=H.slice(0,xe),j=I.map(ge=>{let fe=ge.text.length>mo?`${ge.text.slice(0,mo)}...`: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
- `)}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
- `).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
- ${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
- `).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
- `).map(we=>{let xe=we.match(/^\s*\d+\s*│\s?(.*)$/);return xe?xe[1]:we}).join(`
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?ls:void 0,chunkSize:$,expandContext:L,useIndex:C});if(!J.success)return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.error}
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: ${Ys})`},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: ${zl})`}},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:x,use_index:C=true,for_edit:w,max_output_chars:T}=l,M=e(),B=Qm(M),E=w===true,L=typeof x=="number"?Math.max(0,x):lr,N=typeof T=="number"&&T>0?Math.floor(T):zl,$=d||(E?Ym:Ys);$=Math.min($,cr),!d&&_&&($=Math.max(Ar,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=ms(pe).split(`
692
+ `);return {absPath:J,lines:D,totalLines:D.length}},U=(J,pe,S)=>{let D=Math.max(1,Math.floor(J)),H=typeof pe=="number"?Math.floor(pe):D+$-1,V=Math.min(S,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),S=[];for(let D of pe){let H=S[S.length-1];!H||D.start>H.end+1?S.push({...D}):H.end=Math.max(H.end,D.end);}return S};if(A){if(!_)return "\u2717 list_matches \u9700\u8981\u914D\u5408 pattern \u4F7F\u7528";try{let{absPath:J,lines:pe,totalLines:S}=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,S)),1);return [`\u2713 \u6587\u4EF6: ${V}`,`\u603B\u884C\u6570: ${S} | \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=fo+12,Se=Math.max(5,Math.min(Zm,Math.floor(N/we))),I=H.slice(0,Se),j=I.map(ge=>{let fe=ge.text.length>fo?`${ge.text.slice(0,fo)}...`:ge.text;return `${String(ge.line).padStart(6)} \u2502 ${fe}`}),z=[`\u2713 \u6587\u4EF6: ${V}`,`\u603B\u884C\u6570: ${S} | \u5339\u914D: ${H.length}`,"\u7B56\u7565: grep-list","",`--- \u5339\u914D\u6458\u8981\uFF08\u524D ${j.length}/${H.length}\uFF09---`,...j];j.length<H.length&&z.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 z.push("",`\u{1F4A1} \u8BFB\u53D6\u5339\u914D\u9644\u8FD1: readfile(path="${V}", anchor_lines=[${ye}], num_lines=${Math.min(200,$)})`),z.join(`
694
+ `)}catch(J){return `\u2717 \u8BFB\u53D6\u5931\u8D25: ${J.message}`}}if(G||X)try{let{absPath:J,lines:pe,totalLines:S}=await K(),D=[];if(G)for(let j of W)!j||typeof j.start!="number"||D.push(U(j.start,j.end,S));else if(X){let j=Math.max(1,d||L*2+1);for(let z of F){if(typeof z!="number"||Number.isNaN(z))continue;let ye=Math.max(1,Math.floor(z-Math.floor(j/2))),ge=Math.min(S,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: ${S} | \u533A\u5757: ${H.length}`,"\u7B56\u7565: batch-range","","--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"],Se=we.join(`
695
+ `).length,I=0;for(let[j,z]of H.entries()){let ye=Le(pe.slice(z.start-1,z.end),z.start),fe=`${`# \u533A\u5757 ${j+1}: ${z.start}-${z.end}`}
696
+ ${ye}`;if(Se+fe.length+2>N&&I>0)break;we.push(fe,""),Se+=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
+ `).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 S=[`\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&&S.push(`\u7B26\u53F7: ${J.metadata.symbol.name} (${J.metadata.symbol.kind})`),J.truncated&&(S.push(""),S.push(`\u26A0\uFE0F \u5185\u5BB9\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528 start_line=${J.endLine+1} \u7EE7\u7EED\u8BFB\u53D6`)),S.push(""),S.push("--- \u5185\u5BB9\uFF08\u5E26\u884C\u53F7\uFF0C\u4FBF\u4E8E\u9605\u8BFB\uFF09---"),S.push(J.content),E){let V=J.content.split(`
698
+ `).map(we=>{let Se=we.match(/^\s*\d+\s*│\s?(.*)$/);return Se?Se[1]:we}).join(`
699
+ `);S.push(""),S.push("--- \u{1F525} COPY THIS FOR edit_file old_string (\u4E0D\u5E26\u884C\u53F7) ---"),S.push(V),S.push("--- END ---");}return S.join(`
700
+ `)},ie=0,se="",ae=!d;for(;;){let J=await B.read({path:c,locator:Te,mode:"smart",autoFullThreshold:ae?cs: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>ls&&J.strategy==="chunk"&&(se+=`
704
+ - \u4F7F\u7528 search_files \u67E5\u627E\u6587\u4EF6`;if(se=Q(J),!Te&&J.totalLines>cs&&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(Ir,Math.floor($*D)),ie+=1;continue}if(d||se.length<=N||ie>=Km||$<=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,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(Ar,Math.floor($*D)),ie+=1;continue}if(d||se.length<=N||ie>=Xm||$<=Ar)return se;let pe=Math.max(.1,Math.min(.9,N/se.length)),S=Math.max(Ar,Math.floor($*pe));if(S>=$)return se;$=S,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
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 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(`
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 _n(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=bn(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=_n(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
@@ -753,9 +753,9 @@ search_symbol(query="usr", fuzzy=true) \u2192 \u6A21\u7CCA\u641C\u7D22
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=bn(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=_n(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(!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}"
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(!ql(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
 
@@ -768,10 +768,10 @@ get_definitions(query="User", path="src/auth") \u2192 \u9650\u5B9A\u76EE\u5F55`
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(!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:Zm(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
- `),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
- \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 bn(l).getStats();if(!u.hasIndex)return `\u{1F4CA} \u7D22\u5F15\u72B6\u6001: \u672A\u6784\u5EFA
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(!ql(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 x=y?c:th(c);b=new RegExp(x,f?"gi":"g");}catch(x){return `\u2717 \u65E0\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F: ${x.message}`}let _=[];if(d.isDirectory()){let x=l.file_pattern||"**/*";_=await xs(x,{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 x of _){if(k>=h)break;try{let C=await Z.readFile(x,"utf-8");if(C.includes("\0"))continue;let w=C.split(`
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:x,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(x=>x!=="");for(let x of v){let C=gt(x.file);F.push(`
773
+ \u25B8 ${C} (${x.matchCount} \u5904)`),F.push("\u2500".repeat(50));let w=-10;for(let T of x.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 _n(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 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),i=t.substring(s+1);e[n]=i;}}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 bo=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");}},Yl=new bo;var Ar={terminal:true,editor:false,debug:true,trace:true},_o={...Ar,editor:true};le();function sh(){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=sh(),vo=Y__default.join(Zl,"token-usage.json"),Xl=3e3,To=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(vo,"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=`${vo}.${Date.now()}.tmp`;await Z__default.writeFile(e,JSON.stringify(this.stats,null,2),"utf-8"),await Z__default.rename(e,vo),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 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});}},Ql=new To;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.
784
+ \u{1F4A1} \u4F7F\u7528 build_index(force=true) \u53EF\u4EE5\u91CD\u5EFA\u7D22\u5F15`}}]}le();le();var Be=null,Jt=null;function Kl(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 Vl(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 Yl(r={}){if(Be)return;if(Jt){await Jt;return}let e={...process.env};if(process.platform==="win32"){Be=e;return}let t=Vn(),s=r.maxWaitMs??(t?800:5e3),n=r.background??t,i=async o=>{try{let a=process.env.SHELL||"/bin/zsh";g.debug("SHELL","Preloading shell environment asynchronously...");let l=await execa(a,["-lc","env"],{encoding:"utf8",timeout:o,reject:!1,stdin:"ignore",stdout:"pipe",stderr:"ignore"});if(l.stdout){let c=Vl(l.stdout),u=Kl(c,e);return g.debug("SHELL","Preloaded shell environment successfully",{pathLength:u.PATH?.length}),u}}catch(a){g.warn("SHELL","Failed to preload shell environment",{error:a});}return null};if(n){Be=e,Jt=(async()=>{let o=await i(s);if(o){Be=o;return}let a=await i(5e3);a&&(Be=a);})().finally(()=>{Jt=null;});return}Jt=(async()=>{Be=await i(s)??e;})().finally(()=>{Jt=null;}),await Jt;}function Xl(){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=Vl(t.stdout);Be=Kl(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 vo=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");}},Zl=new vo;var Or={terminal:true,editor:false,debug:true,trace:true},To={...Or,editor:true};le();function ih(){let r=process.platform;if(r==="darwin")return Y__default.join(Gs.homedir(),"Library","Application Support","Neox");if(r==="win32")return Y__default.join(process.env.APPDATA||Y__default.join(Gs.homedir(),"AppData","Roaming"),"Neox");{let e=process.env.XDG_CONFIG_HOME||Y__default.join(Gs.homedir(),".config");return Y__default.join(e,"neox")}}var ec=ih(),xo=Y__default.join(ec,"token-usage.json"),Ql=3e3,ko=class{stats=null;directoriesReady;saveDebounceTimer=null;constructor(){this.directoriesReady=this.ensureDirectories();}async ensureDirectories(){await Z__default.mkdir(ec,{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(xo,"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=`${xo}.${Date.now()}.tmp`;await Z__default.writeFile(e,JSON.stringify(this.stats,null,2),"utf-8"),await Z__default.rename(e,xo),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>Ql&&(t.records=t.records.slice(-Ql)),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});}},tc=new ko;function vn(){return {logger:g,shellEnv:{preloadShellEnv:Yl,getShellEnv:Xl},processManager:Zl,capabilities:Or,tokenUsage:tc}}var Dr={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,33 +791,33 @@ 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 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 oh="NEOX_WORKDIR",ah="NEOX_WORKER",lh=wn(),Pe=lh,be=Pe.logger;function cc(r){Pe=r,be=r.logger;}var xo=new Map,ch=300*1e3;function uh(r,e){return e?r.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):r}async function ph(r){await(r??Pe).shellEnv.preloadShellEnv();}function dh(){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 mh(r,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=dh();return n?new Promise(i=>{let o=fork(n,[],{env:{...process.env,[ah]:"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 sc(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 ch="NEOX_WORKDIR",uh="NEOX_WORKER",ph=vn(),Pe=ph,be=Pe.logger;function pc(r){Pe=r,be=r.logger;}var Co=new Map,dh=300*1e3;function mh(r,e){return e?r.filter(t=>!t.capabilities||t.capabilities.length===0?true:t.capabilities.every(s=>e[s]===true)):r}async function hh(r){await(r??Pe).shellEnv.preloadShellEnv();}function gh(){let r=process.env.NEOX_WORKER_ENTRY;if(r&&Sn__default.existsSync(r))return r;let e=process.argv[1];if(e&&e.endsWith(".js")&&Sn__default.existsSync(e))return e;let t=Y__default.resolve(process.cwd(),"dist","cli","main.js");return Sn__default.existsSync(t)?t:null}async function fh(r,e,t,s){if(process.env.NEOX_SHELL_WORKER_DISABLED==="1")return null;let n=gh();return n?new Promise(i=>{let o=fork(n,[],{env:{...process.env,[uh]:"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
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 sc(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(){let r=process.env[oh];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 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 nc=12e3,rc=4e3,ic=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((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 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 fh(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var yh={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=xo.get(n),a=Date.now();if(o&&o.checksum===i&&o.success&&a-o.timestamp<ch){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"),xo.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 xo.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 bh(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{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 rc(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(){let r=process.env[ch];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(Gs.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 ic=12e3,oc=4e3,ac=1e6;function St(r){let e=He(),t=Y__default.relative(e,r);return t===""?true:!t.startsWith("..")&&!Y__default.isAbsolute(t)}function $r(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 Vt(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 _h(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var wh={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(q("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(q("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(q("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=Co.get(n),a=Date.now();if(o&&o.checksum===i&&o.success&&a-o.timestamp<dh){let l=s.split(`
802
+ `).length;return JSON.stringify(q("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"),Co.set(n,{checksum:i,timestamp:a,success:!0});let c=s.split(`
803
+ `).length,u=l?"updated":"created";return JSON.stringify(q("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 Co.set(n,{checksum:i,timestamp:a,success:false}),JSON.stringify(q("write_file","error",`Failed to write file: ${l.message}`,{file_path:n,error:l.message,verify_hint:"Check file permissions and path validity."}))}}};function vh(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 oc(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 So(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(oc(r[n+o])!==oc(e[o])){i=false;break}if(i)return n}return null}var _h=2e5;function wh(r,e){let t=r.length,s=e.length;if(t*s>_h)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 vh(r,e){if(r.length===0&&e.length===0)return [];let t=wh(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 Th={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 lc(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 Ro(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(lc(r[n+o])!==lc(e[o])){i=false;break}if(i)return n}return null}var Th=2e5;function Sh(r,e){let t=r.length,s=e.length;if(t*s>Th)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 xh(r,e){if(r.length===0&&e.length===0)return [];let t=Sh(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 kh={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}=bh(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=So(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=So(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=So(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=vh(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,i=r.change_context??r.changeContext??r.context,o=Oe(e);Re(o);if(!e)return JSON.stringify(q("edit_file","error","Missing required parameter: file_path",{error:"file_path (or path) is required"}));if(t==null)return JSON.stringify(q("edit_file","error","Missing required parameter: old_string",{error:"old_string is required"}));if(s==null)return JSON.stringify(q("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(q("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}=vh(l),d=t.split(/\r?\n/),m=s.split(/\r?\n/);if(d.length===1&&d[0]==="")return JSON.stringify(q("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=Ro(c,T,0);if(M===null)return JSON.stringify(q("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=Ro(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=Ro(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(q("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=xh(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(q("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:[],x=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(q("edit_file","success",`Edited ${Y__default.basename(o)}: ${b.length} replacement(s) at line ${x}`,{file_path:o,verify_hint:`Use "readfile ${e}" to verify the changes.`,metadata:{replacements:b.length,start_line:x,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."}))}}},xh={name:"search_files",description:`Fast file pattern matching tool (Glob).
813
+ `),start_line:x,old_line_count:W.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(q("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."}))}}},Ch={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 lc(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 uc(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:
@@ -825,13 +825,13 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
825
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
826
  `);let o=50;return n.slice(0,o).forEach(l=>{i.push(` ${l}`);}),n.length>o&&i.push(`
827
827
  ... \u8FD8\u6709 ${n.length-o} \u4E2A\u6587\u4EF6`),i.join(`
828
- `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},Sh={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)}
828
+ `)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},Rh={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
829
  `];if(i.length>0&&(a.push("\u5B50\u76EE\u5F55:"),i.forEach(l=>a.push(` - ${l}/`))),o.length>0){a.push(`
830
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}`}}},kh={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."}))}}},Ch={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}))}}},Rh={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}))}}},Eh={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")>ic)return JSON.stringify(z("apply_patch","error",`Patch too large (max ${ic} 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 Kt(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(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],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(()=>{});}}},Ih=process.env.NEOX_SANDBOX==="on";var Mh={name:"execute_shell",description:`Execute shell command with smart background process management.
831
+ `)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},Eh={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(q("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(q("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(q("create_directory","success",`Directory created: ${t}`,{file_path:e,verify_hint:`Use "list_directory ${r}" to verify.`}))}catch(s){return JSON.stringify(q("create_directory","error",`Failed to create directory: ${s.message}`,{file_path:e,error:s.message,verify_hint:"Check path validity and permissions."}))}}},Ih={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(q("delete_file","error","Missing required parameter: path",{error:"path is required"}));let s=Oe(r),n=Re(s),i=He();if(!St(s))return JSON.stringify(q("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(q("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?q("delete_file","already_done",`Path already removed: ${n}`,{file_path:s}):q("delete_file","error",`Path not found: ${n}`,{file_path:s,error:"Path not found"}));if(o.isDirectory()){if(!e)return JSON.stringify(q("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(q("delete_file","success",`Deleted: ${n}`,{file_path:s,verify_hint:`Use "list_directory ${Y__default.dirname(n)}" to verify.`}))}catch(o){return JSON.stringify(q("delete_file","error",`Failed to delete: ${n}`,{file_path:s,error:o.message}))}}},Mh={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(q("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(!St(n)||!St(i))return JSON.stringify(q("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(q("rename_file","error","Refusing to rename workspace root",{file_path:n}));try{await Z__default.lstat(n);}catch{return JSON.stringify(q("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(q("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(q("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(q("rename_file","error",`Failed to rename: ${o}`,{file_path:n,error:u.message}))}}},Ah={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(q("apply_patch","error","Missing required parameter: patch",{error:"patch is required"}));if(!Number.isInteger(e)||e<0||e>10)return JSON.stringify(q("apply_patch","error","Invalid strip value (must be an integer between 0 and 10)",{error:"Invalid strip value"}));if(Buffer.byteLength(r,"utf8")>ac)return JSON.stringify(q("apply_patch","error",`Patch too large (max ${ac} 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(q("apply_patch","error","Patch contains absolute paths",{error:"Absolute paths are not allowed in patch"}));if(p.split(/[\\/]+/).includes(".."))return JSON.stringify(q("apply_patch","error","Patch contains path traversal",{error:"Path traversal is not allowed in patch"}))}let n=He(),{repoRoot:i,error:o}=await Vt(n);if(!i)return JSON.stringify(q("apply_patch","error",`Not a git repository: ${o||"unknown error"}`,{error:"Not a git repository"}));let a=await Z__default.mkdtemp(Y__default.join(Gs.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(q("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(q("apply_patch","error","Patch apply failed",{error:d||"Patch apply failed"}))}return JSON.stringify(q("apply_patch","success","Patch applied successfully",{verify_hint:"Use git diff or readfile to verify changes."}))}catch(c){return JSON.stringify(q("apply_patch","error","Patch apply failed",{error:c.message}))}finally{await Z__default.rm(a,{recursive:true,force:true}).catch(()=>{});}}},Ph=process.env.NEOX_SANDBOX==="on";var Oh={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(Ih){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(Ph){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 mh(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(),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 fh(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
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
@@ -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`}}},Ah={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)}/
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`}}},Lh={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
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}`}}},Ph={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 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"))}},Oh={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 Kt(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||""))}},Lh={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 Kt(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||""))}},Dh={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 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||""))}},$h={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 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}}))}},Nh={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 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 Fh(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 Uh(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 Ro(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 Fh(s),o=t.command,a=[];if(o){let l=fh(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=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(i){let l=Uh(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=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 jh={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 Ro("run_tests","test",r)}},Gh={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 Ro("run_lint","lint",r)}},Bh={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 Ro("run_format","format",r)}},Wh={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(`
962
+ `)}catch(t){return `\u2717 \u663E\u793A\u76EE\u5F55\u6811\u5931\u8D25: ${t.message}`}}},Dh={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(!St(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 Vt(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"))}},$h={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(!St(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 Vt(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(!St(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||""))}},Nh={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(!St(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 Vt(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||""))}},Fh={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(!St(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 Vt(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||""))}},Uh={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 Vt(t);if(!s)return JSON.stringify(q("git_branch","error",`Not a git repository: ${n||"unknown error"}`,{error:"Not a git repository"}));if(!r)return JSON.stringify(q("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(q("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(q("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(q("git_branch","error","Branch created but checkout failed",{error:u||"Checkout failed"}))}}return JSON.stringify(q("git_branch","success",e?`Branch created and checked out: ${i}`:`Branch created: ${i}`,{metadata:{branch:i,checkout:e}}))}},jh={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 Vt(t);if(!s)return JSON.stringify(q("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(q("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(q("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(q("git_commit","error","git commit failed",{error:a||"git commit failed"}))}return JSON.stringify(q("git_commit","success",`Commit created: ${i}`,{metadata:{message:i}}))}};async function Gh(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 Bh(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 Mo(r,e,t){let s=Oe(t.cwd||".");if(!St(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 Gh(s),o=t.command,a=[];if(o){let l=_h(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=$r(d,ic),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:$r(d,oc).text,metadata:{command:[l.command,...u].join(" "),exit_code:p.exitCode,duration_ms:p.durationMs,output_truncated:m.truncated}}))}if(i){let l=Bh(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=$r(u,ic),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:$r(u,oc).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 Wh={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 Mo("run_tests","test",r)}},Hh={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 Mo("run_lint","lint",r)}},zh={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 Mo("run_format","format",r)}},qh={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
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
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(`
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}`}}},ko=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],vn=null,Jt=null;async function Co(){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 Hh(){return vn!==null||(vn=await Co()!==null,vn?be.info("SEARCH","ripgrep available"):be.warn("SEARCH","ripgrep not available, using fallback")),vn}function qh(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 zh={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}`}}},Eo=["!**/node_modules/**","!**/.git/**","!**/dist/**","!**/build/**","!**/out/**","!**/.next/**","!**/coverage/**","!**/__pycache__/**","!**/target/**","!**/vendor/**"],Tn=null,Kt=null;async function Io(){if(Kt!==null)return Kt;try{let{rgPath:r}=await import('@vscode/ripgrep');return Kt=r,be.info("SEARCH",`Using bundled ripgrep: ${r}`),Kt}catch(r){be.warn("SEARCH",`Bundled ripgrep not available: ${r.message}`);try{if((await Ne("rg",["--version"],He(),{timeoutMs:2e3})).exitCode===0)return Kt="rg",be.info("SEARCH","Using system ripgrep"),Kt}catch{}}return Kt=null,null}async function Jh(){return Tn!==null||(Tn=await Io()!==null,Tn?be.info("SEARCH","ripgrep available"):be.warn("SEARCH","ripgrep not available, using fallback")),Tn}function Kh(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 Vh={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&&!Tn__default.existsSync(R)){let I=W,j=null;for(;;){let q=Y__default.resolve(I,o);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=qh({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 Hh();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 Co();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),ko.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 oe=l||"**/*",ze=w?oe:oe.replace("**/","");return (await lc(ze,{cwd:R,absolute:!0,dot:c,onlyFiles:!0,ignore:ko.map(ce=>ce.replace("!",""))})).map(ce=>Re(ce))})();b();let j=T.map(oe=>{let ze=oe.regex?oe.pattern:sc(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:sc(I.pattern),q=I.caseInsensitive?"i":"";return new RegExp(j,q)}),Te=[];if(X){let I=await Co();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),ko.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?`
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&&!Sn__default.existsSync(R)){let I=W,j=null;for(;;){let z=Y__default.resolve(I,o);if(Sn__default.existsSync(z)){j=z;break}let ye=Y__default.dirname(I);if(ye===I)break;I=ye;}j&&(R=j,O="ancestor");}let F=Re(R);b();let x;try{x=await Z__default.stat(R);}catch(I){return JSON.stringify(de("search","error",`search failed: ${I.message}`,void 0,{error:I.message}))}let C=x.isDirectory(),w=a!==void 0?a:C,T=Kh({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 Jh();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 Io();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),Eo.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 Us=Y__default.isAbsolute(nt)?Y__default.resolve(nt):Y__default.resolve(He(),nt);return Re(Us)})}let oe=l||"**/*",qe=w?oe:oe.replace("**/","");return (await uc(qe,{cwd:R,absolute:!0,dot:c,onlyFiles:!0,ignore:Eo.map(ce=>ce.replace("!",""))})).map(ce=>Re(ce))})();b();let j=T.map(oe=>{let qe=oe.regex?oe.pattern:rc(oe.pattern),_e=oe.caseInsensitive?"i":"";return {query:oe,regex:new RegExp(qe,_e)}}),z=[],ye=0;for(let oe of I){b();let qe=oe,_e=j.map(xe=>({op:xe.query.op,hit:xe.regex.test(qe)})),ce=_e.some(xe=>xe.op==="or"&&xe.hit),ve=_e.filter(xe=>xe.op==="and").every(xe=>xe.hit);!_e.some(xe=>xe.op==="not"&&xe.hit)&&(B.length===0||ve)&&(E.length===0||ce)&&z.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 ${z.length} \u4E2A\u6587\u4EF6`,""].filter(oe=>oe!==""),fe=50;return z.slice(0,fe).forEach(oe=>ge.push(` ${oe}`)),z.length>fe&&ge.push(` ... \u8FD8\u6709 ${z.length-fe} \u4E2A\u6587\u4EF6`),JSON.stringify(de("search","success",z.length>0?`search files "${G}" (${z.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:z,queries:T}}))}let P=new Map,K=new Map,U=0,ne=L.map(I=>{let j=I.regex?I.pattern:rc(I.pattern),z=I.caseInsensitive?"i":"";return new RegExp(j,z)}),Te=[];if(X){let I=await Io();if(!I)throw new Error("ripgrep not available (this should not happen)");for(let j of M){b();let z=["--json","--with-filename","--line-number","--column","-a"];z.push("-C",String(p)),j.caseInsensitive&&z.push("-i"),j.regex||z.push("-F"),c&&z.push("--hidden"),!w&&C&&z.push("--max-depth","1"),l&&z.push("-g",l),Eo.forEach(_e=>z.push("-g",_e)),z.push("--",j.pattern,R);let ye=`${I} ${z.join(" ")}`;Te.push(ye);let ge="",fe=0,oe="";try{let _e=await Ne(I,z,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
998
  Error: ${oe}`:"",ce=`
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 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$/,""),ci=P.get(nt)||new Map,Us=ci.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);}ci.set(Fs,Us),P.set(nt,ci);}}}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(`
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}))}}},Jh={name:Or.name,description:Or.description,parameters:Or.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return ec(r)}},uc=[yh,Th,Ch,Rh,Eh,xh,Sh,kh,Ph,Oh,Lh,Dh,$h,Nh,jh,Gh,Bh,Mh,Ah,Ia,Wh,zh,wi,vi,Ti,Na,Jh];async function Eo(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($i),s.javaDebug?.enabled)try{let c=await ji(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=yo(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(...tr()),t?.editor&&i&&n.push(...sr());let o=uh(n,t),a=s.enabledTools||{};return o.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 Kh(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 Vh(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 Yh(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 Xh(r){let e=r.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Vt(r,e){let t=Xh(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(xn(r)){let o=Kh(r)||String(e||"UNKNOWN"),a=Vh(r)||"Server error",l=Yh(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(xn(a)){let l=Vt(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 Zh(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 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 Io(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 Qh(r){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(r))}function eg(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=Io(r)?r:void 0,i=(s?eg(s.response?.data):void 0)||e;if(s?.response?.status){let o=s.response.status,a=$r(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(xn(i)){let p=Vt(i,o);c=p.message,p.detail&&(c+=`
1004
- `+p.detail);}let u=a||Zh(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(xn(i)){let u=Vt(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 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: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(Io(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}):Io(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}):Qh(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 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 Es(c);return c}catch(l){if(l instanceof Es)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 Es(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 Is(c);return c}catch(l){if(l instanceof Is)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 Is(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 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,Mo=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 Mo||(Mo=wc()),Mo}function Ao(r,e,t,s){let n=vc(r);if(process.env.CLI_DEBUG==="1"){let i=kn();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"&&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 ig=fileURLToPath(import.meta.url),Lo=dirname(ig),Do=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(Lo.includes(".asar")||Lo.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(Lo,"../../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||{},i=this.safeStringify({timestamp:s,...n})+`
1006
- `;if(this.enabled)try{let o=this.getLogFile(e);Tn__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 Do;function Rc(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 ag=new og({allErrors:true,strict:false});function lg(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 cg(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=ag.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=lg(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:cg(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:
999
+ Command: ${I} ${z.join(" ")}`;throw new Error(`ripgrep failed (exit code ${fe})${_e}${ce}`)}let qe=0;for(let _e of ge.split(`
1000
+ `)){if(b(),qe++,qe%_===0&&await v(),!_e.trim())continue;let ce;try{ce=JSON.parse(_e);}catch{continue}if(ce.type==="summary"){let ns=ce.data?.stats;ns&&typeof ns.searches=="number"&&(U=Math.max(U,ns.searches));continue}let ve=ce.type==="match",Xe=ce.type==="context";if(!ve&&!Xe)continue;let xe=ce.data,nt=xe?.path?.text,Us=xe?.line_number,ra=xe?.lines?.text,ia=Array.isArray(xe?.submatches)?xe.submatches[0]:void 0;if(!nt||!Us||typeof ra!="string")continue;let oa=ra.replace(/\n$/,""),di=P.get(nt)||new Map,js=di.get(Us)||{line:oa,queryIds:new Set};if(js.line=oa,ve){js.queryIds.add(j.id),js.column===void 0&&ia?.start!==void 0&&(js.column=ia.start+1);let ns=K.get(nt)||new Set;ns.add(j.id),K.set(nt,ns);}di.set(Us,js),P.set(nt,di);}}}let Q=new Set(B.map(I=>I.id)),ie=[],se=0,ae=0,J=0,pe=[],S=[],D=0;for(let[I,j]of P.entries()){if(b(),se>=d&&!m)break;D++,D%_===0&&await v();let z=K.get(I)||new Set,ye=!0;if(Q.forEach(ce=>{z.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 qe=[];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(qe.push({lineNum:ce,line:ve.line,isMatch:Xe}),Xe&&S.length<d){for(let xe of ve.queryIds)if(S.push({file:oe,line:ce,column:ve.column,preview:ve.line,queryId:xe}),S.length>=d)break}}),ie.push({file:I,matches:qe,matchCount:fe.length});}ie.sort((I,j)=>Re(I.file).localeCompare(Re(j.file)));let H=I=>{let z=Re(I).split(Y__default.sep),ye=z.findIndex(ge=>["src","lib","app","core","packages"].includes(ge));return ye>=0&&ye+1<z.length?z[ye+1]:z[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,Se=0;for(let I of ie){Se++,Se%_===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,z)=>z[1]-j[1]);for(let[j,z]of I.slice(0,5))V.push(` ${j}: ${z}`);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 z=Re(j.file),ye=H(j.file);V.push(` [${ye}] ${z}: ${j.matchCount}`);}}else {let I=0,j=100;for(let z of ie){if(b(),J>=d){V.push(`
1001
+ ... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${d} \u4E0A\u9650)`);break}let ye=Re(z.file),ge=H(z.file);V.push(`
1002
+ \u25B8 [${ge}] ${ye} (${z.matchCount} \u5904)`),V.push("\u2500".repeat(50));let fe=-10;for(let oe of z.matches){if(J>=d)break;I++,I%j===0&&await v(),oe.lineNum>fe+1&&fe>0&&V.push(" \u2504\u2504\u2504");let qe=oe.isMatch?"\u25B6":" ";V.push(`${qe}${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:S,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}))}}},Yh={name:Dr.name,description:Dr.description,parameters:Dr.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return sc(r)}},dc=[wh,kh,Ih,Mh,Ah,Ch,Rh,Eh,Dh,$h,Nh,Fh,Uh,jh,Wh,Hh,zh,Oh,Lh,Aa,qh,Vh,Si,xi,ki,Ua,Yh];async function Ao(r,e){e&&pc(e);let t=e?.capabilities??Pe.capabilities,s=Ks(),n=[...dc];if(r&&n.push(ja(r)),s.webSearch?.enabled&&n.push(Ui),s.javaDebug?.enabled)try{let c=await Wi(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=wo(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(...nr()),t?.editor&&i&&n.push(...rr());let o=mh(n,t),a=s.enabledTools||{};return o.filter(c=>a[c.name]!==false)}function Nr(r){return {output_info:r,behavior:{type:"allow"}}}function mc(r,e){return {output_info:e,behavior:{type:"reject_content",message:r}}}function Xh(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 Zh(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 xn(r){return r.trim().startsWith("<!DOCTYPE html")||r.trim().startsWith("<html")||/<html[^>]*>/i.test(r)}function eg(r){let e=r.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Yt(r,e){let t=eg(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(xn(r)){let o=Xh(r)||String(e||"UNKNOWN"),a=Zh(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(xn(a)){let l=Yt(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 xt(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 tg(r){switch(r){case 502:return 3e3;case 503:return 5e3;case 504:return 2e3;default:return 2e3}}function Fr(r){if(!r)return;let e=r["retry-after"]||r["Retry-After"];if(e){let i=xt(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=xt(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 Po(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function hc(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 sg(r){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(r))}function ng(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=Po(r)?r:void 0,i=(s?ng(s.response?.data):void 0)||e;if(s?.response?.status){let o=s.response.status,a=Fr(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(xn(i)){let p=Yt(i,o);c=p.message,p.detail&&(c+=`
1004
+ `+p.detail);}let u=a||tg(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(xn(i)){let u=Yt(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 hc(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(Po(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}):Po(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}):hc(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}):sg(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 gc(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 Ur(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 Es(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 fc=100,yc=200,bc=1800*1e3;var kn=class extends Error{constructor(e){super(e),this.name="GuardrailTripwireTriggered";}},Is=class extends kn{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}}},Ms=class extends kn{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 kn{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 Xt=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 Is(c);return c}catch(l){if(l instanceof Is)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 Is(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 Ms(c);return c}catch(l){if(l instanceof Ms)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 Ms(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 _c=null,wc=false;function Cn(){if(!wc&&(wc=true,typeof process<"u"&&process.env&&!process.env.NEOX_UI_MODE))try{Promise.resolve().then(()=>(le(),Bn)).then(r=>{_c=r.cliLogger;}).catch(()=>{});}catch{}return _c}var vc=new WeakMap,Oo=null;function Tc(){return {writtenFiles:new Map,editedFiles:new Map,editDetails:new Map,fileReadCache:new Map,toolCallHistory:[],createdAt:Date.now()}}function Sc(r){if(r){let e=vc.get(r);return e?process.env.CLI_DEBUG==="1"&&Cn()?.debug("SESSION",`Retrieved EXISTING SessionState for context: ${Object.keys(r).join(",")}, history: ${e.toolCallHistory.length}`):(e=Tc(),vc.set(r,e),process.env.CLI_DEBUG==="1"&&Cn()?.debug("SESSION",`Created NEW SessionState for context: ${Object.keys(r).join(",")}`)),e}return Oo||(Oo=Tc()),Oo}function Lo(r,e,t,s){let n=Sc(r);if(process.env.CLI_DEBUG==="1"){let i=Cn();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"&&Cn()?.debug("SESSION",` - history length after: ${n.toolCallHistory.length}`),n.toolCallHistory.length>100&&n.toolCallHistory.shift();}function xc(r,e=10){let t=Sc(r);if(process.env.CLI_DEBUG==="1"){let s=Cn();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 lg=fileURLToPath(import.meta.url),No=dirname(lg),Fo=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(No.includes(".asar")||No.includes("app.asar")){try{let{app:e}=Ec();if(e&&e.getPath){let t=e.getPath("userData");return Y__default.join(t,"logs")}}catch{}return Y__default.join(Gs.tmpdir(),"neox-logs")}return Y__default.join(No,"../../logs")}initLogDir(){try{Sn__default.existsSync(this.logDir)||Sn__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);Sn__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 Fo;function Ic(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 ug=new cg({allErrors:true,strict:false});function pg(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 dg(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 Gr=class{constructor(e){this.definition=e;this.validateFn=ug.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=pg(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:dg(this.validateFn.errors)}}buildRetryPrompt(e){let t=[`Your previous response did not satisfy the required JSON schema "${this.definition.name}".`];return e.errors&&e.errors.length>0?t.push(`Validation issues:
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 No(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:No(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),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 ug={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},pg={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function dg(r,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return No(r,ug)}function Cn(r,e,t){return r==="retryable_rate_limit"?dg(e,t):r==="retryable_stream"||r==="retryable_network"?No(e,pg):Dt(t,e)}le();le();var mg=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"},hg={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 jo(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:jo(e,t)}function As(r){return new Promise(e=>setTimeout(e,r))}function Zt(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 ze(r){if(r<1e3)return `${r}ms`;let e=r/1e3;return e<60?`${e.toFixed(1)}s`:`${(e/60).toFixed(1)}m`}var mg={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},hg={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function gg(r,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return jo(r,mg)}function Rn(r,e,t){return r==="retryable_rate_limit"?gg(e,t):r==="retryable_stream"||r==="retryable_network"?jo(e,hg):Dt(t,e)}le();le();var fg=2e3,Mc={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"},yg={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,9 +1075,9 @@ ${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(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 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=hg[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(Mc);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":Mc[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=yg[e];if(!o)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=mg;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(`
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=fg;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
1081
  `),i=t?`\u{1F4C4} ${t}
1082
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(`
1083
1083
  `),c=n.slice(-a).join(`
@@ -1107,7 +1107,7 @@ ${t.slice(0,5).map(o=>`- ${o}`).join(`
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 gg=15,fg=[/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
1110
+ ${o}`}truncate(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}};new $t;le();var bg=15,_g=[/error/i,/错误/,/failed/i,/失败/,/exception/i,/异常/,/❌/,/warning/i,/警告/],En={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}`},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??gg;}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 fg.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,i=6e3,o=e.length>i?e.slice(0,i)+`
1135
+ ${r}`},Ps=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??bg;}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 _g.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)?En.systemZh:En.system,i=6e3,o=e.length>i?e.slice(0,i)+`
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
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(`
1141
1141
 
1142
- `),i=/[\u4e00-\u9fa5]/.test(s)?Rn.systemZh:Rn.system,o=await t.llmProvider.chat([{role:"system",content:i},{role:"user",content:Rn.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 As;var yg={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},jr=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...yg,...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(),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 bg(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 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 bg(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 Zt={environment:{zh:r=>`## \u73AF\u5883
1142
+ `),i=/[\u4e00-\u9fa5]/.test(s)?En.systemZh:En.system,o=await t.llmProvider.chat([{role:"system",content:i},{role:"user",content:En.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 Ps;var wg={debug:false,minRecentMessages:15,defaultTokenBudget:1e5,enableLLMCompression:true,llmTimeout:3e4},Br=class{config;toolCompressor;messageCompressor;llmProvider;model;contextWindow;constructor(e){this.config={...wg,...e},this.config.debug=this.config.debug||process.env.CLI_DEBUG==="1",this.toolCompressor=new $t({debug:this.config.debug}),this.messageCompressor=new Ps({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 vg(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 Wr=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 vg(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 Qt={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}
@@ -1165,8 +1165,8 @@ ${o}`}],{model:t.model,temperature:.2});return ee(a.choices[0]?.message?.content
1165
1165
  **Large file chunking** (when necessary):
1166
1166
  1. Files >300 lines or 10KB \u2192 Write in chunks, each chunk <200 lines
1167
1167
  2. First step write_file: Create skeleton structure
1168
- 3. Subsequent edit_file: Replace section by section (readfile before each edit!)`},toolResults:{zh:'## \u7406\u89E3\u5DE5\u5177\u7ED3\u679C\n\n- `write_file` / `edit_file` \u8FD4\u56DE\u7ED3\u6784\u5316\u7ED3\u679C\uFF1A\n - `"status": "success" + "final": true` \u2192 \u4FEE\u6539\u6210\u529F\uFF0C\u4E0D\u91CD\u590D\u64CD\u4F5C\n - `"status": "already_done"` \u2192 \u5DF2\u5B8C\u6210\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u4E2A\u4EFB\u52A1\n - `"status": "error"` \u2192 \u8BFB\u53D6\u9519\u8BEF\u4FE1\u606F\u5E76\u4FEE\u590D\n- \u4FEE\u6539\u5B8C\u6210\u540E\u4F7F\u7528 `readfile` \u9A8C\u8BC1\u5173\u952E\u51FD\u6570/\u7C7B\u5185\u5BB9\n- readfile \u5931\u8D25 \u2192 \u6269\u5927\u8303\u56F4\u6216\u8C03\u6574\u5173\u952E\u8BCD\uFF0C\u518D\u5C1D\u8BD5',en:'## Understanding Tool Results\n\n- `write_file` / `edit_file` return structured results:\n - `"status": "success" + "final": true` \u2192 Modification successful, don\'t repeat\n - `"status": "already_done"` \u2192 Already complete, proceed to next task\n - `"status": "error"` \u2192 Read error message and fix\n- After modification, use `readfile` to verify key functions/classes\n- readfile fails \u2192 Expand scope or adjust keywords, then retry'},specializedTools:{zh:"## \u4E13\u7528\u5DE5\u5177\n\n- **Git**\uFF1A`git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **\u6587\u4EF6\u64CD\u4F5C**\uFF1A`delete_file` / `rename_file` / `apply_patch`\n- **\u5BFC\u822A**\uFF1A`search_symbol` / `get_definitions` / `get_references`\uFF08\u7D22\u5F15\u53EF\u7528\u65F6\u4F18\u5148\uFF09\n- **\u6D4B\u8BD5**\uFF1A`run_tests` / `run_lint` / `run_format`\uFF08\u907F\u514D\u7528 shell \u4EE3\u66FF\uFF09\n- \u82E5\u89E6\u8FBE\u8FED\u4EE3/\u5DE5\u5177/\u8FD0\u884C\u65F6\u95F4\u9650\u5236\uFF0C\u5148\u603B\u7ED3\u8FDB\u5EA6\u5E76\u8BE2\u95EE\u662F\u5426\u7EE7\u7EED",en:"## Specialized Tools\n\n- **Git**: `git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **File operations**: `delete_file` / `rename_file` / `apply_patch`\n- **Navigation**: `search_symbol` / `get_definitions` / `get_references` (prefer when index available)\n- **Tests**: `run_tests` / `run_lint` / `run_format` (avoid using shell instead)\n- If hitting iteration/tool/runtime limits, summarize progress and ask to continue"},errorRecovery:{zh:"## \u9519\u8BEF\u6062\u590D\n\n- `edit_file` \u5931\u8D25\uFF1A\u91CD\u65B0 `readfile(path, for_edit=true)`\uFF0C\u7F29\u5C0F `old_string`\uFF0C\u5FC5\u8981\u65F6\u52A0 `change_context`\n- \u8FDE\u7EED\u5931\u8D25 2 \u6B21\uFF1A\u6539\u7528 `write_file` \u91CD\u5199\u6574\u4E2A\u6587\u4EF6\n- \u8FDE\u7EED\u5931\u8D25 3 \u6B21\uFF1A\u505C\u6B62\u5F53\u524D\u65B9\u6CD5\uFF0C\u62A5\u544A\u7ED9\u7528\u6237\n- \u7981\u6B62\u4F7F\u7528 sed/awk \u7B49 shell \u547D\u4EE4\u7F16\u8F91\u6587\u4EF6",en:"## Error Recovery\n\n- `edit_file` fails: Re-`readfile(path, for_edit=true)`, reduce `old_string`, add `change_context` if needed\n- 2 consecutive fails: Use `write_file` to rewrite entire file\n- 3 consecutive fails: Stop current approach, report to user\n- Never use sed/awk or other shell commands to edit files"},outputFormat:{zh:"## \u8F93\u51FA\u8981\u6C42\n\n- \u7528\u4E2D\u6587\u56DE\u590D\n- \u64CD\u4F5C\u540E\u7B80\u77ED\u786E\u8BA4\n- \u4E0D\u521B\u5EFA\u7528\u6237\u672A\u8981\u6C42\u7684\u6587\u4EF6\n- \u9047\u5230\u9519\u8BEF\u4F18\u5148\u7528 readfile \u9A8C\u8BC1\uFF0C\u4E0D\u76F2\u76EE\u91CD\u590D\u64CD\u4F5C\n\n### Markdown \u683C\u5F0F\u89C4\u8303\n- \u6807\u9898\u5FC5\u987B\u5728 # \u540E\u52A0\u7A7A\u683C\uFF1A`### \u6807\u9898` \u2713\uFF0C`###\u6807\u9898` \u2717\n- \u7C97\u4F53/\u659C\u4F53\u6807\u8BB0\u4E0E\u6587\u5B57\u4E4B\u95F4\u4E0D\u52A0\u7A7A\u683C\uFF1A`**\u7C97\u4F53**` \u2713\n- \u5217\u8868\u9879 `-` \u540E\u5FC5\u987B\u52A0\u7A7A\u683C\uFF1A`- \u9879\u76EE` \u2713",en:"## Output Requirements\n\n- Reply in English\n- Brief confirmation after operations\n- Don't create unrequested files\n- When encountering errors, verify with readfile first, don't blindly repeat operations\n\n### Markdown Format Rules\n- Headings must have space after #: `### Title` \u2713, `###Title` \u2717\n- Bold/italic markers without space to text: `**bold**` \u2713\n- List items must have space after `-`: `- item` \u2713"}};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(`
1169
- `)}var _g={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1168
+ 3. Subsequent edit_file: Replace section by section (readfile before each edit!)`},toolResults:{zh:'## \u7406\u89E3\u5DE5\u5177\u7ED3\u679C\n\n- `write_file` / `edit_file` \u8FD4\u56DE\u7ED3\u6784\u5316\u7ED3\u679C\uFF1A\n - `"status": "success" + "final": true` \u2192 \u4FEE\u6539\u6210\u529F\uFF0C\u4E0D\u91CD\u590D\u64CD\u4F5C\n - `"status": "already_done"` \u2192 \u5DF2\u5B8C\u6210\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u4E2A\u4EFB\u52A1\n - `"status": "error"` \u2192 \u8BFB\u53D6\u9519\u8BEF\u4FE1\u606F\u5E76\u4FEE\u590D\n- \u4FEE\u6539\u5B8C\u6210\u540E\u4F7F\u7528 `readfile` \u9A8C\u8BC1\u5173\u952E\u51FD\u6570/\u7C7B\u5185\u5BB9\n- readfile \u5931\u8D25 \u2192 \u6269\u5927\u8303\u56F4\u6216\u8C03\u6574\u5173\u952E\u8BCD\uFF0C\u518D\u5C1D\u8BD5',en:'## Understanding Tool Results\n\n- `write_file` / `edit_file` return structured results:\n - `"status": "success" + "final": true` \u2192 Modification successful, don\'t repeat\n - `"status": "already_done"` \u2192 Already complete, proceed to next task\n - `"status": "error"` \u2192 Read error message and fix\n- After modification, use `readfile` to verify key functions/classes\n- readfile fails \u2192 Expand scope or adjust keywords, then retry'},specializedTools:{zh:"## \u4E13\u7528\u5DE5\u5177\n\n- **Git**\uFF1A`git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **\u6587\u4EF6\u64CD\u4F5C**\uFF1A`delete_file` / `rename_file` / `apply_patch`\n- **\u5BFC\u822A**\uFF1A`search_symbol` / `get_definitions` / `get_references`\uFF08\u7D22\u5F15\u53EF\u7528\u65F6\u4F18\u5148\uFF09\n- **\u6D4B\u8BD5**\uFF1A`run_tests` / `run_lint` / `run_format`\uFF08\u907F\u514D\u7528 shell \u4EE3\u66FF\uFF09\n- \u82E5\u89E6\u8FBE\u8FED\u4EE3/\u5DE5\u5177/\u8FD0\u884C\u65F6\u95F4\u9650\u5236\uFF0C\u5148\u603B\u7ED3\u8FDB\u5EA6\u5E76\u8BE2\u95EE\u662F\u5426\u7EE7\u7EED",en:"## Specialized Tools\n\n- **Git**: `git_status` / `git_diff` / `git_blame` / `git_branch_list` / `git_branch` / `git_commit`\n- **File operations**: `delete_file` / `rename_file` / `apply_patch`\n- **Navigation**: `search_symbol` / `get_definitions` / `get_references` (prefer when index available)\n- **Tests**: `run_tests` / `run_lint` / `run_format` (avoid using shell instead)\n- If hitting iteration/tool/runtime limits, summarize progress and ask to continue"},errorRecovery:{zh:"## \u9519\u8BEF\u6062\u590D\n\n- `edit_file` \u5931\u8D25\uFF1A\u91CD\u65B0 `readfile(path, for_edit=true)`\uFF0C\u7F29\u5C0F `old_string`\uFF0C\u5FC5\u8981\u65F6\u52A0 `change_context`\n- \u8FDE\u7EED\u5931\u8D25 2 \u6B21\uFF1A\u6539\u7528 `write_file` \u91CD\u5199\u6574\u4E2A\u6587\u4EF6\n- \u8FDE\u7EED\u5931\u8D25 3 \u6B21\uFF1A\u505C\u6B62\u5F53\u524D\u65B9\u6CD5\uFF0C\u62A5\u544A\u7ED9\u7528\u6237\n- \u7981\u6B62\u4F7F\u7528 sed/awk \u7B49 shell \u547D\u4EE4\u7F16\u8F91\u6587\u4EF6",en:"## Error Recovery\n\n- `edit_file` fails: Re-`readfile(path, for_edit=true)`, reduce `old_string`, add `change_context` if needed\n- 2 consecutive fails: Use `write_file` to rewrite entire file\n- 3 consecutive fails: Stop current approach, report to user\n- Never use sed/awk or other shell commands to edit files"},outputFormat:{zh:"## \u8F93\u51FA\u8981\u6C42\n\n- \u7528\u4E2D\u6587\u56DE\u590D\n- \u64CD\u4F5C\u540E\u7B80\u77ED\u786E\u8BA4\n- \u4E0D\u521B\u5EFA\u7528\u6237\u672A\u8981\u6C42\u7684\u6587\u4EF6\n- \u9047\u5230\u9519\u8BEF\u4F18\u5148\u7528 readfile \u9A8C\u8BC1\uFF0C\u4E0D\u76F2\u76EE\u91CD\u590D\u64CD\u4F5C\n\n### Markdown \u683C\u5F0F\u89C4\u8303\n- \u6807\u9898\u5FC5\u987B\u5728 # \u540E\u52A0\u7A7A\u683C\uFF1A`### \u6807\u9898` \u2713\uFF0C`###\u6807\u9898` \u2717\n- \u7C97\u4F53/\u659C\u4F53\u6807\u8BB0\u4E0E\u6587\u5B57\u4E4B\u95F4\u4E0D\u52A0\u7A7A\u683C\uFF1A`**\u7C97\u4F53**` \u2713\n- \u5217\u8868\u9879 `-` \u540E\u5FC5\u987B\u52A0\u7A7A\u683C\uFF1A`- \u9879\u76EE` \u2713",en:"## Output Requirements\n\n- Reply in English\n- Brief confirmation after operations\n- Don't create unrequested files\n- When encountering errors, verify with readfile first, don't blindly repeat operations\n\n### Markdown Format Rules\n- Headings must have space after #: `### Title` \u2713, `###Title` \u2717\n- Bold/italic markers without space to text: `**bold**` \u2713\n- List items must have space after `-`: `- item` \u2713"}};function Ac(r,e="zh"){let t=[];return t.push(Qt.environment[e](r)),t.push(""),t.push(Qt.toolUsage[e]),t.push(""),t.push(Qt.editRules[e]),t.push(""),t.push(Qt.toolResults[e]),t.push(""),t.push(Qt.specializedTools[e]),t.push(""),t.push(Qt.errorRecovery[e]),t.push(""),t.push(Qt.outputFormat[e]),t.join(`
1169
+ `)}var Tg={identity:{zh:`\u4F60\u662F Neox AI \u52A9\u624B\uFF0C\u53EF\u4EE5\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u5404\u79CD\u4EFB\u52A1\u3002
1170
1170
 
1171
1171
  **\u6838\u5FC3\u539F\u5219**\uFF1A
1172
1172
  - \u5FEB\u901F\u7406\u89E3\u7528\u6237\u610F\u56FE
@@ -1212,10 +1212,10 @@ For complex multi-step tasks, use the update_plan tool to create an execution pl
1212
1212
  - Only one step can be in_progress at a time
1213
1213
  - Update plan status as work progresses
1214
1214
 
1215
- Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function Mc(r="zh"){return _g.identity[r]}function Br(r){let{workDir:e,language:t="zh"}=r,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1215
+ Example scenarios: refactoring code, adding features, project migration, performance optimization, etc.`}};function Pc(r="zh"){return Tg.identity[r]}function Hr(r){let{workDir:e,language:t="zh"}=r,s=[],n=t==="zh"?`\u5DE5\u4F5C\u76EE\u5F55: ${e}
1216
1216
  Shell \u6BCF\u6B21\u8C03\u7528\u72EC\u7ACB\uFF0Ccd \u4E0D\u8DE8\u8C03\u7528\u6301\u7EED`:`Working directory: ${e}
1217
- 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(`
1218
- `)}var wg=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1217
+ Shell calls are independent; cd does not persist across calls`;return s.push(n),s.push(""),s.push(Pc(t)),s.push(""),s.push(Ac(e,t)),s.push(""),s.push(t==="zh"?"\u5F00\u59CB\u5DE5\u4F5C\u3002":"Start working."),s.join(`
1218
+ `)}var Sg=`You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
1219
1219
 
1220
1220
  ## General
1221
1221
 
@@ -1331,7 +1331,7 @@ You are producing plain text that will later be styled by the CLI. Follow these
1331
1331
  * Optionally include line/column (1\u2011based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
1332
1332
  * Do not use URIs like file://, vscode://, or https://.
1333
1333
  * Do not provide range of lines
1334
- * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function Fo(r){let{workDir:e,language:t="zh",useCodexStyle:s=false}=r;return s?wg:Br({workDir:e,language:t})}function Ac(r,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${r}
1334
+ * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5`;function Go(r){let{workDir:e,language:t="zh",useCodexStyle:s=false}=r;return s?Sg:Hr({workDir:e,language:t})}function Oc(r,e,t="zh"){return t==="zh"?`\u6587\u4EF6\u7F16\u8F91\u5931\u8D25: ${r}
1335
1335
 
1336
1336
  \u9519\u8BEF\u4FE1\u606F: ${e}
1337
1337
 
@@ -1345,7 +1345,7 @@ Error: ${e}
1345
1345
  Suggestions:
1346
1346
  1. Re-read with readfile(path, for_edit=true)
1347
1347
  2. Ensure old_string matches exactly (spaces, newlines)
1348
- 3. If failing repeatedly, consider rewriting with write_file`}le();var Uo=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(),oa(Gn));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(),oa(Gn));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:`
1348
+ 3. If failing repeatedly, consider rewriting with write_file`}le();var Bo=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(),ca(Bn));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(),ca(Bn));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:`
1349
1349
  [SYSTEM NOTICE]
1350
1350
  You have called "${t}" ${this.getCallCount(t,s)} times with similar arguments.
1351
1351
  ${i?"\u26A0\uFE0F Previous calls already returned SUCCESS.":""}
@@ -1381,7 +1381,7 @@ Please:
1381
1381
  - Check if the file/path exists
1382
1382
  - Verify your approach
1383
1383
  - Try a different method
1384
- `.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 Uo}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),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 En=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1384
+ `.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 Lc(){return new Bo}var Os=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 In=class{mode="ask";filterTools(e){return e.filter(t=>this.isReadOnlyTool(t))}getSystemPrompt(){return `You are in ASK mode (read-only). You can:
1385
1385
  - Read files and search code
1386
1386
  - Analyze and understand the codebase
1387
1387
  - Answer questions about the project
@@ -1389,7 +1389,7 @@ Please:
1389
1389
 
1390
1390
  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.
1391
1391
 
1392
- 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:
1392
+ 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 An=class{mode="agent";filterTools(e){return e}getSystemPrompt(){return `You are in AGENT mode (standard). You have access to:
1393
1393
  - Read and analyze the codebase
1394
1394
  - Make file edits and create new files
1395
1395
  - Run commands and scripts
@@ -1400,7 +1400,7 @@ Some dangerous operations may require user approval before execution. When reque
1400
1400
  - Mention any potential risks
1401
1401
  - Wait for user confirmation before proceeding
1402
1402
 
1403
- 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:
1403
+ 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 Pn=class{mode="auto";filterTools(e){return e}getSystemPrompt(){return `You are in AUTO mode (automatic). You have full access to:
1404
1404
  - Read and write files
1405
1405
  - Execute commands
1406
1406
  - Make changes to the project
@@ -1414,33 +1414,33 @@ All operations will execute automatically without user confirmation. You should:
1414
1414
 
1415
1415
  \u26A0\uFE0F Important: Since there's no approval step, double-check your actions before executing.
1416
1416
 
1417
- 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 jo(r){return Nt.getStrategy(r)}var Lc=2e4,Tg=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 xg(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 Sg=Fc("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),kg=Fc("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Cg=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Nc(r,e=Tg){if(!r||r.length<=e)return r;let t=r.split(`
1417
+ 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 In);Nt.register(new An);Nt.register(new Pn);function Wo(r){return Nt.getStrategy(r)}var $c=2e4,kg=15e3;function jc(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 Nc(r,e){let t=r??e;return t===0||t===1/0?null:!Number.isFinite(t)||t<0?e:Math.floor(t)}function zr(){let r=new Error("Request aborted");return r.name="AbortError",r.code="ERR_CANCELED",r.category="canceled",r}async function Fc(r,e){if(r?.aborted)throw zr();return e()}function Cg(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 Rg=jc("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),Eg=jc("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Ig=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Uc(r,e=kg){if(!r||r.length<=e)return r;let t=r.split(`
1418
1418
  `).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=`
1419
1419
 
1420
1420
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1421
1421
 
1422
- `;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=jo(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=jo(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??Lc,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??Lc}, safety=${o})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Cg){for await(let o of e)yield o;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((o,a)=>{t.aborted?a(Wr()):t.addEventListener("abort",()=>a(Wr()),{once:true});}):null,i=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw Wr()}let o=i?kg:Sg,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(xg(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 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 fo(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)),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 $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),Ao(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}}Ao(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}
1422
+ `;return l+p+c}var qr=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 Gr(e.structuredOutput)),this.inputGuardrails=e.inputGuardrails||[],this.outputGuardrails=e.outputGuardrails||[],this.toolInputGuardrails=e.toolInputGuardrails||[],this.toolOutputGuardrails=e.toolOutputGuardrails||[],this.parallelExecutor=new Wr,this.compressionMode=e.compressionMode??"sync",this.workspacePath=e.workspacePath,this.unifiedCompressor=new Br({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=Wo(this.currentMode),this.permissionManager=e.permissionManager??new Os({defaultPermission:"ask"}),this.loopDetector=Lc(),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=Wo(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??$c,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??$c}, safety=${o})`;console.log(u);}return c}async*withStreamWatchdog(e,t){if(Ig){for await(let o of e)yield o;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((o,a)=>{t.aborted?a(zr()):t.addEventListener("abort",()=>a(zr()),{once:true});}):null,i=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw zr()}let o=i?Eg:Rg,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Cg(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 Xt.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 _o(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:fc,W=O===0||O===1/0,F=Nc(this.config.maxToolCalls,yc),x=Nc(this.config.maxRuntimeMs,bc);for(;W||d<O;){if(s?.aborted){_="interrupted",y=true,yield {type:"error",error:"Task interrupted by user."};break}if(x!==null&&Date.now()-p>=x){_="runtime_limit",y=true,yield {type:"error",error:`Reached max runtime (${ze(x)}). 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 S of $){let D=S.function.arguments||"";if(P.test(D)){console.error("[Runner] \u{1F6A8} Placeholder string detected in tool arguments!"),console.error(`[Runner] Tool: ${S.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:S.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 S=$.map(H=>H.function.name),D=[...new Set(S)];D.length===1&&S.length>1?g.info("RUNNER",`\u{1F504} Parallel calls: ${S.length}x ${D[0]} (different parameters)`):g.info("RUNNER",`\u{1F504} Parallel calls: ${S.join(", ")}`);}for(let S of $){h++,yield {type:"run_item_stream_event",name:"tool_called",item:{type:"tool_call_item",id:S.id,name:S.function.name,arguments:S.function.arguments,timestamp:Date.now()}},yield {type:"tool_call_start",id:S.id,name:S.function.name};let H=!1;try{S.function.arguments&&(JSON.parse(S.function.arguments),H=!0);}catch(V){te.toolError(S.function.name,`Invalid JSON arguments (${V.message}): ${S.function.arguments.substring(0,200)}...`),console.error(`[Runner] \u26A0\uFE0F Tool ${S.function.name} has invalid JSON arguments`),console.error(`[Runner] Arguments length: ${S.function.arguments.length}`),console.error(`[Runner] First 200 chars: ${S.function.arguments.substring(0,200)}`),console.error(`[Runner] Last 200 chars: ${S.function.arguments.substring(Math.max(0,S.function.arguments.length-200))}`);}yield {type:"tool_call_done",id:S.id,name:S.function.name,arguments:S.function.arguments,success:H},yield {type:"raw_response_event",data:{type:"response.function_call_arguments.done",call_id:S.id,name:S.function.name,arguments:S.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(S=>S.function.name)});for(let S of $){let D={};try{let I=S.function.arguments?.trim()||"";D=I?JSON.parse(I):{};}catch(I){te.toolError(S.function.name,`Loop detection skipped: invalid JSON (${I.message})`);continue}let H=this.loopDetector.detect(S.function.name,D);if(this.loopDetector.record(S.function.name,D),H===0)continue;let V=this.loopDetector.generateIntervention(H,S.function.name,D);if(this.memory.add({role:"system",content:V.message}),H===2&&da(S.function.name))continue;if(yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:V.message,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:S.function.name,output:V.message,success:!1},this.memory.addToolResult(S.id,S.function.name,V.message),this.loopDetector.updateLastStatus("error"),K.add(S.id),V.shouldTerminate){U=V;break}}if(U&&(yield {type:"error",error:U.message},y=!0),y)break;let Te=K.size>0?$.filter(S=>!K.has(S.id)):$,Q=new Set(this.modeStrategy.filterTools(this.tools).map(S=>S.name)),ie=S=>S.replace(/["\s/>]+$/g,"").trim(),se=[];for(let S of Te){let D=ie(S.function.name);if(Q.has(D)||Q.has(S.function.name)){se.push(S);continue}let H=`Tool "${S.function.name}" is not allowed in ${this.currentMode} mode`;te.toolError(S.function.name,H),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.function.name,output:H,success:!1,timestamp:Date.now()}},yield {type:"tool_output",name:S.function.name,output:H,success:!1},this.memory.addToolResult(S.id,S.function.name,H),g.info("PERMISSION",`Tool blocked by mode: ${S.function.name} - ${H}`);}if(se.length===0)continue;let ae=se.map(S=>({id:S.id,type:"function",function:{name:S.function.name,arguments:S.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 S=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 Se=await Fc(s,async()=>this.permissionManager.checkPermission(we,V));if(!Se.allowed){S.add(D.id);let I=Se.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 z=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,z),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=>!S.has(D.id)),ae=ae.filter(D=>!S.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 S=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},Se=this.tools.find(j=>j.name===D.function.name);if(!Se)continue;this.runContext.iteration=d;let I=await Fc(s,async()=>Xt.runToolInputGuardrails(this.toolInputGuardrails,{context:this.runContext,tool_context:we,agent_name:this.agentName,tool:Se}));if(!I.should_execute){S.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),Lo(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=>!S.has(D.id)),ae=ae.filter(D=>!S.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,S=>{if(te.toolCall(S.name,{}),S.success){let H=typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length;te.toolResult(S.name,!0,H,S.executionTime||0);}else te.toolError(S.name,S.output);let D={type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()};},s);for(let S of pe.results){if(this.toolMetricsHistory.push({name:S.name,duration:S.executionTime||0,success:S.success}),this.toolMetricsHistory.length>50&&this.toolMetricsHistory.shift(),yield {type:"run_item_stream_event",name:"tool_output",item:{type:"tool_call_output_item",id:S.id,name:S.name,output:S.output,success:S.success,timestamp:Date.now()}},yield {type:"tool_output",name:S.name,output:S.output,success:S.success},S.name==="update_plan"&&S.success)try{g.info("PLAN_UPDATE","\u{1F525} Detected update_plan tool call",{resultId:S.id,toolCallsCount:$.length});let I=$.find(j=>j.id===S.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:S.id,availableIds:$.map(j=>j.id)});}catch(I){g.error("PLAN_UPDATE","\u274C Failed to parse plan",{error:I});}let H=typeof S.output=="string"?Uc(S.output):Uc(JSON.stringify(S.output));H=this.enrichToolResult(H,S.name,S.executionTime||0);let V=$.find(I=>I.id===S.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===S.name);if(I){let j={tool_name:S.name,tool_input:we,tool_call_id:S.id},z=await Xt.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:j,agent_name:this.agentName,tool:I,output:S.output});z.should_use_output||(H=z.replacement_message||"[Output blocked by guardrail]",te.toolError(S.name,"Output blocked by guardrail"));}}catch(I){I instanceof st&&te.toolError(S.name,`Output guardrail tripwire triggered: ${I.message}`);}if(!S.success&&typeof S.output=="string"){let I=S.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}}Lo(this.runContext,S.name,we,S.success),g.info("TOOL_RESULT",`\u{1F4E6} Tool raw output: ${S.name}`,{toolName:S.name,success:S.success,rawLength:typeof S.output=="string"?S.output.length:JSON.stringify(S.output).length,truncatedLength:H.length,outputPreview:H.substring(0,500)}),this.memory.addToolResult(S.id,S.name,H);let Se=S.success?"success":"error";try{let I=typeof S.output=="string"?S.output:JSON.stringify(S.output),j=JSON.parse(I);j.status==="already_done"?Se="already_done":j.status==="success"?Se="success":j.status==="error"&&(Se="error");}catch{}if(this.loopDetector.updateLastStatus(Se),Se==="error"){let I=(v.get(S.name)||0)+1;if(v.set(S.name,I),S.name==="edit_file"&&(I===2||I===3)){let j=typeof S.output=="string"?S.output:JSON.stringify(S.output),z=S.name,ye=Oc(z,j);this.memory.add({role:"system",content:ye});}}else v.set(S.name,0);}if(d>0&&d%5===0){let S=this.buildPerformanceHint();S&&(this.memory.add({role:"system",content:S}),process.env.CLI_DEBUG_CONSOLE==="1"&&console.log("[Runner] Performance hint injected:",S));}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 Xt.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=Rn(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 ${ze(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 As(N),d--;continue}let B=Ur(M),E=M.message;B&&!E.includes(B)&&(E=`${E}
1423
1423
 
1424
- \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}]
1424
+ \u{1F4A1} Suggestion: ${B}`),y=true;let L=Ic(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}]
1425
1425
 
1426
1426
  `+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:`
1427
1427
  [Performance Notice]
1428
1428
  ${n.join(`
1429
1429
  `)}
1430
- `}};le();var Eg={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,"/"),i=n(s),o=Tc(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})?Dr():(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}`),pc(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1430
+ `}};le();var Ag={name:"require_read_before_edit",guardrail_function:async r=>{let{tool_name:e,tool_input:t}=r.tool_context;if(e!=="edit_file")return Nr();let s=t.file_path;if(!s)return Nr();let n=l=>Y__default.resolve(l).replace(/\\/g,"/"),i=n(s),o=xc(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})?Nr():(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}`),mc(`\u26A0\uFE0F \u7F16\u8F91\u524D\u8BF7\u5148\u8BFB\u53D6\u6587\u4EF6
1431
1431
 
1432
1432
  \u6587\u4EF6: ${s}
1433
1433
 
1434
1434
  \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
1435
- \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=[Eg],jc=[];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(`
1435
+ \u8FD9\u53EF\u4EE5\u907F\u514D\u57FA\u4E8E\u8FC7\u65F6\u4FE1\u606F\u8FDB\u884C\u7F16\u8F91\u3002`,{file_path:s,suggestion:"use readfile first"}))}};var Gc=[Ag],Bc=[];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(`
1436
1436
 
1437
- `):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 Ig={"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}}},Mg={"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"}},Ag={"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"}},Pg={"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"}},Og={"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"}},Lg={"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"}},Dg={"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"}},Go=class{models=new Map;constructor(){this.registerModels(Ig),this.registerModels(Mg),this.registerModels(Ag),this.registerModels(Pg),this.registerModels(Og),this.registerModels(Lg),this.registerModels(Dg);}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 Go;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=Gc.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 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}
1437
+ `):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 Pg={"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}}},Og={"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"}},Lg={"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"}},Dg={"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"}},$g={"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"}},Ng={"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"}},Fg={"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"}},Ho=class{models=new Map;constructor(){this.registerModels(Pg),this.registerModels(Og),this.registerModels(Lg),this.registerModels(Dg),this.registerModels($g),this.registerModels(Ng),this.registerModels(Fg);}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}},Wc=new Ho;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=Wc.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 Ls(r){return e=>r.includes(e)?true:`Must be one of: ${r.join(", ")}`}function Hc(r){return e=>{let t=typeof e;return t!==r?`Expected ${r}, got ${t}`:true}}function Jr(...r){return (e,t)=>{for(let s of r){let n=s(e,t);if(n!==true)return n}return true}}var es=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:Ls(["low","medium","high"]),verbosity:Ls(["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":Ls(["text","json_object","json_schema"]),stream:e=>typeof e=="boolean"||"Must be a boolean",n:Jr(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}
1438
1438
 
1439
1439
  ${s.content}`:s.content).join(`
1440
1440
 
1441
- `)}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,`
1441
+ `)}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 ts(r){return r.replace(/\n{3,}/g,`
1442
1442
 
1443
- `).trim()}var $g=`You are Claude Code, Anthropic's official CLI for Claude.
1443
+ `).trim()}var Ug=`You are Claude Code, Anthropic's official CLI for Claude.
1444
1444
 
1445
1445
  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.
1446
1446
 
@@ -1478,11 +1478,11 @@ When planning tasks, provide concrete implementation steps without time estimate
1478
1478
  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.
1479
1479
  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.
1480
1480
 
1481
- 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:i}=e;return this.isResponsesAPIModel(n)?this.buildResponsesAPIPrompt(i):this.buildChatCompletionsPrompt(t,s,n,i)}buildResponsesAPIPrompt(e){let t=$g;return e&&e.trim()&&(t+=`
1481
+ 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(),ss=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=Ug;return e&&e.trim()&&(t+=`
1482
1482
 
1483
1483
  # Custom Instructions
1484
1484
 
1485
- `+e.trim()),es(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}),es(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
1485
+ `+e.trim()),ts(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}),ts(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
1486
1486
 
1487
1487
  \u4F60\u7684\u4E3B\u8981\u804C\u8D23\u662F\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u8F6F\u4EF6\u5DE5\u7A0B\u4EFB\u52A1\uFF0C\u5305\u62EC\uFF1A
1488
1488
  - \u4EE3\u7801\u751F\u6210\u548C\u4FEE\u6539
@@ -1552,26 +1552,26 @@ Tool results are returned via messages with role "tool".`}getGeneralRules(e){ret
1552
1552
  1. **Accuracy First**: Ensure correctness of code and suggestions
1553
1553
  2. **Be Concise**: Avoid redundancy, answer directly
1554
1554
  3. **Safety First**: No malicious code, be aware of security risks
1555
- 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 Bg=16e3;function Wc(r,e=Bg){if(!r||r.length<=e)return r;let t=r.split(`
1555
+ 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 zg=16e3;function zc(r,e=zg){if(!r||r.length<=e)return r;let t=r.split(`
1556
1556
  `).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=`
1557
1557
 
1558
1558
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1559
1559
 
1560
- `;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=Ng.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: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 Ms(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 Xt(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=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`)),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}}),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=[],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(` \\
1561
- `),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?`
1562
- `+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=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=Fo({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>
1560
+ `;return l+p+c}function qc(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 Jc(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=jg.create({baseURL:this.baseUrl,headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"},timeout:12e4}),this.defaultModel=e.defaultModel||"gpt-4";let t=Es("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=xt(h),y=Dt(f,p+1,this.retryConfig);g.info("OpenAI",`Request failed (${m.code}), retrying in ${ze(y)} (${p+1}/${c})...`),await As(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=xt(h),y=Dt(f,p,this.retryConfig);g.info("OpenAI",`Stream failed (${m.code}), reconnecting in ${ze(y)} (${p}/${u})...`),yield {choices:[],type:"stream_retry",error:m.message,errorCode:m.code,attempt:p,maxRetries:u,delayMs:y};try{await Zt(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=Jc(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}}),qc(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=zc(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(` \\
1561
+ `),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=Yt(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=Yt(d,m);h=`${f.message}${f.detail?`
1562
+ `+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=Jc(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,qc(u,this.privacySettings)}buildResponsesInstructions(e){let t=Go({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>
1563
1563
  ${n}
1564
- </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=Wc(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
1564
+ </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=zc(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
1565
1565
 
1566
1566
  <INSTRUCTIONS>
1567
1567
  ${n}
1568
1568
  </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(`
1569
1569
  `);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(`
1570
- `);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 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: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 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,i=Br({workDir:t,language:s});return n&&n.trim()&&(i+=`
1570
+ `);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 Kr=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new es,this.promptBuilder=new ss,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 On=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:Jr(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":Ls(["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 Ln=class extends Ut{buildSystemPrompt(e){let{workDir:t,language:s="zh",customInstructions:n}=e,i=Hr({workDir:t,language:s});return n&&n.trim()&&(i+=`
1571
1571
 
1572
1572
  # Custom Instructions
1573
1573
 
1574
- `+n.trim()),es(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
1574
+ `+n.trim()),ts(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
1575
1575
 
1576
1576
  - **Extended Thinking**: ${s?"\u652F\u6301\u6DF1\u5EA6\u601D\u8003\u6A21\u5F0F\uFF08thinking.type: enabled\uFF09":"\u4E0D\u652F\u6301"}
1577
1577
  - **Prompt Caching**: \u81EA\u52A8\u7F13\u5B58\u91CD\u590D\u7684\u4E0A\u4E0B\u6587\uFF0C\u8282\u7701\u6210\u672C
@@ -1621,21 +1621,21 @@ Claude uses standard tool calling format:
1621
1621
  }
1622
1622
  \`\`\`
1623
1623
 
1624
- 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 Hg=15e3,Dn=2*1024*1024,qg=1.5*1024*1024;function zg(r,e=Hg){if(!r||r.length<=e)return r;let t=r.split(`
1624
+ 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 Jg=15e3,$n=2*1024*1024,Kg=1.5*1024*1024;function Vg(r,e=Jg){if(!r||r.length<=e)return r;let t=r.split(`
1625
1625
  `).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=`
1626
1626
 
1627
1627
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1628
1628
 
1629
- `;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)}
1630
- ...[truncated ${s.length-e} chars]`:s:"No headers"}var Bo="You are Claude Code, Anthropic's official CLI for Claude.",Jg=["claude-code-20250219","interleaved-thinking-2025-05-14"],Kr="2023-06-01",Vr=64,Kg=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"},Wo={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||Jg,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?Bo:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Ng.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,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: ${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),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=$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 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(`
1631
- `);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?Wo[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: ${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(`
1632
- `),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=$r(u.response?.headers),y=Cn(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 Xt(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:Bo}),n&&a.push({type:"text",text:`
1633
- `+n})):(a.push({type:"text",text:Bo,cache_control:{type:"ephemeral"}}),n&&a.push({type:"text",text:`
1634
- `+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>Dn){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:Dn,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 ${(Dn/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>qg&&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(i=>i.role==="user");if(n>=0){let i=s[n],o={type:"text",text:`<system_context>
1629
+ `;return l+p+c}function Kc(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)}
1630
+ ...[truncated ${s.length-e} chars]`:s:"No headers"}var zo="You are Claude Code, Anthropic's official CLI for Claude.",Yg=["claude-code-20250219","interleaved-thinking-2025-05-14"],Yr="2023-06-01",Xr=64,Xg=1024;var Vc=18e4,Yc=6e4,Xc={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"},qo={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"},Ds=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||Yg,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?zo:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=jg.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=Es("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: ${Kc(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=Fr(u.response?.headers),m=Rn(p.category,a+1,d||p.retryAfter),h=p.category==="retryable_rate_limit",f=h?`\u23F3 API \u4EE3\u7406\u901F\u7387\u9650\u5236\uFF0C${ze(m)} \u540E\u91CD\u8BD5...`:`Retrying in ${ze(m)}...`;this.debugLog("Retrying",{delay:ze(m),attempt:a+1,isRateLimit:h,serverDelay:d?ze(d):"none",retryMsg:f});try{await Zt(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(`
1631
+ `);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?qo[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: ${Kc(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=[],x=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(`
1632
+ `),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"?x={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"?x&&(G.delta?.type==="thinking_delta"?x.thinking+=G.delta.thinking||"":G.delta?.type==="signature_delta"&&(x.signature+=G.delta.signature||"")):G.type==="content_block_stop"&&x&&(F.push({type:x.type,thinking:x.thinking,signature:x.signature}),x=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=Fr(u.response?.headers),y=Rn(p.category,i,f||p.retryAfter),b=p.category==="retryable_rate_limit",_=p.category==="retryable_stream";this.debugLog("Stream retrying",{delay:ze(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 Zt(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:zo}),n&&a.push({type:"text",text:`
1633
+ `+n})):(a.push({type:"text",text:zo,cache_control:{type:"ephemeral"}}),n&&a.push({type:"text",text:`
1634
+ `+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>$n){if(this.debugLog("Request body exceeds limit",{bodySize:s,limit:$n,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 ${($n/1024/1024).toFixed(1)}MB limit. Request may fail.`);}else s>Kg&&this.debugLog("Request body approaching limit",{bodySize:s,limit:$n,percentage:(s/$n*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>
1635
1635
  ${e}
1636
- </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,Kg)}}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(`
1636
+ </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,Xg)}}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(`
1637
1637
 
1638
- `):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=zg(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?Vc[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?Wo[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?Wo[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?Vc[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":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",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?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=[o.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 (${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();hi(i,o,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,i,a),this.debugLog(`${s?"Stream ":""}Request`,{url:i,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:i,disableCaching:o,userId:a,...l}=e;this.provider=new Ls({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 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=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 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: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 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: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}),es(this.combinePromptSections(o))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1638
+ `):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=Vg(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?Xc[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?qo[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?qo[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?Xc[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":Yr,"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":Yr,"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>Xr?createHash("sha256").update(e).digest("hex").slice(0,Xr):/^[\w.+-]+@[\w.-]+\.\w+$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Xr):/^\+?[\d\s-]{10,}$/.test(e)?createHash("sha256").update(e).digest("hex").slice(0,Xr):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?Vc:Yc,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 ${Vc/1e3}s`:`Stream first chunk timeout: no response for ${Yc/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();yi(i,o,t);let a=this.isProxyMode?{Authorization:"Bearer ***","anthropic-version":Yr,"anthropic-beta":this.betaFeatures.join(","),"Content-Type":"application/json"}:{"anthropic-api-key":"***","anthropic-version":Yr,"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 Zr=class extends ft{constraints;promptBuilder;provider;defaultModel;disableCaching;constructor(e){super(),this.constraints=new On,this.promptBuilder=new Ln,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 Ds({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 Qr=class extends es{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 ei=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new Qr,this.promptBuilder=new ss,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 ti=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:Hc("boolean")},defaults:{temperature:1}}}};var Nn=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}),ts(this.combinePromptSections(o))}getConstraintInstructions(e){return e==="zh"?`- temperature: 0.0 - 2.0
1639
1639
  - topP: 0.0 - 1.0
1640
1640
  - topK: >= 1
1641
1641
  - maxOutputTokens: \u63A7\u5236\u8F93\u51FA\u957F\u5EA6
@@ -1679,24 +1679,24 @@ Your primary responsibilities:
1679
1679
  1. **Accuracy first**: ensure correctness
1680
1680
  2. **Be concise**: avoid redundancy
1681
1681
  3. **Safety first**: avoid destructive actions
1682
- 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 Xg(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 Zg(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 Qg="skip_thought_signature_validator",Zc=8192;function Qc(r){return r.includes("gemini-3")||r.includes("preview")}function ef(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:Qg},t[s]={...n,parts:i});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=Xg(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=Lt(Rs("gemini"),s);let i={"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"?i["x-goog-api-key"]=this.apiKey:this.authMode==="bearer"&&(i.Authorization=`Bearer ${this.apiKey}`),this.client=Ng.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:Zg(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??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||[],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:Xc(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 Ms(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=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)?ef(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: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: ${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(`
1682
+ 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 ef(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 tf(r){try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{value:e}}catch{return {}}}function Qc(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 sf="skip_thought_signature_validator",eu=8192;function tu(r){return r.includes("gemini-3")||r.includes("preview")}function nf(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:sf},t[s]={...n,parts:i});break}}}}return t}var $s=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=ef(n?.pathPrefix),this.userId=randomUUID(),this.authMode=this.resolveAuthMode(n?.authMode),this.retryConfig=Lt(Es("gemini"),s);let i={"Content-Type":"application/json","User-Agent":`GeminiCLI/v22.16.0 (${Gs.platform()}; ${Gs.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=jg.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:tf(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??eu,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:Qc(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=xt(i.response?.headers?.["retry-after"]);if(!o.retryable||n>this.retryConfig.requestMaxRetries)break;let l=Dt(a,n,this.retryConfig);await As(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=tu(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??eu,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:tu(s)?nf(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:Qc(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(`
1683
1683
  `);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(`
1684
- `));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 ei=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:i}=e;this.provider=new Ds(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 $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 ei(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 sf=16e3;function nf(r,e=sf){if(!r||r.length<=e)return r;let t=r.split(`
1684
+ `));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 si=class extends ft{constraints;promptBuilder;provider;defaultModel;constructor(e){super(),this.constraints=new ti,this.promptBuilder=new Nn,this.defaultModel=e.defaultModel||"gemini-2.5-flash";let{apiKey:t,baseUrl:s,urlSuffix:n,retry:i}=e;this.provider=new $s(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 Ns=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 Kr(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 Zr(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 ei(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 si(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 of=16e3;function af(r,e=of){if(!r||r.length<=e)return r;let t=r.split(`
1685
1685
  `).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=`
1686
1686
 
1687
1687
  \u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
1688
1688
 
1689
- `;return l+p+c}var ti=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=Ng.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(`
1689
+ `;return l+p+c}var ni=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=jg.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(`
1690
1690
  [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(`
1691
1691
  [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(`
1692
1692
  [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(`
1693
1693
  [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}
1694
- ${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: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(`
1694
+ ${h}`),te.llmError("doubao-responses",m),f.retryable&&d<p){d++;let y=m.response?.headers?.["retry-after"],b=xt(y),_=Dt(b,d,this.retryConfig);console.log(`[Doubao] Stream failed (${f.code}), reconnecting in ${ze(_)} (${d}/${p})...`),yield {choices:[],type:"stream_retry",error:f.message,errorCode:f.code,attempt:d,maxRetries:p,delayMs:_};try{await Zt(_,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(`
1695
1695
 
1696
- `):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=nf(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(`
1696
+ `):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=af(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(`
1697
1697
  `);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(`
1698
1698
  `);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(`
1699
- `));}(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 Ho="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",rf=60,of=200,af=`You are a highly skilled assistant tasked with summarizing conversation history.
1699
+ `));}(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 Jo="# \u4F1A\u8BDD\u5386\u53F2\u6458\u8981",lf=60,cf=200,uf=`You are a highly skilled assistant tasked with summarizing conversation history.
1700
1700
 
1701
1701
  Your goal is to create a concise yet comprehensive summary that captures:
1702
1702
  1. The main topics and objectives discussed
@@ -1713,7 +1713,7 @@ Guidelines:
1713
1713
  - Write in the same language as the conversation (Chinese if Chinese, English if English)
1714
1714
  - Format the summary clearly with sections if needed
1715
1715
 
1716
- Output only the summary, no additional commentary.`,lf=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1716
+ Output only the summary, no additional commentary.`,pf=`\u4F60\u662F\u4E00\u4E2A\u4E13\u4E1A\u7684\u5BF9\u8BDD\u5386\u53F2\u603B\u7ED3\u52A9\u624B\u3002
1717
1717
 
1718
1718
  \u4F60\u7684\u76EE\u6807\u662F\u521B\u5EFA\u4E00\u4E2A\u7B80\u6D01\u4F46\u5168\u9762\u7684\u6458\u8981\uFF0C\u9700\u8981\u5305\u542B\uFF1A
1719
1719
  1. \u8BA8\u8BBA\u7684\u4E3B\u8981\u4E3B\u9898\u548C\u76EE\u6807
@@ -1730,7 +1730,7 @@ Output only the summary, no additional commentary.`,lf=`\u4F60\u662F\u4E00\u4E2A
1730
1730
  - \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
1731
1731
  - \u5982\u679C\u9700\u8981\uFF0C\u4F7F\u7528\u5206\u8282\u6765\u6E05\u6670\u5730\u683C\u5F0F\u5316\u6458\u8981
1732
1732
 
1733
- \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function cf(r){for(let e of r){let t=ee(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function uf(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}
1733
+ \u53EA\u8F93\u51FA\u6458\u8981\uFF0C\u4E0D\u8981\u6DFB\u52A0\u989D\u5916\u7684\u8BC4\u8BBA\u3002`;function df(r){for(let e of r){let t=ee(e.content);if(/[\u4e00-\u9fa5]/.test(t))return "zh"}return "en"}function mf(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}
1734
1734
  ${o}`);}}return `Please summarize the following conversation history:
1735
1735
 
1736
1736
  ---
@@ -1740,18 +1740,18 @@ ${e.join(`
1740
1740
  `)}
1741
1741
  ---
1742
1742
 
1743
- 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 zo(r,e){return r.length<=e?r:r.slice(0,e-1).trimEnd()+"\u2026"}function pf(r){return r.replace(/\s+/g," ").trim()}function qo(r,e){if(r.length===0)return {summary:"",lines:0};let t=[];for(let n of r){if(t.length>=rf)break;let i=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,o=ee(n.content),l=(o?pf(o):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${i}] ${zo(l,of)}`);}return {summary:`${e}
1743
+ Provide a comprehensive summary:`}function Fn(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 Vo(r,e){return r.length<=e?r:r.slice(0,e-1).trimEnd()+"\u2026"}function hf(r){return r.replace(/\s+/g," ").trim()}function Ko(r,e){if(r.length===0)return {summary:"",lines:0};let t=[];for(let n of r){if(t.length>=lf)break;let i=n.role==="assistant"?"Assistant":n.role==="user"?"User":n.role,o=ee(n.content),l=(o?hf(o):"")||(n.tool_calls?.length?`Tool calls: ${n.tool_calls.map(c=>c.function.name).join(", ")}`:"No textual content");t.push(`- [${i}] ${Vo(l,cf)}`);}return {summary:`${e}
1744
1744
  ${t.join(`
1745
- `)}`,lines:t.length}}async function Jo(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+=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;i?.("summarizing",`Summarizing ${f.length} messages with AI...`);let k=cf(f),R=k==="zh"?lf:af,O=uf(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}=qo(f,Ho);W=U;}}catch(A){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",A.message);let{summary:P}=qo(f,Ho);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)"}
1745
+ `)}`,lines:t.length}}async function Yo(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+=Fn(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=Fn(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=Fn(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=df(f),R=k==="zh"?pf:uf,O=mf(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}=Ko(f,Jo);W=U;}}catch(A){console.error("[SmartCompact] LLM call failed, falling back to lightweight:",A.message);let{summary:P}=Ko(f,Jo);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)"}
1746
1746
 
1747
- ${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:zo(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(),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+=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}=qo(u,r.summaryHeader??Ho);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:zo(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 si=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()}},ni=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(`
1748
- `)?`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,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 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 i=e.pattern||e.query;return i?`Searching for "${i}"`:"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 ri=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 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,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 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],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 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 ou=12e3,ii=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 si;commandGenerator=new ni;lastAssistantMessage="";batchDetector=new ri;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;pendingInjectedMessages=[];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});}injectUserMessage(e,t){if(!this.isRunning)return g.debug("INJECT","Cannot inject message: no task running"),0;this.pendingInjectedMessages.push({text:e,timestamp:new Date,images:t});let s=this.pendingInjectedMessages.length;return process.env.CLI_DEBUG&&g.debug("INJECT",`Message queued at position ${s}: "${e.substring(0,50)}..."`),s}hasPendingInjectedMessages(){return this.pendingInjectedMessages.length>0}getAndClearPendingMessages(){let e=[...this.pendingInjectedMessages];return this.pendingInjectedMessages=[],e}processPendingInjectedMessages(){if(this.pendingInjectedMessages.length===0)return 0;let e=[...this.pendingInjectedMessages];this.pendingInjectedMessages=[],process.env.CLI_DEBUG&&g.debug("INJECT",`Processing ${e.length} injected messages`);for(let t of e){let s=[];if(t.text&&s.push({type:"text",text:t.text}),t.images&&t.images.length>0)for(let i of t.images)s.push({type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}});let n={role:"user",content:s.length===1&&s[0].type==="text"?s[0].text:s};this.memory.add(n);}return e.length}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:
1747
+ ${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:Vo(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=Fn({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 su(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+=Fn(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}=Ko(u,r.summaryHeader??Jo);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:Vo(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 ri=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()}},ii=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(`
1748
+ `)?`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 Fs(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 nu(r,e){switch(r){case "readfile":let t=Fs(r,e);return t?`Reading ${t}`:"Reading file";case "write_file":case "create_file":let s=Fs(r,e);return s?`Writing ${s}`:"Writing file";case "edit_file":case "Edit":let n=Fs(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 ${Fs(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 oi=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();var gf={default:["Thinking...","Processing...","Analyzing...","Pondering...","Contemplating..."]};var ai={};function ff(r,e,t=true){ai[e]||(ai[e]=0);let s=ai[e]%r.length,n=r[s];return t&&(ai[e]=(s+1)%r.length),n}function ru(){let r=gf.default;return ff(r,"default")}function iu(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 ou(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 au(r,e,t){let s=gc(r,e,t),n=Ur(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 cu=12e3,li=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 ri;commandGenerator=new ii;lastAssistantMessage="";batchDetector=new oi;toolCallIdCounter=0;recentToolCalls=new Map;currentTaskMetadata;pendingInjectedMessages=[];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=Fa(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});}injectUserMessage(e,t){if(!this.isRunning)return g.debug("INJECT","Cannot inject message: no task running"),0;this.pendingInjectedMessages.push({text:e,timestamp:new Date,images:t});let s=this.pendingInjectedMessages.length;return g.info("INJECT",`\u{1F4E8} Message queued at position ${s}: "${e.substring(0,50)}..."`),this.emitEvent({type:"queued_message_added",position:s,text:e}),s}hasPendingInjectedMessages(){return this.pendingInjectedMessages.length>0}getPendingMessagesForDisplay(){return [...this.pendingInjectedMessages]}getAndClearPendingMessages(){let e=[...this.pendingInjectedMessages];return this.pendingInjectedMessages=[],e}processPendingInjectedMessages(){if(this.pendingInjectedMessages.length===0)return 0;let e=[...this.pendingInjectedMessages];this.pendingInjectedMessages=[],process.env.CLI_DEBUG&&g.debug("INJECT",`Processing ${e.length} injected messages`);for(let t of e){let s=[];if(t.text&&s.push({type:"text",text:t.text}),t.images&&t.images.length>0)for(let i of t.images)s.push({type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}});let n={role:"user",content:s.length===1&&s[0].type==="text"?s[0].text:s};this.memory.add(n);}return e.length}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:
1749
1749
  ${n.map((o,a)=>`Attachment ${a+1}: [URL: ${o.data}]`).join(`
1750
1750
  `)}
1751
1751
 
1752
1752
  ${s}`),t?.mode==="ask"&&(s=`Mode: ASK (respond conversationally and avoid unnecessary tool calls).
1753
1753
 
1754
- ${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=ns(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 Jo({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=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: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+=`
1754
+ ${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=rs(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 Yo({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=rs(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+=`
1755
1755
 
1756
1756
  \u{1F4C8} Context: ${a} \u2192 ${c}`),l.detailedStats){let{before:b,after:_,saved:v}=l.detailedStats,k=R=>(R/1e3).toFixed(1)+"K";y+=`
1757
1757
 
@@ -1765,28 +1765,28 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
1765
1765
  \u2502 \u603B\u8BA1: ${k(_.totalTokens)}`,y+=`
1766
1766
  \u2514\u2500 \u8282\u7701\uFF1A`,y+=`
1767
1767
  User: ${k(v.userTokens)} \u2022 Assistant: ${k(v.assistantTokens)} \u2022 Tool: ${k(v.toolTokens)}`,y+=`
1768
- \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: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=`
1769
- \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=ns(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(`
1770
- `))&&(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,`
1768
+ \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 su({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=`
1769
+ \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=rs(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 x=R.next();x.catch(()=>{});let C=await Promise.race([x,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,u>1){let E=this.processPendingInjectedMessages();E>0&&(g.info("INJECT",`\u2705 Processed ${E} injected messages at iteration ${u}`),this.emitEvent({type:"queued_messages_processed",count:E}));}if(this.emitEvent({type:"thinking",iteration:u,timestamp:Date.now()}),this.emitEvent({type:"status",status:"thinking",message:ru()}),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(`
1770
+ `))&&(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 S=0;S<U.length;S++)if(U[S]==="\\")Te++;else {if(U[S]==='"'&&Te%2===0){ne=S;break}Te=0;}ne>0&&(U=U.substring(0,ne));let Q=U.replace(/\\n/g,`
1771
1771
  `).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(`
1772
- `),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=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,ou),G=E.length>ou;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(`
1773
- `).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=ns(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)
1772
+ `),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=ou(w.name,E);if(L.isTruncated){process.env.CLI_DEBUG_CONSOLE==="1"&&g.log("MK",`[AgentHost] \u26A0\uFE0F Truncation detected: ${L.reason}`);let Q=iu(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 $=Fs(w.name,N),G=this.descriptionExtractor.extractFromAssistantMessage(m,w.name);G||(G=nu(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=au(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,cu),G=E.length>cu;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(`
1773
+ `).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=rs(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)
1774
1774
  \u7CFB\u7EDF\u63D0\u793A\u8BCD: ${i.toLocaleString()} tokens
1775
1775
  \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
1776
1776
  \u5BF9\u8BDD\u5386\u53F2: ${(o/1e3).toFixed(1)}K tokens (${d.length} \u6761\u6D88\u606F)
1777
- \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 Jo({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+=`
1777
+ \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 Yo({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=rs(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,x=C=>(C/1e3).toFixed(1)+"K";R+=`
1778
1778
 
1779
1779
  \u25A0 \u8BE6\u7EC6\u7EDF\u8BA1\uFF1A`,R+=`
1780
1780
  \u250C\u2500 \u538B\u7F29\u524D\uFF1A`,R+=`
1781
- \u2502 User: ${S(O.userTokens)} \u2022 Assistant: ${S(O.assistantTokens)} \u2022 Tool: ${S(O.toolTokens)}`,R+=`
1782
- \u2502 \u603B\u8BA1: ${S(O.totalTokens)}`,R+=`
1781
+ \u2502 User: ${x(O.userTokens)} \u2022 Assistant: ${x(O.assistantTokens)} \u2022 Tool: ${x(O.toolTokens)}`,R+=`
1782
+ \u2502 \u603B\u8BA1: ${x(O.totalTokens)}`,R+=`
1783
1783
  \u251C\u2500 \u538B\u7F29\u540E\uFF1A`,R+=`
1784
- \u2502 User: ${S(W.userTokens)} \u2022 Assistant: ${S(W.assistantTokens)} \u2022 Tool: ${S(W.toolTokens)}`,R+=`
1785
- \u2502 Summary: ${S(W.summaryTokens)}`,R+=`
1786
- \u2502 \u603B\u8BA1: ${S(W.totalTokens)}`,R+=`
1784
+ \u2502 User: ${x(W.userTokens)} \u2022 Assistant: ${x(W.assistantTokens)} \u2022 Tool: ${x(W.toolTokens)}`,R+=`
1785
+ \u2502 Summary: ${x(W.summaryTokens)}`,R+=`
1786
+ \u2502 \u603B\u8BA1: ${x(W.totalTokens)}`,R+=`
1787
1787
  \u2514\u2500 \u8282\u7701\uFF1A`,R+=`
1788
- User: ${S(F.userTokens)} \u2022 Assistant: ${S(F.assistantTokens)} \u2022 Tool: ${S(F.toolTokens)}`,R+=`
1789
- \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 hf="ark.cn-beijing.volces.com";function gf(r){return r.includes("opus-4-5")||r.includes("opus-4.5")||r.endsWith("-thinking")}function Ko(r){return r.includes("doubao-seed")}function Vo(r){return !!r&&r.includes(hf)}function ff(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function yf(r){let e=r?.getProvider?.();return e instanceof Ls?e:void 0}function bf(r){let e=r?.getProvider?.();return e instanceof Ds?e:void 0}function _f(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&&Vo(t)&&Ko(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 au(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:Vo(o)&&Ko(t)?{type:"enabled"}:void 0},h=$s.createAdapter(n,m);a=h,l=ff(h),l&&Vo(o)&&Ko(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let m={...e,defaultModel:t,lastSelectedModel:t},h=$s.createAdapter(n,m);a=h,c=yf(h),c&&gf(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 ti({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=$s.createAdapter(n,m);a=h,p=bf(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=_f({model:t,baseUrl:o,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 ii({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 Yo(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??uu(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}=au({provider:t,model:s.model,sessionId:e}),M=s.compatProfile??null,B=M?new Hn(M):void 0,E=p??await Eo(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: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:cu({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 Xo=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: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 Yo({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 pu(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 Fn=240,oi=2e3;function ut(r,e){return r?r.length<=e?r:r.slice(0,e).trimEnd()+"...":""}var ai=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},Zo=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,Fn);this.actionLog.record({type:"run_start",sessionId:t,runId:R,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:ut(s,oi),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 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 ai("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,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=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),oi):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,oi):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,oi),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 wf=[".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:wf};var li=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 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=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}`,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(`
1788
+ User: ${x(F.userTokens)} \u2022 Assistant: ${x(F.assistantTokens)} \u2022 Tool: ${x(F.toolTokens)}`,R+=`
1789
+ \u51C0\u8282\u7701: ${x(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 _f="ark.cn-beijing.volces.com";function wf(r){return r.includes("opus-4-5")||r.includes("opus-4.5")||r.endsWith("-thinking")}function Xo(r){return r.includes("doubao-seed")}function Zo(r){return !!r&&r.includes(_f)}function vf(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function Tf(r){let e=r?.getProvider?.();return e instanceof Ds?e:void 0}function Sf(r){let e=r?.getProvider?.();return e instanceof $s?e:void 0}function xf(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&&Zo(t)&&Xo(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 uu(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:Zo(o)&&Xo(t)?{type:"enabled"}:void 0},h=Ns.createAdapter(n,m);a=h,l=vf(h),l&&Zo(o)&&Xo(t)&&l.setDoubaoThinking({type:"enabled"});}else if(n==="anthropic"){let m={...e,defaultModel:t,lastSelectedModel:t},h=Ns.createAdapter(n,m);a=h,c=Tf(h),c&&wf(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 ni({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=Ns.createAdapter(n,m);a=h,p=Sf(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=xf({model:t,baseUrl:o,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:p});return {llmProvider:a,controls:d}}function pu(r){return new qr({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??Gc,toolOutputGuardrails:r.toolOutputGuardrails??Bc,compressionMode:r.compressionMode,workspacePath:r.workspacePath,permissionManager:r.permissionManager,disableSystemPrompt:r.disableSystemPrompt})}function du(r){return new li({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 mu(r){return new Ws(r)}le();async function Qo(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,x=d??mu(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}=uu({provider:t,model:s.model,sessionId:e}),M=s.compatProfile??null,B=M?new zn(M):void 0,E=p??await Ao(n,R),L=h??{maxIterations:0,temperature:.7},N=pu({llmProvider:w,model:s.model,tools:E,memory:x,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:du({runner:N,memory:x,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:x}}var ea=class{hostController;platformServices;constructor(e){this.platformServices=e.platformServices,this.hostController=e.hostController??new Wn;}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:x,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 Qo({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:x});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 hu(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 Un=240,ci=2e3;function ut(r,e){return r?r.length<=e?r:r.slice(0,e).trimEnd()+"...":""}var ui=class extends Error{code;constructor(e){super(e),this.code="missing_provider";}},ta=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,Un);this.actionLog.record({type:"run_start",sessionId:t,runId:R,actor:"user",summary:F?`User: ${F}`:"User: (empty prompt)",data:{prompt:ut(s,ci),promptLength:s.length,attachments:n?.attachments?.map(x=>({type:x.type,name:x.name,path:x.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 hu({modelAlias:a?.modelAlias,initialProviderId:_,initialModelName:v,routeConfig:a,resolvedRoute:k,fallbackDecider:c,modelRouter:l??void 0,autoFailover:a?.autoFailover===!0,onRetry:({decision:x})=>{this.actionLog&&this.actionLog.record({type:"status",sessionId:t,runId:R,actor:"system",summary:x?.event?`Fallback: ${x.event.fromProviderId} -> ${x.event.toProviderId}`:"Fallback: switching provider",data:{from:x?.event?.fromProviderId,to:x?.event?.toProviderId,reason:x?.reason}}),b?.(x);},onExhausted:x=>{f?.("error",`All providers exhausted: ${x}`),this.actionLog&&this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`All providers exhausted: ${ut(x,Un)}`,data:{reason:x}});},runAttempt:async x=>{let C=this.resolveProvider(x.providerId,x.modelName);if(!C.provider||!C.llmConfig)throw new ui("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:x.isRetry?`Retry ${x.attempt}: ${C.llmConfig.model}`:`Run: ${C.llmConfig.model}`,data:{providerId:C.provider.id,providerName:C.llmConfig.providerName,model:C.llmConfig.model,attempt:x.attempt,isRetry:x.isRetry,previousError:x.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 x=Date.now()-i;l.recordSuccess(F.providerId,x),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 x=F instanceof Error?F.message:String(F);this.actionLog.record({type:"run_error",sessionId:t,runId:R,actor:"system",summary:`Run error: ${ut(x,Un)}`,data:{message:x}});}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),ci):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,ci):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,ci),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,Un)}`,data:{message:e.message}};case "error_classified":return {type:"run_error",sessionId:t,runId:s,actor:"system",summary:`Error ${e.code}: ${ut(e.message,Un)}`,data:{category:e.category,code:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable}};default:return null}}};var kf=[".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"],gu={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:kf};var pi=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={...gu,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=fu();}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=Sn.existsSync(this.shadowGitDir);this.git=fu(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=yu.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(`
1790
1790
  `).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?`
1791
1791
 
1792
1792
  Session: ${this.currentSessionId}
@@ -1799,4 +1799,4 @@ Stats: +${t.created} ~${t.modified} -${t.deleted} d${t.directories}${s}`}parseCo
1799
1799
  .cdundo/
1800
1800
  `:`# Neox checkpoint directory
1801
1801
  .cdundo/
1802
- `;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(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 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 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 li(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())}}};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}`,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 vf(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 Tf(){return {...wn(),capabilities:_o}}export{ea as RuntimeCheckpointService,Xo as RuntimeHostService,Zo as RuntimeOrchestrator,ai as RuntimeOrchestratorError,vf as applyThinkingMode,Fo as buildInstructions,Yo as createAgentRuntimeHost,Tf as createElectronServices,wn as createNodeServices,_o as electronToolCapabilities,Eo as getTools,Ar as nodeToolCapabilities,ph as preloadShellEnv,cc as setToolServices};
1802
+ `;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(Sn.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 jn=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 pi(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())}}};jn.getInstance();var na=class{checkpointManager;workspacePath=null;enabled=true;sessionMessageCounts=new Map;constructor(e){this.checkpointManager=e??jn.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 Cf(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 Rf(){return {...vn(),capabilities:To}}export{na as RuntimeCheckpointService,ea as RuntimeHostService,ta as RuntimeOrchestrator,ui as RuntimeOrchestratorError,Cf as applyThinkingMode,Go as buildInstructions,Qo as createAgentRuntimeHost,Rf as createElectronServices,vn as createNodeServices,To as electronToolCapabilities,Ao as getTools,Or as nodeToolCapabilities,hh as preloadShellEnv,pc as setToolServices};