@mk-co/neox-cli 2.0.30 → 2.0.32
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/cli/main.js +230 -224
- package/dist/sdk/index.js +62 -62
- package/package.json +1 -1
package/dist/sdk/index.js
CHANGED
|
@@ -2,10 +2,10 @@ import*as Sn from'fs';import Sn__default,{realpathSync,readlinkSync,readdirSync,
|
|
|
2
2
|
`)}function Au(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
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 Ou(){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,Iu,fi,Pu,le=ku(()=>{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,Iu=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);}},Pu=new fi;});var Za=mi((z0,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((q0,il)=>{var Qa=Za();il.exports=kd;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 Sd(r){return r.split("\\\\").join(el).split("\\{").join(tl).split("\\}").join(Vi).split("\\,").join(sl).split("\\.").join(nl)}function xd(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 kd(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Zs(Sd(r),true).map(xd)):[]}function Cd(r){return "{"+r+"}"}function Rd(r){return /^-?0\d/.test(r)}function Ed(r,e){return r<=e}function Id(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(Cd),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,_=Ed,v=f<h;v&&(b*=-1,_=Id);var k=d.some(Rd);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((Kv,Rc)=>{var kc=aa("fs"),Do=aa("path"),Cc=Do.join(__dirname,"path.txt");function ig(){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=ig();});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 Lu={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 Du(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=Du(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 Lu[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)+`
|
|
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,Iu=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);}},Pu=new fi;});var Za=mi((q0,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=kd;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 Sd(r){return r.split("\\\\").join(el).split("\\{").join(tl).split("\\}").join(Vi).split("\\,").join(sl).split("\\.").join(nl)}function xd(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 kd(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),Zs(Sd(r),true).map(xd)):[]}function Cd(r){return "{"+r+"}"}function Rd(r){return /^-?0\d/.test(r)}function Ed(r,e){return r<=e}function Id(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(Cd),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,_=Ed,v=f<h;v&&(b*=-1,_=Id);var k=d.some(Rd);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((Kv,Rc)=>{var kc=aa("fs"),Do=aa("path"),Cc=Do.join(__dirname,"path.txt");function ig(){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=ig();});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 Lu={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 Du(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 qn=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=Du(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 Lu[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(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.startsWith("mcp__"))return "summarized";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 Wu={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}},Hu={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={...Hu,...e};}async execute(e,t){let s=Date.now(),n=Wu[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)+`
|
|
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 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 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.startsWith("mcp__"))return "summarized";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 Wu={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}},Hu={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={...Hu,...e};}async execute(e,t){let s=Date.now(),n=Wu[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 Sn from'fs';import Sn__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
|
-
`)}},fa=new rt;async function
|
|
20
|
+
`)}},fa=new rt;async function qs(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
|
|
|
@@ -27,11 +27,11 @@ Configuration:
|
|
|
27
27
|
- File system access: ${r?.allowFileSystem!==false?"Enabled":"Disabled"}
|
|
28
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
|
|
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 qs(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
|
|
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 qs(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
|
|
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 qs(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 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
|
|
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 zs=join(homedir(),".neox","browser-profile");function Ci(){return zs}function Yn(){return existsSync(zs)||(mkdirSync(zs,{recursive:true}),g.info("CHROME",`Created browser profile directory: ${zs}`)),zs}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 Xu.launch(n);return g.info("CHROME","Chrome launched successfully"),i}le();var Zu=["xhr","fetch"],wa=["stylesheet","script","image","font","media"];function Qu(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__ || [];
|
|
@@ -349,7 +349,7 @@ Examples:
|
|
|
349
349
|
- "formatDate(timestamp)" - Call a function
|
|
350
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=[wp,vp,Tp,Sp,xp,kp,Cp,Rp,Ep,Ip,Mp,Ap,Pp],Ea=["editor"];function rr(){return Li.map(r=>({...r,capabilities:r.capabilities?Array.from(new Set([...r.capabilities,...Ea])):Ea}))}le();le();var Op=new Set([".git",".svn",".hg",".idea",".vscode",".vs",".fleet",".DS_Store","__MACOSX","Thumbs.db"]),Lp={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"}},Dp=new Set(["src","lib","app","core","api","test","tests","docs","doc","examples","scripts","config","configs"]);async function $p(r){let e={types:[],skipDirs:new Set(Op),skipPatterns:[],interestingDirs:new Set(Dp),descriptions:[]};try{let t=await Z__default.readdir(r),s=new Set(t);for(let[n,i]of Object.entries(Lp))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 Np(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:Fp(p.name,e),itemCount:m});}else {let m=Np(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 Fp(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 Up(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?` (${Up(n.size)})`:"";t.push(`${e}${o}[] ${n.name}${l}`);}}return t}async function jp(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):Gp(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
351
|
`)}catch(s){return JSON.stringify({error:s.message})}}function Gp(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 Bp(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 Wp="NEOX_WORKDIR";function Ma(){let r=process.env[Wp];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Hp(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
|
|
352
|
+
... [\u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u4F7F\u7528\u66F4\u5177\u4F53\u7684 directory \u53C2\u6570\u67E5\u770B\u5B50\u76EE\u5F55]`};function Bp(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 Wp="NEOX_WORKDIR";function Ma(){let r=process.env[Wp];return r&&r.trim()?Y__default.resolve(r):process.cwd()}function Hp(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 qp(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,7 +366,7 @@ 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=Hp(r),n=
|
|
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=Hp(r),n=qp(s);if(!(await Z__default.stat(s)).isDirectory())return `[x] \u4E0D\u662F\u76EE\u5F55: ${n}`;let o=await $p(s);if(e==="structure")return await jp(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')),Bp(p).join(`
|
|
370
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 Kp(){return Y__default.join(Gs.homedir(),".neox")}var Js=Kp(),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
371
|
\u274C Permission denied: Cannot write to config file`),console.error(` Location: ${Ni}`),console.error(`
|
|
372
372
|
Please check directory permissions or try:`),console.error(` sudo chown -R $USER "${Js}"
|
|
@@ -610,9 +610,9 @@ Example debugging workflow:
|
|
|
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 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
|
|
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 qa(r){return createHash("md5").update(r).digest("hex")}async function za(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 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
|
|
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 qi(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 zi(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=Td(t,s);return (t.length-n)/t.length}function Td(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
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
|
|
|
@@ -624,28 +624,28 @@ By default, this will terminate the debugged program. Set terminateDebuggee=fals
|
|
|
624
624
|
|
|
625
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
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=Ru(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 Md={"[: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,"\\$&"),Ad=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(Md))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 [Ad(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 Pd=new Set(["!","?","+","*","@"]),cl=r=>Pd.has(r),Od="(?!(?:^|/)\\.\\.?(?:$|/))",dr="(?!\\.)",Ld=new Set(["[","."]),Dd=new Set(["..","."]),$d=new Set("().*{}+?[]^$\\!"),Nd=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&&Dd.has(this.#n[0]))){let h=Ld,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?Od: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+=($d.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+=Nd(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)),Fd=/^\*+([^+@!?\*\[\(]*)$/,Ud=r=>e=>!e.startsWith(".")&&e.endsWith(r),jd=r=>e=>e.endsWith(r),Gd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),Bd=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Wd=/^\*+\.\*+$/,Hd=r=>!r.startsWith(".")&&r.includes("."),zd=r=>r!=="."&&r!==".."&&r.includes("."),qd=/^\.\*+$/,Jd=r=>r!=="."&&r!==".."&&r.startsWith("."),Kd=/^\*+$/,Vd=r=>r.length!==0&&!r.startsWith("."),Yd=r=>r.length!==0&&r!=="."&&r!=="..",Xd=/^\?+([^+@!?\*\[\(]*)?$/,Zd=([r,e=""])=>{let t=gl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Qd=([r,e=""])=>{let t=fl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},em=([r,e=""])=>{let t=fl([r]);return e?s=>t(s)&&s.endsWith(e):t},tm=([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:"/"}},sm=yl==="win32"?dl.win32.sep:dl.posix.sep;Ue.sep=sm;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var nm="[^/]",rm=nm+"*?",im="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",om="(?:(?!(?:\\/|^)\\.).)*?",am=(r,e={})=>t=>Ue(t,r,e);Ue.filter=am;var Ze=(r,e={})=>Object.assign({},r,e),lm=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=lm;var bl=(r,e={})=>(Qs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, hl.default)(r));Ue.braceExpand=bl;var cm=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=cm;var um=(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=um;var ml=/[?*]|[+@!]\(.*?\)|\[|\]/,pm=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(`
|
|
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=Ru(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 Md={"[: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,"\\$&"),Ad=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(Md))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 [Ad(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 Pd=new Set(["!","?","+","*","@"]),cl=r=>Pd.has(r),Od="(?!(?:^|/)\\.\\.?(?:$|/))",dr="(?!\\.)",Ld=new Set(["[","."]),Dd=new Set(["..","."]),$d=new Set("().*{}+?[]^$\\!"),Nd=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&&Dd.has(this.#n[0]))){let h=Ld,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?Od: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+=($d.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+=Nd(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)),Fd=/^\*+([^+@!?\*\[\(]*)$/,Ud=r=>e=>!e.startsWith(".")&&e.endsWith(r),jd=r=>e=>e.endsWith(r),Gd=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),Bd=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),Wd=/^\*+\.\*+$/,Hd=r=>!r.startsWith(".")&&r.includes("."),qd=r=>r!=="."&&r!==".."&&r.includes("."),zd=/^\.\*+$/,Jd=r=>r!=="."&&r!==".."&&r.startsWith("."),Kd=/^\*+$/,Vd=r=>r.length!==0&&!r.startsWith("."),Yd=r=>r.length!==0&&r!=="."&&r!=="..",Xd=/^\?+([^+@!?\*\[\(]*)?$/,Zd=([r,e=""])=>{let t=gl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},Qd=([r,e=""])=>{let t=fl([r]);return e?(e=e.toLowerCase(),s=>t(s)&&s.toLowerCase().endsWith(e)):t},em=([r,e=""])=>{let t=fl([r]);return e?s=>t(s)&&s.endsWith(e):t},tm=([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:"/"}},sm=yl==="win32"?dl.win32.sep:dl.posix.sep;Ue.sep=sm;var Ae=Symbol("globstar **");Ue.GLOBSTAR=Ae;var nm="[^/]",rm=nm+"*?",im="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",om="(?:(?!(?:\\/|^)\\.).)*?",am=(r,e={})=>t=>Ue(t,r,e);Ue.filter=am;var Ze=(r,e={})=>Object.assign({},r,e),lm=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=lm;var bl=(r,e={})=>(Qs(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, hl.default)(r));Ue.braceExpand=bl;var cm=(r,e={})=>new Ke(r,e).makeRe();Ue.makeRe=cm;var um=(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=um;var ml=/[?*]|[+@!]\(.*?\)|\[|\]/,pm=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 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(Kd))?n=t.dot?Yd:Vd:(s=e.match(Fd))?n=(t.nocase?t.dot?Bd:Gd:t.dot?jd:Ud)(s[1]):(s=e.match(Xd))?n=(t.nocase?t.dot?Qd:Zd:t.dot?em:tm)(s):(s=e.match(Wd))?n=t.dot?zd:Hd:(s=e.match(qd))&&(n=Jd);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?rm:t.dot?im:om,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"?pm(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 dm=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";dm(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},hm=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof Rl||gm(r)||fm(r)),gm=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Rl.Writable.prototype.pipe,fm=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),ym=r=>r(),bm=r=>r==="end"||r==="finish"||r==="prefinish",_m=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,wm=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);}},vm=r=>!!r.objectMode,Tm=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");vm(t)?(this[De]=true,this[at]=null):Tm(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:ym;if(!this[De]&&!Buffer.isBuffer(e)){if(wm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(_m(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(bm(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 hm}};var Am=realpathSync.native,ln={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Am,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,$m=r=>r.replace(/\//g,"\\").replace(Ol,"$1\\"),Nm=/[\\\/]/,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,Fm=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&Fm,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<)}calledReaddir(){return !!(this.#s&oo)}isENOENT(){return !!(this.#s<)}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<||(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<)===0)try{return this.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s<)===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=Nm;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=$m(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 Um=r=>r.length>=1,jm=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(!Um(e))throw new TypeError("empty pattern list");if(!jm(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 Gm=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=Gm}){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 Bm=(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=Bm(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 Hm=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||Hm,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 zm=Er,qm=Object.assign(Bl,{sync:Er}),Jm=Ir,Km=Object.assign(Hl,{sync:Ir}),Vm=Object.assign(Wl,{stream:Er,iterate:Ir}),xs=Object.assign(Gl,{glob:Gl,globSync:Wl,sync:Vm,globStream:Bl,stream:qm,globStreamSync:Er,streamSync:zm,globIterate:Hl,iterate:Km,globIterateSync:Ir,iterateSync:Jm,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(`
|
|
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(Kd))?n=t.dot?Yd:Vd:(s=e.match(Fd))?n=(t.nocase?t.dot?Bd:Gd:t.dot?jd:Ud)(s[1]):(s=e.match(Xd))?n=(t.nocase?t.dot?Qd:Zd:t.dot?em:tm)(s):(s=e.match(Wd))?n=t.dot?qd:Hd:(s=e.match(zd))&&(n=Jd);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?rm:t.dot?im:om,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"?pm(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 dm=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";dm(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},hm=r=>!!r&&typeof r=="object"&&(r instanceof Pt||r instanceof Rl||gm(r)||fm(r)),gm=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Rl.Writable.prototype.pipe,fm=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),ym=r=>r(),bm=r=>r==="end"||r==="finish"||r==="prefinish",_m=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,wm=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);}},vm=r=>!!r.objectMode,Tm=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");vm(t)?(this[De]=true,this[at]=null):Tm(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:ym;if(!this[De]&&!Buffer.isBuffer(e)){if(wm(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(_m(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(bm(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 hm}};var Am=realpathSync.native,ln={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:Am,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,$m=r=>r.replace(/\//g,"\\").replace(Ol,"$1\\"),Nm=/[\\\/]/,et=0,Ll=1,Dl=2,ht=4,$l=6,Nl=8,qt=10,Fl=12,Qe=15,an=~Qe,oo=16,El=32,cn=64,lt=128,wr=256,Tr=512,Il=cn|lt|Tr,Fm=1023,ao=r=>r.isFile()?Nl:r.isDirectory()?ht:r.isSymbolicLink()?qt: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&Fm,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&qt)===qt}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!==qt||this.#s&wr||this.#s<)}calledReaddir(){return !!(this.#s&oo)}isENOENT(){return !!(this.#s<)}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<||(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!==qt&&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<)===0)try{return this.#q(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#F(e.code);}}lstatSync(){if((this.#s<)===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.#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!==qt&&(this.#s|=cn);}#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&Il)return false;let e=Qe&this.#s;return e===et||e===ht||e===qt}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=Nm;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=$m(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 Um=r=>r.length>=1,jm=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(!Um(e))throw new TypeError("empty pattern list");if(!jm(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 Gm=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=Gm}){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 Bm=(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=Bm(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 Hm=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||Hm,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 qm=Er,zm=Object.assign(Bl,{sync:Er}),Jm=Ir,Km=Object.assign(Hl,{sync:Ir}),Vm=Object.assign(Wl,{stream:Er,iterate:Ir}),xs=Object.assign(Gl,{glob:Gl,globSync:Wl,sync:Vm,globStream:Bl,stream:zm,globStreamSync:Er,streamSync:qm,globIterate:Hl,iterate:Km,globIterateSync:Ir,iterateSync:Jm,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
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
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 Ym="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
|
|
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 Ym="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 za(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=qi(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:Ym,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=qi(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:qa(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 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=
|
|
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=zi(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=zi(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,zt={small:cs,large:1e3},ql=12e3,Xm=120,Ar=20,Zm=3,Qm=200,fo=200;function eh(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 th(r){return process.cwd()}function gt(r){let e=th();return Y.relative(e,r)||r}function zl(r,e){let t=Y.relative(r,e);return t===""?true:!t.startsWith("..")&&!Y.isAbsolute(t)}function sh(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${
|
|
640
|
-
- \u5927\u6587\u4EF6 (>${
|
|
639
|
+
- \u5C0F\u6587\u4EF6 (\u2264${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
|
|
640
|
+
- \u5927\u6587\u4EF6 (>${zt.large}\u884C): \u4F18\u5148\u7528 symbol/function/class \u5B9A\u4F4D
|
|
641
641
|
\u2713 readfile(path="big.ts", function="handleClick") - \u7CBE\u51C6\u5B9A\u4F4D\u51FD\u6570
|
|
642
642
|
\u2713 readfile(path="big.ts", class="UserService") - \u7CBE\u51C6\u5B9A\u4F4D\u7C7B
|
|
643
643
|
- \u4E2D\u7B49\u6587\u4EF6: pattern \u548C symbol \u5747\u53EF\uFF0C\u6309\u9700\u9009\u62E9`:`
|
|
644
644
|
\u{1F4D6} readfile \u7B56\u7565\u63D0\u793A:
|
|
645
645
|
- \u7D22\u5F15\u672A\u6784\u5EFA\uFF0C\u4F7F\u7528 pattern/grep \u5B9A\u4F4D
|
|
646
|
-
- \u5C0F\u6587\u4EF6 (\u2264${
|
|
646
|
+
- \u5C0F\u6587\u4EF6 (\u2264${zt.small}\u884C): \u9ED8\u8BA4 full \u8BFB\u53D6
|
|
647
647
|
- \u5927\u6587\u4EF6: \u5148\u7528 pattern/list_matches \u5B9A\u4F4D\uFF0C\u518D\u7528 anchor_lines/ranges \u6279\u91CF\u8BFB\u53D6
|
|
648
|
-
- \u{1F4A1} \u8FD0\u884C build_index() \u53EF\u4EE5\u542F\u7528\u7B26\u53F7\u5B9A\u4F4D\u529F\u80FD`}async function _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${
|
|
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${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
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:
|
|
@@ -688,11 +688,11 @@ 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: ${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: ${
|
|
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: ${ql})`}},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=eh(M),E=w===true,L=typeof x=="number"?Math.max(0,x):lr,N=typeof T=="number"&&T>0?Math.floor(T):ql,$=d||(E?Xm: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
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(Qm,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}`}),
|
|
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
|
|
695
|
-
`).length,I=0;for(let[j,
|
|
693
|
+
`)}let we=fo+12,Se=Math.max(5,Math.min(Qm,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}`}),q=[`\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&&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: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 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(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,q]of H.entries()){let ye=Le(pe.slice(q.start-1,q.end),q.start),fe=`${`# \u533A\u5757 ${j+1}: ${q.start}-${q.end}`}
|
|
696
696
|
${ye}`;if(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
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
698
|
`).map(we=>{let Se=we.match(/^\s*\d+\s*│\s?(.*)$/);return Se?Se[1]:we}).join(`
|
|
@@ -755,7 +755,7 @@ get_definitions(query="UserService") \u2192 \u67E5\u627E\u5B9A\u4E49
|
|
|
755
755
|
get_definitions(symbol="handleLogin", kind="function")
|
|
756
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(!
|
|
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(!zl(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,7 +768,7 @@ 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(!
|
|
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(!zl(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:sh(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
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
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
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
|
|
@@ -798,19 +798,19 @@ Rules:
|
|
|
798
798
|
|
|
799
799
|
\u26A0 \u547D\u4EE4\u88AB\u7528\u6237\u4E2D\u65AD
|
|
800
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[uh];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 wh(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var vh={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(
|
|
802
|
-
`).length;return JSON.stringify(
|
|
803
|
-
`).length,u=l?"updated":"created";return JSON.stringify(
|
|
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 wh(r){let e=r.trim().split(/\s+/).filter(Boolean);return {command:e[0]||"",args:e.slice(1)}}var vh={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=Co.get(n),a=Date.now();if(o&&o.checksum===i&&o.success&&a-o.timestamp<mh){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"),Co.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 Co.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 Th(r){let e=r.includes(`\r
|
|
804
804
|
`)?`\r
|
|
805
805
|
`:`
|
|
806
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 Sh=2e5;function xh(r,e){let t=r.length,s=e.length;if(t*s>Sh)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 kh(r,e){if(r.length===0&&e.length===0)return [];let t=xh(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 Ch={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(
|
|
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}=Th(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=Ro(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=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(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=kh(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:[],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(z("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:x,old_line_count:W.length,new_line_count:F.length}}}))}catch(c){return JSON.stringify(
|
|
813
|
+
`),start_line:x,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."}))}}},Rh={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
|
|
@@ -828,10 +828,10 @@ For searching file CONTENTS, use search instead.`,parameters:{type:"object",prop
|
|
|
828
828
|
`)}catch(s){return `\u2717 \u641C\u7D22\u5931\u8D25: ${s.message}`}}},Eh={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}`}}},Ih={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(
|
|
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(
|
|
833
|
-
`).trim();return JSON.stringify(
|
|
834
|
-
`).trim();return JSON.stringify(
|
|
831
|
+
`)}catch(t){return `\u2717 \u5217\u51FA\u76EE\u5F55\u5931\u8D25: ${t.message}`}}},Ih={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."}))}}},Mh={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(!St(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}))}}},Ah={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(!St(n)||!St(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}))}}},Ph={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")>ac)return JSON.stringify(z("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(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 Vt(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(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(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(()=>{});}}},Oh=process.env.NEOX_SANDBOX==="on";var Lh={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)
|
|
@@ -963,13 +963,13 @@ ${u.stderr}
|
|
|
963
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"))}},Nh={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
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||""))}},Fh={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
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||""))}},Uh={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||""))}},jh={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(
|
|
967
|
-
`).trim();return JSON.stringify(
|
|
968
|
-
`).trim();return JSON.stringify(
|
|
969
|
-
`).trim();return JSON.stringify(
|
|
970
|
-
`).trim();return JSON.stringify(
|
|
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||""))}},jh={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(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}}))}},Gh={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(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 Bh(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 Wh(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 Bh(s),o=t.command,a=[];if(o){let l=wh(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
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=Wh(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 Hh={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)}},
|
|
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 Hh={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)}},qh={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)}},Jh={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(`
|
|
@@ -991,16 +991,16 @@ 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&&!Sn__default.existsSync(R)){let I=W,j=null;for(;;){let
|
|
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 q=Y__default.resolve(I,o);if(Sn__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 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=Vh({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 Kh();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
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||"**/*",
|
|
997
|
-
`),{metadata:{mode:"files",strategy:X?"rg":"glob",regex:T.some(oe=>oe.regex),case_insensitive:u,path:F,resolved_from:O,files:
|
|
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||"**/*",ze=w?oe:oe.replace("**/","");return (await uc(ze,{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 ze=oe.regex?oe.pattern:rc(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(xe=>({op:xe.query.op,hit:xe.regex.test(ze)})),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)&&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:rc(I.pattern),q=I.caseInsensitive?"i":"";return new RegExp(j,q)}),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 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),Eo.forEach(_e=>q.push("-g",_e)),q.push("--",j.pattern,R);let ye=`${I} ${q.join(" ")}`;Te.push(ye);let ge="",fe=0,oe="";try{let _e=await Ne(I,q,He(),{signal:y});ge=_e.stdout,oe=_e.stderr||"",fe=_e.exitCode;}catch(_e){if(_e?.name==="AbortError"||y?.aborted)throw _e;oe=_e?.message||_e?.stderr||String(_e),fe=_e?.exitCode||2;}if(fe!==0&&fe!==1){let _e=oe?`
|
|
998
998
|
Error: ${oe}`:"",ce=`
|
|
999
|
-
Command: ${I} ${
|
|
1000
|
-
`)){if(b(),
|
|
1001
|
-
... \u8FD8\u6709\u66F4\u591A\u5339\u914D (\u5DF2\u8FBE ${d} \u4E0A\u9650)`);break}let ye=Re(
|
|
1002
|
-
\u25B8 [${ge}] ${ye} (${
|
|
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}))}}},Xh={name:Dr.name,description:Dr.description,parameters:Dr.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return sc(r)}},dc=[vh,Ch,Mh,Ah,Ph,Rh,Eh,Ih,$h,Nh,Fh,Uh,jh,Gh,Hh,zh,
|
|
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 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 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&&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: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,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,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: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}))}}},Xh={name:Dr.name,description:Dr.description,parameters:Dr.parameters,permission:{category:"read",allowInAskMode:true},async function(r){return sc(r)}},dc=[vh,Ch,Mh,Ah,Ph,Rh,Eh,Ih,$h,Nh,Fh,Uh,jh,Gh,Hh,qh,zh,Lh,Dh,Aa,Jh,Yh,Si,xi,ki,Ua,Xh];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=hh(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 Zh(r){let e=r.match(/Error\s+(?:code\s+)?(\d{3})/i);if(e)return e[1];let t=r.match(/(\d{3}):\s*([^<\n]+)/);return t?t[1]:null}function Qh(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 eg(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 tg(r){let e=r.match(/^data:\s*(\{.*\})/m);return e?e[1]:null}function Yt(r,e){let t=tg(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=Zh(r)||String(e||"UNKNOWN"),a=Qh(r)||"Server error",l=eg(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 sg(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 ng(r){return [/quota.*exceeded/i,/usage.*limit/i,/rate.*limit/i,/insufficient.*quota/i,/billing/i].some(t=>t.test(r))}function rg(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?rg(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
1004
|
`+p.detail);}let u=a||sg(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
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}):ng(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 cg=fileURLToPath(import.meta.url),No=dirname(cg),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
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(`
|
|
@@ -1010,7 +1010,7 @@ Command: ${I} ${z.join(" ")}`;throw new Error(`ripgrep failed (exit code ${fe})$
|
|
|
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 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
|
|
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 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 hg={initialDelayMs:3e3,backoffFactor:2.5,maxDelayMs:6e4,jitterRange:.3},gg={initialDelayMs:1e3,backoffFactor:1.5,maxDelayMs:1e4,jitterRange:.2};function fg(r,e){if(e!==void 0&&e>0){let t=1+Math.random()*.2;return Math.floor(e*t)}return jo(r,hg)}function Rn(r,e,t){return r==="retryable_rate_limit"?fg(e,t):r==="retryable_stream"||r==="retryable_network"?jo(e,gg):Dt(t,e)}le();le();var yg=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"},bg={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
|
|
@@ -1414,12 +1414,12 @@ 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 In);Nt.register(new An);Nt.register(new Pn);function Wo(r){return Nt.getStrategy(r)}var $c=2e4,Cg=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
|
|
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,Cg=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 qr(){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 qr();return e()}function Rg(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 Eg=jc("NEOX_STREAM_FIRST_CHUNK_TIMEOUT_MS",6e4),Ig=jc("NEOX_STREAM_CHUNK_TIMEOUT_MS",18e4),Mg=process.env.NEOX_STREAM_WATCHDOG_DISABLED==="1";function Uc(r,e=Cg){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 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(Mg){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?Ig:Eg,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Rg(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}
|
|
1422
|
+
`;return l+p+c}var zr=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(Mg){for await(let o of e)yield o;return}let s=e[Symbol.asyncIterator](),n=t?new Promise((o,a)=>{t.aborted?a(qr()):t.addEventListener("abort",()=>a(qr()),{once:true});}):null,i=false;for(;;){if(t?.aborted){if(s.return)try{await s.return();}catch{}throw qr()}let o=i?Ig:Eg,a=null,l=new Promise((c,u)=>{a=setTimeout(()=>{u(Rg(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 (${qe(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 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=>!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},q=await Xt.runToolOutputGuardrails(this.toolOutputGuardrails,{context:this.runContext,tool_context:j,agent_name:this.agentName,tool:I,output:S.output});q.should_use_output||(H=q.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),q=S.name,ye=Oc(q,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 ${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 As(N),d--;continue}let B=Ur(M),E=M.message;B&&!E.includes(B)&&(E=`${E}
|
|
1423
1423
|
|
|
1424
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
|
|
|
@@ -1552,16 +1552,16 @@ 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
|
|
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 qc(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
|
|
1560
|
+
`;return l+p+c}function zc(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=Gg.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 ${qe(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 ${qe(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}}),zc(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=qc(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
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,
|
|
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,zc(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=
|
|
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=qc(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}
|
|
@@ -1627,15 +1627,15 @@ Tool results are returned via tool_result messages.`}supportsExtendedThinking(e)
|
|
|
1627
1627
|
\u2026[${s-l.length-c.length} chars truncated, total ${t} lines]\u2026
|
|
1628
1628
|
|
|
1629
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
|
|
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?
|
|
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:
|
|
1633
|
-
`+n})):(a.push({type:"text",text:
|
|
1630
|
+
...[truncated ${s.length-e} chars]`:s:"No headers"}var qo="You are Claude Code, Anthropic's official CLI for Claude.",Xg=["claude-code-20250219","interleaved-thinking-2025-05-14"],Yr="2023-06-01",Xr=64,Zg=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"},zo={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||Xg,this.systemPromptPrefix=e.systemPromptPrefix||(this.isProxyMode?qo:null),this.sanitizeToolsForProxy=false,this.disableCaching=e.disableCaching||false,this.client=Gg.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${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 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?zo[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: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 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:qo}),n&&a.push({type:"text",text:`
|
|
1633
|
+
`+n})):(a.push({type:"text",text:qo,cache_control:{type:"ephemeral"}}),n&&a.push({type:"text",text:`
|
|
1634
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>Vg&&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
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,Zg)}}buildMetadata(e){let t={...e};return t.user_id?t.user_id=this.sanitizeUserId(t.user_id):t.user_id=this.claudeCodeUserId,t}shouldEnableThinking(e,t){return t.thinking?.type==="enabled"?true:t.thinking?.type==="disabled"?false:!!(e.endsWith("-thinking")||e.includes("opus-4-5")||e.includes("opus-4.5"))}normalizeModelName(e){return e.endsWith("-thinking")?e.replace(/-thinking$/,""):e}convertMessages(e,t){let s=this.normalizeMessages(e),n=[],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=Yg(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
|
|
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=Yg(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?zo[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?zo[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
|
|
@@ -1691,7 +1691,7 @@ Your primary responsibilities:
|
|
|
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=xt(y),_=Dt(b,d,this.retryConfig);console.log(`[Doubao] Stream failed (${f.code}), reconnecting in ${
|
|
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 ${qe(_)} (${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
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=lf(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(`
|
|
@@ -1786,7 +1786,7 @@ ${s}`),s.trim()}extractImageUrls(e){return e?.attachments?.length?e.attachments.
|
|
|
1786
1786
|
\u2502 \u603B\u8BA1: ${x(W.totalTokens)}`,R+=`
|
|
1787
1787
|
\u2514\u2500 \u8282\u7701\uFF1A`,R+=`
|
|
1788
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 wf="ark.cn-beijing.volces.com";function vf(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(wf)}function Tf(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function Sf(r){let e=r?.getProvider?.();return e instanceof Ds?e:void 0}function xf(r){let e=r?.getProvider?.();return e instanceof $s?e:void 0}function kf(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 pu(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=Tf(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=Sf(h),c&&vf(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=xf(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=kf({model:t,baseUrl:o,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:p});return {llmProvider:a,controls:d}}function du(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 mu(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 hu(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??hu(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}=pu({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=du({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:mu({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 gu(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 gu({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 Cf=[".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"],fu={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:Cf};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={...fu,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=yu();}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=yu(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=bu.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(`
|
|
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 wf="ark.cn-beijing.volces.com";function vf(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(wf)}function Tf(r){let e=r?.getProvider?.();return e instanceof Ct?e:void 0}function Sf(r){let e=r?.getProvider?.();return e instanceof Ds?e:void 0}function xf(r){let e=r?.getProvider?.();return e instanceof $s?e:void 0}function kf(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 pu(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=Tf(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=Sf(h),c&&vf(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=xf(h);}else throw new Error(`Unsupported provider protocol: ${n}`);let d=kf({model:t,baseUrl:o,openaiProvider:l,anthropicProvider:c,doubaoProvider:u,geminiProvider:p});return {llmProvider:a,controls:d}}function du(r){return new zr({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 mu(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 hu(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??hu(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}=pu({provider:t,model:s.model,sessionId:e}),M=s.compatProfile??null,B=M?new qn(M):void 0,E=p??await Ao(n,R),L=h??{maxIterations:0,temperature:.7},N=du({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:mu({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 gu(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 gu({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 Cf=[".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"],fu={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:Cf};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={...fu,...e},this.workspacePath="",this.shadowDir="",this.shadowGitDir="",this.git=yu();}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=yu(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=bu.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}
|