@mk-co/neox-cli 2.0.31 → 2.0.34

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 CHANGED
@@ -210,8 +210,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
210
210
  `);let e=performance.now(),{output:t,outputHeight:n,staticOutput:s}=qg(this.rootNode,this.isScreenReaderEnabled),o=performance.now()-e;rn.env.CLI_DEBUG==="1"&&o>100&&rn.stderr.write(`[INK_RENDER] \u26A0\uFE0F Slow render: ${o.toFixed(1)}ms, outputHeight=${n}
211
211
  `),this.options.onRender?.({renderTime:o});let i=s&&s!==`
212
212
  `;if(this.options.debug){i&&this.options.stdout.write(s),t!==this.lastOutput&&(this.options.stdout.write(t),this.lastOutput=t,this.lastOutputHeight=n);return}if(wr){i&&this.options.stdout.write(s),this.lastOutput=t,this.lastOutputHeight=n;return}if(this.isScreenReaderEnabled){if(i){let c=this.lastOutputHeight>0?Mn.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(c+s),this.lastOutputHeight=0;}if(t===this.lastOutput&&!i)return;let a=this.options.stdout.columns||80,l=Ux(t,a,{trim:false,hard:true});if(i)this.options.stdout.write(l);else {let c=this.lastOutputHeight>0?Mn.eraseLines(this.lastOutputHeight):"";this.options.stdout.write(c+l);}this.lastOutput=t,this.lastOutputHeight=l===""?0:l.split(`
213
- `).length;return}if(i){this.lastOutputHeight>0&&this.options.stdout.write(Mn.eraseLines(this.lastOutputHeight)),this.log.sync(""),this.options.stdout.write(s);let a=t,l=n;setImmediate(()=>{this.isUnmounted||(this.options.stdout.write(a+`
214
- `),this.log.sync(a),this.lastOutputHeight=l);}),this.lastOutput=t;return}else t!==this.lastOutput&&this.throttledLog(t);this.lastOutput=t,this.lastOutputHeight=n,rn.env.NEOX_INK_DEBUG==="1"&&rn.stderr.write(`[INK_RENDER] \u2705 onRender completed
213
+ `).length;return}if(i){this.lastOutputHeight>0&&this.options.stdout.write(Mn.eraseLines(this.lastOutputHeight)),this.log.sync(""),this.options.stdout.write(s),this.log(t),this.lastOutput=t,this.lastOutputHeight=n;return}else t!==this.lastOutput&&this.throttledLog(t);this.lastOutput=t,this.lastOutputHeight=n,rn.env.NEOX_INK_DEBUG==="1"&&rn.stderr.write(`[INK_RENDER] \u2705 onRender completed
215
214
  `);};render(e){let t=E.createElement(us.Provider,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},E.createElement($o,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount,onResize:this.handleResizeFromApp},e));En.updateContainerSync(t,this.container,null,Ch),En.flushSyncWork();}writeToStdout(e){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(e+this.lastOutput);return}if(wr){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput);}}writeToStderr(e){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.lastOutput);return}if(wr){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput);}}unmount(e){this.isUnmounted||(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),wr?this.options.stdout.write(this.lastOutput+`
216
215
  `):this.options.debug||this.log.done(),this.isUnmounted=true,En.updateContainerSync(null,this.container,null,Ch),En.flushSyncWork(),yr.delete(this.options.stdout),e instanceof Error?this.rejectExitPromise(e):this.resolveExitPromise());}async waitUntilExit(){return this.exitPromise||=new Promise((e,t)=>{this.resolveExitPromise=e,this.rejectExitPromise=t;}),this.exitPromise}clear(){!wr&&!this.options.debug&&this.log.clear();}patchConsole(){this.options.debug||(this.restoreConsole=hT((e,t)=>{e==="stdout"&&this.writeToStdout(t),e==="stderr"&&(t.startsWith("The above error occurred")||this.writeToStderr(t));}));}};var CT=(r,e)=>{let t={stdout:rn.stdout,stdin:rn.stdin,stderr:rn.stderr,debug:false,exitOnCtrlC:true,patchConsole:true,maxFps:30,incrementalRendering:true,...xT(e)},n=wT(t.stdout,()=>new Oo(t));return n.render(r),{rerender:n.render,unmount(){n.unmount();},waitUntilExit:n.waitUntilExit,cleanup:()=>yr.delete(t.stdout),clear:n.clear}},Tr=CT,xT=(r={})=>r instanceof Stream?{stdout:r,stdin:rn.stdin}:r,wT=(r,e)=>{let t=yr.get(r);return t||(t=e(),yr.set(r,t)),t};function Fa(r){let{items:e,children:t,style:n}=r,[s,o]=useState(0),i=e.length<s?0:s,a=useMemo(()=>e.slice(i),[i,e]);useLayoutEffect(()=>{e.length<s?o(0):e.length>s&&o(e.length);},[e.length,s]);let l=useMemo(()=>a.map((u,d)=>t(u,i+d)),[a,t,i]),c=useMemo(()=>({position:"absolute",flexDirection:"column",...n}),[n]);return E.createElement("ink-box",{internal_static:true,style:c},l)}var IT=/^(?:\x1b)([a-zA-Z0-9])$/,ET=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,xh={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},wh=[...Object.values(xh),"backspace"],AT=r=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(r),MT=r=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(r),PT=(r="")=>{let e;Buffer$1.isBuffer(r)?r[0]>127&&r[1]===void 0?(r[0]-=128,r="\x1B"+String(r)):r=String(r):r!==void 0&&typeof r!="string"?r=String(r):r||(r="");let t={name:"",ctrl:false,meta:false,shift:false,option:false,sequence:r,raw:r};if(t.sequence=t.sequence||r||t.name,r==="\r")t.raw=void 0,t.name="return";else if(r===`
217
216
  `)t.name="enter";else if(r===" ")t.name="tab";else if(r==="\b"||r==="\x1B\b")t.name="backspace",t.meta=r.charAt(0)==="\x1B";else if(r==="\x7F"||r==="\x1B\x7F")t.name="delete",t.meta=r.charAt(0)==="\x1B";else if(r==="\x1B"||r==="\x1B\x1B")t.name="escape",t.meta=r.length===2;else if(r===" "||r==="\x1B ")t.name="space",t.meta=r.length===2;else if(r.length===1&&r<="")t.name=String.fromCharCode(r.charCodeAt(0)+97-1),t.ctrl=true;else if(r.length===1&&r>="0"&&r<="9")t.name="number";else if(r.length===1&&r>="a"&&r<="z")t.name=r;else if(r.length===1&&r>="A"&&r<="Z")t.name=r.toLowerCase(),t.shift=true;else if(e=IT.exec(r))t.meta=true,t.shift=/^[A-Z]$/.test(e[1]);else if(e=ET.exec(r)){let n=[...r];n[0]==="\x1B"&&n[1]==="\x1B"&&(t.option=true);let s=[e[1],e[2],e[4],e[6]].filter(Boolean).join(""),o=(e[3]||e[5]||1)-1;t.ctrl=!!(o&4),t.meta=!!(o&10),t.shift=!!(o&1),t.code=s,t.name=xh[s],t.shift=AT(s)||t.shift,t.ctrl=MT(s)||t.ctrl;}return t},Th=PT;var DT=()=>useContext(br),Ua=DT;re();var NT=(r,e={})=>{let{stdin:t,setRawMode:n,internal_exitOnCtrlC:s,internal_eventEmitter:o}=Ua();useEffect(()=>{if(e.isActive!==false)return ()=>{}},[e.isActive,n]),useEffect(()=>{if(e.isActive===false)return;let i=a=>{let l=Date.now();ae("INPUT",`>>> handleData START, data.length=${a.length}`);let c=a==="\r"||a===`
@@ -375,7 +374,7 @@ ${i}`}],{model:t.model,temperature:.2});return Ce(a.choices[0]?.message?.content
375
374
  `),a=i.length,l=Math.max(1,n),c=Math.min(l+s-1,a),u=i.slice(l-1,c);return {success:true,path:t,totalLines:a,startLine:l,endLine:c,content:_t(u,l),truncated:c<a,strategy:"chunk"}}async readFull(e,t,n){let s=await Ee.readFile(e,"utf-8"),o=Lr(s).split(`
376
375
  `),i=o.length,a=Math.min(i,n),l=o.slice(0,a);return {success:true,path:t,totalLines:i,startLine:1,endLine:a,content:_t(l,1),truncated:a<i,strategy:"full"}}buildSymbolPattern(e,t,n){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o={function:`(function|async\\s+function|const|let|var)\\s+${s}\\s*[=(<]`,class:`class\\s+${s}(\\s+extends|\\s+implements|\\s*\\{|\\s*$)`,interface:`interface\\s+${s}(\\s+extends|\\s*\\{|\\s*$)`,method:n?`(${s}|${n}\\.${s})\\s*\\(`:`${s}\\s*\\(`,variable:`(const|let|var)\\s+${s}\\s*[=:]`,type:`type\\s+${s}\\s*[=<]`,enum:`enum\\s+${s}\\s*\\{`,constant:`(const|final|static\\s+final)\\s+[A-Z_]+\\s*${s}`};return t&&o[t]?o[t]:`(function|class|interface|type|enum|const|let|var|def|fn|func)\\s+${s}|${s}\\s*(=|\\()`}resolvePath(e){return he.isAbsolute(e)?e:he.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 fd(r){return new Ya(r)}var hf=wg(af());var Jo=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var CS={"[: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]},Vo=r=>r.replace(/[[\]\\-]/g,"\\$&"),xS=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),lf=r=>r.join(""),cf=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let n=[],s=[],o=t+1,i=false,a=false,l=false,c=false,u=t,d="";e:for(;o<r.length;){let f=r.charAt(o);if((f==="!"||f==="^")&&o===t+1){c=true,o++;continue}if(f==="]"&&i&&!l){u=o+1;break}if(i=true,f==="\\"&&!l){l=true,o++;continue}if(f==="["&&!l){for(let[v,[b,C,w]]of Object.entries(CS))if(r.startsWith(v,o)){if(d)return ["$.",false,r.length-t,true];o+=v.length,w?s.push(b):n.push(b),a=a||C;continue e}}if(l=false,d){f>d?n.push(Vo(d)+"-"+Vo(f)):f===d&&n.push(Vo(f)),d="",o++;continue}if(r.startsWith("-]",o+1)){n.push(Vo(f+"-")),o+=2;continue}if(r.startsWith("-",o+1)){d=f,o+=2;continue}n.push(Vo(f)),o++;}if(u<o)return ["",false,0,false];if(!n.length&&!s.length)return ["$.",false,r.length-t,true];if(s.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let f=n[0].length===2?n[0].slice(-1):n[0];return [xS(f),false,u-t,false]}let m="["+(c?"^":"")+lf(n)+"]",g="["+(c?"":"^")+lf(s)+"]";return [n.length&&s.length?"("+m+"|"+g+")":n.length?m:g,a,u-t,true]};var yn=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var wS=new Set(["!","?","+","*","@"]),uf=r=>wS.has(r),TS="(?!(?:^|/)\\.\\.?(?:$|/))",Qa="(?!\\.)",SS=new Set(["[","."]),kS=new Set(["..","."]),_S=new Set("().*{}+?[]^$\\!"),IS=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),vd="[^/]",df=vd+"*?",pf=vd+"+?",$r=class r{type;#e;#t;#o=false;#s=[];#i;#C;#c;#d=false;#a;#l;#r=false;constructor(e,t,n={}){this.type=e,e&&(this.#t=true),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#d&&this.#c.push(this),this.#C=this.#i?this.#i.#s.length:0;}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#s)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=true;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#s.map(e=>String(e)).join("|")+")":this.#l=this.#s.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#d)return this;this.toString(),this.#d=true;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,n=t.#i;for(;n;){for(let s=t.#C+1;!n.type&&s<n.#s.length;s++)for(let o of e.#s){if(typeof o=="string")throw new Error("string part in extglob AST??");o.copyIn(n.#s[s]);}t=n,n=t.#i;}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#i===this))throw new Error("invalid part: "+t);this.#s.push(t);}}toJSON(){let e=this.type===null?this.#s.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#s.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#d&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return true;if(!this.#i?.isStart())return false;if(this.#C===0)return true;let e=this.#i;for(let t=0;t<this.#C;t++){let n=e.#s[t];if(!(n instanceof r&&n.type==="!"))return false}return true}isEnd(){if(this.#e===this||this.#i?.type==="!")return true;if(!this.#i?.isEnd())return false;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#s.length:0;return this.#C===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 n of this.#s)t.copyIn(n);return t}static#y(e,t,n,s){let o=false,i=false,a=-1,l=false;if(t.type===null){let g=n,h="";for(;g<e.length;){let f=e.charAt(g++);if(o||f==="\\"){o=!o,h+=f;continue}if(i){g===a+1?(f==="^"||f==="!")&&(l=true):f==="]"&&!(g===a+2&&l)&&(i=false),h+=f;continue}else if(f==="["){i=true,a=g,l=false,h+=f;continue}if(!s.noext&&uf(f)&&e.charAt(g)==="("){t.push(h),h="";let v=new r(f,t);g=r.#y(e,v,g,s),t.push(v);continue}h+=f;}return t.push(h),g}let c=n+1,u=new r(null,t),d=[],m="";for(;c<e.length;){let g=e.charAt(c++);if(o||g==="\\"){o=!o,m+=g;continue}if(i){c===a+1?(g==="^"||g==="!")&&(l=true):g==="]"&&!(c===a+2&&l)&&(i=false),m+=g;continue}else if(g==="["){i=true,a=c,l=false,m+=g;continue}if(uf(g)&&e.charAt(c)==="("){u.push(m),m="";let h=new r(g,u);u.push(h),c=r.#y(e,h,c,s);continue}if(g==="|"){u.push(m),m="",d.push(u),u=new r(null,t);continue}if(g===")")return m===""&&t.#s.length===0&&(t.#r=true),u.push(m),m="",t.push(...d,u),c;m+=g;}return t.type=null,t.#t=void 0,t.#s=[e.substring(n-1)],c}static fromGlob(e,t={}){let n=new r(null,void 0,t);return r.#y(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,s,o]=this.toRegExpSource();if(!(s||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(o?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#s.map(g=>{let[h,f,v,b]=typeof g=="string"?r.#p(g,this.#t,l):g.toRegExpSource(e);return this.#t=this.#t||v,this.#o=this.#o||b,h}).join(""),u="";if(this.isStart()&&typeof this.#s[0]=="string"&&!(this.#s.length===1&&kS.has(this.#s[0]))){let h=SS,f=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),v=!t&&!e&&h.has(c.charAt(0));u=f?TS:v?Qa:"";}let d="";return this.isEnd()&&this.#e.#d&&this.#i?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,yn(c),this.#t=!!this.#t,this.#o]}let n=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:",o=this.#m(t);if(this.isStart()&&this.isEnd()&&!o&&this.type!=="!"){let l=this.toString();return this.#s=[l],this.type=null,this.#t=void 0,[l,yn(this.toString()),false,false]}let i=!n||e||t||!Qa?"":this.#m(true);i===o&&(i=""),i&&(o=`(?:${o})(?:${i})*?`);let a="";if(this.type==="!"&&this.#r)a=(this.isStart()&&!t?Qa:"")+pf;else {let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Qa:"")+df+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;a=s+o+l;}return [a,yn(o),this.#t=!!this.#t,this.#o]}#m(e){return this.#s.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[n,s,o,i]=t.toRegExpSource(e);return this.#o=this.#o||i,n}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#p(e,t,n=false){let s=false,o="",i=false;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(s){s=false,o+=(_S.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?o+="\\\\":s=true;continue}if(l==="["){let[c,u,d,m]=cf(e,a);if(d){o+=c,i=i||u,a+=d-1,t=t||m;continue}}if(l==="*"){n&&e==="*"?o+=pf:o+=df,t=true;continue}if(l==="?"){o+=vd,t=true;continue}o+=IS(l);}return [o,yn(e),!!t,i]}};var Or=(r,{windowsPathsNoEscape:e=false}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var Dt=(r,e,t={})=>(Jo(e),!t.nocomment&&e.charAt(0)==="#"?false:new Yt(e,t).match(r)),ES=/^\*+([^+@!?\*\[\(]*)$/,AS=r=>e=>!e.startsWith(".")&&e.endsWith(r),MS=r=>e=>e.endsWith(r),PS=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),RS=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),DS=/^\*+\.\*+$/,NS=r=>!r.startsWith(".")&&r.includes("."),LS=r=>r!=="."&&r!==".."&&r.includes("."),$S=/^\.\*+$/,OS=r=>r!=="."&&r!==".."&&r.startsWith("."),BS=/^\*+$/,FS=r=>r.length!==0&&!r.startsWith("."),US=r=>r.length!==0&&r!=="."&&r!=="..",GS=/^\?+([^+@!?\*\[\(]*)?$/,jS=([r,e=""])=>{let t=ff([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},WS=([r,e=""])=>{let t=yf([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},HS=([r,e=""])=>{let t=yf([r]);return e?n=>t(n)&&n.endsWith(e):t},zS=([r,e=""])=>{let t=ff([r]);return e?n=>t(n)&&n.endsWith(e):t},ff=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},yf=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},bf=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",mf={win32:{sep:"\\"},posix:{sep:"/"}},qS=bf==="win32"?mf.win32.sep:mf.posix.sep;Dt.sep=qS;var yt=Symbol("globstar **");Dt.GLOBSTAR=yt;var KS="[^/]",JS=KS+"*?",VS="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",YS="(?:(?!(?:\\/|^)\\.).)*?",XS=(r,e={})=>t=>Dt(t,r,e);Dt.filter=XS;var ln=(r,e={})=>Object.assign({},r,e),QS=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return Dt;let e=Dt;return Object.assign((n,s,o={})=>e(n,s,ln(r,o)),{Minimatch:class extends e.Minimatch{constructor(s,o={}){super(s,ln(r,o));}static defaults(s){return e.defaults(ln(r,s)).Minimatch}},AST:class extends e.AST{constructor(s,o,i={}){super(s,o,ln(r,i));}static fromGlob(s,o={}){return e.AST.fromGlob(s,ln(r,o))}},unescape:(n,s={})=>e.unescape(n,ln(r,s)),escape:(n,s={})=>e.escape(n,ln(r,s)),filter:(n,s={})=>e.filter(n,ln(r,s)),defaults:n=>e.defaults(ln(r,n)),makeRe:(n,s={})=>e.makeRe(n,ln(r,s)),braceExpand:(n,s={})=>e.braceExpand(n,ln(r,s)),match:(n,s,o={})=>e.match(n,s,ln(r,o)),sep:e.sep,GLOBSTAR:yt})};Dt.defaults=QS;var vf=(r,e={})=>(Jo(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0, hf.default)(r));Dt.braceExpand=vf;var ZS=(r,e={})=>new Yt(r,e).makeRe();Dt.makeRe=ZS;var ek=(r,e,t={})=>{let n=new Yt(e,t);return r=r.filter(s=>n.match(s)),n.options.nonull&&!r.length&&r.push(e),r};Dt.match=ek;var gf=/[?*]|[+@!]\(.*?\)|\[|\]/,tk=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Yt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){Jo(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||bf,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===false,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=false,this.nonegate=!!t.nonegate,this.comment=false,this.empty=false,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make();}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return true;for(let e of this.set)for(let t of e)if(typeof t!="string")return true;return false}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=true;return}if(!e){this.empty=true;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...o)=>console.error(...o)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(o=>this.slashSplit(o));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let s=this.globParts.map((o,i,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=o[0]===""&&o[1]===""&&(o[2]==="?"||!gf.test(o[2]))&&!gf.test(o[3]),c=/^[a-z]:/i.test(o[0]);if(l)return [...o.slice(0,4),...o.slice(4).map(u=>this.parse(u))];if(c)return [o[0],...o.slice(1).map(u=>this.parse(u))]}return o.map(l=>this.parse(l))});if(this.debug(this.pattern,s),this.set=s.filter(o=>o.indexOf(false)===-1),this.isWindows)for(let o=0;o<this.set.length;o++){let i=this.set[o];i[0]===""&&i[1]===""&&this.globParts[o][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?");}this.debug(this.pattern,this.set);}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let s=0;s<e[n].length;s++)e[n][s]==="**"&&(e[n][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let n=-1;for(;(n=t.indexOf("**",n+1))!==-1;){let s=n;for(;t[s+1]==="**";)s++;s!==n&&t.splice(n,s-n);}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((n,s)=>{let o=n[n.length-1];return s==="**"&&o==="**"?n:s===".."&&o&&o!==".."&&o!=="."&&o!=="**"?(n.pop(),n):(n.push(s),n)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=false;do{if(t=false,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let o=e[s];s===1&&o===""&&e[0]===""||(o==="."||o==="")&&(t=true,e.splice(s,1),s--);}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=true,e.pop());}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let s=e[n-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=true,e.splice(n-1,2),n-=2);}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=false;do{t=false;for(let n of e){let s=-1;for(;(s=n.indexOf("**",s+1))!==-1;){let i=s;for(;n[i+1]==="**";)i++;i>s&&n.splice(s+1,i-s);let a=n[s+1],l=n[s+2],c=n[s+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=true,n.splice(s,1);let u=n.slice(0);u[s]="**",e.push(u),s--;}if(!this.preserveMultipleSlashes){for(let i=1;i<n.length-1;i++){let a=n[i];i===1&&a===""&&n[0]===""||(a==="."||a==="")&&(t=true,n.splice(i,1),i--);}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(t=true,n.pop());}let o=0;for(;(o=n.indexOf("..",o+1))!==-1;){let i=n[o-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=true;let l=o===1&&n[o+1]==="**"?["."]:[];n.splice(o-1,2,...l),n.length===0&&n.push(""),o-=2;}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let s=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(s){e[t]=[],e[n]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,n=false){let s=0,o=0,i=[],a="";for(;s<e.length&&o<t.length;)if(e[s]===t[o])i.push(a==="b"?t[o]:e[s]),s++,o++;else if(n&&e[s]==="**"&&t[o]===e[s+1])i.push(e[s]),s++;else if(n&&t[o]==="**"&&e[s]===t[o+1])i.push(t[o]),o++;else if(e[s]==="*"&&t[o]&&(this.options.dot||!t[o].startsWith("."))&&t[o]!=="**"){if(a==="b")return false;a="a",i.push(e[s]),s++,o++;}else if(t[o]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(a==="a")return false;a="b",i.push(t[o]),s++,o++;}else return false;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=false,n=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t;}matchOne(e,t,n=false){let s=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),v=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),b=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),C=!b&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),w=v?3:f?0:void 0,I=C?3:b?0:void 0;if(typeof w=="number"&&typeof I=="number"){let[M,N]=[e[w],t[I]];M.toLowerCase()===N.toLowerCase()&&(t[I]=M,I>w?t=t.slice(I):w>I&&(e=e.slice(w)));}}let{optimizationLevel:o=1}=this.options;o>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,a=0,l=e.length,c=t.length;i<l&&a<c;i++,a++){this.debug("matchOne loop");var u=t[a],d=e[i];if(this.debug(t,u,d),u===false)return false;if(u===yt){this.debug("GLOBSTAR",[t,u,d]);var m=i,g=a+1;if(g===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!s.dot&&e[i].charAt(0)===".")return false;return true}for(;m<l;){var h=e[m];if(this.debug(`
377
376
  globstar while`,e,m,t,g,h),this.matchOne(e.slice(m),t.slice(g),n))return this.debug("globstar found match!",m,l,h),true;if(h==="."||h===".."||!s.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,m,t,g);break}this.debug("globstar swallow a segment, and continue"),m++;}return !!(n&&(this.debug(`
378
- >>> no match, partial?`,e,m,t,g),m===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return false}if(i===l&&a===c)return true;if(i===l)return n;if(a===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return vf(this.pattern,this.options)}parse(e){Jo(e);let t=this.options;if(e==="**")return yt;if(e==="")return "";let n,s=null;(n=e.match(BS))?s=t.dot?US:FS:(n=e.match(ES))?s=(t.nocase?t.dot?RS:PS:t.dot?MS:AS)(n[1]):(n=e.match(GS))?s=(t.nocase?t.dot?WS:jS:t.dot?HS:zS)(n):(n=e.match(DS))?s=t.dot?LS:NS:(n=e.match($S))&&(s=OS);let o=$r.fromGlob(e,this.options).toMMPattern();return s&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:s}),o}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,n=t.noglobstar?JS:t.dot?VS:YS,s=new Set(t.nocase?["i"]:[]),o=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))s.add(d);return typeof u=="string"?tk(u):u===yt?yt:u._src});return c.forEach((u,d)=>{let m=c[d+1],g=c[d-1];u!==yt||g===yt||(g===void 0?m!==void 0&&m!==yt?c[d+1]="(?:\\/|"+n+"\\/)?"+m:c[d]=n:m===void 0?c[d-1]=g+"(?:\\/|"+n+")?":m!==yt&&(c[d-1]=g+"(?:\\/|\\/"+n+"\\/)"+m,c[d+1]=yt));}),c.filter(u=>u!==yt).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];o="^"+i+o+a+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let o=this.set;this.debug(this.pattern,"set",o);let i=s[s.length-1];if(!i)for(let a=s.length-2;!i&&a>=0;a--)i=s[a];for(let a=0;a<o.length;a++){let l=o[a],c=s;if(n.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return n.flipNegate?true:!this.negate}return n.flipNegate?false:this.negate}static defaults(e){return Dt.defaults(e).Minimatch}};Dt.AST=$r;Dt.Minimatch=Yt;Dt.escape=Or;Dt.unescape=yn;var Br=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,Cd=typeof process=="object"&&process?process:{},wf=(r,e,t,n)=>{typeof Cd.emitWarning=="function"?Cd.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`);},Za=globalThis.AbortController,Cf=globalThis.AbortSignal;if(typeof Za>"u"){Cf=class{onabort;_onabort=[];reason;aborted=false;addEventListener(n,s){this._onabort.push(s);}},Za=class{constructor(){e();}signal=new Cf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=true;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n);}}};let r=Cd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=false,wf("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 nk=r=>!xf.has(r);var vs=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Tf=r=>vs(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Fr:null:null,Fr=class extends Array{constructor(e){super(e),this.fill(0);}},xd=class r{heap;length;static#e=false;static create(e){let t=Tf(e);if(!t)return [];r.#e=true;let n=new r(e,t);return r.#e=false,n}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]}},Yo=class r{#e;#t;#o;#s;#i;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#d;#a;#l;#r;#f;#y;#m;#p;#T;#h;#S;#k;#v;#x;#w;#g;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#v,sizes:e.#S,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#p},free:e.#T,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,n,s,o)=>e.#B(t,n,s,o),moveToTail:t=>e.#U(t),indexes:t=>e.#I(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.#d}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#C}get dispose(){return this.#o}get disposeAfter(){return this.#s}constructor(e){let{max:t=0,ttl:n,ttlResolution:s=1,ttlAutopurge:o,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:m,maxSize:g=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:v,memoMethod:b,noDeleteOnFetchRejection:C,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:I,allowStaleOnFetchAbort:M,ignoreFetchAbort:N}=e;if(t!==0&&!vs(t))throw new TypeError("max option must be a nonnegative integer");let R=t?Tf(t):Array;if(!R)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=g,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.#C=b,v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=v,this.#w=!!v,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new R(t),this.#y=new R(t),this.#m=0,this.#p=0,this.#T=xd.create(t),this.#c=0,this.#d=0,typeof c=="function"&&(this.#o=c),typeof u=="function"?(this.#s=u,this.#h=[]):(this.#s=void 0,this.#h=void 0),this.#x=!!this.#o,this.#g=!!this.#s,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!C,this.allowStaleOnFetchRejection=!!I,this.allowStaleOnFetchAbort=!!M,this.ignoreFetchAbort=!!N,this.maxEntrySize!==0){if(this.#t!==0&&!vs(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!vs(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#M();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=vs(s)||s===0?s:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!vs(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#A();}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 O="LRU_CACHE_UNBOUNDED";nk(O)&&(xf.add(O),wf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",O,r));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#A(){let e=new Fr(this.#e),t=new Fr(this.#e);this.#v=e,this.#k=t,this.#R=(o,i,a=Br.now())=>{if(t[o]=i!==0?a:0,e[o]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(o)&&this.#P(this.#l[o],"expire");},i+1);l.unref&&l.unref();}},this.#_=o=>{t[o]=e[o]!==0?Br.now():0;},this.#n=(o,i)=>{if(e[i]){let a=e[i],l=t[i];if(!a||!l)return;o.ttl=a,o.start=l,o.now=n||s();let c=o.now-l;o.remainingTTL=a-c;}};let n=0,s=()=>{let o=Br.now();if(this.ttlResolution>0){n=o;let i=setTimeout(()=>n=0,this.ttlResolution);i.unref&&i.unref();}return o};this.getRemainingTTL=o=>{let i=this.#a.get(o);if(i===void 0)return 0;let a=e[i],l=t[i];if(!a||!l)return 1/0;let c=(n||s())-l;return a-c},this.#b=o=>{let i=t[o],a=e[o];return !!a&&!!i&&(n||s())-i>a};}#_=()=>{};#n=()=>{};#R=()=>{};#b=()=>false;#M(){let e=new Fr(this.#e);this.#d=0,this.#S=e,this.#D=t=>{this.#d-=e[t],e[t]=0;},this.#L=(t,n,s,o)=>{if(this.#u(n))return 0;if(!vs(s))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(s=o(n,t),!vs(s))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 s},this.#N=(t,n,s)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];for(;this.#d>o;)this.#O(true);}this.#d+=e[t],s&&(s.entrySize=n,s.totalCalculatedSize=this.#d);};}#D=e=>{};#N=(e,t,n)=>{};#L=(e,t,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#E({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#p));)t=this.#f[t];}#$(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#I())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*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.#I()){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.#I())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 n of this.#I()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;if(o!==void 0&&e(o,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#I()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;o!==void 0&&e.call(t,o,this.#l[n],this);}}rforEach(e,t=this){for(let n of this.#E()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;o!==void 0&&e.call(t,o,this.#l[n],this);}}purgeStale(){let e=false;for(let t of this.#E({allowStale:true}))this.#b(t)&&(this.#P(this.#l[t],"expire"),e=true);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#r[t],s=this.#u(n)?n.__staleWhileFetching:n;if(s===void 0)return;let o={value:s};if(this.#v&&this.#k){let i=this.#v[t],a=this.#k[t];if(i&&a){let l=i-(Br.now()-a);o.ttl=l,o.start=Date.now();}}return this.#S&&(o.size=this.#S[t]),o}dump(){let e=[];for(let t of this.#I({allowStale:true})){let n=this.#l[t],s=this.#r[t],o=this.#u(s)?s.__staleWhileFetching:s;if(o===void 0||n===void 0)continue;let i={value:o};if(this.#v&&this.#k){i.ttl=this.#v[t];let a=Br.now()-this.#k[t];i.start=Math.floor(Date.now()-a);}this.#S&&(i.size=this.#S[t]),e.unshift([n,i]);}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let s=Date.now()-n.start;n.start=Br.now()-s;}this.set(t,n.value,n);}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:o,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,u=this.#L(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#P(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#p:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#O(false):this.#c,this.#l[d]=e,this.#r[d]=t,this.#a.set(e,d),this.#f[this.#p]=d,this.#y[d]=this.#p,this.#p=d,this.#c++,this.#N(d,u,l),l&&(l.set="add"),c=false;else {this.#U(d);let m=this.#r[d];if(t!==m){if(this.#w&&this.#u(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=m;g!==void 0&&!i&&(this.#x&&this.#o?.(g,e,"set"),this.#g&&this.#h?.push([g,e,"set"]));}else i||(this.#x&&this.#o?.(m,e,"set"),this.#g&&this.#h?.push([m,e,"set"]));if(this.#D(d),this.#N(d,u,l),this.#r[d]=t,l){l.set="replace";let g=m&&this.#u(m)?m.__staleWhileFetching:m;g!==void 0&&(l.oldValue=g);}}else l&&(l.set="update");}if(s!==0&&!this.#v&&this.#A(),this.#v&&(c||this.#R(d,s,o),l&&this.#n(l,d)),!i&&this.#g&&this.#h){let m=this.#h,g;for(;g=m?.shift();)this.#s?.(...g);}return this}pop(){try{for(;this.#c;){let e=this.#r[this.#m];if(this.#O(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#g&&this.#h){let e=this.#h,t;for(;t=e?.shift();)this.#s?.(...t);}}}#O(e){let t=this.#m,n=this.#l[t],s=this.#r[t];return this.#w&&this.#u(s)?s.__abortController.abort(new Error("evicted")):(this.#x||this.#g)&&(this.#x&&this.#o?.(s,n,"evict"),this.#g&&this.#h?.push([s,n,"evict"])),this.#D(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#p=0,this.#T.length=0):this.#m=this.#f[t],this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=t,o=this.#a.get(e);if(o!==void 0){let i=this.#r[o];if(this.#u(i)&&i.__staleWhileFetching===void 0)return false;if(this.#b(o))s&&(s.has="stale",this.#n(s,o));else return n&&this.#_(o),s&&(s.has="hit",this.#n(s,o)),true}else s&&(s.has="miss");return false}peek(e,t={}){let{allowStale:n=this.allowStale}=t,s=this.#a.get(e);if(s===void 0||!n&&this.#b(s))return;let o=this.#r[s];return this.#u(o)?o.__staleWhileFetching:o}#B(e,t,n,s){let o=t===void 0?void 0:this.#r[t];if(this.#u(o))return o;let i=new Za,{signal:a}=n;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let l={signal:i.signal,options:n,context:s},c=(f,v=false)=>{let{aborted:b}=i.signal,C=n.ignoreFetchAbort&&f!==void 0;if(n.status&&(b&&!v?(n.status.fetchAborted=true,n.status.fetchError=i.signal.reason,C&&(n.status.fetchAbortIgnored=true)):n.status.fetchResolved=true),b&&!C&&!v)return d(i.signal.reason);let w=g;return this.#r[t]===g&&(f===void 0?w.__staleWhileFetching?this.#r[t]=w.__staleWhileFetching:this.#P(e,"fetch"):(n.status&&(n.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(n.status&&(n.status.fetchRejected=true,n.status.fetchError=f),d(f)),d=f=>{let{aborted:v}=i.signal,b=v&&n.allowStaleOnFetchAbort,C=b||n.allowStaleOnFetchRejection,w=C||n.noDeleteOnFetchRejection,I=g;if(this.#r[t]===g&&(!w||I.__staleWhileFetching===void 0?this.#P(e,"fetch"):b||(this.#r[t]=I.__staleWhileFetching)),C)return n.status&&I.__staleWhileFetching!==void 0&&(n.status.returnedStale=true),I.__staleWhileFetching;if(I.__returned===I)throw f},m=(f,v)=>{let b=this.#i?.(e,o,l);b&&b instanceof Promise&&b.then(C=>f(C===void 0?void 0:C),v),i.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(f(void 0),n.allowStaleOnFetchAbort&&(f=C=>c(C,true)));});};n.status&&(n.status.fetchDispatched=true);let g=new Promise(m).then(c,u),h=Object.assign(g,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#r[t]=h,h}#u(e){if(!this.#w)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Za}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:v=false,status:b,signal:C}=t;if(!this.#w)return b&&(b.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:o,status:b});let w={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:g,status:b,signal:C},I=this.#a.get(e);if(I===void 0){b&&(b.fetch="miss");let M=this.#B(e,I,w,f);return M.__returned=M}else {let M=this.#r[I];if(this.#u(M)){let A=n&&M.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",A&&(b.returnedStale=true)),A?M.__staleWhileFetching:M.__returned=M}let N=this.#b(I);if(!v&&!N)return b&&(b.fetch="hit"),this.#U(I),s&&this.#_(I),b&&this.#n(b,I),M;let R=this.#B(e,I,w,f),k=R.__staleWhileFetching!==void 0&&n;return b&&(b.fetch=N?"stale":"refresh",k&&N&&(b.returnedStale=true)),k?R.__staleWhileFetching:R.__returned=R}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#C;if(!n)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:o,...i}=t,a=this.get(e,i);if(!o&&a!==void 0)return a;let l=n(e,a,{options:i,context:s});return this.set(e,l,i),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#r[a],c=this.#u(l);return i&&this.#n(i,a),this.#b(a)?(i&&(i.get="stale"),c?(i&&n&&l.__staleWhileFetching!==void 0&&(i.returnedStale=true),n?l.__staleWhileFetching:void 0):(o||this.#P(e,"expire"),i&&n&&(i.returnedStale=true),n?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#U(a),s&&this.#_(a),l))}else i&&(i.get="miss");}#F(e,t){this.#y[t]=e,this.#f[e]=t;}#U(e){e!==this.#p&&(e===this.#m?this.#m=this.#f[e]:this.#F(this.#y[e],this.#f[e]),this.#F(this.#p,e),this.#p=e);}delete(e){return this.#P(e,"delete")}#P(e,t){let n=false;if(this.#c!==0){let s=this.#a.get(e);if(s!==void 0)if(n=true,this.#c===1)this.#G(t);else {this.#D(s);let o=this.#r[s];if(this.#u(o)?o.__abortController.abort(new Error("deleted")):(this.#x||this.#g)&&(this.#x&&this.#o?.(o,e,t),this.#g&&this.#h?.push([o,e,t])),this.#a.delete(e),this.#l[s]=void 0,this.#r[s]=void 0,s===this.#p)this.#p=this.#y[s];else if(s===this.#m)this.#m=this.#f[s];else {let i=this.#y[s];this.#f[i]=this.#f[s];let a=this.#f[s];this.#y[a]=this.#y[s];}this.#c--,this.#T.push(s);}}if(this.#g&&this.#h?.length){let s=this.#h,o;for(;o=s?.shift();)this.#s?.(...o);}return n}clear(){return this.#G("delete")}#G(e){for(let t of this.#E({allowStale:true})){let n=this.#r[t];if(this.#u(n))n.__abortController.abort(new Error("deleted"));else {let s=this.#l[t];this.#x&&this.#o?.(n,s,e),this.#g&&this.#h?.push([n,s,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#v&&this.#k&&(this.#v.fill(0),this.#k.fill(0)),this.#S&&this.#S.fill(0),this.#m=0,this.#p=0,this.#T.length=0,this.#d=0,this.#c=0,this.#g&&this.#h){let t=this.#h,n;for(;n=t?.shift();)this.#s?.(...n);}}};var Sf=typeof process=="object"&&process?process:{stdout:null,stderr:null},rk=r=>!!r&&typeof r=="object"&&(r instanceof xs||r instanceof Ef||ok(r)||ik(r)),ok=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Ef.Writable.prototype.pipe,ik=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.write=="function"&&typeof r.end=="function",Qn=Symbol("EOF"),Zn=Symbol("maybeEmitEnd"),Cs=Symbol("emittedEnd"),el=Symbol("emittingEnd"),Xo=Symbol("emittedError"),tl=Symbol("closed"),kf=Symbol("read"),nl=Symbol("flush"),_f=Symbol("flushChunk"),bn=Symbol("encoding"),Ur=Symbol("decoder"),ct=Symbol("flowing"),Qo=Symbol("paused"),Gr=Symbol("resume"),ut=Symbol("buffer"),Nt=Symbol("pipes"),dt=Symbol("bufferLength"),wd=Symbol("bufferPush"),sl=Symbol("bufferShift"),It=Symbol("objectMode"),Qe=Symbol("destroyed"),Td=Symbol("error"),Sd=Symbol("emitData"),If=Symbol("emitEnd"),kd=Symbol("emitEnd2"),Rn=Symbol("async"),_d=Symbol("abort"),rl=Symbol("aborted"),Zo=Symbol("signal"),Ks=Symbol("dataListeners"),Xt=Symbol("discarded"),ei=r=>Promise.resolve().then(r),ak=r=>r(),lk=r=>r==="end"||r==="finish"||r==="prefinish",ck=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,uk=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),ol=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Gr](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Id=class extends ol{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,n){super(e,t,n),this.proxyErrors=s=>t.emit("error",s),e.on("error",this.proxyErrors);}},dk=r=>!!r.objectMode,pk=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",xs=class extends EventEmitter{[ct]=false;[Qo]=false;[Nt]=[];[ut]=[];[It];[bn];[Rn];[Ur];[Qn]=false;[Cs]=false;[el]=false;[tl]=false;[Xo]=null;[dt]=0;[Qe]=false;[Zo];[rl]=false;[Ks]=0;[Xt]=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");dk(t)?(this[It]=true,this[bn]=null):pk(t)?(this[bn]=t.encoding,this[It]=false):(this[It]=false,this[bn]=null),this[Rn]=!!t.async,this[Ur]=this[bn]?new StringDecoder(this[bn]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[ut]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[Nt]});let{signal:n}=t;n&&(this[Zo]=n,n.aborted?this[_d]():n.addEventListener("abort",()=>this[_d]()));}get bufferLength(){return this[dt]}get encoding(){return this[bn]}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[It]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Rn]}set async(e){this[Rn]=this[Rn]||!!e;}[_d](){this[rl]=true,this.emit("abort",this[Zo]?.reason),this.destroy(this[Zo]?.reason);}get aborted(){return this[rl]}set aborted(e){}write(e,t,n){if(this[rl])return false;if(this[Qn])throw new Error("write after end");if(this[Qe])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let s=this[Rn]?ei:ak;if(!this[It]&&!Buffer.isBuffer(e)){if(uk(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(ck(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[It]?(this[ct]&&this[dt]!==0&&this[nl](true),this[ct]?this.emit("data",e):this[wd](e),this[dt]!==0&&this.emit("readable"),n&&s(n),this[ct]):e.length?(typeof e=="string"&&!(t===this[bn]&&!this[Ur]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[bn]&&(e=this[Ur].write(e)),this[ct]&&this[dt]!==0&&this[nl](true),this[ct]?this.emit("data",e):this[wd](e),this[dt]!==0&&this.emit("readable"),n&&s(n),this[ct]):(this[dt]!==0&&this.emit("readable"),n&&s(n),this[ct])}read(e){if(this[Qe])return null;if(this[Xt]=false,this[dt]===0||e===0||e&&e>this[dt])return this[Zn](),null;this[It]&&(e=null),this[ut].length>1&&!this[It]&&(this[ut]=[this[bn]?this[ut].join(""):Buffer.concat(this[ut],this[dt])]);let t=this[kf](e||null,this[ut][0]);return this[Zn](),t}[kf](e,t){if(this[It])this[sl]();else {let n=t;e===n.length||e===null?this[sl]():typeof n=="string"?(this[ut][0]=n.slice(e),t=n.slice(0,e),this[dt]-=e):(this[ut][0]=n.subarray(e),t=n.subarray(0,e),this[dt]-=e);}return this.emit("data",t),!this[ut].length&&!this[Qn]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Qn]=true,this.writable=false,(this[ct]||!this[Qo])&&this[Zn](),this}[Gr](){this[Qe]||(!this[Ks]&&!this[Nt].length&&(this[Xt]=true),this[Qo]=false,this[ct]=true,this.emit("resume"),this[ut].length?this[nl]():this[Qn]?this[Zn]():this.emit("drain"));}resume(){return this[Gr]()}pause(){this[ct]=false,this[Qo]=true,this[Xt]=false;}get destroyed(){return this[Qe]}get flowing(){return this[ct]}get paused(){return this[Qo]}[wd](e){this[It]?this[dt]+=1:this[dt]+=e.length,this[ut].push(e);}[sl](){return this[It]?this[dt]-=1:this[dt]-=this[ut][0].length,this[ut].shift()}[nl](e=false){do;while(this[_f](this[sl]())&&this[ut].length);!e&&!this[ut].length&&!this[Qn]&&this.emit("drain");}[_f](e){return this.emit("data",e),this[ct]}pipe(e,t){if(this[Qe])return e;this[Xt]=false;let n=this[Cs];return t=t||{},e===Sf.stdout||e===Sf.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Nt].push(t.proxyErrors?new Id(this,e,t):new ol(this,e,t)),this[Rn]?ei(()=>this[Gr]()):this[Gr]()),e}unpipe(e){let t=this[Nt].find(n=>n.dest===e);t&&(this[Nt].length===1?(this[ct]&&this[Ks]===0&&(this[ct]=false),this[Nt]=[]):this[Nt].splice(this[Nt].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[Xt]=false,this[Ks]++,!this[Nt].length&&!this[ct]&&this[Gr]();else if(e==="readable"&&this[dt]!==0)super.emit("readable");else if(lk(e)&&this[Cs])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Xo]){let s=t;this[Rn]?ei(()=>s.call(this,this[Xo])):s.call(this,this[Xo]);}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Ks]=this.listeners("data").length,this[Ks]===0&&!this[Xt]&&!this[Nt].length&&(this[ct]=false)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Ks]=0,!this[Xt]&&!this[Nt].length&&(this[ct]=false)),t}get emittedEnd(){return this[Cs]}[Zn](){!this[el]&&!this[Cs]&&!this[Qe]&&this[ut].length===0&&this[Qn]&&(this[el]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[tl]&&this.emit("close"),this[el]=false);}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==Qe&&this[Qe])return false;if(e==="data")return !this[It]&&!n?false:this[Rn]?(ei(()=>this[Sd](n)),true):this[Sd](n);if(e==="end")return this[If]();if(e==="close"){if(this[tl]=true,!this[Cs]&&!this[Qe])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[Xo]=n,super.emit(Td,n);let o=!this[Zo]||this.listeners("error").length?super.emit("error",n):false;return this[Zn](),o}else if(e==="resume"){let o=super.emit("resume");return this[Zn](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let s=super.emit(e,...t);return this[Zn](),s}[Sd](e){for(let n of this[Nt])n.dest.write(e)===false&&this.pause();let t=this[Xt]?false:super.emit("data",e);return this[Zn](),t}[If](){return this[Cs]?false:(this[Cs]=true,this.readable=false,this[Rn]?(ei(()=>this[kd]()),true):this[kd]())}[kd](){if(this[Ur]){let t=this[Ur].end();if(t){for(let n of this[Nt])n.dest.write(t);this[Xt]||super.emit("data",t);}}for(let t of this[Nt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[It]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[It]||(e.dataLength+=n.length);}),await t,e}async concat(){if(this[It])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[bn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Qe,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[Xt]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[Qn])return t();let o,i,a=d=>{this.off("data",l),this.off("end",c),this.off(Qe,u),t(),i(d);},l=d=>{this.off("error",a),this.off("end",c),this.off(Qe,u),this.pause(),o({value:d,done:!!this[Qn]});},c=()=>{this.off("error",a),this.off("data",l),this.off(Qe,u),t(),o({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((d,m)=>{i=m,o=d,this.once(Qe,u),this.once("error",a),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Xt]=false;let e=false,t=()=>(this.pause(),this.off(Td,t),this.off(Qe,t),this.off("end",t),e=true,{done:true,value:void 0}),n=()=>{if(e)return t();let s=this.read();return s===null?t():{done:false,value:s}};return this.once("end",t),this.once(Td,t),this.once(Qe,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Qe])return e?this.emit("error",e):this.emit(Qe),this;this[Qe]=true,this[Xt]=true,this[ut].length=0,this[dt]=0;let t=this;return typeof t.close=="function"&&!this[tl]&&t.close(),e?this.emit("error",e):this.emit(Qe),this}static get isStream(){return rk}};var xk=realpathSync.native,ni={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:xk,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Df=r=>!r||r===ni||r===Ze?ni:{...ni,...r,promises:{...ni.promises,...r.promises||{}}},Nf=/^\\\\\?\\([a-z]:)\\?$/i,_k=r=>r.replace(/\//g,"\\").replace(Nf,"$1\\"),Ik=/[\\\/]/,un=0,Lf=1,$f=2,Dn=4,Of=6,Bf=8,Js=10,Ff=12,cn=15,ti=~cn,Ad=16,Af=32,si=64,vn=128,il=256,ll=512,Mf=si|vn|ll,Ek=1023,Md=r=>r.isFile()?Bf:r.isDirectory()?Dn:r.isSymbolicLink()?Js:r.isCharacterDevice()?$f:r.isBlockDevice()?Of:r.isSocket()?Ff:r.isFIFO()?Lf:un,Pf=new Map,ri=r=>{let e=Pf.get(r);if(e)return e;let t=r.normalize("NFKD");return Pf.set(r,t),t},Rf=new Map,al=r=>{let e=Rf.get(r);if(e)return e;let t=ri(r.toLowerCase());return Rf.set(r,t),t},cl=class extends Yo{constructor(){super({max:256});}},Rd=class extends Yo{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Uf=Symbol("PathScurry setAsCwd"),Et=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#o;get mode(){return this.#o}#s;get nlink(){return this.#s}#i;get uid(){return this.#i}#C;get gid(){return this.#C}#c;get rdev(){return this.#c}#d;get blksize(){return this.#d}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#p;get birthtimeMs(){return this.#p}#T;get atime(){return this.#T}#h;get mtime(){return this.#h}#S;get ctime(){return this.#S}#k;get birthtime(){return this.#k}#v;#x;#w;#g;#A;#_;#n;#R;#b;#M;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=un,n,s,o,i,a){this.name=e,this.#v=o?al(e):ri(e),this.#n=t&Ek,this.nocase=o,this.roots=s,this.root=n||this,this.#R=i,this.#w=a.fullpath,this.#A=a.relative,this.#_=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Df(a.fs);}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#R}resolve(e){if(!e)return this;let t=this.getRootString(e),s=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#D(s):this.#D(s)}#D(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#R.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#R.set(this,t),this.#n&=~Ad,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),s=this.nocase?al(e):ri(e);for(let l of n)if(l.#v===s)return l;let o=this.parent?this.sep:"",i=this.#w?this.#w+o+e:void 0,a=this.newChild(e,un,{...t,parent:this,fullpath:i});return this.canReaddir()||(a.#n|=vn),n.push(a),a}relative(){if(this.isCWD)return "";if(this.#A!==void 0)return this.#A;let e=this.name,t=this.parent;if(!t)return this.#A=this.name;let n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(this.#_!==void 0)return this.#_;let e=this.name,t=this.parent;if(!t)return this.#_=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#w!==void 0)return this.#w;let e=this.name,t=this.parent;if(!t)return this.#w=this.name;let s=t.fullpath()+(t.parent?this.sep:"")+e;return this.#w=s}fullpathPosix(){if(this.#g!==void 0)return this.#g;if(this.sep==="/")return this.#g=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?this.#g=`//?/${s}`:this.#g=s}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#g=n}isUnknown(){return (this.#n&cn)===un}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#n&cn)===Bf}isDirectory(){return (this.#n&cn)===Dn}isCharacterDevice(){return (this.#n&cn)===$f}isBlockDevice(){return (this.#n&cn)===Of}isFIFO(){return (this.#n&cn)===Lf}isSocket(){return (this.#n&cn)===Ff}isSymbolicLink(){return (this.#n&Js)===Js}lstatCached(){return this.#n&Af?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.#n&cn;return !(e!==un&&e!==Js||this.#n&il||this.#n&vn)}calledReaddir(){return !!(this.#n&Ad)}isENOENT(){return !!(this.#n&vn)}isNamed(e){return this.nocase?this.#v===al(e):this.#v===ri(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}#N(e){this.#n|=Ad;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#L();}}#L(){this.#n&vn||(this.#n=(this.#n|vn)&ti,this.#I());}#I(){let e=this.children();e.provisional=0;for(let t of e)t.#L();}#E(){this.#n|=ll,this.#$();}#$(){if(this.#n&si)return;let e=this.#n;(e&cn)===Dn&&(e&=ti),this.#n=e|si,this.#I();}#O(e=""){e==="ENOTDIR"||e==="EPERM"?this.#$():e==="ENOENT"?this.#L():this.children().provisional=0;}#B(e=""){e==="ENOTDIR"?this.parent.#$():e==="ENOENT"&&this.#L();}#u(e=""){let t=this.#n;t|=il,e==="ENOENT"&&(t|=vn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=ti),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#$();}#F(e,t){return this.#P(e,t)||this.#U(e,t)}#U(e,t){let n=Md(e),s=this.newChild(e.name,n,{parent:this}),o=s.#n&cn;return o!==Dn&&o!==Js&&o!==un&&(s.#n|=si),t.unshift(s),t.provisional++,s}#P(e,t){for(let n=t.provisional;n<t.length;n++){let s=t[n];if((this.nocase?al(e.name):ri(e.name))===s.#v)return this.#G(e,s,n,t)}}#G(e,t,n,s){let o=t.name;return t.#n=t.#n&ti|Md(e),o!==e.name&&(t.name=e.name),n!==s.provisional&&(n===s.length-1?s.pop():s.splice(n,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#n&vn)===0)try{return this.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#B(e.code);}}lstatSync(){if((this.#n&vn)===0)try{return this.#z(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#B(e.code);}}#z(e){let{atime:t,atimeMs:n,birthtime:s,birthtimeMs:o,blksize:i,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:d,ino:m,mode:g,mtime:h,mtimeMs:f,nlink:v,rdev:b,size:C,uid:w}=e;this.#T=t,this.#f=n,this.#k=s,this.#p=o,this.#d=i,this.#r=a,this.#S=l,this.#m=c,this.#t=u,this.#C=d,this.#a=m,this.#o=g,this.#h=h,this.#y=f,this.#s=v,this.#c=b,this.#l=C,this.#i=w;let I=Md(e);this.#n=this.#n&ti|I|Af,I!==un&&I!==Dn&&I!==Js&&(this.#n|=si);}#W=[];#H=false;#q(e){this.#H=false;let t=this.#W.slice();this.#W.length=0,t.forEach(n=>n(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let o=n.slice(0,n.provisional);t?e(null,o):queueMicrotask(()=>e(null,o));return}if(this.#W.push(e),this.#H)return;this.#H=true;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:true},(o,i)=>{if(o)this.#O(o.code),n.provisional=0;else {for(let a of i)this.#F(a,n);this.#N(n);}this.#q(n.slice(0,n.provisional));});}#j;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.#j)await this.#j;else {let n=()=>{};this.#j=new Promise(s=>n=s);try{for(let s of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#F(s,e);this.#N(e);}catch(s){this.#O(s.code),e.provisional=0;}this.#j=void 0,n();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#F(n,e);this.#N(e);}catch(n){this.#O(n.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&Mf)return false;let e=cn&this.#n;return e===un||e===Dn||e===Js}shouldWalk(e,t){return (this.#n&Dn)===Dn&&!(this.#n&Mf)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#M)return this.#M;if(!((ll|il|vn)&this.#n))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(!((ll|il|vn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}[Uf](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),n=[],s=this;for(;s&&s.parent;)t.add(s),s.#A=n.join(this.sep),s.#_=n.join("/"),s=s.parent,n.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#A=void 0,s.#_=void 0,s=s.parent;}},ul=class r extends Et{sep="\\";splitSep=Ik;constructor(e,t=un,n,s,o,i,a){super(e,t,n,s,o,i,a);}newChild(e,t=un,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=_k(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new jr(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Nf,"$1\\"),e===t}},dl=class r extends Et{splitSep="/";sep="/";constructor(e,t=un,n,s,o,i,a){super(e,t,n,s,o,i,a);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=un,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},pl=class{root;rootPath;roots;cwd;#e;#t;#o;nocase;#s;constructor(e=process.cwd(),t,n,{nocase:s,childrenCacheSize:o=16*1024,fs:i=ni}={}){this.#s=Df(i),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new cl,this.#t=new cl,this.#o=new Rd(o);let l=a.substring(this.rootPath.length).split(n);if(l.length===1&&!l[0]&&l.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#s),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,m=this.rootPath,g=false;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:m+=(g?"":d)+h}),g=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#o}resolve(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#e.get(t);if(n!==void 0)return n;let s=this.cwd.resolve(t).fullpath();return this.#e.set(t,s),s}resolvePosix(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#t.get(t);if(n!==void 0)return n;let s=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,s),s}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 Et||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let s=await e.readdir();return n?s:s.map(o=>o.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(s=>s.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 Et||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(n?e:e.fullpath());let l=new Set,c=(d,m)=>{l.add(d),d.readdirCB((g,h)=>{if(g)return m(g);let f=h.length;if(!f)return m();let v=()=>{--f===0&&m();};for(let b of h)(!o||o(b))&&a.push(n?b:b.fullpath()),s&&b.isSymbolicLink()?b.realpath().then(C=>C?.isUnknown()?C.lstat():C).then(C=>C?.shouldWalk(l,i)?c(C,v):v()):b.shouldWalk(l,i)?c(b,v):v();},true);},u=e;return new Promise((d,m)=>{c(u,g=>{if(g)return m(g);d(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!o||o(d))&&a.push(n?d:d.fullpath());let m=d;if(d.isSymbolicLink()){if(!(s&&(m=d.realpathSync())))continue;m.isUnknown()&&m.lstatSync();}m.shouldWalk(l,i)&&l.add(m);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(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 Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t;(!o||o(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!o||o(u))&&(yield n?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(a,i)&&a.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=new xs({objectMode:true});(!o||o(e))&&a.write(n?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let m=false;for(;!m;){let g=c.shift();if(!g){u===0&&a.end();return}u++,l.add(g);let h=(v,b,C=false)=>{if(v)return a.emit("error",v);if(s&&!C){let w=[];for(let I of b)I.isSymbolicLink()&&w.push(I.realpath().then(M=>M?.isUnknown()?M.lstat():M));if(w.length){Promise.all(w).then(()=>h(null,b,true));return}}for(let w of b)w&&(!o||o(w))&&(a.write(n?w:w.fullpath())||(m=true));u--;for(let w of b){let I=w.realpathCached()||w;I.shouldWalk(l,i)&&c.push(I);}m&&!a.flowing?a.once("drain",d):f||d();},f=true;g.readdirCB(h,true),f=false;}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=new xs({objectMode:true}),l=new Set;(!o||o(e))&&a.write(n?e:e.fullpath());let c=[e],u=0,d=()=>{let m=false;for(;!m;){let g=c.shift();if(!g){u===0&&a.end();return}u++,l.add(g);let h=g.readdirSync();for(let f of h)(!o||o(f))&&(a.write(n?f:f.fullpath())||(m=true));u--;for(let f of h){let v=f;if(f.isSymbolicLink()){if(!(s&&(v=f.realpathSync())))continue;v.isUnknown()&&v.lstatSync();}v.shouldWalk(l,i)&&c.push(v);}}m&&!a.flowing&&a.once("drain",d);};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Uf](t);}},jr=class extends pl{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,win32,"\\",{...t,nocase:n}),this.nocase=n;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new ul(this.rootPath,Dn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Wr=class extends pl{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=false}=t;super(e,posix,"/",{...t,nocase:n}),this.nocase=n;}parseRootPath(e){return "/"}newRoot(e){return new dl(this.rootPath,Dn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},oi=class extends Wr{constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,{...t,nocase:n});}};process.platform==="win32"?ul:dl;var Gf=process.platform==="win32"?jr:process.platform==="darwin"?oi:Wr;var Ak=r=>r.length>=1,Mk=r=>r.length>=1,Hr=class r{#e;#t;#o;length;#s;#i;#C;#c;#d;#a;#l=true;constructor(e,t,n,s){if(!Ak(e))throw new TypeError("empty pattern list");if(!Mk(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#o=n,this.#s=s,this.#o===0){if(this.isUNC()){let[o,i,a,l,...c]=this.#e,[u,d,m,g,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[o,i,a,l,""].join("/"),v=[u,d,m,g,""].join("/");this.#e=[f,...c],this.#t=[v,...h],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[o,...i]=this.#e,[a,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=o+"/",u=a+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#o]}isString(){return typeof this.#e[this.#o]=="string"}isGlobstar(){return this.#e[this.#o]===yt}isRegExp(){return this.#e[this.#o]instanceof RegExp}globString(){return this.#C=this.#C||(this.#o===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#o).join("/"))}hasMore(){return this.length>this.#o+1}rest(){return this.#i!==void 0?this.#i:this.hasMore()?(this.#i=new r(this.#e,this.#t,this.#o+1,this.#s),this.#i.#a=this.#a,this.#i.#d=this.#d,this.#i.#c=this.#c,this.#i):this.#i=null}isUNC(){let e=this.#e;return this.#d!==void 0?this.#d:this.#d=this.#s==="win32"&&this.#o===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#s==="win32"&&this.#o===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#o===0?e:""}checkFollowGlobstar(){return !(this.#o===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#o===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};var Pk=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",zr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:s,noglobstar:o,platform:i=Pk}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:true,nobrace:t,nocase:n,noext:s,noglobstar:o,optimizationLevel:2,platform:i,nocomment:true,nonegate:true};for(let a of e)this.add(a);}add(e){let t=new Yt(e,this.mmopts);for(let n=0;n<t.set.length;n++){let s=t.set[n],o=t.globParts[n];if(!s||!o)throw new Error("invalid pattern object");for(;s[0]==="."&&o[0]===".";)s.shift(),o.shift();let i=new Hr(s,o,0,this.platform),a=new Yt(i.globString(),this.mmopts),l=o[o.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(e){let t=e.fullpath(),n=`${t}/`,s=e.relative()||".",o=`${s}/`;for(let i of this.relative)if(i.match(s)||i.match(o))return true;for(let i of this.absolute)if(i.match(t)||i.match(n))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(n))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}};var Dd=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 n=e.fullpath(),s=this.store.get(n);s?s.add(t.globString()):this.store.set(n,new Set([t.globString()]));}},Nd=class{store=new Map;add(e,t,n){let s=(t?2:0)|(n?1:0),o=this.store.get(e);this.store.set(e,o===void 0?s:s&o);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Ld=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(s=>s.globString()===t.globString())||n.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},ii=class r{hasWalkedCache;matches=new Nd;subwalks=new Ld;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Dd;}processPatterns(e,t){this.patterns=t;let n=t.map(s=>[e,s]);for(let[s,o]of n){this.hasWalkedCache.storeWalked(s,o);let i=o.root(),a=o.isAbsolute()&&this.opts.absolute!==false;if(i){s=s.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=o.rest();if(d)o=d;else {this.matches.add(s,true,false);continue}}if(s.isENOENT())continue;let l,c,u=false;for(;typeof(l=o.pattern())=="string"&&(c=o.rest());)s=s.resolve(l),o=c,u=true;if(l=o.pattern(),c=o.rest(),u){if(this.hasWalkedCache.hasWalked(s,o))continue;this.hasWalkedCache.storeWalked(s,o);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(s.resolve(l),a,d);continue}else if(l===yt){(!s.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(s,o);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(s,a,d===""||d===".");else if(d===".."){let g=s.parent||s;m?this.hasWalkedCache.hasWalked(g,m)||this.subwalks.add(g,m):this.matches.add(g,a,true);}}else l instanceof RegExp&&this.subwalks.add(s,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),s=this.child();for(let o of t)for(let i of n){let a=i.isAbsolute(),l=i.pattern(),c=i.rest();l===yt?s.testGlobstar(o,i,c,a):l instanceof RegExp?s.testRegExp(o,l,c,a):s.testString(o,l,c,a);}return s}testGlobstar(e,t,n,s){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,s,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let o=n.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(e,o,n.rest(),s);else if(o===".."){let i=e.parent||e;this.subwalks.add(i,n);}else o instanceof RegExp&&this.testRegExp(e,o,n.rest(),s);}}testRegExp(e,t,n,s){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,s,false));}testString(e,t,n,s){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,s,false));}};var Rk=(r,e)=>typeof r=="string"?new zr([r],e):Array.isArray(r)?new zr(r,e):r,ml=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#o;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#o=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==false,(n.ignore||!this.includeChildMatches)&&(this.#t=Rk(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#s(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(e){return !!this.#t?.childrenIgnored?.(e)}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=this.#e.shift());)e();}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n;}let o=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=await o.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat();}return this.matchCheckTest(o,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#s(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n;}let o=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=o.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync();}return this.matchCheckTest(o,t)}matchFinish(e,t){if(this.#s(e))return;if(!this.includeChildMatches&&this.#t?.add){let o=`${e.relativePosix()}/**`;this.#t.add(o);}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#o:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let o=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(o+s);}else {let o=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!o.startsWith(".."+this.#o)?"."+this.#o:"";this.matchEmit(o?i+o+s:"."+s);}}async match(e,t,n){let s=await this.matchCheck(e,n);s&&this.matchFinish(s,t);}matchSync(e,t,n){let s=this.matchCheckSync(e,n);s&&this.matchFinish(s,t);}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new ii(this.opts),n);}walkCB2(e,t,n,s){if(this.#i(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,s));return}n.processPatterns(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(o++,this.match(a,l,c).then(()=>i()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,n,i):a.readdirCB((c,u)=>this.walkCB3(a,u,n,i),true);}i();}walkCB3(e,t,n,s){n=n.filterEntries(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(o++,this.match(a,l,c).then(()=>i()));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2(a,l,n.child(),i);i();}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new ii(this.opts),n);}walkCB2Sync(e,t,n,s){if(this.#i(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,s));return}n.processPatterns(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirSync();this.walkCB3Sync(a,l,n,i);}i();}walkCB3Sync(e,t,n,s){n=n.filterEntries(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let[a,l]of n.subwalks.entries())o++,this.walkCB2Sync(a,l,n.child(),i);i();}},ai=class extends ml{matches=new Set;constructor(e,t,n){super(e,t,n);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},li=class extends ml{results;constructor(e,t,n){super(e,t,n),this.results=new xs({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 Nk=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Cn=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||Nk,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"?jr:t.platform==="darwin"?oi:t.platform?Wr:Gf;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",s={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},o=this.pattern.map(l=>new Yt(l,s)),[i,a]=o.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new Hr(l,u,0,this.platform)});}async walk(){return [...await new ai(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 ai(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 li(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 li(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 $d=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Yt(t,e).hasMagic())return true;return false};function gl(r,e={}){return new Cn(r,e).streamSync()}function Wf(r,e={}){return new Cn(r,e).stream()}function Hf(r,e={}){return new Cn(r,e).walkSync()}async function jf(r,e={}){return new Cn(r,e).walk()}function hl(r,e={}){return new Cn(r,e).iterateSync()}function zf(r,e={}){return new Cn(r,e).iterate()}var Lk=gl,$k=Object.assign(Wf,{sync:gl}),Ok=hl,Bk=Object.assign(zf,{sync:hl}),Fk=Object.assign(Hf,{stream:gl,iterate:hl}),qr=Object.assign(jf,{glob:jf,globSync:Hf,sync:Fk,globStream:Wf,stream:$k,globStreamSync:gl,streamSync:Lk,globIterate:zf,iterate:Bk,globIterateSync:hl,iterateSync:Ok,Glob:Cn,hasMagic:$d,escape:Or,unescape:yn});qr.glob=qr;var ci=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let n=e.split(`
377
+ >>> no match, partial?`,e,m,t,g),m===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return false}if(i===l&&a===c)return true;if(i===l)return n;if(a===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return vf(this.pattern,this.options)}parse(e){Jo(e);let t=this.options;if(e==="**")return yt;if(e==="")return "";let n,s=null;(n=e.match(BS))?s=t.dot?US:FS:(n=e.match(ES))?s=(t.nocase?t.dot?RS:PS:t.dot?MS:AS)(n[1]):(n=e.match(GS))?s=(t.nocase?t.dot?WS:jS:t.dot?HS:zS)(n):(n=e.match(DS))?s=t.dot?LS:NS:(n=e.match($S))&&(s=OS);let o=$r.fromGlob(e,this.options).toMMPattern();return s&&typeof o=="object"&&Reflect.defineProperty(o,"test",{value:s}),o}makeRe(){if(this.regexp||this.regexp===false)return this.regexp;let e=this.set;if(!e.length)return this.regexp=false,this.regexp;let t=this.options,n=t.noglobstar?JS:t.dot?VS:YS,s=new Set(t.nocase?["i"]:[]),o=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))s.add(d);return typeof u=="string"?tk(u):u===yt?yt:u._src});return c.forEach((u,d)=>{let m=c[d+1],g=c[d-1];u!==yt||g===yt||(g===void 0?m!==void 0&&m!==yt?c[d+1]="(?:\\/|"+n+"\\/)?"+m:c[d]=n:m===void 0?c[d-1]=g+"(?:\\/|"+n+")?":m!==yt&&(c[d-1]=g+"(?:\\/|\\/"+n+"\\/)"+m,c[d+1]=yt));}),c.filter(u=>u!==yt).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];o="^"+i+o+a+"$",this.negate&&(o="^(?!"+o+").+$");try{this.regexp=new RegExp(o,[...s].join(""));}catch{this.regexp=false;}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return false;if(this.empty)return e==="";if(e==="/"&&t)return true;let n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let o=this.set;this.debug(this.pattern,"set",o);let i=s[s.length-1];if(!i)for(let a=s.length-2;!i&&a>=0;a--)i=s[a];for(let a=0;a<o.length;a++){let l=o[a],c=s;if(n.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return n.flipNegate?true:!this.negate}return n.flipNegate?false:this.negate}static defaults(e){return Dt.defaults(e).Minimatch}};Dt.AST=$r;Dt.Minimatch=Yt;Dt.escape=Or;Dt.unescape=yn;var Br=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,xf=new Set,Cd=typeof process=="object"&&process?process:{},wf=(r,e,t,n)=>{typeof Cd.emitWarning=="function"?Cd.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`);},Za=globalThis.AbortController,Cf=globalThis.AbortSignal;if(typeof Za>"u"){Cf=class{onabort;_onabort=[];reason;aborted=false;addEventListener(n,s){this._onabort.push(s);}},Za=class{constructor(){e();}signal=new Cf;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=true;for(let s of this.signal._onabort)s(n);this.signal.onabort?.(n);}}};let r=Cd.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=false,wf("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 nk=r=>!xf.has(r);var vs=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Tf=r=>vs(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?Fr:null:null,Fr=class extends Array{constructor(e){super(e),this.fill(0);}},xd=class r{heap;length;static#e=false;static create(e){let t=Tf(e);if(!t)return [];r.#e=true;let n=new r(e,t);return r.#e=false,n}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]}},Yo=class r{#e;#t;#o;#s;#i;#C;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#d;#a;#l;#r;#f;#y;#m;#p;#T;#h;#S;#k;#v;#x;#w;#g;static unsafeExposeInternals(e){return {starts:e.#k,ttls:e.#v,sizes:e.#S,keyMap:e.#a,keyList:e.#l,valList:e.#r,next:e.#f,prev:e.#y,get head(){return e.#m},get tail(){return e.#p},free:e.#T,isBackgroundFetch:t=>e.#u(t),backgroundFetch:(t,n,s,o)=>e.#B(t,n,s,o),moveToTail:t=>e.#U(t),indexes:t=>e.#I(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.#d}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#C}get dispose(){return this.#o}get disposeAfter(){return this.#s}constructor(e){let{max:t=0,ttl:n,ttlResolution:s=1,ttlAutopurge:o,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:m,maxSize:g=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:v,memoMethod:b,noDeleteOnFetchRejection:C,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:I,allowStaleOnFetchAbort:M,ignoreFetchAbort:N}=e;if(t!==0&&!vs(t))throw new TypeError("max option must be a nonnegative integer");let R=t?Tf(t):Array;if(!R)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=g,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.#C=b,v!==void 0&&typeof v!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=v,this.#w=!!v,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#r=new Array(t).fill(void 0),this.#f=new R(t),this.#y=new R(t),this.#m=0,this.#p=0,this.#T=xd.create(t),this.#c=0,this.#d=0,typeof c=="function"&&(this.#o=c),typeof u=="function"?(this.#s=u,this.#h=[]):(this.#s=void 0,this.#h=void 0),this.#x=!!this.#o,this.#g=!!this.#s,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!C,this.allowStaleOnFetchRejection=!!I,this.allowStaleOnFetchAbort=!!M,this.ignoreFetchAbort=!!N,this.maxEntrySize!==0){if(this.#t!==0&&!vs(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!vs(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#M();}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=vs(s)||s===0?s:1,this.ttlAutopurge=!!o,this.ttl=n||0,this.ttl){if(!vs(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#A();}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 O="LRU_CACHE_UNBOUNDED";nk(O)&&(xf.add(O),wf("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",O,r));}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#A(){let e=new Fr(this.#e),t=new Fr(this.#e);this.#v=e,this.#k=t,this.#R=(o,i,a=Br.now())=>{if(t[o]=i!==0?a:0,e[o]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#b(o)&&this.#P(this.#l[o],"expire");},i+1);l.unref&&l.unref();}},this.#_=o=>{t[o]=e[o]!==0?Br.now():0;},this.#n=(o,i)=>{if(e[i]){let a=e[i],l=t[i];if(!a||!l)return;o.ttl=a,o.start=l,o.now=n||s();let c=o.now-l;o.remainingTTL=a-c;}};let n=0,s=()=>{let o=Br.now();if(this.ttlResolution>0){n=o;let i=setTimeout(()=>n=0,this.ttlResolution);i.unref&&i.unref();}return o};this.getRemainingTTL=o=>{let i=this.#a.get(o);if(i===void 0)return 0;let a=e[i],l=t[i];if(!a||!l)return 1/0;let c=(n||s())-l;return a-c},this.#b=o=>{let i=t[o],a=e[o];return !!a&&!!i&&(n||s())-i>a};}#_=()=>{};#n=()=>{};#R=()=>{};#b=()=>false;#M(){let e=new Fr(this.#e);this.#d=0,this.#S=e,this.#D=t=>{this.#d-=e[t],e[t]=0;},this.#L=(t,n,s,o)=>{if(this.#u(n))return 0;if(!vs(s))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(s=o(n,t),!vs(s))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 s},this.#N=(t,n,s)=>{if(e[t]=n,this.#t){let o=this.#t-e[t];for(;this.#d>o;)this.#O(true);}this.#d+=e[t],s&&(s.entrySize=n,s.totalCalculatedSize=this.#d);};}#D=e=>{};#N=(e,t,n)=>{};#L=(e,t,n,s)=>{if(n||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#m));)t=this.#y[t];}*#E({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#$(t)||((e||!this.#b(t))&&(yield t),t===this.#p));)t=this.#f[t];}#$(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#I())this.#r[e]!==void 0&&this.#l[e]!==void 0&&!this.#u(this.#r[e])&&(yield [this.#l[e],this.#r[e]]);}*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.#I()){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.#I())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 n of this.#I()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;if(o!==void 0&&e(o,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#I()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;o!==void 0&&e.call(t,o,this.#l[n],this);}}rforEach(e,t=this){for(let n of this.#E()){let s=this.#r[n],o=this.#u(s)?s.__staleWhileFetching:s;o!==void 0&&e.call(t,o,this.#l[n],this);}}purgeStale(){let e=false;for(let t of this.#E({allowStale:true}))this.#b(t)&&(this.#P(this.#l[t],"expire"),e=true);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#r[t],s=this.#u(n)?n.__staleWhileFetching:n;if(s===void 0)return;let o={value:s};if(this.#v&&this.#k){let i=this.#v[t],a=this.#k[t];if(i&&a){let l=i-(Br.now()-a);o.ttl=l,o.start=Date.now();}}return this.#S&&(o.size=this.#S[t]),o}dump(){let e=[];for(let t of this.#I({allowStale:true})){let n=this.#l[t],s=this.#r[t],o=this.#u(s)?s.__staleWhileFetching:s;if(o===void 0||n===void 0)continue;let i={value:o};if(this.#v&&this.#k){i.ttl=this.#v[t];let a=Br.now()-this.#k[t];i.start=Math.floor(Date.now()-a);}this.#S&&(i.size=this.#S[t]),e.unshift([n,i]);}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let s=Date.now()-n.start;n.start=Br.now()-s;}this.set(t,n.value,n);}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:s=this.ttl,start:o,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,u=this.#L(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=true),this.#P(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#p:this.#T.length!==0?this.#T.pop():this.#c===this.#e?this.#O(false):this.#c,this.#l[d]=e,this.#r[d]=t,this.#a.set(e,d),this.#f[this.#p]=d,this.#y[d]=this.#p,this.#p=d,this.#c++,this.#N(d,u,l),l&&(l.set="add"),c=false;else {this.#U(d);let m=this.#r[d];if(t!==m){if(this.#w&&this.#u(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=m;g!==void 0&&!i&&(this.#x&&this.#o?.(g,e,"set"),this.#g&&this.#h?.push([g,e,"set"]));}else i||(this.#x&&this.#o?.(m,e,"set"),this.#g&&this.#h?.push([m,e,"set"]));if(this.#D(d),this.#N(d,u,l),this.#r[d]=t,l){l.set="replace";let g=m&&this.#u(m)?m.__staleWhileFetching:m;g!==void 0&&(l.oldValue=g);}}else l&&(l.set="update");}if(s!==0&&!this.#v&&this.#A(),this.#v&&(c||this.#R(d,s,o),l&&this.#n(l,d)),!i&&this.#g&&this.#h){let m=this.#h,g;for(;g=m?.shift();)this.#s?.(...g);}return this}pop(){try{for(;this.#c;){let e=this.#r[this.#m];if(this.#O(!0),this.#u(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#g&&this.#h){let e=this.#h,t;for(;t=e?.shift();)this.#s?.(...t);}}}#O(e){let t=this.#m,n=this.#l[t],s=this.#r[t];return this.#w&&this.#u(s)?s.__abortController.abort(new Error("evicted")):(this.#x||this.#g)&&(this.#x&&this.#o?.(s,n,"evict"),this.#g&&this.#h?.push([s,n,"evict"])),this.#D(t),e&&(this.#l[t]=void 0,this.#r[t]=void 0,this.#T.push(t)),this.#c===1?(this.#m=this.#p=0,this.#T.length=0):this.#m=this.#f[t],this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:s}=t,o=this.#a.get(e);if(o!==void 0){let i=this.#r[o];if(this.#u(i)&&i.__staleWhileFetching===void 0)return false;if(this.#b(o))s&&(s.has="stale",this.#n(s,o));else return n&&this.#_(o),s&&(s.has="hit",this.#n(s,o)),true}else s&&(s.has="miss");return false}peek(e,t={}){let{allowStale:n=this.allowStale}=t,s=this.#a.get(e);if(s===void 0||!n&&this.#b(s))return;let o=this.#r[s];return this.#u(o)?o.__staleWhileFetching:o}#B(e,t,n,s){let o=t===void 0?void 0:this.#r[t];if(this.#u(o))return o;let i=new Za,{signal:a}=n;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let l={signal:i.signal,options:n,context:s},c=(f,v=false)=>{let{aborted:b}=i.signal,C=n.ignoreFetchAbort&&f!==void 0;if(n.status&&(b&&!v?(n.status.fetchAborted=true,n.status.fetchError=i.signal.reason,C&&(n.status.fetchAbortIgnored=true)):n.status.fetchResolved=true),b&&!C&&!v)return d(i.signal.reason);let w=g;return this.#r[t]===g&&(f===void 0?w.__staleWhileFetching?this.#r[t]=w.__staleWhileFetching:this.#P(e,"fetch"):(n.status&&(n.status.fetchUpdated=true),this.set(e,f,l.options))),f},u=f=>(n.status&&(n.status.fetchRejected=true,n.status.fetchError=f),d(f)),d=f=>{let{aborted:v}=i.signal,b=v&&n.allowStaleOnFetchAbort,C=b||n.allowStaleOnFetchRejection,w=C||n.noDeleteOnFetchRejection,I=g;if(this.#r[t]===g&&(!w||I.__staleWhileFetching===void 0?this.#P(e,"fetch"):b||(this.#r[t]=I.__staleWhileFetching)),C)return n.status&&I.__staleWhileFetching!==void 0&&(n.status.returnedStale=true),I.__staleWhileFetching;if(I.__returned===I)throw f},m=(f,v)=>{let b=this.#i?.(e,o,l);b&&b instanceof Promise&&b.then(C=>f(C===void 0?void 0:C),v),i.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(f(void 0),n.allowStaleOnFetchAbort&&(f=C=>c(C,true)));});};n.status&&(n.status.fetchDispatched=true);let g=new Promise(m).then(c,u),h=Object.assign(g,{__abortController:i,__staleWhileFetching:o,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#r[t]=h,h}#u(e){if(!this.#w)return false;let t=e;return !!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof Za}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:v=false,status:b,signal:C}=t;if(!this.#w)return b&&(b.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:o,status:b});let w={allowStale:n,updateAgeOnGet:s,noDeleteOnStaleGet:o,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:g,status:b,signal:C},I=this.#a.get(e);if(I===void 0){b&&(b.fetch="miss");let M=this.#B(e,I,w,f);return M.__returned=M}else {let M=this.#r[I];if(this.#u(M)){let A=n&&M.__staleWhileFetching!==void 0;return b&&(b.fetch="inflight",A&&(b.returnedStale=true)),A?M.__staleWhileFetching:M.__returned=M}let N=this.#b(I);if(!v&&!N)return b&&(b.fetch="hit"),this.#U(I),s&&this.#_(I),b&&this.#n(b,I),M;let R=this.#B(e,I,w,f),k=R.__staleWhileFetching!==void 0&&n;return b&&(b.fetch=N?"stale":"refresh",k&&N&&(b.returnedStale=true)),k?R.__staleWhileFetching:R.__returned=R}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#C;if(!n)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:o,...i}=t,a=this.get(e,i);if(!o&&a!==void 0)return a;let l=n(e,a,{options:i,context:s});return this.set(e,l,i),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:i}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#r[a],c=this.#u(l);return i&&this.#n(i,a),this.#b(a)?(i&&(i.get="stale"),c?(i&&n&&l.__staleWhileFetching!==void 0&&(i.returnedStale=true),n?l.__staleWhileFetching:void 0):(o||this.#P(e,"expire"),i&&n&&(i.returnedStale=true),n?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#U(a),s&&this.#_(a),l))}else i&&(i.get="miss");}#F(e,t){this.#y[t]=e,this.#f[e]=t;}#U(e){e!==this.#p&&(e===this.#m?this.#m=this.#f[e]:this.#F(this.#y[e],this.#f[e]),this.#F(this.#p,e),this.#p=e);}delete(e){return this.#P(e,"delete")}#P(e,t){let n=false;if(this.#c!==0){let s=this.#a.get(e);if(s!==void 0)if(n=true,this.#c===1)this.#G(t);else {this.#D(s);let o=this.#r[s];if(this.#u(o)?o.__abortController.abort(new Error("deleted")):(this.#x||this.#g)&&(this.#x&&this.#o?.(o,e,t),this.#g&&this.#h?.push([o,e,t])),this.#a.delete(e),this.#l[s]=void 0,this.#r[s]=void 0,s===this.#p)this.#p=this.#y[s];else if(s===this.#m)this.#m=this.#f[s];else {let i=this.#y[s];this.#f[i]=this.#f[s];let a=this.#f[s];this.#y[a]=this.#y[s];}this.#c--,this.#T.push(s);}}if(this.#g&&this.#h?.length){let s=this.#h,o;for(;o=s?.shift();)this.#s?.(...o);}return n}clear(){return this.#G("delete")}#G(e){for(let t of this.#E({allowStale:true})){let n=this.#r[t];if(this.#u(n))n.__abortController.abort(new Error("deleted"));else {let s=this.#l[t];this.#x&&this.#o?.(n,s,e),this.#g&&this.#h?.push([n,s,e]);}}if(this.#a.clear(),this.#r.fill(void 0),this.#l.fill(void 0),this.#v&&this.#k&&(this.#v.fill(0),this.#k.fill(0)),this.#S&&this.#S.fill(0),this.#m=0,this.#p=0,this.#T.length=0,this.#d=0,this.#c=0,this.#g&&this.#h){let t=this.#h,n;for(;n=t?.shift();)this.#s?.(...n);}}};var Sf=typeof process=="object"&&process?process:{stdout:null,stderr:null},rk=r=>!!r&&typeof r=="object"&&(r instanceof xs||r instanceof Ef||ok(r)||ik(r)),ok=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.pipe=="function"&&r.pipe!==Ef.Writable.prototype.pipe,ik=r=>!!r&&typeof r=="object"&&r instanceof EventEmitter&&typeof r.write=="function"&&typeof r.end=="function",Qn=Symbol("EOF"),Zn=Symbol("maybeEmitEnd"),Cs=Symbol("emittedEnd"),el=Symbol("emittingEnd"),Xo=Symbol("emittedError"),tl=Symbol("closed"),kf=Symbol("read"),nl=Symbol("flush"),_f=Symbol("flushChunk"),bn=Symbol("encoding"),Ur=Symbol("decoder"),ut=Symbol("flowing"),Qo=Symbol("paused"),Gr=Symbol("resume"),dt=Symbol("buffer"),Nt=Symbol("pipes"),pt=Symbol("bufferLength"),wd=Symbol("bufferPush"),sl=Symbol("bufferShift"),It=Symbol("objectMode"),Qe=Symbol("destroyed"),Td=Symbol("error"),Sd=Symbol("emitData"),If=Symbol("emitEnd"),kd=Symbol("emitEnd2"),Rn=Symbol("async"),_d=Symbol("abort"),rl=Symbol("aborted"),Zo=Symbol("signal"),Ks=Symbol("dataListeners"),Xt=Symbol("discarded"),ei=r=>Promise.resolve().then(r),ak=r=>r(),lk=r=>r==="end"||r==="finish"||r==="prefinish",ck=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,uk=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),ol=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[Gr](),this.dest.on("drain",this.ondrain);}unpipe(){this.dest.removeListener("drain",this.ondrain);}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end();}},Id=class extends ol{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe();}constructor(e,t,n){super(e,t,n),this.proxyErrors=s=>t.emit("error",s),e.on("error",this.proxyErrors);}},dk=r=>!!r.objectMode,pk=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",xs=class extends EventEmitter{[ut]=false;[Qo]=false;[Nt]=[];[dt]=[];[It];[bn];[Rn];[Ur];[Qn]=false;[Cs]=false;[el]=false;[tl]=false;[Xo]=null;[pt]=0;[Qe]=false;[Zo];[rl]=false;[Ks]=0;[Xt]=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");dk(t)?(this[It]=true,this[bn]=null):pk(t)?(this[bn]=t.encoding,this[It]=false):(this[It]=false,this[bn]=null),this[Rn]=!!t.async,this[Ur]=this[bn]?new StringDecoder(this[bn]):null,t&&t.debugExposeBuffer===true&&Object.defineProperty(this,"buffer",{get:()=>this[dt]}),t&&t.debugExposePipes===true&&Object.defineProperty(this,"pipes",{get:()=>this[Nt]});let{signal:n}=t;n&&(this[Zo]=n,n.aborted?this[_d]():n.addEventListener("abort",()=>this[_d]()));}get bufferLength(){return this[pt]}get encoding(){return this[bn]}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[It]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Rn]}set async(e){this[Rn]=this[Rn]||!!e;}[_d](){this[rl]=true,this.emit("abort",this[Zo]?.reason),this.destroy(this[Zo]?.reason);}get aborted(){return this[rl]}set aborted(e){}write(e,t,n){if(this[rl])return false;if(this[Qn])throw new Error("write after end");if(this[Qe])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),true;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let s=this[Rn]?ei:ak;if(!this[It]&&!Buffer.isBuffer(e)){if(uk(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(ck(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[It]?(this[ut]&&this[pt]!==0&&this[nl](true),this[ut]?this.emit("data",e):this[wd](e),this[pt]!==0&&this.emit("readable"),n&&s(n),this[ut]):e.length?(typeof e=="string"&&!(t===this[bn]&&!this[Ur]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[bn]&&(e=this[Ur].write(e)),this[ut]&&this[pt]!==0&&this[nl](true),this[ut]?this.emit("data",e):this[wd](e),this[pt]!==0&&this.emit("readable"),n&&s(n),this[ut]):(this[pt]!==0&&this.emit("readable"),n&&s(n),this[ut])}read(e){if(this[Qe])return null;if(this[Xt]=false,this[pt]===0||e===0||e&&e>this[pt])return this[Zn](),null;this[It]&&(e=null),this[dt].length>1&&!this[It]&&(this[dt]=[this[bn]?this[dt].join(""):Buffer.concat(this[dt],this[pt])]);let t=this[kf](e||null,this[dt][0]);return this[Zn](),t}[kf](e,t){if(this[It])this[sl]();else {let n=t;e===n.length||e===null?this[sl]():typeof n=="string"?(this[dt][0]=n.slice(e),t=n.slice(0,e),this[pt]-=e):(this[dt][0]=n.subarray(e),t=n.subarray(0,e),this[pt]-=e);}return this.emit("data",t),!this[dt].length&&!this[Qn]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Qn]=true,this.writable=false,(this[ut]||!this[Qo])&&this[Zn](),this}[Gr](){this[Qe]||(!this[Ks]&&!this[Nt].length&&(this[Xt]=true),this[Qo]=false,this[ut]=true,this.emit("resume"),this[dt].length?this[nl]():this[Qn]?this[Zn]():this.emit("drain"));}resume(){return this[Gr]()}pause(){this[ut]=false,this[Qo]=true,this[Xt]=false;}get destroyed(){return this[Qe]}get flowing(){return this[ut]}get paused(){return this[Qo]}[wd](e){this[It]?this[pt]+=1:this[pt]+=e.length,this[dt].push(e);}[sl](){return this[It]?this[pt]-=1:this[pt]-=this[dt][0].length,this[dt].shift()}[nl](e=false){do;while(this[_f](this[sl]())&&this[dt].length);!e&&!this[dt].length&&!this[Qn]&&this.emit("drain");}[_f](e){return this.emit("data",e),this[ut]}pipe(e,t){if(this[Qe])return e;this[Xt]=false;let n=this[Cs];return t=t||{},e===Sf.stdout||e===Sf.stderr?t.end=false:t.end=t.end!==false,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[Nt].push(t.proxyErrors?new Id(this,e,t):new ol(this,e,t)),this[Rn]?ei(()=>this[Gr]()):this[Gr]()),e}unpipe(e){let t=this[Nt].find(n=>n.dest===e);t&&(this[Nt].length===1?(this[ut]&&this[Ks]===0&&(this[ut]=false),this[Nt]=[]):this[Nt].splice(this[Nt].indexOf(t),1),t.unpipe());}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[Xt]=false,this[Ks]++,!this[Nt].length&&!this[ut]&&this[Gr]();else if(e==="readable"&&this[pt]!==0)super.emit("readable");else if(lk(e)&&this[Cs])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Xo]){let s=t;this[Rn]?ei(()=>s.call(this,this[Xo])):s.call(this,this[Xo]);}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Ks]=this.listeners("data").length,this[Ks]===0&&!this[Xt]&&!this[Nt].length&&(this[ut]=false)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return (e==="data"||e===void 0)&&(this[Ks]=0,!this[Xt]&&!this[Nt].length&&(this[ut]=false)),t}get emittedEnd(){return this[Cs]}[Zn](){!this[el]&&!this[Cs]&&!this[Qe]&&this[dt].length===0&&this[Qn]&&(this[el]=true,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[tl]&&this.emit("close"),this[el]=false);}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==Qe&&this[Qe])return false;if(e==="data")return !this[It]&&!n?false:this[Rn]?(ei(()=>this[Sd](n)),true):this[Sd](n);if(e==="end")return this[If]();if(e==="close"){if(this[tl]=true,!this[Cs]&&!this[Qe])return false;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(e==="error"){this[Xo]=n,super.emit(Td,n);let o=!this[Zo]||this.listeners("error").length?super.emit("error",n):false;return this[Zn](),o}else if(e==="resume"){let o=super.emit("resume");return this[Zn](),o}else if(e==="finish"||e==="prefinish"){let o=super.emit(e);return this.removeAllListeners(e),o}let s=super.emit(e,...t);return this[Zn](),s}[Sd](e){for(let n of this[Nt])n.dest.write(e)===false&&this.pause();let t=this[Xt]?false:super.emit("data",e);return this[Zn](),t}[If](){return this[Cs]?false:(this[Cs]=true,this.readable=false,this[Rn]?(ei(()=>this[kd]()),true):this[kd]())}[kd](){if(this[Ur]){let t=this[Ur].end();if(t){for(let n of this[Nt])n.dest.write(t);this[Xt]||super.emit("data",t);}}for(let t of this[Nt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[It]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[It]||(e.dataLength+=n.length);}),await t,e}async concat(){if(this[It])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[bn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(Qe,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e());})}[Symbol.asyncIterator](){this[Xt]=false;let e=false,t=async()=>(this.pause(),e=true,{value:void 0,done:true});return {next:()=>{if(e)return t();let s=this.read();if(s!==null)return Promise.resolve({done:false,value:s});if(this[Qn])return t();let o,i,a=d=>{this.off("data",l),this.off("end",c),this.off(Qe,u),t(),i(d);},l=d=>{this.off("error",a),this.off("end",c),this.off(Qe,u),this.pause(),o({value:d,done:!!this[Qn]});},c=()=>{this.off("error",a),this.off("data",l),this.off(Qe,u),t(),o({done:true,value:void 0});},u=()=>a(new Error("stream destroyed"));return new Promise((d,m)=>{i=m,o=d,this.once(Qe,u),this.once("error",a),this.once("end",c),this.once("data",l);})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Xt]=false;let e=false,t=()=>(this.pause(),this.off(Td,t),this.off(Qe,t),this.off("end",t),e=true,{done:true,value:void 0}),n=()=>{if(e)return t();let s=this.read();return s===null?t():{done:false,value:s}};return this.once("end",t),this.once(Td,t),this.once(Qe,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[Qe])return e?this.emit("error",e):this.emit(Qe),this;this[Qe]=true,this[Xt]=true,this[dt].length=0,this[pt]=0;let t=this;return typeof t.close=="function"&&!this[tl]&&t.close(),e?this.emit("error",e):this.emit(Qe),this}static get isStream(){return rk}};var xk=realpathSync.native,ni={lstatSync:lstatSync,readdir:readdir$1,readdirSync:readdirSync,readlinkSync:readlinkSync,realpathSync:xk,promises:{lstat:lstat,readdir:readdir,readlink:readlink,realpath:realpath}},Df=r=>!r||r===ni||r===Ze?ni:{...ni,...r,promises:{...ni.promises,...r.promises||{}}},Nf=/^\\\\\?\\([a-z]:)\\?$/i,_k=r=>r.replace(/\//g,"\\").replace(Nf,"$1\\"),Ik=/[\\\/]/,un=0,Lf=1,$f=2,Dn=4,Of=6,Bf=8,Js=10,Ff=12,cn=15,ti=~cn,Ad=16,Af=32,si=64,vn=128,il=256,ll=512,Mf=si|vn|ll,Ek=1023,Md=r=>r.isFile()?Bf:r.isDirectory()?Dn:r.isSymbolicLink()?Js:r.isCharacterDevice()?$f:r.isBlockDevice()?Of:r.isSocket()?Ff:r.isFIFO()?Lf:un,Pf=new Map,ri=r=>{let e=Pf.get(r);if(e)return e;let t=r.normalize("NFKD");return Pf.set(r,t),t},Rf=new Map,al=r=>{let e=Rf.get(r);if(e)return e;let t=ri(r.toLowerCase());return Rf.set(r,t),t},cl=class extends Yo{constructor(){super({max:256});}},Rd=class extends Yo{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1});}},Uf=Symbol("PathScurry setAsCwd"),Et=class{name;root;roots;parent;nocase;isCWD=false;#e;#t;get dev(){return this.#t}#o;get mode(){return this.#o}#s;get nlink(){return this.#s}#i;get uid(){return this.#i}#C;get gid(){return this.#C}#c;get rdev(){return this.#c}#d;get blksize(){return this.#d}#a;get ino(){return this.#a}#l;get size(){return this.#l}#r;get blocks(){return this.#r}#f;get atimeMs(){return this.#f}#y;get mtimeMs(){return this.#y}#m;get ctimeMs(){return this.#m}#p;get birthtimeMs(){return this.#p}#T;get atime(){return this.#T}#h;get mtime(){return this.#h}#S;get ctime(){return this.#S}#k;get birthtime(){return this.#k}#v;#x;#w;#g;#A;#_;#n;#R;#b;#M;get parentPath(){return (this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=un,n,s,o,i,a){this.name=e,this.#v=o?al(e):ri(e),this.#n=t&Ek,this.nocase=o,this.roots=s,this.root=n||this,this.#R=i,this.#w=a.fullpath,this.#A=a.relative,this.#_=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=Df(a.fs);}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#R}resolve(e){if(!e)return this;let t=this.getRootString(e),s=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#D(s):this.#D(s)}#D(e){let t=this;for(let n of e)t=t.child(n);return t}children(){let e=this.#R.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#R.set(this,t),this.#n&=~Ad,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),s=this.nocase?al(e):ri(e);for(let l of n)if(l.#v===s)return l;let o=this.parent?this.sep:"",i=this.#w?this.#w+o+e:void 0,a=this.newChild(e,un,{...t,parent:this,fullpath:i});return this.canReaddir()||(a.#n|=vn),n.push(a),a}relative(){if(this.isCWD)return "";if(this.#A!==void 0)return this.#A;let e=this.name,t=this.parent;if(!t)return this.#A=this.name;let n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return "";if(this.#_!==void 0)return this.#_;let e=this.name,t=this.parent;if(!t)return this.#_=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#w!==void 0)return this.#w;let e=this.name,t=this.parent;if(!t)return this.#w=this.name;let s=t.fullpath()+(t.parent?this.sep:"")+e;return this.#w=s}fullpathPosix(){if(this.#g!==void 0)return this.#g;if(this.sep==="/")return this.#g=this.fullpath();if(!this.parent){let s=this.fullpath().replace(/\\/g,"/");return /^[a-z]:\//i.test(s)?this.#g=`//?/${s}`:this.#g=s}let e=this.parent,t=e.fullpathPosix(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#g=n}isUnknown(){return (this.#n&cn)===un}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return (this.#n&cn)===Bf}isDirectory(){return (this.#n&cn)===Dn}isCharacterDevice(){return (this.#n&cn)===$f}isBlockDevice(){return (this.#n&cn)===Of}isFIFO(){return (this.#n&cn)===Lf}isSocket(){return (this.#n&cn)===Ff}isSymbolicLink(){return (this.#n&Js)===Js}lstatCached(){return this.#n&Af?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.#n&cn;return !(e!==un&&e!==Js||this.#n&il||this.#n&vn)}calledReaddir(){return !!(this.#n&Ad)}isENOENT(){return !!(this.#n&vn)}isNamed(e){return this.nocase?this.#v===al(e):this.#v===ri(e)}async readlink(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}readlinkSync(){let e=this.#b;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#b=n}catch(t){this.#u(t.code);return}}#N(e){this.#n|=Ad;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#L();}}#L(){this.#n&vn||(this.#n=(this.#n|vn)&ti,this.#I());}#I(){let e=this.children();e.provisional=0;for(let t of e)t.#L();}#E(){this.#n|=ll,this.#$();}#$(){if(this.#n&si)return;let e=this.#n;(e&cn)===Dn&&(e&=ti),this.#n=e|si,this.#I();}#O(e=""){e==="ENOTDIR"||e==="EPERM"?this.#$():e==="ENOENT"?this.#L():this.children().provisional=0;}#B(e=""){e==="ENOTDIR"?this.parent.#$():e==="ENOENT"&&this.#L();}#u(e=""){let t=this.#n;t|=il,e==="ENOENT"&&(t|=vn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=ti),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#$();}#F(e,t){return this.#P(e,t)||this.#U(e,t)}#U(e,t){let n=Md(e),s=this.newChild(e.name,n,{parent:this}),o=s.#n&cn;return o!==Dn&&o!==Js&&o!==un&&(s.#n|=si),t.unshift(s),t.provisional++,s}#P(e,t){for(let n=t.provisional;n<t.length;n++){let s=t[n];if((this.nocase?al(e.name):ri(e.name))===s.#v)return this.#G(e,s,n,t)}}#G(e,t,n,s){let o=t.name;return t.#n=t.#n&ti|Md(e),o!==e.name&&(t.name=e.name),n!==s.provisional&&(n===s.length-1?s.pop():s.splice(n,1),s.unshift(t)),s.provisional++,t}async lstat(){if((this.#n&vn)===0)try{return this.#z(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#B(e.code);}}lstatSync(){if((this.#n&vn)===0)try{return this.#z(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#B(e.code);}}#z(e){let{atime:t,atimeMs:n,birthtime:s,birthtimeMs:o,blksize:i,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:d,ino:m,mode:g,mtime:h,mtimeMs:f,nlink:v,rdev:b,size:C,uid:w}=e;this.#T=t,this.#f=n,this.#k=s,this.#p=o,this.#d=i,this.#r=a,this.#S=l,this.#m=c,this.#t=u,this.#C=d,this.#a=m,this.#o=g,this.#h=h,this.#y=f,this.#s=v,this.#c=b,this.#l=C,this.#i=w;let I=Md(e);this.#n=this.#n&ti|I|Af,I!==un&&I!==Dn&&I!==Js&&(this.#n|=si);}#W=[];#H=false;#q(e){this.#H=false;let t=this.#W.slice();this.#W.length=0,t.forEach(n=>n(null,e));}readdirCB(e,t=false){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let o=n.slice(0,n.provisional);t?e(null,o):queueMicrotask(()=>e(null,o));return}if(this.#W.push(e),this.#H)return;this.#H=true;let s=this.fullpath();this.#e.readdir(s,{withFileTypes:true},(o,i)=>{if(o)this.#O(o.code),n.provisional=0;else {for(let a of i)this.#F(a,n);this.#N(n);}this.#q(n.slice(0,n.provisional));});}#j;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.#j)await this.#j;else {let n=()=>{};this.#j=new Promise(s=>n=s);try{for(let s of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#F(s,e);this.#N(e);}catch(s){this.#O(s.code),e.provisional=0;}this.#j=void 0,n();}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return [];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#F(n,e);this.#N(e);}catch(n){this.#O(n.code),e.provisional=0;}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&Mf)return false;let e=cn&this.#n;return e===un||e===Dn||e===Js}shouldWalk(e,t){return (this.#n&Dn)===Dn&&!(this.#n&Mf)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#M)return this.#M;if(!((ll|il|vn)&this.#n))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(!((ll|il|vn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#M=this.resolve(e)}catch{this.#E();}}[Uf](e){if(e===this)return;e.isCWD=false,this.isCWD=true;let t=new Set([]),n=[],s=this;for(;s&&s.parent;)t.add(s),s.#A=n.join(this.sep),s.#_=n.join("/"),s=s.parent,n.push("..");for(s=e;s&&s.parent&&!t.has(s);)s.#A=void 0,s.#_=void 0,s=s.parent;}},ul=class r extends Et{sep="\\";splitSep=Ik;constructor(e,t=un,n,s,o,i,a){super(e,t,n,s,o,i,a);}newChild(e,t=un,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return win32.parse(e).root}getRoot(e){if(e=_k(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new jr(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(Nf,"$1\\"),e===t}},dl=class r extends Et{splitSep="/";sep="/";constructor(e,t=un,n,s,o,i,a){super(e,t,n,s,o,i,a);}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=un,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},pl=class{root;rootPath;roots;cwd;#e;#t;#o;nocase;#s;constructor(e=process.cwd(),t,n,{nocase:s,childrenCacheSize:o=16*1024,fs:i=ni}={}){this.#s=Df(i),(e instanceof URL||e.startsWith("file://"))&&(e=fileURLToPath(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new cl,this.#t=new cl,this.#o=new Rd(o);let l=a.substring(this.rootPath.length).split(n);if(l.length===1&&!l[0]&&l.pop(),s===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=s,this.root=this.newRoot(this.#s),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,m=this.rootPath,g=false;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:m+=(g?"":d)+h}),g=true;}this.cwd=c;}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#o}resolve(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#e.get(t);if(n!==void 0)return n;let s=this.cwd.resolve(t).fullpath();return this.#e.set(t,s),s}resolvePosix(...e){let t="";for(let o=e.length-1;o>=0;o--){let i=e[o];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#t.get(t);if(n!==void 0)return n;let s=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,s),s}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 Et||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let s=await e.readdir();return n?s:s.map(o=>o.name)}else return []}readdirSync(e=this.cwd,t={withFileTypes:true}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true}=t;return e.canReaddir()?n?e.readdirSync():e.readdirSync().map(s=>s.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 Et||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:false}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(n?e:e.fullpath());let l=new Set,c=(d,m)=>{l.add(d),d.readdirCB((g,h)=>{if(g)return m(g);let f=h.length;if(!f)return m();let v=()=>{--f===0&&m();};for(let b of h)(!o||o(b))&&a.push(n?b:b.fullpath()),s&&b.isSymbolicLink()?b.realpath().then(C=>C?.isUnknown()?C.lstat():C).then(C=>C?.shouldWalk(l,i)?c(C,v):v()):b.shouldWalk(l,i)?c(b,v):v();},true);},u=e;return new Promise((d,m)=>{c(u,g=>{if(g)return m(g);d(a);});})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=[];(!o||o(e))&&a.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!o||o(d))&&a.push(n?d:d.fullpath());let m=d;if(d.isSymbolicLink()){if(!(s&&(m=d.realpathSync())))continue;m.isUnknown()&&m.lstatSync();}m.shouldWalk(l,i)&&l.add(m);}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(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 Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t;(!o||o(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!o||o(u))&&(yield n?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(s&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync();}d.shouldWalk(a,i)&&a.add(d);}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=new xs({objectMode:true});(!o||o(e))&&a.write(n?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let m=false;for(;!m;){let g=c.shift();if(!g){u===0&&a.end();return}u++,l.add(g);let h=(v,b,C=false)=>{if(v)return a.emit("error",v);if(s&&!C){let w=[];for(let I of b)I.isSymbolicLink()&&w.push(I.realpath().then(M=>M?.isUnknown()?M.lstat():M));if(w.length){Promise.all(w).then(()=>h(null,b,true));return}}for(let w of b)w&&(!o||o(w))&&(a.write(n?w:w.fullpath())||(m=true));u--;for(let w of b){let I=w.realpathCached()||w;I.shouldWalk(l,i)&&c.push(I);}m&&!a.flowing?a.once("drain",d):f||d();},f=true;g.readdirCB(h,true),f=false;}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof Et||(t=e,e=this.cwd);let{withFileTypes:n=true,follow:s=false,filter:o,walkFilter:i}=t,a=new xs({objectMode:true}),l=new Set;(!o||o(e))&&a.write(n?e:e.fullpath());let c=[e],u=0,d=()=>{let m=false;for(;!m;){let g=c.shift();if(!g){u===0&&a.end();return}u++,l.add(g);let h=g.readdirSync();for(let f of h)(!o||o(f))&&(a.write(n?f:f.fullpath())||(m=true));u--;for(let f of h){let v=f;if(f.isSymbolicLink()){if(!(s&&(v=f.realpathSync())))continue;v.isUnknown()&&v.lstatSync();}v.shouldWalk(l,i)&&c.push(v);}}m&&!a.flowing&&a.once("drain",d);};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[Uf](t);}},jr=class extends pl{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,win32,"\\",{...t,nocase:n}),this.nocase=n;for(let s=this.cwd;s;s=s.parent)s.nocase=this.nocase;}parseRootPath(e){return win32.parse(e).root.toUpperCase()}newRoot(e){return new ul(this.rootPath,Dn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Wr=class extends pl{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=false}=t;super(e,posix,"/",{...t,nocase:n}),this.nocase=n;}parseRootPath(e){return "/"}newRoot(e){return new dl(this.rootPath,Dn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},oi=class extends Wr{constructor(e=process.cwd(),t={}){let{nocase:n=true}=t;super(e,{...t,nocase:n});}};process.platform==="win32"?ul:dl;var Gf=process.platform==="win32"?jr:process.platform==="darwin"?oi:Wr;var Ak=r=>r.length>=1,Mk=r=>r.length>=1,Hr=class r{#e;#t;#o;length;#s;#i;#C;#c;#d;#a;#l=true;constructor(e,t,n,s){if(!Ak(e))throw new TypeError("empty pattern list");if(!Mk(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#o=n,this.#s=s,this.#o===0){if(this.isUNC()){let[o,i,a,l,...c]=this.#e,[u,d,m,g,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[o,i,a,l,""].join("/"),v=[u,d,m,g,""].join("/");this.#e=[f,...c],this.#t=[v,...h],this.length=this.#e.length;}else if(this.isDrive()||this.isAbsolute()){let[o,...i]=this.#e,[a,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=o+"/",u=a+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length;}}}pattern(){return this.#e[this.#o]}isString(){return typeof this.#e[this.#o]=="string"}isGlobstar(){return this.#e[this.#o]===yt}isRegExp(){return this.#e[this.#o]instanceof RegExp}globString(){return this.#C=this.#C||(this.#o===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#o).join("/"))}hasMore(){return this.length>this.#o+1}rest(){return this.#i!==void 0?this.#i:this.hasMore()?(this.#i=new r(this.#e,this.#t,this.#o+1,this.#s),this.#i.#a=this.#a,this.#i.#d=this.#d,this.#i.#c=this.#c,this.#i):this.#i=null}isUNC(){let e=this.#e;return this.#d!==void 0?this.#d:this.#d=this.#s==="win32"&&this.#o===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#s==="win32"&&this.#o===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#o===0?e:""}checkFollowGlobstar(){return !(this.#o===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#o===0||!this.isGlobstar()||!this.#l?false:(this.#l=false,true)}};var Pk=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",zr=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:s,noglobstar:o,platform:i=Pk}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:true,nobrace:t,nocase:n,noext:s,noglobstar:o,optimizationLevel:2,platform:i,nocomment:true,nonegate:true};for(let a of e)this.add(a);}add(e){let t=new Yt(e,this.mmopts);for(let n=0;n<t.set.length;n++){let s=t.set[n],o=t.globParts[n];if(!s||!o)throw new Error("invalid pattern object");for(;s[0]==="."&&o[0]===".";)s.shift(),o.shift();let i=new Hr(s,o,0,this.platform),a=new Yt(i.globString(),this.mmopts),l=o[o.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a));}}ignored(e){let t=e.fullpath(),n=`${t}/`,s=e.relative()||".",o=`${s}/`;for(let i of this.relative)if(i.match(s)||i.match(o))return true;for(let i of this.absolute)if(i.match(t)||i.match(n))return true;return false}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let s of this.relativeChildren)if(s.match(n))return true;for(let s of this.absoluteChildren)if(s.match(t))return true;return false}};var Dd=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 n=e.fullpath(),s=this.store.get(n);s?s.add(t.globString()):this.store.set(n,new Set([t.globString()]));}},Nd=class{store=new Map;add(e,t,n){let s=(t?2:0)|(n?1:0),o=this.store.get(e);this.store.set(e,o===void 0?s:s&o);}entries(){return [...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Ld=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(s=>s.globString()===t.globString())||n.push(t):this.store.set(e,[t]);}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return [...this.store.keys()].filter(e=>e.canReaddir())}},ii=class r{hasWalkedCache;matches=new Nd;subwalks=new Ld;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new Dd;}processPatterns(e,t){this.patterns=t;let n=t.map(s=>[e,s]);for(let[s,o]of n){this.hasWalkedCache.storeWalked(s,o);let i=o.root(),a=o.isAbsolute()&&this.opts.absolute!==false;if(i){s=s.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=o.rest();if(d)o=d;else {this.matches.add(s,true,false);continue}}if(s.isENOENT())continue;let l,c,u=false;for(;typeof(l=o.pattern())=="string"&&(c=o.rest());)s=s.resolve(l),o=c,u=true;if(l=o.pattern(),c=o.rest(),u){if(this.hasWalkedCache.hasWalked(s,o))continue;this.hasWalkedCache.storeWalked(s,o);}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(s.resolve(l),a,d);continue}else if(l===yt){(!s.isSymbolicLink()||this.follow||o.checkFollowGlobstar())&&this.subwalks.add(s,o);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(s,a,d===""||d===".");else if(d===".."){let g=s.parent||s;m?this.hasWalkedCache.hasWalked(g,m)||this.subwalks.add(g,m):this.matches.add(g,a,true);}}else l instanceof RegExp&&this.subwalks.add(s,o);}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),s=this.child();for(let o of t)for(let i of n){let a=i.isAbsolute(),l=i.pattern(),c=i.rest();l===yt?s.testGlobstar(o,i,c,a):l instanceof RegExp?s.testRegExp(o,l,c,a):s.testString(o,l,c,a);}return s}testGlobstar(e,t,n,s){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,s,false),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let o=n.pattern();if(typeof o=="string"&&o!==".."&&o!==""&&o!==".")this.testString(e,o,n.rest(),s);else if(o===".."){let i=e.parent||e;this.subwalks.add(i,n);}else o instanceof RegExp&&this.testRegExp(e,o,n.rest(),s);}}testRegExp(e,t,n,s){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,s,false));}testString(e,t,n,s){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,s,false));}};var Rk=(r,e)=>typeof r=="string"?new zr([r],e):Array.isArray(r)?new zr(r,e):r,ml=class{path;patterns;opts;seen=new Set;paused=false;aborted=false;#e=[];#t;#o;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#o=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==false,(n.ignore||!this.includeChildMatches)&&(this.#t=Rk(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let s="cannot ignore child matches, ignore lacks add() method.";throw new Error(s)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0;}));}#s(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(e){return !!this.#t?.childrenIgnored?.(e)}pause(){this.paused=true;}resume(){if(this.signal?.aborted)return;this.paused=false;let e;for(;!this.paused&&(e=this.#e.shift());)e();}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e());}async matchCheck(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n;}let o=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=await o.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat();}return this.matchCheckTest(o,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#s(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n;}let o=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&o?.isSymbolicLink()){let i=o.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync();}return this.matchCheckTest(o,t)}matchFinish(e,t){if(this.#s(e))return;if(!this.includeChildMatches&&this.#t?.add){let o=`${e.relativePosix()}/**`;this.#t.add(o);}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let s=this.opts.mark&&e.isDirectory()?this.#o:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let o=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(o+s);}else {let o=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!o.startsWith(".."+this.#o)?"."+this.#o:"";this.matchEmit(o?i+o+s:"."+s);}}async match(e,t,n){let s=await this.matchCheck(e,n);s&&this.matchFinish(s,t);}matchSync(e,t,n){let s=this.matchCheckSync(e,n);s&&this.matchFinish(s,t);}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new ii(this.opts),n);}walkCB2(e,t,n,s){if(this.#i(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,s));return}n.processPatterns(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(o++,this.match(a,l,c).then(()=>i()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,n,i):a.readdirCB((c,u)=>this.walkCB3(a,u,n,i),true);}i();}walkCB3(e,t,n,s){n=n.filterEntries(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||(o++,this.match(a,l,c).then(()=>i()));for(let[a,l]of n.subwalks.entries())o++,this.walkCB2(a,l,n.child(),i);i();}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new ii(this.opts),n);}walkCB2Sync(e,t,n,s){if(this.#i(e))return s();if(this.signal?.aborted&&s(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,s));return}n.processPatterns(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;o++;let l=a.readdirSync();this.walkCB3Sync(a,l,n,i);}i();}walkCB3Sync(e,t,n,s){n=n.filterEntries(e,t);let o=1,i=()=>{--o===0&&s();};for(let[a,l,c]of n.matches.entries())this.#s(a)||this.matchSync(a,l,c);for(let[a,l]of n.subwalks.entries())o++,this.walkCB2Sync(a,l,n.child(),i);i();}},ai=class extends ml{matches=new Set;constructor(e,t,n){super(e,t,n);}matchEmit(e){this.matches.add(e);}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches);});}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},li=class extends ml{results;constructor(e,t,n){super(e,t,n),this.results=new xs({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 Nk=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Cn=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||Nk,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"?jr:t.platform==="darwin"?oi:t.platform?Wr:Gf;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs});}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",s={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:true,noext:this.noext,nonegate:true,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},o=this.pattern.map(l=>new Yt(l,s)),[i,a]=o.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new Hr(l,u,0,this.platform)});}async walk(){return [...await new ai(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 ai(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 li(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 li(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 $d=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Yt(t,e).hasMagic())return true;return false};function gl(r,e={}){return new Cn(r,e).streamSync()}function Wf(r,e={}){return new Cn(r,e).stream()}function Hf(r,e={}){return new Cn(r,e).walkSync()}async function jf(r,e={}){return new Cn(r,e).walk()}function hl(r,e={}){return new Cn(r,e).iterateSync()}function zf(r,e={}){return new Cn(r,e).iterate()}var Lk=gl,$k=Object.assign(Wf,{sync:gl}),Ok=hl,Bk=Object.assign(zf,{sync:hl}),Fk=Object.assign(Hf,{stream:gl,iterate:hl}),qr=Object.assign(jf,{glob:jf,globSync:Hf,sync:Fk,globStream:Wf,stream:$k,globStreamSync:gl,streamSync:Lk,globIterate:zf,iterate:Bk,globIterateSync:hl,iterateSync:Ok,Glob:Cn,hasMagic:$d,escape:Or,unescape:yn});qr.glob=qr;var ci=class{languageId="typescript";extensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];async parse(e,t){let n=e.split(`
379
378
  `),s=[],o={class:/^(\s*)(export\s+)?(abstract\s+)?class\s+(\w+)(\s+extends\s+\w+)?(\s+implements\s+[\w,\s]+)?/,interface:/^(\s*)(export\s+)?interface\s+(\w+)(\s+extends\s+[\w,\s]+)?/,type:/^(\s*)(export\s+)?type\s+(\w+)\s*[=<]/,enum:/^(\s*)(export\s+)?enum\s+(\w+)/,function:/^(\s*)(export\s+)?(async\s+)?function\s+(\w+)\s*[<(]/,constFunction:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]\s*(async\s+)?(\([^)]*\)|[a-zA-Z_]\w*)\s*(=>|:.*=>)/,variable:/^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*[=:]/,method:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(async\s+)?(\w+)\s*[<(]/,property:/^(\s+)(public\s+|private\s+|protected\s+)?(static\s+)?(readonly\s+)?(\w+)\s*[=:?]/},i=null,a=0;for(let l=0;l<n.length;l++){let c=n[l],u=l+1;if(i){let f=c.match(/^(\s*)/)?.[1].length||0;c.trim()&&f<=a&&!c.match(/^\s*[})\]]/)&&(i.endLine=l,s.push(i),i=null);}if(c.trim().startsWith("//")||c.trim().startsWith("/*")||!c.trim())continue;let d=c.match(o.class);if(d){if(i&&(i.endLine=l,s.push(i)),a=d[1].length,i={name:d[4],kind:"class",startLine:u,endLine:this.findSymbolEnd(n,l),children:[]},l>0){let f=n[l-1].trim();f.startsWith("/**")||f.startsWith("/*")?i.docstring=this.extractDocstring(n,l-1):f.startsWith("//")&&(i.docstring=f.replace(/^\/\/\s*/,""));}continue}let m=c.match(o.interface);if(m){s.push({name:m[3],kind:"interface",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let g=c.match(o.type);if(g){s.push({name:g[3],kind:"type",startLine:u,endLine:this.findTypeEnd(n,l)});continue}let h=c.match(o.enum);if(h){s.push({name:h[3],kind:"enum",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}if(!i){let f=c.match(o.function);if(f){s.push({name:f[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let v=c.match(o.constFunction);if(v){s.push({name:v[4],kind:"function",startLine:u,endLine:this.findSymbolEnd(n,l)});continue}let b=c.match(o.variable);if(b&&!o.constFunction.test(c)){s.push({name:b[4],kind:"variable",startLine:u,endLine:u});continue}}if(i){let f=c.match(o.method);if(f&&!["if","for","while","switch","catch","constructor"].includes(f[5])){let b={name:f[5],kind:(f[5]==="constructor","method"),startLine:u,endLine:this.findSymbolEnd(n,l),parent:i.name};i.children.push(b);continue}let v=c.match(o.property);if(v&&!["if","for","while","switch","catch","return","const","let","var"].includes(v[5])){let b={name:v[5],kind:"variable",startLine:u,endLine:u,parent:i.name};i.children.push(b);}}}return i&&(i.endLine=n.length,s.push(i)),s}findSymbolEnd(e,t){return bs(e,t)}findTypeEnd(e,t){for(let n=t;n<e.length;n++){let s=e[n];if(s.includes(";")||n>t&&/^(export|type|interface|class|function|const|let|var)/.test(s.trim()))return n+1}return t+1}extractDocstring(e,t){let n=[],s=t;for(;s>=0;){let o=e[s].trim();if(o.startsWith("/**")||o.startsWith("/*"))break;s--;}for(let o=s;o<=t;o++){let i=e[o].trim();i=i.replace(/^\/\*\*?\s*/,"").replace(/\*\/\s*$/,"").replace(/^\*\s?/,""),i&&n.push(i);}return n.join(`
380
379
  `)}buildSymbolPattern(e,t){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");switch(t){case "function":return `(function|async\\s+function|const|let|var)\\s+${n}\\s*[=(<]`;case "class":return `class\\s+${n}(\\s+extends|\\s+implements|\\s*\\{)`;case "interface":return `interface\\s+${n}(\\s+extends|\\s*\\{)`;case "type":return `type\\s+${n}\\s*[=<]`;case "enum":return `enum\\s+${n}\\s*\\{`;case "method":return `(async\\s+)?${n}\\s*\\(`;case "variable":return `(const|let|var)\\s+${n}\\s*[=:]`;default:return `(function|class|interface|type|enum|const|let|var)\\s+${n}|${n}\\s*(=|\\()`}}};var ui=class{languageId="python";extensions=[".py",".pyw"];async parse(e,t){let n=e.split(`
381
380
  `),s=[],o={class:/^(\s*)class\s+(\w+)(\s*\([^)]*\))?\s*:/,function:/^(\s*)(async\s+)?def\s+(\w+)\s*\(/,variable:/^([A-Z][A-Z0-9_]*)\s*[=:]/},i=null,a=-1;for(let l=0;l<n.length;l++){let c=n[l],u=l+1,d=c.match(/^(\s*)/)?.[1].length||0;if(i&&c.trim()&&d<=a&&(i.endLine=l,s.push(i),i=null,a=-1),c.trim().startsWith("#")||!c.trim())continue;let m=c.match(o.class);if(m){i&&(i.endLine=l,s.push(i)),a=m[1].length,i={name:m[2],kind:"class",startLine:u,endLine:this.findClassEnd(n,l,a),children:[],docstring:this.extractDocstring(n,l+1)};continue}let g=c.match(o.function);if(g){let h=g[1].length,f=g[3],v=i&&h>a,b={name:f,kind:v?"method":"function",startLine:u,endLine:this.findFunctionEnd(n,l,h),docstring:this.extractDocstring(n,l+1)};v&&i?(b.parent=i.name,i.children.push(b)):s.push(b);continue}if(!i&&c.match(o.variable)){let h=c.match(o.variable);h&&s.push({name:h[1],kind:"constant",startLine:u,endLine:u});}}return i&&(i.endLine=n.length,s.push(i)),s}findClassEnd(e,t,n){for(let s=t+1;s<e.length;s++){let o=e[s];if(!o.trim())continue;if((o.match(/^(\s*)/)?.[1].length||0)<=n)return s}return e.length}findFunctionEnd(e,t,n){let s=false;for(let o=t+1;o<e.length;o++){let i=e[o];if(!i.trim())continue;let a=i.match(/^(\s*)/)?.[1].length||0;if(a>n){s=true;continue}if(s&&a<=n)return o}return e.length}extractDocstring(e,t){if(t>=e.length)return;let n=e[t].trim();if(n.startsWith('"""')||n.startsWith("'''")){let s=n.startsWith('"""')?'"""':"'''";if(n.endsWith(s)&&n.length>6)return n.slice(3,-3);let o=[n.slice(3)];for(let i=t+1;i<e.length;i++){let a=e[i].trim();if(a.endsWith(s)){o.push(a.slice(0,-3));break}o.push(a);}return o.join(`
@@ -1688,7 +1687,7 @@ Command: ${W} ${ie.join(" ")}`;throw new Error(`ripgrep failed (exit code ${Le})
1688
1687
  `+r.slice(T);u(Q);return}if(J.return){if(C&&s.length>0){let Q=s[I];b(0),w(false),d(Q);return}process.env.CLI_DEBUG==="1"&&p.debug("INPUT_LINE","Enter pressed - submitting",{valueLength:r.length,value:r.substring(0,50),disabled:t}),d(),b(0),w(false);return}if(C&&s.length>0){if(J.upArrow){M(Q=>Q>0?Q-1:s.length-1);return}if(J.downArrow){M(Q=>Q<s.length-1?Q+1:0);return}}if(J.upArrow){if(ee===0)m(),b(0);else {let Q=r.lastIndexOf(`
1689
1688
  `,T-j-2)+1,te=F[ee-1].length,pe=Math.min(j,te),D=Q+pe;b(r.length-D);}return}if(J.downArrow){if(ee===F.length-1)g(),b(0);else {r.lastIndexOf(`
1690
1689
  `,T-1)+1;let te=r.indexOf(`
1691
- `,T)+1,pe=F[ee+1].length,D=Math.min(j,pe),q=te+D;b(r.length-q);}return}if(J.leftArrow){b(Math.min(v+1,r.length));return}if(J.rightArrow){b(Math.max(v-1,0));return}if(J.home||J.ctrl&&Y==="a"){b(r.length);return}if(J.end||J.ctrl&&Y==="e"){b(0);return}if(J.backspace||J.delete){if(v===r.length){r.length===0&&a>0&&c&&c();return}let Q=T-1,te=r.slice(0,Q)+r.slice(Q+1);u(te);return}if(!J.ctrl&&!J.meta&&Y){let Q=r.slice(0,T)+Y+r.slice(T);u(Q);return}}}},{isActive:z});let Z=!r,X=()=>Z?E.createElement(_,null,E.createElement(y,{color:"green",bold:true},"> "),E.createElement(y,{inverse:true}," "),E.createElement(y,{dimColor:true},e)):F.map((Y,J)=>{let Q=J===ee,te=F.slice(0,J).reduce((le,_e)=>le+_e.length+1,0);te+Y.length;let D=-1;Q&&(D=T-te);let q=J===0?"> ":"\u2502 ",se="green";if(t)return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,{dimColor:true},Y));if(Q&&D>=0){let le=Y.slice(0,D),_e=Y[D]||" ",$e=Y.slice(D+1);return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,null,le,E.createElement(y,{inverse:true},_e),$e))}return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,null,Y))});return E.createElement(_,{flexDirection:"column"},U&&!t&&E.createElement(_,{marginBottom:0},E.createElement(y,{dimColor:true}," \u21B5 Shift+Enter \u6362\u884C \u2502 Enter \u53D1\u9001 \u2502 ",F.length," \u884C")),E.createElement(_,{flexDirection:"column"},X()))};var oE=({isRunning:r,statusText:e="",tokenStats:t,streamingTokens:n=0,streamingStartTime:s=null,provider:o,model:i,onContextMenuToggle:a,agentContextStats:l=[],maxDisplayAgents:c=3,runMode:u="single",networkStats:d,cooperateStats:m})=>{let[g,h]=useState(null),[f,v]=useState(0),[b,C]=useState(0),[w,I]=useState(0),[M,N]=useState(0);useEffect(()=>{r?(h(s||Date.now()),v(0)):!r&&(t?.output||0)===0&&(h(null),v(0));},[r,s,t?.output]),useEffect(()=>{if(!r||g===null)return;let Z=setInterval(()=>{v(Math.floor((Date.now()-g)/1e3));},500);return ()=>clearInterval(Z)},[r,g]),useEffect(()=>{if(!r||n===0){C(0);return}let Z=Math.floor(n);if(b===Z)return;let X=Z-b,Y=Math.min(Math.abs(X),20),J=X/Y,te=setInterval(()=>{C(pe=>{let D=pe+J;return Math.abs(D-Z)<1?Z:D});},50);return ()=>clearInterval(te)},[n,r,b]),useEffect(()=>{let Z=t?.output||0;if(w===Z)return;let X=Z-w;if(Math.abs(X)>100){I(Z);return}let Y=Math.max(Math.ceil(Math.abs(X)/10),3),J=X/Y,te=setInterval(()=>{I(pe=>{let D=pe+J;return Math.abs(D-Z)<1?Z:D});},10);return ()=>clearInterval(te)},[t?.output,w]),useEffect(()=>{if(!r){N(0);return}let X=(e||"Thinking...").length,Y=setInterval(()=>{N(J=>(J+1)%(X+3));},80);return ()=>clearInterval(Y)},[r,e]);let R=()=>{if(f<60)return `${f}s`;let Z=Math.floor(f/60),X=f%60;return `${Z}m ${X}s`},O=Z=>Z>=1e6?(Z/1e6).toFixed(1)+"M":Z>=1e3?(Z/1e3).toFixed(1)+"K":Z.toString(),k=t?.contextWindow||0,A=t?.tokensUsedForContext||t?.total||0,T=t?.pressure||0,P=Math.round(T*100),$=()=>T>.8?"red":T>.5?"yellow":"green",G=Z=>Z.split("").map((Y,J)=>{let Q=J-M;return Q>=0&&Q<2?E.createElement(y,{key:J,color:"white",bold:true},Y):Q>=-1&&Q<0?E.createElement(y,{key:J,color:"cyanBright"},Y):E.createElement(y,{key:J,color:"cyan"},Y)}),L=(()=>{switch(u){case "single":return {icon:"\u{1F464}",label:"Single",color:"cyan"};case "collab":return {icon:"\u{1F91D}",label:"Collab",color:"magenta"};case "cooperate":return {icon:"\u{1F527}",label:"Cooperate",color:"yellow"};case "network":return {icon:"\u{1F310}",label:"Network",color:"blue"};default:return {icon:"\u{1F464}",label:"Single",color:"cyan"}}})(),F=e&&(e.includes("Streaming:")||e.toLowerCase().includes("stream")),U=e?.match(/Streaming:\s*(\w+)/),H=U?U[1]:null,ee=l.length>0,j=l.find(Z=>Z.agentId==="Main"),z=l.filter(Z=>Z.agentId!=="Main"),ue=z.length>c,V=()=>z.length===0?null:E.createElement(_,null,E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"magenta"},z.length),E.createElement(y,{dimColor:true}," workers"),ue&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 Ctrl+G"))),ve=(Z,X)=>{let Y=Z.pressure||0,J=Math.round(Y*100),Q=()=>Y>.8?"red":Y>.5?"yellow":"green",te=()=>{switch(Z.status||"idle"){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},{icon:pe,color:D}=te(),q=Z.currentTask?Z.currentTask.length>20?Z.currentTask.slice(0,17)+"...":Z.currentTask:"";return E.createElement(_,{key:Z.agentId,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{dimColor:true},X?"\u2514\u2500 ":"\u251C\u2500 "),E.createElement(y,{color:D},pe),E.createElement(y,null," "),E.createElement(y,{color:"magenta"},Z.agentLabel),q&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{dimColor:true},q))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Z.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(Z.output)),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},O(Z.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(Z.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:Q()},J,"%"),E.createElement(y,{dimColor:true},")")))};if(u==="network"){let Z=d?.teamSize||0,X=d?.activeAgents||0,Y=d?.currentPhase||"executing",J=d?.currentAgent,Q=d?.totalInputTokens||t?.input||0,te=d?.totalOutputTokens||t?.output||0,pe=d?.completedTasks,D=d?.totalTasks,se=(()=>{switch(Y){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})();return E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"blue"},"\u{1F310}"),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"blue"},Z),E.createElement(y,{dimColor:true}," agents"),X>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"green"},X),E.createElement(y,{dimColor:true}," active)")),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),J?E.createElement(E.Fragment,null,G(J),E.createElement(y,{dimColor:true},": "),E.createElement(y,{color:se.color},se.text)):E.createElement(y,{color:se.color},se.text),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,te>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,pe!==void 0&&D!==void 0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true},"tasks "),E.createElement(y,{color:"yellow"},pe),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},D),E.createElement(y,{dimColor:true}," \u2502 ")),r&&b>0&&E.createElement(E.Fragment,null,E.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),E.createElement(y,{dimColor:true}," \u2502 ")),E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Q)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(te))))}if(u==="cooperate"&&m){let{models:Z,phase:X,totalInputTokens:Y,totalOutputTokens:J,ccbResult:Q,dagProgress:te}=m,D=(()=>{switch(X){case "analyzing":return {text:"Analyzing",color:"cyan"};case "ccb_review":return {text:"CCB Review",color:"yellow"};case "dag_planning":return {text:"Planning",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})(),q=()=>Z.length===0?null:Z.map((le,_e)=>{let $e=le.status==="running"?"green":le.status==="completed"?"blue":"gray";return E.createElement(E.Fragment,{key:_e},_e>0&&E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:$e},le.shortName))}),se=Z.filter(le=>le.status==="completed").length;return E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"yellow"},"\u{1F527}"),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),e?G(e):E.createElement(y,{color:D.color},D.text),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")")),b>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ~"),E.createElement(y,{color:"magenta"},Math.floor(b)),E.createElement(y,{dimColor:true}," tok"))):E.createElement(_,null,J>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,Z.length>0&&E.createElement(E.Fragment,null,q(),E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:"yellow"},se),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},Z.length),E.createElement(y,{dimColor:true}," \u2502 ")),Q&&E.createElement(E.Fragment,null,E.createElement(y,{color:Q.approved?"green":"red"},Q.approved?"\u2713":"\u2717"),E.createElement(y,{dimColor:true}," CCB "),E.createElement(y,{color:"yellow"},Q.approveCount),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},Q.totalCount),E.createElement(y,{dimColor:true}," \u2502 ")),te&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true},"DAG "),E.createElement(y,{color:"yellow"},te.completedNodes),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},te.totalNodes),E.createElement(y,{dimColor:true}," \u2502 ")),E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Y||t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(J||t?.output||0))))}if((u==="collab"||u==="cooperate")&&ee){let Z=j?.pressure||0,X=Math.round(Z*100),Y=()=>Z>.8?"red":Z>.5?"yellow":"green",J=z.length<=c&&z.length>0,Q=j?.agentLabel||"Main";return E.createElement(_,{flexDirection:"column"},E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:L.color},L.icon),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),E.createElement(y,{bold:true,color:"cyan"},"\u25CF"),E.createElement(y,null," "),F&&H?E.createElement(E.Fragment,null,G(`Streaming: ${H}`)):G(e||"Thinking..."),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,(j?.output||t?.output||0)>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,j?E.createElement(_,null,E.createElement(y,{dimColor:true},Q,": "),E.createElement(y,{color:"cyan"},O(j.input)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"green"},O(j.output)),(j.cacheCreationTokens||j.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},O(j.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},O(j.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"yellow"},O(j.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(j.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:Y()},X,"%"),E.createElement(y,{dimColor:true},")"),V()):E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(t?.output||0)),V()))),J&&z.map((te,pe)=>ve(te,pe===z.length-1)))}return E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:L.color},L.icon),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),E.createElement(y,{bold:true,color:"cyan"},"\u25CF"),E.createElement(y,null," "),F&&H?E.createElement(E.Fragment,null,G(`Streaming: ${H}`)):G(e||"Thinking..."),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true}," \u2022 esc to interrupt"),b>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 "),E.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),E.createElement(y,{dimColor:true}," ",F?"chars":"tokens")),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,(t?.output||0)>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,k>0?E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(t?.output||0)),(t?.cacheCreationTokens||t?.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},O(t.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},O(t.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},O(A)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(k)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:$()},P,"%"),E.createElement(y,{dimColor:true},")")):E.createElement(y,{dimColor:true},"context: --")))},iE=(r,e)=>!r&&!e?true:!r||!e||r.length!==e.length?false:r.every((t,n)=>{let s=e[n];return t.agentId===s.agentId&&t.input===s.input&&t.output===s.output&&t.pressure===s.pressure&&t.tokensUsedForContext===s.tokensUsedForContext&&t.status===s.status&&t.currentTask===s.currentTask&&t.contextWindow===s.contextWindow&&t.cacheCreationTokens===s.cacheCreationTokens&&t.cacheReadTokens===s.cacheReadTokens}),Sb=E.memo(oE,(r,e)=>r.isRunning===e.isRunning&&r.statusText===e.statusText&&r.streamingTokens===e.streamingTokens&&r.streamingStartTime===e.streamingStartTime&&r.tokenStats?.input===e.tokenStats?.input&&r.tokenStats?.output===e.tokenStats?.output&&r.tokenStats?.total===e.tokenStats?.total&&r.tokenStats?.pressure===e.tokenStats?.pressure&&r.tokenStats?.cacheCreationTokens===e.tokenStats?.cacheCreationTokens&&r.tokenStats?.cacheReadTokens===e.tokenStats?.cacheReadTokens&&r.runMode===e.runMode&&r.networkStats?.teamSize===e.networkStats?.teamSize&&r.networkStats?.activeAgents===e.networkStats?.activeAgents&&r.networkStats?.currentPhase===e.networkStats?.currentPhase&&r.networkStats?.currentAgent===e.networkStats?.currentAgent&&r.networkStats?.totalInputTokens===e.networkStats?.totalInputTokens&&r.networkStats?.totalOutputTokens===e.networkStats?.totalOutputTokens&&r.networkStats?.completedTasks===e.networkStats?.completedTasks&&r.networkStats?.totalTasks===e.networkStats?.totalTasks&&r.cooperateStats?.phase===e.cooperateStats?.phase&&r.cooperateStats?.totalInputTokens===e.cooperateStats?.totalInputTokens&&r.cooperateStats?.totalOutputTokens===e.cooperateStats?.totalOutputTokens&&r.cooperateStats?.ccbResult?.approved===e.cooperateStats?.ccbResult?.approved&&r.cooperateStats?.ccbResult?.approveCount===e.cooperateStats?.ccbResult?.approveCount&&r.cooperateStats?.dagProgress?.completedNodes===e.cooperateStats?.dagProgress?.completedNodes&&r.cooperateStats?.models?.length===e.cooperateStats?.models?.length&&iE(r.agentContextStats,e.agentContextStats));var kb=({isRunning:r,hasInput:e,customHints:t,menuActive:n=false,thinkingEnabled:s=true,accumulatedRunTime:o=0,provider:i,model:a,runMode:l="single"})=>{let[c,u]=useState(o);useEffect(()=>{if(!r){u(o);return}u(o);let f=setInterval(()=>{u(v=>v+1);},1e3);return ()=>clearInterval(f)},[r,o]);let d=()=>{if(c<60)return `${c}s`;let f=Math.floor(c/60),v=c%60;if(f<60)return `${f}m ${v}s`;let b=Math.floor(f/60),C=f%60;return `${b}h ${C}m`},m=()=>{if(!i||!a)return "";let f=i,v=i.indexOf(" (");v>0&&(f=i.substring(0,v));let b=a.length>35?a.substring(0,32)+"...":a;return `${f}/${b}`},h=(()=>{switch(l){case "single":return {label:"SINGLE",color:"cyan"};case "collab":return {label:"COLLAB",color:"magenta"};case "cooperate":return {label:"COOPERATE",color:"yellow"};case "network":return {label:"NETWORK",color:"blue"};default:return {label:"SINGLE",color:"cyan"}}})();return t?E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{color:"yellow"},t)):n?E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{dimColor:true}," ","\u2191\u2193 to select, Enter to confirm, ESC to cancel")):E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{dimColor:true},"? for shortcuts"),c>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 "),E.createElement(y,{color:"cyan"},d()),E.createElement(y,{dimColor:true}," session"))),E.createElement(_,null,E.createElement(y,{color:h.color,bold:true},"["),E.createElement(y,{color:h.color},h.label),E.createElement(y,{color:h.color,bold:true},"]"),E.createElement(y,{dimColor:true}," \u2022 "),m()&&E.createElement(E.Fragment,null,E.createElement(y,{color:"magenta",bold:true},"["),E.createElement(y,{color:"magenta"},m()),E.createElement(y,{color:"magenta",bold:true},"]"),E.createElement(y,{dimColor:true}," \u2022 ")),s?E.createElement(y,{color:"cyan"},"Thinking on"):E.createElement(y,{dimColor:true},"Thinking off"),E.createElement(y,{dimColor:true}," (tab to toggle)")))};var _b=({attachments:r,onRemove:e})=>r.length===0?null:E.createElement(_,{flexDirection:"column",paddingLeft:2,marginBottom:1},E.createElement(y,{color:"magenta",dimColor:true},"Attachments:"),r.map((t,n)=>{let s=t.name||t.path?.split("/").pop()||"unknown",o=t.type?.startsWith("image/")||t.mediaType?.startsWith("image/")||s.match(/\.(png|jpg|jpeg|gif|webp)$/i);return E.createElement(_,{key:n},E.createElement(y,{color:"magenta"},o?"\u{1F4CE} \u{1F5BC}\uFE0F ":"\u{1F4CE} ",s),e&&E.createElement(y,{color:"gray",dimColor:true}," (press \u232B Backspace to remove)"))}));var Ib=({planSteps:r,isRunning:e=false})=>{let t=r.find(s=>s.status==="pending");if(!t||!e)return null;let n=t.step.length>50?t.step.substring(0,47)+"...":t.step;return E.createElement(_,{paddingLeft:2},E.createElement(y,{dimColor:true},"\u2514\u2500 "),E.createElement(y,{color:"gray"},"\u25CB"),E.createElement(y,{dimColor:true}," Next: "),E.createElement(y,{color:"cyan"},n))};var Eb=({contextWindow:r,tokensUsed:e,systemTokens:t=0,userTokens:n=0,assistantTokens:s=0,toolCallTokens:o=0,toolResultTokens:i=0,compactionThreshold:a=.8,compressionMode:l="sync",agentContextStats:c=[],runMode:u="single",networkStats:d,onClose:m})=>{let g=R=>R>=1e6?`${(R/1e6).toFixed(1)}M`:R>=1e3?`${(R/1e3).toFixed(1)}k`:R.toString(),h=R=>R>.8?"red":R>.5?"yellow":"green",f=({color:R,label:O,tokens:k,total:A,indent:T=2})=>{let P=A>0?(k/A*100).toFixed(2):"0.00";return E.createElement(_,{marginLeft:T},E.createElement(y,{color:R},"\u25A0"),E.createElement(y,null," ",O,": "),E.createElement(y,{color:"yellow"},g(k)),E.createElement(y,{dimColor:true}," tokens (",P,"%)"))},v=({stat:R,indent:O=2})=>{let k=R.cacheCreationTokens||0,A=R.cacheReadTokens||0,T=R.contextWindow||2e5,P=R.tokensUsedForContext||0,$=T>0?P/T:0,G=Math.round($*100);return E.createElement(_,{marginLeft:O,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"magenta"},R.agentLabel||R.agentId),R.status&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:R.status==="running"?"green":R.status==="error"?"red":"gray"},R.status==="running"?"\u25CF":R.status==="completed"?"\u2713":R.status==="error"?"\u2717":"\u25CB"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},g(R.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},g(R.output)),(k>0||A>0)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2502 cw "),E.createElement(y,{color:"blue"},g(k)),E.createElement(y,{dimColor:true}," cr "),E.createElement(y,{color:"blue"},g(A))),E.createElement(y,{dimColor:true}," \u2502 ctx "),E.createElement(y,{color:"yellow"},g(P)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},g(T)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:h($)},G,"%"),E.createElement(y,{dimColor:true},")")))},b=({stat:R,indent:O=2})=>{let k=R.contextWindow>0?R.tokensUsedForContext/R.contextWindow:0,A=Math.round(k*100);return E.createElement(_,{marginLeft:O,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"magenta"},R.agentLabel||R.agentId),R.status&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:R.status==="running"?"green":R.status==="error"?"red":"gray"},R.status==="running"?"\u25CF":R.status==="completed"?"\u2713":R.status==="error"?"\u2717":"\u25CB"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},g(R.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},g(R.output)),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"yellow"},g(R.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},g(R.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:h(k)},A,"%"),E.createElement(y,{dimColor:true},")")))};if(u==="network"){let R=d?.teamSize||c.length||0,O=d?.activeAgents||0,k=d?.totalInputTokens||0,A=d?.totalOutputTokens||0,T=k+A,$=(G=>{switch(G){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Idle",color:"gray"}}})(d?.currentPhase);return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:"blue"},"\u{1F310}"),E.createElement(y,{bold:true,color:"blue"}," Network Context Overview")),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Team Size: "),E.createElement(y,{color:"blue",bold:true},R),E.createElement(y,{dimColor:true}," agents"),O>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"green"},O),E.createElement(y,{dimColor:true}," active)"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"Current Phase: "),E.createElement(y,{color:$.color,bold:true},$.text),d?.currentAgent&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," - "),E.createElement(y,{color:"cyan"},d.currentAgent))),d?.completedTasks!==void 0&&d?.totalTasks!==void 0&&E.createElement(_,null,E.createElement(y,{dimColor:true},"Tasks: "),E.createElement(y,{color:"yellow"},d.completedTasks),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},d.totalTasks),E.createElement(y,{dimColor:true}," completed"))),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(y,{bold:true,dimColor:true},"Total Token Usage:"),E.createElement(_,{marginLeft:2},E.createElement(y,{dimColor:true},"Input: "),E.createElement(y,{color:"cyan"},g(k)),E.createElement(y,{dimColor:true}," \u2502 Output: "),E.createElement(y,{color:"green"},g(A)),E.createElement(y,{dimColor:true}," \u2502 Total: "),E.createElement(y,{color:"yellow"},g(T)))),c.length>0&&E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Agent Context Details:"),c.map(G=>E.createElement(v,{key:G.agentId,stat:G})),E.createElement(_,{marginTop:1,marginLeft:2},E.createElement(y,{dimColor:true},"Total Tokens: "),E.createElement(y,{color:"yellow"},g(c.reduce((G,S)=>G+S.input+S.output,0))),E.createElement(y,{dimColor:true}," across "),E.createElement(y,{color:"cyan"},c.length),E.createElement(y,{dimColor:true}," agents"))),c.length===0&&E.createElement(_,{marginTop:1},E.createElement(y,{dimColor:true,italic:true},"Agent context details not available yet.")))}if((u==="collab"||u==="cooperate")&&c.length>0){let R=c.find(S=>S.agentId==="Main"),O=c.filter(S=>S.agentId!=="Main"&&S.agentId!=="supervisor"),k=c.reduce((S,L)=>S+L.tokensUsedForContext,0),A=c.reduce((S,L)=>S+L.input,0),T=c.reduce((S,L)=>S+L.output,0),P=u==="collab"?"\u{1F91D}":"\u{1F527}",$=u==="collab"?"Collab":"Cooperate",G=u==="collab"?"magenta":"yellow";return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:G,paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:G},P),E.createElement(y,{bold:true,color:G}," ",$," Context Overview")),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Total Agents: "),E.createElement(y,{color:G,bold:true},c.length),O.length>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," (1 Main + "),E.createElement(y,{color:"cyan"},O.length),E.createElement(y,{dimColor:true}," Workers)"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"Total Tokens: "),E.createElement(y,{color:"cyan"},g(A)),E.createElement(y,{dimColor:true}," in / "),E.createElement(y,{color:"green"},g(T)),E.createElement(y,{dimColor:true}," out"))),R&&E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(y,{bold:true,dimColor:true},"Main Agent:"),E.createElement(b,{stat:R})),O.length>0&&E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Worker Agents (",O.length,"):"),O.map(S=>E.createElement(b,{key:S.agentId,stat:S}))),E.createElement(_,{marginTop:1},E.createElement(y,{dimColor:true},"Combined Context: "),E.createElement(y,{color:"yellow"},g(k)),E.createElement(y,{dimColor:true}," tokens")))}let C=r-e,w=r>0?e/r:0,I=Math.floor(r*a),M=Math.max(0,I-e),N=Math.round(w*100);return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(y,{bold:true,color:"cyan"},"Context Window Details"),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Total: "),E.createElement(y,{color:"yellow"},g(e)),E.createElement(y,{dimColor:true}," / "),E.createElement(y,{color:"yellow"},g(r)),E.createElement(y,{dimColor:true}," tokens ("),E.createElement(y,{color:h(w),bold:true},N,"%"),E.createElement(y,{dimColor:true},")")),E.createElement(_,null,E.createElement(y,{dimColor:true},"Remaining: "),E.createElement(y,{color:"green"},g(C)),E.createElement(y,{dimColor:true}," tokens"))),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Compression: "),E.createElement(y,{color:l==="sync"?"green":"yellow"},l==="sync"?"Sync LLM":"Async LLM"),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"cyan"},Math.round(a*100),"%"),E.createElement(y,{dimColor:true}," threshold)"))),M>0?E.createElement(_,{marginBottom:1},E.createElement(y,{dimColor:true},"Compaction in: "),E.createElement(y,{color:"cyan"},g(M)),E.createElement(y,{dimColor:true}," tokens")):E.createElement(_,{marginBottom:1},E.createElement(y,{color:"red",bold:true},"\u26A0\uFE0F Compaction threshold reached!")),E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Context Breakdown:"),E.createElement(f,{color:"magenta",label:"System",tokens:t,total:e}),E.createElement(f,{color:"cyan",label:"User",tokens:n,total:e}),E.createElement(f,{color:"green",label:"Assistant",tokens:s,total:e}),E.createElement(f,{color:"blue",label:"Tool Calls",tokens:o,total:e}),E.createElement(f,{color:"yellow",label:"Tool Results",tokens:i,total:e}),E.createElement(_,{marginTop:1,marginLeft:2},E.createElement(y,{dimColor:true},"Usage: "),E.createElement(y,{color:h(w)},"\u2588".repeat(Math.floor(w*20))),E.createElement(y,{dimColor:true},"\u2591".repeat(20-Math.floor(w*20))))))};var Pb=[{name:"/help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",category:"\u57FA\u7840"},{name:"/clear",description:"\u6E05\u7A7A\u5C4F\u5E55",category:"\u57FA\u7840"},{name:"/exit",description:"\u9000\u51FA\u7A0B\u5E8F",category:"\u57FA\u7840"},{name:"/mode",description:"\u5207\u6362 ask/agent \u6A21\u5F0F",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/collab",description:"\u534F\u4F5C\u6A21\u5F0F\u914D\u7F6E",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/thinking",description:"\u601D\u8003\u6A21\u5F0F\u5F00\u5173",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/approval",description:"\u5BA1\u6279\u6A21\u5F0F\u5F00\u5173",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/sandbox",description:"\u6C99\u76D2\u6A21\u5F0F\u8BBE\u7F6E",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/provider",description:"\u7BA1\u7406 AI \u670D\u52A1\u5546",category:"AI",hasSubMenu:true},{name:"/model",description:"\u7BA1\u7406\u6A21\u578B",category:"AI",hasSubMenu:true},{name:"/sessions",description:"\u67E5\u770B\u6240\u6709\u4F1A\u8BDD",category:"\u4F1A\u8BDD"},{name:"/session",description:"\u5207\u6362\u4F1A\u8BDD",category:"\u4F1A\u8BDD",hasSubMenu:true},{name:"/session-new",description:"\u521B\u5EFA\u65B0\u4F1A\u8BDD",category:"\u4F1A\u8BDD"},{name:"/session-info",description:"\u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F",category:"\u4F1A\u8BDD"},{name:"/checkpoint",description:"\u521B\u5EFA\u68C0\u67E5\u70B9",category:"\u4F1A\u8BDD"},{name:"/checkpoints",description:"\u67E5\u770B\u68C0\u67E5\u70B9\u5217\u8868",category:"\u4F1A\u8BDD"},{name:"/rollback",description:"\u56DE\u6EDA\u5230\u68C0\u67E5\u70B9",category:"\u4F1A\u8BDD",hasSubMenu:true},{name:"/undo",description:"\u64A4\u9500\u64CD\u4F5C",category:"\u4F1A\u8BDD"},{name:"/compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",category:"\u4F1A\u8BDD"},{name:"/processes",description:"\u67E5\u770B\u540E\u53F0\u8FDB\u7A0B",category:"\u8FDB\u7A0B"},{name:"/ps",description:"\u67E5\u770B\u540E\u53F0\u8FDB\u7A0B (\u7B80\u5199)",category:"\u8FDB\u7A0B"},{name:"/kill",description:"\u7EC8\u6B62\u8FDB\u7A0B",category:"\u8FDB\u7A0B",hasSubMenu:true},{name:"/attach",description:"\u6DFB\u52A0\u9644\u4EF6",category:"\u5DE5\u5177"},{name:"/attachments",description:"\u67E5\u770B\u9644\u4EF6",category:"\u5DE5\u5177"},{name:"/workspace",description:"\u5DE5\u4F5C\u533A\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/mcp",description:"MCP \u670D\u52A1\u5668\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/context",description:"\u4E0A\u4E0B\u6587\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/memory",description:"\u5185\u5B58\u8BCA\u65AD",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/remote",description:"\u8FDC\u7A0B\u670D\u52A1",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/index",description:"\u7D22\u5F15\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/stats",description:"\u4F1A\u8BDD\u7EDF\u8BA1",category:"\u7EDF\u8BA1"},{name:"/statistic",description:"Token \u4F7F\u7528\u7EDF\u8BA1",category:"\u7EDF\u8BA1",hasSubMenu:true},{name:"/config-clear",description:"\u6E05\u9664\u914D\u7F6E",category:"\u914D\u7F6E"},{name:"/config-reset",description:"\u91CD\u7F6E\u914D\u7F6E",category:"\u914D\u7F6E"},{name:"/notify",description:"\u901A\u77E5\u8BBE\u7F6E",category:"\u914D\u7F6E",hasSubMenu:true}],cE=({isVisible:r,filter:e="",onSelect:t,onCancel:n})=>{let[s,o]=useState(0),[i,a]=useState(0),l=10,c=e&&e!=="/"?Pb.filter(m=>m.name.toLowerCase().includes(e.toLowerCase())||m.description.toLowerCase().includes(e.toLowerCase())):Pb;useEffect(()=>{o(0),a(0);},[e]),useEffect(()=>{s<i?a(s):s>=i+l&&a(s-l+1);},[s]),Xe((m,g)=>{if(r){if(g.escape){n();return}if(g.upArrow){o(h=>h>0?h-1:c.length-1);return}if(g.downArrow){o(h=>h<c.length-1?h+1:0);return}if(g.pageUp||g.ctrl&&m==="u"){o(h=>Math.max(0,h-l));return}if(g.pageDown||g.ctrl&&m==="d"){o(h=>Math.min(c.length-1,h+l));return}if(g.return){c.length>0&&t(c[s].name);return}if(g.tab){c.length>0&&t(c[s].name+" ");return}}},{isActive:r});let u=c.slice(i,i+l),d=E.useMemo(()=>u.map((m,g)=>{let f=i+g===s;return E.createElement(_,{key:m.name},E.createElement(y,{color:f?"cyan":"white"},f?"\u203A ":" "),E.createElement(y,{color:f?"cyan":"white",bold:f},"\u25CF ",m.name),E.createElement(y,{color:f?"cyan":"gray"}," ","- ",m.description))}),[u,i,s]);return !r||c.length===0?null:E.createElement(_,{flexDirection:"column",paddingLeft:0},E.createElement(y,{color:"cyan",bold:true},"\u547D\u4EE4\u83DC\u5355"),E.createElement(y,{dimColor:true},"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88"),i>0&&E.createElement(y,{dimColor:true}," \u2191 \u66F4\u591A..."),d,i+l<c.length&&E.createElement(y,{dimColor:true}," \u2193 \u66F4\u591A..."),E.createElement(y,{dimColor:true},"\u2500".repeat(40)),E.createElement(y,{dimColor:true},c.length," \u4E2A\u547D\u4EE4 \xB7 \u7B2C ",Math.floor(i/l)+1,"/",Math.ceil(c.length/l)," \u9875"))},Rb=E.memo(cE,(r,e)=>r.isVisible===e.isVisible&&r.filter===e.filter&&r.onSelect===e.onSelect&&r.onCancel===e.onCancel);re();var uE=({inputValue:r,isRunning:e,statusText:t="",tokenStats:n,streamingTokens:s=0,streamingStartTime:o=null,accumulatedRunTime:i=0,provider:a,model:l,customHints:c,attachments:u=[],multiline:d=false,completions:m=[],menuActive:g=false,promptActive:h=false,promptMessage:f,promptHint:v,promptOnCancel:b,thinkingEnabled:C=true,contextMenuActive:w=false,compressionMode:I="sync",compactionThreshold:M=.85,agentContextStats:N=[],runMode:R="single",networkStats:O,cooperateStats:k,currentPlanSteps:A=[],onInputChange:T,onSubmit:P,onInterrupt:$,onExit:G,onHistoryUp:S,onHistoryDown:L,onTabComplete:F,onRemoveAttachment:U,onContextMenuToggle:H,onAgentContextScreenToggle:ee,onPasteImage:j,onShowInterruptInput:z})=>{let{columns:ue}=Ws(),V=r==="/"||r.startsWith("/")&&!r.includes(" "),ve=E.useCallback(X=>{X.endsWith(" ")?T(X.trim()):(T(""),setTimeout(()=>{P(X);},0));},[T,P]),Z=E.useCallback(()=>{T("");},[T]);return Xe((X,Y)=>{if(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","BottomBar useInput",{key:Y,input:X,menuActive:g,promptActive:h,isRunning:e,inputValue:r.substring(0,20)}),!g){if(e&&X==="i"&&!Y.ctrl&&!Y.meta&&z){p.debug("INK_INPUT",'Interrupt input triggered with "i" key'),z();return}if(Y.ctrl&&X==="g"&&ee){ee();return}if(Y.ctrl&&X==="z"){process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+Z blocked (prevents suspension)");return}if(Y.escape){let J=!X||X==="\x1B"||X==="";if(p.info("INK_INPUT",`ESC detected: isRealEscape=${J}, input=${JSON.stringify(X)}, isRunning=${e}`),!J){p.debug("INK_INPUT","Ignoring escape sequence (not real ESC key)");return}if(w&&H){H();return}if(h&&b){b(),T("");return}e?(p.info("INK_INPUT","\u{1F6D1} User pressed ESC to interrupt task"),$()):r&&T("");return}Y.ctrl&&X==="c"&&(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+C pressed",{isRunning:e}),e?$():(p.info("INK_INPUT","\u26A0\uFE0F Ctrl+C pressed - exiting"),G()));}},{isActive:true}),E.createElement(_,{flexDirection:"column"},h&&f&&E.createElement(_,{paddingX:2,paddingY:1},E.createElement(y,{color:"cyan",bold:true},f)),h&&v&&E.createElement(_,{paddingX:2,paddingBottom:1},E.createElement(y,{dimColor:true},v)),!h&&E.createElement(Sb,{isRunning:e,statusText:t,tokenStats:n,streamingTokens:s,streamingStartTime:o,provider:a,model:l,onContextMenuToggle:H,agentContextStats:N,runMode:R,networkStats:O,cooperateStats:k}),!h&&E.createElement(Ib,{planSteps:A,isRunning:e}),u.length>0&&E.createElement(_b,{attachments:u,onRemove:U}),E.createElement(_,{flexDirection:"column"},E.createElement(y,{color:"gray"},"\u2500".repeat(ue)),E.createElement(Tb,{value:r,placeholder:h?v||"Type your answer...":e?"Enter to interrupt and send...":"Type a message...",disabled:g,multiline:d,completions:[],menuActive:g,slashMenuActive:V,imageCount:u.length,onChange:T,onSubmit:X=>P(X??r),onHistoryUp:S,onHistoryDown:L,onTabComplete:F,onPasteImage:j,onRemoveLastAttachment:U?()=>U(u.length-1):void 0}),E.createElement(y,{color:"gray"},"\u2500".repeat(ue))),V&&!g&&!e&&E.createElement(Rb,{isVisible:true,filter:r,onSelect:ve,onCancel:Z}),!h&&E.createElement(kb,{isRunning:e,hasInput:r.length>0,customHints:c,menuActive:g,thinkingEnabled:C,accumulatedRunTime:i,provider:a,model:l,runMode:R}),w&&n?.contextWindow&&H&&E.createElement(Eb,{contextWindow:n.contextWindow,tokensUsed:n.tokensUsedForContext||n.total,systemTokens:n.systemTokens,userTokens:n.userTokens,assistantTokens:n.assistantTokens,toolCallTokens:n.toolCallTokens,toolResultTokens:n.toolResultTokens,compressionMode:I,compactionThreshold:M,agentContextStats:N,runMode:R,networkStats:O,onClose:H}))},Db=E.memo(uE);var Bp=({message:r,choices:e,initialIndex:t=0,hint:n,maxVisible:s=20,onSelect:o,onCancel:i,onExit:a})=>{let[l,c]=useState(t),[u,d]=useState(0),[m,g]=useState(null);useEffect(()=>{c(t);},[t]),useEffect(()=>{let b=setTimeout(()=>{g(Date.now());},200);return ()=>clearTimeout(b)},[]),useEffect(()=>{if(e.length<=s){d(0);return}l<u?d(l):l>=u+s&&d(l-s+1);},[l,e.length,s,u]),Xe((b,C)=>{if(C.ctrl&&b==="c"&&a){process.nextTick(()=>a());return}if(C.escape&&i){process.nextTick(()=>i());return}if(C.upArrow){c(w=>w>0?w-1:e.length-1);return}if(C.downArrow){c(w=>w<e.length-1?w+1:0);return}if(C.return){if(!m)return;process.nextTick(()=>o(e[l].value));return}});let h=Math.min(e.length,s),f=u>0,v=u+h<e.length;return E.createElement(_,{flexDirection:"column"},r&&E.createElement(_,{marginBottom:1,paddingX:2},E.createElement(y,{bold:true,color:"cyan"},r)),n&&E.createElement(_,{marginBottom:1,paddingX:2},E.createElement(y,{dimColor:true},n)),f&&E.createElement(_,{paddingX:2},E.createElement(y,{dimColor:true}," \u2191 more")),e.slice(u,u+h).map((b,C)=>{let w=u+C,I=w===l,M=I?"\u276F ":" ";return E.createElement(_,{key:`${b.value}-${w}`,flexDirection:"row",paddingX:2},E.createElement(y,{color:I?"cyan":void 0,bold:I},M,b.label),b.description&&E.createElement(y,{dimColor:true}," - ",b.description))}),v&&E.createElement(_,{paddingX:2},E.createElement(y,{dimColor:true}," \u2193 more")))};var Lb=({onSubmit:r,onCancel:e})=>{let[t,n]=useState(""),[s,o]=useState(0),i=t.length-s;Xe((u,d)=>{if(d.escape){e();return}if(d.return){let m=t.trim();m&&r(m);return}if(d.backspace||d.delete){if(s===t.length)return;let m=i-1,g=t.slice(0,m)+t.slice(m+1);n(g);return}if(d.leftArrow){o(Math.min(s+1,t.length));return}if(d.rightArrow){o(Math.max(s-1,0));return}if(d.home||d.ctrl&&u==="a"){o(t.length);return}if(d.end||d.ctrl&&u==="e"){o(0);return}if(!d.ctrl&&!d.meta&&u){let m=t.slice(0,i)+u+t.slice(i);n(m);return}},{isActive:true});let a=t.slice(0,i),l=t[i]||" ",c=t.slice(i+1);return E.createElement(_,{flexDirection:"column",borderStyle:"double",borderColor:"yellow",paddingX:2,paddingY:1,width:"80%"},E.createElement(_,{marginBottom:1,justifyContent:"center"},E.createElement(y,{bold:true,color:"yellow"},"\u2728 \u63D2\u961F\u6D88\u606F - \u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001")),E.createElement(_,{flexDirection:"column"},E.createElement(y,{dimColor:true},"\u8F93\u5165\u4F60\u7684\u6D88\u606F:"),E.createElement(_,{marginTop:1},E.createElement(y,{color:"green",bold:true},"\u276F "),t?E.createElement(y,null,a,E.createElement(y,{inverse:true},l),c):E.createElement(_,null,E.createElement(y,{inverse:true}," "),E.createElement(y,{dimColor:true},"\u8F93\u5165\u6D88\u606F...")))),E.createElement(_,{marginTop:1,justifyContent:"space-between"},E.createElement(y,{dimColor:true},"Enter: \u786E\u8BA4"),E.createElement(y,{dimColor:true},"ESC: \u53D6\u6D88")))};var no=r=>r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:String(r),dE=r=>{switch(r){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},$b=({agentContextStats:r,onClose:e})=>{let{columns:t}=Ws();Xe((s,o)=>{(o.escape||s==="q")&&e();},{isActive:true});let n=[...r].sort((s,o)=>s.agentId==="Main"?-1:o.agentId==="Main"?1:s.agentLabel.localeCompare(o.agentLabel));return E.createElement(_,{flexDirection:"column",width:"100%"},E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{bold:true,color:"cyan"},"Agent Context Overview"),E.createElement(y,{dimColor:true},"ESC to close")),E.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),n.length===0?E.createElement(y,{dimColor:true},"No agent context stats available."):n.map(s=>{let o=s.contextWindow||0,i=s.tokensUsedForContext||0,a=o>0?i/o:0,l=Math.round(a*100),{icon:c,color:u}=dE(s.status),d=s.currentTask?s.currentTask.length>40?`${s.currentTask.slice(0,37)}...`:s.currentTask:"";return E.createElement(_,{key:s.agentId,justifyContent:"space-between",marginTop:1},E.createElement(_,null,E.createElement(y,{color:"magenta"},s.agentLabel),E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:u},c),d&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{dimColor:true},d))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},no(s.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},no(s.output)),(s.cacheCreationTokens||s.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},no(s.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},no(s.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},no(i)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},no(o)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:a>.8?"red":a>.5?"yellow":"green"},l,"%"),E.createElement(y,{dimColor:true},")")))}),E.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),E.createElement(y,{dimColor:true},"Tip: Press Q or ESC to return"))};var Ob=({messages:r})=>r.length===0?null:E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:"magenta",bold:true},"\u250C\u2500 "),E.createElement(y,{color:"magenta",bold:true},"Queued (",r.length,")"),E.createElement(y,{color:"magenta",bold:true}," \u2500")),r.map((e,t)=>E.createElement(_,{key:e.id,paddingLeft:1},E.createElement(y,{color:"gray"},"\u2502 "),E.createElement(y,{color:"cyan",bold:true},"> "),E.createElement(y,{color:"white"},e.text.length>70?e.text.substring(0,67)+"...":e.text))),E.createElement(_,null,E.createElement(y,{color:"magenta",bold:true},"\u2514\u2500"),E.createElement(y,{dimColor:true}," Press "),E.createElement(y,{color:"yellow"},"\u2191"),E.createElement(y,{dimColor:true}," to edit queued messages")));Ql();re();var vE=[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg"],CE=r=>{let e=new WeakSet;try{return JSON.stringify(r,(t,n)=>{if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return n})}catch{try{return String(r)}catch{return "[Unserializable]"}}};function xE(r){if(!r)return false;let e=r.trim(),t=e.toLowerCase(),n=vE.some(o=>t.endsWith(o)),s=e.startsWith("/")||e.startsWith("./")||e.startsWith("~/")||e.includes("/")&&n;return n&&s}var Bb=({staticEntries:r=[],pendingEntries:e=[],isRunning:t,statusText:n="",tokenStats:s,streamingTokens:o=0,streamingStartTime:i=null,accumulatedRunTime:a=0,version:l=ro,provider:c="OpenAI",model:u="gpt-4",workDir:d=process.cwd(),showHeader:m=true,thinkingEnabled:g=true,selectMenuOptions:h=null,textPromptOptions:f=null,contextMenuActive:v=false,agentContextScreenActive:b=false,compressionMode:C="sync",compactionThreshold:w=.85,agentContextStats:I=[],runMode:M="single",networkStats:N,cooperateStats:R,commandOutput:O=[],attachedImages:k=[],interruptInputActive:A=false,queuedMessages:T=[],currentPlanSteps:P=[],getCompletions:$,onStaticRendered:G,onSubmit:S,onInterrupt:L,onExit:F,onContextMenuToggle:U,onAgentContextScreenToggle:H,onClearCommandOutput:ee,onAttachImage:j,onClearImages:z,onInterruptInputSubmit:ue,onInterruptInputCancel:V,onShowInterruptInput:ve})=>{let[Z,X]=useState(""),[Y,J]=useState([]),[Q,te]=useState(-1),[pe,D]=useState(null),q=useRef(false),se=useMemo(()=>!$||!Z.startsWith("/")?[]:$(Z),[Z,$]),le=useContext(br);useEffect(()=>{if(!le?.internal_eventEmitter||!j)return;let K=xe=>{ae("CLI_APP",`\u{1F4CE} Received image-paste event from vendor Ink: ${xe.name}`),j(xe);};return le.internal_eventEmitter.on("image-paste",K),()=>{le.internal_eventEmitter.off("image-paste",K);}},[le,j]),useEffect(()=>{f?.defaultValue&&X(f.defaultValue);},[f?.defaultValue]),Xe((K,xe)=>{if(xe.escape){if(b)return;pe?D(null):O.length>0&&ee&&ee();}},{isActive:!h&&!pe});let _e=e.filter(K=>K.type!=="thinking"&&K.type!=="reasoning"),$e=K=>{if(!K)return false;let{content:xe}=K;return typeof xe=="string"?xe.trim().length>0:Array.isArray(xe)?xe.some(fe=>{if(!fe||typeof fe!="object"||!("type"in fe))return false;switch(fe.type){case "text":return typeof fe.text=="string"&&fe.text.trim().length>0;case "image_url":return true;case "tool_use":return true;case "tool_result":return fe.content!==null&&fe.content!==void 0&&String(fe.content).trim().length>0;case "thinking":return typeof fe.thinking=="string"&&fe.thinking.trim().length>0;case "redacted_thinking":return typeof fe.data=="string"&&fe.data.trim().length>0;default:return true}}):false},W=K=>{if(K.message){let _o=$e(K.message);if(K.type==="user"&&!_o&&process.env.CLI_DEBUG==="1"){let Io=CE(K.message.content).slice(0,100);ae("APP",`User message filtered out! entry.id=${K.id}, message.role=${K.message.role}, content=${Io}`);}return _o}let xe=typeof K.text=="string"&&K.text.trim().length>0,fe=K.type==="plan"&&!!K.planSteps&&K.planSteps.length>0,et=(K.type==="pipeline_node_start"||K.type==="pipeline_node_complete"||K.type==="pipeline_node_fail"||K.type==="pipeline_node_retry")&&(K.pipelineNode||K.pipelineNodeRetry),Bs=(K.type==="network_node_start"||K.type==="network_node_complete"||K.type==="network_node_fail")&&K.networkNode,ma=(K.type==="ccb_review"||K.type==="ccb_agent_review"||K.type==="ccb_retry"||K.type==="ccb_failed")&&!!(K.ccbReview||K.ccbAgentReview||K.ccbRetry||K.ccbFailed),ga=K.type==="pipeline_dag"&&!!K.pipelineDAG;return !!(xe||fe||et||Bs||ma||ga)},ne=useMemo(()=>_e.filter(W),[_e]),ie=useMemo(()=>{let K=r.filter(W);return process.env.CLI_DEBUG==="1"&&ae("APP",`visibleStaticEntries: staticEntries=${r.length}, visible=${K.length}, types=${K.map(xe=>xe.type).join(",")}`),K},[r]),Ae=m&&!q.current,Ne=E.useCallback((K,xe)=>K,[]),Le=useMemo(()=>{let K=[],xe=ie.length+ne.length;return Ae&&K.push(E.createElement(ob,{key:"header",version:l,provider:c,model:u,workDir:d})),ie.forEach((fe,et)=>{K.push(E.createElement(Lp,{key:`static-entry-${fe.id}`,entry:fe})),(et<ie.length-1||xe>ie.length)&&K.push(E.createElement(y,{key:`static-spacer-${fe.id}`},""));}),K},[Ae,ie,ne.length,l,c,u,d]);if(useEffect(()=>{!Ae&&r.length===0||(Ae&&(q.current=true),G?.());},[Ae,r.length,G]),b)return E.createElement($b,{agentContextStats:I,onClose:()=>H?.()});let Ie=K=>{if(f){if(!K.trim()&&!f.allowEmpty)return;f.onSubmit(K),X("");return}let xe=k.length>0,fe=K.trim().length>0;(fe||xe)&&(fe&&J([...Y,K]),te(-1),X(""),S(K,xe?k:void 0));},Rt=()=>{if(Y.length===0)return;let K=Q+1;K<Y.length&&(te(K),X(Y[Y.length-1-K]));},Fe=()=>{if(Q<=0){te(-1),X("");return}let K=Q-1;te(K),X(Y[Y.length-1-K]);},Me=K=>{if(!$)return null;let xe=$(K);if(xe.length===0)return null;if(xe.length===1)return xe[0];let fe=xe.map(et=>({label:et,value:et,description:void 0}));return D({message:"Select completion:",choices:fe,initialIndex:0,onSelect:et=>{X(et),D(null);},onCancel:()=>{D(null);}}),null};return E.createElement(_,{flexDirection:"column",width:"100%"},E.createElement(Fa,{items:Le},Ne),ne.map((K,xe)=>E.createElement(_,{key:`pending-wrapper-${K.id}`,flexDirection:"column"},E.createElement(Lp,{entry:K}),xe<ne.length-1&&E.createElement(y,null,""))),E.createElement(y,null,`
1690
+ `,T)+1,pe=F[ee+1].length,D=Math.min(j,pe),q=te+D;b(r.length-q);}return}if(J.leftArrow){b(Math.min(v+1,r.length));return}if(J.rightArrow){b(Math.max(v-1,0));return}if(J.home||J.ctrl&&Y==="a"){b(r.length);return}if(J.end||J.ctrl&&Y==="e"){b(0);return}if(J.backspace||J.delete){if(v===r.length){r.length===0&&a>0&&c&&c();return}let Q=T-1,te=r.slice(0,Q)+r.slice(Q+1);u(te);return}if(!J.ctrl&&!J.meta&&Y){let Q=r.slice(0,T)+Y+r.slice(T);u(Q);return}}}},{isActive:z});let Z=!r,X=()=>Z?E.createElement(_,null,E.createElement(y,{color:"green",bold:true},"> "),E.createElement(y,{inverse:true}," "),E.createElement(y,{dimColor:true},e)):F.map((Y,J)=>{let Q=J===ee,te=F.slice(0,J).reduce((le,_e)=>le+_e.length+1,0);te+Y.length;let D=-1;Q&&(D=T-te);let q=J===0?"> ":"\u2502 ",se="green";if(t)return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,{dimColor:true},Y));if(Q&&D>=0){let le=Y.slice(0,D),_e=Y[D]||" ",$e=Y.slice(D+1);return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,null,le,E.createElement(y,{inverse:true},_e),$e))}return E.createElement(_,{key:J},E.createElement(y,{color:se,bold:true},q),E.createElement(y,null,Y))});return E.createElement(_,{flexDirection:"column"},U&&!t&&E.createElement(_,{marginBottom:0},E.createElement(y,{dimColor:true}," \u21B5 Shift+Enter \u6362\u884C \u2502 Enter \u53D1\u9001 \u2502 ",F.length," \u884C")),E.createElement(_,{flexDirection:"column"},X()))};var oE=({isRunning:r,statusText:e="",tokenStats:t,streamingTokens:n=0,streamingStartTime:s=null,provider:o,model:i,onContextMenuToggle:a,agentContextStats:l=[],maxDisplayAgents:c=3,runMode:u="single",networkStats:d,cooperateStats:m})=>{let[g,h]=useState(null),[f,v]=useState(0),[b,C]=useState(0),[w,I]=useState(0),[M,N]=useState(0);useEffect(()=>{r?(h(s||Date.now()),v(0)):!r&&(t?.output||0)===0&&(h(null),v(0));},[r,s,t?.output]),useEffect(()=>{if(!r||g===null)return;let Z=setInterval(()=>{v(Math.floor((Date.now()-g)/1e3));},500);return ()=>clearInterval(Z)},[r,g]),useEffect(()=>{if(!r||n===0){C(0);return}let Z=Math.floor(n);if(b===Z)return;let X=Z-b,Y=Math.min(Math.abs(X),20),J=X/Y,te=setInterval(()=>{C(pe=>{let D=pe+J;return Math.abs(D-Z)<1?Z:D});},50);return ()=>clearInterval(te)},[n,r,b]),useEffect(()=>{let Z=t?.output||0;if(w===Z)return;let X=Z-w;if(Math.abs(X)>100){I(Z);return}let Y=Math.max(Math.ceil(Math.abs(X)/10),3),J=X/Y,te=setInterval(()=>{I(pe=>{let D=pe+J;return Math.abs(D-Z)<1?Z:D});},10);return ()=>clearInterval(te)},[t?.output,w]),useEffect(()=>{if(!r){N(0);return}let X=(e||"Thinking...").length,Y=setInterval(()=>{N(J=>(J+1)%(X+3));},80);return ()=>clearInterval(Y)},[r,e]);let R=()=>{if(f<60)return `${f}s`;let Z=Math.floor(f/60),X=f%60;return `${Z}m ${X}s`},O=Z=>Z>=1e6?(Z/1e6).toFixed(1)+"M":Z>=1e3?(Z/1e3).toFixed(1)+"K":Z.toString(),k=t?.contextWindow||0,A=t?.tokensUsedForContext||t?.total||0,T=t?.pressure||0,P=Math.round(T*100),$=()=>T>.8?"red":T>.5?"yellow":"green",G=Z=>Z.split("").map((Y,J)=>{let Q=J-M;return Q>=0&&Q<2?E.createElement(y,{key:J,color:"white",bold:true},Y):Q>=-1&&Q<0?E.createElement(y,{key:J,color:"cyanBright"},Y):E.createElement(y,{key:J,color:"cyan"},Y)}),L=(()=>{switch(u){case "single":return {icon:"\u{1F464}",label:"Single",color:"cyan"};case "collab":return {icon:"\u{1F91D}",label:"Collab",color:"magenta"};case "cooperate":return {icon:"\u{1F527}",label:"Cooperate",color:"yellow"};case "network":return {icon:"\u{1F310}",label:"Network",color:"blue"};default:return {icon:"\u{1F464}",label:"Single",color:"cyan"}}})(),F=e&&(e.includes("Streaming:")||e.toLowerCase().includes("stream")),U=e?.match(/Streaming:\s*(\w+)/),H=U?U[1]:null,ee=l.length>0,j=l.find(Z=>Z.agentId==="Main"),z=l.filter(Z=>Z.agentId!=="Main"),ue=z.length>c,V=()=>z.length===0?null:E.createElement(_,null,E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"magenta"},z.length),E.createElement(y,{dimColor:true}," workers"),ue&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 Ctrl+G"))),ve=(Z,X)=>{let Y=Z.pressure||0,J=Math.round(Y*100),Q=()=>Y>.8?"red":Y>.5?"yellow":"green",te=()=>{switch(Z.status||"idle"){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},{icon:pe,color:D}=te(),q=Z.currentTask?Z.currentTask.length>20?Z.currentTask.slice(0,17)+"...":Z.currentTask:"";return E.createElement(_,{key:Z.agentId,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{dimColor:true},X?"\u2514\u2500 ":"\u251C\u2500 "),E.createElement(y,{color:D},pe),E.createElement(y,null," "),E.createElement(y,{color:"magenta"},Z.agentLabel),q&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{dimColor:true},q))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Z.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(Z.output)),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},O(Z.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(Z.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:Q()},J,"%"),E.createElement(y,{dimColor:true},")")))};if(u==="network"){let Z=d?.teamSize||0,X=d?.activeAgents||0,Y=d?.currentPhase||"executing",J=d?.currentAgent,Q=d?.totalInputTokens||t?.input||0,te=d?.totalOutputTokens||t?.output||0,pe=d?.completedTasks,D=d?.totalTasks,se=(()=>{switch(Y){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})();return E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"blue"},"\u{1F310}"),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"blue"},Z),E.createElement(y,{dimColor:true}," agents"),X>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"green"},X),E.createElement(y,{dimColor:true}," active)")),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),J?E.createElement(E.Fragment,null,G(J),E.createElement(y,{dimColor:true},": "),E.createElement(y,{color:se.color},se.text)):E.createElement(y,{color:se.color},se.text),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,te>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,pe!==void 0&&D!==void 0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true},"tasks "),E.createElement(y,{color:"yellow"},pe),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},D),E.createElement(y,{dimColor:true}," \u2502 ")),r&&b>0&&E.createElement(E.Fragment,null,E.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),E.createElement(y,{dimColor:true}," \u2502 ")),E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Q)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(te))))}if(u==="cooperate"&&m){let{models:Z,phase:X,totalInputTokens:Y,totalOutputTokens:J,ccbResult:Q,dagProgress:te}=m,D=(()=>{switch(X){case "analyzing":return {text:"Analyzing",color:"cyan"};case "ccb_review":return {text:"CCB Review",color:"yellow"};case "dag_planning":return {text:"Planning",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Running",color:"cyan"}}})(),q=()=>Z.length===0?null:Z.map((le,_e)=>{let $e=le.status==="running"?"green":le.status==="completed"?"blue":"gray";return E.createElement(E.Fragment,{key:_e},_e>0&&E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:$e},le.shortName))}),se=Z.filter(le=>le.status==="completed").length;return E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"yellow"},"\u{1F527}"),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),e?G(e):E.createElement(y,{color:D.color},D.text),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")")),b>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ~"),E.createElement(y,{color:"magenta"},Math.floor(b)),E.createElement(y,{dimColor:true}," tok"))):E.createElement(_,null,J>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,Z.length>0&&E.createElement(E.Fragment,null,q(),E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:"yellow"},se),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},Z.length),E.createElement(y,{dimColor:true}," \u2502 ")),Q&&E.createElement(E.Fragment,null,E.createElement(y,{color:Q.approved?"green":"red"},Q.approved?"\u2713":"\u2717"),E.createElement(y,{dimColor:true}," CCB "),E.createElement(y,{color:"yellow"},Q.approveCount),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},Q.totalCount),E.createElement(y,{dimColor:true}," \u2502 ")),te&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true},"DAG "),E.createElement(y,{color:"yellow"},te.completedNodes),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},te.totalNodes),E.createElement(y,{dimColor:true}," \u2502 ")),E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(Y||t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(J||t?.output||0))))}if((u==="collab"||u==="cooperate")&&ee){let Z=j?.pressure||0,X=Math.round(Z*100),Y=()=>Z>.8?"red":Z>.5?"yellow":"green",J=z.length<=c&&z.length>0,Q=j?.agentLabel||"Main";return E.createElement(_,{flexDirection:"column"},E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:L.color},L.icon),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),E.createElement(y,{bold:true,color:"cyan"},"\u25CF"),E.createElement(y,null," "),F&&H?E.createElement(E.Fragment,null,G(`Streaming: ${H}`)):G(e||"Thinking..."),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,(j?.output||t?.output||0)>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,j?E.createElement(_,null,E.createElement(y,{dimColor:true},Q,": "),E.createElement(y,{color:"cyan"},O(j.input)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"green"},O(j.output)),(j.cacheCreationTokens||j.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},O(j.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},O(j.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"yellow"},O(j.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(j.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:Y()},X,"%"),E.createElement(y,{dimColor:true},")"),V()):E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(t?.output||0)),V()))),J&&z.map((te,pe)=>ve(te,pe===z.length-1)))}return E.createElement(_,{justifyContent:"space-between",width:"100%"},E.createElement(_,null,E.createElement(y,{color:L.color},L.icon),E.createElement(y,{dimColor:true}," \u2502 "),r?E.createElement(_,null,E.createElement(Xl,{type:"dots"}),E.createElement(y,null," "),E.createElement(y,{bold:true,color:"cyan"},"\u25CF"),E.createElement(y,null," "),F&&H?E.createElement(E.Fragment,null,G(`Streaming: ${H}`)):G(e||"Thinking..."),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true}," \u2022 esc to interrupt"),b>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 "),E.createElement(y,{color:"green"},"\u2193 ",Math.floor(b)),E.createElement(y,{dimColor:true}," ",F?"chars":"tokens")),E.createElement(y,{dimColor:true},")"))):E.createElement(_,null,(t?.output||0)>0?E.createElement(E.Fragment,null,E.createElement(y,{color:"green",bold:true},"\u25A0"),E.createElement(y,null," "),E.createElement(y,{color:"green"},"Complete!"),f>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"yellow"},R()),E.createElement(y,{dimColor:true},")"))):E.createElement(E.Fragment,null,E.createElement(y,{color:"cyan",bold:true},"\u25CF"),E.createElement(y,null," "),E.createElement(y,{color:"cyan"},"Ready")))),E.createElement(_,null,k>0?E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},O(t?.input||0)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},O(t?.output||0)),(t?.cacheCreationTokens||t?.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},O(t.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},O(t.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},O(A)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},O(k)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:$()},P,"%"),E.createElement(y,{dimColor:true},")")):E.createElement(y,{dimColor:true},"context: --")))},iE=(r,e)=>!r&&!e?true:!r||!e||r.length!==e.length?false:r.every((t,n)=>{let s=e[n];return t.agentId===s.agentId&&t.input===s.input&&t.output===s.output&&t.pressure===s.pressure&&t.tokensUsedForContext===s.tokensUsedForContext&&t.status===s.status&&t.currentTask===s.currentTask&&t.contextWindow===s.contextWindow&&t.cacheCreationTokens===s.cacheCreationTokens&&t.cacheReadTokens===s.cacheReadTokens}),Sb=E.memo(oE,(r,e)=>r.isRunning===e.isRunning&&r.statusText===e.statusText&&r.streamingTokens===e.streamingTokens&&r.streamingStartTime===e.streamingStartTime&&r.tokenStats?.input===e.tokenStats?.input&&r.tokenStats?.output===e.tokenStats?.output&&r.tokenStats?.total===e.tokenStats?.total&&r.tokenStats?.pressure===e.tokenStats?.pressure&&r.tokenStats?.cacheCreationTokens===e.tokenStats?.cacheCreationTokens&&r.tokenStats?.cacheReadTokens===e.tokenStats?.cacheReadTokens&&r.runMode===e.runMode&&r.networkStats?.teamSize===e.networkStats?.teamSize&&r.networkStats?.activeAgents===e.networkStats?.activeAgents&&r.networkStats?.currentPhase===e.networkStats?.currentPhase&&r.networkStats?.currentAgent===e.networkStats?.currentAgent&&r.networkStats?.totalInputTokens===e.networkStats?.totalInputTokens&&r.networkStats?.totalOutputTokens===e.networkStats?.totalOutputTokens&&r.networkStats?.completedTasks===e.networkStats?.completedTasks&&r.networkStats?.totalTasks===e.networkStats?.totalTasks&&r.cooperateStats?.phase===e.cooperateStats?.phase&&r.cooperateStats?.totalInputTokens===e.cooperateStats?.totalInputTokens&&r.cooperateStats?.totalOutputTokens===e.cooperateStats?.totalOutputTokens&&r.cooperateStats?.ccbResult?.approved===e.cooperateStats?.ccbResult?.approved&&r.cooperateStats?.ccbResult?.approveCount===e.cooperateStats?.ccbResult?.approveCount&&r.cooperateStats?.dagProgress?.completedNodes===e.cooperateStats?.dagProgress?.completedNodes&&r.cooperateStats?.models?.length===e.cooperateStats?.models?.length&&iE(r.agentContextStats,e.agentContextStats));var kb=({isRunning:r,hasInput:e,customHints:t,menuActive:n=false,thinkingEnabled:s=true,accumulatedRunTime:o=0,provider:i,model:a,runMode:l="single"})=>{let[c,u]=useState(o);useEffect(()=>{if(!r){u(o);return}u(o);let f=setInterval(()=>{u(v=>v+1);},1e3);return ()=>clearInterval(f)},[r,o]);let d=()=>{if(c<60)return `${c}s`;let f=Math.floor(c/60),v=c%60;if(f<60)return `${f}m ${v}s`;let b=Math.floor(f/60),C=f%60;return `${b}h ${C}m`},m=()=>{if(!i||!a)return "";let f=i,v=i.indexOf(" (");v>0&&(f=i.substring(0,v));let b=a.length>35?a.substring(0,32)+"...":a;return `${f}/${b}`},h=(()=>{switch(l){case "single":return {label:"SINGLE",color:"cyan"};case "collab":return {label:"COLLAB",color:"magenta"};case "cooperate":return {label:"COOPERATE",color:"yellow"};case "network":return {label:"NETWORK",color:"blue"};default:return {label:"SINGLE",color:"cyan"}}})();return t?E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{color:"yellow"},t)):n?E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{dimColor:true}," ","\u2191\u2193 to select, Enter to confirm, ESC to cancel")):E.createElement(_,{justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{dimColor:true},"? for shortcuts"),c>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2022 "),E.createElement(y,{color:"cyan"},d()),E.createElement(y,{dimColor:true}," session"))),E.createElement(_,null,E.createElement(y,{color:h.color,bold:true},"["),E.createElement(y,{color:h.color},h.label),E.createElement(y,{color:h.color,bold:true},"]"),E.createElement(y,{dimColor:true}," \u2022 "),m()&&E.createElement(E.Fragment,null,E.createElement(y,{color:"magenta",bold:true},"["),E.createElement(y,{color:"magenta"},m()),E.createElement(y,{color:"magenta",bold:true},"]"),E.createElement(y,{dimColor:true}," \u2022 ")),s?E.createElement(y,{color:"cyan"},"Thinking on"):E.createElement(y,{dimColor:true},"Thinking off"),E.createElement(y,{dimColor:true}," (tab to toggle)")))};var _b=({attachments:r,onRemove:e})=>r.length===0?null:E.createElement(_,{flexDirection:"column",paddingLeft:2,marginBottom:1},E.createElement(y,{color:"magenta",dimColor:true},"Attachments:"),r.map((t,n)=>{let s=t.name||t.path?.split("/").pop()||"unknown",o=t.type?.startsWith("image/")||t.mediaType?.startsWith("image/")||s.match(/\.(png|jpg|jpeg|gif|webp)$/i);return E.createElement(_,{key:n},E.createElement(y,{color:"magenta"},o?"\u{1F4CE} \u{1F5BC}\uFE0F ":"\u{1F4CE} ",s),e&&E.createElement(y,{color:"gray",dimColor:true}," (press \u232B Backspace to remove)"))}));var Ib=({planSteps:r,isRunning:e=false})=>{let t=r.find(s=>s.status==="pending");if(!t||!e)return null;let n=t.step.length>50?t.step.substring(0,47)+"...":t.step;return E.createElement(_,{paddingLeft:3},E.createElement(y,{dimColor:true},"\u2514\u2500 "),E.createElement(y,{color:"gray"},"\u25CB"),E.createElement(y,{dimColor:true}," Next: "),E.createElement(y,{color:"cyan"},n))};var Eb=({contextWindow:r,tokensUsed:e,systemTokens:t=0,userTokens:n=0,assistantTokens:s=0,toolCallTokens:o=0,toolResultTokens:i=0,compactionThreshold:a=.8,compressionMode:l="sync",agentContextStats:c=[],runMode:u="single",networkStats:d,onClose:m})=>{let g=R=>R>=1e6?`${(R/1e6).toFixed(1)}M`:R>=1e3?`${(R/1e3).toFixed(1)}k`:R.toString(),h=R=>R>.8?"red":R>.5?"yellow":"green",f=({color:R,label:O,tokens:k,total:A,indent:T=2})=>{let P=A>0?(k/A*100).toFixed(2):"0.00";return E.createElement(_,{marginLeft:T},E.createElement(y,{color:R},"\u25A0"),E.createElement(y,null," ",O,": "),E.createElement(y,{color:"yellow"},g(k)),E.createElement(y,{dimColor:true}," tokens (",P,"%)"))},v=({stat:R,indent:O=2})=>{let k=R.cacheCreationTokens||0,A=R.cacheReadTokens||0,T=R.contextWindow||2e5,P=R.tokensUsedForContext||0,$=T>0?P/T:0,G=Math.round($*100);return E.createElement(_,{marginLeft:O,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"magenta"},R.agentLabel||R.agentId),R.status&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:R.status==="running"?"green":R.status==="error"?"red":"gray"},R.status==="running"?"\u25CF":R.status==="completed"?"\u2713":R.status==="error"?"\u2717":"\u25CB"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},g(R.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},g(R.output)),(k>0||A>0)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," \u2502 cw "),E.createElement(y,{color:"blue"},g(k)),E.createElement(y,{dimColor:true}," cr "),E.createElement(y,{color:"blue"},g(A))),E.createElement(y,{dimColor:true}," \u2502 ctx "),E.createElement(y,{color:"yellow"},g(P)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},g(T)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:h($)},G,"%"),E.createElement(y,{dimColor:true},")")))},b=({stat:R,indent:O=2})=>{let k=R.contextWindow>0?R.tokensUsedForContext/R.contextWindow:0,A=Math.round(k*100);return E.createElement(_,{marginLeft:O,justifyContent:"space-between"},E.createElement(_,null,E.createElement(y,{color:"magenta"},R.agentLabel||R.agentId),R.status&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:R.status==="running"?"green":R.status==="error"?"red":"gray"},R.status==="running"?"\u25CF":R.status==="completed"?"\u2713":R.status==="error"?"\u2717":"\u25CB"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},g(R.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},g(R.output)),E.createElement(y,{dimColor:true}," \u2502 "),E.createElement(y,{color:"yellow"},g(R.tokensUsedForContext)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},g(R.contextWindow)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:h(k)},A,"%"),E.createElement(y,{dimColor:true},")")))};if(u==="network"){let R=d?.teamSize||c.length||0,O=d?.activeAgents||0,k=d?.totalInputTokens||0,A=d?.totalOutputTokens||0,T=k+A,$=(G=>{switch(G){case "analyzing":return {text:"Analyzing",color:"cyan"};case "bidding":return {text:"Bidding",color:"yellow"};case "negotiating":return {text:"Negotiating",color:"magenta"};case "executing":return {text:"Executing",color:"green"};case "reviewing":return {text:"Reviewing",color:"blue"};case "complete":return {text:"Complete",color:"green"};default:return {text:"Idle",color:"gray"}}})(d?.currentPhase);return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:"blue",paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:"blue"},"\u{1F310}"),E.createElement(y,{bold:true,color:"blue"}," Network Context Overview")),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Team Size: "),E.createElement(y,{color:"blue",bold:true},R),E.createElement(y,{dimColor:true}," agents"),O>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"green"},O),E.createElement(y,{dimColor:true}," active)"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"Current Phase: "),E.createElement(y,{color:$.color,bold:true},$.text),d?.currentAgent&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," - "),E.createElement(y,{color:"cyan"},d.currentAgent))),d?.completedTasks!==void 0&&d?.totalTasks!==void 0&&E.createElement(_,null,E.createElement(y,{dimColor:true},"Tasks: "),E.createElement(y,{color:"yellow"},d.completedTasks),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},d.totalTasks),E.createElement(y,{dimColor:true}," completed"))),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(y,{bold:true,dimColor:true},"Total Token Usage:"),E.createElement(_,{marginLeft:2},E.createElement(y,{dimColor:true},"Input: "),E.createElement(y,{color:"cyan"},g(k)),E.createElement(y,{dimColor:true}," \u2502 Output: "),E.createElement(y,{color:"green"},g(A)),E.createElement(y,{dimColor:true}," \u2502 Total: "),E.createElement(y,{color:"yellow"},g(T)))),c.length>0&&E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Agent Context Details:"),c.map(G=>E.createElement(v,{key:G.agentId,stat:G})),E.createElement(_,{marginTop:1,marginLeft:2},E.createElement(y,{dimColor:true},"Total Tokens: "),E.createElement(y,{color:"yellow"},g(c.reduce((G,S)=>G+S.input+S.output,0))),E.createElement(y,{dimColor:true}," across "),E.createElement(y,{color:"cyan"},c.length),E.createElement(y,{dimColor:true}," agents"))),c.length===0&&E.createElement(_,{marginTop:1},E.createElement(y,{dimColor:true,italic:true},"Agent context details not available yet.")))}if((u==="collab"||u==="cooperate")&&c.length>0){let R=c.find(S=>S.agentId==="Main"),O=c.filter(S=>S.agentId!=="Main"&&S.agentId!=="supervisor"),k=c.reduce((S,L)=>S+L.tokensUsedForContext,0),A=c.reduce((S,L)=>S+L.input,0),T=c.reduce((S,L)=>S+L.output,0),P=u==="collab"?"\u{1F91D}":"\u{1F527}",$=u==="collab"?"Collab":"Cooperate",G=u==="collab"?"magenta":"yellow";return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:G,paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:G},P),E.createElement(y,{bold:true,color:G}," ",$," Context Overview")),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Total Agents: "),E.createElement(y,{color:G,bold:true},c.length),O.length>0&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," (1 Main + "),E.createElement(y,{color:"cyan"},O.length),E.createElement(y,{dimColor:true}," Workers)"))),E.createElement(_,null,E.createElement(y,{dimColor:true},"Total Tokens: "),E.createElement(y,{color:"cyan"},g(A)),E.createElement(y,{dimColor:true}," in / "),E.createElement(y,{color:"green"},g(T)),E.createElement(y,{dimColor:true}," out"))),R&&E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(y,{bold:true,dimColor:true},"Main Agent:"),E.createElement(b,{stat:R})),O.length>0&&E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Worker Agents (",O.length,"):"),O.map(S=>E.createElement(b,{key:S.agentId,stat:S}))),E.createElement(_,{marginTop:1},E.createElement(y,{dimColor:true},"Combined Context: "),E.createElement(y,{color:"yellow"},g(k)),E.createElement(y,{dimColor:true}," tokens")))}let C=r-e,w=r>0?e/r:0,I=Math.floor(r*a),M=Math.max(0,I-e),N=Math.round(w*100);return E.createElement(_,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:2,paddingY:1},E.createElement(_,{justifyContent:"space-between",marginBottom:1},E.createElement(y,{bold:true,color:"cyan"},"Context Window Details"),E.createElement(y,{dimColor:true},"(press ESC to close)")),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Total: "),E.createElement(y,{color:"yellow"},g(e)),E.createElement(y,{dimColor:true}," / "),E.createElement(y,{color:"yellow"},g(r)),E.createElement(y,{dimColor:true}," tokens ("),E.createElement(y,{color:h(w),bold:true},N,"%"),E.createElement(y,{dimColor:true},")")),E.createElement(_,null,E.createElement(y,{dimColor:true},"Remaining: "),E.createElement(y,{color:"green"},g(C)),E.createElement(y,{dimColor:true}," tokens"))),E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{dimColor:true},"Compression: "),E.createElement(y,{color:l==="sync"?"green":"yellow"},l==="sync"?"Sync LLM":"Async LLM"),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:"cyan"},Math.round(a*100),"%"),E.createElement(y,{dimColor:true}," threshold)"))),M>0?E.createElement(_,{marginBottom:1},E.createElement(y,{dimColor:true},"Compaction in: "),E.createElement(y,{color:"cyan"},g(M)),E.createElement(y,{dimColor:true}," tokens")):E.createElement(_,{marginBottom:1},E.createElement(y,{color:"red",bold:true},"\u26A0\uFE0F Compaction threshold reached!")),E.createElement(_,{flexDirection:"column"},E.createElement(y,{bold:true,dimColor:true},"Context Breakdown:"),E.createElement(f,{color:"magenta",label:"System",tokens:t,total:e}),E.createElement(f,{color:"cyan",label:"User",tokens:n,total:e}),E.createElement(f,{color:"green",label:"Assistant",tokens:s,total:e}),E.createElement(f,{color:"blue",label:"Tool Calls",tokens:o,total:e}),E.createElement(f,{color:"yellow",label:"Tool Results",tokens:i,total:e}),E.createElement(_,{marginTop:1,marginLeft:2},E.createElement(y,{dimColor:true},"Usage: "),E.createElement(y,{color:h(w)},"\u2588".repeat(Math.floor(w*20))),E.createElement(y,{dimColor:true},"\u2591".repeat(20-Math.floor(w*20))))))};var Pb=[{name:"/help",description:"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F",category:"\u57FA\u7840"},{name:"/clear",description:"\u6E05\u7A7A\u5C4F\u5E55",category:"\u57FA\u7840"},{name:"/exit",description:"\u9000\u51FA\u7A0B\u5E8F",category:"\u57FA\u7840"},{name:"/mode",description:"\u5207\u6362 ask/agent \u6A21\u5F0F",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/collab",description:"\u534F\u4F5C\u6A21\u5F0F\u914D\u7F6E",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/thinking",description:"\u601D\u8003\u6A21\u5F0F\u5F00\u5173",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/approval",description:"\u5BA1\u6279\u6A21\u5F0F\u5F00\u5173",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/sandbox",description:"\u6C99\u76D2\u6A21\u5F0F\u8BBE\u7F6E",category:"\u6A21\u5F0F",hasSubMenu:true},{name:"/provider",description:"\u7BA1\u7406 AI \u670D\u52A1\u5546",category:"AI",hasSubMenu:true},{name:"/model",description:"\u7BA1\u7406\u6A21\u578B",category:"AI",hasSubMenu:true},{name:"/sessions",description:"\u67E5\u770B\u6240\u6709\u4F1A\u8BDD",category:"\u4F1A\u8BDD"},{name:"/session",description:"\u5207\u6362\u4F1A\u8BDD",category:"\u4F1A\u8BDD",hasSubMenu:true},{name:"/session-new",description:"\u521B\u5EFA\u65B0\u4F1A\u8BDD",category:"\u4F1A\u8BDD"},{name:"/session-info",description:"\u5F53\u524D\u4F1A\u8BDD\u4FE1\u606F",category:"\u4F1A\u8BDD"},{name:"/checkpoint",description:"\u521B\u5EFA\u68C0\u67E5\u70B9",category:"\u4F1A\u8BDD"},{name:"/checkpoints",description:"\u67E5\u770B\u68C0\u67E5\u70B9\u5217\u8868",category:"\u4F1A\u8BDD"},{name:"/rollback",description:"\u56DE\u6EDA\u5230\u68C0\u67E5\u70B9",category:"\u4F1A\u8BDD",hasSubMenu:true},{name:"/undo",description:"\u64A4\u9500\u64CD\u4F5C",category:"\u4F1A\u8BDD"},{name:"/compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",category:"\u4F1A\u8BDD"},{name:"/processes",description:"\u67E5\u770B\u540E\u53F0\u8FDB\u7A0B",category:"\u8FDB\u7A0B"},{name:"/ps",description:"\u67E5\u770B\u540E\u53F0\u8FDB\u7A0B (\u7B80\u5199)",category:"\u8FDB\u7A0B"},{name:"/kill",description:"\u7EC8\u6B62\u8FDB\u7A0B",category:"\u8FDB\u7A0B",hasSubMenu:true},{name:"/attach",description:"\u6DFB\u52A0\u9644\u4EF6",category:"\u5DE5\u5177"},{name:"/attachments",description:"\u67E5\u770B\u9644\u4EF6",category:"\u5DE5\u5177"},{name:"/workspace",description:"\u5DE5\u4F5C\u533A\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/mcp",description:"MCP \u670D\u52A1\u5668\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/context",description:"\u4E0A\u4E0B\u6587\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/memory",description:"\u5185\u5B58\u8BCA\u65AD",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/remote",description:"\u8FDC\u7A0B\u670D\u52A1",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/index",description:"\u7D22\u5F15\u7BA1\u7406",category:"\u5DE5\u5177",hasSubMenu:true},{name:"/stats",description:"\u4F1A\u8BDD\u7EDF\u8BA1",category:"\u7EDF\u8BA1"},{name:"/statistic",description:"Token \u4F7F\u7528\u7EDF\u8BA1",category:"\u7EDF\u8BA1",hasSubMenu:true},{name:"/config-clear",description:"\u6E05\u9664\u914D\u7F6E",category:"\u914D\u7F6E"},{name:"/config-reset",description:"\u91CD\u7F6E\u914D\u7F6E",category:"\u914D\u7F6E"},{name:"/notify",description:"\u901A\u77E5\u8BBE\u7F6E",category:"\u914D\u7F6E",hasSubMenu:true}],cE=({isVisible:r,filter:e="",onSelect:t,onCancel:n})=>{let[s,o]=useState(0),[i,a]=useState(0),l=10,c=e&&e!=="/"?Pb.filter(m=>m.name.toLowerCase().includes(e.toLowerCase())||m.description.toLowerCase().includes(e.toLowerCase())):Pb;useEffect(()=>{o(0),a(0);},[e]),useEffect(()=>{s<i?a(s):s>=i+l&&a(s-l+1);},[s]),Xe((m,g)=>{if(r){if(g.escape){n();return}if(g.upArrow){o(h=>h>0?h-1:c.length-1);return}if(g.downArrow){o(h=>h<c.length-1?h+1:0);return}if(g.pageUp||g.ctrl&&m==="u"){o(h=>Math.max(0,h-l));return}if(g.pageDown||g.ctrl&&m==="d"){o(h=>Math.min(c.length-1,h+l));return}if(g.return){c.length>0&&t(c[s].name);return}if(g.tab){c.length>0&&t(c[s].name+" ");return}}},{isActive:r});let u=c.slice(i,i+l),d=E.useMemo(()=>u.map((m,g)=>{let f=i+g===s;return E.createElement(_,{key:m.name},E.createElement(y,{color:f?"cyan":"white"},f?"\u203A ":" "),E.createElement(y,{color:f?"cyan":"white",bold:f},"\u25CF ",m.name),E.createElement(y,{color:f?"cyan":"gray"}," ","- ",m.description))}),[u,i,s]);return !r||c.length===0?null:E.createElement(_,{flexDirection:"column",paddingLeft:0},E.createElement(y,{color:"cyan",bold:true},"\u547D\u4EE4\u83DC\u5355"),E.createElement(y,{dimColor:true},"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88"),i>0&&E.createElement(y,{dimColor:true}," \u2191 \u66F4\u591A..."),d,i+l<c.length&&E.createElement(y,{dimColor:true}," \u2193 \u66F4\u591A..."),E.createElement(y,{dimColor:true},"\u2500".repeat(40)),E.createElement(y,{dimColor:true},c.length," \u4E2A\u547D\u4EE4 \xB7 \u7B2C ",Math.floor(i/l)+1,"/",Math.ceil(c.length/l)," \u9875"))},Rb=E.memo(cE,(r,e)=>r.isVisible===e.isVisible&&r.filter===e.filter&&r.onSelect===e.onSelect&&r.onCancel===e.onCancel);re();var uE=({inputValue:r,isRunning:e,statusText:t="",tokenStats:n,streamingTokens:s=0,streamingStartTime:o=null,accumulatedRunTime:i=0,provider:a,model:l,customHints:c,attachments:u=[],multiline:d=false,completions:m=[],menuActive:g=false,promptActive:h=false,promptMessage:f,promptHint:v,promptOnCancel:b,thinkingEnabled:C=true,contextMenuActive:w=false,compressionMode:I="sync",compactionThreshold:M=.85,agentContextStats:N=[],runMode:R="single",networkStats:O,cooperateStats:k,currentPlanSteps:A=[],onInputChange:T,onSubmit:P,onInterrupt:$,onExit:G,onHistoryUp:S,onHistoryDown:L,onTabComplete:F,onRemoveAttachment:U,onContextMenuToggle:H,onAgentContextScreenToggle:ee,onPasteImage:j,onShowInterruptInput:z})=>{let{columns:ue}=Ws(),V=r==="/"||r.startsWith("/")&&!r.includes(" "),ve=E.useCallback(X=>{X.endsWith(" ")?T(X.trim()):(T(""),setTimeout(()=>{P(X);},0));},[T,P]),Z=E.useCallback(()=>{T("");},[T]);return Xe((X,Y)=>{if(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","BottomBar useInput",{key:Y,input:X,menuActive:g,promptActive:h,isRunning:e,inputValue:r.substring(0,20)}),!g){if(e&&X==="i"&&!Y.ctrl&&!Y.meta&&z){p.debug("INK_INPUT",'Interrupt input triggered with "i" key'),z();return}if(Y.ctrl&&X==="g"&&ee){ee();return}if(Y.ctrl&&X==="z"){process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+Z blocked (prevents suspension)");return}if(Y.escape){let J=!X||X==="\x1B"||X==="";if(p.info("INK_INPUT",`ESC detected: isRealEscape=${J}, input=${JSON.stringify(X)}, isRunning=${e}`),!J){p.debug("INK_INPUT","Ignoring escape sequence (not real ESC key)");return}if(w&&H){H();return}if(h&&b){b(),T("");return}e?(p.info("INK_INPUT","\u{1F6D1} User pressed ESC to interrupt task"),$()):r&&T("");return}Y.ctrl&&X==="c"&&(process.env.CLI_DEBUG==="1"&&p.debug("INK_INPUT","Ctrl+C pressed",{isRunning:e}),e?$():(p.info("INK_INPUT","\u26A0\uFE0F Ctrl+C pressed - exiting"),G()));}},{isActive:true}),E.createElement(_,{flexDirection:"column"},h&&f&&E.createElement(_,{paddingX:2,paddingY:1},E.createElement(y,{color:"cyan",bold:true},f)),h&&v&&E.createElement(_,{paddingX:2,paddingBottom:1},E.createElement(y,{dimColor:true},v)),!h&&E.createElement(_,{marginTop:1,width:"100%"},E.createElement(Sb,{isRunning:e,statusText:t,tokenStats:n,streamingTokens:s,streamingStartTime:o,provider:a,model:l,onContextMenuToggle:H,agentContextStats:N,runMode:R,networkStats:O,cooperateStats:k})),!h&&E.createElement(Ib,{planSteps:A,isRunning:e}),u.length>0&&E.createElement(_b,{attachments:u,onRemove:U}),E.createElement(_,{flexDirection:"column"},E.createElement(y,{color:"gray"},"\u2500".repeat(ue)),E.createElement(Tb,{value:r,placeholder:h?v||"Type your answer...":e?"Enter to interrupt and send...":"Type a message...",disabled:g,multiline:d,completions:[],menuActive:g,slashMenuActive:V,imageCount:u.length,onChange:T,onSubmit:X=>P(X??r),onHistoryUp:S,onHistoryDown:L,onTabComplete:F,onPasteImage:j,onRemoveLastAttachment:U?()=>U(u.length-1):void 0}),E.createElement(y,{color:"gray"},"\u2500".repeat(ue))),V&&!g&&!e&&E.createElement(Rb,{isVisible:true,filter:r,onSelect:ve,onCancel:Z}),!h&&E.createElement(kb,{isRunning:e,hasInput:r.length>0,customHints:c,menuActive:g,thinkingEnabled:C,accumulatedRunTime:i,provider:a,model:l,runMode:R}),w&&n?.contextWindow&&H&&E.createElement(Eb,{contextWindow:n.contextWindow,tokensUsed:n.tokensUsedForContext||n.total,systemTokens:n.systemTokens,userTokens:n.userTokens,assistantTokens:n.assistantTokens,toolCallTokens:n.toolCallTokens,toolResultTokens:n.toolResultTokens,compressionMode:I,compactionThreshold:M,agentContextStats:N,runMode:R,networkStats:O,onClose:H}))},Db=E.memo(uE);var Bp=({message:r,choices:e,initialIndex:t=0,hint:n,maxVisible:s=20,onSelect:o,onCancel:i,onExit:a})=>{let[l,c]=useState(t),[u,d]=useState(0),[m,g]=useState(null);useEffect(()=>{c(t);},[t]),useEffect(()=>{let b=setTimeout(()=>{g(Date.now());},200);return ()=>clearTimeout(b)},[]),useEffect(()=>{if(e.length<=s){d(0);return}l<u?d(l):l>=u+s&&d(l-s+1);},[l,e.length,s,u]),Xe((b,C)=>{if(C.ctrl&&b==="c"&&a){process.nextTick(()=>a());return}if(C.escape&&i){process.nextTick(()=>i());return}if(C.upArrow){c(w=>w>0?w-1:e.length-1);return}if(C.downArrow){c(w=>w<e.length-1?w+1:0);return}if(C.return){if(!m)return;process.nextTick(()=>o(e[l].value));return}});let h=Math.min(e.length,s),f=u>0,v=u+h<e.length;return E.createElement(_,{flexDirection:"column"},r&&E.createElement(_,{marginBottom:1,paddingX:2},E.createElement(y,{bold:true,color:"cyan"},r)),n&&E.createElement(_,{marginBottom:1,paddingX:2},E.createElement(y,{dimColor:true},n)),f&&E.createElement(_,{paddingX:2},E.createElement(y,{dimColor:true}," \u2191 more")),e.slice(u,u+h).map((b,C)=>{let w=u+C,I=w===l,M=I?"\u276F ":" ";return E.createElement(_,{key:`${b.value}-${w}`,flexDirection:"row",paddingX:2},E.createElement(y,{color:I?"cyan":void 0,bold:I},M,b.label),b.description&&E.createElement(y,{dimColor:true}," - ",b.description))}),v&&E.createElement(_,{paddingX:2},E.createElement(y,{dimColor:true}," \u2193 more")))};var Lb=({onSubmit:r,onCancel:e})=>{let[t,n]=useState(""),[s,o]=useState(0),i=t.length-s;Xe((u,d)=>{if(d.escape){e();return}if(d.return){let m=t.trim();m&&r(m);return}if(d.backspace||d.delete){if(s===t.length)return;let m=i-1,g=t.slice(0,m)+t.slice(m+1);n(g);return}if(d.leftArrow){o(Math.min(s+1,t.length));return}if(d.rightArrow){o(Math.max(s-1,0));return}if(d.home||d.ctrl&&u==="a"){o(t.length);return}if(d.end||d.ctrl&&u==="e"){o(0);return}if(!d.ctrl&&!d.meta&&u){let m=t.slice(0,i)+u+t.slice(i);n(m);return}},{isActive:true});let a=t.slice(0,i),l=t[i]||" ",c=t.slice(i+1);return E.createElement(_,{flexDirection:"column",borderStyle:"double",borderColor:"yellow",paddingX:2,paddingY:1,width:"80%"},E.createElement(_,{marginBottom:1,justifyContent:"center"},E.createElement(y,{bold:true,color:"yellow"},"\u2728 \u63D2\u961F\u6D88\u606F - \u5C06\u5728\u4E0B\u6B21\u8BF7\u6C42\u65F6\u53D1\u9001")),E.createElement(_,{flexDirection:"column"},E.createElement(y,{dimColor:true},"\u8F93\u5165\u4F60\u7684\u6D88\u606F:"),E.createElement(_,{marginTop:1},E.createElement(y,{color:"green",bold:true},"\u276F "),t?E.createElement(y,null,a,E.createElement(y,{inverse:true},l),c):E.createElement(_,null,E.createElement(y,{inverse:true}," "),E.createElement(y,{dimColor:true},"\u8F93\u5165\u6D88\u606F...")))),E.createElement(_,{marginTop:1,justifyContent:"space-between"},E.createElement(y,{dimColor:true},"Enter: \u786E\u8BA4"),E.createElement(y,{dimColor:true},"ESC: \u53D6\u6D88")))};var no=r=>r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:String(r),dE=r=>{switch(r){case "running":return {icon:"\u25CF",color:"green"};case "waiting":return {icon:"\u25D0",color:"yellow"};case "completed":return {icon:"\u2713",color:"blue"};case "error":return {icon:"\u2717",color:"red"};default:return {icon:"\u25CB",color:"gray"}}},$b=({agentContextStats:r,onClose:e})=>{let{columns:t}=Ws();Xe((s,o)=>{(o.escape||s==="q")&&e();},{isActive:true});let n=[...r].sort((s,o)=>s.agentId==="Main"?-1:o.agentId==="Main"?1:s.agentLabel.localeCompare(o.agentLabel));return E.createElement(_,{flexDirection:"column",width:"100%"},E.createElement(_,{justifyContent:"space-between"},E.createElement(y,{bold:true,color:"cyan"},"Agent Context Overview"),E.createElement(y,{dimColor:true},"ESC to close")),E.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),n.length===0?E.createElement(y,{dimColor:true},"No agent context stats available."):n.map(s=>{let o=s.contextWindow||0,i=s.tokensUsedForContext||0,a=o>0?i/o:0,l=Math.round(a*100),{icon:c,color:u}=dE(s.status),d=s.currentTask?s.currentTask.length>40?`${s.currentTask.slice(0,37)}...`:s.currentTask:"";return E.createElement(_,{key:s.agentId,justifyContent:"space-between",marginTop:1},E.createElement(_,null,E.createElement(y,{color:"magenta"},s.agentLabel),E.createElement(y,{dimColor:true}," "),E.createElement(y,{color:u},c),d&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," "),E.createElement(y,{dimColor:true},d))),E.createElement(_,null,E.createElement(y,{dimColor:true},"in "),E.createElement(y,{color:"cyan"},no(s.input)),E.createElement(y,{dimColor:true}," out "),E.createElement(y,{color:"green"},no(s.output)),(s.cacheCreationTokens||s.cacheReadTokens)&&E.createElement(E.Fragment,null,E.createElement(y,{dimColor:true}," cache-w "),E.createElement(y,{color:"magenta"},no(s.cacheCreationTokens||0)),E.createElement(y,{dimColor:true}," cache-r "),E.createElement(y,{color:"blue"},no(s.cacheReadTokens||0))),E.createElement(y,{dimColor:true}," \u2502 context "),E.createElement(y,{color:"yellow"},no(i)),E.createElement(y,{dimColor:true},"/"),E.createElement(y,{color:"yellow"},no(o)),E.createElement(y,{dimColor:true}," ("),E.createElement(y,{color:a>.8?"red":a>.5?"yellow":"green"},l,"%"),E.createElement(y,{dimColor:true},")")))}),E.createElement(y,{color:"gray"},"\u2500".repeat(Math.max(t,10))),E.createElement(y,{dimColor:true},"Tip: Press Q or ESC to return"))};var Ob=({messages:r})=>r.length===0?null:E.createElement(_,{flexDirection:"column",marginBottom:1},E.createElement(_,null,E.createElement(y,{color:"magenta",bold:true},"\u250C\u2500 "),E.createElement(y,{color:"magenta",bold:true},"Queued (",r.length,")"),E.createElement(y,{color:"magenta",bold:true}," \u2500")),r.map((e,t)=>E.createElement(_,{key:e.id,paddingLeft:1},E.createElement(y,{color:"gray"},"\u2502 "),E.createElement(y,{color:"cyan",bold:true},"> "),E.createElement(y,{color:"white"},e.text.length>70?e.text.substring(0,67)+"...":e.text))),E.createElement(_,null,E.createElement(y,{color:"magenta",bold:true},"\u2514\u2500"),E.createElement(y,{dimColor:true}," Press "),E.createElement(y,{color:"yellow"},"\u2191"),E.createElement(y,{dimColor:true}," to edit queued messages")));Ql();re();var vE=[".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg"],CE=r=>{let e=new WeakSet;try{return JSON.stringify(r,(t,n)=>{if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return n})}catch{try{return String(r)}catch{return "[Unserializable]"}}};function xE(r){if(!r)return false;let e=r.trim(),t=e.toLowerCase(),n=vE.some(o=>t.endsWith(o)),s=e.startsWith("/")||e.startsWith("./")||e.startsWith("~/")||e.includes("/")&&n;return n&&s}var Bb=({staticEntries:r=[],pendingEntries:e=[],isRunning:t,statusText:n="",tokenStats:s,streamingTokens:o=0,streamingStartTime:i=null,accumulatedRunTime:a=0,version:l=ro,provider:c="OpenAI",model:u="gpt-4",workDir:d=process.cwd(),showHeader:m=true,thinkingEnabled:g=true,selectMenuOptions:h=null,textPromptOptions:f=null,contextMenuActive:v=false,agentContextScreenActive:b=false,compressionMode:C="sync",compactionThreshold:w=.85,agentContextStats:I=[],runMode:M="single",networkStats:N,cooperateStats:R,commandOutput:O=[],attachedImages:k=[],interruptInputActive:A=false,queuedMessages:T=[],currentPlanSteps:P=[],getCompletions:$,onStaticRendered:G,onSubmit:S,onInterrupt:L,onExit:F,onContextMenuToggle:U,onAgentContextScreenToggle:H,onClearCommandOutput:ee,onAttachImage:j,onClearImages:z,onInterruptInputSubmit:ue,onInterruptInputCancel:V,onShowInterruptInput:ve})=>{let[Z,X]=useState(""),[Y,J]=useState([]),[Q,te]=useState(-1),[pe,D]=useState(null),q=useRef(false),se=useMemo(()=>!$||!Z.startsWith("/")?[]:$(Z),[Z,$]),le=useContext(br);useEffect(()=>{if(!le?.internal_eventEmitter||!j)return;let K=xe=>{ae("CLI_APP",`\u{1F4CE} Received image-paste event from vendor Ink: ${xe.name}`),j(xe);};return le.internal_eventEmitter.on("image-paste",K),()=>{le.internal_eventEmitter.off("image-paste",K);}},[le,j]),useEffect(()=>{f?.defaultValue&&X(f.defaultValue);},[f?.defaultValue]),Xe((K,xe)=>{if(xe.escape){if(b)return;pe?D(null):O.length>0&&ee&&ee();}},{isActive:!h&&!pe});let _e=e.filter(K=>K.type!=="thinking"&&K.type!=="reasoning"),$e=K=>{if(!K)return false;let{content:xe}=K;return typeof xe=="string"?xe.trim().length>0:Array.isArray(xe)?xe.some(fe=>{if(!fe||typeof fe!="object"||!("type"in fe))return false;switch(fe.type){case "text":return typeof fe.text=="string"&&fe.text.trim().length>0;case "image_url":return true;case "tool_use":return true;case "tool_result":return fe.content!==null&&fe.content!==void 0&&String(fe.content).trim().length>0;case "thinking":return typeof fe.thinking=="string"&&fe.thinking.trim().length>0;case "redacted_thinking":return typeof fe.data=="string"&&fe.data.trim().length>0;default:return true}}):false},W=K=>{if(K.message){let _o=$e(K.message);if(K.type==="user"&&!_o&&process.env.CLI_DEBUG==="1"){let Io=CE(K.message.content).slice(0,100);ae("APP",`User message filtered out! entry.id=${K.id}, message.role=${K.message.role}, content=${Io}`);}return _o}let xe=typeof K.text=="string"&&K.text.trim().length>0,fe=K.type==="plan"&&!!K.planSteps&&K.planSteps.length>0,et=(K.type==="pipeline_node_start"||K.type==="pipeline_node_complete"||K.type==="pipeline_node_fail"||K.type==="pipeline_node_retry")&&(K.pipelineNode||K.pipelineNodeRetry),Bs=(K.type==="network_node_start"||K.type==="network_node_complete"||K.type==="network_node_fail")&&K.networkNode,ma=(K.type==="ccb_review"||K.type==="ccb_agent_review"||K.type==="ccb_retry"||K.type==="ccb_failed")&&!!(K.ccbReview||K.ccbAgentReview||K.ccbRetry||K.ccbFailed),ga=K.type==="pipeline_dag"&&!!K.pipelineDAG;return !!(xe||fe||et||Bs||ma||ga)},ne=useMemo(()=>_e.filter(W),[_e]),ie=useMemo(()=>{let K=r.filter(W);return process.env.CLI_DEBUG==="1"&&ae("APP",`visibleStaticEntries: staticEntries=${r.length}, visible=${K.length}, types=${K.map(xe=>xe.type).join(",")}`),K},[r]),Ae=m&&!q.current,Ne=E.useCallback((K,xe)=>K,[]),Le=useMemo(()=>{let K=[],xe=ie.length+ne.length;return Ae&&K.push(E.createElement(ob,{key:"header",version:l,provider:c,model:u,workDir:d})),ie.forEach((fe,et)=>{K.push(E.createElement(Lp,{key:`static-entry-${fe.id}`,entry:fe})),(et<ie.length-1||xe>ie.length)&&K.push(E.createElement(y,{key:`static-spacer-${fe.id}`},""));}),K},[Ae,ie,ne.length,l,c,u,d]);if(useEffect(()=>{!Ae&&r.length===0||(Ae&&(q.current=true),G?.());},[Ae,r.length,G]),b)return E.createElement($b,{agentContextStats:I,onClose:()=>H?.()});let Ie=K=>{if(f){if(!K.trim()&&!f.allowEmpty)return;f.onSubmit(K),X("");return}let xe=k.length>0,fe=K.trim().length>0;(fe||xe)&&(fe&&J([...Y,K]),te(-1),X(""),S(K,xe?k:void 0));},Rt=()=>{if(Y.length===0)return;let K=Q+1;K<Y.length&&(te(K),X(Y[Y.length-1-K]));},Fe=()=>{if(Q<=0){te(-1),X("");return}let K=Q-1;te(K),X(Y[Y.length-1-K]);},Me=K=>{if(!$)return null;let xe=$(K);if(xe.length===0)return null;if(xe.length===1)return xe[0];let fe=xe.map(et=>({label:et,value:et,description:void 0}));return D({message:"Select completion:",choices:fe,initialIndex:0,onSelect:et=>{X(et),D(null);},onCancel:()=>{D(null);}}),null};return E.createElement(_,{flexDirection:"column",width:"100%"},E.createElement(Fa,{items:Le},Ne),ne.map((K,xe)=>E.createElement(_,{key:`pending-wrapper-${K.id}`,flexDirection:"column"},E.createElement(Lp,{entry:K}),xe<ne.length-1&&E.createElement(y,null,""))),E.createElement(y,null,`
1692
1691
  `),A&&ue&&V?E.createElement(_,{flexShrink:0,flexDirection:"column"},E.createElement(Lb,{onSubmit:ue,onCancel:V})):E.createElement(_,{flexShrink:0,flexDirection:"column"},T.length>0&&E.createElement(Ob,{messages:T}),E.createElement(Db,{inputValue:Z,isRunning:t,statusText:n,tokenStats:s,streamingTokens:o,streamingStartTime:i,accumulatedRunTime:a,provider:c,model:u,menuActive:!!h||!!pe,promptActive:!!f,promptMessage:f?.message,promptHint:f?.hint,promptOnCancel:f?.onCancel,thinkingEnabled:g,contextMenuActive:v,compressionMode:C,compactionThreshold:w,agentContextStats:I,runMode:M,networkStats:N,cooperateStats:R,currentPlanSteps:P,attachments:k,completions:se,onInputChange:K=>{if(j&&xE(K)){j(K.trim());return}X(K);},onSubmit:Ie,onInterrupt:L,onExit:F,onHistoryUp:Rt,onHistoryDown:Fe,onTabComplete:Me,onContextMenuToggle:U,onAgentContextScreenToggle:H,onRemoveAttachment:z?K=>{z();}:void 0,onPasteImage:j,onShowInterruptInput:ve}),h&&E.createElement(Bp,{message:h.message,choices:h.choices,initialIndex:h.initialIndex,hint:h.hint,onSelect:h.onSelect,onCancel:h.onCancel,onExit:F}),pe&&E.createElement(Bp,{message:pe.message,choices:pe.choices,initialIndex:pe.initialIndex,hint:pe.hint,onSelect:pe.onSelect,onCancel:pe.onCancel,onExit:F}),O.length>0&&E.createElement(_,{flexDirection:"column",paddingX:2,paddingY:1,borderStyle:"round",borderColor:"gray"},O.map((K,xe)=>E.createElement(y,{key:xe},K)))))};re();ps();var tc=class r{appInstance=null;messages=[];staticEntries=[];nextEntryId=1;isRunning=false;statusText="";tokenStats={input:0,output:0,total:0,contextWindow:void 0,tokensUsedForContext:0,pressure:0};version="";provider="";model="";workDir="";showHeader=true;thinkingEnabled=true;callbacks;forceUpdate=null;selectMenuOptions=null;textPromptOptions=null;contextMenuActive=false;agentContextScreenActive=false;commandOutput=[];getCompletions;memoryLogTimer=null;ttyWriteGuardActive=false;allowTTYWriteDepth=0;originalStdoutWrite=null;originalStderrWrite=null;inkStdout=null;attachedImages=[];pendingEntries=[];getPendingMessages=null;interruptInputActive=false;runMode="single";streamingTokens=0;streamingStartTime=null;accumulatedRunTime=0;runningStartTime=null;compressionMode="sync";compactionThreshold=.85;agentContextStats=new Map;networkStats=null;cooperateStats=null;currentPlanSteps=[];static MAX_QUEUED_STATIC=50;constructor(e){this.callbacks=e;}setCompletionFunction(e){this.getCompletions=e;}start(){p.info("INK","Starting Ink runtime"),this.startMemorySampler();let e=()=>{let[,s]=useState(0);return useLayoutEffect(()=>(this.forceUpdate=()=>{let o=Date.now();p.debug("RUNTIME",`>>> forceUpdate called, staticEntries=${this.staticEntries.length}, pendingEntries=${this.pendingEntries.length}`),s(a=>a+1);let i=Date.now()-o;i>50&&p.warn("RUNTIME",`\u26A0\uFE0F forceUpdate slow: setCounter took ${i}ms`);},()=>{this.forceUpdate=null;}),[]),E.createElement(Bb,{staticEntries:this.staticEntries,pendingEntries:this.pendingEntries,isRunning:this.isRunning,statusText:this.statusText,tokenStats:this.tokenStats,streamingTokens:this.streamingTokens,streamingStartTime:this.streamingStartTime,accumulatedRunTime:this.accumulatedRunTime,compressionMode:this.compressionMode,compactionThreshold:this.compactionThreshold,agentContextStats:this.getAgentContextStats(),runMode:this.runMode,networkStats:this.networkStats||void 0,cooperateStats:this.cooperateStats||void 0,currentPlanSteps:this.currentPlanSteps,version:this.version,provider:this.provider,model:this.model,workDir:this.workDir,showHeader:this.showHeader,thinkingEnabled:this.thinkingEnabled,selectMenuOptions:this.selectMenuOptions,textPromptOptions:this.textPromptOptions,contextMenuActive:this.contextMenuActive,agentContextScreenActive:this.agentContextScreenActive,commandOutput:this.commandOutput,attachedImages:this.attachedImages,interruptInputActive:this.interruptInputActive,queuedMessages:this.getQueuedMessagesForDisplay(),getCompletions:this.getCompletions,onStaticRendered:void 0,onSubmit:(o,i)=>{let a=i||this.attachedImages;this.attachedImages=[],this.callbacks.onSubmit(o,a);},onInterrupt:this.callbacks.onInterrupt,onExit:this.callbacks.onExit,onContextMenuToggle:()=>{this.contextMenuActive=!this.contextMenuActive,this.forceUpdate?.();},onAgentContextScreenToggle:()=>{this.agentContextScreenActive=!this.agentContextScreenActive,this.forceUpdate?.();},onClearCommandOutput:()=>{this.clearCommandOutput();},onAttachImage:o=>{this.attachImage(o);},onClearImages:()=>{this.clearAttachedImages();},onInterruptInputSubmit:o=>{this.handleInterruptInputSubmit(o);},onInterruptInputCancel:()=>{this.hideInterruptInput();},onShowInterruptInput:()=>{this.showInterruptInput();}})},t=Ve();t&&p.info("INK","WSL detected, disabling incremental rendering for compatibility");let n=this.installTTYWriteGuard();this.appInstance=Tr(E.createElement(e,null),{stdout:n,stdin:process.stdin,exitOnCtrlC:false,patchConsole:false,incrementalRendering:!t}),t&&setTimeout(()=>{this.forceUpdate&&(p.debug("INK","WSL startup render nudge"),this.forceUpdate());},0);try{process.stdout.isTTY&&!process.stdout.destroyed&&(this.writeDirectStdout("\x1B[?2004h"),p.info("INK","Bracketed paste mode enabled for image paste detection"));}catch(s){p.warn("INK","Failed to enable bracketed paste mode",{error:s});}try{p.debug("TTY_STATE","\u{1F6E1}\uFE0F [INK] Re-registering SIGTSTP ignore handler after Ink starts"),process.removeAllListeners("SIGTSTP"),process.on("SIGTSTP","ignore"),p.debug("TTY_STATE","\u2705 [INK] SIGTSTP handler re-registered (Ctrl+Z ignored)"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP handler registered (Ctrl+Z ignored)");}catch{p.debug("TTY_STATE","\u26A0\uFE0F [INK] SIGTSTP not supported on this platform"),process.env.CLI_DEBUG==="1"&&p.debug("INK","SIGTSTP not supported on this platform");}p.info("INK","Ink runtime started");}stop(){try{process.stdout.isTTY&&!process.stdout.destroyed&&(this.writeDirectStdout("\x1B[?2004l"),p.debug("INK","Bracketed paste mode disabled"));}catch(e){p.debug("INK","Failed to disable bracketed paste mode (ignored)",{error:e});}this.appInstance&&(this.appInstance.unmount(),this.appInstance=null,p.info("INK","Ink runtime stopped")),this.restoreTTYWriteGuard(),this.stopMemorySampler();}installTTYWriteGuard(){if(this.ttyWriteGuardActive)return this.inkStdout??process.stdout;this.originalStdoutWrite=process.stdout.write.bind(process.stdout),this.originalStderrWrite=process.stderr.write.bind(process.stderr);let e=t=>(n,s,o)=>{if(typeof s=="function"&&(o=s,s=void 0),this.allowTTYWriteDepth>0){let i=t==="stdout"?this.originalStdoutWrite:this.originalStderrWrite;if(i)return i(n,s,o)}return this.handleSuppressedWrite(t,n),typeof o=="function"&&o(),true};return process.stdout.write=e("stdout"),process.stderr.write=e("stderr"),this.inkStdout=this.createInkStdoutProxy(),this.ttyWriteGuardActive=true,p.info("INK","TTY output guard enabled"),this.inkStdout}restoreTTYWriteGuard(){this.ttyWriteGuardActive&&(this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite),this.originalStderrWrite&&(process.stderr.write=this.originalStderrWrite),this.ttyWriteGuardActive=false,this.inkStdout=null,p.info("INK","TTY output guard disabled"));}createInkStdoutProxy(){let e=process.stdout,t=this.originalStdoutWrite||e.write.bind(e);return new Proxy(e,{get:(n,s,o)=>{if(s==="write")return (a,l,c)=>this.withDirectTTYWrite(()=>t(a,l,c));let i=Reflect.get(n,s,o);return typeof i=="function"?i.bind(n):i}})}withDirectTTYWrite(e){this.allowTTYWriteDepth+=1;try{return e()}finally{this.allowTTYWriteDepth=Math.max(0,this.allowTTYWriteDepth-1);}}writeDirectStdout(e){let t=this.originalStdoutWrite||process.stdout.write.bind(process.stdout);this.withDirectTTYWrite(()=>{t(e);});}handleSuppressedWrite(e,t){if(t==null)return;let n="";if(typeof t=="string")n=t;else if(Buffer.isBuffer(t))n=t.toString("utf8");else try{n=String(t);}catch{return}if(!n||n.trim().length===0)return;let s=n.length>2e3?`${n.slice(0,2e3)}...`:n;p.warn("TTY_SUPPRESS",`[${e}] ${s}`);}addMessage(e){this.messages=[...this.messages.slice(-4),e],this.forceUpdate?.();}addEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};if(e.type==="user"){let n=!!e.message,s=e.message?.content;p.debug("INK_RUNTIME",`[addEntry] user entry id=${t.id}, hasMessage=${n}, contentType=${typeof s}, isArray=${Array.isArray(s)}`);}return this.staticEntries.length>=r.MAX_QUEUED_STATIC&&(p.warn("INK_RUNTIME",`Static queue reached limit (${this.staticEntries.length}). Forcing immediate render to prevent OOM.`),this.forceUpdate?.(),setImmediate(()=>{this.clearStaticEntries();})),this.staticEntries=[...this.staticEntries,t],p.debug("INK_RUNTIME",`Queued static entry ${t.id}. Pending static: ${this.staticEntries.length}, type: ${e.type}, forceUpdate: ${!!this.forceUpdate}`),this.forceUpdate?this.forceUpdate():setImmediate(()=>{this.forceUpdate?.();}),t.id}updateEntry(e,t){let n=this.staticEntries.findIndex(o=>o.id===e);if(n>=0){this.staticEntries=this.staticEntries.map((o,i)=>i===n?{...o,...t}:o),this.forceUpdate?.();return}let s=this.pendingEntries.findIndex(o=>o.id===e);s>=0&&(this.pendingEntries=this.pendingEntries.map((o,i)=>i===s?{...o,...t}:o),this.forceUpdate?.());}getEntry(e){return this.staticEntries.find(t=>t.id===e)||this.pendingEntries.find(t=>t.id===e)}addPendingEntry(e){let t={...e,id:this.nextEntryId++,timestamp:new Date};if(this.pendingEntries.length>=10){p.warn("INK_RUNTIME",`Too many pending entries (${this.pendingEntries.length}). Auto-committing oldest.`);let s=this.pendingEntries[0];this.staticEntries=[...this.staticEntries,s],this.pendingEntries=this.pendingEntries.slice(1);}return this.pendingEntries=[...this.pendingEntries,t],p.debug("INK_RUNTIME",`Added pending entry ${t.id}. Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),t.id}updatePendingEntry(e,t){let n=this.pendingEntries.findIndex(s=>s.id===e);n>=0&&(this.pendingEntries=this.pendingEntries.map((s,o)=>o===n?{...s,...t}:s),this.forceUpdate?.());}updatePendingEntryByKey(e,t){let n=this.pendingEntries.findIndex(s=>s.entryKey===e);if(n>=0)this.pendingEntries=this.pendingEntries.map((s,o)=>o===n?{...s,...t,entryKey:e,timestamp:new Date}:s);else {let s={...t,entryKey:e,id:this.nextEntryId++,timestamp:new Date};this.pendingEntries=[...this.pendingEntries,s];}this.forceUpdate?.();}commitPendingEntryByKey(e){let t=this.pendingEntries.findIndex(n=>n.entryKey===e);if(t>=0){let n=this.pendingEntries[t];return this.pendingEntries=this.pendingEntries.filter((s,o)=>o!==t),this.staticEntries=[...this.staticEntries,{...n,isStreaming:false,isComplete:true}],p.debug("INK_RUNTIME",`Committed entry by key ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.(),true}return false}commitPendingEntry(e){let t=this.pendingEntries.findIndex(n=>n.id===e);if(t>=0){let n=this.pendingEntries[t];this.pendingEntries=this.pendingEntries.filter((s,o)=>o!==t),this.staticEntries=[...this.staticEntries,n],p.debug("INK_RUNTIME",`Committed entry ${e}. Static: ${this.staticEntries.length}, Pending: ${this.pendingEntries.length}`),this.forceUpdate?.();}else p.warn("INK_RUNTIME",`Cannot commit entry ${e} - not found in pending entries`);}clearPendingEntries(){this.pendingEntries.length>0&&(this.pendingEntries=[],this.forceUpdate?.());}commitAllPendingEntries(){if(this.pendingEntries.length>0){let e=this.pendingEntries.map(t=>({...t,isStreaming:false,isComplete:true}));this.staticEntries=[...this.staticEntries,...e],this.pendingEntries=[],p.debug("INK_RUNTIME",`Committed ${e.length} pending entries on run complete`),this.forceUpdate?.();}}updateStreamingStats(e){this.streamingTokens=e,this.streamingStartTime||(this.streamingStartTime=Date.now()),this.forceUpdate?.();}resetStreamingStats(){this.streamingTokens=0,this.streamingStartTime=null;}getAccumulatedRunTime(){if(this.isRunning&&this.runningStartTime!==null){let e=Math.floor((Date.now()-this.runningStartTime)/1e3);return this.accumulatedRunTime+e}return this.accumulatedRunTime}resetAccumulatedRunTime(){this.accumulatedRunTime=0,this.runningStartTime=null,this.forceUpdate?.();}setCompressionMode(e){this.compressionMode!==e&&(this.compressionMode=e,this.forceUpdate?.());}setCompactionThreshold(e){this.compactionThreshold!==e&&(this.compactionThreshold=e,this.forceUpdate?.());}updateAgentContext(e,t){this.agentContextStats.set(e,t),this.forceUpdate?.();}clearAgentContext(e){this.agentContextStats.has(e)&&(this.agentContextStats.delete(e),this.forceUpdate?.());}clearAllAgentContexts(){this.agentContextStats.size>0&&(this.agentContextStats.clear(),this.forceUpdate?.());}getAgentContextStats(){return Array.from(this.agentContextStats.values()).sort((t,n)=>t.agentId==="supervisor"?-1:n.agentId==="supervisor"?1:t.agentId.localeCompare(n.agentId))}updateLastMessage(e){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1];if(typeof t.content=="string")t.content=e;else if(Array.isArray(t.content)){let n=t.content.find(s=>s.type==="text");n&&"text"in n&&(n.text=e);}this.forceUpdate?.();}getLastMessageText(){if(this.messages.length===0)return "";let e=this.messages[this.messages.length-1];if(typeof e.content=="string")return e.content;if(Array.isArray(e.content)){let t=e.content.find(n=>n.type==="text");if(t&&"text"in t)return t.text||""}return ""}setRunning(e){if(this.isRunning!==e){if(e)this.runningStartTime=Date.now();else if(this.runningStartTime!==null){let t=Math.floor((Date.now()-this.runningStartTime)/1e3);this.accumulatedRunTime+=t,this.runningStartTime=null;}this.isRunning=e,this.forceUpdate?.();}}triggerForceUpdate(){this.forceUpdate?.();}setStatusText(e){this.statusText!==e&&(this.statusText=e,this.forceUpdate?.());}setTokenStats(e){p.info("DEBUG_CTX",`InkRuntime.setTokenStats: received contextWindow=${e.contextWindow}, current=${this.tokenStats.contextWindow}`);let t=e.contextWindow!==void 0?e.contextWindow:this.tokenStats.contextWindow;(this.tokenStats.input!==e.input||this.tokenStats.output!==e.output||this.tokenStats.total!==e.total||this.tokenStats.contextWindow!==t||this.tokenStats.tokensUsedForContext!==e.tokensUsedForContext||this.tokenStats.pressure!==e.pressure||this.tokenStats.toolTokens!==e.toolTokens||this.tokenStats.messageTokens!==e.messageTokens||this.tokenStats.systemTokens!==e.systemTokens||this.tokenStats.userTokens!==e.userTokens||this.tokenStats.assistantTokens!==e.assistantTokens||this.tokenStats.toolCallTokens!==e.toolCallTokens||this.tokenStats.toolResultTokens!==e.toolResultTokens||this.tokenStats.cacheCreationTokens!==e.cacheCreationTokens||this.tokenStats.cacheReadTokens!==e.cacheReadTokens)&&(this.tokenStats={...e,contextWindow:t,tokensUsedForContext:e.tokensUsedForContext??this.tokenStats.tokensUsedForContext,pressure:e.pressure??this.tokenStats.pressure},p.info("DEBUG_CTX",`InkRuntime.setTokenStats: after update contextWindow=${this.tokenStats.contextWindow}`),this.forceUpdate?.());}clearMessages(){p.warn("INK_RUNTIME",`clearMessages called! This will clear pending/static queues. Messages: ${this.messages.length}`),this.messages=[],this.staticEntries=[],this.pendingEntries=[],this.forceUpdate?.();}setCommandOutput(e){p.debug("INK_RUNTIME","Set command output",{lineCount:e.length}),this.commandOutput=e,this.forceUpdate?.();}clearCommandOutput(){p.debug("INK_RUNTIME","Clear command output"),this.commandOutput=[],this.forceUpdate?.();}attachImage(e){let t;if(typeof e=="string")if(e.startsWith("data:")){let s=e.match(/^data:([^;]+);base64,(.+)$/);if(s){let o=`image_${Date.now()}.png`;t={mediaType:s[1],data:s[2],name:o};}else {p.error("INK_RUNTIME","Invalid data URL format",{imageData:e});return}}else {let s=e.split("/").pop()||e;t={path:e,name:s};}else t=e;if(this.attachedImages.some(s=>s.path&&t.path&&s.path===t.path||s.data&&t.data&&s.data===t.data)){p.debug("INK_RUNTIME","Image already attached");return}this.attachedImages.push(t),p.info("INK_RUNTIME",`\u{1F4CE} Attached image #${this.attachedImages.length}: ${t.name||"unnamed"}`),this.forceUpdate?.();}clearAttachedImages(){this.attachedImages.length>0&&(p.debug("INK_RUNTIME",`Cleared ${this.attachedImages.length} attached images`),this.attachedImages=[],this.forceUpdate?.());}getAttachedImages(){return [...this.attachedImages]}showInterruptInput(){p.debug("INK_RUNTIME","Show interrupt input"),this.interruptInputActive=true,this.forceUpdate?.();}hideInterruptInput(){p.debug("INK_RUNTIME","Hide interrupt input"),this.interruptInputActive=false,this.forceUpdate?.();}handleInterruptInputSubmit(e){p.debug("INK_RUNTIME","Handle interrupt input submit",{text:e.substring(0,50)}),this.hideInterruptInput(),this.callbacks.onSubmit(e);}setGetPendingMessages(e){this.getPendingMessages=e;}getQueuedMessagesForDisplay(){return this.getPendingMessages?this.getPendingMessages().map((e,t)=>({id:t+1,text:e.text,timestamp:e.timestamp})):[]}hasQueuedMessages(){return this.getPendingMessages?this.getPendingMessages().length>0:false}addAgentSpawnEntry(e,t,n,s){return this.addEntry({type:"agent_spawn",agentId:e,agentIndex:t,agentStatus:"running",agentTask:n,agentModel:s,text:n})}addAgentProgressEntry(e,t,n,s){return this.addEntry({type:"agent_progress",agentId:e,agentIndex:t,agentStatus:"running",agentProgress:n,text:s})}addAgentCompleteEntry(e,t,n){return this.addEntry({type:"agent_complete",agentId:e,agentIndex:t,agentStatus:"completed",text:n})}addAgentErrorEntry(e,t,n){return this.addEntry({type:"agent_error",agentId:e,agentIndex:t,agentStatus:"error",agentError:n,text:n})}setVersion(e){this.version=e,this.forceUpdate?.();}setProvider(e){this.provider=e,this.forceUpdate?.();}setModel(e){this.model=e,this.forceUpdate?.();}setRunMode(e){this.runMode=e,e!=="network"&&(this.networkStats=null),this.forceUpdate?.();}updateNetworkStats(e){this.networkStats||(this.networkStats={teamSize:0,activeAgents:0,totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.networkStats,e),this.forceUpdate?.();}clearNetworkStats(){this.networkStats=null,this.forceUpdate?.();}getNetworkStats(){return this.networkStats}updateCooperateStats(e){this.cooperateStats||(this.cooperateStats={models:[],totalInputTokens:0,totalOutputTokens:0}),Object.assign(this.cooperateStats,e),this.forceUpdate?.();}clearCooperateStats(){this.cooperateStats=null,this.forceUpdate?.();}getCooperateStats(){return this.cooperateStats}setPlanSteps(e){this.currentPlanSteps=e,this.forceUpdate?.();}getPlanSteps(){return this.currentPlanSteps}clearPlanSteps(){this.currentPlanSteps=[],this.forceUpdate?.();}setWorkDir(e){this.workDir=e,this.forceUpdate?.();}setShowHeader(e){this.showHeader=e,this.forceUpdate?.();}setThinkingEnabled(e){this.thinkingEnabled!==e&&(this.thinkingEnabled=e,this.forceUpdate?.());}showSelectMenu(e){if(p.debug("INK_RUNTIME","Show select menu",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;process.stdin.isRaw||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showSelectMenu: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for SelectMenu");}catch(s){p.error("INK_RUNTIME","Failed to resume stdin for SelectMenu",{error:s});}}}this.selectMenuOptions=e,this.forceUpdate?.();}hideSelectMenu(){p.debug("INK_RUNTIME","Hide select menu"),this.selectMenuOptions=null,this.forceUpdate?.(),process.nextTick(()=>{this.forceUpdate?.();});}isSelectMenuActive(){return this.selectMenuOptions!==null}updateSelectMenuIndex(e){if(!this.selectMenuOptions)return;let t=Math.max(0,this.selectMenuOptions.choices.length-1),n=Math.max(0,Math.min(e,t));this.selectMenuOptions={...this.selectMenuOptions,initialIndex:n},this.forceUpdate?.();}showTextPrompt(e){if(p.debug("INK_RUNTIME","Show text prompt",{options:e}),process.stdin.isTTY&&!process.stdin.destroyed){let t=process.stdin.isPaused?.()||false;if(t){process.env.CLI_DEBUG==="1"&&p.debug("INK_RUNTIME",`showTextPrompt: Resuming stdin (wasPaused=${t})`);try{process.stdin.resume(),p.info("INK_RUNTIME","\u2713 Stdin resumed for TextPrompt");}catch(n){p.error("INK_RUNTIME","Failed to resume stdin for TextPrompt",{error:n});}}}this.textPromptOptions=e,this.forceUpdate?.();}hideTextPrompt(){p.debug("INK_RUNTIME","Hide text prompt"),this.textPromptOptions=null,this.forceUpdate?.();}showContextMenu(){p.debug("INK_RUNTIME","Show context menu"),this.contextMenuActive=true,this.forceUpdate?.();}hideContextMenu(){p.debug("INK_RUNTIME","Hide context menu"),this.contextMenuActive=false,this.forceUpdate?.();}getContextMenuActive(){return this.contextMenuActive}clearStaticEntries(){if(this.staticEntries.length===0)return;let e=this.staticEntries.length;p.debug("INK_RUNTIME",`Clearing ${e} static entries from memory`),this.staticEntries=[],global.gc&&e>10&&(p.debug("INK_RUNTIME","Triggering manual GC after clearing entries"),setImmediate(()=>{global.gc&&global.gc();}));}startMemorySampler(){this.memoryLogTimer||process.env.INK_MEM!=="1"||(this.memoryLogTimer=setInterval(()=>{let e=process.memoryUsage(),t=n=>Math.round(n/1024/1024*10)/10;p.info("INK_MEM","usage",{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),heapTotalMB:t(e.heapTotal),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers??0),pendingEntries:this.pendingEntries.length,queuedStatic:this.staticEntries.length,isRunning:this.isRunning});},1e4));}stopMemorySampler(){this.memoryLogTimer&&(clearInterval(this.memoryLogTimer),this.memoryLogTimer=null);}};re();Li();var EE=r=>{let e=new WeakSet;try{return JSON.stringify(r,(t,n)=>{if(typeof n=="bigint")return n.toString();if(n instanceof Error)return {name:n.name,message:n.message,stack:n.stack};if(typeof n=="function")return "[Function]";if(typeof n=="object"&&n!==null){if(e.has(n))return "[Circular]";e.add(n);}return n})}catch{try{return String(r)}catch{return "[Unserializable]"}}},oc=class{runtime;config;callbacks;currentThinkingText="";lastMessageRole=null;lastEntryId=null;tokenStats={inputTokens:0,outputTokens:0,totalTokens:0};memory;streamingTextPendingId=null;streamingReasoningPendingId=null;streamingTextBuffer="";streamingReasoningBuffer="";streamingReasoningType="thinking";streamingToolChars=0;hasInferredThinkingStatus=false;toolLogIdByToolId=new Map;toolLogDetailsByToolId=new Map;toolLogNameByToolId=new Map;toolLogOutputByToolId=new Map;toolLogSourceLabelByToolId=new Map;streamingSourceLabel=null;streamingSourceType=null;agentBuffers=new Map;activeAgentId=null;constructor(e){this.config=e,this.memory=e.memory,this.runtime=new tc({onSubmit:(t,n)=>{this.callbacks?.onSubmit&&this.callbacks.onSubmit(t,n);},onInterrupt:()=>{this.callbacks?.onInterrupt&&this.callbacks.onInterrupt();},onExit:()=>{this.callbacks?.onExit&&this.callbacks.onExit();}}),e.getPendingMessages&&this.runtime.setGetPendingMessages(e.getPendingMessages);}start(e){this.callbacks=e,this.runtime.setVersion(this.config.version),this.runtime.setProvider(this.config.provider),this.runtime.setModel(this.config.model),this.runtime.setWorkDir(this.config.workDir),this.config.getCompletions&&this.runtime.setCompletionFunction(this.config.getCompletions),this.runtime.start(),p.info("INK_ADAPTER","Ink UI started");}stop(){this.runtime.stop(),this.callbacks=void 0,p.info("INK_ADAPTER","Ink UI stopped");}addUserMessage(e,t,n){let s=[{type:"text",text:e}];if(t&&t.length>0)for(let i of t)s.push({type:"image_url",image_url:{url:`file://${i.path}`}});let o={role:"user",content:s};this.lastEntryId=this.runtime.addEntry({type:"user",message:o,sourceLabel:n==="remote"?"Android":void 0}),this.lastMessageRole="user";}addAssistantMessage(e=""){if(e===""){this.lastMessageRole="assistant";return}let t={role:"assistant",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"assistant",message:t,isStreaming:false}),this.lastMessageRole="assistant";}addSupervisorMessage(e){let t={role:"user",content:[{type:"text",text:e}]};this.lastEntryId=this.runtime.addEntry({type:"supervisor",message:t}),this.lastMessageRole="user";}startSupervisorStreaming(){this.startAgentStreaming("Supervisor"),this.streamingSourceLabel="Supervisor",this.streamingSourceType="supervisor";}startExecutorStreaming(e){let t=e||"Executor";this.startAgentStreaming(t);}getStreamingSourceType(){return this.streamingSourceType}startAgentStreaming(e){this.agentBuffers.has(e)||this.agentBuffers.set(e,""),this.activeAgentId=e,this.lastMessageRole="assistant",p.debug("INK_ADAPTER",`Started agent streaming for ${e}`);}startWorkerStreaming(e){this.startAgentStreaming(e);}addWorkerTextDelta(e,t){this.streamText(t,e);}completeWorkerStreaming(e){this.completeTextStreaming(e);}addWorkerInfo(e,t,n,s="info"){let i=`${`[${e}]`} ${t}`,a=s==="error"?"warning":s;this.addInfo(i,n,a);}streamText(e,t){let n=Date.now(),s=t||this.activeAgentId||"default";p.debug("INK_ADAPTER",`streamText: ${e.length} chars to ${s}`,{snippet:e.substring(0,30),bufferExists:this.agentBuffers.has(s)});let o=Date.now()-n;o>10&&p.warn("INK_ADAPTER",`\u26A0\uFE0F streamText slow: ${o}ms for ${e.length} chars`);let i=this.agentBuffers.get(s)||"";this.agentBuffers.set(s,i+e);}addTextDelta(e,t){p.debug("INK_ADAPTER",`addTextDelta called: ${e.length} chars, agentId=${t||"default"}`,{delta:e.substring(0,50)}),this.streamText(e,t);}addAgentTextDelta(e,t,n){p.debug("INK_ADAPTER",`addAgentTextDelta: ${e.length} chars, agentId=${t}`,{delta:e.substring(0,50)}),this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let s=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,s+e);let i={role:"assistant",content:[{type:"text",text:this.agentBuffers.get(t)||""}]};this.runtime.updatePendingEntryByKey(t,{type:"assistant",message:i,isStreaming:true,isComplete:false,sourceLabel:n||t});}bufferAgentTextOnly(e,t){this.agentBuffers.has(t)||this.agentBuffers.set(t,"");let n=this.agentBuffers.get(t)||"";this.agentBuffers.set(t,n+e);}flushAgentBuffer(e){let t=this.agentBuffers.get(e)||"";return this.agentBuffers.delete(e),t}commitPendingEntryByKey(e){return this.agentBuffers.has(e)&&this.agentBuffers.delete(e),this.runtime.commitPendingEntryByKey(e)}addToolCall(e,t){let n={role:"assistant",content:[{type:"tool_use",id:`tool_${Math.floor(Date.now())}`,name:e,input:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_call";}addToolCallEntry(e,t,n){p.debug("INK_ADAPTER","Add tool call entry",{toolName:e,sourceLabel:n?.sourceLabel});let o={read_file:"readfile",Read:"readfile",search:"search",Grep:"search",grep:"search",glob:"search_files",Glob:"search_files",search_files:"search_files",smart_tree:"show_tree",tree:"show_tree",bash:"command_running",Bash:"command_running",shell:"command_running",execute_shell:"command_running",edit:"file_update",Edit:"file_update",write:"file_update",Write:"file_update",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser:"browser_debug",task:"task",Task:"task"}[e]||"tool_call",i=["bash","Bash","shell","execute_shell"].includes(e),a,l;i&&t.command?(l=`$ ${t.command}`,a="\u23F3 \u6B63\u5728\u6267\u884C\u4E2D..."):(l=e,a=JSON.stringify(t,null,2)),this.runtime.addEntry({type:o,text:l,details:a,isStreaming:i,sourceLabel:n?.sourceLabel});}addToolResult(e,t=false){let n={role:"user",content:[{type:"tool_result",tool_use_id:`tool_${Math.floor(Date.now())}`,content:e,is_error:t}]};this.runtime.addMessage(n),this.lastMessageRole="tool_result";}addEntry(e){return p.debug("INK_ADAPTER",`AddEntry: ${e.type}`,{text:e.text}),this.runtime.addEntry(e)}addInfo(e,t,n="info"){p.info("INK_ADAPTER",`Info: ${e}`,t?{details:t}:void 0);let s=n==="warning"||e.includes("\u26A0")||e.includes("\u23F3")||e.includes("\u23F1\uFE0F")||e.includes("\u{1F504}");this.runtime.addEntry({type:s?"warning":"info",text:e,details:t});}addError(e,t){let n=typeof t=="string"?t:t?.details,s=typeof t=="object"?t?.sourceLabel:void 0;p.error("INK_ADAPTER",e,n?{details:n}:void 0),this.runtime.addEntry({type:"error",text:e,details:n,sourceLabel:s});}addWarning(e,t,n){p.warn("INK_ADAPTER",e,t?{details:t}:void 0),this.runtime.addEntry({type:"warning",text:e,details:t,sourceLabel:n?.sourceLabel});}addCompacting(e,t){p.info("INK_ADAPTER",`Compacting: ${e}`,t?{details:t}:void 0),this.runtime.addEntry({type:"compacting",text:e,details:t});}updateStatus(e,t){if(t==="tool_call"&&e.includes("Streaming:")){let n=e.match(/\((\d+) chars\)/);if(n){let s=parseInt(n[1],10);this.streamingToolChars=s,this.runtime.updateStreamingStats(s);}}else t!=="tool_call"&&(this.streamingToolChars=0);t==="compacting"||t==="thinking"||t==="tool_call"?this.runtime.setRunning(true):(t==="complete"||t==="error")&&this.runtime.setRunning(false),this.runtime.setStatusText(e);}setRunning(e){this.runtime.setRunning(e);}startSessionTimer(){}getAccumulatedRunTime(){return this.runtime.getAccumulatedRunTime()}resetAccumulatedRunTime(){this.runtime.resetAccumulatedRunTime();}setCompressionMode(e){this.runtime.setCompressionMode(e);}setCompactionThreshold(e){this.runtime.setCompactionThreshold(e/100);}updateTokenStats(e,t){this.tokenStats.inputTokens=e,this.tokenStats.outputTokens=t,this.tokenStats.totalTokens=e+t,this.runtime.setTokenStats({input:e,output:t,total:e+t});}updateAgentContext(e,t){this.runtime.updateAgentContext(e,t);}clearAgentContext(e){this.runtime.clearAgentContext(e);}clearAllAgentContexts(){this.runtime.clearAllAgentContexts();}getTokenStats(){return {...this.tokenStats}}setTokenStats(e,t,n){p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: input=${e}, output=${t}, extras.contextWindow=${n?.contextWindow}`),this.tokenStats={inputTokens:e,outputTokens:t,totalTokens:e+t,...n};let s=n?.anthropicCacheCreationTokens||n?.openaiCachedTokens||n?.cacheCreationTokens,o=n?.anthropicCacheReadTokens||n?.cacheReadTokens,i=n?.contextWindow||0,a=n?.tokensUsedForContext||e+t+(o||0),l=i>0?a/i:0;p.info("DEBUG_CTX",`InkUIAdapter.setTokenStats: passing to runtime contextWindow=${n?.contextWindow}, calculated contextWindow=${i}`),this.runtime.setTokenStats({input:e,output:t,total:e+t,contextWindow:n?.contextWindow,tokensUsedForContext:n?.tokensUsedForContext,pressure:l,systemTokens:n?.systemTokens,userTokens:n?.userTokens,assistantTokens:n?.assistantTokens,toolCallTokens:n?.toolCallTokens,toolResultTokens:n?.toolResultTokens,toolTokens:n?.toolTokens,messageTokens:n?.messageTokens,cacheCreationTokens:s,cacheReadTokens:o});}startThinking(){this.streamingReasoningBuffer="",this.streamingReasoningType="thinking",this.hasInferredThinkingStatus=false,this.updateStatus(rc(),"thinking");}streamThinking(e,t="thinking"){if(this.streamingReasoningBuffer+=e,!this.hasInferredThinkingStatus&&this.streamingReasoningBuffer.length>30){let n=jb(this.streamingReasoningBuffer);n&&(this.updateStatus(n,"thinking"),this.hasInferredThinkingStatus=true);}this.streamingReasoningPendingId?this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{text:this.streamingReasoningBuffer}):(this.streamingReasoningType=t,this.streamingReasoningPendingId=this.runtime.addPendingEntry({type:t,text:this.streamingReasoningBuffer,isStreaming:true}));}endThinking(){if(!this.streamingReasoningPendingId){this.updateStatus("","info");return}try{this.streamingReasoningBuffer&&this.streamingReasoningBuffer.trim().length>0?(this.runtime.updatePendingEntry(this.streamingReasoningPendingId,{isStreaming:!1,isComplete:!0}),this.runtime.commitPendingEntry(this.streamingReasoningPendingId),p.debug("INK_ADAPTER",`Committed reasoning entry (${this.streamingReasoningBuffer.length} chars)`)):p.debug("INK_ADAPTER","Discarding empty reasoning entry (no content)");}catch(e){p.warn("INK_ADAPTER","Failed to commit reasoning entry",{error:e});}finally{this.streamingReasoningPendingId=null,this.streamingReasoningBuffer="",this.runtime.resetStreamingStats(),this.updateStatus("","info");}}startTaskTimer(){this.runtime.setRunning(true);}stopTaskTimer(){this.runtime.setRunning(false);}setStreamingTokens(e){this.runtime.updateStreamingStats(e);}clear(){this.runtime.clearMessages(),this.lastMessageRole=null;}resetStreamingState(){this.agentBuffers.clear(),this.activeAgentId=null,this.streamingTextBuffer="",this.streamingTextPendingId=null,this.streamingReasoningBuffer="",this.streamingReasoningPendingId=null,this.currentThinkingText="",this.streamingToolChars=0,this.runtime.clearPendingEntries(),this.runtime.resetStreamingStats(),this.runtime.setStatusText(""),p.debug("INK_ADAPTER","Reset streaming state (cleared all pending entries and buffers)");}finalizeStreamingState(){let e=Array.from(this.agentBuffers.keys());if(e.length>0)for(let t of e)this.completeTextStreaming(t);else this.completeTextStreaming();this.completeReasoningStreaming();}startReasoningStreaming(){this.startThinking();}streamReasoningText(e){this.streamThinking(e);}addReasoningDelta(e){this.streamThinking(e,"reasoning");}completeReasoningStreaming(){this.endThinking();}addThinking(e){}completeTextStreaming(e){let t=e||this.activeAgentId||"default",n=this.agentBuffers.get(t)||"";if(!(n&&n.trim().length>0)){p.debug("INK_ADAPTER",`Complete text streaming (${t}) - no text to commit`),this.agentBuffers.delete(t),this.runtime.commitPendingEntryByKey(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.runtime.resetStreamingStats());return}try{if(this.runtime.commitPendingEntryByKey(t))p.debug("INK_ADAPTER",`Complete text streaming (${t}) - committed pending entry ${n.length} chars`);else {let i={role:"assistant",content:[{type:"text",text:n}]};this.runtime.addEntry({type:"assistant",message:i,isStreaming:!1,isComplete:!0,sourceLabel:t==="default"?void 0:t}),p.debug("INK_ADAPTER",`Complete text streaming (${t}) - created static entry from buffer ${n.length} chars`);}}catch(o){p.warn("INK_ADAPTER","Failed to commit text entry",{error:o});}finally{this.agentBuffers.delete(t),(t==="default"||t===this.activeAgentId)&&(this.streamingTextPendingId=null,this.streamingSourceLabel=null,this.streamingSourceType=null,this.lastMessageRole="assistant",this.runtime.resetStreamingStats()),this.activeAgentId===t&&(this.activeAgentId=null);}}printCommandOutput(e){p.debug("INK_ADAPTER",`Command output: ${e}`);}setCommandOutputLines(e){p.debug("INK_ADAPTER",`Set command output lines: ${e.length}`),this.runtime.setCommandOutput(e);}clearCommandOutputLines(){p.debug("INK_ADAPTER","Clear command output lines"),this.runtime.clearCommandOutput();}startToolCallWithId(e,t,n,s){p.debug("INK_ADAPTER",`Start tool call: ${t}`,{toolId:e,args:n});let o=this.buildToolCallDetails(n,s),i=s?.sourceLabel,c={readfile:"readfile",Read:"readfile",read_file:"readfile",search:"search",Grep:"search",grep:"search",search_files:"search_files",Glob:"search_files",glob:"search_files",find_files:"search_files",show_tree:"show_tree",smart_tree:"show_tree",list_directory:"show_tree",ls:"show_tree",file_update:"file_update",Edit:"file_update",edit_file:"file_update",Write:"file_update",write_file:"file_update",command_exec:"command_exec",Bash:"command_exec",bash:"command_exec",shell:"command_exec",execute_command:"command_exec",code_exec:"code_exec",web_search:"web_search",WebSearch:"web_search",web_fetch:"web_fetch",WebFetch:"web_fetch",browser_debug:"browser_debug",TodoWrite:"todo",TodoRead:"todo",Task:"task",NotebookEdit:"notebook",NotebookRead:"notebook",AskUserQuestion:"ask_user"}[t]||"tool_call",u=this.runtime.addEntry({type:c,text:t,details:o,isStreaming:true,sourceLabel:i});this.toolLogIdByToolId.set(e,u),this.toolLogDetailsByToolId.set(e,o||""),this.toolLogNameByToolId.set(e,t),i&&this.toolLogSourceLabelByToolId.set(e,i);let d=sc(t,n);this.updateStatus(d,"tool_call");}updateToolCallOutput(e,t,n){p.debug("INK_ADAPTER",`Update tool output: ${e}`,{output:t});let s=this.toolLogIdByToolId.get(e);if(!s)return;let o=this.toolLogDetailsByToolId.get(e)||"",i=this.formatToolOutput(t,n?.truncated);i&&this.toolLogOutputByToolId.set(e,i);let a=this.mergeToolDetails(o,i);this.runtime.updateEntry(s,{details:a,isStreaming:true});}completeToolCall(e,t){p.debug("INK_ADAPTER",`Complete tool call: ${e}`);let n=this.toolLogIdByToolId.get(e);if(!n){t?.result&&this.addToolResult(t.result,t.isError||false);return}let s=this.toolLogNameByToolId.get(e)||"",o=this.toolLogDetailsByToolId.get(e)||"",i=this.toolLogOutputByToolId.get(e)||"",a=this.toolLogSourceLabelByToolId.get(e),l=t?.summary||t?.error||"",c=[];o&&c.push(o),l&&c.push(l),!l&&i&&c.push(i),typeof t?.duration=="number"&&c.push(`duration: ${this.formatDuration(t.duration)}`),typeof t?.resultLength=="number"&&c.push(`result: ${t.resultLength}B`);let u=c.length>0?c.join(`
1693
1692
  `):void 0;this.runtime.updateEntry(n,{type:t?.success?"tool_result":"tool_error",text:s||void 0,details:u,isStreaming:false,isComplete:true,sourceLabel:a}),this.toolLogIdByToolId.delete(e),this.toolLogDetailsByToolId.delete(e),this.toolLogNameByToolId.delete(e),this.toolLogOutputByToolId.delete(e),this.toolLogSourceLabelByToolId.delete(e);}updateTaskTokens(e,t=false){p.debug("INK_ADAPTER",`Update task tokens: ${e}`,{isActual:t}),!t&&this.runtime.updateStreamingStats(e);}addToolError(e,t){p.error("INK_ADAPTER",`Tool error: ${e}`,{error:t}),this.addToolResult(t,true);}printCommandOutputLines(e){e.forEach(t=>this.printCommandOutput(t));}resetTokenStats(){this.tokenStats={inputTokens:0,outputTokens:0,totalTokens:0},this.runtime.setTokenStats({input:0,output:0,total:0});}pause(){p.debug("INK_ADAPTER","Pause UI");}resume(){p.debug("INK_ADAPTER","Resume UI");}refreshUI(){p.debug("INK_ADAPTER","Refresh UI");}forceUpdate(){p.debug("INK_ADAPTER","Force UI update"),this.runtime.triggerForceUpdate();}setPlanSteps(e){p.debug("INK_ADAPTER",`Set plan steps: ${e.length} items`),this.runtime.setPlanSteps(e);}getPlanSteps(){return this.runtime.getPlanSteps()}clearPlanSteps(){p.debug("INK_ADAPTER","Clear plan steps"),this.runtime.clearPlanSteps();}commitAllPendingEntries(){p.debug("INK_ADAPTER","Commit all pending entries"),this.runtime.commitAllPendingEntries();}updateProvider(e,t){this.config.provider=e,this.config.model=t,this.runtime.setProvider(e),this.runtime.setModel(t);}updateWorkDir(e){this.config.workDir=e,this.runtime.setWorkDir(e);}setThinkingEnabled(e){this.runtime.setThinkingEnabled(e);}setRunMode(e){this.runtime.setRunMode(e);}updateNetworkStats(e){this.runtime.updateNetworkStats(e);}clearNetworkStats(){this.runtime.clearNetworkStats();}updateCooperateStats(e){this.runtime.updateCooperateStats(e);}clearCooperateStats(){this.runtime.clearCooperateStats();}showContextMenu(){return new Promise(e=>{this.runtime.showContextMenu();let t=setInterval(()=>{this.runtime.getContextMenuActive()||(clearInterval(t),e());},100);})}async promptText(e){return new Promise(t=>{this.runtime.showTextPrompt({message:e.message,defaultValue:e.defaultValue??e.initial,hint:e.hint,allowEmpty:e.allowEmpty??false,onSubmit:n=>{this.runtime.hideTextPrompt(),t(n);},onCancel:()=>{this.runtime.hideTextPrompt(),t(null);}});})}async promptSelect(e){return new Promise(t=>{this.runtime.hideSelectMenu();let n=e.choices.map(o=>({label:o.title,value:o.value,description:o.description})),s=e.initial||0;if(e.initialValue){let o=e.choices.findIndex(i=>i.value===e.initialValue);o>=0&&(s=o);}setTimeout(()=>{this.runtime.showSelectMenu({message:e.message,choices:n,initialIndex:s,hint:e.hint,onSelect:o=>{this.runtime.hideSelectMenu(),setTimeout(()=>t(o),100);},onCancel:()=>{this.runtime.hideSelectMenu(),setTimeout(()=>t(null),100);}});},100);})}handleSelectBack(){return p.debug("INK_ADAPTER","Handle select back"),this.runtime.isSelectMenuActive()?(this.runtime.hideSelectMenu(),true):false}addWebSearchResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip web search start (waiting for completion)");return}p.debug("INK_ADAPTER","Add web search result",{options:e});let t=e.query||"query",n=e.results?`Found ${e.results.length} results`:void 0;this.runtime.addEntry({type:"web_search",text:t,details:n,sourceLabel:e.sourceLabel});}addWebFetchResult(e){if(e.status==="fetching"){p.debug("INK_ADAPTER","Skip web fetch start (waiting for completion)");return}p.debug("INK_ADAPTER","Add web fetch result",{options:e});let t=e.url||"URL",n=e.contentLength?`${(e.contentLength/1024).toFixed(1)}KB`:e.contentPreview?`${e.contentPreview.length} chars`:void 0;this.runtime.addEntry({type:"web_fetch",text:t,details:n,sourceLabel:e.sourceLabel});}addReadFileResult(e){if(e.status==="reading"){p.debug("INK_ADAPTER","Skip read file start (waiting for completion)");return}p.debug("INK_ADAPTER","Add read file result",{options:e});let t=e.filePath||"file",n=[];e.totalLines&&n.push(`${e.totalLines} lines`),e.fileSize&&n.push(e.fileSize);let s=n.length>0?n.join(", "):void 0;this.runtime.addEntry({type:"readfile",text:t,details:s,sourceLabel:e.sourceLabel});}addSearchResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip search start (waiting for completion)");return}p.debug("INK_ADAPTER","Add search result",{options:e});let t=[];if(e.pattern&&t.push(`pattern="${e.pattern}"`),e.filePath){let i=e.filePath==="."?".":e.filePath;t.push(`path="${i}"`);}e.mode&&t.push(`mode="${e.mode}"`),e.strategy&&t.push(`engine="${e.strategy}"`),e.status==="completed"?e.matchCount!==void 0&&t.push(`matches=${e.matchCount}`):e.status==="error"&&t.push("\u274C ERROR");let n=t.join(", "),s=[];if(e.command){let i=this.simplifyRipgrepCommand(e.command);s.push(`$ ${i}`),s.push("");}e.status==="error"&&e.error?s.push(this.parseErrorMessage(e.error)):e.details&&s.push(e.details);let o=s.length>0?s.join(`
1694
1693
  `):void 0;this.runtime.addEntry({type:"search",text:n,details:o,sourceLabel:e.sourceLabel});}addSearchFilesResult(e){if(e.status==="searching"){p.debug("INK_ADAPTER","Skip search files start (waiting for completion)");return}p.debug("INK_ADAPTER","Add search files result",{options:e});let t=[];e.pattern&&t.push(`pattern="${e.pattern}"`),e.path&&t.push(`path="${e.path}"`),e.fileCount!==void 0&&t.push(`files=${e.fileCount}`);let n=t.length>0?t.join(", "):"Glob";this.runtime.addEntry({type:"search_files",text:n,sourceLabel:e.sourceLabel});}addShowTreeResult(e){if(e.status==="loading"){p.debug("INK_ADAPTER","Skip show tree start (waiting for completion)");return}p.debug("INK_ADAPTER","Add show tree result",{options:e});let n=[`path="${e.path||"."}"`];if(e.mode&&n.push(`mode="${e.mode}"`),e.maxDepth!==void 0&&e.maxDepth!==null&&n.push(`depth=${e.maxDepth}`),e.status==="completed"&&e.totalChars){let a=(e.totalChars/1024).toFixed(1);n.push(`${a}KB`);}else e.status==="error"&&n.push("\u274C ERROR");let s=n.join(", "),o=this.formatSmartTreeDetails(e.content),i;e.status==="error"&&e.error?i=`Error: ${e.error}`:o?i=o:e.content&&(i=e.content.length>500?e.content.slice(0,500)+"...":e.content),this.runtime.addEntry({type:"show_tree",text:s,details:i,sourceLabel:e.sourceLabel});}addCommandExecResult(e){let t=e.command||"command",n=`shell_${t.substring(0,50)}`;if(e.status==="running"){p.debug("INK_ADAPTER","Add command exec running",{command:t});let l=[];e.timeout&&l.push(`timeout=${Math.round(e.timeout/1e3)}s`),e.background&&l.push("bg");let c=l.length>0?` (${l.join(", ")})`:"";this.runtime.updatePendingEntryByKey(n,{type:"command_running",text:`$ ${t}${c}`,details:e.cwd?`cwd: ${e.cwd}`:void 0,isStreaming:true,sourceLabel:e.sourceLabel});return}p.debug("INK_ADAPTER","Add command exec result",{options:e});let s=e.status==="error",o,i=e.output||e.error||"";if(i){let l=i.split(`
@@ -3563,7 +3562,7 @@ Model: ${s}`);}else await dg(r,s);BC(r,n);}async function yu(r,e,t){let n=t||r.p
3563
3562
  `));}async function JC(r,e,t){r.logInfo(t?"\u{1F504} \u6B63\u5728\u91CD\u5EFA\u7D22\u5F15...":"\u{1F528} \u6B63\u5728\u6784\u5EFA\u7D22\u5F15...");let n=Date.now(),s=await e.buildIndex({force:t,onProgress:(c,u,d)=>{}}),o=((Date.now()-n)/1e3).toFixed(2),i=[];if(i.push(`\u6587\u4EF6\u6570: ${s.filesIndexed}`),i.push(`\u7B26\u53F7\u6570: ${s.symbolsFound}`),i.push(`\u8017\u65F6: ${o}s`),s.errors.length>0){i.push(""),i.push(x.warning("\u9519\u8BEF:"));for(let c of s.errors.slice(0,3))i.push(x.dim(` ${c.file}: ${c.error}`));s.errors.length>3&&i.push(x.dim(` ... \u8FD8\u6709 ${s.errors.length-3} \u4E2A\u9519\u8BEF`));}let a=s.success?x.success("\u2713 \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210"):x.warning("\u26A0\uFE0F \u7D22\u5F15\u6784\u5EFA\u5B8C\u6210 (\u6709\u9519\u8BEF)");r.logInfo(a,i.join(`
3564
3563
  `));let l={...r.userConfig,smartRead:{...r.userConfig.smartRead,enabled:true}};r.updateConfig(l),Pe(l);}async function QP(r,e){if(!(await e.getStats()).hasIndex){r.logInfo("\u7D22\u5F15\u4E0D\u5B58\u5728","\u65E0\u9700\u6E05\u9664");return}try{if(await r.promptSelect("\u26A0\uFE0F \u786E\u5B9A\u8981\u6E05\u9664\u6240\u6709\u7D22\u5F15\u6587\u4EF6\u5417?",[{label:"\u53D6\u6D88",value:"no",description:"\u4FDD\u7559\u7D22\u5F15\u6587\u4EF6"},{label:"\u786E\u5B9A\u6E05\u9664",value:"yes",description:"\u5220\u9664\u6240\u6709\u7D22\u5F15\u6587\u4EF6"}],"no","\u6309 \u2191\u2193 \u9009\u62E9")!=="yes"){r.logInfo("\u64CD\u4F5C\u5DF2\u53D6\u6D88");return}await e.clear(),r.logInfo(x.success("\u2713 \u7D22\u5F15\u5DF2\u6E05\u9664"));}catch(n){n?.message!=="cancelled"&&r.logInfo("\u6E05\u9664\u5931\u8D25",n?.message);}}async function ZP(r){let e=r.userConfig.smartRead||{enabled:true},t=[{label:"Web \u5F00\u53D1 (TS + JS)",value:"web",languages:["typescript","javascript"]},{label:"Full Stack (TS + JS + Python)",value:"fullstack",languages:["typescript","javascript","python"]},{label:"\u5168\u90E8\u8BED\u8A00",value:"all",languages:["typescript","javascript","python","java","go","rust"]},{label:"\u4EC5 TypeScript",value:"ts",languages:["typescript"]},{label:"\u4EC5 Python",value:"python",languages:["python"]},{label:"\u4EC5 Go",value:"go",languages:["go"]}];try{let n=await r.promptSelect("\u9009\u62E9\u8981\u7D22\u5F15\u7684\u8BED\u8A00",t.map(i=>({label:i.label,value:i.value,description:i.languages.join(", ")})),"fullstack","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4"),s=t.find(i=>i.value===n);if(!s){r.logInfo("\u914D\u7F6E\u5DF2\u53D6\u6D88");return}let o={...r.userConfig,smartRead:{...e,enabled:!0,languages:s.languages}};r.updateConfig(o),Pe(o),r.logInfo(x.success("\u2713 \u914D\u7F6E\u5DF2\u4FDD\u5B58"),`\u8BED\u8A00: ${s.languages.join(", ")}
3565
3564
  \u8FD0\u884C /index rebuild \u4EE5\u5E94\u7528\u65B0\u914D\u7F6E`);}catch(n){n?.message!=="cancelled"&&r.logInfo("\u914D\u7F6E\u5931\u8D25",n?.message);}}function eR(r){if(r===0)return {systemTokens:0,toolTokens:0,messageTokens:0};let e=Math.floor(r*.125),t=Math.floor(r*.25),n=r-e-t;return {systemTokens:e,toolTokens:t,messageTokens:Math.max(0,n)}}function tR(r){return {compressionMode:r.context?.compressionMode??"sync",thresholdPercent:r.context?.thresholdPercent??85}}async function Hn(r,e){let t=tR(r.userConfig);if(!e)try{e=await r.promptSelect("\u4E0A\u4E0B\u6587\u7BA1\u7406",[{label:"\u25CF \u67E5\u770B\u8BE6\u7EC6\u72B6\u6001",value:"show",description:"\u663E\u793A context \u4F7F\u7528\u60C5\u51B5\u548C\u5206\u7C7B\u5360\u6BD4"},{label:"\u25CF \u8BBE\u7F6E\u538B\u7F29\u9608\u503C",value:"threshold",description:`\u5F53\u524D: ${t.thresholdPercent}% - \u89E6\u53D1\u538B\u7F29\u7684 token \u4F7F\u7528\u7387`},{label:"\u25CF \u5207\u6362\u538B\u7F29\u6A21\u5F0F",value:"mode",description:t.compressionMode==="sync"?"\u5F53\u524D: \u540C\u6B65LLM\u538B\u7F29":"\u5F53\u524D: \u5F02\u6B65LLM\u538B\u7F29"}],"show","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88");}catch(n){n?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",n?.message);return}switch(e){case "show":await nR(r,t);break;case "threshold":await rR(r,t);break;case "mode":await sR(r,t);break;default:r.logInfo("\u65E0\u6548\u7684\u64CD\u4F5C","\u4F7F\u7528 /context \u67E5\u770B\u53EF\u7528\u64CD\u4F5C");}}async function nR(r,e){if(r.uiController&&"showContextMenu"in r.uiController){await r.uiController.showContextMenu(),await Hn(r);return}let t=i=>i>=1e3?`${(i/1e3).toFixed(1)}k`:i.toString(),n=[];n.push("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"),n.push("\u2502 Context Window Details \u2502"),n.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"),n.push("");let s=false;if(r.memoryPressure){let i=r.memoryPressure.getSnapshot();if(i&&i.profile&&i.pressure!==void 0){s=true;let{profile:a,tokensUsed:l,pressure:c}=i,u=Math.round(c*100),d=a.contextWindow||0,m=d-l,g=Math.floor(d*(e.thresholdPercent/100)),h=Math.max(0,g-l);n.push(`Total: ${t(l)} / ${t(d)} tokens (${u}%)`),n.push(`Remaining: ${t(m)} tokens`),n.push("");let f=e.compressionMode==="sync"?"Sync LLM":"Async LLM";n.push(`Compression: ${f} (${e.thresholdPercent}% threshold)`),n.push(""),h>0?n.push(`Compaction in: ${t(h)} tokens`):n.push("\u26A0\uFE0F Compaction threshold reached!"),n.push("");let v=eR(l);if(v.systemTokens>0||v.toolTokens>0||v.messageTokens>0){n.push("Context Breakdown:"),n.push("");let b=l>0?Math.round(v.systemTokens/l*100):0,C=l>0?Math.round(v.toolTokens/l*100):0,w=l>0?Math.round(v.messageTokens/l*100):0;n.push(` \u25A0 System: ${t(v.systemTokens)} (${b}%)`),n.push(` \u25A0 Tools: ${t(v.toolTokens)} (${C}%)`),n.push(` \u25A0 Messages: ${t(v.messageTokens)} (${w}%)`),n.push("");}}}if(!s){n.push("Total: 0 / -- tokens (0%)"),n.push("Remaining: -- tokens"),n.push("");let i=e.compressionMode==="sync"?"Sync LLM":"Async LLM";n.push(`Compression: ${i} (${e.thresholdPercent}% threshold)`),n.push(""),n.push("\u{1F4A1} Send a message to see context usage details"),n.push("");}let o=n.join(`
3566
- `);r.logInfo("Context Details",o);try{await r.promptSelect("",[{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],"back","\u6309 Enter \u8FD4\u56DE")==="back"&&await Hn(r);}catch{}}async function sR(r,e){try{let t=await r.promptSelect("\u9009\u62E9\u538B\u7F29\u6A21\u5F0F",[{label:"\u25B8 \u540C\u6B65LLM\u538B\u7F29 (\u63A8\u8350)",value:"sync",description:"\u963B\u585E\u5F0FLLM\u538B\u7F29\uFF0C\u538B\u7F29\u65F6\u6682\u505C\u5BF9\u8BDD"},{label:"\u25B8 \u5F02\u6B65LLM\u538B\u7F29",value:"async",description:"\u540E\u53F0LLM\u538B\u7F29\uFF0C\u538B\u7F29\u65F6\u53EF\u7EE7\u7EED\u5BF9\u8BDD"},{label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"separator",description:""},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],e.compressionMode,"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CESC \u53D6\u6D88");if(t==="back"){await Hn(r);return}if(t==="separator"){await Hn(r);return}if(t===e.compressionMode)r.logInfo("\u538B\u7F29\u6A21\u5F0F\u672A\u6539\u53D8");else {let n={...r.userConfig,context:{...e,compressionMode:t}};r.updateConfig(n),Pe(n),r.runner&&r.runner.setCompressionMode(t),r.uiController&&"setCompressionMode"in r.uiController&&r.uiController.setCompressionMode(t),r.updateCompressionMode&&r.updateCompressionMode(t),r.logInfo(`\u2713 \u538B\u7F29\u6A21\u5F0F\u5DF2\u5207\u6362\u4E3A: ${t==="sync"?"\u540C\u6B65LLM\u538B\u7F29":"\u5F02\u6B65LLM\u538B\u7F29"}`);}await Hn(r);}catch(t){t?.message!=="cancelled"&&r.logInfo("\u5207\u6362\u5931\u8D25",t?.message);}}async function rR(r,e){try{let t=await r.promptSelect("\u9009\u62E9\u89E6\u53D1\u538B\u7F29\u7684\u9608\u503C",[{label:"20% (\u6D4B\u8BD5)",value:"20",description:"\u6D4B\u8BD5\u81EA\u52A8\u538B\u7F29\u529F\u80FD"},{label:"70%",value:"70",description:"\u8F83\u65E9\u89E6\u53D1\uFF0C\u66F4\u79EF\u6781\u7684\u538B\u7F29"},{label:"80%",value:"80",description:"\u5E73\u8861\u9009\u62E9"},{label:"85% (\u9ED8\u8BA4)",value:"85",description:"\u63A8\u8350\u8BBE\u7F6E"},{label:"90%",value:"90",description:"\u5EF6\u8FDF\u89E6\u53D1\uFF0C\u4FDD\u7559\u66F4\u591A\u4E0A\u4E0B\u6587"},{label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"separator",description:""},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],String(e.thresholdPercent),"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CESC \u53D6\u6D88");if(t==="back"){await Hn(r);return}if(t==="separator"){await Hn(r);return}let n=parseInt(t,10);if(n===e.thresholdPercent)r.logInfo("\u9608\u503C\u672A\u6539\u53D8");else {let s={...r.userConfig,context:{...e,thresholdPercent:n}};r.updateConfig(s),Pe(s),r.uiController&&"setCompactionThreshold"in r.uiController&&r.uiController.setCompactionThreshold(n),r.updateCompactionThreshold&&r.updateCompactionThreshold(n),r.logInfo(`\u2713 \u538B\u7F29\u9608\u503C\u5DF2\u8BBE\u7F6E\u4E3A: ${n}%`);}await Hn(r);}catch(t){t?.message!=="cancelled"&&r.logInfo("\u8BBE\u7F6E\u5931\u8D25",t?.message);}}Gt();mn();Gl();function lt(r){return r>=1e6?(r/1e6).toFixed(1)+"M":r>=1e3?(r/1e3).toFixed(1)+"K":r.toString()}function Os(r,e){r.outputLines?r.outputLines(e):e.forEach(t=>oe(t));}function QC(r){let e=new Date(r),n=new Date().getTime()-r;return n<6e4?"\u521A\u521A":n<36e5?`${Math.floor(n/6e4)} \u5206\u949F\u524D`:n<864e5?`${Math.floor(n/36e5)} \u5C0F\u65F6\u524D`:n<6048e5?`${Math.floor(n/864e5)} \u5929\u524D`:e.toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}async function YC(r){try{r.clearOutputLines&&r.clearOutputLines();let e=await pn.getSummary();if(e.totalRequests===0){r.logInfo("\u6682\u65E0\u4F7F\u7528\u8BB0\u5F55");return}let t=[];if(t.push(""),t.push(x.highlight("\u{1F4CA} Token \u4F7F\u7528\u7EDF\u8BA1\u603B\u89C8")),t.push(""),t.push(x.primary(" \u603B\u8BF7\u6C42\u6570: ")+x.success(lt(e.totalRequests)+" \u6B21")),t.push(x.primary(" \u603B Tokens: ")+x.success(lt(e.totalTokens))),t.push(x.primary(" Input: ")+x.dim(lt(e.totalInputTokens))),t.push(x.primary(" Output: ")+x.dim(lt(e.totalOutputTokens))),e.totalCachedTokens>0){t.push(""),t.push(x.highlight(" \u7F13\u5B58\u7EDF\u8BA1:"));let s=(e.cacheHitRate*100).toFixed(1);t.push(x.primary(" \u603B\u7F13\u5B58\u547D\u4E2D: ")+x.success(lt(e.totalCachedTokens))+x.dim(` (${s}% \u547D\u4E2D\u7387)`)),e.totalOpenaiCachedTokens>0&&t.push(x.primary(" OpenAI \u7F13\u5B58: ")+x.dim(lt(e.totalOpenaiCachedTokens))+x.success(" (50% \u8282\u7701)")),e.totalAnthropicCacheReadTokens>0&&t.push(x.primary(" Claude Read: ")+x.dim(lt(e.totalAnthropicCacheReadTokens))+x.success(" (90% \u8282\u7701)")),e.totalAnthropicCacheCreationTokens>0&&t.push(x.primary(" Claude Write: ")+x.dim(lt(e.totalAnthropicCacheCreationTokens))+x.warning(" (+25% \u6210\u672C)"));}t.push(""),t.push(x.primary(" Provider \u6570: ")+x.dim(e.providerCount.toString())),t.push(x.primary(" \u6700\u540E\u8BF7\u6C42: ")+x.dim(QC(e.lastRequestTime))),t.push(""),Os(r,t);let n=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",[{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u67E5\u770B\u5404\u4E2A Provider \u7684\u8BE6\u7EC6\u7EDF\u8BA1"},{label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"}],"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(n==="back"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}n==="providers"?await vu(r):n==="records"&&await ca(r);}catch(e){r.clearOutputLines&&r.clearOutputLines(),e.message!=="cancelled"&&e.message!=="User cancelled"&&Os(r,[x.error("\u52A0\u8F7D\u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}function oR(r){let e=[];e.push(x.success("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),e.push(x.primary(`${r.provider}`)+x.dim(` (${r.totalRequests} \u6B21\u8BF7\u6C42)`)),e.push(""),e.push(x.dim("Input: ")+x.primary(lt(r.totalInputTokens).padEnd(8))+x.dim("Output: ")+x.success(lt(r.totalOutputTokens).padEnd(8))+x.dim("Total: ")+x.warning(lt(r.totalTokens))),r.totalCachedTokens>0&&(e.push(""),r.totalOpenaiCachedTokens>0&&e.push(x.dim("OpenAI \u7F13\u5B58: ")+x.code(lt(r.totalOpenaiCachedTokens))+x.success(" (50% \u8282\u7701)")),r.totalAnthropicCacheReadTokens>0&&e.push(x.dim("Claude Read: ")+x.info(lt(r.totalAnthropicCacheReadTokens))+x.success(" (90% \u8282\u7701)")),r.totalAnthropicCacheCreationTokens>0&&e.push(x.dim("Claude Write: ")+x.code(lt(r.totalAnthropicCacheCreationTokens))+x.warning(" (+25% \u6210\u672C)")));let t=r.totalRequests>0?(r.successRequests/r.totalRequests*100).toFixed(1):"0";e.push(""),e.push(x.dim("\u6210\u529F\u7387: ")+x.success(t+"%")+x.dim(" \u5E73\u5747\u8017\u65F6: ")+x.warning(r.avgDuration+"ms"));let n=Object.entries(r.models);if(n.length>0){e.push(""),e.push(x.dim("\u6A21\u578B\u5206\u5E03:"));for(let[s,o]of n.slice(0,3)){let i=s.length>30?s.slice(0,27)+"...":s;e.push(x.dim(` ${i.padEnd(30)} `)+x.primary(lt(o.totalTokens).padEnd(8))+x.dim(` (${o.requests} \u6B21)`));}n.length>3&&e.push(x.dim(` ... \u8FD8\u6709 ${n.length-3} \u4E2A\u6A21\u578B`));}return e.push(""),e}async function vu(r){try{let e=await pn.getProviderStats();if(e.length===0){r.logInfo("\u6682\u65E0 Provider \u7EDF\u8BA1");return}let t=2,n=Math.ceil(e.length/t),s=0;for(;;){r.clearOutputLines&&r.clearOutputLines();let o=s*t,i=Math.min(o+t,e.length),a=e.slice(o,i),l=[];l.push(""),l.push(x.highlight("\u{1F4C8} Provider \u7EDF\u8BA1")+x.dim(` (\u7B2C ${s+1}/${n} \u9875)`)),l.push("");for(let d of a)l.push(...oR(d));l.push(x.success("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),l.push(""),Os(r,l);let c=[];s>0&&c.push({label:"\u2190 \u4E0A\u4E00\u9875",value:"prev",description:`\u67E5\u770B\u7B2C ${s} \u9875`}),s<n-1&&c.push({label:"\u2192 \u4E0B\u4E00\u9875",value:"next",description:`\u67E5\u770B\u7B2C ${s+2} \u9875`}),c.push({label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"}),c.push({label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"});let u=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",c,"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(u==="prev"){s--;continue}else if(u==="next"){s++;continue}if(u==="back"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}if(u==="records"){await ca(r);return}}}catch(e){r.clearOutputLines&&r.clearOutputLines(),e.message!=="cancelled"&&e.message!=="User cancelled"&&Os(r,[x.error("\u52A0\u8F7D Provider \u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}async function ca(r){try{r.clearOutputLines&&r.clearOutputLines();let e=await pn.getProviderStats();if(e.length===0){r.logInfo("\u6682\u65E0 Provider \u7EDF\u8BA1");return}let t=e.map(i=>({label:i.provider,value:i.provider,description:`${i.totalRequests} \u6B21\u8BF7\u6C42, ${lt(i.totalTokens)} tokens`}));t.push({label:"\u2190 \u8FD4\u56DE",value:"__back__",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"});let n=await r.promptSelect("\u9009\u62E9 Provider \u67E5\u770B\u8BE6\u7EC6\u8BB0\u5F55",t,e[0].provider,"\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(n==="__back__"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}r.clearOutputLines&&r.clearOutputLines();let s=await pn.getProviderRecords(n,50);if(s.length===0){r.logInfo("\u8BE5 Provider \u6682\u65E0\u8BB0\u5F55");return}let o=[];o.push(""),o.push(x.highlight(`\u{1F4DD} ${n} - \u6700\u8FD1 ${s.length} \u6761\u8BB0\u5F55`)),o.push(""),o.push(x.dim(" \u7C7B\u578B ")+x.dim("\u6A21\u578B ")+x.dim("Input ")+x.dim("Output ")+x.dim("Cache ")+x.dim("\u8017\u65F6 ")+x.dim("\u72B6\u6001 ")+x.dim("\u65F6\u95F4")),o.push(x.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));for(let i of s){let a=i.requestType==="health-check"?"\u6D4B\u8BD5":"\u5BF9\u8BDD",l=i.model.length>14?i.model.slice(0,11)+"...":i.model,c=lt(i.inputTokens).padEnd(7),u=lt(i.outputTokens).padEnd(7),d=i.cachedTokens?lt(i.cachedTokens).padEnd(7):"-".padEnd(7),m=(i.duration+"ms").padEnd(7),g=i.success?x.success("\u2713"):x.error("\u2717"),h=QC(i.timestamp);o.push(x.dim(" "+a.padEnd(8))+x.primary(l.padEnd(16))+x.dim(c)+x.success(u)+x.code(d)+x.warning(m)+g+" "+x.dim(h));}o.push(""),Os(r,o);try{let i=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",[{label:"\u2190 \u8FD4\u56DE\u4E3B\u83DC\u5355",value:"back",description:"\u8FD4\u56DE\u7EDF\u8BA1\u4E3B\u83DC\u5355"},{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u8FD4\u56DE Provider \u7EDF\u8BA1\u5217\u8868"},{label:"\u25CF \u67E5\u770B\u5176\u4ED6 Provider",value:"other",description:"\u67E5\u770B\u5176\u4ED6 Provider \u7684\u8BE6\u7EC6\u8BB0\u5F55"}],"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");r.clearOutputLines&&r.clearOutputLines(),i==="other"?await ca(r):i==="providers"?await vu(r):i==="back"&&await So(r);}catch{r.clearOutputLines&&r.clearOutputLines();}}catch(e){e.message==="cancelled"||e.message==="User cancelled"?r.clearOutputLines&&r.clearOutputLines():r.logInfo("\u52A0\u8F7D\u8BE6\u7EC6\u8BB0\u5F55\u5931\u8D25",e.message);}}async function XC(r){try{let e=await pn.getProviderStats(),t=[{label:"\u6E05\u9664\u6240\u6709\u7EDF\u8BA1",value:"all",description:"\u26A0\uFE0F \u6E05\u9664\u6240\u6709 Provider \u7684\u7EDF\u8BA1\u6570\u636E"}];if(e.length>0)for(let s of e)t.push({label:`\u6E05\u9664 ${s.provider}`,value:s.provider,description:`\u6E05\u9664\u8BE5 Provider \u7684 ${s.totalRequests} \u6761\u8BB0\u5F55`});t.push({label:"\u53D6\u6D88",value:"cancel",description:"\u8FD4\u56DE\u4E0A\u4E00\u7EA7"});let n=await r.promptSelect("\u6E05\u9664\u7EDF\u8BA1\u6570\u636E",t,"cancel","\u26A0\uFE0F \u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D");if(n==="cancel")return;n==="all"?(await pn.clearAll(),r.logInfo("\u5DF2\u6E05\u9664\u6240\u6709\u7EDF\u8BA1\u6570\u636E")):(await pn.clearProvider(n),r.logInfo(`\u5DF2\u6E05\u9664 ${n} \u7684\u7EDF\u8BA1\u6570\u636E`));}catch(e){Os(r,[x.error("\u6E05\u9664\u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}async function So(r,e){if(e)switch(e){case "summary":await YC(r);return;case "providers":await vu(r);return;case "records":await ca(r);return;case "clear":await XC(r);return;default:Os(r,[x.error(`\u672A\u77E5\u64CD\u4F5C: ${e}`),x.dim("\u53EF\u7528\u64CD\u4F5C: summary, providers, records, clear")]);return}try{let t=await r.promptSelect("Token \u4F7F\u7528\u7EDF\u8BA1",[{label:"\u25CF \u67E5\u770B\u603B\u89C8",value:"summary",description:"\u663E\u793A\u6574\u4F53 Token \u4F7F\u7528\u7EDF\u8BA1"},{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u67E5\u770B\u5404\u4E2A Provider \u7684\u8BE6\u7EC6\u7EDF\u8BA1"},{label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"},{label:"\u25CF \u6E05\u9664\u7EDF\u8BA1",value:"clear",description:"\u6E05\u9664\u7EDF\u8BA1\u6570\u636E"},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E00\u7EA7"}],"summary","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u9000\u51FA");if(t==="back")return;switch(t){case "summary":await YC(r);break;case "providers":await vu(r);break;case "records":await ca(r);break;case "clear":await XC(r);break}}catch(t){t.message!=="User cancelled"&&t.message!=="cancelled"&&Os(r,[x.error("\u7EDF\u8BA1\u547D\u4EE4\u5931\u8D25: "+t.message)]);}}Gt();mn();async function ZC(r,e){let t=e?.toLowerCase();if(!t)try{t=await r.promptSelect("\u8BB0\u5FC6\u7CFB\u7EDF",[{label:"\u25CF \u67E5\u770B\u8BB0\u5FC6\u7EDF\u8BA1",value:"show",description:"\u77ED\u671F/\u4E2D\u671F/\u957F\u671F/\u6C38\u4E45 \u6761\u6570\u4E0E\u5927\u5C0F"},{label:"\u25CF \u67E5\u770B\u8DEF\u5F84",value:"paths",description:"\u663E\u793A\u8BB0\u5FC6\u6587\u4EF6\u8DEF\u5F84"},{label:"\u25CF \u914D\u7F6E\u6458\u8981\u6A21\u578B",value:"config",description:"\u5F00\u5173\u8BB0\u5FC6\u6458\u8981\u4E0E\u9009\u62E9\u6A21\u578B"},{label:"\u25CF \u8C03\u8BD5\u6CE8\u5165\u5185\u5BB9",value:"debug",description:"\u663E\u793A\u5F53\u524D\u4F1A\u6CE8\u5165\u7684\u8BB0\u5FC6\u6458\u8981"}],"show","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88");}catch(n){n?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",n?.message);return}switch(t){case "show":case "stats":await cR(r);break;case "paths":await uR(r);break;case "config":case "configure":await iR(r);break;case "debug":await dR(r);break;default:r.logInfo("\u65E0\u6548\u7684\u64CD\u4F5C","\u4F7F\u7528 /memory \u67E5\u770B\u53EF\u7528\u64CD\u4F5C");}}async function iR(r){let e=r.userConfig.memory??{},t=e.summarizerEnabled??true,n=e.summarizerModel??"",s=e.summarizerProviderId??"",o;try{o=await r.promptSelect("\u8BB0\u5FC6\u6458\u8981\u8BBE\u7F6E",[{label:`\u25CF \u6458\u8981\u5F00\u5173: ${t?"\u5F00\u542F":"\u5173\u95ED"}`,value:"toggle",description:"\u63A7\u5236\u81EA\u52A8\u8BB0\u5FC6\u6458\u8981"},{label:`\u25CF \u6458\u8981\u6A21\u578B: ${n||"\u9ED8\u8BA4"}`,value:"model",description:"\u9009\u62E9\u6458\u8981\u6A21\u578B\uFF08\u5982 haiku/gpt\uFF09"},{label:`\u25CF \u6458\u8981 Provider: ${s||"\u81EA\u52A8"}`,value:"provider",description:"\u6307\u5B9A\u6458\u8981\u4F7F\u7528\u7684 Provider\uFF08\u53EF\u9009\uFF09"},{label:"\u25CF \u8FD4\u56DE",value:"back"}],"toggle","Enter \u9009\u62E9\uFF0CESC \u53D6\u6D88");}catch(i){i?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",i?.message);return}if(o!=="back"){if(o==="toggle"){let i=await r.promptSelect("\u662F\u5426\u542F\u7528\u8BB0\u5FC6\u6458\u8981",[{label:"\u5F00\u542F",value:"on"},{label:"\u5173\u95ED",value:"off"}],t?"on":"off");ua(r,{summarizerEnabled:i==="on"}),r.logInfo("\u8BB0\u5FC6\u6458\u8981\u5DF2\u66F4\u65B0",i==="on"?"\u5DF2\u5F00\u542F":"\u5DF2\u5173\u95ED");return}if(o==="model"){let i;try{i=await aR(r,n);}catch(c){c?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",c?.message);return}let{model:a,existsInConfig:l}=i;if(a==="__cancel__")return;if(a==="__default__"){ua(r,{summarizerModel:void 0}),r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u66F4\u65B0","\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B");return}if(ua(r,{summarizerModel:a}),!l){r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u8BBE\u7F6E",`\u6A21\u578B "${a}" \u672A\u5728 provider \u914D\u7F6E\u4E2D\u627E\u5230\uFF0C\u53EF\u80FD\u65E0\u6CD5\u751F\u6548`);return}r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u8BBE\u7F6E",a);return}if(o==="provider"){let i;try{i=await lR(r,s);}catch(a){a?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",a?.message);return}if(!i)return;if(i==="__auto__"){ua(r,{summarizerProviderId:void 0}),r.logInfo("\u6458\u8981 Provider \u5DF2\u66F4\u65B0","\u81EA\u52A8\u9009\u62E9");return}ua(r,{summarizerProviderId:i}),r.logInfo("\u6458\u8981 Provider \u5DF2\u8BBE\u7F6E",i);}}}async function aR(r,e){let t=new qe(r.userConfig),n=new Set;for(let l of t.getProviders())for(let c of l.models??[])c?.name&&n.add(c.name);let s=["claude-haiku-4-5-20251001","claude-haiku","gpt-4o-mini","gpt-4.1-mini","gpt-4o","gemini-1.5-flash","gemini-2.0-flash"],o=Array.from(new Set([...s,...n])),i=[{label:"\u9ED8\u8BA4\uFF08\u81EA\u52A8\u9009\u62E9\uFF09",value:"__default__",description:"\u4F7F\u7528\u9ED8\u8BA4\u6458\u8981\u6A21\u578B"},...o.map(l=>({label:l,value:l,description:n.has(l)?void 0:"\u672A\u5728 provider \u914D\u7F6E\u4E2D\u627E\u5230"})),{label:"\u81EA\u5B9A\u4E49\u6A21\u578B",value:"__custom__",description:"\u8F93\u5165\u81EA\u5B9A\u4E49\u6A21\u578B\u540D\u79F0"}],a=await r.promptSelect("\u9009\u62E9\u6458\u8981\u6A21\u578B",i,e||"__default__");if(a==="__custom__"){let c=(await r.promptText("\u8F93\u5165\u6A21\u578B\u540D\u79F0",{allowEmpty:false})).trim();return {model:c||"__cancel__",existsInConfig:n.has(c)}}return {model:a||"__cancel__",existsInConfig:n.has(a)}}async function lR(r,e){let n=new qe(r.userConfig).getProviders();if(n.length===0)return r.logInfo("\u672A\u914D\u7F6E Provider","\u8BF7\u5148\u901A\u8FC7 /provider \u6DFB\u52A0"),null;let s=[{label:"\u81EA\u52A8\u9009\u62E9",value:"__auto__",description:"\u6839\u636E\u6A21\u578B\u81EA\u52A8\u5339\u914D"},...n.map(i=>({label:i.id,value:i.id,description:i.name}))];return await r.promptSelect("\u9009\u62E9\u6458\u8981 Provider",s,e||"__auto__")}function ua(r,e){let t={...r.userConfig.memory??{}};"summarizerEnabled"in e&&(t.summarizerEnabled=e.summarizerEnabled),"summarizerModel"in e&&(e.summarizerModel?t.summarizerModel=e.summarizerModel:delete t.summarizerModel),"summarizerProviderId"in e&&(e.summarizerProviderId?t.summarizerProviderId=e.summarizerProviderId:delete t.summarizerProviderId);let n={...r.userConfig,memory:t};r.updateConfig(n),Pe(n);}async function cR(r){let e=await r.actionLog.getMemoryStats(),t=pR(e);gg(r,t);}async function uR(r){let e=await r.actionLog.getMemoryStats(),t=mR(e);gg(r,t);}async function dR(r){let e=await r.actionLog.getMemoryInjectionSummary({language:r.userConfig.language??"zh",includePersistent:true,includeLastRun:true}),t=[];t.push(""),t.push(x.highlight(" \u8BB0\u5FC6\u6CE8\u5165\u9884\u89C8")),t.push(""),e?e.split(`
3565
+ `);r.logInfo("Context Details",o);try{await r.promptSelect("",[{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],"back","\u6309 Enter \u8FD4\u56DE")==="back"&&await Hn(r);}catch{}}async function sR(r,e){try{let t=await r.promptSelect("\u9009\u62E9\u538B\u7F29\u6A21\u5F0F",[{label:"\u25B8 \u540C\u6B65LLM\u538B\u7F29 (\u63A8\u8350)",value:"sync",description:"\u963B\u585E\u5F0FLLM\u538B\u7F29\uFF0C\u538B\u7F29\u65F6\u6682\u505C\u5BF9\u8BDD"},{label:"\u25B8 \u5F02\u6B65LLM\u538B\u7F29",value:"async",description:"\u540E\u53F0LLM\u538B\u7F29\uFF0C\u538B\u7F29\u65F6\u53EF\u7EE7\u7EED\u5BF9\u8BDD"},{label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"separator",description:""},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],e.compressionMode,"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CESC \u53D6\u6D88");if(t==="back"){await Hn(r);return}if(t==="separator"){await Hn(r);return}if(t===e.compressionMode)r.logInfo("\u538B\u7F29\u6A21\u5F0F\u672A\u6539\u53D8");else {let n={...r.userConfig,context:{...e,compressionMode:t}};r.updateConfig(n),Pe(n),r.runner&&r.runner.setCompressionMode(t),r.uiController&&"setCompressionMode"in r.uiController&&r.uiController.setCompressionMode(t),r.updateCompressionMode&&r.updateCompressionMode(t),r.logInfo(`\u2713 \u538B\u7F29\u6A21\u5F0F\u5DF2\u5207\u6362\u4E3A: ${t==="sync"?"\u540C\u6B65LLM\u538B\u7F29":"\u5F02\u6B65LLM\u538B\u7F29"}`);}await Hn(r);}catch(t){t?.message!=="cancelled"&&r.logInfo("\u5207\u6362\u5931\u8D25",t?.message);}}async function rR(r,e){try{let t=await r.promptSelect("\u9009\u62E9\u89E6\u53D1\u538B\u7F29\u7684\u9608\u503C",[{label:"20% (\u6D4B\u8BD5)",value:"20",description:"\u6D4B\u8BD5\u81EA\u52A8\u538B\u7F29\u529F\u80FD"},{label:"70%",value:"70",description:"\u8F83\u65E9\u89E6\u53D1\uFF0C\u66F4\u79EF\u6781\u7684\u538B\u7F29"},{label:"80%",value:"80",description:"\u5E73\u8861\u9009\u62E9"},{label:"85% (\u9ED8\u8BA4)",value:"85",description:"\u63A8\u8350\u8BBE\u7F6E"},{label:"90%",value:"90",description:"\u5EF6\u8FDF\u89E6\u53D1\uFF0C\u4FDD\u7559\u66F4\u591A\u4E0A\u4E0B\u6587"},{label:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",value:"separator",description:""},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E0B\u6587\u7BA1\u7406\u83DC\u5355"}],String(e.thresholdPercent),"\u6309 \u2191\u2193 \u9009\u62E9\uFF0CESC \u53D6\u6D88");if(t==="back"){await Hn(r);return}if(t==="separator"){await Hn(r);return}let n=parseInt(t,10);if(n===e.thresholdPercent)r.logInfo("\u9608\u503C\u672A\u6539\u53D8");else {let s={...r.userConfig,context:{...e,thresholdPercent:n}};r.updateConfig(s),Pe(s),r.uiController&&"setCompactionThreshold"in r.uiController&&r.uiController.setCompactionThreshold(n),r.updateCompactionThreshold&&r.updateCompactionThreshold(n),r.logInfo(`\u2713 \u538B\u7F29\u9608\u503C\u5DF2\u8BBE\u7F6E\u4E3A: ${n}%`);}await Hn(r);}catch(t){t?.message!=="cancelled"&&r.logInfo("\u8BBE\u7F6E\u5931\u8D25",t?.message);}}Gt();mn();Gl();function ct(r){return r>=1e6?(r/1e6).toFixed(1)+"M":r>=1e3?(r/1e3).toFixed(1)+"K":r.toString()}function Os(r,e){r.outputLines?r.outputLines(e):e.forEach(t=>oe(t));}function QC(r){let e=new Date(r),n=new Date().getTime()-r;return n<6e4?"\u521A\u521A":n<36e5?`${Math.floor(n/6e4)} \u5206\u949F\u524D`:n<864e5?`${Math.floor(n/36e5)} \u5C0F\u65F6\u524D`:n<6048e5?`${Math.floor(n/864e5)} \u5929\u524D`:e.toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}async function YC(r){try{r.clearOutputLines&&r.clearOutputLines();let e=await pn.getSummary();if(e.totalRequests===0){r.logInfo("\u6682\u65E0\u4F7F\u7528\u8BB0\u5F55");return}let t=[];if(t.push(""),t.push(x.highlight("\u{1F4CA} Token \u4F7F\u7528\u7EDF\u8BA1\u603B\u89C8")),t.push(""),t.push(x.primary(" \u603B\u8BF7\u6C42\u6570: ")+x.success(ct(e.totalRequests)+" \u6B21")),t.push(x.primary(" \u603B Tokens: ")+x.success(ct(e.totalTokens))),t.push(x.primary(" Input: ")+x.dim(ct(e.totalInputTokens))),t.push(x.primary(" Output: ")+x.dim(ct(e.totalOutputTokens))),e.totalCachedTokens>0){t.push(""),t.push(x.highlight(" \u7F13\u5B58\u7EDF\u8BA1:"));let s=(e.cacheHitRate*100).toFixed(1);t.push(x.primary(" \u603B\u7F13\u5B58\u547D\u4E2D: ")+x.success(ct(e.totalCachedTokens))+x.dim(` (${s}% \u547D\u4E2D\u7387)`)),e.totalOpenaiCachedTokens>0&&t.push(x.primary(" OpenAI \u7F13\u5B58: ")+x.dim(ct(e.totalOpenaiCachedTokens))+x.success(" (50% \u8282\u7701)")),e.totalAnthropicCacheReadTokens>0&&t.push(x.primary(" Claude Read: ")+x.dim(ct(e.totalAnthropicCacheReadTokens))+x.success(" (90% \u8282\u7701)")),e.totalAnthropicCacheCreationTokens>0&&t.push(x.primary(" Claude Write: ")+x.dim(ct(e.totalAnthropicCacheCreationTokens))+x.warning(" (+25% \u6210\u672C)"));}t.push(""),t.push(x.primary(" Provider \u6570: ")+x.dim(e.providerCount.toString())),t.push(x.primary(" \u6700\u540E\u8BF7\u6C42: ")+x.dim(QC(e.lastRequestTime))),t.push(""),Os(r,t);let n=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",[{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u67E5\u770B\u5404\u4E2A Provider \u7684\u8BE6\u7EC6\u7EDF\u8BA1"},{label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"}],"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(n==="back"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}n==="providers"?await vu(r):n==="records"&&await ca(r);}catch(e){r.clearOutputLines&&r.clearOutputLines(),e.message!=="cancelled"&&e.message!=="User cancelled"&&Os(r,[x.error("\u52A0\u8F7D\u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}function oR(r){let e=[];e.push(x.success("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),e.push(x.primary(`${r.provider}`)+x.dim(` (${r.totalRequests} \u6B21\u8BF7\u6C42)`)),e.push(""),e.push(x.dim("Input: ")+x.primary(ct(r.totalInputTokens).padEnd(8))+x.dim("Output: ")+x.success(ct(r.totalOutputTokens).padEnd(8))+x.dim("Total: ")+x.warning(ct(r.totalTokens))),r.totalCachedTokens>0&&(e.push(""),r.totalOpenaiCachedTokens>0&&e.push(x.dim("OpenAI \u7F13\u5B58: ")+x.code(ct(r.totalOpenaiCachedTokens))+x.success(" (50% \u8282\u7701)")),r.totalAnthropicCacheReadTokens>0&&e.push(x.dim("Claude Read: ")+x.info(ct(r.totalAnthropicCacheReadTokens))+x.success(" (90% \u8282\u7701)")),r.totalAnthropicCacheCreationTokens>0&&e.push(x.dim("Claude Write: ")+x.code(ct(r.totalAnthropicCacheCreationTokens))+x.warning(" (+25% \u6210\u672C)")));let t=r.totalRequests>0?(r.successRequests/r.totalRequests*100).toFixed(1):"0";e.push(""),e.push(x.dim("\u6210\u529F\u7387: ")+x.success(t+"%")+x.dim(" \u5E73\u5747\u8017\u65F6: ")+x.warning(r.avgDuration+"ms"));let n=Object.entries(r.models);if(n.length>0){e.push(""),e.push(x.dim("\u6A21\u578B\u5206\u5E03:"));for(let[s,o]of n.slice(0,3)){let i=s.length>30?s.slice(0,27)+"...":s;e.push(x.dim(` ${i.padEnd(30)} `)+x.primary(ct(o.totalTokens).padEnd(8))+x.dim(` (${o.requests} \u6B21)`));}n.length>3&&e.push(x.dim(` ... \u8FD8\u6709 ${n.length-3} \u4E2A\u6A21\u578B`));}return e.push(""),e}async function vu(r){try{let e=await pn.getProviderStats();if(e.length===0){r.logInfo("\u6682\u65E0 Provider \u7EDF\u8BA1");return}let t=2,n=Math.ceil(e.length/t),s=0;for(;;){r.clearOutputLines&&r.clearOutputLines();let o=s*t,i=Math.min(o+t,e.length),a=e.slice(o,i),l=[];l.push(""),l.push(x.highlight("\u{1F4C8} Provider \u7EDF\u8BA1")+x.dim(` (\u7B2C ${s+1}/${n} \u9875)`)),l.push("");for(let d of a)l.push(...oR(d));l.push(x.success("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")),l.push(""),Os(r,l);let c=[];s>0&&c.push({label:"\u2190 \u4E0A\u4E00\u9875",value:"prev",description:`\u67E5\u770B\u7B2C ${s} \u9875`}),s<n-1&&c.push({label:"\u2192 \u4E0B\u4E00\u9875",value:"next",description:`\u67E5\u770B\u7B2C ${s+2} \u9875`}),c.push({label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"}),c.push({label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"});let u=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",c,"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(u==="prev"){s--;continue}else if(u==="next"){s++;continue}if(u==="back"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}if(u==="records"){await ca(r);return}}}catch(e){r.clearOutputLines&&r.clearOutputLines(),e.message!=="cancelled"&&e.message!=="User cancelled"&&Os(r,[x.error("\u52A0\u8F7D Provider \u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}async function ca(r){try{r.clearOutputLines&&r.clearOutputLines();let e=await pn.getProviderStats();if(e.length===0){r.logInfo("\u6682\u65E0 Provider \u7EDF\u8BA1");return}let t=e.map(i=>({label:i.provider,value:i.provider,description:`${i.totalRequests} \u6B21\u8BF7\u6C42, ${ct(i.totalTokens)} tokens`}));t.push({label:"\u2190 \u8FD4\u56DE",value:"__back__",description:"\u8FD4\u56DE\u4E3B\u83DC\u5355"});let n=await r.promptSelect("\u9009\u62E9 Provider \u67E5\u770B\u8BE6\u7EC6\u8BB0\u5F55",t,e[0].provider,"\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");if(n==="__back__"){r.clearOutputLines&&r.clearOutputLines(),await So(r);return}r.clearOutputLines&&r.clearOutputLines();let s=await pn.getProviderRecords(n,50);if(s.length===0){r.logInfo("\u8BE5 Provider \u6682\u65E0\u8BB0\u5F55");return}let o=[];o.push(""),o.push(x.highlight(`\u{1F4DD} ${n} - \u6700\u8FD1 ${s.length} \u6761\u8BB0\u5F55`)),o.push(""),o.push(x.dim(" \u7C7B\u578B ")+x.dim("\u6A21\u578B ")+x.dim("Input ")+x.dim("Output ")+x.dim("Cache ")+x.dim("\u8017\u65F6 ")+x.dim("\u72B6\u6001 ")+x.dim("\u65F6\u95F4")),o.push(x.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));for(let i of s){let a=i.requestType==="health-check"?"\u6D4B\u8BD5":"\u5BF9\u8BDD",l=i.model.length>14?i.model.slice(0,11)+"...":i.model,c=ct(i.inputTokens).padEnd(7),u=ct(i.outputTokens).padEnd(7),d=i.cachedTokens?ct(i.cachedTokens).padEnd(7):"-".padEnd(7),m=(i.duration+"ms").padEnd(7),g=i.success?x.success("\u2713"):x.error("\u2717"),h=QC(i.timestamp);o.push(x.dim(" "+a.padEnd(8))+x.primary(l.padEnd(16))+x.dim(c)+x.success(u)+x.code(d)+x.warning(m)+g+" "+x.dim(h));}o.push(""),Os(r,o);try{let i=await r.promptSelect("\u7EE7\u7EED\u67E5\u770B",[{label:"\u2190 \u8FD4\u56DE\u4E3B\u83DC\u5355",value:"back",description:"\u8FD4\u56DE\u7EDF\u8BA1\u4E3B\u83DC\u5355"},{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u8FD4\u56DE Provider \u7EDF\u8BA1\u5217\u8868"},{label:"\u25CF \u67E5\u770B\u5176\u4ED6 Provider",value:"other",description:"\u67E5\u770B\u5176\u4ED6 Provider \u7684\u8BE6\u7EC6\u8BB0\u5F55"}],"back","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u8FD4\u56DE");r.clearOutputLines&&r.clearOutputLines(),i==="other"?await ca(r):i==="providers"?await vu(r):i==="back"&&await So(r);}catch{r.clearOutputLines&&r.clearOutputLines();}}catch(e){e.message==="cancelled"||e.message==="User cancelled"?r.clearOutputLines&&r.clearOutputLines():r.logInfo("\u52A0\u8F7D\u8BE6\u7EC6\u8BB0\u5F55\u5931\u8D25",e.message);}}async function XC(r){try{let e=await pn.getProviderStats(),t=[{label:"\u6E05\u9664\u6240\u6709\u7EDF\u8BA1",value:"all",description:"\u26A0\uFE0F \u6E05\u9664\u6240\u6709 Provider \u7684\u7EDF\u8BA1\u6570\u636E"}];if(e.length>0)for(let s of e)t.push({label:`\u6E05\u9664 ${s.provider}`,value:s.provider,description:`\u6E05\u9664\u8BE5 Provider \u7684 ${s.totalRequests} \u6761\u8BB0\u5F55`});t.push({label:"\u53D6\u6D88",value:"cancel",description:"\u8FD4\u56DE\u4E0A\u4E00\u7EA7"});let n=await r.promptSelect("\u6E05\u9664\u7EDF\u8BA1\u6570\u636E",t,"cancel","\u26A0\uFE0F \u6B64\u64CD\u4F5C\u4E0D\u53EF\u6062\u590D");if(n==="cancel")return;n==="all"?(await pn.clearAll(),r.logInfo("\u5DF2\u6E05\u9664\u6240\u6709\u7EDF\u8BA1\u6570\u636E")):(await pn.clearProvider(n),r.logInfo(`\u5DF2\u6E05\u9664 ${n} \u7684\u7EDF\u8BA1\u6570\u636E`));}catch(e){Os(r,[x.error("\u6E05\u9664\u7EDF\u8BA1\u5931\u8D25: "+e.message)]);}}async function So(r,e){if(e)switch(e){case "summary":await YC(r);return;case "providers":await vu(r);return;case "records":await ca(r);return;case "clear":await XC(r);return;default:Os(r,[x.error(`\u672A\u77E5\u64CD\u4F5C: ${e}`),x.dim("\u53EF\u7528\u64CD\u4F5C: summary, providers, records, clear")]);return}try{let t=await r.promptSelect("Token \u4F7F\u7528\u7EDF\u8BA1",[{label:"\u25CF \u67E5\u770B\u603B\u89C8",value:"summary",description:"\u663E\u793A\u6574\u4F53 Token \u4F7F\u7528\u7EDF\u8BA1"},{label:"\u25CF Provider \u7EDF\u8BA1",value:"providers",description:"\u67E5\u770B\u5404\u4E2A Provider \u7684\u8BE6\u7EC6\u7EDF\u8BA1"},{label:"\u25CF \u8BE6\u7EC6\u8BB0\u5F55",value:"records",description:"\u67E5\u770B\u6307\u5B9A Provider \u7684\u8BF7\u6C42\u8BB0\u5F55"},{label:"\u25CF \u6E05\u9664\u7EDF\u8BA1",value:"clear",description:"\u6E05\u9664\u7EDF\u8BA1\u6570\u636E"},{label:"\u2190 \u8FD4\u56DE",value:"back",description:"\u8FD4\u56DE\u4E0A\u4E00\u7EA7"}],"summary","\u4E0A\u4E0B\u952E\u9009\u62E9\uFF0C\u56DE\u8F66\u786E\u8BA4\uFF0CESC \u9000\u51FA");if(t==="back")return;switch(t){case "summary":await YC(r);break;case "providers":await vu(r);break;case "records":await ca(r);break;case "clear":await XC(r);break}}catch(t){t.message!=="User cancelled"&&t.message!=="cancelled"&&Os(r,[x.error("\u7EDF\u8BA1\u547D\u4EE4\u5931\u8D25: "+t.message)]);}}Gt();mn();async function ZC(r,e){let t=e?.toLowerCase();if(!t)try{t=await r.promptSelect("\u8BB0\u5FC6\u7CFB\u7EDF",[{label:"\u25CF \u67E5\u770B\u8BB0\u5FC6\u7EDF\u8BA1",value:"show",description:"\u77ED\u671F/\u4E2D\u671F/\u957F\u671F/\u6C38\u4E45 \u6761\u6570\u4E0E\u5927\u5C0F"},{label:"\u25CF \u67E5\u770B\u8DEF\u5F84",value:"paths",description:"\u663E\u793A\u8BB0\u5FC6\u6587\u4EF6\u8DEF\u5F84"},{label:"\u25CF \u914D\u7F6E\u6458\u8981\u6A21\u578B",value:"config",description:"\u5F00\u5173\u8BB0\u5FC6\u6458\u8981\u4E0E\u9009\u62E9\u6A21\u578B"},{label:"\u25CF \u8C03\u8BD5\u6CE8\u5165\u5185\u5BB9",value:"debug",description:"\u663E\u793A\u5F53\u524D\u4F1A\u6CE8\u5165\u7684\u8BB0\u5FC6\u6458\u8981"}],"show","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88");}catch(n){n?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",n?.message);return}switch(t){case "show":case "stats":await cR(r);break;case "paths":await uR(r);break;case "config":case "configure":await iR(r);break;case "debug":await dR(r);break;default:r.logInfo("\u65E0\u6548\u7684\u64CD\u4F5C","\u4F7F\u7528 /memory \u67E5\u770B\u53EF\u7528\u64CD\u4F5C");}}async function iR(r){let e=r.userConfig.memory??{},t=e.summarizerEnabled??true,n=e.summarizerModel??"",s=e.summarizerProviderId??"",o;try{o=await r.promptSelect("\u8BB0\u5FC6\u6458\u8981\u8BBE\u7F6E",[{label:`\u25CF \u6458\u8981\u5F00\u5173: ${t?"\u5F00\u542F":"\u5173\u95ED"}`,value:"toggle",description:"\u63A7\u5236\u81EA\u52A8\u8BB0\u5FC6\u6458\u8981"},{label:`\u25CF \u6458\u8981\u6A21\u578B: ${n||"\u9ED8\u8BA4"}`,value:"model",description:"\u9009\u62E9\u6458\u8981\u6A21\u578B\uFF08\u5982 haiku/gpt\uFF09"},{label:`\u25CF \u6458\u8981 Provider: ${s||"\u81EA\u52A8"}`,value:"provider",description:"\u6307\u5B9A\u6458\u8981\u4F7F\u7528\u7684 Provider\uFF08\u53EF\u9009\uFF09"},{label:"\u25CF \u8FD4\u56DE",value:"back"}],"toggle","Enter \u9009\u62E9\uFF0CESC \u53D6\u6D88");}catch(i){i?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",i?.message);return}if(o!=="back"){if(o==="toggle"){let i=await r.promptSelect("\u662F\u5426\u542F\u7528\u8BB0\u5FC6\u6458\u8981",[{label:"\u5F00\u542F",value:"on"},{label:"\u5173\u95ED",value:"off"}],t?"on":"off");ua(r,{summarizerEnabled:i==="on"}),r.logInfo("\u8BB0\u5FC6\u6458\u8981\u5DF2\u66F4\u65B0",i==="on"?"\u5DF2\u5F00\u542F":"\u5DF2\u5173\u95ED");return}if(o==="model"){let i;try{i=await aR(r,n);}catch(c){c?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",c?.message);return}let{model:a,existsInConfig:l}=i;if(a==="__cancel__")return;if(a==="__default__"){ua(r,{summarizerModel:void 0}),r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u66F4\u65B0","\u4F7F\u7528\u9ED8\u8BA4\u6A21\u578B");return}if(ua(r,{summarizerModel:a}),!l){r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u8BBE\u7F6E",`\u6A21\u578B "${a}" \u672A\u5728 provider \u914D\u7F6E\u4E2D\u627E\u5230\uFF0C\u53EF\u80FD\u65E0\u6CD5\u751F\u6548`);return}r.logInfo("\u6458\u8981\u6A21\u578B\u5DF2\u8BBE\u7F6E",a);return}if(o==="provider"){let i;try{i=await lR(r,s);}catch(a){a?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",a?.message);return}if(!i)return;if(i==="__auto__"){ua(r,{summarizerProviderId:void 0}),r.logInfo("\u6458\u8981 Provider \u5DF2\u66F4\u65B0","\u81EA\u52A8\u9009\u62E9");return}ua(r,{summarizerProviderId:i}),r.logInfo("\u6458\u8981 Provider \u5DF2\u8BBE\u7F6E",i);}}}async function aR(r,e){let t=new qe(r.userConfig),n=new Set;for(let l of t.getProviders())for(let c of l.models??[])c?.name&&n.add(c.name);let s=["claude-haiku-4-5-20251001","claude-haiku","gpt-4o-mini","gpt-4.1-mini","gpt-4o","gemini-1.5-flash","gemini-2.0-flash"],o=Array.from(new Set([...s,...n])),i=[{label:"\u9ED8\u8BA4\uFF08\u81EA\u52A8\u9009\u62E9\uFF09",value:"__default__",description:"\u4F7F\u7528\u9ED8\u8BA4\u6458\u8981\u6A21\u578B"},...o.map(l=>({label:l,value:l,description:n.has(l)?void 0:"\u672A\u5728 provider \u914D\u7F6E\u4E2D\u627E\u5230"})),{label:"\u81EA\u5B9A\u4E49\u6A21\u578B",value:"__custom__",description:"\u8F93\u5165\u81EA\u5B9A\u4E49\u6A21\u578B\u540D\u79F0"}],a=await r.promptSelect("\u9009\u62E9\u6458\u8981\u6A21\u578B",i,e||"__default__");if(a==="__custom__"){let c=(await r.promptText("\u8F93\u5165\u6A21\u578B\u540D\u79F0",{allowEmpty:false})).trim();return {model:c||"__cancel__",existsInConfig:n.has(c)}}return {model:a||"__cancel__",existsInConfig:n.has(a)}}async function lR(r,e){let n=new qe(r.userConfig).getProviders();if(n.length===0)return r.logInfo("\u672A\u914D\u7F6E Provider","\u8BF7\u5148\u901A\u8FC7 /provider \u6DFB\u52A0"),null;let s=[{label:"\u81EA\u52A8\u9009\u62E9",value:"__auto__",description:"\u6839\u636E\u6A21\u578B\u81EA\u52A8\u5339\u914D"},...n.map(i=>({label:i.id,value:i.id,description:i.name}))];return await r.promptSelect("\u9009\u62E9\u6458\u8981 Provider",s,e||"__auto__")}function ua(r,e){let t={...r.userConfig.memory??{}};"summarizerEnabled"in e&&(t.summarizerEnabled=e.summarizerEnabled),"summarizerModel"in e&&(e.summarizerModel?t.summarizerModel=e.summarizerModel:delete t.summarizerModel),"summarizerProviderId"in e&&(e.summarizerProviderId?t.summarizerProviderId=e.summarizerProviderId:delete t.summarizerProviderId);let n={...r.userConfig,memory:t};r.updateConfig(n),Pe(n);}async function cR(r){let e=await r.actionLog.getMemoryStats(),t=pR(e);gg(r,t);}async function uR(r){let e=await r.actionLog.getMemoryStats(),t=mR(e);gg(r,t);}async function dR(r){let e=await r.actionLog.getMemoryInjectionSummary({language:r.userConfig.language??"zh",includePersistent:true,includeLastRun:true}),t=[];t.push(""),t.push(x.highlight(" \u8BB0\u5FC6\u6CE8\u5165\u9884\u89C8")),t.push(""),e?e.split(`
3567
3566
  `).forEach(n=>{t.push(x.info(` ${n}`));}):t.push(x.dim(" (\u65E0\u53EF\u7528\u8BB0\u5FC6)")),t.push(""),gg(r,t);}function pR(r){let e=o=>o.toLocaleString("en-US"),t=o=>{if(o<1024)return `${o} B`;let i=o/1024;if(i<1024)return `${i.toFixed(1)} KB`;let a=i/1024;return a<1024?`${a.toFixed(2)} MB`:`${(a/1024).toFixed(2)} GB`},n=r.longTerm.total,s=[];return s.push(""),s.push(x.highlight(" \u8BB0\u5FC6\u7EDF\u8BA1")),s.push(""),s.push(x.dim(" \u77ED\u671F (recent): ")+x.info(`${e(r.shortTerm.count)} \u6761, ${t(r.shortTerm.sizeBytes)}`)),s.push(x.dim(" \u4E2D\u671F (session): ")+x.info(`${e(r.session.count)} \u6761, ${t(r.session.sizeBytes)}`)),s.push(x.dim(" \u957F\u671F (progress/standard/lesson): ")+x.info(`${e(n.count)} \u6761, ${t(n.sizeBytes)}`)),s.push(x.dim(" - progress: ")+x.info(`${e(r.longTerm.progress.count)} \u6761, ${t(r.longTerm.progress.sizeBytes)}`)),s.push(x.dim(" - standard: ")+x.info(`${e(r.longTerm.standard.count)} \u6761, ${t(r.longTerm.standard.sizeBytes)}`)),s.push(x.dim(" - lesson: ")+x.info(`${e(r.longTerm.lesson.count)} \u6761, ${t(r.longTerm.lesson.sizeBytes)}`)),s.push(x.dim(" \u6C38\u4E45 (pinned): ")+x.info(`${e(r.pinned.count)} \u6761, ${t(r.pinned.sizeBytes)}`)),s.push(""),s.push(x.dim(" \u603B\u8BA1: ")+x.info(`${e(r.totals.count)} \u6761, ${t(r.totals.sizeBytes)}`)),s.push(""),s}function mR(r){let e=[];return e.push(""),e.push(x.highlight(" \u8BB0\u5FC6\u8DEF\u5F84")),e.push(""),r.shortTerm.path&&e.push(x.dim(" \u77ED\u671F: ")+x.info(r.shortTerm.path)),r.session.path&&e.push(x.dim(" \u4E2D\u671F: ")+x.info(r.session.path)),r.longTerm.progress.path&&e.push(x.dim(" \u8FDB\u5EA6: ")+x.info(r.longTerm.progress.path)),r.longTerm.standard.path&&e.push(x.dim(" \u89C4\u8303: ")+x.info(r.longTerm.standard.path)),r.longTerm.lesson.path&&e.push(x.dim(" \u6559\u8BAD: ")+x.info(r.longTerm.lesson.path)),r.pinned.path&&e.push(x.dim(" \u6C38\u4E45: ")+x.info(r.pinned.path)),e.push(""),e}function gg(r,e){if(r.uiController){let t=r.uiController;if(typeof t.setCommandOutputLines=="function"){t.setCommandOutputLines(e);return}if(typeof t.printCommandOutput=="function"){for(let n of e)t.printCommandOutput(n);return}}for(let t of e)oe(t);}ps();var ex="0.0.0.0",tx=7090;async function fR(r){try{let{renderUnicodeCompact:e}=await import('uqr');return {qr:e(r,{ecc:"M",border:1})}}catch(e){return {qr:null,error:e instanceof Error?e.message:String(e)}}}async function yR(r){try{let e=await import('qrcode'),t=e.default??e;if(!t||typeof t.toFile!="function")return {filePath:null,error:"QRCode module missing or invalid."};let n=Date.now(),s=join(tmpdir(),`neox-qr-${n}.png`);await t.toFile(s,r,{type:"png",errorCorrectionLevel:"H",margin:4,scale:10,color:{dark:"#000000",light:"#FFFFFF"}});let{exec:o}=await import('child_process'),{promisify:i}=await import('util'),a=i(o),l=process.platform,c;return l==="darwin"?c=`open "${s}"`:l==="win32"?c=`start "" "${s}"`:Ve()?c=`explorer.exe "${js(s)}"`:c=`xdg-open "${s}"`,await a(c),{filePath:s}}catch(e){return {filePath:null,error:e instanceof Error?e.message:String(e)}}}function bR(r){let e=r.urls[0],t=e?new URL(e).hostname:r.host&&r.host!==ex?r.host:"127.0.0.1";return {payload:`neox://pair?${new URLSearchParams({mode:r.networkMode,host:t,port:String(r.port),token:r.token||""}).toString()}`,lanUrl:`http://${t}:${r.port}`}}function vR(r){return r.remote??{}}function nx(r){return r==="vps"?"vps":"lan"}async function sx(r,e){let t=r.getStatus(),n=e?.toLowerCase();if(!n)try{n=await r.promptSelect("\u8FDC\u7A0B\u8BBF\u95EE (Remote Access)",[{label:`\u25CF \u5F00\u5173: ${t.enabled?"\u5F00\u542F":"\u5173\u95ED"}`,value:"toggle",description:"\u542F\u7528\u6216\u5173\u95ED\u8FDC\u7A0B\u8BBF\u95EE"},{label:`\u25CF \u7F51\u7EDC\u6A21\u5F0F: ${t.networkMode.toUpperCase()}`,value:"network",description:"LAN \u6216 VPS \u4E2D\u8F6C"},{label:`\u25CF \u7AEF\u53E3: ${t.port}`,value:"port",description:"\u672C\u5730\u670D\u52A1\u76D1\u542C\u7AEF\u53E3"},{label:"\u25CF \u663E\u793A\u4E8C\u7EF4\u7801",value:"qr",description:"\u624B\u673A\u626B\u7801\u5FEB\u901F\u914D\u5BF9"},{label:"\u25CF \u663E\u793A\u914D\u5BF9\u4FE1\u606F",value:"pair",description:"\u67E5\u770B\u8FDE\u63A5\u5730\u5740\u4E0E Token"},{label:"\u25CF \u91CD\u65B0\u751F\u6210 Token",value:"token",description:"\u66F4\u65B0\u914D\u5BF9 Token"},{label:"\u25CF \u8FD4\u56DE",value:"back"}],"toggle","\u6309 \u2191\u2193 \u9009\u62E9\uFF0CEnter \u786E\u8BA4\uFF0CESC \u53D6\u6D88");}catch(s){s?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",s?.message);return}if(n!=="back"){if(n==="on"||n==="off"||n==="toggle"){let s=n==="on"?true:n==="off"?false:!t.enabled;if(hg(r,{enabled:s}),s){await r.startRemote();let o=r.getStatus(),i=[`\u6A21\u5F0F: ${o.networkMode.toUpperCase()}`,`\u5730\u5740: ${o.host}:${o.port}`,`Token: ${o.token||"(\u672A\u751F\u6210)"}`];if(o.urls.length>0){i.push("LAN \u5730\u5740:");for(let a of o.urls)i.push(`- ${a}`);}r.logInfo("\u8FDC\u7A0B\u8BBF\u95EE\u5DF2\u5F00\u542F",i.join(`
3568
3567
  `));}else await r.stopRemote(),r.logInfo("\u8FDC\u7A0B\u8BBF\u95EE\u5DF2\u5173\u95ED","\u5DF2\u65AD\u5F00\u8FDC\u7A0B\u8FDE\u63A5");return}if(n==="network"){let s;try{s=await r.promptSelect("\u9009\u62E9\u7F51\u7EDC\u6A21\u5F0F",[{label:"LAN (\u5C40\u57DF\u7F51)",value:"lan",description:"\u540C\u4E00\u5185\u7F51\u8FDE\u63A5"},{label:"VPS (\u516C\u7F51\u4E2D\u8F6C)",value:"vps",description:"\u9700\u8981 VPS \u4E2D\u8F6C"}],t.networkMode);}catch(i){i?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",i?.message);return}let o=nx(s);hg(r,{networkMode:o}),o==="vps"?r.logInfo("\u5DF2\u5207\u6362\u5230 VPS \u6A21\u5F0F","VPS \u4E2D\u8F6C\u914D\u7F6E\u5C06\u5728\u540E\u7EED\u5B9E\u73B0"):r.logInfo("\u5DF2\u5207\u6362\u5230 LAN \u6A21\u5F0F","\u53EF\u76F4\u63A5\u4F7F\u7528\u5C40\u57DF\u7F51\u8FDE\u63A5"),await r.startRemote();return}if(n==="port"){let s="";try{s=await r.promptText("\u8F93\u5165\u76D1\u542C\u7AEF\u53E3",{defaultValue:String(t.port||tx),allowEmpty:!1});}catch(i){i?.message!=="cancelled"&&r.logInfo("\u64CD\u4F5C\u53D6\u6D88",i?.message);return}let o=parseInt(s,10);if(!Number.isFinite(o)||o<1||o>65535){r.logInfo("\u65E0\u6548\u7AEF\u53E3","\u8BF7\u8F93\u5165 1-65535 \u4E4B\u95F4\u7684\u7AEF\u53E3");return}hg(r,{port:o}),await r.startRemote(),r.logInfo("\u7AEF\u53E3\u5DF2\u66F4\u65B0",`\u5F53\u524D\u7AEF\u53E3: ${o}`);return}if(n==="token"){let s=r.regenerateToken();r.logInfo("Token \u5DF2\u66F4\u65B0",`\u65B0\u7684 Token: ${s}`),await r.startRemote();return}if(n==="pair"||n==="status"){let s=r.getStatus();s.token||(r.regenerateToken(),s=r.getStatus());let o=[`\u72B6\u6001: ${s.enabled?"\u5F00\u542F":"\u5173\u95ED"} / ${s.running?"\u8FD0\u884C\u4E2D":"\u672A\u8FD0\u884C"}`,`\u6A21\u5F0F: ${s.networkMode.toUpperCase()}`,`\u5730\u5740: ${s.host}:${s.port}`,`Token: ${s.token||"(\u672A\u751F\u6210)"}`];if(s.urls.length>0){o.push("LAN \u5730\u5740:");for(let i of s.urls)o.push(`- ${i}`);}r.logInfo("\u8FDC\u7A0B\u914D\u5BF9\u4FE1\u606F",o.join(`
3569
3568
  `));return}if(n==="qr"){let s=r.getStatus();s.token||(r.regenerateToken(),s=r.getStatus());let o=bR(s);r.clearOutputLines&&r.clearOutputLines();let i=await yR(o.payload),a=await fR(o.payload),l=[`LAN \u5730\u5740: ${o.lanUrl}`,`Token: ${s.token||"(\u672A\u751F\u6210)"}`,`\u534F\u8BAE: ${o.payload}`];i.filePath?(l.push(`\u4E8C\u7EF4\u7801\u56FE\u7247: ${i.filePath}`),l.push("(\u5DF2\u5728\u65B0\u7A97\u53E3\u6253\u5F00\uFF0C\u8BF7\u4F7F\u7528\u624B\u673A\u626B\u63CF)")):i.error&&l.push(`\u56FE\u7247\u751F\u6210\u5931\u8D25: ${i.error}`);let c=a.qr?l:[...l,a.error?`\u7EC8\u7AEF\u4E8C\u7EF4\u7801\u751F\u6210\u5931\u8D25: ${a.error}`:"\u7EC8\u7AEF\u4E8C\u7EF4\u7801\u751F\u6210\u5931\u8D25: \u672A\u77E5\u9519\u8BEF"];if(a.qr){let u=a.qr.split(`