hwjcode-personal 1.1.133 → 1.1.134

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/bundle/hwjcode.js CHANGED
@@ -2190,7 +2190,7 @@ ${e.format(r)}`.trim())}};Epr.exports=iit});var oit=Le((wzi,Vpr)=>{"use strict";
2190
2190
  ${o}`;break;case"retry":pGr(o)&&(r[i]=o);break;case"id":bGr(o)&&(r[i]=o);break;case"event":o.length>0&&(r[i]=o);break}}processEvent(e){e.retry&&pGr(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&bGr(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||"message",options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event={data:void 0,event:void 0,id:void 0,retry:void 0}}};fGr.exports={EventSourceStream:Fst}});var wGr=Le((v_i,FGr)=>{"use strict";var{pipeline:sIa}=Yt("node:stream"),{fetching:oIa}=cse(),{makeRequest:lIa}=a7(),{webidl:G2}=Fp(),{EventSourceStream:cIa}=GGr(),{parseMIMEType:uIa}=pZ(),{createFastMessageEvent:dIa}=oFe(),{isNetworkError:gGr}=sse(),{kEnumerableProperty:pL}=hs(),{environmentSettingsObject:vGr}=$1(),yGr=!1,ZGr=3e3,bse=0,WGr=1,fse=2,IIa="anonymous",hIa="use-credentials",m7=class n extends EventTarget{#e={open:null,error:null,message:null};#t;#r=!1;#n=bse;#i=null;#a=null;#c;#o;constructor(e,r={}){super(),G2.util.markAsUncloneable(this);let a="EventSource constructor";G2.argumentLengthCheck(arguments,1,a),yGr||(yGr=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),e=G2.converters.USVString(e),r=G2.converters.EventSourceInitDict(r,a,"eventSourceInitDict"),this.#c=r.node.dispatcher||r.dispatcher,this.#o={lastEventId:"",reconnectionTime:r.node.reconnectionTime};let i=vGr,o;try{o=new URL(e,i.settingsObject.baseUrl),this.#o.origin=o.origin}catch(d){throw new DOMException(d,"SyntaxError")}this.#t=o.href;let t=IIa;r.withCredentials===!0&&(t=hIa,this.#r=!0);let s={redirect:"follow",keepalive:!0,mode:"cors",credentials:t==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};s.client=vGr.settingsObject,s.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],s.cache="no-store",s.initiator="other",s.urlList=[new URL(this.#t)],this.#i=lIa(s),this.#s()}get readyState(){return this.#n}get url(){return this.#t}get withCredentials(){return this.#r}#s(){if(this.#n===fse)return;this.#n=bse;let e={request:this.#i,dispatcher:this.#c},r=a=>{if(!gGr(a))return this.#I()};e.processResponseEndOfBody=r,e.processResponse=a=>{if(gGr(a))if(a.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#I();return}let i=a.headersList.get("content-type",!0),o=i!==null?uIa(i):"failure",t=o!=="failure"&&o.essence==="text/event-stream";if(a.status!==200||t===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#n=WGr,this.dispatchEvent(new Event("open")),this.#o.origin=a.urlList[a.urlList.length-1].origin;let s=new cIa({eventSourceSettings:this.#o,push:d=>{this.dispatchEvent(dIa(d.type,d.options))}});sIa(a.body.stream,s,d=>{d?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#a=oIa(e)}#I(){this.#n!==fse&&(this.#n=bse,this.dispatchEvent(new Event("error")),setTimeout(()=>{this.#n===bse&&(this.#o.lastEventId.length&&this.#i.headersList.set("last-event-id",this.#o.lastEventId,!0),this.#s())},this.#o.reconnectionTime)?.unref())}close(){G2.brandCheck(this,n),this.#n!==fse&&(this.#n=fse,this.#a.abort(),this.#i=null)}get onopen(){return this.#e.open}set onopen(e){this.#e.open&&this.removeEventListener("open",this.#e.open);let r=G2.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(e){this.#e.message&&this.removeEventListener("message",this.#e.message);let r=G2.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get onerror(){return this.#e.error}set onerror(e){this.#e.error&&this.removeEventListener("error",this.#e.error);let r=G2.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}},NGr={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:bse,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:WGr,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:fse,writable:!1}};Object.defineProperties(m7,NGr);Object.defineProperties(m7.prototype,NGr);Object.defineProperties(m7.prototype,{close:pL,onerror:pL,onmessage:pL,onopen:pL,readyState:pL,url:pL,withCredentials:pL});G2.converters.EventSourceInitDict=G2.dictionaryConverter([{key:"withCredentials",converter:G2.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:G2.converters.any},{key:"node",converter:G2.dictionaryConverter([{key:"reconnectionTime",converter:G2.converters["unsigned long"],defaultValue:()=>ZGr},{key:"dispatcher",converter:G2.converters.any}]),defaultValue:()=>({})}]);FGr.exports={EventSource:m7,defaultReconnectionTime:ZGr}});var yFe=Le((y_i,Fa)=>{"use strict";var mIa=xV(),AGr=pie(),pIa=MS(),bIa=I0r(),fIa=b0r(),GIa=_S(),gIa=cat(),vIa=iat(),yIa=tmr(),ZIa=lmr(),WIa=dmr(),EGr=_i(),vFe=hs(),{InvalidArgumentError:gFe}=EGr,p7=Umr(),NIa=QS(),FIa=_at(),{MockCallHistory:wIa,MockCallHistoryLog:RIa}=qat(),AIa=sit(),EIa=tit(),xIa=Mpr(),CIa=Cat(),YIa=pNe(),{getGlobalDispatcher:xGr,setGlobalDispatcher:VIa}=xNe(),QIa=KU(),HIa=mit();Object.assign(AGr.prototype,p7);Fa.exports.Dispatcher=AGr;Fa.exports.Client=mIa;Fa.exports.Pool=pIa;Fa.exports.BalancedPool=bIa;Fa.exports.RoundRobinPool=fIa;Fa.exports.Agent=GIa;Fa.exports.ProxyAgent=gIa;Fa.exports.Socks5ProxyAgent=vIa;Fa.exports.EnvHttpProxyAgent=yIa;Fa.exports.RetryAgent=ZIa;Fa.exports.H2CClient=WIa;Fa.exports.RetryHandler=YIa;Fa.exports.DecoratorHandler=QIa;Fa.exports.RedirectHandler=HIa;Fa.exports.interceptors={redirect:rbr(),responseError:abr(),retry:sbr(),dump:lbr(),dns:Ibr(),cache:Obr(),decompress:Pbr(),deduplicate:efr()};Fa.exports.cacheStores={MemoryCacheStore:Eit()};var XIa=nfr();Fa.exports.cacheStores.SqliteCacheStore=XIa;Fa.exports.buildConnector=NIa;Fa.exports.errors=EGr;Fa.exports.util={parseHeaders:vFe.parseHeaders,headerNameToString:vFe.headerNameToString};function Gse(n){return(e,r,a)=>{if(typeof r=="function"&&(a=r,r=null),!e||typeof e!="string"&&typeof e!="object"&&!(e instanceof URL))throw new gFe("invalid url");if(r!=null&&typeof r!="object")throw new gFe("invalid opts");if(r&&r.path!=null){if(typeof r.path!="string")throw new gFe("invalid opts.path");let t=r.path;r.path.startsWith("/")||(t=`/${t}`),e=new URL(vFe.parseOrigin(e).origin+t)}else r||(r=typeof e=="object"?e:{}),e=vFe.parseURL(e);let{agent:i,dispatcher:o=xGr()}=r;if(i)throw new gFe("unsupported opts.agent. Did you mean opts.client?");return n.call(o,{...r,origin:e.origin,path:e.search?`${e.pathname}${e.search}`:e.pathname,method:r.method||(r.body?"PUT":"GET")},a)}}Fa.exports.setGlobalDispatcher=VIa;Fa.exports.getGlobalDispatcher=xGr;var kIa=cse().fetch,RGr=typeof __filename<"u"?__filename:void 0;function CGr(n,e){if(!n||typeof n!="object")return;let r=typeof n.stack=="string"?n.stack:"",a=e.replace(/\\/g,"/");if(r&&(r.includes(e)||r.includes(a)))return;let i={};if(Error.captureStackTrace(i,CGr),!i.stack)return;let o=i.stack.split(`
2191
2191
  `).slice(1).join(`
2192
2192
  `);n.stack=r?`${r}
2193
- ${o}`:i.stack}Fa.exports.fetch=function(e,r=void 0){return kIa(e,r).catch(a=>{throw RGr?CGr(a,RGr):a&&typeof a=="object"&&Error.captureStackTrace(a,Fa.exports.fetch),a})};Fa.exports.Headers=oL().Headers;Fa.exports.Response=sse().Response;Fa.exports.Request=a7().Request;Fa.exports.FormData=TWe().FormData;var{setGlobalOrigin:SIa,getGlobalOrigin:LIa}=Ort();Fa.exports.setGlobalOrigin=SIa;Fa.exports.getGlobalOrigin=LIa;var{CacheStorage:JIa}=h2r(),{kConstruct:BIa}=Wc();Fa.exports.caches=new JIa(BIa);var{deleteCookie:TIa,getCookies:DIa,getSetCookies:OIa,setCookie:MIa,parseCookie:UIa}=F2r();Fa.exports.deleteCookie=TIa;Fa.exports.getCookies=DIa;Fa.exports.getSetCookies=OIa;Fa.exports.setCookie=MIa;Fa.exports.parseCookie=UIa;var{parseMIMEType:zIa,serializeAMimeType:_Ia}=pZ();Fa.exports.parseMIMEType=zIa;Fa.exports.serializeAMimeType=_Ia;var{CloseEvent:PIa,ErrorEvent:jIa,MessageEvent:qIa}=oFe(),{WebSocket:KIa,ping:$Ia}=aGr();Fa.exports.WebSocket=KIa;Fa.exports.CloseEvent=PIa;Fa.exports.ErrorEvent=jIa;Fa.exports.MessageEvent=qIa;Fa.exports.ping=$Ia;Fa.exports.WebSocketStream=IGr().WebSocketStream;Fa.exports.WebSocketError=vst().WebSocketError;Fa.exports.request=Gse(p7.request);Fa.exports.stream=Gse(p7.stream);Fa.exports.pipeline=Gse(p7.pipeline);Fa.exports.connect=Gse(p7.connect);Fa.exports.upgrade=Gse(p7.upgrade);Fa.exports.MockClient=FIa;Fa.exports.MockCallHistory=wIa;Fa.exports.MockCallHistoryLog=RIa;Fa.exports.MockPool=EIa;Fa.exports.MockAgent=AIa;Fa.exports.SnapshotAgent=xIa;Fa.exports.mockErrors=CIa;var{EventSource:eha}=wGr();Fa.exports.EventSource=eha;function tha(){globalThis.fetch=Fa.exports.fetch,globalThis.Headers=Fa.exports.Headers,globalThis.Response=Fa.exports.Response,globalThis.Request=Fa.exports.Request,globalThis.FormData=Fa.exports.FormData,globalThis.WebSocket=Fa.exports.WebSocket,globalThis.CloseEvent=Fa.exports.CloseEvent,globalThis.ErrorEvent=Fa.exports.ErrorEvent,globalThis.MessageEvent=Fa.exports.MessageEvent,globalThis.EventSource=Fa.exports.EventSource}Fa.exports.install=tha});function fF(n){let e=n??"1.1.133"??"unknown",r=process.platform,a=process.arch;if(e.startsWith("VSCode-")){let i=e.slice(7)||"unknown";return`${ZFe}/VSCode/${i} (${r}; ${a})`}if(e.startsWith("Desktop-")){let i=e.slice(8)||"unknown";return`${ZFe}/Desktop/${i} (${r}; ${a})`}return`${ZFe}/CLI/${e} (${r}; ${a})`}var ZFe,bL=De(()=>{"use strict";ZFe="HwjCode"});import*as lv from"node:path";import*as Ji from"node:fs";import*as YGr from"node:os";import*as VGr from"node:zlib";import{spawn as WFe,spawnSync as rha}from"node:child_process";function XGr(n){if(Ji.existsSync(n)){for(let e of Ji.readdirSync(n)){let r=lv.join(n,e);Ji.statSync(r).isDirectory()?XGr(r):Ji.unlinkSync(r)}Ji.rmdirSync(n)}}var QGr,HGr,GI,kGr=De(()=>{"use strict";QGr=Vt(yFe(),1),HGr=Vt(zje(),1);bL();nm();GI=class{static get lspDir(){return lv.join(YGr.homedir(),Ho,"lsp")}static findOnPath(e){let r=process.platform==="win32"?"where.exe":"which",i=(rha(r,[e],{shell:!1,encoding:"utf8",windowsHide:!0}).stdout||"").toString().trim();if(!i)return null;for(let o of i.split(/\r?\n/).map(t=>t.trim()).filter(Boolean))if(Ji.existsSync(o))return o;return null}static async cleanBinaryCache(e){let r=lv.join(this.lspDir,e);Ji.existsSync(r)&&(console.log(`[LSP] Cleaning corrupted binary cache for ${e} at ${r}`),XGr(r),console.log("[LSP] Cache cleaned successfully"))}static async ensureBinary(e,r,a){let i=a?.maxRetries??1,o=null;for(let t=0;t<=i;t++)try{let s=lv.join(this.lspDir,e);return Ji.existsSync(s)||Ji.mkdirSync(s,{recursive:!0}),await r(s)}catch(s){o=s,t<i&&(console.log(`[LSP] Attempt ${t+1} failed: ${o.message}`),console.log(`[LSP] Cleaning cache and retrying (${i-t} retries left)...`),await this.cleanBinaryCache(e))}throw o||new Error(`Failed to ensure binary for ${e}`)}static async npmInstaller(e,r){return async a=>{let i=lv.join(a,"node_modules",".bin",r+(process.platform==="win32"?".cmd":""));return Ji.existsSync(i)||(console.log(`[LSP] Installing ${e.join(", ")} via npm...`),Ji.existsSync(lv.join(a,"package.json"))||Ji.writeFileSync(lv.join(a,"package.json"),JSON.stringify({name:`deepv-lsp-${r}`,version:"1.0.0",private:!0})),await new Promise((o,t)=>{let s=process.platform==="win32",d=["install",...e,"--no-save"];(s?WFe("cmd.exe",["/c","npm",...d],{cwd:a,shell:!1,stdio:"inherit"}):WFe("npm",d,{cwd:a,shell:!1,stdio:"inherit"})).on("close",u=>{u===0?o():t(new Error(`npm install failed with code ${u}`))})})),i}}static async goInstaller(e,r,a="latest"){return async i=>{let o=process.platform,t=lv.join(i,r+(o==="win32"?".exe":""));if(Ji.existsSync(t))return t;let s=this.findOnPath("go");if(!s)throw new Error(`[LSP] Go toolchain not found in PATH (required to install ${r}). Please install Go from https://go.dev/dl/ and ensure "go" is available in your PATH, or configure a preinstalled gopls via PATH/DEEPV_GOPLS_PATH.`);if(console.log(`[LSP] Installing ${r} via go install (${e}@${a})...`),await new Promise((d,I)=>{let u=WFe(s,["install",`${e}@${a}`],{cwd:i,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,GOBIN:i}}),h="";u.stdout?.on("data",c=>{process.stdout.write(c)}),u.stderr?.on("data",c=>{let m=c.toString();h+=m,h.length>16384&&(h=h.slice(h.length-16384)),process.stderr.write(c)}),u.on("close",c=>{if(c===0)d();else{let m=h.trim();I(new Error(`[LSP] go install failed with code ${c}`+(m?`
2193
+ ${o}`:i.stack}Fa.exports.fetch=function(e,r=void 0){return kIa(e,r).catch(a=>{throw RGr?CGr(a,RGr):a&&typeof a=="object"&&Error.captureStackTrace(a,Fa.exports.fetch),a})};Fa.exports.Headers=oL().Headers;Fa.exports.Response=sse().Response;Fa.exports.Request=a7().Request;Fa.exports.FormData=TWe().FormData;var{setGlobalOrigin:SIa,getGlobalOrigin:LIa}=Ort();Fa.exports.setGlobalOrigin=SIa;Fa.exports.getGlobalOrigin=LIa;var{CacheStorage:JIa}=h2r(),{kConstruct:BIa}=Wc();Fa.exports.caches=new JIa(BIa);var{deleteCookie:TIa,getCookies:DIa,getSetCookies:OIa,setCookie:MIa,parseCookie:UIa}=F2r();Fa.exports.deleteCookie=TIa;Fa.exports.getCookies=DIa;Fa.exports.getSetCookies=OIa;Fa.exports.setCookie=MIa;Fa.exports.parseCookie=UIa;var{parseMIMEType:zIa,serializeAMimeType:_Ia}=pZ();Fa.exports.parseMIMEType=zIa;Fa.exports.serializeAMimeType=_Ia;var{CloseEvent:PIa,ErrorEvent:jIa,MessageEvent:qIa}=oFe(),{WebSocket:KIa,ping:$Ia}=aGr();Fa.exports.WebSocket=KIa;Fa.exports.CloseEvent=PIa;Fa.exports.ErrorEvent=jIa;Fa.exports.MessageEvent=qIa;Fa.exports.ping=$Ia;Fa.exports.WebSocketStream=IGr().WebSocketStream;Fa.exports.WebSocketError=vst().WebSocketError;Fa.exports.request=Gse(p7.request);Fa.exports.stream=Gse(p7.stream);Fa.exports.pipeline=Gse(p7.pipeline);Fa.exports.connect=Gse(p7.connect);Fa.exports.upgrade=Gse(p7.upgrade);Fa.exports.MockClient=FIa;Fa.exports.MockCallHistory=wIa;Fa.exports.MockCallHistoryLog=RIa;Fa.exports.MockPool=EIa;Fa.exports.MockAgent=AIa;Fa.exports.SnapshotAgent=xIa;Fa.exports.mockErrors=CIa;var{EventSource:eha}=wGr();Fa.exports.EventSource=eha;function tha(){globalThis.fetch=Fa.exports.fetch,globalThis.Headers=Fa.exports.Headers,globalThis.Response=Fa.exports.Response,globalThis.Request=Fa.exports.Request,globalThis.FormData=Fa.exports.FormData,globalThis.WebSocket=Fa.exports.WebSocket,globalThis.CloseEvent=Fa.exports.CloseEvent,globalThis.ErrorEvent=Fa.exports.ErrorEvent,globalThis.MessageEvent=Fa.exports.MessageEvent,globalThis.EventSource=Fa.exports.EventSource}Fa.exports.install=tha});function fF(n){let e=n??"1.1.134"??"unknown",r=process.platform,a=process.arch;if(e.startsWith("VSCode-")){let i=e.slice(7)||"unknown";return`${ZFe}/VSCode/${i} (${r}; ${a})`}if(e.startsWith("Desktop-")){let i=e.slice(8)||"unknown";return`${ZFe}/Desktop/${i} (${r}; ${a})`}return`${ZFe}/CLI/${e} (${r}; ${a})`}var ZFe,bL=De(()=>{"use strict";ZFe="HwjCode"});import*as lv from"node:path";import*as Ji from"node:fs";import*as YGr from"node:os";import*as VGr from"node:zlib";import{spawn as WFe,spawnSync as rha}from"node:child_process";function XGr(n){if(Ji.existsSync(n)){for(let e of Ji.readdirSync(n)){let r=lv.join(n,e);Ji.statSync(r).isDirectory()?XGr(r):Ji.unlinkSync(r)}Ji.rmdirSync(n)}}var QGr,HGr,GI,kGr=De(()=>{"use strict";QGr=Vt(yFe(),1),HGr=Vt(zje(),1);bL();nm();GI=class{static get lspDir(){return lv.join(YGr.homedir(),Ho,"lsp")}static findOnPath(e){let r=process.platform==="win32"?"where.exe":"which",i=(rha(r,[e],{shell:!1,encoding:"utf8",windowsHide:!0}).stdout||"").toString().trim();if(!i)return null;for(let o of i.split(/\r?\n/).map(t=>t.trim()).filter(Boolean))if(Ji.existsSync(o))return o;return null}static async cleanBinaryCache(e){let r=lv.join(this.lspDir,e);Ji.existsSync(r)&&(console.log(`[LSP] Cleaning corrupted binary cache for ${e} at ${r}`),XGr(r),console.log("[LSP] Cache cleaned successfully"))}static async ensureBinary(e,r,a){let i=a?.maxRetries??1,o=null;for(let t=0;t<=i;t++)try{let s=lv.join(this.lspDir,e);return Ji.existsSync(s)||Ji.mkdirSync(s,{recursive:!0}),await r(s)}catch(s){o=s,t<i&&(console.log(`[LSP] Attempt ${t+1} failed: ${o.message}`),console.log(`[LSP] Cleaning cache and retrying (${i-t} retries left)...`),await this.cleanBinaryCache(e))}throw o||new Error(`Failed to ensure binary for ${e}`)}static async npmInstaller(e,r){return async a=>{let i=lv.join(a,"node_modules",".bin",r+(process.platform==="win32"?".cmd":""));return Ji.existsSync(i)||(console.log(`[LSP] Installing ${e.join(", ")} via npm...`),Ji.existsSync(lv.join(a,"package.json"))||Ji.writeFileSync(lv.join(a,"package.json"),JSON.stringify({name:`deepv-lsp-${r}`,version:"1.0.0",private:!0})),await new Promise((o,t)=>{let s=process.platform==="win32",d=["install",...e,"--no-save"];(s?WFe("cmd.exe",["/c","npm",...d],{cwd:a,shell:!1,stdio:"inherit"}):WFe("npm",d,{cwd:a,shell:!1,stdio:"inherit"})).on("close",u=>{u===0?o():t(new Error(`npm install failed with code ${u}`))})})),i}}static async goInstaller(e,r,a="latest"){return async i=>{let o=process.platform,t=lv.join(i,r+(o==="win32"?".exe":""));if(Ji.existsSync(t))return t;let s=this.findOnPath("go");if(!s)throw new Error(`[LSP] Go toolchain not found in PATH (required to install ${r}). Please install Go from https://go.dev/dl/ and ensure "go" is available in your PATH, or configure a preinstalled gopls via PATH/DEEPV_GOPLS_PATH.`);if(console.log(`[LSP] Installing ${r} via go install (${e}@${a})...`),await new Promise((d,I)=>{let u=WFe(s,["install",`${e}@${a}`],{cwd:i,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:{...process.env,GOBIN:i}}),h="";u.stdout?.on("data",c=>{process.stdout.write(c)}),u.stderr?.on("data",c=>{let m=c.toString();h+=m,h.length>16384&&(h=h.slice(h.length-16384)),process.stderr.write(c)}),u.on("close",c=>{if(c===0)d();else{let m=h.trim();I(new Error(`[LSP] go install failed with code ${c}`+(m?`
2194
2194
  ${m}`:"")))}}),u.on("error",c=>{I(new Error(`[LSP] Failed to spawn go (${s}): ${c.message}. Please ensure Go is installed and available in PATH.`))})}),!Ji.existsSync(t))throw new Error(`[LSP] ${r} installation completed but binary not found at ${t}. This usually means Go did not honor GOBIN or the install failed silently.`);return t}}static async githubInstaller(e,r,a){return async i=>{let o=process.platform,t=process.arch,s=a(o,t),d=r+(o==="win32"?".exe":""),I=lv.join(i,d);if(Ji.existsSync(I))return I;console.log(`[LSP] Downloading ${r} from GitHub ${e}/${r}...`);let u=process.env.GITHUB_TOKEN||process.env.GITHUB_PAT,h={"User-Agent":fF()};u&&(h.Authorization=`Bearer ${u}`);let c=`https://api.github.com/repos/${e}/${r}/releases/latest`,y=await(await(0,QGr.request)(c,{headers:h})).body.json(),g=y.assets.find(R=>typeof s=="string"?R.name===s:s.test(R.name));if(!g){let R=`${o}-${t}`,b=[];r==="rust-analyzer"&&(R==="win32-x64"?b.push(/rust-analyzer.*x86_64.*windows.*\.zip/i,/rust-analyzer.*x64.*windows.*\.zip/i,/rust-analyzer.*msvc.*\.zip/i):R==="win32-arm64"?b.push(/rust-analyzer.*aarch64.*windows.*\.zip/i):R==="darwin-x64"?b.push(/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,/rust-analyzer.*x86_64.*macos.*\.gz/i):R==="darwin-arm64"?b.push(/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,/rust-analyzer.*aarch64.*macos.*\.gz/i):R==="linux-x64"?b.push(/rust-analyzer.*x86_64.*linux.*\.gz/i,/rust-analyzer.*x86_64.*gnu.*\.gz/i):R==="linux-arm64"&&b.push(/rust-analyzer.*aarch64.*linux.*\.gz/i,/rust-analyzer.*aarch64.*gnu.*\.gz/i)),b.length>0&&(g=y.assets.find(W=>b.some(N=>N.test(W.name))))}if(!g){let R=y.assets.map(b=>b.name).join(", ");throw new Error(`Could not find a suitable binary for ${o}-${t} in ${e}/${r} releases. Available: ${R}`)}console.log(`[LSP] Downloading: ${g.name}`),console.log(`[LSP] File size: ${(g.size/1024/1024).toFixed(1)}MB`);let Z=lv.join(i,g.name),v=Date.now(),E=0;if(await new Promise((R,b)=>{let W=process.platform==="win32"?"curl.exe":"curl",N=WFe(W,["-L","--fail","-o",Z,g.browser_download_url]),A="",p=setInterval(()=>{if(Ji.existsSync(Z)){let f=Ji.statSync(Z).size,G=(f/(g.size||1)*100).toFixed(1),F=(f/1024/1024).toFixed(1),C=(g.size/1024/1024).toFixed(1);console.log(`[LSP] \u2B07\uFE0F ${g.name}: ${F}MB / ${C}MB (${G}%)`),E=f,v=Date.now()}},2e3);N.stderr.on("data",f=>{A+=f.toString()}),N.on("close",f=>{clearInterval(p),f===0?R():(Ji.existsSync(Z)&&Ji.unlinkSync(Z),b(new Error(`[LSP] curl failed with code ${f}: ${A}`)))}),N.on("error",f=>{clearInterval(p),Ji.existsSync(Z)&&Ji.unlinkSync(Z),b(new Error(`[LSP] Failed to spawn curl: ${f.message}. curl may not be installed or available in PATH. Please install curl and add it to your system PATH.`))})}),!Ji.existsSync(Z))throw new Error(`[LSP] Downloaded file not found at ${Z}. curl may have failed silently.`);let w=Ji.statSync(Z).size;if(w===0)throw Ji.unlinkSync(Z),new Error(`[LSP] Downloaded file is empty (0 bytes) for ${g.name}. The download URL may be invalid or temporarily unavailable. Please retry.`);if(console.log(`[LSP] Downloaded ${w} bytes (expected: ${g.size} bytes)`),g.name.endsWith(".gz")){console.log(`[LSP] Decompressing ${g.name}...`);let R=Ji.readFileSync(Z);try{let b=VGr.gunzipSync(R);if(b.length===0)throw new Error("Decompressed data is empty");Ji.writeFileSync(I,b)}catch(b){Ji.unlinkSync(Z);let W=b instanceof Error?b.message:String(b);throw new Error(`[LSP] Failed to decompress ${g.name}: ${W}. The file may be corrupted. Please retry.`)}Ji.unlinkSync(Z)}else if(g.name.endsWith(".zip")){console.log(`[LSP] Extracting ${g.name}...`);let R=Ji.readFileSync(Z);if(R.length<4)throw Ji.unlinkSync(Z),new Error(`[LSP] ZIP file is too small (${R.length} bytes) for ${g.name}. The download is corrupted. Please retry or check your network connection.`);if(R[0]!==80||R[1]!==75||R[2]!==3||R[3]!==4)throw Ji.unlinkSync(Z),new Error(`[LSP] ZIP file header is corrupted for ${g.name}. The download may have been interrupted. Please retry.`);let b;try{b=await HGr.default.loadAsync(R)}catch(f){Ji.unlinkSync(Z);let G=f instanceof Error?f.message:String(f);throw new Error(`[LSP] Failed to parse ZIP file ${g.name}: ${G}. The file may be corrupted. Please retry the download.`)}let W=d.toLowerCase(),A=Object.values(b.files).filter(f=>!f.dir).filter(f=>lv.posix.basename(f.name).toLowerCase()===W).sort((f,G)=>f.name.length-G.name.length)[0];if(!A)throw new Error(`Zip archive did not contain expected executable "${d}" for ${e}/${r}.`);let p=await A.async("nodebuffer");Ji.writeFileSync(I,p),Ji.unlinkSync(Z)}else Ji.renameSync(Z,I);if(o!=="win32"&&Ji.chmodSync(I,493),console.log(`[LSP] Binary installed at: ${I}`),console.log(`[LSP] Binary exists: ${Ji.existsSync(I)}`),Ji.existsSync(I)){let R=Ji.statSync(I);console.log(`[LSP] Binary stats: size=${R.size}, mode=${(R.mode&parseInt("777",8)).toString(8)}`)}return I}}}});import*as N0 from"node:path";import*as NZ from"node:fs";import{spawn as OV}from"node:child_process";function b7(n,e,r){let i=process.platform==="win32"&&n.toLowerCase().endsWith(".cmd"),o={cwd:r.cwd,shell:!1,stdio:["pipe","pipe","pipe"]};if(i&&NZ.existsSync(n)){let s=NZ.readFileSync(n,"utf8").match(/%dp0%([^"]*\.m?js)/i);if(s){let d=N0.dirname(n),I=s[1].replace(/\\/g,N0.sep);I.startsWith(N0.sep)&&(I="."+I);let u=N0.resolve(d,I);if(NZ.existsSync(u))return OV(process.execPath,[u,...e],o)}return OV("cmd.exe",["/c",n,...e],o)}return OV(n,e,o)}var gse,nha,aha,iha,sha,oha,lha,cha,uha,dha,SGr,LGr=De(()=>{"use strict";kGr();gse=(n,e)=>async r=>{let a=N0.normalize(N0.dirname(N0.resolve(r))),i=N0.normalize(N0.resolve(e)),o=(t,s)=>{let d=t.toLowerCase(),I=s.toLowerCase();return d.startsWith(I)||d===I};for(;o(a,i);){for(let s of n)if(NZ.existsSync(N0.join(a,s)))return a;let t=N0.normalize(N0.dirname(a));if(t===a)break;a=t}return i},nha=n=>({id:"typescript-language-server",displayName:"TypeScript/JavaScript Language Server",extensions:[".ts",".tsx",".js",".jsx"],root:gse(["package.json","tsconfig.json","jsconfig.json"],n),async spawn(e){let r=await GI.ensureBinary("typescript-language-server",await GI.npmInstaller(["typescript-language-server","typescript"],"typescript-language-server")),a=N0.join(N0.dirname(r),"..","..","typescript","lib","tsserver.js"),i=["--stdio"];return NZ.existsSync(a)&&i.push("--tsserver-path",a),{process:b7(r,i,{cwd:e})}}}),aha=n=>({id:"pyright",displayName:"Python Language Server",extensions:[".py"],root:gse(["pyproject.toml","setup.py","requirements.txt","package.json"],n),async spawn(e){let r=await GI.ensureBinary("pyright",await GI.npmInstaller(["pyright"],"pyright-langserver"));return{process:b7(r,["--stdio"],{cwd:e})}}}),iha=n=>({id:"rust-analyzer",displayName:"Rust Language Server",extensions:[".rs"],root:gse(["Cargo.toml"],n),async spawn(e){let r=process.platform,a=process.arch;console.log(`[LSP] Detecting platform for rust-analyzer: platform=${r}, arch=${a}`);let i=await GI.githubInstaller("rust-lang","rust-analyzer",(s,d)=>{let I={"win32-x64":/rust-analyzer.*x86_64.*windows.*\.zip/i,"win32-arm64":/rust-analyzer.*aarch64.*windows.*\.zip/i,"darwin-x64":/rust-analyzer.*x86_64.*apple-darwin.*\.gz/i,"darwin-arm64":/rust-analyzer.*aarch64.*apple-darwin.*\.gz/i,"linux-x64":/rust-analyzer.*x86_64.*linux.*\.gz/i,"linux-arm64":/rust-analyzer.*aarch64.*linux.*\.gz/i},u=`${s}-${d}`,h=I[u]||/rust-analyzer-.*/;return console.log(`[LSP] Asset matcher for ${u}: ${h instanceof RegExp?h.source:h}`),h}),o=await GI.ensureBinary("rust-analyzer",i,{maxRetries:1});if(console.log(`[LSP] RustAnalyzer binary path: ${o}`),console.log(`[LSP] RustAnalyzer binary exists: ${NZ.existsSync(o)}`),NZ.existsSync(o)){let s=NZ.statSync(o);console.log(`[LSP] RustAnalyzer binary stats: size=${s.size}, isFile=${s.isFile()}, mode=${(s.mode&parseInt("777",8)).toString(8)}`)}console.log(`[LSP] RustAnalyzer spawning with cwd=${e}, args=[], shell=undefined`);let t=OV(o,[],{cwd:e});return console.log(`[LSP] RustAnalyzer spawn returned: pid=${t.pid}`),t.on("error",s=>{console.error("[LSP] RustAnalyzer process error:",{code:s.code,errno:s.errno,syscall:s.syscall,path:s.path,message:s.message})}),t.on("exit",(s,d)=>{console.log(`[LSP] RustAnalyzer process exited: code=${s}, signal=${d}`)}),{process:t}}}),sha=n=>({id:"gopls",displayName:"Go Language Server",extensions:[".go"],root:gse(["go.mod","go.sum"],n),async spawn(e){let r=process.env.DEEPV_GOPLS_PATH;if(r&&NZ.existsSync(r))return{process:OV(r,[],{cwd:e})};let a=GI.findOnPath("gopls");if(a)return{process:OV(a,[],{cwd:e})};let i=await GI.ensureBinary("gopls",await GI.goInstaller("golang.org/x/tools/gopls","gopls"),{maxRetries:1});return{process:OV(i,[],{cwd:e})}}}),oha=n=>({id:"clangd",displayName:"C/C++ Language Server",extensions:[".c",".cpp",".h",".hpp",".cc"],root:gse(["compile_commands.json","CMakeLists.txt",".git"],n),async spawn(e){let r=await GI.githubInstaller("clangd","clangd",(i,o)=>{let t=i==="win32"?"windows":i==="darwin"?"mac":"linux";return new RegExp(`clangd-${t}-.*\\.zip`)}),a=await GI.ensureBinary("clangd",r,{maxRetries:1});return{process:OV(a,[],{cwd:e})}}}),lha=n=>({id:"vscode-langservers-extracted",displayName:"HTML/CSS/JSON/ESLint Language Server",extensions:[".html",".css",".json",".jsonc"],root:async()=>n,async spawn(e){let r=await GI.ensureBinary("vscode-langservers-extracted",await GI.npmInstaller(["vscode-langservers-extracted"],"vscode-html-language-server"));return{process:b7(r,["--stdio"],{cwd:e})}}}),cha=n=>({id:"sql-language-server",displayName:"SQL Language Server",extensions:[".sql"],root:async()=>n,async spawn(e){let r=await GI.ensureBinary("sql-language-server",await GI.npmInstaller(["sql-language-server"],"sql-language-server"));return{process:b7(r,["up","--method","stdio"],{cwd:e})}}}),uha=n=>({id:"dockerfile-language-server-nodejs",displayName:"Dockerfile Language Server",extensions:["Dockerfile",".dockerfile"],root:async()=>n,async spawn(e){let r=await GI.ensureBinary("dockerfile-language-server-nodejs",await GI.npmInstaller(["dockerfile-language-server-nodejs"],"docker-langserver"));return{process:b7(r,["--stdio"],{cwd:e})}}}),dha=n=>({id:"yaml-language-server",displayName:"YAML Language Server",extensions:[".yaml",".yml"],root:async()=>n,async spawn(e){let r=await GI.ensureBinary("yaml-language-server",await GI.npmInstaller(["yaml-language-server"],"yaml-language-server"));return{process:b7(r,["--stdio"],{cwd:e})}}}),SGr=n=>[nha(n),aha(n),iha(n),sha(n),oha(n),lha(n),cha(n),uha(n),dha(n)]});import*as cx from"node:path";import*as FFe from"node:fs";import{pathToFileURL as Iha}from"node:url";var NFe,JGr=De(()=>{"use strict";Mur();LGr();NFe=class{clients=new Map;servers;projectRoot;openedFiles=new Set;fileVersions=new Map;fileContents=new Map;freshClients=new Set;constructor(e){this.projectRoot=e,this.servers=SGr(e)}async getClientsForFile(e){let r=cx.extname(e).toLowerCase(),a=this.servers.filter(o=>o.extensions.includes(r)),i=[];for(let o of a){let t=await o.root(e),s=`${o.id}:${t}`;if(this.clients.has(s))i.push(this.clients.get(s));else try{console.log(`[LSP] Starting ${o.id} for root ${t}`);let{process:d}=await o.spawn(t);console.log(`[LSP] Process spawned: pid=${d.pid}, stdio=${JSON.stringify(d.stdio)}`);let I=await Dur({serverID:o.id,server:{process:d},root:t});this.clients.set(s,I),this.freshClients.add(I.serverID),i.push(I)}catch(d){let I=d instanceof Error?{message:d.message,stack:d.stack,code:d.code,errno:d.errno,syscall:d.syscall,path:d.path}:String(d);console.error(`[LSP] Failed to start ${o.id}:`,I);let u=d;(u.errno===-4094||u.code==="UNKNOWN")&&console.error(`[LSP] Binary file may be corrupted (errno=${u.errno}). Suggest deleting ${o.id} cache and reinitializing.`)}}return i}async syncDocument(e,r){let a=this.getUri(r),i=`${e.serverID}:${a}`,o=FFe.readFileSync(r,"utf8");if(!this.openedFiles.has(i))this.fileVersions.set(i,1),this.fileContents.set(i,o),await e.connection.sendNotification("textDocument/didOpen",{textDocument:{uri:a,languageId:this.getLanguageId(r),version:1,text:o}}),this.openedFiles.add(i),await new Promise(t=>setTimeout(t,3e3));else{if(this.fileContents.get(i)===o)return;let s=(this.fileVersions.get(i)||1)+1;this.fileVersions.set(i,s),this.fileContents.set(i,o),await e.connection.sendNotification("textDocument/didChange",{textDocument:{uri:a,version:s},contentChanges:[{text:o}]})}}getLanguageId(e){switch(cx.extname(e).toLowerCase()){case".ts":case".tsx":return"typescript";case".js":case".jsx":return"javascript";case".go":return"go";case".py":return"python";case".rs":return"rust";default:return"plaintext"}}getUri(e){return Iha(cx.resolve(e)).href.replace(/^file:\/\/\/([A-Z])[:%3A]+\//i,(a,i)=>`file:///${i.toLowerCase()}%3A/`)}async shutdown(){for(let e of this.clients.values())await Our(e);this.clients.clear(),this.openedFiles.clear()}async run(e,r,a){let i=process.env.DEEPV_LSP_DEBUG==="1"||process.env.DEEPV_LSP_DEBUG==="true",o=Number(process.env.DEEPV_LSP_REQUEST_TIMEOUT_MS),t=a?.timeoutMs??(Number.isFinite(o)&&o>0?o:15e3),s=a?.operationName??"request",d=cx.normalize(e),I=await this.getClientsForFile(d),u=await Promise.all(I.map(async c=>{await this.syncDocument(c,d),this.freshClients.has(c.serverID)&&this.freshClients.delete(c.serverID);try{return await Promise.race([r(c),new Promise((y,g)=>{let Z=setTimeout(()=>{clearTimeout(Z),g(new Error(`[LSP][${c.serverID}] ${s} timed out after ${t}ms`))},t)})])}catch(m){if(i)console.error(`[LSP][${c.serverID}] Request failed:`,m);else{let y=m instanceof Error?m.message:String(m);y.includes("timed out after")?console.warn(y):console.error(`[LSP][${c.serverID}] Request failed:`,y)}return null}})),h=[];for(let c of u)c!==null&&h.push(c);return h}async getHover(e,r,a){return this.run(e,i=>i.connection.sendRequest("textDocument/hover",{textDocument:{uri:this.getUri(e)},position:{line:r,character:a}}),{operationName:"textDocument/hover"})}async getDefinition(e,r,a){return this.run(e,i=>i.connection.sendRequest("textDocument/definition",{textDocument:{uri:this.getUri(e)},position:{line:r,character:a}}),{operationName:"textDocument/definition"})}async getReferences(e,r,a){return this.run(e,async i=>{let o={textDocument:{uri:this.getUri(e)},position:{line:r,character:a},context:{includeDeclaration:!0}},t=await i.connection.sendRequest("textDocument/references",o);return(!t||t.length===0)&&(console.log(`[LSP][${i.serverID}] No references found, retrying in 3s...`),await new Promise(s=>setTimeout(s,3e3)),t=await i.connection.sendRequest("textDocument/references",o)),t},{operationName:"textDocument/references"})}async getImplementation(e,r,a){return this.run(e,async i=>{let o={textDocument:{uri:this.getUri(e)},position:{line:r,character:a}},t=await i.connection.sendRequest("textDocument/implementation",o);return(!t||t.length===0)&&(console.log(`[LSP][${i.serverID}] No implementation found, retrying in 3s...`),await new Promise(s=>setTimeout(s,3e3)),t=await i.connection.sendRequest("textDocument/implementation",o)),t},{operationName:"textDocument/implementation"})}async getDocumentSymbols(e){return this.run(e,r=>r.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:this.getUri(e)}}),{operationName:"textDocument/documentSymbol"})}async getWorkspaceSymbols(e){if(this.clients.size===0){console.log("[LSP] No active clients for workspace symbols, probing project...");let a=FFe.readdirSync(this.projectRoot,{recursive:!0}),i=[{ext:".ts",id:"typescript-language-server"},{ext:".py",id:"pyright"},{ext:".go",id:"gopls"},{ext:".rs",id:"rust-analyzer"},{ext:".js",id:"typescript-language-server"}];for(let o of i){let t=a.find(s=>s.endsWith(o.ext)&&!s.includes("node_modules")&&!s.includes("dist"));if(t){console.log(`[LSP] Detected ${o.ext} project, activating ${o.id}...`);let s=cx.join(this.projectRoot,t),d=await this.getClientsForFile(s);for(let I of d)await this.syncDocument(I,s);console.log(`[LSP] Waiting 5s for ${o.id} indexing...`),await new Promise(I=>setTimeout(I,5e3));break}}}let r=[];console.log(`[LSP] Searching workspace symbols for "${e}" across ${this.clients.size} clients...`);for(let a of this.clients.values())try{let i=await a.connection.sendRequest("workspace/symbol",{query:e});(!i||i.length===0)&&(console.log(`[LSP][${a.serverID}] No symbols yet, retrying in 3s...`),await new Promise(o=>setTimeout(o,3e3)),i=await a.connection.sendRequest("workspace/symbol",{query:e})),console.log(`[LSP][${a.serverID}] Found ${i?.length||0} symbols`),i&&r.push(i)}catch(i){console.error(`[LSP][${a.serverID}] Workspace symbols failed:`,i)}return r}async getDiagnostics(e){return[]}}});function BGr(n){return wst||(wst=new NFe(n)),wst}var wst,TGr=De(()=>{"use strict";JGr();wst=null});import*as f7 from"node:path";import{fileURLToPath as hha}from"node:url";var Db,Rst=De(()=>{"use strict";Es();TGr();gi();pc();Db=class n extends Jn{config;static Name="lsp";constructor(e){super(n.Name,"LSP Tool","Perform Language Server Protocol operations like Go to Definition, Find References, Hover, etc. Useful for code navigation and understanding.",yn.LightBulb,{properties:{operation:{type:Pt.STRING,enum:["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation"],description:"The LSP operation to perform."},filePath:{type:Pt.STRING,description:"The absolute path to the file. Required for file-specific operations."},line:{type:Pt.NUMBER,description:"The 1-based line number. Required for position-specific operations."},character:{type:Pt.NUMBER,description:"The 1-based character offset. Required for position-specific operations."},query:{type:Pt.STRING,description:"Search query. Required for workspaceSymbol."}},required:["operation"],type:Pt.OBJECT}),this.config=e}validateToolParams(e){let r=ai.validate(this.schema.parameters,e,n.Name);return r||(e.operation!=="workspaceSymbol"&&(!e.filePath||!f7.isAbsolute(e.filePath))?"filePath must be an absolute path for this operation.":["goToDefinition","findReferences","hover","goToImplementation"].includes(e.operation)&&(!e.line||!e.character||e.line<1||e.character<1)?"line and character must be 1-based (>= 1) for this operation.":e.operation==="workspaceSymbol"&&!e.query?"query is required for workspaceSymbol.":null)}async execute(e){let r=BGr(this.config.getTargetDir()),a=null,i=e.filePath?f7.resolve(e.filePath):void 0;try{switch(e.operation){case"goToDefinition":a=await r.getDefinition(i,e.line-1,e.character-1);break;case"findReferences":a=await r.getReferences(i,e.line-1,e.character-1);break;case"hover":a=await r.getHover(i,e.line-1,e.character-1);break;case"documentSymbol":a=await r.getDocumentSymbols(i);break;case"workspaceSymbol":a=await r.getWorkspaceSymbols(e.query||"");break;case"goToImplementation":a=await r.getImplementation(i,e.line-1,e.character-1);break;default:throw new Error(`Unknown operation: ${e.operation}`)}let o=a;Array.isArray(a)&&(e.operation==="hover"?o=a.find(d=>d&&d.contents)||null:e.operation==="goToDefinition"?(o=a.flat().filter(Boolean),o.length===0?o=null:o.length===1&&(o=o[0])):(o=a.flat().filter(Boolean),o.length===0&&Array.isArray(a)&&(o=[])));let t=this.formatLspResult(o,e.operation,this.config.getTargetDir());return{llmContent:`Operation ${e.operation} result:
2195
2195
  ${t}`,returnDisplay:t}}catch(o){let t=o instanceof Error?o.message:String(o);return{llmContent:`Error executing LSP operation ${e.operation}: ${t}`,returnDisplay:`Error: ${t}`}}}formatLspResult(e,r,a){if(!e)return"No result found.";let i=(o,t)=>{let s=o;o.startsWith("file://")&&(s=hha(o));let d=f7.relative(a,s),I=t.start.line+1,u=t.start.character+1,h=t.end.line+1,c=t.end.character+1;return I===h?`${d}:${I}:${u}-${c}`:`${d}:${I}:${u} - ${h}:${c}`};if(Array.isArray(e)){if(e.length===0)return"No results.";let o=e[0];return o.uri||o.targetUri?e.map(t=>{let s=t.uri||t.targetUri,d=t.range||t.targetSelectionRange;return`\u2022 ${i(s,d)}`}).join(`
2196
2196
  `):o.name&&o.kind!==void 0?e.map(t=>{let d={1:"File",2:"Module",3:"Namespace",4:"Package",5:"Class",6:"Method",7:"Property",8:"Field",9:"Constructor",10:"Enum",11:"Interface",12:"Function",13:"Variable",14:"Constant",15:"String"}[t.kind]||`Kind(${t.kind})`,I="";if(t.location)I=i(t.location.uri,t.location.range);else if(t.range){let u=t.range;I=`${u.start.line+1}:${u.start.character+1}`}return`\u2022 [${d}] ${t.name} (${I})`}).join(`
@@ -4044,11 +4044,11 @@ ${v}
4044
4044
 
4045
4045
  Dangerous commands cannot be auto-executed in YOLO mode. Please run this command in interactive mode for confirmation.`);console.error(`
4046
4046
  ${"=".repeat(80)}`),console.error("\u{1F6AB} DANGEROUS COMMAND EXECUTION PREVENTED"),console.error(`${"=".repeat(80)}`),console.error(`Rule: ${Z}`),console.error(`Warning: ${v}`),console.error(`${"=".repeat(80)}
4047
- `);let w=Date.now()-o;return console.warn(`[ToolCall] Blocked dangerous command: ${e.name}, duration: ${w}ms`),t(!1,E.message.length),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:E.message}}}],resultDisplay:E.message,error:E}}let u=await i.execute(e.args,d),h=u.llmContent,c=u.returnDisplay,m=Date.now()-o;console.debug(`[ToolCall] Success: ${e.name}, duration: ${m}ms`);let y=typeof h=="string"?h.length:JSON.stringify(h).length;t(!0,y);let g=Dk(e.name,e.callId,h);return{callId:e.callId,responseParts:g,resultDisplay:c,error:void 0}}catch(d){let I=d instanceof Error?d:new Error(String(d)),u=Date.now()-o;return console.warn(`[ToolCall] Failed: ${e.name}, error: ${I.message}, duration: ${u}ms`),t(!1,I.message.length),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:I.message}}}],resultDisplay:I.message,error:I}}}var vAr=De(()=>{"use strict";B2e();ete();BK();});import{randomUUID as FRa}from"crypto";function HF(){return mle||(mle=FRa()),mle}function yAr(n){mle=n}function ZAr(){mle=void 0}var mle,WAr,WIt=De(()=>{"use strict";WAr=HF()});import*as Tc from"fs";import*as XF from"path";import*as KL from"os";function wRa(n){kF.configure(n)}function RRa(n){kF.setUserInfo(n)}function ARa(n){kF.setCliVersion(n)}async function ERa(){return await kF.getUserHeaders()}function xRa(){return kF.getStatus()}var ple,Dc,kF,ble=De(()=>{"use strict";_lt();WIt();bL();nm();ple=259200,Dc=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){return fF(this.cliVersion)}formatTimeRemaining(e){if(e<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(e/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),o=Math.floor(r%3600/60),t=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${o}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${o}\u5206\u949F${t}\u79D2`:o>0?`${o}\u5206\u949F${t}\u79D2`:`${t}\u79D2`}formatAbsoluteTime(e){return new Date(e).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=XF.join(KL.homedir(),Ho,"user-info-dev.json"),this.jwtTokenFilePath=XF.join(KL.homedir(),Ho,"jwt-token-dev.json"),this.usageStatsFilePath=XF.join(KL.homedir(),Ho,"usage-stats-dev.json")):(this.userInfoFilePath=XF.join(KL.homedir(),Ho,"user-info.json"),this.jwtTokenFilePath=XF.join(KL.homedir(),Ho,"jwt-token.json"),this.usageStatsFilePath=XF.join(KL.homedir(),Ho,"usage-stats.json")),this.cliVersion="1.1.133",this.config={proxyServerUrl:zlt()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId===null&&(this.periodicStatusCheckIntervalId=setInterval(()=>{this.runPeriodicTokenCheck()},600*1e3))}async runPeriodicTokenCheck(){if(!this.userInfo&&!this.jwtTokenData)return;(!this.jwtTokenData||this.isTokenExpired())&&this.reloadFromDisk();let e=!!this.jwtTokenData&&!this.isTokenExpired();if(this.userInfo&&!e){if(this.jwtTokenData?.refreshToken)try{await this.refreshAccessToken(),console.log("[Login Check] \u2705 Periodic status check - expired access credential renewed via refresh credential");return}catch(r){if(this.jwtTokenData?.refreshToken){console.warn("[Login Check] \u26A0\uFE0F Periodic status check - credential refresh failed transiently, keeping session and retrying next cycle:",r instanceof Error?r.message:String(r));return}}console.log("[Login Check] \u26A0\uFE0F Periodic status check - Credential expired and cannot be renewed, signing out to return to login"),this.clear(),this.triggerLoginSuccessCallbacks();return}if(this.jwtTokenData){let r=Date.now(),a=this.jwtTokenData.expiresAt-r,i=this.formatTimeRemaining(a),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-ple*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${i} (until ${o}), next renewal: ${t}`)}}static getInstance(){return n.instance||(n.instance=new n),n.instance}chmodOwnerOnly(e){if(process.platform!=="win32")try{Tc.chmodSync(e,384)}catch(r){console.warn("[Login Check] Failed to chmod credential file:",r)}}loadUserInfo(){try{if(Tc.existsSync(this.userInfoFilePath)){this.chmodOwnerOnly(this.userInfoFilePath);let e=Tc.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(e);let r=a=>{if(!a||!a.includes("@"))return a;let[i,o]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${o}`}}else this.userInfo=null}catch(e){console.warn("[Login Check] Failed to load user info from local file:",e),this.userInfo=null}}saveUserInfo(){try{let e=XF.dirname(this.userInfoFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),this.chmodOwnerOnly(this.userInfoFilePath),console.log("[Login Check] User info saved to local file")}catch(e){console.error("[Login Check] Failed to save user info:",e)}}loadJwtToken(){try{if(Tc.existsSync(this.jwtTokenFilePath)){this.chmodOwnerOnly(this.jwtTokenFilePath);let e=Tc.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(e),this.isTokenExpired()?this.jwtTokenData?.refreshToken||(this.jwtTokenData=null):this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required"),this.jwtTokenData=null}catch(e){console.warn("[Login Check] Failed to load access credential from local file:",e),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let e=XF.dirname(this.jwtTokenFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),this.chmodOwnerOnly(this.jwtTokenFilePath),console.log("[Login Check] Access credential data saved to local file")}catch(e){console.error("[Login Check] Failed to save access credential:",e)}}loadUsageStats(){try{if(Tc.existsSync(this.usageStatsFilePath)){let e=Tc.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(e)}}catch(e){console.warn("[Login Check] Failed to load usage stats from local file:",e),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let e=XF.dirname(this.usageStatsFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),this.chmodOwnerOnly(this.usageStatsFilePath),console.log("[Login Check] Usage stats saved to local file")}catch(e){console.error("[Login Check] Failed to save usage stats:",e)}}updateUsageStats(e){e<=0||(this.usageStats.totalCreditsConsumed+=e,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${e})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(e){this.config={...this.config,...e},e.userInfo&&(this.userInfo=e.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${e.userInfo.name}`)),e.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${e.proxyServerUrl}`),e.cliVersion&&(this.cliVersion=e.cliVersion,console.log(`[Login Check] CLI version set: ${e.cliVersion}`))}setUserInfo(e){this.userInfo=e,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${e.name} (${e.email||e.openId||"N/A"})`),this.startPeriodicStatusCheck(),this.triggerLoginSuccessCallbacks()}onLoginSuccess(e){this.onLoginSuccessCallbacks.push(e)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(e=>{try{e()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(e){this.cliVersion=e,console.log(`[Login Check] CLI version updated: ${e}`)}setJwtToken(e){let r=Date.now();this.jwtTokenData={accessToken:e,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(e){let a=Date.now()+e.expiresIn*1e3;this.jwtTokenData={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(e.expiresIn*1e3),o=this.formatAbsoluteTime(a),t=this.formatAbsoluteTime(a-ple*1e3),d=!!e.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${o}), next renewal: ${t}${d}`)}reloadFromDisk(){this.loadUserInfo(),this.loadJwtToken()}async getAccessToken(){if(this.jwtTokenData||this.reloadFromDisk(),!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let e=Date.now(),r=this.jwtTokenData.expiresAt-e,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-ple*1e3,o=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(t){return console.error("[Login Check] Credential renewal failed:",t),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(e=ple){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=e*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${e}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let e=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":this.getUserAgent()},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!e.ok){if(e.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let d=await e.text();throw new Error(`Credential refresh failed (${e.status}): ${d}`)}let r=await e.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let o=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-ple*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${o} (until ${t}), next renewal: ${s}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(e){throw console.error("[Login Check] Credential refresh error:",e),e}}clearTokens(){this.jwtTokenData=null;try{Tc.existsSync(this.jwtTokenFilePath)&&Tc.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(e){let r=this.getCliVersion(),a=this.getUserAgent(),i={"Content-Type":"application/json","X-Client-Version":r,"User-Agent":a,"X-Session-ID":HF()};return e&&(i["X-DVCode-Scene"]=e),i}getUserHeadersSync(){let e=this.getCliVersion(),r=this.getUserAgent();return{"Content-Type":"application/json","X-Client-Version":e,"User-Agent":r,"X-Session-ID":HF()}}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{Tc.existsSync(this.userInfoFilePath)&&Tc.unlinkSync(this.userInfoFilePath)}catch(e){console.warn("[Login Check] Failed to delete user info file:",e)}try{Tc.existsSync(this.jwtTokenFilePath)&&Tc.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}console.log("[Login Check] Authentication cleared")}},kF=Dc.getInstance()});function CRa(n){try{let e=new URL(n).hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"}catch{return!1}}async function fle(n={}){let e=(n.baseUrl??kF.getProxyServerUrl()??"").trim().replace(/\/+$/,"");if(!e)throw new SF("Proxy server URL is not configured");if(CRa(e))return[];let r=`${e}/web-api/models`,a=await kF.getUserHeaders(),i=n.timeoutMs??YRa,o=new AbortController,t=setTimeout(()=>o.abort(new Error(`Timed out after ${i}ms`)),i),s=[o.signal];n.signal&&s.push(n.signal);let d=s.length===1?s[0]:AbortSignal.any?.(s)??s[0];try{let I;try{I=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json",...a,"User-Agent":n.userAgent??"DeepCode"},signal:d})}catch(c){if(o.signal.aborted)throw new SF(`Request to ${r} timed out after ${i}ms`,void 0,c);let m=c instanceof Error?c.message:String(c);throw new SF(`Network error contacting ${r}: ${m}`,void 0,c)}if(!I.ok){let c="";try{c=await I.text()}catch{}if(I.status===401&&x8e(c))throw new Tz;let m=c?c.length>200?c.slice(0,200)+"\u2026":c:I.statusText||"no body";throw new SF(`Proxy /web-api/models returned HTTP ${I.status}: ${m}`,I.status)}let u;try{u=await I.json()}catch(c){throw new SF("Proxy /web-api/models returned a body that is not valid JSON",I.status,c)}if(!u?.success)throw new SF(u?.message||"Proxy /web-api/models response was unsuccessful",I.status);if(!Array.isArray(u.data))throw new SF('Proxy /web-api/models response is missing the expected "data" array',I.status);let h=u.data.filter(c=>!!c&&typeof c.name=="string").map(c=>({name:c.name,displayName:typeof c.displayName=="string"&&c.displayName?c.displayName:c.name,creditsPerRequest:typeof c.creditsPerRequest=="number"?c.creditsPerRequest:0,available:c.available!==!1,maxToken:typeof c.maxToken=="number"?c.maxToken:0,highVolumeThreshold:typeof c.highVolumeThreshold=="number"?c.highVolumeThreshold:0,highVolumeCredits:typeof c.highVolumeCredits=="number"?c.highVolumeCredits:0}));return h.sort((c,m)=>c.displayName.localeCompare(m.displayName)),h}finally{clearTimeout(t)}}var YRa,SF,Tz,NAr=De(()=>{"use strict";ble();gu();YRa=15e3,SF=class extends Error{status;cause;constructor(e,r,a){super(e),this.status=r,this.cause=a,this.name="CloudModelsFetchError"}},Tz=class extends SF{constructor(e="Authentication required - please re-authenticate"){super(e,401),this.name="CloudModelsAuthError"}}});var NIt,FAr=De(()=>{"use strict";NIt=class{onToolStatusChanged(e,r,a,i){}onOutputUpdate(e,r,a){}getPreferredEditor(e){}getStatusUpdateCallback(){}onPreToolExecution(e,r,a,i){}onAllToolsComplete(e,r){}onToolCallsUpdate(e,r){}}});import*as BR from"node:fs";import*as yQ from"node:path";import*as wAr from"node:os";function FIt(){return yQ.join(wAr.homedir(),Ho,"trusted-project-hooks.json")}function e5e(){try{let n=FIt();if(!BR.existsSync(n))return{trustedPaths:[]};let e=BR.readFileSync(n,"utf-8"),r=JSON.parse(e);return Array.isArray(r.trustedPaths)?{trustedPaths:r.trustedPaths}:{trustedPaths:[]}}catch{return{trustedPaths:[]}}}function RAr(n){let e=FIt(),r=yQ.dirname(e);BR.mkdirSync(r,{recursive:!0});let a=`${e}.${process.pid}.tmp`;BR.writeFileSync(a,JSON.stringify(n,null,2),"utf8"),BR.renameSync(a,e)}function Dz(n){let e=yQ.resolve(n),{trustedPaths:r}=e5e();return r.includes(e)}function wIt(n){let e=yQ.resolve(n),r=e5e();r.trustedPaths.includes(e)||(r.trustedPaths.push(e),RAr(r))}function RIt(n){let e=yQ.resolve(n),r=e5e(),a=r.trustedPaths.filter(i=>i!==e);a.length!==r.trustedPaths.length&&RAr({trustedPaths:a})}function VRa(){return e5e().trustedPaths}var AAr=De(()=>{"use strict";nm();});function EAr(n){if(n==null)return;if(typeof n=="object"){let a=n;if(typeof a.status=="number")return a.status;if(typeof a.statusCode=="number")return a.statusCode;let i=a.response;if(i&&typeof i.status=="number")return i.status}if(Zy(n)&&typeof n.error.code=="number")return n.error.code;let e=typeof n=="string"?n:typeof n=="object"&&n!==null&&"message"in n?String(n.message??""):"",r=[/API request failed \((\d{3})\)/,/Stream API error \((\d{3})\)/,/\(Status:\s*(\d{3})\)/i,/\bHTTP\s+(\d{3})\b/i,/\bstatus[\s:=]+(\d{3})\b/i];for(let a of r){let i=e.match(a);if(i){let o=parseInt(i[1],10);if(o>=100&&o<600)return o}}}function xAr(n){if(n==null)return"";if(typeof n=="string")return AIt(n)??n;if(Zy(n))return n.error.message||"";if(lb(n)||n instanceof Error)return AIt(n.message)??n.message;try{return String(n)}catch{return""}}function AIt(n){if(!n)return;let e=n.indexOf("{");if(e===-1)return;let r=n.substring(e);try{let a=JSON.parse(r);if(a&&typeof a=="object"){let i=a;if(i.error&&typeof i.error=="object"&&typeof i.error.message=="string"){let o=i.error.message;if(o.trim())return`${n.substring(0,e).trim()} ${o}`.trim()}if(typeof i.message=="string"&&i.message.trim()){let o=n.substring(0,e).trim();return o?`${o} ${i.message}`:i.message}if(typeof i.error=="string"&&i.error.trim()){let o=n.substring(0,e).trim();return o?`${o} ${i.error}`:i.error}}}catch{}}function $L(n){let e=EAr(n),r=xAr(n).trim();if(e!==void 0)return r?`[HTTP ${e}] ${r}`:`[HTTP ${e}]`}var CAr=De(()=>{"use strict";_X();});function QAr(n){if(!n)return!1;let e=n.trim().toLowerCase(),r=e.lastIndexOf("@");if(r<=0)return!1;let a=e.slice(r+1);return QRa.includes(a)}function HRa(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n&&typeof n=="object"){let e=n;if(typeof e.message=="string")return e.message;try{return JSON.stringify(e.response?.data??e)}catch{return String(n)}}return String(n)}function HAr(n){let e=HRa(n).match(/available[\s:]*([0-9]+(?:\.[0-9]+)?)/i);return e?e[1]:null}function t5e(n){return s1(n)}function Gle(n,e={}){if(!t5e(n))return null;let r=e.locale??"zh",a=HAr(n),i=QAr(e.email);if(r==="en"){let s=a!==null?`Your credit balance is insufficient (current balance: ${a}).`:"Your credit balance is insufficient.",d=i?`As a Cheetah employee, request an "HwjCode quota" via the Feishu approval form: ${VAr}`:`Sign in at ${YAr} to recharge.`;return`${s} ${d}`}let o=a!==null?`\u60A8\u7684\u53EF\u7528\u79EF\u5206\u4F59\u989D\u4E0D\u8DB3,\u5F53\u524D\u4F59\u989D:${a}\u3002`:"\u60A8\u7684\u53EF\u7528\u79EF\u5206\u4F59\u989D\u4E0D\u8DB3\u3002",t=i?`\u60A8\u662F\u730E\u8C79\u5458\u5DE5,\u8BF7\u524D\u5F80\u98DE\u4E66\u5BA1\u6279(${VAr})\u7533\u8BF7"HwjCode \u914D\u989D"\u3002`:`\u8BF7\u767B\u5F55 ${YAr} \u5145\u503C\u3002`;return`${o}${t}`}var YAr,VAr,QRa,XAr=De(()=>{"use strict";_X();YAr="https://hwjcode.bot/",VAr="https://applink.feishu.cn/T981u6WkPNNZ",QRa=["cmcm.com","orionstar.com"]});function r5e(n){let e=Rw(n),r=[],a=[],i=e.toolCallReliability==="low"||e.needsFormatTolerance,o=e.needsFormatTolerance||e.proneToIncompleteStream||e.enableMalformedRetry;return e.toolCallReliability==="low"&&(r.push("Consider using sequential tool calls instead of concurrent ones"),r.push("Enable debug logging to monitor tool call success rates")),e.needsFormatTolerance&&(r.push("Tolerant parameter validation is enabled for this model"),r.push("Consider upgrading to a more capable model for production use")),e.proneToIncompleteStream&&(r.push("Streaming responses may be incomplete - validation and retry enabled"),a.push("Function calls may require automatic fixing during streaming")),e.maxConcurrentTools<3&&a.push(`Concurrent tool calls limited to ${e.maxConcurrentTools} for stability`),e.enableMalformedRetry&&r.push("Automatic retry enabled for malformed function calls"),e.enableProgressiveDegradation&&r.push("Progressive degradation enabled - will reduce complexity on failures"),{modelName:n,capabilities:e,recommendations:r,warnings:a,isSmallModel:i,needsSpecialHandling:o}}function XRa(n,e=!1){let r=r5e(n);console.log(`
4047
+ `);let w=Date.now()-o;return console.warn(`[ToolCall] Blocked dangerous command: ${e.name}, duration: ${w}ms`),t(!1,E.message.length),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:E.message}}}],resultDisplay:E.message,error:E}}let u=await i.execute(e.args,d),h=u.llmContent,c=u.returnDisplay,m=Date.now()-o;console.debug(`[ToolCall] Success: ${e.name}, duration: ${m}ms`);let y=typeof h=="string"?h.length:JSON.stringify(h).length;t(!0,y);let g=Dk(e.name,e.callId,h);return{callId:e.callId,responseParts:g,resultDisplay:c,error:void 0}}catch(d){let I=d instanceof Error?d:new Error(String(d)),u=Date.now()-o;return console.warn(`[ToolCall] Failed: ${e.name}, error: ${I.message}, duration: ${u}ms`),t(!1,I.message.length),{callId:e.callId,responseParts:[{functionResponse:{id:e.callId,name:e.name,response:{error:I.message}}}],resultDisplay:I.message,error:I}}}var vAr=De(()=>{"use strict";B2e();ete();BK();});import{randomUUID as FRa}from"crypto";function HF(){return mle||(mle=FRa()),mle}function yAr(n){mle=n}function ZAr(){mle=void 0}var mle,WAr,WIt=De(()=>{"use strict";WAr=HF()});import*as Tc from"fs";import*as XF from"path";import*as KL from"os";function wRa(n){kF.configure(n)}function RRa(n){kF.setUserInfo(n)}function ARa(n){kF.setCliVersion(n)}async function ERa(){return await kF.getUserHeaders()}function xRa(){return kF.getStatus()}var ple,Dc,kF,ble=De(()=>{"use strict";_lt();WIt();bL();nm();ple=259200,Dc=class n{static instance=null;config;userInfo=null;jwtTokenData=null;usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()};userInfoFilePath;jwtTokenFilePath;usageStatsFilePath;refreshPromise=null;cliVersion="unknown";periodicStatusCheckIntervalId=null;onLoginSuccessCallbacks=[];getCliVersion(){return this.cliVersion}getUserAgent(){return fF(this.cliVersion)}formatTimeRemaining(e){if(e<=0)return"\u5DF2\u8FC7\u671F";let r=Math.floor(e/1e3),a=Math.floor(r/(24*3600)),i=Math.floor(r%(24*3600)/3600),o=Math.floor(r%3600/60),t=r%60;return a>0?`${a}\u5929${i}\u5C0F\u65F6${o}\u5206\u949F`:i>0?`${i}\u5C0F\u65F6${o}\u5206\u949F${t}\u79D2`:o>0?`${o}\u5206\u949F${t}\u79D2`:`${t}\u79D2`}formatAbsoluteTime(e){return new Date(e).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}constructor(){"https://api-code.deepvlab.ai"?.includes("localhost")?(this.userInfoFilePath=XF.join(KL.homedir(),Ho,"user-info-dev.json"),this.jwtTokenFilePath=XF.join(KL.homedir(),Ho,"jwt-token-dev.json"),this.usageStatsFilePath=XF.join(KL.homedir(),Ho,"usage-stats-dev.json")):(this.userInfoFilePath=XF.join(KL.homedir(),Ho,"user-info.json"),this.jwtTokenFilePath=XF.join(KL.homedir(),Ho,"jwt-token.json"),this.usageStatsFilePath=XF.join(KL.homedir(),Ho,"usage-stats.json")),this.cliVersion="1.1.134",this.config={proxyServerUrl:zlt()},this.loadUserInfo(),this.loadJwtToken(),this.loadUsageStats(),this.startPeriodicStatusCheck()}startPeriodicStatusCheck(){this.periodicStatusCheckIntervalId===null&&(this.periodicStatusCheckIntervalId=setInterval(()=>{this.runPeriodicTokenCheck()},600*1e3))}async runPeriodicTokenCheck(){if(!this.userInfo&&!this.jwtTokenData)return;(!this.jwtTokenData||this.isTokenExpired())&&this.reloadFromDisk();let e=!!this.jwtTokenData&&!this.isTokenExpired();if(this.userInfo&&!e){if(this.jwtTokenData?.refreshToken)try{await this.refreshAccessToken(),console.log("[Login Check] \u2705 Periodic status check - expired access credential renewed via refresh credential");return}catch(r){if(this.jwtTokenData?.refreshToken){console.warn("[Login Check] \u26A0\uFE0F Periodic status check - credential refresh failed transiently, keeping session and retrying next cycle:",r instanceof Error?r.message:String(r));return}}console.log("[Login Check] \u26A0\uFE0F Periodic status check - Credential expired and cannot be renewed, signing out to return to login"),this.clear(),this.triggerLoginSuccessCallbacks();return}if(this.jwtTokenData){let r=Date.now(),a=this.jwtTokenData.expiresAt-r,i=this.formatTimeRemaining(a),o=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-ple*1e3);console.log(`[Login Check] \u{1F4CA} Periodic status check - Credential remaining: ${i} (until ${o}), next renewal: ${t}`)}}static getInstance(){return n.instance||(n.instance=new n),n.instance}chmodOwnerOnly(e){if(process.platform!=="win32")try{Tc.chmodSync(e,384)}catch(r){console.warn("[Login Check] Failed to chmod credential file:",r)}}loadUserInfo(){try{if(Tc.existsSync(this.userInfoFilePath)){this.chmodOwnerOnly(this.userInfoFilePath);let e=Tc.readFileSync(this.userInfoFilePath,"utf8");this.userInfo=JSON.parse(e);let r=a=>{if(!a||!a.includes("@"))return a;let[i,o]=a.split("@");return i.length<=2?a:`${i[0]+"*".repeat(i.length-2)+i[i.length-1]}@${o}`}}else this.userInfo=null}catch(e){console.warn("[Login Check] Failed to load user info from local file:",e),this.userInfo=null}}saveUserInfo(){try{let e=XF.dirname(this.userInfoFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.userInfoFilePath,JSON.stringify(this.userInfo,null,2)),this.chmodOwnerOnly(this.userInfoFilePath),console.log("[Login Check] User info saved to local file")}catch(e){console.error("[Login Check] Failed to save user info:",e)}}loadJwtToken(){try{if(Tc.existsSync(this.jwtTokenFilePath)){this.chmodOwnerOnly(this.jwtTokenFilePath);let e=Tc.readFileSync(this.jwtTokenFilePath,"utf8");this.jwtTokenData=JSON.parse(e),this.isTokenExpired()?this.jwtTokenData?.refreshToken||(this.jwtTokenData=null):this.isTokenNearExpiry(300)&&console.log("\u26A0\uFE0F Access credential expiring soon, auto-renewal in progress")}else console.log("[Login Check] No stored access credential found, authentication required"),this.jwtTokenData=null}catch(e){console.warn("[Login Check] Failed to load access credential from local file:",e),this.jwtTokenData=null}}saveJwtToken(){try{if(!this.jwtTokenData)return;let e=XF.dirname(this.jwtTokenFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.jwtTokenFilePath,JSON.stringify(this.jwtTokenData,null,2)),this.chmodOwnerOnly(this.jwtTokenFilePath),console.log("[Login Check] Access credential data saved to local file")}catch(e){console.error("[Login Check] Failed to save access credential:",e)}}loadUsageStats(){try{if(Tc.existsSync(this.usageStatsFilePath)){let e=Tc.readFileSync(this.usageStatsFilePath,"utf8");this.usageStats=JSON.parse(e)}}catch(e){console.warn("[Login Check] Failed to load usage stats from local file:",e),this.usageStats={totalCreditsConsumed:0,lastUpdated:new Date().toISOString()}}}saveUsageStats(){try{let e=XF.dirname(this.usageStatsFilePath);Tc.existsSync(e)||Tc.mkdirSync(e,{recursive:!0,mode:448}),Tc.writeFileSync(this.usageStatsFilePath,JSON.stringify(this.usageStats,null,2)),this.chmodOwnerOnly(this.usageStatsFilePath),console.log("[Login Check] Usage stats saved to local file")}catch(e){console.error("[Login Check] Failed to save usage stats:",e)}}updateUsageStats(e){e<=0||(this.usageStats.totalCreditsConsumed+=e,this.usageStats.lastUpdated=new Date().toISOString(),this.saveUsageStats(),console.log(`[Usage Stats] Updated total credits consumed: ${this.usageStats.totalCreditsConsumed} (+${e})`))}getUsageStats(){return{...this.usageStats}}checkStartupTokenStatus(){return this.jwtTokenData?{hasToken:!0,isExpired:Date.now()>=this.jwtTokenData.expiresAt,expiresAt:this.jwtTokenData.expiresAt,hasRefreshToken:!!this.jwtTokenData.refreshToken}:{hasToken:!1,isExpired:!0,expiresAt:null,hasRefreshToken:!1}}configure(e){this.config={...this.config,...e},e.userInfo&&(this.userInfo=e.userInfo,this.saveUserInfo(),console.log(`[Login Check] User info configured: ${e.userInfo.name}`)),e.proxyServerUrl&&console.log(`[Login Check] Proxy server URL: ${e.proxyServerUrl}`),e.cliVersion&&(this.cliVersion=e.cliVersion,console.log(`[Login Check] CLI version set: ${e.cliVersion}`))}setUserInfo(e){this.userInfo=e,this.saveUserInfo(),console.log(`[Login Check] User info updated: ${e.name} (${e.email||e.openId||"N/A"})`),this.startPeriodicStatusCheck(),this.triggerLoginSuccessCallbacks()}onLoginSuccess(e){this.onLoginSuccessCallbacks.push(e)}triggerLoginSuccessCallbacks(){this.onLoginSuccessCallbacks.forEach(e=>{try{e()}catch(r){console.error("[ProxyAuthManager] Error in login success callback:",r)}})}setCliVersion(e){this.cliVersion=e,console.log(`[Login Check] CLI version updated: ${e}`)}setJwtToken(e){let r=Date.now();this.jwtTokenData={accessToken:e,expiresIn:900,expiresAt:r+900*1e3,savedAt:new Date().toISOString()},this.saveJwtToken(),console.log("[Login Check] Access credential updated")}setJwtTokenData(e){let a=Date.now()+e.expiresIn*1e3;this.jwtTokenData={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresIn:e.expiresIn,expiresAt:a,savedAt:new Date().toISOString()},this.saveJwtToken();let i=this.formatTimeRemaining(e.expiresIn*1e3),o=this.formatAbsoluteTime(a),t=this.formatAbsoluteTime(a-ple*1e3),d=!!e.refreshToken?", will auto-renew":", manual login required";console.log(`[Login Check] Access credential updated - valid for: ${i} (until ${o}), next renewal: ${t}${d}`)}reloadFromDisk(){this.loadUserInfo(),this.loadJwtToken()}async getAccessToken(){if(this.jwtTokenData||this.reloadFromDisk(),!this.jwtTokenData)return console.log("[Login Check] No access credential available, authentication required"),null;let e=Date.now(),r=this.jwtTokenData.expiresAt-e,a=this.formatTimeRemaining(r),i=this.jwtTokenData.expiresAt-ple*1e3,o=this.formatAbsoluteTime(i);if(this.isTokenNearExpiry()){console.log(`[Login Check] Access credential expiring soon (remaining: ${a}), starting auto-renewal...`);try{return await this.refreshAccessToken()}catch(t){return console.error("[Login Check] Credential renewal failed:",t),null}}return this.jwtTokenData.accessToken}isTokenExpired(){return this.jwtTokenData?Date.now()>=this.jwtTokenData.expiresAt:!0}isTokenNearExpiry(e=ple){if(!this.jwtTokenData)return!0;let r=this.jwtTokenData.expiresAt-Date.now(),a=r<=e*1e3;if(a){let i=this.formatTimeRemaining(r);console.log(`[Login Check] Credential expiry check: ${i} remaining <= ${e}s threshold, renewal needed: ${a}`)}return a}async refreshAccessToken(){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.performTokenRefresh();try{return await this.refreshPromise}finally{this.refreshPromise=null}}async performTokenRefresh(){if(!this.jwtTokenData?.refreshToken)throw new Error("No refresh token available");try{console.log("[Login Check] Refreshing access credential...");let e=await fetch(`${this.config.proxyServerUrl}/auth/jwt/refresh`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":this.getUserAgent()},body:JSON.stringify({refreshToken:this.jwtTokenData.refreshToken})});if(!e.ok){if(e.status===401)throw this.clearTokens(),new Error("Refresh credential expired or invalid - authentication required");let d=await e.text();throw new Error(`Credential refresh failed (${e.status}): ${d}`)}let r=await e.json();if(!r.success||!r.data?.accessToken)throw new Error("Invalid refresh response from server");let a=Date.now(),i=!!r.data.refreshToken;this.jwtTokenData={accessToken:r.data.accessToken,refreshToken:r.data.refreshToken||this.jwtTokenData.refreshToken,expiresIn:r.data.expiresIn||900,expiresAt:a+(r.data.expiresIn||900)*1e3,savedAt:new Date().toISOString()},this.saveJwtToken();let o=this.formatTimeRemaining((r.data.expiresIn||900)*1e3),t=this.formatAbsoluteTime(this.jwtTokenData.expiresAt),s=this.formatAbsoluteTime(this.jwtTokenData.expiresAt-ple*1e3);return console.log(`[Login Check] \u2705 Credential renewed successfully - valid for: ${o} (until ${t}), next renewal: ${s}${i?" (refresh credential updated)":" (reusing existing refresh credential)"}`),this.jwtTokenData.accessToken}catch(e){throw console.error("[Login Check] Credential refresh error:",e),e}}clearTokens(){this.jwtTokenData=null;try{Tc.existsSync(this.jwtTokenFilePath)&&Tc.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}}getProxyServerUrl(){return this.config.proxyServerUrl}async getUserHeaders(e){let r=this.getCliVersion(),a=this.getUserAgent(),i={"Content-Type":"application/json","X-Client-Version":r,"User-Agent":a,"X-Session-ID":HF()};return e&&(i["X-DVCode-Scene"]=e),i}getUserHeadersSync(){let e=this.getCliVersion(),r=this.getUserAgent();return{"Content-Type":"application/json","X-Client-Version":e,"User-Agent":r,"X-Session-ID":HF()}}getUserInfo(){return this.userInfo}isConfigured(){return!!this.userInfo}getStatus(){return{configured:this.isConfigured(),proxyServerUrl:this.config.proxyServerUrl,hasUserInfo:!!this.userInfo,userInfo:this.userInfo}}clear(){this.userInfo=null,this.jwtTokenData=null,this.periodicStatusCheckIntervalId!==null&&(clearInterval(this.periodicStatusCheckIntervalId),this.periodicStatusCheckIntervalId=null);try{Tc.existsSync(this.userInfoFilePath)&&Tc.unlinkSync(this.userInfoFilePath)}catch(e){console.warn("[Login Check] Failed to delete user info file:",e)}try{Tc.existsSync(this.jwtTokenFilePath)&&Tc.unlinkSync(this.jwtTokenFilePath)}catch(e){console.warn("[Login Check] Failed to delete access credential file:",e)}console.log("[Login Check] Authentication cleared")}},kF=Dc.getInstance()});function CRa(n){try{let e=new URL(n).hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"}catch{return!1}}async function fle(n={}){let e=(n.baseUrl??kF.getProxyServerUrl()??"").trim().replace(/\/+$/,"");if(!e)throw new SF("Proxy server URL is not configured");if(CRa(e))return[];let r=`${e}/web-api/models`,a=await kF.getUserHeaders(),i=n.timeoutMs??YRa,o=new AbortController,t=setTimeout(()=>o.abort(new Error(`Timed out after ${i}ms`)),i),s=[o.signal];n.signal&&s.push(n.signal);let d=s.length===1?s[0]:AbortSignal.any?.(s)??s[0];try{let I;try{I=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json",...a,"User-Agent":n.userAgent??"DeepCode"},signal:d})}catch(c){if(o.signal.aborted)throw new SF(`Request to ${r} timed out after ${i}ms`,void 0,c);let m=c instanceof Error?c.message:String(c);throw new SF(`Network error contacting ${r}: ${m}`,void 0,c)}if(!I.ok){let c="";try{c=await I.text()}catch{}if(I.status===401&&x8e(c))throw new Tz;let m=c?c.length>200?c.slice(0,200)+"\u2026":c:I.statusText||"no body";throw new SF(`Proxy /web-api/models returned HTTP ${I.status}: ${m}`,I.status)}let u;try{u=await I.json()}catch(c){throw new SF("Proxy /web-api/models returned a body that is not valid JSON",I.status,c)}if(!u?.success)throw new SF(u?.message||"Proxy /web-api/models response was unsuccessful",I.status);if(!Array.isArray(u.data))throw new SF('Proxy /web-api/models response is missing the expected "data" array',I.status);let h=u.data.filter(c=>!!c&&typeof c.name=="string").map(c=>({name:c.name,displayName:typeof c.displayName=="string"&&c.displayName?c.displayName:c.name,creditsPerRequest:typeof c.creditsPerRequest=="number"?c.creditsPerRequest:0,available:c.available!==!1,maxToken:typeof c.maxToken=="number"?c.maxToken:0,highVolumeThreshold:typeof c.highVolumeThreshold=="number"?c.highVolumeThreshold:0,highVolumeCredits:typeof c.highVolumeCredits=="number"?c.highVolumeCredits:0}));return h.sort((c,m)=>c.displayName.localeCompare(m.displayName)),h}finally{clearTimeout(t)}}var YRa,SF,Tz,NAr=De(()=>{"use strict";ble();gu();YRa=15e3,SF=class extends Error{status;cause;constructor(e,r,a){super(e),this.status=r,this.cause=a,this.name="CloudModelsFetchError"}},Tz=class extends SF{constructor(e="Authentication required - please re-authenticate"){super(e,401),this.name="CloudModelsAuthError"}}});var NIt,FAr=De(()=>{"use strict";NIt=class{onToolStatusChanged(e,r,a,i){}onOutputUpdate(e,r,a){}getPreferredEditor(e){}getStatusUpdateCallback(){}onPreToolExecution(e,r,a,i){}onAllToolsComplete(e,r){}onToolCallsUpdate(e,r){}}});import*as BR from"node:fs";import*as yQ from"node:path";import*as wAr from"node:os";function FIt(){return yQ.join(wAr.homedir(),Ho,"trusted-project-hooks.json")}function e5e(){try{let n=FIt();if(!BR.existsSync(n))return{trustedPaths:[]};let e=BR.readFileSync(n,"utf-8"),r=JSON.parse(e);return Array.isArray(r.trustedPaths)?{trustedPaths:r.trustedPaths}:{trustedPaths:[]}}catch{return{trustedPaths:[]}}}function RAr(n){let e=FIt(),r=yQ.dirname(e);BR.mkdirSync(r,{recursive:!0});let a=`${e}.${process.pid}.tmp`;BR.writeFileSync(a,JSON.stringify(n,null,2),"utf8"),BR.renameSync(a,e)}function Dz(n){let e=yQ.resolve(n),{trustedPaths:r}=e5e();return r.includes(e)}function wIt(n){let e=yQ.resolve(n),r=e5e();r.trustedPaths.includes(e)||(r.trustedPaths.push(e),RAr(r))}function RIt(n){let e=yQ.resolve(n),r=e5e(),a=r.trustedPaths.filter(i=>i!==e);a.length!==r.trustedPaths.length&&RAr({trustedPaths:a})}function VRa(){return e5e().trustedPaths}var AAr=De(()=>{"use strict";nm();});function EAr(n){if(n==null)return;if(typeof n=="object"){let a=n;if(typeof a.status=="number")return a.status;if(typeof a.statusCode=="number")return a.statusCode;let i=a.response;if(i&&typeof i.status=="number")return i.status}if(Zy(n)&&typeof n.error.code=="number")return n.error.code;let e=typeof n=="string"?n:typeof n=="object"&&n!==null&&"message"in n?String(n.message??""):"",r=[/API request failed \((\d{3})\)/,/Stream API error \((\d{3})\)/,/\(Status:\s*(\d{3})\)/i,/\bHTTP\s+(\d{3})\b/i,/\bstatus[\s:=]+(\d{3})\b/i];for(let a of r){let i=e.match(a);if(i){let o=parseInt(i[1],10);if(o>=100&&o<600)return o}}}function xAr(n){if(n==null)return"";if(typeof n=="string")return AIt(n)??n;if(Zy(n))return n.error.message||"";if(lb(n)||n instanceof Error)return AIt(n.message)??n.message;try{return String(n)}catch{return""}}function AIt(n){if(!n)return;let e=n.indexOf("{");if(e===-1)return;let r=n.substring(e);try{let a=JSON.parse(r);if(a&&typeof a=="object"){let i=a;if(i.error&&typeof i.error=="object"&&typeof i.error.message=="string"){let o=i.error.message;if(o.trim())return`${n.substring(0,e).trim()} ${o}`.trim()}if(typeof i.message=="string"&&i.message.trim()){let o=n.substring(0,e).trim();return o?`${o} ${i.message}`:i.message}if(typeof i.error=="string"&&i.error.trim()){let o=n.substring(0,e).trim();return o?`${o} ${i.error}`:i.error}}}catch{}}function $L(n){let e=EAr(n),r=xAr(n).trim();if(e!==void 0)return r?`[HTTP ${e}] ${r}`:`[HTTP ${e}]`}var CAr=De(()=>{"use strict";_X();});function QAr(n){if(!n)return!1;let e=n.trim().toLowerCase(),r=e.lastIndexOf("@");if(r<=0)return!1;let a=e.slice(r+1);return QRa.includes(a)}function HRa(n){if(typeof n=="string")return n;if(n instanceof Error)return n.message;if(n&&typeof n=="object"){let e=n;if(typeof e.message=="string")return e.message;try{return JSON.stringify(e.response?.data??e)}catch{return String(n)}}return String(n)}function HAr(n){let e=HRa(n).match(/available[\s:]*([0-9]+(?:\.[0-9]+)?)/i);return e?e[1]:null}function t5e(n){return s1(n)}function Gle(n,e={}){if(!t5e(n))return null;let r=e.locale??"zh",a=HAr(n),i=QAr(e.email);if(r==="en"){let s=a!==null?`Your credit balance is insufficient (current balance: ${a}).`:"Your credit balance is insufficient.",d=i?`As a Cheetah employee, request an "HwjCode quota" via the Feishu approval form: ${VAr}`:`Sign in at ${YAr} to recharge.`;return`${s} ${d}`}let o=a!==null?`\u60A8\u7684\u53EF\u7528\u79EF\u5206\u4F59\u989D\u4E0D\u8DB3,\u5F53\u524D\u4F59\u989D:${a}\u3002`:"\u60A8\u7684\u53EF\u7528\u79EF\u5206\u4F59\u989D\u4E0D\u8DB3\u3002",t=i?`\u60A8\u662F\u730E\u8C79\u5458\u5DE5,\u8BF7\u524D\u5F80\u98DE\u4E66\u5BA1\u6279(${VAr})\u7533\u8BF7"HwjCode \u914D\u989D"\u3002`:`\u8BF7\u767B\u5F55 ${YAr} \u5145\u503C\u3002`;return`${o}${t}`}var YAr,VAr,QRa,XAr=De(()=>{"use strict";_X();YAr="https://hwjcode.bot/",VAr="https://applink.feishu.cn/T981u6WkPNNZ",QRa=["cmcm.com","orionstar.com"]});function r5e(n){let e=Rw(n),r=[],a=[],i=e.toolCallReliability==="low"||e.needsFormatTolerance,o=e.needsFormatTolerance||e.proneToIncompleteStream||e.enableMalformedRetry;return e.toolCallReliability==="low"&&(r.push("Consider using sequential tool calls instead of concurrent ones"),r.push("Enable debug logging to monitor tool call success rates")),e.needsFormatTolerance&&(r.push("Tolerant parameter validation is enabled for this model"),r.push("Consider upgrading to a more capable model for production use")),e.proneToIncompleteStream&&(r.push("Streaming responses may be incomplete - validation and retry enabled"),a.push("Function calls may require automatic fixing during streaming")),e.maxConcurrentTools<3&&a.push(`Concurrent tool calls limited to ${e.maxConcurrentTools} for stability`),e.enableMalformedRetry&&r.push("Automatic retry enabled for malformed function calls"),e.enableProgressiveDegradation&&r.push("Progressive degradation enabled - will reduce complexity on failures"),{modelName:n,capabilities:e,recommendations:r,warnings:a,isSmallModel:i,needsSpecialHandling:o}}function XRa(n,e=!1){let r=r5e(n);console.log(`
4048
4048
  \u{1F50D} Model Diagnostics: ${n}`),console.log(`\u{1F4CA} Reliability: ${r.capabilities.toolCallReliability}`),console.log(`\u{1F527} Format Tolerance: ${r.capabilities.needsFormatTolerance?"Yes":"No"}`),console.log(`\u{1F504} Max Concurrent Tools: ${r.capabilities.maxConcurrentTools}`),r.warnings.length>0&&(console.log(`
4049
4049
  \u26A0\uFE0F Warnings:`),r.warnings.forEach(a=>console.log(` \u2022 ${a}`))),e&&r.recommendations.length>0&&(console.log(`
4050
4050
  \u{1F4A1} Recommendations:`),r.recommendations.forEach(a=>console.log(` \u2022 ${a}`))),e&&(console.log(`
4051
- \u{1F4CB} Full Capabilities:`),console.log(JSON.stringify(r.capabilities,null,2)))}function kRa(n){let e=r5e(n);return e.isSmallModel||e.needsSpecialHandling}function SRa(n){let e=r5e(n);return e.capabilities.toolCallReliability==="high"?"\u2705 Excellent tool calling compatibility":e.capabilities.toolCallReliability==="medium"?"\u{1F7E1} Good compatibility with enhanced error handling":"\u{1F7E0} Limited compatibility - enhanced robustness features active"}var kAr=De(()=>{"use strict";qee();});import*as TZ from"fs";import*as n5e from"path";var LRa,gle,SAr=De(()=>{"use strict";Zd();LRa="healthy-use-reminder.json",gle=class{projectRoot;stateFilePath;constructor(e){this.projectRoot=e;let r=AG(e);this.stateFilePath=n5e.join(r,LRa)}shouldShowReminder(){let r=new Date().getHours();if(!(r>=22||r<6))return this.clearState(),!1;let i=this.loadState();if(!i||i.lastReminderShownAt===0)return!0;let o=2700*1e3;return Date.now()-i.lastReminderShownAt>=o}markReminderShown(){this.saveState({lastReminderShownAt:Date.now()})}clearState(){try{TZ.existsSync(this.stateFilePath)&&TZ.unlinkSync(this.stateFilePath)}catch(e){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to clear state:",e)}}loadState(){try{if(!TZ.existsSync(this.stateFilePath))return null;let e=TZ.readFileSync(this.stateFilePath,"utf-8");return JSON.parse(e)}catch(e){return process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to load state:",e),null}}saveState(e){try{let r=n5e.dirname(this.stateFilePath);TZ.existsSync(r)||TZ.mkdirSync(r,{recursive:!0}),TZ.writeFileSync(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}catch(r){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to save state:",r)}}}});var EIt,xIt,JRa,BRa,TRa,LAr=De(()=>{"use strict";EIt="--- Content from referenced files ---",xIt="--- End of content ---",JRa=2e3,BRa=2e3,TRa=20});function BAr(...n){return DRa(...n)}function TAr(...n){return ORa(...n)}function JAr(n,e){return n in e}function CIt(){let n={get(i,o){if(o==="write")return BAr;if(JAr(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},e=new Proxy(process.stdout,n),r={get(i,o){if(o==="write")return TAr;if(JAr(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},a=new Proxy(process.stderr,r);return{stdout:e,stderr:a}}var DRa,ORa,DAr=De(()=>{"use strict";DRa=process.stdout.write.bind(process.stdout),ORa=process.stderr.write.bind(process.stderr)});import{readFile as MRa}from"node:fs/promises";import{fileURLToPath as URa}from"node:url";import YIt from"node:path";function zRa(){let n=globalThis.import?.meta??void 0;try{let r=typeof import.meta<"u"?import.meta.url:void 0;if(r)return YIt.dirname(URa(r))}catch{}let e=globalThis.__dirname;return typeof e=="string"?e:process.cwd()}function TR(){return vle||(vle=(async()=>"1.1.133")(),vle)}function _Ra(){vle=void 0}var vle,VIt=De(()=>{"use strict";});function PRa(n="latest"){let e=n?.trim().toLowerCase();return OAr.includes(e)?e:MAr}var OAr,MAr,UAr=De(()=>{"use strict";OAr=["stable","latest"],MAr="stable"});import{EventEmitter as jRa}from"node:events";var yle,QIt,HIt,zAr=De(()=>{"use strict";(function(n){n.ApprovalModeChanged="approval_mode_changed"})(yle||(yle={}));QIt=class{emitter=new jRa;on(e,r){return this.emitter.on(e,r),()=>this.emitter.off(e,r)}off(e,r){this.emitter.off(e,r)}emit(e,r){this.emitter.emit(e,r)}removeAllListeners(e){e?this.emitter.removeAllListeners(e):this.emitter.removeAllListeners()}},HIt=new QIt});function a5e(n){return Array.isArray(n)?n.map(e=>typeof e=="string"?{text:e}:e):typeof n=="string"?[{text:n}]:[n]}function qRa(n){return n.map(e=>typeof e.text=="string"?e.text:"").join("")}function XIt(n){if(!n||n.length===0)return[];let e=[];for(let r of n){if(r.role&&(r.parts||r.content!==void 0)){let a=r.parts??a5e(r.content);e.push({role:r.role,parts:a});continue}if(!(r.type==="info"||r.type==="error"||r.type==="warning")){if(r.type==="user"){let a=r.content!==void 0?a5e(r.content):[],i=qRa(a).trim();if(i.startsWith("/")||i.startsWith("?")||a.length===0)continue;e.push({role:"user",parts:a});continue}if(r.type==="gemini"){let a=[];if(r.thoughts&&r.thoughts.length>0)for(let o of r.thoughts){let t=o.subject?`**${o.subject}** ${o.description}`:o.description;a.push({text:t,thought:!0})}let i=!!r.toolCalls&&r.toolCalls.length>0;if(r.content!==void 0&&a.push(...a5e(r.content)),i)for(let o of r.toolCalls)a.push({functionCall:{name:o.name,args:o.args,...o.id?{id:o.id}:{}}});if(a.length>0&&e.push({role:"model",parts:a}),i){let o=[];for(let t of r.toolCalls)t.result!==void 0&&(typeof t.result=="string"?o.push({functionResponse:{id:t.id,name:t.name,response:{output:t.result}}}):Array.isArray(t.result)?o.push(...a5e(t.result)):o.push(t.result));o.length>0&&e.push({role:"user",parts:o})}}}}return e}var _Ar=De(()=>{"use strict";});var e6,PAr,Zle,jAr=De(()=>{"use strict";e6=class n extends Error{constructor(e){super(e),this.name="SessionError"}static noSessionsFound(){return new n("No persisted sessions found.")}static invalidSessionIdentifier(e,r){return new n(`Session '${e}' was not found under ${r}.`)}},PAr="latest",Zle=class{manager;constructor(e){this.manager=e}async sessionExists(e){return(await this.listAllMetadata()).some(a=>a.sessionId===e)}async listSessions(){return(await this.listAllMetadata()).map(r=>({id:r.sessionId,startTime:r.createdAt,title:r.title,messageCount:r.messageCount})).sort((r,a)=>new Date(r.startTime).getTime()-new Date(a.startTime).getTime())}async findSession(e){let r=e.trim(),a=await this.listSessions();if(a.length===0)throw e6.noSessionsFound();let i=a.find(t=>t.id===r);if(i)return i;let o=Number.parseInt(r,10);if(Number.isInteger(o)&&o.toString()===r&&o>0&&o<=a.length)return a[o-1];throw e6.invalidSessionIdentifier(r,"sessions/")}async resolveSession(e){let r=e.trim(),a;if(r===PAr){let o=await this.listSessions();if(o.length===0)throw e6.noSessionsFound();a=o[o.length-1]}else a=await this.findSession(r);let i=await this.manager.loadSession(a.id);if(!i)throw new e6(`Session '${a.id}' exists in index but could not be loaded.`);return{session:a,data:i}}async listAllMetadata(){let e=this.manager;return typeof e.listSessions=="function"?await e.listSessions():typeof e.getSessionIndex=="function"?(await e.getSessionIndex())?.sessions??[]:[]}}});function KRa(n,e,r){return new i5e(n,e,r)}var i5e,s5e,o5e,qAr=De(()=>{"use strict";Oee();bL();i5e=class n{tokenManager;baseURL;requestQueue=[];isRefreshing=!1;onAuthenticationRequired;constructor(e,r,a){this.baseURL=e.replace(/\/$/,""),this.tokenManager=r,this.onAuthenticationRequired=a}setAuthenticationRequiredCallback(e){this.onAuthenticationRequired=e}async request(e,r={}){let a=`${this.baseURL}${e}`,i=await this.prepareRequestOptions(r),o=await fetch(a,i);return o.status===401&&this.tokenManager&&(o=await this.handleUnauthorized(a,i)),o}async get(e,r={}){return this.request(e,{...r,method:"GET"})}async post(e,r,a={}){let i={...a,method:"POST",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async put(e,r,a={}){let i={...a,method:"PUT",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async delete(e,r={}){return this.request(e,{...r,method:"DELETE"})}async prepareRequestOptions(e){let r={"User-Agent":fF(),...e.headers};if(this.tokenManager)try{let a=await this.tokenManager.getAccessToken();a?r.Authorization=`Bearer ${a}`:BA("warn","\u26A0\uFE0F No access token available")}catch(a){BA("warn","\u26A0\uFE0F Failed to get access token:",a),this.onAuthenticationRequired&&a instanceof Error&&a.message?.includes("authentication required")&&(BA("log","\u{1F504} Triggering authentication flow..."),this.onAuthenticationRequired())}return{...e,headers:r}}async handleUnauthorized(e,r){if(this.isRefreshing)return new Promise((a,i)=>{this.requestQueue.push({resolve:a,reject:i,request:()=>fetch(e,r)})});this.isRefreshing=!0;try{BA("log","\u{1F504} Access token expired, attempting refresh...");let a=await this.tokenManager.refreshAccessToken();if(a){BA("log","\u2705 Token refreshed successfully");let i={...r,headers:{...r.headers,Authorization:`Bearer ${a}`}},o=fetch(e,i);return this.processRequestQueue(a),await o}else throw new Error("Failed to refresh token")}catch(a){throw console.error("\u274C Token refresh failed:",a),this.tokenManager.clearTokens?await this.tokenManager.clearTokens():this.tokenManager.clear&&this.tokenManager.clear(),this.rejectRequestQueue(new Error("Authentication required")),this.onAuthenticationRequired&&(BA("log","\u{1F504} Authentication required, triggering auth flow..."),this.onAuthenticationRequired()),new s5e("Authentication required - please re-authenticate")}finally{this.isRefreshing=!1}}processRequestQueue(e){this.requestQueue.splice(0).forEach(({resolve:a,reject:i,request:o})=>{o().then(t=>a(t)).catch(t=>i(t))})}rejectRequestQueue(e){this.requestQueue.splice(0).forEach(({reject:a})=>{a(e)})}static async checkResponse(e){if(!e.ok){let a=await e.text();throw new o5e(`HTTP ${e.status}: ${e.statusText}`,e.status,a)}let r=e.headers.get("content-type");return r&&r.includes("application/json")?await e.json():await e.text()}async requestJson(e,r={}){let a=await this.request(e,r);return n.checkResponse(a)}async postJson(e,r){let a=await this.post(e,r);return n.checkResponse(a)}async putJson(e,r){let a=await this.put(e,r);return n.checkResponse(a)}async getJson(e){let r=await this.get(e);return n.checkResponse(r)}async deleteJson(e){let r=await this.delete(e);return n.checkResponse(r)}},s5e=class extends Error{constructor(e){super(e),this.name="AuthenticationError"}},o5e=class extends Error{status;response;constructor(e,r,a){super(e),this.name="HttpError",this.status=r,this.response=a}}});function $Ra(n){return Wle.getInstance(n)}function e5a(n){let e=Wle.getInstance(n);return()=>e.handleAuthenticationRequired()}var Wle,KAr=De(()=>{"use strict";ble();Wle=class n{static instance=null;config;isAuthenticating=!1;constructor(e={}){this.config={authUrl:"/auth",autoOpenBrowser:!0,...e}}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}updateConfig(e){this.config={...this.config,...e}}async handleAuthenticationRequired(){if(this.isAuthenticating){console.log("[AuthNavigator] Authentication already in progress, skipping...");return}this.isAuthenticating=!0;try{console.log("\u{1F510} [AuthNavigator] Authentication required"),Dc.getInstance().clear(),this.config.customAuthHandler?(console.log("[AuthNavigator] Using custom authentication handler"),await this.config.customAuthHandler()):await this.handleDefaultAuthentication()}catch(e){console.error("[AuthNavigator] Authentication handling failed:",e)}finally{this.isAuthenticating=!1}}async handleDefaultAuthentication(){console.log("[AuthNavigator] Starting default authentication flow"),typeof process<"u"&&process.argv?await this.handleCLIAuthentication():await this.handleWebAuthentication()}async handleCLIAuthentication(){console.log(""),console.log("\u{1F510} \u8BA4\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u9700\u8981\u91CD\u65B0\u8BA4\u8BC1"),console.log("\u{1F4A1} \u8BF7\u5728CLI\u4E2D\u8F93\u5165 /auth \u547D\u4EE4\u8FDB\u884C\u91CD\u65B0\u8BA4\u8BC1"),console.log("")}async handleWebAuthentication(){if(typeof window<"u"){let a=`${Dc.getInstance().getProxyServerUrl()}${this.config.authUrl}`;console.log(`[AuthNavigator] Redirecting to auth page: ${a}`),window.location.href=a}else console.error("[AuthNavigator] Cannot redirect in non-browser environment")}isInProgress(){return this.isAuthenticating}}});import*as l5e from"fs";import*as x2 from"path";function t5a(){return typeof globalThis.__dirname=="string"?globalThis.__dirname:""}var Nle,kIt,$Ar=De(()=>{"use strict";Nle=t5a(),kIt=class{static cache=new Map;static customBasePath=null;static setBasePath(e){this.customBasePath=e,console.log(`\u{1F4C1} [AuthTemplates] Custom base path set: ${e}`)}static getAuthSelectPage(){return this.loadTemplate("authSelectPage.html")}static getFeishuSuccessPage(){return this.generateFeishuSuccessTemplate()}static getDeepvlabSuccessPage(){return this.generateDeepvlabSuccessTemplate()}static getErrorPage(e){return this.generateErrorTemplate(e)}static loadTemplate(e){if(this.cache.has(e))return this.cache.get(e);try{let r=[];if(this.customBasePath&&(r.push(x2.join(this.customBasePath,"dist","bundled","auth","login","templates",e)),r.push(x2.join(this.customBasePath,"bundled","auth","login","templates",e)),r.push(x2.join(this.customBasePath,"auth","login","templates",e))),Nle&&r.push(x2.join(Nle,e)),Nle){let o=Nle;for(let t=0;t<10;t++)r.push(x2.join(o,"bundled","auth","login","templates",e)),r.push(x2.join(o,"bundled",e)),r.push(x2.join(o,"bundle","login","templates",e)),r.push(x2.join(o,"auth","login","templates",e)),o=x2.dirname(o)}if(typeof process<"u"&&process.cwd)try{let o=process.cwd();r.push(x2.join(o,"bundle","login","templates",e)),r.push(x2.join(o,"dist","bundled","auth","login","templates",e)),r.push(x2.join(o,"bundled","auth","login","templates",e)),r.push(x2.join(o,"auth","login","templates",e))}catch{}let a=null;for(let o of r)try{if(l5e.existsSync(o)){a=o,console.error(`\u2705 [AuthTemplates] Template loaded: ${e} from ${o}`);break}}catch{continue}if(!a){if(console.warn(`\u26A0\uFE0F [AuthTemplates] Template ${e} not found in any location.`),console.warn(` Tried ${r.length} paths. First 5:`),r.slice(0,5).forEach((o,t)=>console.warn(` ${t+1}. ${o}`)),console.warn(` Current dirname: ${Nle||"(unavailable - cross-platform build)"}`),console.warn(` Custom base path: ${this.customBasePath||"(not set)"}`),typeof process<"u"&&process.cwd)try{console.warn(` Process cwd: ${process.cwd()}`)}catch{console.warn(" Process cwd: unavailable")}return console.log(`\u2139\uFE0F [AuthTemplates] Using fallback template for ${e}`),this.generateBasicAuthSelectTemplate()}let i=l5e.readFileSync(a,"utf-8");return this.cache.set(e,i),i}catch(r){return console.error(`\u274C [AuthTemplates] Failed to load template ${e}:`,r),this.generateBasicAuthSelectTemplate()}}static generateBasicAuthSelectTemplate(){return`
4051
+ \u{1F4CB} Full Capabilities:`),console.log(JSON.stringify(r.capabilities,null,2)))}function kRa(n){let e=r5e(n);return e.isSmallModel||e.needsSpecialHandling}function SRa(n){let e=r5e(n);return e.capabilities.toolCallReliability==="high"?"\u2705 Excellent tool calling compatibility":e.capabilities.toolCallReliability==="medium"?"\u{1F7E1} Good compatibility with enhanced error handling":"\u{1F7E0} Limited compatibility - enhanced robustness features active"}var kAr=De(()=>{"use strict";qee();});import*as TZ from"fs";import*as n5e from"path";var LRa,gle,SAr=De(()=>{"use strict";Zd();LRa="healthy-use-reminder.json",gle=class{projectRoot;stateFilePath;constructor(e){this.projectRoot=e;let r=AG(e);this.stateFilePath=n5e.join(r,LRa)}shouldShowReminder(){let r=new Date().getHours();if(!(r>=22||r<6))return this.clearState(),!1;let i=this.loadState();if(!i||i.lastReminderShownAt===0)return!0;let o=2700*1e3;return Date.now()-i.lastReminderShownAt>=o}markReminderShown(){this.saveState({lastReminderShownAt:Date.now()})}clearState(){try{TZ.existsSync(this.stateFilePath)&&TZ.unlinkSync(this.stateFilePath)}catch(e){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to clear state:",e)}}loadState(){try{if(!TZ.existsSync(this.stateFilePath))return null;let e=TZ.readFileSync(this.stateFilePath,"utf-8");return JSON.parse(e)}catch(e){return process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to load state:",e),null}}saveState(e){try{let r=n5e.dirname(this.stateFilePath);TZ.existsSync(r)||TZ.mkdirSync(r,{recursive:!0}),TZ.writeFileSync(this.stateFilePath,JSON.stringify(e,null,2),"utf-8")}catch(r){process.env.DEBUG&&console.error("[HealthyUseReminderState] Failed to save state:",r)}}}});var EIt,xIt,JRa,BRa,TRa,LAr=De(()=>{"use strict";EIt="--- Content from referenced files ---",xIt="--- End of content ---",JRa=2e3,BRa=2e3,TRa=20});function BAr(...n){return DRa(...n)}function TAr(...n){return ORa(...n)}function JAr(n,e){return n in e}function CIt(){let n={get(i,o){if(o==="write")return BAr;if(JAr(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},e=new Proxy(process.stdout,n),r={get(i,o){if(o==="write")return TAr;if(JAr(o,i)){let t=i[o];return typeof t=="function"?t.bind(i):t}}},a=new Proxy(process.stderr,r);return{stdout:e,stderr:a}}var DRa,ORa,DAr=De(()=>{"use strict";DRa=process.stdout.write.bind(process.stdout),ORa=process.stderr.write.bind(process.stderr)});import{readFile as MRa}from"node:fs/promises";import{fileURLToPath as URa}from"node:url";import YIt from"node:path";function zRa(){let n=globalThis.import?.meta??void 0;try{let r=typeof import.meta<"u"?import.meta.url:void 0;if(r)return YIt.dirname(URa(r))}catch{}let e=globalThis.__dirname;return typeof e=="string"?e:process.cwd()}function TR(){return vle||(vle=(async()=>"1.1.134")(),vle)}function _Ra(){vle=void 0}var vle,VIt=De(()=>{"use strict";});function PRa(n="latest"){let e=n?.trim().toLowerCase();return OAr.includes(e)?e:MAr}var OAr,MAr,UAr=De(()=>{"use strict";OAr=["stable","latest"],MAr="stable"});import{EventEmitter as jRa}from"node:events";var yle,QIt,HIt,zAr=De(()=>{"use strict";(function(n){n.ApprovalModeChanged="approval_mode_changed"})(yle||(yle={}));QIt=class{emitter=new jRa;on(e,r){return this.emitter.on(e,r),()=>this.emitter.off(e,r)}off(e,r){this.emitter.off(e,r)}emit(e,r){this.emitter.emit(e,r)}removeAllListeners(e){e?this.emitter.removeAllListeners(e):this.emitter.removeAllListeners()}},HIt=new QIt});function a5e(n){return Array.isArray(n)?n.map(e=>typeof e=="string"?{text:e}:e):typeof n=="string"?[{text:n}]:[n]}function qRa(n){return n.map(e=>typeof e.text=="string"?e.text:"").join("")}function XIt(n){if(!n||n.length===0)return[];let e=[];for(let r of n){if(r.role&&(r.parts||r.content!==void 0)){let a=r.parts??a5e(r.content);e.push({role:r.role,parts:a});continue}if(!(r.type==="info"||r.type==="error"||r.type==="warning")){if(r.type==="user"){let a=r.content!==void 0?a5e(r.content):[],i=qRa(a).trim();if(i.startsWith("/")||i.startsWith("?")||a.length===0)continue;e.push({role:"user",parts:a});continue}if(r.type==="gemini"){let a=[];if(r.thoughts&&r.thoughts.length>0)for(let o of r.thoughts){let t=o.subject?`**${o.subject}** ${o.description}`:o.description;a.push({text:t,thought:!0})}let i=!!r.toolCalls&&r.toolCalls.length>0;if(r.content!==void 0&&a.push(...a5e(r.content)),i)for(let o of r.toolCalls)a.push({functionCall:{name:o.name,args:o.args,...o.id?{id:o.id}:{}}});if(a.length>0&&e.push({role:"model",parts:a}),i){let o=[];for(let t of r.toolCalls)t.result!==void 0&&(typeof t.result=="string"?o.push({functionResponse:{id:t.id,name:t.name,response:{output:t.result}}}):Array.isArray(t.result)?o.push(...a5e(t.result)):o.push(t.result));o.length>0&&e.push({role:"user",parts:o})}}}}return e}var _Ar=De(()=>{"use strict";});var e6,PAr,Zle,jAr=De(()=>{"use strict";e6=class n extends Error{constructor(e){super(e),this.name="SessionError"}static noSessionsFound(){return new n("No persisted sessions found.")}static invalidSessionIdentifier(e,r){return new n(`Session '${e}' was not found under ${r}.`)}},PAr="latest",Zle=class{manager;constructor(e){this.manager=e}async sessionExists(e){return(await this.listAllMetadata()).some(a=>a.sessionId===e)}async listSessions(){return(await this.listAllMetadata()).map(r=>({id:r.sessionId,startTime:r.createdAt,title:r.title,messageCount:r.messageCount})).sort((r,a)=>new Date(r.startTime).getTime()-new Date(a.startTime).getTime())}async findSession(e){let r=e.trim(),a=await this.listSessions();if(a.length===0)throw e6.noSessionsFound();let i=a.find(t=>t.id===r);if(i)return i;let o=Number.parseInt(r,10);if(Number.isInteger(o)&&o.toString()===r&&o>0&&o<=a.length)return a[o-1];throw e6.invalidSessionIdentifier(r,"sessions/")}async resolveSession(e){let r=e.trim(),a;if(r===PAr){let o=await this.listSessions();if(o.length===0)throw e6.noSessionsFound();a=o[o.length-1]}else a=await this.findSession(r);let i=await this.manager.loadSession(a.id);if(!i)throw new e6(`Session '${a.id}' exists in index but could not be loaded.`);return{session:a,data:i}}async listAllMetadata(){let e=this.manager;return typeof e.listSessions=="function"?await e.listSessions():typeof e.getSessionIndex=="function"?(await e.getSessionIndex())?.sessions??[]:[]}}});function KRa(n,e,r){return new i5e(n,e,r)}var i5e,s5e,o5e,qAr=De(()=>{"use strict";Oee();bL();i5e=class n{tokenManager;baseURL;requestQueue=[];isRefreshing=!1;onAuthenticationRequired;constructor(e,r,a){this.baseURL=e.replace(/\/$/,""),this.tokenManager=r,this.onAuthenticationRequired=a}setAuthenticationRequiredCallback(e){this.onAuthenticationRequired=e}async request(e,r={}){let a=`${this.baseURL}${e}`,i=await this.prepareRequestOptions(r),o=await fetch(a,i);return o.status===401&&this.tokenManager&&(o=await this.handleUnauthorized(a,i)),o}async get(e,r={}){return this.request(e,{...r,method:"GET"})}async post(e,r,a={}){let i={...a,method:"POST",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async put(e,r,a={}){let i={...a,method:"PUT",body:r?JSON.stringify(r):void 0};return r&&!a.headers?.["Content-Type"]&&(i.headers={"Content-Type":"application/json",...a.headers}),this.request(e,i)}async delete(e,r={}){return this.request(e,{...r,method:"DELETE"})}async prepareRequestOptions(e){let r={"User-Agent":fF(),...e.headers};if(this.tokenManager)try{let a=await this.tokenManager.getAccessToken();a?r.Authorization=`Bearer ${a}`:BA("warn","\u26A0\uFE0F No access token available")}catch(a){BA("warn","\u26A0\uFE0F Failed to get access token:",a),this.onAuthenticationRequired&&a instanceof Error&&a.message?.includes("authentication required")&&(BA("log","\u{1F504} Triggering authentication flow..."),this.onAuthenticationRequired())}return{...e,headers:r}}async handleUnauthorized(e,r){if(this.isRefreshing)return new Promise((a,i)=>{this.requestQueue.push({resolve:a,reject:i,request:()=>fetch(e,r)})});this.isRefreshing=!0;try{BA("log","\u{1F504} Access token expired, attempting refresh...");let a=await this.tokenManager.refreshAccessToken();if(a){BA("log","\u2705 Token refreshed successfully");let i={...r,headers:{...r.headers,Authorization:`Bearer ${a}`}},o=fetch(e,i);return this.processRequestQueue(a),await o}else throw new Error("Failed to refresh token")}catch(a){throw console.error("\u274C Token refresh failed:",a),this.tokenManager.clearTokens?await this.tokenManager.clearTokens():this.tokenManager.clear&&this.tokenManager.clear(),this.rejectRequestQueue(new Error("Authentication required")),this.onAuthenticationRequired&&(BA("log","\u{1F504} Authentication required, triggering auth flow..."),this.onAuthenticationRequired()),new s5e("Authentication required - please re-authenticate")}finally{this.isRefreshing=!1}}processRequestQueue(e){this.requestQueue.splice(0).forEach(({resolve:a,reject:i,request:o})=>{o().then(t=>a(t)).catch(t=>i(t))})}rejectRequestQueue(e){this.requestQueue.splice(0).forEach(({reject:a})=>{a(e)})}static async checkResponse(e){if(!e.ok){let a=await e.text();throw new o5e(`HTTP ${e.status}: ${e.statusText}`,e.status,a)}let r=e.headers.get("content-type");return r&&r.includes("application/json")?await e.json():await e.text()}async requestJson(e,r={}){let a=await this.request(e,r);return n.checkResponse(a)}async postJson(e,r){let a=await this.post(e,r);return n.checkResponse(a)}async putJson(e,r){let a=await this.put(e,r);return n.checkResponse(a)}async getJson(e){let r=await this.get(e);return n.checkResponse(r)}async deleteJson(e){let r=await this.delete(e);return n.checkResponse(r)}},s5e=class extends Error{constructor(e){super(e),this.name="AuthenticationError"}},o5e=class extends Error{status;response;constructor(e,r,a){super(e),this.name="HttpError",this.status=r,this.response=a}}});function $Ra(n){return Wle.getInstance(n)}function e5a(n){let e=Wle.getInstance(n);return()=>e.handleAuthenticationRequired()}var Wle,KAr=De(()=>{"use strict";ble();Wle=class n{static instance=null;config;isAuthenticating=!1;constructor(e={}){this.config={authUrl:"/auth",autoOpenBrowser:!0,...e}}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}updateConfig(e){this.config={...this.config,...e}}async handleAuthenticationRequired(){if(this.isAuthenticating){console.log("[AuthNavigator] Authentication already in progress, skipping...");return}this.isAuthenticating=!0;try{console.log("\u{1F510} [AuthNavigator] Authentication required"),Dc.getInstance().clear(),this.config.customAuthHandler?(console.log("[AuthNavigator] Using custom authentication handler"),await this.config.customAuthHandler()):await this.handleDefaultAuthentication()}catch(e){console.error("[AuthNavigator] Authentication handling failed:",e)}finally{this.isAuthenticating=!1}}async handleDefaultAuthentication(){console.log("[AuthNavigator] Starting default authentication flow"),typeof process<"u"&&process.argv?await this.handleCLIAuthentication():await this.handleWebAuthentication()}async handleCLIAuthentication(){console.log(""),console.log("\u{1F510} \u8BA4\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u9700\u8981\u91CD\u65B0\u8BA4\u8BC1"),console.log("\u{1F4A1} \u8BF7\u5728CLI\u4E2D\u8F93\u5165 /auth \u547D\u4EE4\u8FDB\u884C\u91CD\u65B0\u8BA4\u8BC1"),console.log("")}async handleWebAuthentication(){if(typeof window<"u"){let a=`${Dc.getInstance().getProxyServerUrl()}${this.config.authUrl}`;console.log(`[AuthNavigator] Redirecting to auth page: ${a}`),window.location.href=a}else console.error("[AuthNavigator] Cannot redirect in non-browser environment")}isInProgress(){return this.isAuthenticating}}});import*as l5e from"fs";import*as x2 from"path";function t5a(){return typeof globalThis.__dirname=="string"?globalThis.__dirname:""}var Nle,kIt,$Ar=De(()=>{"use strict";Nle=t5a(),kIt=class{static cache=new Map;static customBasePath=null;static setBasePath(e){this.customBasePath=e,console.log(`\u{1F4C1} [AuthTemplates] Custom base path set: ${e}`)}static getAuthSelectPage(){return this.loadTemplate("authSelectPage.html")}static getFeishuSuccessPage(){return this.generateFeishuSuccessTemplate()}static getDeepvlabSuccessPage(){return this.generateDeepvlabSuccessTemplate()}static getErrorPage(e){return this.generateErrorTemplate(e)}static loadTemplate(e){if(this.cache.has(e))return this.cache.get(e);try{let r=[];if(this.customBasePath&&(r.push(x2.join(this.customBasePath,"dist","bundled","auth","login","templates",e)),r.push(x2.join(this.customBasePath,"bundled","auth","login","templates",e)),r.push(x2.join(this.customBasePath,"auth","login","templates",e))),Nle&&r.push(x2.join(Nle,e)),Nle){let o=Nle;for(let t=0;t<10;t++)r.push(x2.join(o,"bundled","auth","login","templates",e)),r.push(x2.join(o,"bundled",e)),r.push(x2.join(o,"bundle","login","templates",e)),r.push(x2.join(o,"auth","login","templates",e)),o=x2.dirname(o)}if(typeof process<"u"&&process.cwd)try{let o=process.cwd();r.push(x2.join(o,"bundle","login","templates",e)),r.push(x2.join(o,"dist","bundled","auth","login","templates",e)),r.push(x2.join(o,"bundled","auth","login","templates",e)),r.push(x2.join(o,"auth","login","templates",e))}catch{}let a=null;for(let o of r)try{if(l5e.existsSync(o)){a=o,console.error(`\u2705 [AuthTemplates] Template loaded: ${e} from ${o}`);break}}catch{continue}if(!a){if(console.warn(`\u26A0\uFE0F [AuthTemplates] Template ${e} not found in any location.`),console.warn(` Tried ${r.length} paths. First 5:`),r.slice(0,5).forEach((o,t)=>console.warn(` ${t+1}. ${o}`)),console.warn(` Current dirname: ${Nle||"(unavailable - cross-platform build)"}`),console.warn(` Custom base path: ${this.customBasePath||"(not set)"}`),typeof process<"u"&&process.cwd)try{console.warn(` Process cwd: ${process.cwd()}`)}catch{console.warn(" Process cwd: unavailable")}return console.log(`\u2139\uFE0F [AuthTemplates] Using fallback template for ${e}`),this.generateBasicAuthSelectTemplate()}let i=l5e.readFileSync(a,"utf-8");return this.cache.set(e,i),i}catch(r){return console.error(`\u274C [AuthTemplates] Failed to load template ${e}:`,r),this.generateBasicAuthSelectTemplate()}}static generateBasicAuthSelectTemplate(){return`
4052
4052
  <!DOCTYPE html>
4053
4053
  <html>
4054
4054
  <head>
@@ -5483,7 +5483,7 @@ ${c}`),a?i.reset(c):c}function qYa(n,e,r,a={}){if(!HVr){HVr=!0;let o="Passing li
5483
5483
 
5484
5484
  ${e}
5485
5485
  `:""}`}set message(e){this.#r=e}#a(e){if(!this.#t)return;let r=this.#e,a=tVa(r,this.#t.message);if(a)return(0,OVr.codeFrameColumns)(r,{start:a},{highlightCode:e})}get codeFrame(){return this.#n??=this.#a(!0),this.#n}get rawCodeFrame(){return this.#i??=this.#a(!1),this.#i}},tVa=(n,e)=>{let r=e.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!r)return;let{index:a,line:i,column:o}=r.groups;return i&&o?{line:Number(i),column:Number(o)}:_0t(n,Number(a),{oneBased:!0})},rVa=n=>n.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(e,r,a)=>`"${a}"(${eVa(a)})`)});var gce=Le((ygs,UVr)=>{"use strict";var nVa=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};UVr.exports=nVa});var vce=Le((Zgs,zVr)=>{"use strict";var aVa="2.0.0",iVa=Number.MAX_SAFE_INTEGER||9007199254740991,sVa=16,oVa=250,lVa=["major","premajor","minor","preminor","patch","prepatch","prerelease"];zVr.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:sVa,MAX_SAFE_BUILD_LENGTH:oVa,MAX_SAFE_INTEGER:iVa,RELEASE_TYPES:lVa,SEMVER_SPEC_VERSION:aVa,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var H_=Le((r5,_Vr)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:q0t,MAX_SAFE_BUILD_LENGTH:cVa,MAX_LENGTH:uVa}=vce(),dVa=gce();r5=_Vr.exports={};var IVa=r5.re=[],hVa=r5.safeRe=[],Ea=r5.src=[],mVa=r5.safeSrc=[],xa=r5.t={},pVa=0,K0t="[a-zA-Z0-9-]",bVa=[["\\s",1],["\\d",uVa],[K0t,cVa]],fVa=n=>{for(let[e,r]of bVa)n=n.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return n},Gs=(n,e,r)=>{let a=fVa(e),i=pVa++;dVa(n,i,e),xa[n]=i,Ea[i]=e,mVa[i]=a,IVa[i]=new RegExp(e,r?"g":void 0),hVa[i]=new RegExp(a,r?"g":void 0)};Gs("NUMERICIDENTIFIER","0|[1-9]\\d*");Gs("NUMERICIDENTIFIERLOOSE","\\d+");Gs("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${K0t}*`);Gs("MAINVERSION",`(${Ea[xa.NUMERICIDENTIFIER]})\\.(${Ea[xa.NUMERICIDENTIFIER]})\\.(${Ea[xa.NUMERICIDENTIFIER]})`);Gs("MAINVERSIONLOOSE",`(${Ea[xa.NUMERICIDENTIFIERLOOSE]})\\.(${Ea[xa.NUMERICIDENTIFIERLOOSE]})\\.(${Ea[xa.NUMERICIDENTIFIERLOOSE]})`);Gs("PRERELEASEIDENTIFIER",`(?:${Ea[xa.NONNUMERICIDENTIFIER]}|${Ea[xa.NUMERICIDENTIFIER]})`);Gs("PRERELEASEIDENTIFIERLOOSE",`(?:${Ea[xa.NONNUMERICIDENTIFIER]}|${Ea[xa.NUMERICIDENTIFIERLOOSE]})`);Gs("PRERELEASE",`(?:-(${Ea[xa.PRERELEASEIDENTIFIER]}(?:\\.${Ea[xa.PRERELEASEIDENTIFIER]})*))`);Gs("PRERELEASELOOSE",`(?:-?(${Ea[xa.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${Ea[xa.PRERELEASEIDENTIFIERLOOSE]})*))`);Gs("BUILDIDENTIFIER",`${K0t}+`);Gs("BUILD",`(?:\\+(${Ea[xa.BUILDIDENTIFIER]}(?:\\.${Ea[xa.BUILDIDENTIFIER]})*))`);Gs("FULLPLAIN",`v?${Ea[xa.MAINVERSION]}${Ea[xa.PRERELEASE]}?${Ea[xa.BUILD]}?`);Gs("FULL",`^${Ea[xa.FULLPLAIN]}$`);Gs("LOOSEPLAIN",`[v=\\s]*${Ea[xa.MAINVERSIONLOOSE]}${Ea[xa.PRERELEASELOOSE]}?${Ea[xa.BUILD]}?`);Gs("LOOSE",`^${Ea[xa.LOOSEPLAIN]}$`);Gs("GTLT","((?:<|>)?=?)");Gs("XRANGEIDENTIFIERLOOSE",`${Ea[xa.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Gs("XRANGEIDENTIFIER",`${Ea[xa.NUMERICIDENTIFIER]}|x|X|\\*`);Gs("XRANGEPLAIN",`[v=\\s]*(${Ea[xa.XRANGEIDENTIFIER]})(?:\\.(${Ea[xa.XRANGEIDENTIFIER]})(?:\\.(${Ea[xa.XRANGEIDENTIFIER]})(?:${Ea[xa.PRERELEASE]})?${Ea[xa.BUILD]}?)?)?`);Gs("XRANGEPLAINLOOSE",`[v=\\s]*(${Ea[xa.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Ea[xa.XRANGEIDENTIFIERLOOSE]})(?:\\.(${Ea[xa.XRANGEIDENTIFIERLOOSE]})(?:${Ea[xa.PRERELEASELOOSE]})?${Ea[xa.BUILD]}?)?)?`);Gs("XRANGE",`^${Ea[xa.GTLT]}\\s*${Ea[xa.XRANGEPLAIN]}$`);Gs("XRANGELOOSE",`^${Ea[xa.GTLT]}\\s*${Ea[xa.XRANGEPLAINLOOSE]}$`);Gs("COERCEPLAIN",`(^|[^\\d])(\\d{1,${q0t}})(?:\\.(\\d{1,${q0t}}))?(?:\\.(\\d{1,${q0t}}))?`);Gs("COERCE",`${Ea[xa.COERCEPLAIN]}(?:$|[^\\d])`);Gs("COERCEFULL",Ea[xa.COERCEPLAIN]+`(?:${Ea[xa.PRERELEASE]})?(?:${Ea[xa.BUILD]})?(?:$|[^\\d])`);Gs("COERCERTL",Ea[xa.COERCE],!0);Gs("COERCERTLFULL",Ea[xa.COERCEFULL],!0);Gs("LONETILDE","(?:~>?)");Gs("TILDETRIM",`(\\s*)${Ea[xa.LONETILDE]}\\s+`,!0);r5.tildeTrimReplace="$1~";Gs("TILDE",`^${Ea[xa.LONETILDE]}${Ea[xa.XRANGEPLAIN]}$`);Gs("TILDELOOSE",`^${Ea[xa.LONETILDE]}${Ea[xa.XRANGEPLAINLOOSE]}$`);Gs("LONECARET","(?:\\^)");Gs("CARETTRIM",`(\\s*)${Ea[xa.LONECARET]}\\s+`,!0);r5.caretTrimReplace="$1^";Gs("CARET",`^${Ea[xa.LONECARET]}${Ea[xa.XRANGEPLAIN]}$`);Gs("CARETLOOSE",`^${Ea[xa.LONECARET]}${Ea[xa.XRANGEPLAINLOOSE]}$`);Gs("COMPARATORLOOSE",`^${Ea[xa.GTLT]}\\s*(${Ea[xa.LOOSEPLAIN]})$|^$`);Gs("COMPARATOR",`^${Ea[xa.GTLT]}\\s*(${Ea[xa.FULLPLAIN]})$|^$`);Gs("COMPARATORTRIM",`(\\s*)${Ea[xa.GTLT]}\\s*(${Ea[xa.LOOSEPLAIN]}|${Ea[xa.XRANGEPLAIN]})`,!0);r5.comparatorTrimReplace="$1$2$3";Gs("HYPHENRANGE",`^\\s*(${Ea[xa.XRANGEPLAIN]})\\s+-\\s+(${Ea[xa.XRANGEPLAIN]})\\s*$`);Gs("HYPHENRANGELOOSE",`^\\s*(${Ea[xa.XRANGEPLAINLOOSE]})\\s+-\\s+(${Ea[xa.XRANGEPLAINLOOSE]})\\s*$`);Gs("STAR","(<|>)?=?\\s*\\*");Gs("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Gs("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var $Ae=Le((Wgs,PVr)=>{"use strict";var GVa=Object.freeze({loose:!0}),gVa=Object.freeze({}),vVa=n=>n?typeof n!="object"?GVa:n:gVa;PVr.exports=vVa});var $0t=Le((Ngs,KVr)=>{"use strict";var jVr=/^[0-9]+$/,qVr=(n,e)=>{if(typeof n=="number"&&typeof e=="number")return n===e?0:n<e?-1:1;let r=jVr.test(n),a=jVr.test(e);return r&&a&&(n=+n,e=+e),n===e?0:r&&!a?-1:a&&!r?1:n<e?-1:1},yVa=(n,e)=>qVr(e,n);KVr.exports={compareIdentifiers:qVr,rcompareIdentifiers:yVa}});var rf=Le((Fgs,eQr)=>{"use strict";var eEe=gce(),{MAX_LENGTH:$Vr,MAX_SAFE_INTEGER:tEe}=vce(),{safeRe:rEe,t:nEe}=H_(),ZVa=$Ae(),{compareIdentifiers:emt}=$0t(),tmt=class n{constructor(e,r){if(r=ZVa(r),e instanceof n){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>$Vr)throw new TypeError(`version is longer than ${$Vr} characters`);eEe("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let a=e.trim().match(r.loose?rEe[nEe.LOOSE]:rEe[nEe.FULL]);if(!a)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+a[1],this.minor=+a[2],this.patch=+a[3],this.major>tEe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>tEe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>tEe||this.patch<0)throw new TypeError("Invalid patch version");a[4]?this.prerelease=a[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let o=+i;if(o>=0&&o<tEe)return o}return i}):this.prerelease=[],this.build=a[5]?a[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(eEe("SemVer.compare",this.version,this.options,e),!(e instanceof n)){if(typeof e=="string"&&e===this.version)return 0;e=new n(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof n||(e=new n(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof n||(e=new n(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let a=this.prerelease[r],i=e.prerelease[r];if(eEe("prerelease compare",r,a,i),a===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(a===void 0)return-1;if(a===i)continue;return emt(a,i)}while(++r)}compareBuild(e){e instanceof n||(e=new n(e,this.options));let r=0;do{let a=this.build[r],i=e.build[r];if(eEe("build compare",r,a,i),a===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(a===void 0)return-1;if(a===i)continue;return emt(a,i)}while(++r)}inc(e,r,a){if(e.startsWith("pre")){if(!r&&a===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let i=`-${r}`.match(this.options.loose?rEe[nEe.PRERELEASELOOSE]:rEe[nEe.PRERELEASE]);if(!i||i[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,a);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,a);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,a),this.inc("pre",r,a);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,a),this.inc("pre",r,a);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(a)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&a===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(r){let o=[r,i];a===!1&&(o=[r]),emt(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};eQr.exports=tmt});var v6=Le((wgs,rQr)=>{"use strict";var tQr=rf(),WVa=(n,e,r=!1)=>{if(n instanceof tQr)return n;try{return new tQr(n,e)}catch(a){if(!r)return null;throw a}};rQr.exports=WVa});var rmt=Le((Rgs,nQr)=>{"use strict";var NVa=v6(),FVa=(n,e)=>{let r=NVa(n,e);return r?r.version:null};nQr.exports=FVa});var nmt=Le((Ags,aQr)=>{"use strict";var wVa=v6(),RVa=(n,e)=>{let r=wVa(n.trim().replace(/^[=v]+/,""),e);return r?r.version:null};aQr.exports=RVa});var amt=Le((Egs,AVa)=>{AVa.exports=["0BSD","3D-Slicer-1.0","AAL","ADSL","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AGPL-1.0-only","AGPL-1.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","AMD-newlib","AMDPLPA","AML","AML-glslang","AMPAS","ANTLR-PD","ANTLR-PD-fallback","APAFML","APL-1.0","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","ASWF-Digital-Assets-1.0","ASWF-Digital-Assets-1.1","Abstyles","AdaCore-doc","Adobe-2006","Adobe-Display-PostScript","Adobe-Glyph","Adobe-Utopia","Afmparse","Aladdin","Apache-1.0","Apache-1.1","Apache-2.0","App-s2p","Arphic-1999","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","Artistic-dist","Aspell-RU","BSD-1-Clause","BSD-2-Clause","BSD-2-Clause-Darwin","BSD-2-Clause-Patent","BSD-2-Clause-Views","BSD-2-Clause-first-lines","BSD-2-Clause-pkgconf-disclaimer","BSD-3-Clause","BSD-3-Clause-Attribution","BSD-3-Clause-Clear","BSD-3-Clause-HP","BSD-3-Clause-LBNL","BSD-3-Clause-Modification","BSD-3-Clause-No-Military-License","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-License-2014","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-Open-MPI","BSD-3-Clause-Sun","BSD-3-Clause-acpica","BSD-3-Clause-flex","BSD-4-Clause","BSD-4-Clause-Shortened","BSD-4-Clause-UC","BSD-4.3RENO","BSD-4.3TAHOE","BSD-Advertising-Acknowledgement","BSD-Attribution-HPND-disclaimer","BSD-Inferno-Nettverk","BSD-Protection","BSD-Source-Code","BSD-Source-beginning-file","BSD-Systemics","BSD-Systemics-W3Works","BSL-1.0","BUSL-1.1","Baekmuk","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","Bitstream-Charter","Bitstream-Vera","BlueOak-1.0.0","Boehm-GC","Boehm-GC-without-fee","Borceux","Brian-Gladman-2-Clause","Brian-Gladman-3-Clause","C-UDA-1.0","CAL-1.0","CAL-1.0-Combined-Work-Exception","CATOSL-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-2.5-AU","CC-BY-3.0","CC-BY-3.0-AT","CC-BY-3.0-AU","CC-BY-3.0-DE","CC-BY-3.0-IGO","CC-BY-3.0-NL","CC-BY-3.0-US","CC-BY-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-3.0-DE","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-3.0-DE","CC-BY-NC-ND-3.0-IGO","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.0-DE","CC-BY-NC-SA-2.0-FR","CC-BY-NC-SA-2.0-UK","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-3.0-DE","CC-BY-NC-SA-3.0-IGO","CC-BY-NC-SA-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-3.0-DE","CC-BY-ND-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.0-UK","CC-BY-SA-2.1-JP","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-3.0-AT","CC-BY-SA-3.0-DE","CC-BY-SA-3.0-IGO","CC-BY-SA-4.0","CC-PDDC","CC-PDM-1.0","CC-SA-1.0","CC0-1.0","CDDL-1.0","CDDL-1.1","CDL-1.0","CDLA-Permissive-1.0","CDLA-Permissive-2.0","CDLA-Sharing-1.0","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","CERN-OHL-1.1","CERN-OHL-1.2","CERN-OHL-P-2.0","CERN-OHL-S-2.0","CERN-OHL-W-2.0","CFITSIO","CMU-Mach","CMU-Mach-nodoc","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","COIL-1.0","CPAL-1.0","CPL-1.0","CPOL-1.02","CUA-OPL-1.0","Caldera","Caldera-no-preamble","Catharon","ClArtistic","Clips","Community-Spec-1.0","Condor-1.1","Cornell-Lossless-JPEG","Cronyx","Crossword","CryptoSwift","CrystalStacker","Cube","D-FSL-1.0","DEC-3-Clause","DL-DE-BY-2.0","DL-DE-ZERO-2.0","DOC","DRL-1.0","DRL-1.1","DSDP","DocBook-DTD","DocBook-Schema","DocBook-Stylesheet","DocBook-XML","Dotseqn","ECL-1.0","ECL-2.0","EFL-1.0","EFL-2.0","EPICS","EPL-1.0","EPL-2.0","EUDatagrid","EUPL-1.0","EUPL-1.1","EUPL-1.2","Elastic-2.0","Entessa","ErlPL-1.1","Eurosym","FBM","FDK-AAC","FSFAP","FSFAP-no-warranty-disclaimer","FSFUL","FSFULLR","FSFULLRSD","FSFULLRWD","FSL-1.1-ALv2","FSL-1.1-MIT","FTL","Fair","Ferguson-Twofish","Frameworx-1.0","FreeBSD-DOC","FreeImage","Furuseth","GCR-docs","GD","GFDL-1.1-invariants-only","GFDL-1.1-invariants-or-later","GFDL-1.1-no-invariants-only","GFDL-1.1-no-invariants-or-later","GFDL-1.1-only","GFDL-1.1-or-later","GFDL-1.2-invariants-only","GFDL-1.2-invariants-or-later","GFDL-1.2-no-invariants-only","GFDL-1.2-no-invariants-or-later","GFDL-1.2-only","GFDL-1.2-or-later","GFDL-1.3-invariants-only","GFDL-1.3-invariants-or-later","GFDL-1.3-no-invariants-only","GFDL-1.3-no-invariants-or-later","GFDL-1.3-only","GFDL-1.3-or-later","GL2PS","GLWTPL","GPL-1.0-only","GPL-1.0-or-later","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","Game-Programming-Gems","Giftware","Glide","Glulxe","Graphics-Gems","Gutmann","HDF5","HIDAPI","HP-1986","HP-1989","HPND","HPND-DEC","HPND-Fenneberg-Livingston","HPND-INRIA-IMAG","HPND-Intel","HPND-Kevlin-Henney","HPND-MIT-disclaimer","HPND-Markus-Kuhn","HPND-Netrek","HPND-Pbmplus","HPND-UC","HPND-UC-export-US","HPND-doc","HPND-doc-sell","HPND-export-US","HPND-export-US-acknowledgement","HPND-export-US-modify","HPND-export2-US","HPND-merchantability-variant","HPND-sell-MIT-disclaimer-xserver","HPND-sell-regexpr","HPND-sell-variant","HPND-sell-variant-MIT-disclaimer","HPND-sell-variant-MIT-disclaimer-rev","HTMLTIDY","HaskellReport","Hippocratic-2.1","IBM-pibs","ICU","IEC-Code-Components-EULA","IJG","IJG-short","IPA","IPL-1.0","ISC","ISC-Veillard","ImageMagick","Imlib2","Info-ZIP","Inner-Net-2.0","InnoSetup","Intel","Intel-ACPI","Interbase-1.0","JPL-image","JPNIC","JSON","Jam","JasPer-2.0","Kastrup","Kazlib","Knuth-CTAN","LAL-1.2","LAL-1.3","LGPL-2.0-only","LGPL-2.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","LGPLLR","LOOP","LPD-document","LPL-1.0","LPL-1.02","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","LZMA-SDK-9.11-to-9.20","LZMA-SDK-9.22","Latex2e","Latex2e-translated-notice","Leptonica","LiLiQ-P-1.1","LiLiQ-R-1.1","LiLiQ-Rplus-1.1","Libpng","Linux-OpenIB","Linux-man-pages-1-para","Linux-man-pages-copyleft","Linux-man-pages-copyleft-2-para","Linux-man-pages-copyleft-var","Lucida-Bitmap-Fonts","MIPS","MIT","MIT-0","MIT-CMU","MIT-Click","MIT-Festival","MIT-Khronos-old","MIT-Modern-Variant","MIT-Wu","MIT-advertising","MIT-enna","MIT-feh","MIT-open-group","MIT-testregex","MITNFA","MMIXware","MPEG-SSG","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","MS-LPL","MS-PL","MS-RL","MTLL","Mackerras-3-Clause","Mackerras-3-Clause-acknowledgment","MakeIndex","Martin-Birgmeier","McPhee-slideshow","Minpack","MirOS","Motosoto","MulanPSL-1.0","MulanPSL-2.0","Multics","Mup","NAIST-2003","NASA-1.3","NBPL-1.0","NCBI-PD","NCGL-UK-2.0","NCL","NCSA","NGPL","NICTA-1.0","NIST-PD","NIST-PD-fallback","NIST-Software","NLOD-1.0","NLOD-2.0","NLPL","NOSL","NPL-1.0","NPL-1.1","NPOSL-3.0","NRL","NTIA-PD","NTP","NTP-0","Naumen","NetCDF","Newsletr","Nokia","Noweb","O-UDA-1.0","OAR","OCCT-PL","OCLC-2.0","ODC-By-1.0","ODbL-1.0","OFFIS","OFL-1.0","OFL-1.0-RFN","OFL-1.0-no-RFN","OFL-1.1","OFL-1.1-RFN","OFL-1.1-no-RFN","OGC-1.0","OGDL-Taiwan-1.0","OGL-Canada-2.0","OGL-UK-1.0","OGL-UK-2.0","OGL-UK-3.0","OGTSL","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.2.2","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OLFL-1.3","OML","OPL-1.0","OPL-UK-3.0","OPUBL-1.0","OSET-PL-2.1","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenPBS-2.3","OpenSSL","OpenSSL-standalone","OpenVision","PADL","PDDL-1.0","PHP-3.0","PHP-3.01","PPL","PSF-2.0","Parity-6.0.0","Parity-7.0.0","Pixar","Plexus","PolyForm-Noncommercial-1.0.0","PolyForm-Small-Business-1.0.0","PostgreSQL","Python-2.0","Python-2.0.1","QPL-1.0","QPL-1.0-INRIA-2004","Qhull","RHeCos-1.1","RPL-1.1","RPL-1.5","RPSL-1.0","RSA-MD","RSCPL","Rdisc","Ruby","Ruby-pty","SAX-PD","SAX-PD-2.0","SCEA","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","SGI-OpenGL","SGP4","SHL-0.5","SHL-0.51","SISSL","SISSL-1.2","SL","SMAIL-GPL","SMLNJ","SMPPL","SNIA","SOFA","SPL-1.0","SSH-OpenSSH","SSH-short","SSLeay-standalone","SSPL-1.0","SUL-1.0","SWL","Saxpath","SchemeReport","Sendmail","Sendmail-8.23","Sendmail-Open-Source-1.1","SimPL-2.0","Sleepycat","Soundex","Spencer-86","Spencer-94","Spencer-99","SugarCRM-1.1.3","Sun-PPP","Sun-PPP-2000","SunPro","Symlinks","TAPR-OHL-1.0","TCL","TCP-wrappers","TGPPL-1.0","TMate","TORQUE-1.1","TOSL","TPDL","TPL-1.0","TTWL","TTYP0","TU-Berlin-1.0","TU-Berlin-2.0","TermReadKey","ThirdEye","TrustedQSL","UCAR","UCL-1.0","UMich-Merit","UPL-1.0","URT-RLE","Ubuntu-font-1.0","Unicode-3.0","Unicode-DFS-2015","Unicode-DFS-2016","Unicode-TOU","UnixCrypt","Unlicense","Unlicense-libtelnet","Unlicense-libwhirlpool","VOSTROM","VSL-1.0","Vim","W3C","W3C-19980720","W3C-20150513","WTFPL","Watcom-1.0","Widget-Workshop","Wsuipa","X11","X11-distribute-modifications-variant","X11-swapped","XFree86-1.1","XSkat","Xdebug-1.03","Xerox","Xfig","Xnet","YPL-1.0","YPL-1.1","ZPL-1.1","ZPL-2.0","ZPL-2.1","Zed","Zeeff","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","any-OSI","any-OSI-perl-modules","bcrypt-Solar-Designer","blessing","bzip2-1.0.6","check-cvs","checkmk","copyleft-next-0.3.0","copyleft-next-0.3.1","curl","cve-tou","diffmark","dtoa","dvipdfm","eGenix","etalab-2.0","fwlw","gSOAP-1.3b","generic-xts","gnuplot","gtkbook","hdparm","iMatix","jove","libpng-1.6.35","libpng-2.0","libselinux-1.0","libtiff","libutil-David-Nugent","lsof","magaz","mailprio","man2html","metamail","mpi-permissive","mpich2","mplus","ngrep","pkgconf","pnmstitch","psfrag","psutils","python-ldap","radvd","snprintf","softSurfer","ssh-keyscan","swrule","threeparttable","ulem","w3m","wwl","xinetd","xkeyboard-config-Zinoviev","xlock","xpp","xzoom","zlib-acknowledgement"]});var iQr=Le((xgs,EVa)=>{EVa.exports=["AGPL-1.0","AGPL-3.0","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-2.0-with-GCC-exception","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-3.0","GPL-3.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","LGPL-2.0","LGPL-2.1","LGPL-3.0","Net-SNMP","Nunit","StandardML-NJ","bzip2-1.0.5","eCos-2.0","wxWindows"]});var sQr=Le((Cgs,xVa)=>{xVa.exports=["389-exception","Asterisk-exception","Autoconf-exception-2.0","Autoconf-exception-3.0","Autoconf-exception-generic","Autoconf-exception-generic-3.0","Autoconf-exception-macro","Bison-exception-1.24","Bison-exception-2.2","Bootloader-exception","Classpath-exception-2.0","CLISP-exception-2.0","cryptsetup-OpenSSL-exception","DigiRule-FOSS-exception","eCos-exception-2.0","Fawkes-Runtime-exception","FLTK-exception","fmt-exception","Font-exception-2.0","freertos-exception-2.0","GCC-exception-2.0","GCC-exception-2.0-note","GCC-exception-3.1","Gmsh-exception","GNAT-exception","GNOME-examples-exception","GNU-compiler-exception","gnu-javamail-exception","GPL-3.0-interface-exception","GPL-3.0-linking-exception","GPL-3.0-linking-source-exception","GPL-CC-1.0","GStreamer-exception-2005","GStreamer-exception-2008","i2p-gpl-java-exception","KiCad-libraries-exception","LGPL-3.0-linking-exception","libpri-OpenH323-exception","Libtool-exception","Linux-syscall-note","LLGPL","LLVM-exception","LZMA-exception","mif-exception","OCaml-LGPL-linking-exception","OCCT-exception-1.0","OpenJDK-assembly-exception-1.0","openvpn-openssl-exception","PS-or-PDF-font-exception-20170817","QPL-1.0-INRIA-2004-exception","Qt-GPL-exception-1.0","Qt-LGPL-exception-1.1","Qwt-exception-1.0","SANE-exception","SHL-2.0","SHL-2.1","stunnel-exception","SWI-exception","Swift-exception","Texinfo-exception","u-boot-exception-2.0","UBDL-exception","Universal-FOSS-exception-1.0","vsftpd-openssl-exception","WxWindows-exception-3.1","x11vnc-openssl-exception"]});var lQr=Le((Ygs,oQr)=>{"use strict";var CVa=[].concat(amt()).concat(iQr()),YVa=sQr();oQr.exports=function(n){var e=0;function r(){return e<n.length}function a(y){if(y instanceof RegExp){var g=n.slice(e),Z=g.match(y);if(Z)return e+=Z[0].length,Z[0]}else if(n.indexOf(y,e)===e)return e+=y.length,y}function i(){a(/[ ]*/)}function o(){for(var y,g=["WITH","AND","OR","(",")",":","+"],Z=0;Z<g.length&&(y=a(g[Z]),!y);Z++);if(y==="+"&&e>1&&n[e-2]===" ")throw new Error("Space before `+`");return y&&{type:"OPERATOR",string:y}}function t(){return a(/[A-Za-z0-9-.]+/)}function s(){var y=t();if(!y)throw new Error("Expected idstring at offset "+e);return y}function d(){if(a("DocumentRef-")){var y=s();return{type:"DOCUMENTREF",string:y}}}function I(){if(a("LicenseRef-")){var y=s();return{type:"LICENSEREF",string:y}}}function u(){var y=e,g=t();if(CVa.indexOf(g)!==-1)return{type:"LICENSE",string:g};if(YVa.indexOf(g)!==-1)return{type:"EXCEPTION",string:g};e=y}function h(){return o()||d()||I()||u()}for(var c=[];r()&&(i(),!!r());){var m=h();if(!m)throw new Error("Unexpected `"+n[e]+"` at offset "+e);c.push(m)}return c}});var uQr=Le((Vgs,cQr)=>{"use strict";cQr.exports=function(n){var e=0;function r(){return e<n.length}function a(){return r()?n[e]:null}function i(){if(!r())throw new Error;e++}function o(g){var Z=a();if(Z&&Z.type==="OPERATOR"&&g===Z.string)return i(),Z.string}function t(){if(o("WITH")){var g=a();if(g&&g.type==="EXCEPTION")return i(),g.string;throw new Error("Expected exception after `WITH`")}}function s(){var g=e,Z="",v=a();if(v.type==="DOCUMENTREF"&&(i(),Z+="DocumentRef-"+v.string+":",!o(":")))throw new Error("Expected `:` after `DocumentRef-...`");if(v=a(),v.type==="LICENSEREF")return i(),Z+="LicenseRef-"+v.string,{license:Z};e=g}function d(){var g=a();if(g&&g.type==="LICENSE"){i();var Z={license:g.string};o("+")&&(Z.plus=!0);var v=t();return v&&(Z.exception=v),Z}}function I(){var g=o("(");if(g){var Z=m();if(!o(")"))throw new Error("Expected `)`");return Z}}function u(){return I()||s()||d()}function h(g,Z){return function v(){var E=Z();if(E){if(!o(g))return E;var w=v();if(!w)throw new Error("Expected expression");return{left:E,conjunction:g.toLowerCase(),right:w}}}}var c=h("AND",u),m=h("OR",c),y=m();if(!y||r())throw new Error("Syntax error");return y}});var imt=Le((Qgs,dQr)=>{"use strict";var VVa=lQr(),QVa=uQr();dQr.exports=function(n){return QVa(VVa(n))}});var vQr=Le((Hgs,gQr)=>{var HVa=imt(),XVa=amt();function aEe(n){try{return HVa(n),!0}catch{return!1}}function GQr(n,e){var r=e[0].length-n[0].length;return r!==0?r:n[0].toUpperCase().localeCompare(e[0].toUpperCase())}var IQr=[["APGL","AGPL"],["Gpl","GPL"],["GLP","GPL"],["APL","Apache"],["ISD","ISC"],["GLP","GPL"],["IST","ISC"],["Claude","Clause"],[" or later","+"],[" International",""],["GNU","GPL"],["GUN","GPL"],["+",""],["GNU GPL","GPL"],["GNU LGPL","LGPL"],["GNU/GPL","GPL"],["GNU GLP","GPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL"],["GNU Lesser General Public License","LGPL"],["GNU LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["GNU Lesser General Public License","LGPL-2.1"],["LESSER GENERAL PUBLIC LICENSE","LGPL"],["Lesser General Public License","LGPL"],["LESSER GENERAL PUBLIC LICENSE","LGPL-2.1"],["Lesser General Public License","LGPL-2.1"],["GNU General Public License","GPL"],["Gnu public license","GPL"],["GNU Public License","GPL"],["GNU GENERAL PUBLIC LICENSE","GPL"],["MTI","MIT"],["Mozilla Public License","MPL"],["Universal Permissive License","UPL"],["WTH","WTF"],["WTFGPL","WTFPL"],["-License",""]].sort(GQr),kVa=0,SVa=1,hQr=[function(n){return n.toUpperCase()},function(n){return n.trim()},function(n){return n.replace(/\./g,"")},function(n){return n.replace(/\s+/g,"")},function(n){return n.replace(/\s+/g,"-")},function(n){return n.replace("v","-")},function(n){return n.replace(/,?\s*(\d)/,"-$1")},function(n){return n.replace(/,?\s*(\d)/,"-$1.0")},function(n){return n.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2")},function(n){return n.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/,"-$2.0")},function(n){return n[0].toUpperCase()+n.slice(1)},function(n){return n.replace("/","-")},function(n){return n.replace(/\s*V\s*(\d)/,"-$1").replace(/(\d)$/,"$1.0")},function(n){return n.indexOf("3.0")!==-1?n+"-or-later":n+"-only"},function(n){return n+"only"},function(n){return n.replace(/(\d)$/,"-$1.0")},function(n){return n.replace(/(-| )?(\d)$/,"-$2-Clause")},function(n){return n.replace(/(-| )clause(-| )(\d)/,"-$3-Clause")},function(n){return n.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i,"BSD-3-Clause")},function(n){return n.replace(/\bSimplified(-| )?BSD((-| )License)?/i,"BSD-2-Clause")},function(n){return n.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i,"BSD-2-Clause-$1BSD")},function(n){return n.replace(/\bClear(-| )?BSD((-| )License)?/i,"BSD-3-Clause-Clear")},function(n){return n.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i,"BSD-4-Clause")},function(n){return"CC-"+n},function(n){return"CC-"+n+"-4.0"},function(n){return n.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")},function(n){return"CC-"+n.replace("Attribution","BY").replace("NonCommercial","NC").replace("NoDerivatives","ND").replace(/ (\d)/,"-$1").replace(/ ?International/,"")+"-4.0"}],smt=XVa.map(function(n){var e=/^(.*)-\d+\.\d+$/.exec(n);return e?[e[0],e[1]]:[n,null]}).reduce(function(n,e){var r=e[1];return n[r]=n[r]||[],n[r].push(e[0]),n},{}),LVa=Object.keys(smt).map(function(e){return[e,smt[e]]}).filter(function(e){return e[1].length===1&&e[0]!==null&&e[0]!=="APL"}).map(function(e){return[e[0],e[1][0]]});smt=void 0;var mQr=[["UNLI","Unlicense"],["WTF","WTFPL"],["2 CLAUSE","BSD-2-Clause"],["2-CLAUSE","BSD-2-Clause"],["3 CLAUSE","BSD-3-Clause"],["3-CLAUSE","BSD-3-Clause"],["AFFERO","AGPL-3.0-or-later"],["AGPL","AGPL-3.0-or-later"],["APACHE","Apache-2.0"],["ARTISTIC","Artistic-2.0"],["Affero","AGPL-3.0-or-later"],["BEER","Beerware"],["BOOST","BSL-1.0"],["BSD","BSD-2-Clause"],["CDDL","CDDL-1.1"],["ECLIPSE","EPL-1.0"],["FUCK","WTFPL"],["GNU","GPL-3.0-or-later"],["LGPL","LGPL-3.0-or-later"],["GPLV1","GPL-1.0-only"],["GPL-1","GPL-1.0-only"],["GPLV2","GPL-2.0-only"],["GPL-2","GPL-2.0-only"],["GPL","GPL-3.0-or-later"],["MIT +NO-FALSE-ATTRIBS","MITNFA"],["MIT","MIT"],["MPL","MPL-2.0"],["X11","X11"],["ZLIB","Zlib"]].concat(LVa).sort(GQr),JVa=0,BVa=1,pQr=function(n){for(var e=0;e<hQr.length;e++){var r=hQr[e](n).trim();if(r!==n&&aEe(r))return r}return null},bQr=function(n){for(var e=n.toUpperCase(),r=0;r<mQr.length;r++){var a=mQr[r];if(e.indexOf(a[JVa])>-1)return a[BVa]}return null},fQr=function(n,e){for(var r=0;r<IQr.length;r++){var a=IQr[r],i=a[kVa];if(n.indexOf(i)>-1){var o=n.replace(i,a[SVa]),t=e(o);if(t!==null)return t}}return null};gQr.exports=function(n,e){e=e||{};var r=e.upgrade===void 0?!0:!!e.upgrade;function a(s){return r?TVa(s):s}var i=typeof n=="string"&&n.trim().length!==0;if(!i)throw Error("Invalid argument. Expected non-empty string.");if(n=n.trim(),aEe(n))return a(n);var o=n.replace(/\+$/,"").trim();if(aEe(o))return a(o);var t=pQr(n);return t!==null||(t=fQr(n,function(s){return aEe(s)?s:pQr(s)}),t!==null)||(t=bQr(n),t!==null)||(t=fQr(n,bQr),t!==null)?a(t):null};function TVa(n){return["GPL-1.0","LGPL-1.0","AGPL-1.0","GPL-2.0","LGPL-2.0","AGPL-2.0","LGPL-2.1"].indexOf(n)!==-1?n+"-only":["GPL-1.0+","GPL-2.0+","GPL-3.0+","LGPL-2.0+","LGPL-2.1+","LGPL-3.0+","AGPL-1.0+","AGPL-3.0+"].indexOf(n)!==-1?n.replace(/\+$/,"-or-later"):["GPL-3.0","LGPL-3.0","AGPL-3.0"].indexOf(n)!==-1?n+"-or-later":n}});var NQr=Le((Xgs,WQr)=>{var DVa=imt(),OVa=vQr(),yQr='license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"',MVa=/^SEE LICEN[CS]E IN (.+)$/;function ZQr(n,e){return e.slice(0,n.length)===n}function omt(n){if(n.hasOwnProperty("license")){var e=n.license;return ZQr("LicenseRef",e)||ZQr("DocumentRef",e)}else return omt(n.left)||omt(n.right)}WQr.exports=function(n){var e;try{e=DVa(n)}catch{var r;if(n==="UNLICENSED"||n==="UNLICENCED")return{validForOldPackages:!0,validForNewPackages:!0,unlicensed:!0};if(r=MVa.exec(n))return{validForOldPackages:!0,validForNewPackages:!0,inFile:r[1]};var a={validForOldPackages:!1,validForNewPackages:!1,warnings:[yQr]};if(n.trim().length!==0){var i=OVa(n);i&&a.warnings.push('license is similar to the valid expression "'+i+'"')}return a}return omt(e)?{validForNewPackages:!1,validForOldPackages:!1,spdx:!0,warnings:[yQr]}:{validForNewPackages:!0,validForOldPackages:!0,spdx:!0}}});var EQr=Le(sEe=>{"use strict";Object.defineProperty(sEe,"__esModule",{value:!0});sEe.LRUCache=void 0;var X_=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,wQr=new Set,lmt=typeof process=="object"&&process?process:{},RQr=(n,e,r,a)=>{typeof lmt.emitWarning=="function"?lmt.emitWarning(n,e,r,a):console.error(`[${r}] ${e}: ${n}`)},iEe=globalThis.AbortController,FQr=globalThis.AbortSignal;if(typeof iEe>"u"){FQr=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(a,i){this._onabort.push(i)}},iEe=class{constructor(){e()}signal=new FQr;abort(a){if(!this.signal.aborted){this.signal.reason=a,this.signal.aborted=!0;for(let i of this.signal._onabort)i(a);this.signal.onabort?.(a)}}};let n=lmt.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,RQr("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 UVa=n=>!wQr.has(n),Lgs=Symbol("type"),OQ=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),AQr=n=>OQ(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?k_:null:null,k_=class extends Array{constructor(e){super(e),this.fill(0)}},cmt=class n{heap;length;static#e=!1;static create(e){let r=AQr(e);if(!r)return[];n.#e=!0;let a=new n(e,r);return n.#e=!1,a}constructor(e,r){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},umt=class n{#e;#t;#r;#n;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#o;#s;#I;#d;#h;#l;#p;#b;#G;#m;#W;#y;#N;#F;#v;#g;static unsafeExposeInternals(e){return{starts:e.#y,ttls:e.#N,sizes:e.#W,keyMap:e.#s,keyList:e.#I,valList:e.#d,next:e.#h,prev:e.#l,get head(){return e.#p},get tail(){return e.#b},free:e.#G,isBackgroundFetch:r=>e.#Z(r),backgroundFetch:(r,a,i,o)=>e.#C(r,a,i,o),moveToTail:r=>e.#D(r),indexes:r=>e.#L(r),rindexes:r=>e.#V(r),isStale:r=>e.#E(r)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#o}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#r}get disposeAfter(){return this.#n}constructor(e){let{max:r=0,ttl:a,ttlResolution:i=1,ttlAutopurge:o,updateAgeOnGet:t,updateAgeOnHas:s,allowStale:d,dispose:I,disposeAfter:u,noDisposeOnSet:h,noUpdateTTL:c,maxSize:m=0,maxEntrySize:y=0,sizeCalculation:g,fetchMethod:Z,memoMethod:v,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:b,ignoreFetchAbort:W}=e;if(r!==0&&!OQ(r))throw new TypeError("max option must be a nonnegative integer");let N=r?AQr(r):Array;if(!N)throw new Error("invalid max value: "+r);if(this.#e=r,this.#t=m,this.maxEntrySize=y||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#a=v,Z!==void 0&&typeof Z!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=Z,this.#v=!!Z,this.#s=new Map,this.#I=new Array(r).fill(void 0),this.#d=new Array(r).fill(void 0),this.#h=new N(r),this.#l=new N(r),this.#p=0,this.#b=0,this.#G=cmt.create(r),this.#c=0,this.#o=0,typeof I=="function"&&(this.#r=I),typeof u=="function"?(this.#n=u,this.#m=[]):(this.#n=void 0,this.#m=void 0),this.#F=!!this.#r,this.#g=!!this.#n,this.noDisposeOnSet=!!h,this.noUpdateTTL=!!c,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!b,this.ignoreFetchAbort=!!W,this.maxEntrySize!==0){if(this.#t!==0&&!OQ(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!OQ(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#x()}if(this.allowStale=!!d,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!t,this.updateAgeOnHas=!!s,this.ttlResolution=OQ(i)||i===0?i:1,this.ttlAutopurge=!!o,this.ttl=a||0,this.ttl){if(!OQ(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#w()}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 A="LRU_CACHE_UNBOUNDED";UVa(A)&&(wQr.add(A),RQr("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",A,n))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#w(){let e=new k_(this.#e),r=new k_(this.#e);this.#N=e,this.#y=r,this.#H=(o,t,s=X_.now())=>{if(r[o]=t!==0?s:0,e[o]=t,t!==0&&this.ttlAutopurge){let d=setTimeout(()=>{this.#E(o)&&this.#k(this.#I[o],"expire")},t+1);d.unref&&d.unref()}},this.#A=o=>{r[o]=e[o]!==0?X_.now():0},this.#u=(o,t)=>{if(e[t]){let s=e[t],d=r[t];if(!s||!d)return;o.ttl=s,o.start=d,o.now=a||i();let I=o.now-d;o.remainingTTL=s-I}};let a=0,i=()=>{let o=X_.now();if(this.ttlResolution>0){a=o;let t=setTimeout(()=>a=0,this.ttlResolution);t.unref&&t.unref()}return o};this.getRemainingTTL=o=>{let t=this.#s.get(o);if(t===void 0)return 0;let s=e[t],d=r[t];if(!s||!d)return 1/0;let I=(a||i())-d;return s-I},this.#E=o=>{let t=r[o],s=e[o];return!!s&&!!t&&(a||i())-t>s}}#A=()=>{};#u=()=>{};#H=()=>{};#E=()=>!1;#x(){let e=new k_(this.#e);this.#o=0,this.#W=e,this.#Y=r=>{this.#o-=e[r],e[r]=0},this.#R=(r,a,i,o)=>{if(this.#Z(a))return 0;if(!OQ(i))if(o){if(typeof o!="function")throw new TypeError("sizeCalculation must be a function");if(i=o(a,r),!OQ(i))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 i},this.#S=(r,a,i)=>{if(e[r]=a,this.#t){let o=this.#t-e[r];for(;this.#o>o;)this.#J(!0)}this.#o+=e[r],i&&(i.entrySize=a,i.totalCalculatedSize=this.#o)}}#Y=e=>{};#S=(e,r,a)=>{};#R=(e,r,a,i)=>{if(a||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#L({allowStale:e=this.allowStale}={}){if(this.#c)for(let r=this.#b;!(!this.#X(r)||((e||!this.#E(r))&&(yield r),r===this.#p));)r=this.#l[r]}*#V({allowStale:e=this.allowStale}={}){if(this.#c)for(let r=this.#p;!(!this.#X(r)||((e||!this.#E(r))&&(yield r),r===this.#b));)r=this.#h[r]}#X(e){return e!==void 0&&this.#s.get(this.#I[e])===e}*entries(){for(let e of this.#L())this.#d[e]!==void 0&&this.#I[e]!==void 0&&!this.#Z(this.#d[e])&&(yield[this.#I[e],this.#d[e]])}*rentries(){for(let e of this.#V())this.#d[e]!==void 0&&this.#I[e]!==void 0&&!this.#Z(this.#d[e])&&(yield[this.#I[e],this.#d[e]])}*keys(){for(let e of this.#L()){let r=this.#I[e];r!==void 0&&!this.#Z(this.#d[e])&&(yield r)}}*rkeys(){for(let e of this.#V()){let r=this.#I[e];r!==void 0&&!this.#Z(this.#d[e])&&(yield r)}}*values(){for(let e of this.#L())this.#d[e]!==void 0&&!this.#Z(this.#d[e])&&(yield this.#d[e])}*rvalues(){for(let e of this.#V())this.#d[e]!==void 0&&!this.#Z(this.#d[e])&&(yield this.#d[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let a of this.#L()){let i=this.#d[a],o=this.#Z(i)?i.__staleWhileFetching:i;if(o!==void 0&&e(o,this.#I[a],this))return this.get(this.#I[a],r)}}forEach(e,r=this){for(let a of this.#L()){let i=this.#d[a],o=this.#Z(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#I[a],this)}}rforEach(e,r=this){for(let a of this.#V()){let i=this.#d[a],o=this.#Z(i)?i.__staleWhileFetching:i;o!==void 0&&e.call(r,o,this.#I[a],this)}}purgeStale(){let e=!1;for(let r of this.#V({allowStale:!0}))this.#E(r)&&(this.#k(this.#I[r],"expire"),e=!0);return e}info(e){let r=this.#s.get(e);if(r===void 0)return;let a=this.#d[r],i=this.#Z(a)?a.__staleWhileFetching:a;if(i===void 0)return;let o={value:i};if(this.#N&&this.#y){let t=this.#N[r],s=this.#y[r];if(t&&s){let d=t-(X_.now()-s);o.ttl=d,o.start=Date.now()}}return this.#W&&(o.size=this.#W[r]),o}dump(){let e=[];for(let r of this.#L({allowStale:!0})){let a=this.#I[r],i=this.#d[r],o=this.#Z(i)?i.__staleWhileFetching:i;if(o===void 0||a===void 0)continue;let t={value:o};if(this.#N&&this.#y){t.ttl=this.#N[r];let s=X_.now()-this.#y[r];t.start=Math.floor(Date.now()-s)}this.#W&&(t.size=this.#W[r]),e.unshift([a,t])}return e}load(e){this.clear();for(let[r,a]of e){if(a.start){let i=Date.now()-a.start;a.start=X_.now()-i}this.set(r,a.value,a)}}set(e,r,a={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:o,noDisposeOnSet:t=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:d}=a,{noUpdateTTL:I=this.noUpdateTTL}=a,u=this.#R(e,r,a.size||0,s);if(this.maxEntrySize&&u>this.maxEntrySize)return d&&(d.set="miss",d.maxEntrySizeExceeded=!0),this.#k(e,"set"),this;let h=this.#c===0?void 0:this.#s.get(e);if(h===void 0)h=this.#c===0?this.#b:this.#G.length!==0?this.#G.pop():this.#c===this.#e?this.#J(!1):this.#c,this.#I[h]=e,this.#d[h]=r,this.#s.set(e,h),this.#h[this.#b]=h,this.#l[h]=this.#b,this.#b=h,this.#c++,this.#S(h,u,d),d&&(d.set="add"),I=!1;else{this.#D(h);let c=this.#d[h];if(r!==c){if(this.#v&&this.#Z(c)){c.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=c;m!==void 0&&!t&&(this.#F&&this.#r?.(m,e,"set"),this.#g&&this.#m?.push([m,e,"set"]))}else t||(this.#F&&this.#r?.(c,e,"set"),this.#g&&this.#m?.push([c,e,"set"]));if(this.#Y(h),this.#S(h,u,d),this.#d[h]=r,d){d.set="replace";let m=c&&this.#Z(c)?c.__staleWhileFetching:c;m!==void 0&&(d.oldValue=m)}}else d&&(d.set="update")}if(i!==0&&!this.#N&&this.#w(),this.#N&&(I||this.#H(h,i,o),d&&this.#u(d,h)),!t&&this.#g&&this.#m){let c=this.#m,m;for(;m=c?.shift();)this.#n?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#d[this.#p];if(this.#J(!0),this.#Z(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#g&&this.#m){let e=this.#m,r;for(;r=e?.shift();)this.#n?.(...r)}}}#J(e){let r=this.#p,a=this.#I[r],i=this.#d[r];return this.#v&&this.#Z(i)?i.__abortController.abort(new Error("evicted")):(this.#F||this.#g)&&(this.#F&&this.#r?.(i,a,"evict"),this.#g&&this.#m?.push([i,a,"evict"])),this.#Y(r),e&&(this.#I[r]=void 0,this.#d[r]=void 0,this.#G.push(r)),this.#c===1?(this.#p=this.#b=0,this.#G.length=0):this.#p=this.#h[r],this.#s.delete(a),this.#c--,r}has(e,r={}){let{updateAgeOnHas:a=this.updateAgeOnHas,status:i}=r,o=this.#s.get(e);if(o!==void 0){let t=this.#d[o];if(this.#Z(t)&&t.__staleWhileFetching===void 0)return!1;if(this.#E(o))i&&(i.has="stale",this.#u(i,o));else return a&&this.#A(o),i&&(i.has="hit",this.#u(i,o)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:a=this.allowStale}=r,i=this.#s.get(e);if(i===void 0||!a&&this.#E(i))return;let o=this.#d[i];return this.#Z(o)?o.__staleWhileFetching:o}#C(e,r,a,i){let o=r===void 0?void 0:this.#d[r];if(this.#Z(o))return o;let t=new iEe,{signal:s}=a;s?.addEventListener("abort",()=>t.abort(s.reason),{signal:t.signal});let d={signal:t.signal,options:a,context:i},I=(g,Z=!1)=>{let{aborted:v}=t.signal,E=a.ignoreFetchAbort&&g!==void 0;if(a.status&&(v&&!Z?(a.status.fetchAborted=!0,a.status.fetchError=t.signal.reason,E&&(a.status.fetchAbortIgnored=!0)):a.status.fetchResolved=!0),v&&!E&&!Z)return h(t.signal.reason);let w=m;return this.#d[r]===m&&(g===void 0?w.__staleWhileFetching?this.#d[r]=w.__staleWhileFetching:this.#k(e,"fetch"):(a.status&&(a.status.fetchUpdated=!0),this.set(e,g,d.options))),g},u=g=>(a.status&&(a.status.fetchRejected=!0,a.status.fetchError=g),h(g)),h=g=>{let{aborted:Z}=t.signal,v=Z&&a.allowStaleOnFetchAbort,E=v||a.allowStaleOnFetchRejection,w=E||a.noDeleteOnFetchRejection,R=m;if(this.#d[r]===m&&(!w||R.__staleWhileFetching===void 0?this.#k(e,"fetch"):v||(this.#d[r]=R.__staleWhileFetching)),E)return a.status&&R.__staleWhileFetching!==void 0&&(a.status.returnedStale=!0),R.__staleWhileFetching;if(R.__returned===R)throw g},c=(g,Z)=>{let v=this.#i?.(e,o,d);v&&v instanceof Promise&&v.then(E=>g(E===void 0?void 0:E),Z),t.signal.addEventListener("abort",()=>{(!a.ignoreFetchAbort||a.allowStaleOnFetchAbort)&&(g(void 0),a.allowStaleOnFetchAbort&&(g=E=>I(E,!0)))})};a.status&&(a.status.fetchDispatched=!0);let m=new Promise(c).then(I,u),y=Object.assign(m,{__abortController:t,__staleWhileFetching:o,__returned:void 0});return r===void 0?(this.set(e,y,{...d.options,status:void 0}),r=this.#s.get(e)):this.#d[r]=y,y}#Z(e){if(!this.#v)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof iEe}async fetch(e,r={}){let{allowStale:a=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:t=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:d=0,sizeCalculation:I=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:h=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:c=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:y=this.allowStaleOnFetchAbort,context:g,forceRefresh:Z=!1,status:v,signal:E}=r;if(!this.#v)return v&&(v.fetch="get"),this.get(e,{allowStale:a,updateAgeOnGet:i,noDeleteOnStaleGet:o,status:v});let w={allowStale:a,updateAgeOnGet:i,noDeleteOnStaleGet:o,ttl:t,noDisposeOnSet:s,size:d,sizeCalculation:I,noUpdateTTL:u,noDeleteOnFetchRejection:h,allowStaleOnFetchRejection:c,allowStaleOnFetchAbort:y,ignoreFetchAbort:m,status:v,signal:E},R=this.#s.get(e);if(R===void 0){v&&(v.fetch="miss");let b=this.#C(e,R,w,g);return b.__returned=b}else{let b=this.#d[R];if(this.#Z(b)){let f=a&&b.__staleWhileFetching!==void 0;return v&&(v.fetch="inflight",f&&(v.returnedStale=!0)),f?b.__staleWhileFetching:b.__returned=b}let W=this.#E(R);if(!Z&&!W)return v&&(v.fetch="hit"),this.#D(R),i&&this.#A(R),v&&this.#u(v,R),b;let N=this.#C(e,R,w,g),p=N.__staleWhileFetching!==void 0&&a;return v&&(v.fetch=W?"stale":"refresh",p&&W&&(v.returnedStale=!0)),p?N.__staleWhileFetching:N.__returned=N}}async forceFetch(e,r={}){let a=await this.fetch(e,r);if(a===void 0)throw new Error("fetch() returned undefined");return a}memo(e,r={}){let a=this.#a;if(!a)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:o,...t}=r,s=this.get(e,t);if(!o&&s!==void 0)return s;let d=a(e,s,{options:t,context:i});return this.set(e,d,t),d}get(e,r={}){let{allowStale:a=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:t}=r,s=this.#s.get(e);if(s!==void 0){let d=this.#d[s],I=this.#Z(d);return t&&this.#u(t,s),this.#E(s)?(t&&(t.get="stale"),I?(t&&a&&d.__staleWhileFetching!==void 0&&(t.returnedStale=!0),a?d.__staleWhileFetching:void 0):(o||this.#k(e,"expire"),t&&a&&(t.returnedStale=!0),a?d:void 0)):(t&&(t.get="hit"),I?d.__staleWhileFetching:(this.#D(s),i&&this.#A(s),d))}else t&&(t.get="miss")}#T(e,r){this.#l[r]=e,this.#h[e]=r}#D(e){e!==this.#b&&(e===this.#p?this.#p=this.#h[e]:this.#T(this.#l[e],this.#h[e]),this.#T(this.#b,e),this.#b=e)}delete(e){return this.#k(e,"delete")}#k(e,r){let a=!1;if(this.#c!==0){let i=this.#s.get(e);if(i!==void 0)if(a=!0,this.#c===1)this.#f(r);else{this.#Y(i);let o=this.#d[i];if(this.#Z(o)?o.__abortController.abort(new Error("deleted")):(this.#F||this.#g)&&(this.#F&&this.#r?.(o,e,r),this.#g&&this.#m?.push([o,e,r])),this.#s.delete(e),this.#I[i]=void 0,this.#d[i]=void 0,i===this.#b)this.#b=this.#l[i];else if(i===this.#p)this.#p=this.#h[i];else{let t=this.#l[i];this.#h[t]=this.#h[i];let s=this.#h[i];this.#l[s]=this.#l[i]}this.#c--,this.#G.push(i)}}if(this.#g&&this.#m?.length){let i=this.#m,o;for(;o=i?.shift();)this.#n?.(...o)}return a}clear(){return this.#f("delete")}#f(e){for(let r of this.#V({allowStale:!0})){let a=this.#d[r];if(this.#Z(a))a.__abortController.abort(new Error("deleted"));else{let i=this.#I[r];this.#F&&this.#r?.(a,i,e),this.#g&&this.#m?.push([a,i,e])}}if(this.#s.clear(),this.#d.fill(void 0),this.#I.fill(void 0),this.#N&&this.#y&&(this.#N.fill(0),this.#y.fill(0)),this.#W&&this.#W.fill(0),this.#p=0,this.#b=0,this.#G.length=0,this.#o=0,this.#c=0,this.#g&&this.#m){let r=this.#m,a;for(;a=r?.shift();)this.#n?.(...a)}}};sEe.LRUCache=umt});var YQr=Le((Bgs,CQr)=>{"use strict";var Xl=(...n)=>n.every(e=>e)?n.join(""):"",zh=n=>n?encodeURIComponent(n):"",xQr=n=>n.toLowerCase().replace(/^\W+|\/|\W+$/g,"").replace(/\W+/g,"-"),zVa={sshtemplate:({domain:n,user:e,project:r,committish:a})=>`git@${n}:${e}/${r}.git${Xl("#",a)}`,sshurltemplate:({domain:n,user:e,project:r,committish:a})=>`git+ssh://git@${n}/${e}/${r}.git${Xl("#",a)}`,edittemplate:({domain:n,user:e,project:r,committish:a,editpath:i,path:o})=>`https://${n}/${e}/${r}${Xl("/",i,"/",zh(a||"HEAD"),"/",o)}`,browsetemplate:({domain:n,user:e,project:r,committish:a,treepath:i})=>`https://${n}/${e}/${r}${Xl("/",i,"/",zh(a))}`,browsetreetemplate:({domain:n,user:e,project:r,committish:a,treepath:i,path:o,fragment:t,hashformat:s})=>`https://${n}/${e}/${r}/${i}/${zh(a||"HEAD")}/${o}${Xl("#",s(t||""))}`,browseblobtemplate:({domain:n,user:e,project:r,committish:a,blobpath:i,path:o,fragment:t,hashformat:s})=>`https://${n}/${e}/${r}/${i}/${zh(a||"HEAD")}/${o}${Xl("#",s(t||""))}`,docstemplate:({domain:n,user:e,project:r,treepath:a,committish:i})=>`https://${n}/${e}/${r}${Xl("/",a,"/",zh(i))}#readme`,httpstemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git+https://${Xl(n,"@")}${e}/${r}/${a}.git${Xl("#",i)}`,filetemplate:({domain:n,user:e,project:r,committish:a,path:i})=>`https://${n}/${e}/${r}/raw/${zh(a||"HEAD")}/${i}`,shortcuttemplate:({type:n,user:e,project:r,committish:a})=>`${n}:${e}/${r}${Xl("#",a)}`,pathtemplate:({user:n,project:e,committish:r})=>`${n}/${e}${Xl("#",r)}`,bugstemplate:({domain:n,user:e,project:r})=>`https://${n}/${e}/${r}/issues`,hashformat:xQr},MQ={};MQ.github={protocols:["git:","http:","git+ssh:","git+https:","ssh:","https:"],domain:"github.com",treepath:"tree",blobpath:"blob",editpath:"edit",filetemplate:({auth:n,user:e,project:r,committish:a,path:i})=>`https://${Xl(n,"@")}raw.githubusercontent.com/${e}/${r}/${zh(a||"HEAD")}/${i}`,gittemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git://${Xl(n,"@")}${e}/${r}/${a}.git${Xl("#",i)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://codeload.${n}/${e}/${r}/tar.gz/${zh(a||"HEAD")}`,extract:n=>{let[,e,r,a,i]=n.pathname.split("/",5);if(!(a&&a!=="tree")&&(a||(i=n.hash.slice(1)),r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:i}}};MQ.bitbucket={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"bitbucket.org",treepath:"src",blobpath:"src",editpath:"?mode=edit",edittemplate:({domain:n,user:e,project:r,committish:a,treepath:i,path:o,editpath:t})=>`https://${n}/${e}/${r}${Xl("/",i,"/",zh(a||"HEAD"),"/",o,t)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/get/${zh(a||"HEAD")}.tar.gz`,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(!["get"].includes(a)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:n.hash.slice(1)}}};MQ.gitlab={protocols:["git+ssh:","git+https:","ssh:","https:"],domain:"gitlab.com",treepath:"tree",blobpath:"tree",editpath:"-/edit",httpstemplate:({auth:n,domain:e,user:r,project:a,committish:i})=>`git+https://${Xl(n,"@")}${e}/${r}/${a}.git${Xl("#",i)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/repository/archive.tar.gz?ref=${zh(a||"HEAD")}`,extract:n=>{let e=n.pathname.slice(1);if(e.includes("/-/")||e.includes("/archive.tar.gz"))return;let r=e.split("/"),a=r.pop();a.endsWith(".git")&&(a=a.slice(0,-4));let i=r.join("/");if(!(!i||!a))return{user:i,project:a,committish:n.hash.slice(1)}}};MQ.gist={protocols:["git:","git+ssh:","git+https:","ssh:","https:"],domain:"gist.github.com",editpath:"edit",sshtemplate:({domain:n,project:e,committish:r})=>`git@${n}:${e}.git${Xl("#",r)}`,sshurltemplate:({domain:n,project:e,committish:r})=>`git+ssh://git@${n}/${e}.git${Xl("#",r)}`,edittemplate:({domain:n,user:e,project:r,committish:a,editpath:i})=>`https://${n}/${e}/${r}${Xl("/",zh(a))}/${i}`,browsetemplate:({domain:n,project:e,committish:r})=>`https://${n}/${e}${Xl("/",zh(r))}`,browsetreetemplate:({domain:n,project:e,committish:r,path:a,hashformat:i})=>`https://${n}/${e}${Xl("/",zh(r))}${Xl("#",i(a))}`,browseblobtemplate:({domain:n,project:e,committish:r,path:a,hashformat:i})=>`https://${n}/${e}${Xl("/",zh(r))}${Xl("#",i(a))}`,docstemplate:({domain:n,project:e,committish:r})=>`https://${n}/${e}${Xl("/",zh(r))}`,httpstemplate:({domain:n,project:e,committish:r})=>`git+https://${n}/${e}.git${Xl("#",r)}`,filetemplate:({user:n,project:e,committish:r,path:a})=>`https://gist.githubusercontent.com/${n}/${e}/raw${Xl("/",zh(r))}/${a}`,shortcuttemplate:({type:n,project:e,committish:r})=>`${n}:${e}${Xl("#",r)}`,pathtemplate:({project:n,committish:e})=>`${n}${Xl("#",e)}`,bugstemplate:({domain:n,project:e})=>`https://${n}/${e}`,gittemplate:({domain:n,project:e,committish:r})=>`git://${n}/${e}.git${Xl("#",r)}`,tarballtemplate:({project:n,committish:e})=>`https://codeload.github.com/gist/${n}/tar.gz/${zh(e||"HEAD")}`,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(a!=="raw"){if(!r){if(!e)return;r=e,e=null}return r.endsWith(".git")&&(r=r.slice(0,-4)),{user:e,project:r,committish:n.hash.slice(1)}}},hashformat:function(n){return n&&"file-"+xQr(n)}};MQ.sourcehut={protocols:["git+ssh:","https:"],domain:"git.sr.ht",treepath:"tree",blobpath:"tree",filetemplate:({domain:n,user:e,project:r,committish:a,path:i})=>`https://${n}/${e}/${r}/blob/${zh(a)||"HEAD"}/${i}`,httpstemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}.git${Xl("#",a)}`,tarballtemplate:({domain:n,user:e,project:r,committish:a})=>`https://${n}/${e}/${r}/archive/${zh(a)||"HEAD"}.tar.gz`,bugstemplate:()=>null,extract:n=>{let[,e,r,a]=n.pathname.split("/",4);if(!["archive"].includes(a)&&(r&&r.endsWith(".git")&&(r=r.slice(0,-4)),!(!e||!r)))return{user:e,project:r,committish:n.hash.slice(1)}}};for(let[n,e]of Object.entries(MQ))MQ[n]=Object.assign({},zVa,e);CQr.exports=MQ});var Imt=Le((Tgs,QQr)=>{var _Va=Yt("url"),dmt=(n,e,r)=>{let a=n.indexOf(r);return n.lastIndexOf(e,a>-1?a:1/0)},VQr=n=>{try{return new _Va.URL(n)}catch{}},PVa=(n,e)=>{let r=n.indexOf(":"),a=n.slice(0,r+1);if(Object.prototype.hasOwnProperty.call(e,a))return n;let i=n.indexOf("@");return i>-1?i>r?`git+ssh://${n}`:n:n.indexOf("//")===r+1?n:`${n.slice(0,r+1)}//${n.slice(r+1)}`},jVa=n=>{let e=dmt(n,"@","#"),r=dmt(n,":","#");return r>e&&(n=n.slice(0,r)+"/"+n.slice(r+1)),dmt(n,":","#")===-1&&n.indexOf("//")===-1&&(n=`git+ssh://${n}`),n};QQr.exports=(n,e)=>{let r=e?PVa(n,e):n;return VQr(r)||VQr(jVa(r))}});var XQr=Le((Dgs,HQr)=>{"use strict";var qVa=Imt(),KVa=n=>{let e=n.indexOf("#"),r=n.indexOf("/"),a=n.indexOf("/",r+1),i=n.indexOf(":"),o=/\s/.exec(n),t=n.indexOf("@"),s=!o||e>-1&&o.index>e,d=t===-1||e>-1&&t>e,I=i===-1||e>-1&&i>e,u=a===-1||e>-1&&a>e,h=r>0,c=e>-1?n[e-1]!=="/":!n.endsWith("/"),m=!n.startsWith(".");return s&&h&&c&&m&&d&&I&&u};HQr.exports=(n,e,{gitHosts:r,protocols:a})=>{if(!n)return;let i=KVa(n)?`github:${n}`:n,o=qVa(i,a);if(!o)return;let t=r.byShortcut[o.protocol],s=r.byDomain[o.hostname.startsWith("www.")?o.hostname.slice(4):o.hostname],d=t||s;if(!d)return;let I=r[t||s],u=null;a[o.protocol]?.auth&&(o.username||o.password)&&(u=`${o.username}${o.password?":"+o.password:""}`);let h=null,c=null,m=null,y=null;try{if(t){let g=o.pathname.startsWith("/")?o.pathname.slice(1):o.pathname,Z=g.indexOf("@");Z>-1&&(g=g.slice(Z+1));let v=g.lastIndexOf("/");v>-1?(c=decodeURIComponent(g.slice(0,v)),c||(c=null),m=decodeURIComponent(g.slice(v+1))):m=decodeURIComponent(g),m.endsWith(".git")&&(m=m.slice(0,-4)),o.hash&&(h=decodeURIComponent(o.hash.slice(1))),y="shortcut"}else{if(!I.protocols.includes(o.protocol))return;let g=I.extract(o);if(!g)return;c=g.user&&decodeURIComponent(g.user),m=decodeURIComponent(g.project),h=decodeURIComponent(g.committish),y=a[o.protocol]?.name||o.protocol.slice(0,-1)}}catch(g){if(g instanceof URIError)return;throw g}return[d,c,u,m,h,y,e]}});var SQr=Le((Ogs,kQr)=>{"use strict";var{LRUCache:$Va}=EQr(),eQa=YQr(),tQa=XQr(),rQa=Imt(),hmt=new $Va({max:1e3}),oEe=class n{constructor(e,r,a,i,o,t,s={}){Object.assign(this,n.#e[e],{type:e,user:r,auth:a,project:i,committish:o,default:t,opts:s})}static#e={byShortcut:{},byDomain:{}};static#t={"git+ssh:":{name:"sshurl"},"ssh:":{name:"sshurl"},"git+https:":{name:"https",auth:!0},"git:":{auth:!0},"http:":{auth:!0},"https:":{auth:!0},"git+http:":{auth:!0}};static addHost(e,r){n.#e[e]=r,n.#e.byDomain[r.domain]=e,n.#e.byShortcut[`${e}:`]=e,n.#t[`${e}:`]={name:e}}static fromUrl(e,r){if(typeof e!="string")return;let a=e+JSON.stringify(r||{});if(!hmt.has(a)){let i=tQa(e,r,{gitHosts:n.#e,protocols:n.#t});hmt.set(a,i?new n(...i):void 0)}return hmt.get(a)}static parseUrl(e){return rQa(e)}#r(e,r){if(typeof e!="function")return null;let a={...this,...this.opts,...r};a.path||(a.path=""),a.path.startsWith("/")&&(a.path=a.path.slice(1)),a.noCommittish&&(a.committish=null);let i=e(a);return a.noGitPlus&&i.startsWith("git+")?i.slice(4):i}hash(){return this.committish?`#${this.committish}`:""}ssh(e){return this.#r(this.sshtemplate,e)}sshurl(e){return this.#r(this.sshurltemplate,e)}browse(e,...r){return typeof e!="string"?this.#r(this.browsetemplate,e):typeof r[0]!="string"?this.#r(this.browsetreetemplate,{...r[0],path:e}):this.#r(this.browsetreetemplate,{...r[1],fragment:r[0],path:e})}browseFile(e,...r){return typeof r[0]!="string"?this.#r(this.browseblobtemplate,{...r[0],path:e}):this.#r(this.browseblobtemplate,{...r[1],fragment:r[0],path:e})}docs(e){return this.#r(this.docstemplate,e)}bugs(e){return this.#r(this.bugstemplate,e)}https(e){return this.#r(this.httpstemplate,e)}git(e){return this.#r(this.gittemplate,e)}shortcut(e){return this.#r(this.shortcuttemplate,e)}path(e){return this.#r(this.pathtemplate,e)}tarball(e){return this.#r(this.tarballtemplate,{...e,noCommittish:!1})}file(e,r){return this.#r(this.filetemplate,{...r,path:e})}edit(e,r){return this.#r(this.edittemplate,{...r,path:e})}getDefaultRepresentation(){return this.default}toString(e){return this.default&&typeof this[this.default]=="function"?this[this.default](e):this.sshurl(e)}};for(let[n,e]of Object.entries(eQa))oEe.addHost(n,e);kQr.exports=oEe});var JQr=Le((Mgs,LQr)=>{LQr.exports=nQa;function nQa(n){if(!n||n==="ERROR: No README data found!")return;n=n.trim().split(`
5486
- `);let e=0;for(;n[e]&&n[e].trim().match(/^(#|$)/);)e++;let r=n.length,a=e+1;for(;a<r&&n[a].trim();)a++;return n.slice(e,a).join(" ").trim()}});var BQr=Le((Ugs,aQa)=>{aQa.exports={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}}});var MQr=Le((zgs,OQr)=>{var iQa=rmt(),sQa=nmt(),oQa=NQr(),lEe=SQr(),lQa=Yt("node:module"),cQa=["dependencies","devDependencies","optionalDependencies"],uQa=JQr(),mmt=Yt("url"),UQ=BQr(),TQr=n=>n.includes("@")&&n.indexOf("@")<n.lastIndexOf(".");OQr.exports={warn:function(){},fixRepositoryField:function(n){if(n.repositories&&(this.warn("repositories"),n.repository=n.repositories[0]),!n.repository)return this.warn("missingRepository");typeof n.repository=="string"&&(n.repository={type:"git",url:n.repository});var e=n.repository.url||"";if(e){var r=lEe.fromUrl(e);r&&(e=n.repository.url=r.getDefaultRepresentation()==="shortcut"?r.https():r.toString())}e.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",e)},fixTypos:function(n){Object.keys(UQ.topLevel).forEach(function(e){Object.prototype.hasOwnProperty.call(n,e)&&this.warn("typo",e,UQ.topLevel[e])},this)},fixScriptsField:function(n){if(n.scripts){if(typeof n.scripts!="object"){this.warn("nonObjectScripts"),delete n.scripts;return}Object.keys(n.scripts).forEach(function(e){typeof n.scripts[e]!="string"?(this.warn("nonStringScript"),delete n.scripts[e]):UQ.script[e]&&!n.scripts[UQ.script[e]]&&this.warn("typo",e,UQ.script[e],"scripts")},this)}},fixFilesField:function(n){var e=n.files;e&&!Array.isArray(e)?(this.warn("nonArrayFiles"),delete n.files):n.files&&(n.files=n.files.filter(function(r){return!r||typeof r!="string"?(this.warn("invalidFilename",r),!1):!0},this))},fixBinField:function(n){if(n.bin&&typeof n.bin=="string"){var e={},r;(r=n.name.match(/^@[^/]+[/](.*)$/))?e[r[1]]=n.bin:e[n.name]=n.bin,n.bin=e}},fixManField:function(n){n.man&&typeof n.man=="string"&&(n.man=[n.man])},fixBundleDependenciesField:function(n){var e="bundledDependencies",r="bundleDependencies";n[e]&&!n[r]&&(n[r]=n[e],delete n[e]),n[r]&&!Array.isArray(n[r])?(this.warn("nonArrayBundleDependencies"),delete n[r]):n[r]&&(n[r]=n[r].filter(function(a){return!a||typeof a!="string"?(this.warn("nonStringBundleDependency",a),!1):(n.dependencies||(n.dependencies={}),Object.prototype.hasOwnProperty.call(n.dependencies,a)||(this.warn("nonDependencyBundleDependency",a),n.dependencies[a]="*"),!0)},this))},fixDependencies:function(n){GQa(n,this.warn),bQa(n,this.warn),this.fixBundleDependenciesField(n),["dependencies","devDependencies"].forEach(function(e){if(e in n){if(!n[e]||typeof n[e]!="object"){this.warn("nonObjectDependencies",e),delete n[e];return}Object.keys(n[e]).forEach(function(r){var a=n[e][r];typeof a!="string"&&(this.warn("nonStringDependency",r,JSON.stringify(a)),delete n[e][r]);var i=lEe.fromUrl(n[e][r]);i&&(n[e][r]=i.toString())},this)}},this)},fixModulesField:function(n){n.modules&&(this.warn("deprecatedModules"),delete n.modules)},fixKeywordsField:function(n){typeof n.keywords=="string"&&(n.keywords=n.keywords.split(/,\s+/)),n.keywords&&!Array.isArray(n.keywords)?(delete n.keywords,this.warn("nonArrayKeywords")):n.keywords&&(n.keywords=n.keywords.filter(function(e){return typeof e!="string"||!e?(this.warn("nonStringKeyword"),!1):!0},this))},fixVersionField:function(n,e){var r=!e;if(!n.version)return n.version="",!0;if(!iQa(n.version,r))throw new Error('Invalid version: "'+n.version+'"');return n.version=sQa(n.version,r),!0},fixPeople:function(n){DQr(n,mQa),DQr(n,pQa)},fixNameField:function(n,e){typeof e=="boolean"?e={strict:e}:typeof e>"u"&&(e={});var r=e.strict;if(!n.name&&!r){n.name="";return}if(typeof n.name!="string")throw new Error("name field must be a string.");r||(n.name=n.name.trim()),hQa(n.name,r,e.allowLegacyCase),lQa.builtinModules.includes(n.name)&&this.warn("conflictingName",n.name)},fixDescriptionField:function(n){n.description&&typeof n.description!="string"&&(this.warn("nonStringDescription"),delete n.description),n.readme&&!n.description&&(n.description=uQa(n.readme)),n.description===void 0&&delete n.description,n.description||this.warn("missingDescription")},fixReadmeField:function(n){n.readme||(this.warn("missingReadme"),n.readme="ERROR: No README data found!")},fixBugsField:function(n){if(!n.bugs&&n.repository&&n.repository.url){var e=lEe.fromUrl(n.repository.url);e&&e.bugs()&&(n.bugs={url:e.bugs()})}else if(n.bugs){if(typeof n.bugs=="string")TQr(n.bugs)?n.bugs={email:n.bugs}:mmt.parse(n.bugs).protocol?n.bugs={url:n.bugs}:this.warn("nonEmailUrlBugsString");else{gQa(n.bugs,this.warn);var r=n.bugs;n.bugs={},r.url&&(typeof r.url=="string"&&mmt.parse(r.url).protocol?n.bugs.url=r.url:this.warn("nonUrlBugsUrlField")),r.email&&(typeof r.email=="string"&&TQr(r.email)?n.bugs.email=r.email:this.warn("nonEmailBugsEmailField"))}!n.bugs.email&&!n.bugs.url&&(delete n.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(n){if(!n.homepage&&n.repository&&n.repository.url){var e=lEe.fromUrl(n.repository.url);e&&e.docs()&&(n.homepage=e.docs())}if(n.homepage){if(typeof n.homepage!="string")return this.warn("nonUrlHomepage"),delete n.homepage;mmt.parse(n.homepage).protocol||(n.homepage="http://"+n.homepage)}},fixLicenseField:function(n){let e=n.license||n.licence;if(!e)return this.warn("missingLicense");if(typeof e!="string"||e.length<1||e.trim()==="")return this.warn("invalidLicense");if(!oQa(e).validForNewPackages)return this.warn("invalidLicense")}};function dQa(n){if(n.charAt(0)!=="@")return!1;var e=n.slice(1).split("/");return e.length!==2?!1:e[0]&&e[1]&&e[0]===encodeURIComponent(e[0])&&e[1]===encodeURIComponent(e[1])}function IQa(n){return!n.match(/[/@\s+%:]/)&&n===encodeURIComponent(n)}function hQa(n,e,r){if(n.charAt(0)==="."||!(dQa(n)||IQa(n))||e&&!r&&n!==n.toLowerCase()||n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico")throw new Error("Invalid name: "+JSON.stringify(n))}function DQr(n,e){return n.author&&(n.author=e(n.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(n[r])&&(n[r]=n[r].map(e))}),n}function mQa(n){if(typeof n=="string")return n;var e=n.name||"",r=n.url||n.web,a=r?" ("+r+")":"",i=n.email||n.mail,o=i?" <"+i+">":"";return e+o+a}function pQa(n){if(typeof n!="string")return n;var e=n.match(/^([^(<]+)/),r=n.match(/\(([^()]+)\)/),a=n.match(/<([^<>]+)>/),i={};return e&&e[0].trim()&&(i.name=e[0].trim()),a&&(i.email=a[1]),r&&(i.url=r[1]),i}function bQa(n){var e=n.optionalDependencies;if(e){var r=n.dependencies||{};Object.keys(e).forEach(function(a){r[a]=e[a]}),n.dependencies=r}}function fQa(n,e,r){if(!n)return{};if(typeof n=="string"&&(n=n.trim().split(/[\n\r\s\t ,]+/)),!Array.isArray(n))return n;r("deprecatedArrayDependencies",e);var a={};return n.filter(function(i){return typeof i=="string"}).forEach(function(i){i=i.trim().split(/(:?[@\s><=])/);var o=i.shift(),t=i.join("");t=t.trim(),t=t.replace(/^@/,""),a[o]=t}),a}function GQa(n,e){cQa.forEach(function(r){n[r]&&(n[r]=fQa(n[r],r,e))})}function gQa(n,e){n&&Object.keys(n).forEach(function(r){UQ.bugs[r]&&(e("typo",r,UQ.bugs[r],"bugs"),n[UQ.bugs[r]]=n[r],delete n[r])})}});var UQr=Le((_gs,vQa)=>{vQa.exports={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."}});var PQr=Le((Pgs,_Qr)=>{var zQr=Yt("util"),pmt=UQr();_Qr.exports=function(){var n=Array.prototype.slice.call(arguments,0),e=n.shift();if(e==="typo")return yQa.apply(null,n);var r=pmt[e]?pmt[e]:e+": '%s'";return n.unshift(r),zQr.format.apply(null,n)};function yQa(n,e,r){return r&&(n=r+"['"+n+"']",e=r+"['"+e+"']"),zQr.format(pmt.typo,n,e)}});var $Qr=Le((jgs,KQr)=>{KQr.exports=jQr;var bmt=MQr();jQr.fixer=bmt;var ZQa=PQr(),WQa=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"],NQa=["dependencies","people","typos"],fmt=WQa.map(function(n){return qQr(n)+"Field"});fmt=fmt.concat(NQa);function jQr(n,e,r){e===!0&&(e=null,r=!0),r||(r=!1),(!e||n.private)&&(e=function(){}),n.scripts&&n.scripts.install==="node-gyp rebuild"&&!n.scripts.preinstall&&(n.gypfile=!0),bmt.warn=function(){e(ZQa.apply(null,arguments))},fmt.forEach(function(a){bmt["fix"+qQr(a)](n,r)}),n._id=n.name+"@"+n.version}function qQr(n){return n.charAt(0).toUpperCase()+n.slice(1)}});var eHr=De(()=>{});import{fileURLToPath as FQa}from"node:url";function tHr(n){return n instanceof URL?FQa(n):n}var rHr=De(()=>{eHr()});import wQa from"node:fs/promises";import RQa from"node:path";async function aHr({cwd:n,normalize:e=!0}={}){let r=await wQa.readFile(AQa(n),"utf8");return EQa(r,e)}var nHr,AQa,EQa,iHr=De(()=>{MVr();nHr=Vt($Qr(),1);rHr();AQa=n=>RQa.resolve(tHr(n)??".","package.json"),EQa=(n,e)=>{let r=typeof n=="string"?j0t(n):n;return e&&(0,nHr.default)(r),r}});import xQa from"node:path";async function sHr(n){let e=await fVr("package.json",n);if(e)return{packageJson:await aHr({...n,cwd:xQa.dirname(e)}),path:e}}var oHr=De(()=>{GVr();iHr()});import{fileURLToPath as CQa}from"url";import YQa from"path";async function L_(){if(S_)return S_;let n=await sHr({cwd:QQa});if(!n){let e="hwjcode-cli",r="1.1.133";return e&&r?(S_={name:e,version:r},S_):void 0}return S_=n.packageJson,S_}var VQa,QQa,S_,cEe=De(()=>{"use strict";oHr();VQa=CQa(import.meta.url),QQa=YQa.dirname(VQa)});var lHr={};Ws(lHr,{getCliVersion:()=>qF});async function qF(){let n=await L_();return"1.1.133"}var y6=De(()=>{"use strict";cEe();});import Z6 from"node:process";var cHr,uHr=De(()=>{"use strict";y6();Fi();Xs();fn();cHr={name:"about",description:we("command.about.description"),kind:"built-in",action:async n=>{let e=Z6.platform,r="no sandbox";Z6.env.SANDBOX&&Z6.env.SANDBOX!=="sandbox-exec"?r=Z6.env.SANDBOX:Z6.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${Z6.env.SEATBELT_PROFILE||"unknown"})`);let a=n.services.config?.getModel()||"Unknown",i=await qF(),o=n.services.settings.merged.selectedAuthType||"",t=Z6.env.GOOGLE_CLOUD_PROJECT||"",s={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:a,selectedAuthType:o,gcpProject:t};n.ui.addItem(s,Date.now())}}});var dHr,IHr=De(()=>{"use strict";Fi();fn();dHr={name:"auth",description:we("command.auth.description"),kind:"built-in",action:(n,e)=>({type:"dialog",dialog:"auth"})}});var hHr,mHr=De(()=>{"use strict";Fi();fn();hHr={name:"clear",description:we("command.clear.description"),kind:"built-in",action:async(n,e)=>{n.ui.setDebugMessage("Clearing terminal screen."),n.ui.clear()}}});var pHr,bHr=De(()=>{"use strict";Xs();Fi();fn();pHr={name:"compress",altNames:["summarize","compact"],description:we("command.compress.description"),kind:"built-in",action:async n=>{let{ui:e}=n,r=n.services.config?.getGeminiClient();if(e.pendingItem){e.addItem({type:"error",text:"Already compressing, wait for previous request to complete"},Date.now());return}if(r?.isCompressionInProgress()){e.addItem({type:"error",text:"Compression already in progress at client level, please wait"},Date.now());return}e.addItem({type:"info",text:we("command.compress.starting")},Date.now());let a={type:"compression",compression:{isPending:!0,originalTokenCount:null,newTokenCount:null}};try{e.setPendingItem(a);let i=`compress-${Date.now()}`,o=await r?.tryCompressChat(i,new AbortController().signal,!0);o?e.addItem({type:"compression",compression:{isPending:!1,originalTokenCount:o.originalTokenCount,newTokenCount:o.newTokenCount}},Date.now()):e.addItem({type:"error",text:"Failed to compress chat history."},Date.now())}catch(i){e.addItem({type:"error",text:`Failed to compress chat history: ${i instanceof Error?i.message:String(i)}`},Date.now())}finally{e.setPendingItem(null)}}}});function J_(n=KZ()){return n.edition==="personal"?["all","none"]:["all","deepv-only","none"]}function B_(n,e=KZ()){return e.edition==="personal"&&n==="deepv-only"?"all":n??"all"}function fHr(n,e=KZ()){return J_(e).includes(n)}function uEe(n,e,r=KZ()){let a=B_(e,r);if(a==="none")return{memoryContent:"",fileCount:0,filePaths:[]};if(a==="deepv-only"){let i=n.filePaths.filter(t=>!(t.split(/[\\/]/).pop()||"").toUpperCase().startsWith("AGENTS"));return i.length===n.filePaths.length?n:{memoryContent:n.memoryContent.split(`
5486
+ `);let e=0;for(;n[e]&&n[e].trim().match(/^(#|$)/);)e++;let r=n.length,a=e+1;for(;a<r&&n[a].trim();)a++;return n.slice(e,a).join(" ").trim()}});var BQr=Le((Ugs,aQa)=>{aQa.exports={topLevel:{dependancies:"dependencies",dependecies:"dependencies",depdenencies:"dependencies",devEependencies:"devDependencies",depends:"dependencies","dev-dependencies":"devDependencies",devDependences:"devDependencies",devDepenencies:"devDependencies",devdependencies:"devDependencies",repostitory:"repository",repo:"repository",prefereGlobal:"preferGlobal",hompage:"homepage",hampage:"homepage",autohr:"author",autor:"author",contributers:"contributors",publicationConfig:"publishConfig",script:"scripts"},bugs:{web:"url",name:"url"},script:{server:"start",tests:"test"}}});var MQr=Le((zgs,OQr)=>{var iQa=rmt(),sQa=nmt(),oQa=NQr(),lEe=SQr(),lQa=Yt("node:module"),cQa=["dependencies","devDependencies","optionalDependencies"],uQa=JQr(),mmt=Yt("url"),UQ=BQr(),TQr=n=>n.includes("@")&&n.indexOf("@")<n.lastIndexOf(".");OQr.exports={warn:function(){},fixRepositoryField:function(n){if(n.repositories&&(this.warn("repositories"),n.repository=n.repositories[0]),!n.repository)return this.warn("missingRepository");typeof n.repository=="string"&&(n.repository={type:"git",url:n.repository});var e=n.repository.url||"";if(e){var r=lEe.fromUrl(e);r&&(e=n.repository.url=r.getDefaultRepresentation()==="shortcut"?r.https():r.toString())}e.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)&&this.warn("brokenGitUrl",e)},fixTypos:function(n){Object.keys(UQ.topLevel).forEach(function(e){Object.prototype.hasOwnProperty.call(n,e)&&this.warn("typo",e,UQ.topLevel[e])},this)},fixScriptsField:function(n){if(n.scripts){if(typeof n.scripts!="object"){this.warn("nonObjectScripts"),delete n.scripts;return}Object.keys(n.scripts).forEach(function(e){typeof n.scripts[e]!="string"?(this.warn("nonStringScript"),delete n.scripts[e]):UQ.script[e]&&!n.scripts[UQ.script[e]]&&this.warn("typo",e,UQ.script[e],"scripts")},this)}},fixFilesField:function(n){var e=n.files;e&&!Array.isArray(e)?(this.warn("nonArrayFiles"),delete n.files):n.files&&(n.files=n.files.filter(function(r){return!r||typeof r!="string"?(this.warn("invalidFilename",r),!1):!0},this))},fixBinField:function(n){if(n.bin&&typeof n.bin=="string"){var e={},r;(r=n.name.match(/^@[^/]+[/](.*)$/))?e[r[1]]=n.bin:e[n.name]=n.bin,n.bin=e}},fixManField:function(n){n.man&&typeof n.man=="string"&&(n.man=[n.man])},fixBundleDependenciesField:function(n){var e="bundledDependencies",r="bundleDependencies";n[e]&&!n[r]&&(n[r]=n[e],delete n[e]),n[r]&&!Array.isArray(n[r])?(this.warn("nonArrayBundleDependencies"),delete n[r]):n[r]&&(n[r]=n[r].filter(function(a){return!a||typeof a!="string"?(this.warn("nonStringBundleDependency",a),!1):(n.dependencies||(n.dependencies={}),Object.prototype.hasOwnProperty.call(n.dependencies,a)||(this.warn("nonDependencyBundleDependency",a),n.dependencies[a]="*"),!0)},this))},fixDependencies:function(n){GQa(n,this.warn),bQa(n,this.warn),this.fixBundleDependenciesField(n),["dependencies","devDependencies"].forEach(function(e){if(e in n){if(!n[e]||typeof n[e]!="object"){this.warn("nonObjectDependencies",e),delete n[e];return}Object.keys(n[e]).forEach(function(r){var a=n[e][r];typeof a!="string"&&(this.warn("nonStringDependency",r,JSON.stringify(a)),delete n[e][r]);var i=lEe.fromUrl(n[e][r]);i&&(n[e][r]=i.toString())},this)}},this)},fixModulesField:function(n){n.modules&&(this.warn("deprecatedModules"),delete n.modules)},fixKeywordsField:function(n){typeof n.keywords=="string"&&(n.keywords=n.keywords.split(/,\s+/)),n.keywords&&!Array.isArray(n.keywords)?(delete n.keywords,this.warn("nonArrayKeywords")):n.keywords&&(n.keywords=n.keywords.filter(function(e){return typeof e!="string"||!e?(this.warn("nonStringKeyword"),!1):!0},this))},fixVersionField:function(n,e){var r=!e;if(!n.version)return n.version="",!0;if(!iQa(n.version,r))throw new Error('Invalid version: "'+n.version+'"');return n.version=sQa(n.version,r),!0},fixPeople:function(n){DQr(n,mQa),DQr(n,pQa)},fixNameField:function(n,e){typeof e=="boolean"?e={strict:e}:typeof e>"u"&&(e={});var r=e.strict;if(!n.name&&!r){n.name="";return}if(typeof n.name!="string")throw new Error("name field must be a string.");r||(n.name=n.name.trim()),hQa(n.name,r,e.allowLegacyCase),lQa.builtinModules.includes(n.name)&&this.warn("conflictingName",n.name)},fixDescriptionField:function(n){n.description&&typeof n.description!="string"&&(this.warn("nonStringDescription"),delete n.description),n.readme&&!n.description&&(n.description=uQa(n.readme)),n.description===void 0&&delete n.description,n.description||this.warn("missingDescription")},fixReadmeField:function(n){n.readme||(this.warn("missingReadme"),n.readme="ERROR: No README data found!")},fixBugsField:function(n){if(!n.bugs&&n.repository&&n.repository.url){var e=lEe.fromUrl(n.repository.url);e&&e.bugs()&&(n.bugs={url:e.bugs()})}else if(n.bugs){if(typeof n.bugs=="string")TQr(n.bugs)?n.bugs={email:n.bugs}:mmt.parse(n.bugs).protocol?n.bugs={url:n.bugs}:this.warn("nonEmailUrlBugsString");else{gQa(n.bugs,this.warn);var r=n.bugs;n.bugs={},r.url&&(typeof r.url=="string"&&mmt.parse(r.url).protocol?n.bugs.url=r.url:this.warn("nonUrlBugsUrlField")),r.email&&(typeof r.email=="string"&&TQr(r.email)?n.bugs.email=r.email:this.warn("nonEmailBugsEmailField"))}!n.bugs.email&&!n.bugs.url&&(delete n.bugs,this.warn("emptyNormalizedBugs"))}},fixHomepageField:function(n){if(!n.homepage&&n.repository&&n.repository.url){var e=lEe.fromUrl(n.repository.url);e&&e.docs()&&(n.homepage=e.docs())}if(n.homepage){if(typeof n.homepage!="string")return this.warn("nonUrlHomepage"),delete n.homepage;mmt.parse(n.homepage).protocol||(n.homepage="http://"+n.homepage)}},fixLicenseField:function(n){let e=n.license||n.licence;if(!e)return this.warn("missingLicense");if(typeof e!="string"||e.length<1||e.trim()==="")return this.warn("invalidLicense");if(!oQa(e).validForNewPackages)return this.warn("invalidLicense")}};function dQa(n){if(n.charAt(0)!=="@")return!1;var e=n.slice(1).split("/");return e.length!==2?!1:e[0]&&e[1]&&e[0]===encodeURIComponent(e[0])&&e[1]===encodeURIComponent(e[1])}function IQa(n){return!n.match(/[/@\s+%:]/)&&n===encodeURIComponent(n)}function hQa(n,e,r){if(n.charAt(0)==="."||!(dQa(n)||IQa(n))||e&&!r&&n!==n.toLowerCase()||n.toLowerCase()==="node_modules"||n.toLowerCase()==="favicon.ico")throw new Error("Invalid name: "+JSON.stringify(n))}function DQr(n,e){return n.author&&(n.author=e(n.author)),["maintainers","contributors"].forEach(function(r){Array.isArray(n[r])&&(n[r]=n[r].map(e))}),n}function mQa(n){if(typeof n=="string")return n;var e=n.name||"",r=n.url||n.web,a=r?" ("+r+")":"",i=n.email||n.mail,o=i?" <"+i+">":"";return e+o+a}function pQa(n){if(typeof n!="string")return n;var e=n.match(/^([^(<]+)/),r=n.match(/\(([^()]+)\)/),a=n.match(/<([^<>]+)>/),i={};return e&&e[0].trim()&&(i.name=e[0].trim()),a&&(i.email=a[1]),r&&(i.url=r[1]),i}function bQa(n){var e=n.optionalDependencies;if(e){var r=n.dependencies||{};Object.keys(e).forEach(function(a){r[a]=e[a]}),n.dependencies=r}}function fQa(n,e,r){if(!n)return{};if(typeof n=="string"&&(n=n.trim().split(/[\n\r\s\t ,]+/)),!Array.isArray(n))return n;r("deprecatedArrayDependencies",e);var a={};return n.filter(function(i){return typeof i=="string"}).forEach(function(i){i=i.trim().split(/(:?[@\s><=])/);var o=i.shift(),t=i.join("");t=t.trim(),t=t.replace(/^@/,""),a[o]=t}),a}function GQa(n,e){cQa.forEach(function(r){n[r]&&(n[r]=fQa(n[r],r,e))})}function gQa(n,e){n&&Object.keys(n).forEach(function(r){UQ.bugs[r]&&(e("typo",r,UQ.bugs[r],"bugs"),n[UQ.bugs[r]]=n[r],delete n[r])})}});var UQr=Le((_gs,vQa)=>{vQa.exports={repositories:"'repositories' (plural) Not supported. Please pick one as the 'repository' field",missingRepository:"No repository field.",brokenGitUrl:"Probably broken git url: %s",nonObjectScripts:"scripts must be an object",nonStringScript:"script values must be string commands",nonArrayFiles:"Invalid 'files' member",invalidFilename:"Invalid filename in 'files' list: %s",nonArrayBundleDependencies:"Invalid 'bundleDependencies' list. Must be array of package names",nonStringBundleDependency:"Invalid bundleDependencies member: %s",nonDependencyBundleDependency:"Non-dependency in bundleDependencies: %s",nonObjectDependencies:"%s field must be an object",nonStringDependency:"Invalid dependency: %s %s",deprecatedArrayDependencies:"specifying %s as array is deprecated",deprecatedModules:"modules field is deprecated",nonArrayKeywords:"keywords should be an array of strings",nonStringKeyword:"keywords should be an array of strings",conflictingName:"%s is also the name of a node core module.",nonStringDescription:"'description' field should be a string",missingDescription:"No description",missingReadme:"No README data",missingLicense:"No license field.",nonEmailUrlBugsString:"Bug string field must be url, email, or {email,url}",nonUrlBugsUrlField:"bugs.url field must be a string url. Deleted.",nonEmailBugsEmailField:"bugs.email field must be a string email. Deleted.",emptyNormalizedBugs:"Normalized value of bugs field is an empty object. Deleted.",nonUrlHomepage:"homepage field must be a string url. Deleted.",invalidLicense:"license should be a valid SPDX license expression",typo:"%s should probably be %s."}});var PQr=Le((Pgs,_Qr)=>{var zQr=Yt("util"),pmt=UQr();_Qr.exports=function(){var n=Array.prototype.slice.call(arguments,0),e=n.shift();if(e==="typo")return yQa.apply(null,n);var r=pmt[e]?pmt[e]:e+": '%s'";return n.unshift(r),zQr.format.apply(null,n)};function yQa(n,e,r){return r&&(n=r+"['"+n+"']",e=r+"['"+e+"']"),zQr.format(pmt.typo,n,e)}});var $Qr=Le((jgs,KQr)=>{KQr.exports=jQr;var bmt=MQr();jQr.fixer=bmt;var ZQa=PQr(),WQa=["name","version","description","repository","modules","scripts","files","bin","man","bugs","keywords","readme","homepage","license"],NQa=["dependencies","people","typos"],fmt=WQa.map(function(n){return qQr(n)+"Field"});fmt=fmt.concat(NQa);function jQr(n,e,r){e===!0&&(e=null,r=!0),r||(r=!1),(!e||n.private)&&(e=function(){}),n.scripts&&n.scripts.install==="node-gyp rebuild"&&!n.scripts.preinstall&&(n.gypfile=!0),bmt.warn=function(){e(ZQa.apply(null,arguments))},fmt.forEach(function(a){bmt["fix"+qQr(a)](n,r)}),n._id=n.name+"@"+n.version}function qQr(n){return n.charAt(0).toUpperCase()+n.slice(1)}});var eHr=De(()=>{});import{fileURLToPath as FQa}from"node:url";function tHr(n){return n instanceof URL?FQa(n):n}var rHr=De(()=>{eHr()});import wQa from"node:fs/promises";import RQa from"node:path";async function aHr({cwd:n,normalize:e=!0}={}){let r=await wQa.readFile(AQa(n),"utf8");return EQa(r,e)}var nHr,AQa,EQa,iHr=De(()=>{MVr();nHr=Vt($Qr(),1);rHr();AQa=n=>RQa.resolve(tHr(n)??".","package.json"),EQa=(n,e)=>{let r=typeof n=="string"?j0t(n):n;return e&&(0,nHr.default)(r),r}});import xQa from"node:path";async function sHr(n){let e=await fVr("package.json",n);if(e)return{packageJson:await aHr({...n,cwd:xQa.dirname(e)}),path:e}}var oHr=De(()=>{GVr();iHr()});import{fileURLToPath as CQa}from"url";import YQa from"path";async function L_(){if(S_)return S_;let n=await sHr({cwd:QQa});if(!n){let e="hwjcode-cli",r="1.1.134";return e&&r?(S_={name:e,version:r},S_):void 0}return S_=n.packageJson,S_}var VQa,QQa,S_,cEe=De(()=>{"use strict";oHr();VQa=CQa(import.meta.url),QQa=YQa.dirname(VQa)});var lHr={};Ws(lHr,{getCliVersion:()=>qF});async function qF(){let n=await L_();return"1.1.134"}var y6=De(()=>{"use strict";cEe();});import Z6 from"node:process";var cHr,uHr=De(()=>{"use strict";y6();Fi();Xs();fn();cHr={name:"about",description:we("command.about.description"),kind:"built-in",action:async n=>{let e=Z6.platform,r="no sandbox";Z6.env.SANDBOX&&Z6.env.SANDBOX!=="sandbox-exec"?r=Z6.env.SANDBOX:Z6.env.SANDBOX==="sandbox-exec"&&(r=`sandbox-exec (${Z6.env.SEATBELT_PROFILE||"unknown"})`);let a=n.services.config?.getModel()||"Unknown",i=await qF(),o=n.services.settings.merged.selectedAuthType||"",t=Z6.env.GOOGLE_CLOUD_PROJECT||"",s={type:"about",cliVersion:i,osVersion:e,sandboxEnv:r,modelVersion:a,selectedAuthType:o,gcpProject:t};n.ui.addItem(s,Date.now())}}});var dHr,IHr=De(()=>{"use strict";Fi();fn();dHr={name:"auth",description:we("command.auth.description"),kind:"built-in",action:(n,e)=>({type:"dialog",dialog:"auth"})}});var hHr,mHr=De(()=>{"use strict";Fi();fn();hHr={name:"clear",description:we("command.clear.description"),kind:"built-in",action:async(n,e)=>{n.ui.setDebugMessage("Clearing terminal screen."),n.ui.clear()}}});var pHr,bHr=De(()=>{"use strict";Xs();Fi();fn();pHr={name:"compress",altNames:["summarize","compact"],description:we("command.compress.description"),kind:"built-in",action:async n=>{let{ui:e}=n,r=n.services.config?.getGeminiClient();if(e.pendingItem){e.addItem({type:"error",text:"Already compressing, wait for previous request to complete"},Date.now());return}if(r?.isCompressionInProgress()){e.addItem({type:"error",text:"Compression already in progress at client level, please wait"},Date.now());return}e.addItem({type:"info",text:we("command.compress.starting")},Date.now());let a={type:"compression",compression:{isPending:!0,originalTokenCount:null,newTokenCount:null}};try{e.setPendingItem(a);let i=`compress-${Date.now()}`,o=await r?.tryCompressChat(i,new AbortController().signal,!0);o?e.addItem({type:"compression",compression:{isPending:!1,originalTokenCount:o.originalTokenCount,newTokenCount:o.newTokenCount}},Date.now()):e.addItem({type:"error",text:"Failed to compress chat history."},Date.now())}catch(i){e.addItem({type:"error",text:`Failed to compress chat history: ${i instanceof Error?i.message:String(i)}`},Date.now())}finally{e.setPendingItem(null)}}}});function J_(n=KZ()){return n.edition==="personal"?["all","none"]:["all","deepv-only","none"]}function B_(n,e=KZ()){return e.edition==="personal"&&n==="deepv-only"?"all":n??"all"}function fHr(n,e=KZ()){return J_(e).includes(n)}function uEe(n,e,r=KZ()){let a=B_(e,r);if(a==="none")return{memoryContent:"",fileCount:0,filePaths:[]};if(a==="deepv-only"){let i=n.filePaths.filter(t=>!(t.split(/[\\/]/).pop()||"").toUpperCase().startsWith("AGENTS"));return i.length===n.filePaths.length?n:{memoryContent:n.memoryContent.split(`
5487
5487
 
5488
5488
  `).filter(t=>!t.includes("AGENTS.md ---")).join(`
5489
5489
 
@@ -6566,7 +6566,7 @@ ${a.length>0?a.join(`
6566
6566
  </vote>`,resources:[]};let o=[];i.topic&&o.push(i.topic);for(let t of(a=i.options)!==null&&a!==void 0?a:[])o.push(`\u2022 ${t}`);return{content:`<vote>
6567
6567
  ${o.join(`
6568
6568
  `)}
6569
- </vote>`,resources:[]}}),cza=new Map([["text",aza],["post",K7a],["image",M7a],["file",T7a],["audio",S7a],["video",_Dr],["media",_Dr],["sticker",rza],["interactive",z7a],["merge_forward",P7a],["share_chat",eza],["share_user",tza],["location",_7a],["system",nza],["vote",lza],["todo",iza],["calendar",L7a],["general_calendar",J7a],["share_calendar_event",B7a],["folder",D7a],["hongbao",O7a],["video_chat",oza]]);function PDr(n,e,r){var a;return K(this,void 0,void 0,function*(){let i=(a=cza.get(e))!==null&&a!==void 0?a:zDr;try{return yield i(n,r)}catch{return zDr(n)}})}function dOr(n,e){var r,a,i,o,t,s,d,I,u,h,c,m;let y=(a=(r=n.context)===null||r===void 0?void 0:r.open_message_id)!==null&&a!==void 0?a:n.open_message_id,g=(o=(i=n.context)===null||i===void 0?void 0:i.open_chat_id)!==null&&o!==void 0?o:n.open_chat_id,Z=(t=n.operator)===null||t===void 0?void 0:t.open_id;return!y||!g||!Z?null:{messageId:y,chatId:g,operator:{openId:Z,userId:(s=n.operator)===null||s===void 0?void 0:s.user_id,name:(d=n.operator)===null||d===void 0?void 0:d.name},action:{value:(I=n.action)===null||I===void 0?void 0:I.value,tag:(h=(u=n.action)===null||u===void 0?void 0:u.tag)!==null&&h!==void 0?h:"unknown",name:(c=n.action)===null||c===void 0?void 0:c.name,option:(m=n.action)===null||m===void 0?void 0:m.option},raw:e?.includeRaw?n:void 0}}function wGt(n,e,r){var a,i,o,t;let s=n.message_id,d=(a=n.reaction_type)===null||a===void 0?void 0:a.emoji_type,I=(i=n.user_id)===null||i===void 0?void 0:i.open_id;if(!s||!d||!I)return null;let u=n.action_time,h=u?parseInt(u,10):void 0;return{messageId:s,operator:{openId:I,userId:(t=(o=n.user_id)===null||o===void 0?void 0:o.user_id)!==null&&t!==void 0?t:void 0},emojiType:d,action:e,actionTime:h!=null&&Number.isFinite(h)?h:void 0,raw:r?.includeRaw?n:void 0}}function IOr(n,e){var r,a,i,o,t,s,d,I,u;let h=n.chat_id,c=(r=n.operator_id)===null||r===void 0?void 0:r.open_id;if(!h||!c)return null;let m=(s=(o=(a=n.name)!==null&&a!==void 0?a:(i=n.i18n_names)===null||i===void 0?void 0:i.zh_cn)!==null&&o!==void 0?o:(t=n.i18n_names)===null||t===void 0?void 0:t.en_us)!==null&&s!==void 0?s:(d=n.i18n_names)===null||d===void 0?void 0:d.ja_jp;return{chatId:h,operator:{openId:c,userId:(u=(I=n.operator_id)===null||I===void 0?void 0:I.user_id)!==null&&u!==void 0?u:void 0},botName:m,external:n.external,raw:e?.includeRaw?n:void 0}}function hOr(n,e){var r,a,i,o,t,s,d,I,u,h,c,m,y;let g=(r=n.file_token)!==null&&r!==void 0?r:(a=n.notice_meta)===null||a===void 0?void 0:a.file_token,Z=(i=n.file_type)!==null&&i!==void 0?i:(o=n.notice_meta)===null||o===void 0?void 0:o.file_type,v=n.comment_id,E=(s=(t=n.notice_meta)===null||t===void 0?void 0:t.from_user_id)!==null&&s!==void 0?s:n.user_id,w=E?.open_id;if(!g||!Z||!v||!w)return null;let R=(u=(d=n.create_time)!==null&&d!==void 0?d:(I=n.notice_meta)===null||I===void 0?void 0:I.timestamp)!==null&&u!==void 0?u:n.action_time,b=R?parseInt(R,10):Date.now();return{fileToken:g,fileType:Z,commentId:v,replyId:n.reply_id,operator:{openId:w,userId:(h=E?.user_id)!==null&&h!==void 0?h:void 0,unionId:E?.union_id},mentionedBot:!!((y=(c=n.is_mentioned)!==null&&c!==void 0?c:(m=n.notice_meta)===null||m===void 0?void 0:m.is_mentioned)!==null&&y!==void 0?y:n.is_mention),timestamp:Number.isFinite(b)?b:Date.now(),raw:e?.includeRaw?n:void 0}}function mOr(n,e){var r,a,i,o,t;return K(this,void 0,void 0,function*(){let s=n.message,d=(r=e.botIdentity)===null||r===void 0?void 0:r.openId,{mentions:I,mentionsByOpenId:u,mentionList:h,mentionAll:c,mentionedBot:m}=x7a(s.mentions,d),y=c||uza(s.content),g={messageId:s.message_id,botOpenId:d,mentions:I,mentionsByOpenId:u,stripBotMentions:(a=e.stripBotMentions)!==null&&a!==void 0?a:!0,fetchSubMessages:e.fetchSubMessages,resolveUserName:e.resolveUserName,batchResolveNames:e.batchResolveNames,dispatch:PDr},{content:Z,resources:v}=yield PDr(s.content,s.message_type,g),E=C7a(Z,g),w=n.sender.sender_id.open_id,R=(o=(i=n.sender.sender_id.user_id)!==null&&i!==void 0?i:n.sender.sender_id.union_id)!==null&&o!==void 0?o:"",b=w??R,W=w?(t=e.resolveSenderName)===null||t===void 0?void 0:t.call(e,w):void 0,N=s.create_time?parseInt(s.create_time,10):0;return{messageId:s.message_id,chatId:s.chat_id,chatType:s.chat_type,senderId:b,senderName:W,content:E,rawContentType:s.message_type,resources:v,mentions:h,mentionAll:y,mentionedBot:m,rootId:s.root_id,threadId:s.thread_id,replyToMessageId:s.parent_id,createTime:Number.isFinite(N)?N:0,raw:e.includeRaw?n:void 0}})}function uza(n){return n?/@_all\b/.test(n):!1}var lCe=class{constructor(e){var r,a,i,o,t,s,d;this.handlers={},this.connected=!1,this.opts=e,this.logger=new hH((r=e.loggerLevel)!==null&&r!==void 0?r:Qa.LoggerLevel.info,(a=e.logger)!==null&&a!==void 0?a:iC),this.rawClient=new eCe({appId:e.appId,appSecret:e.appSecret,domain:(i=e.domain)!==null&&i!==void 0?i:Qa.Domain.Feishu,cache:e.cache,httpInstance:e.httpInstance,logger:e.logger,loggerLevel:e.loggerLevel,source:e.source,extraUaTags:["channel"]}),this.dispatcher=new rCe({verificationToken:(o=e.webhook)===null||o===void 0?void 0:o.verificationToken,encryptKey:(t=e.webhook)===null||t===void 0?void 0:t.encryptKey,cache:e.cache,logger:e.logger,loggerLevel:e.loggerLevel}),this.sender=new gGt(this.rawClient,(s=e.outbound)!==null&&s!==void 0?s:{},this.logger),this.safety=new FGt({config:e.safety,policy:e.policy,cache:(d=e.cache)!==null&&d!==void 0?d:kue,logger:this.logger,onReject:I=>{var u,h;(h=(u=this.handlers).reject)===null||h===void 0||h.call(u,I)},onMessage:I=>K(this,void 0,void 0,function*(){let u=this.handlers.message;u&&(yield u(I))})})}connect(){return K(this,void 0,void 0,function*(){return this.connectPromise?this.connectPromise:(this.connectPromise=this.doConnect().catch(e=>{throw this.connectPromise=void 0,e}),this.connectPromise)})}doConnect(){var e;return K(this,void 0,void 0,function*(){this.botIdentity=yield this.fetchBotIdentity(),this.safety.setBotIdentity(this.botIdentity),this.registerDispatcherHandlers(),((e=this.opts.transport)!==null&&e!==void 0?e:"websocket")==="websocket"&&(yield this.connectWebSocket(15e3)),this.connected=!0})}connectWebSocket(e){return new Promise((r,a)=>{var i;let o=!1,t=setTimeout(()=>{o||(o=!0,a(new su("not_connected",`WebSocket handshake did not complete within ${e}ms`)))},e);this.rawWsClient=new aCe({appId:this.opts.appId,appSecret:this.opts.appSecret,domain:(i=this.opts.domain)!==null&&i!==void 0?i:Qa.Domain.Feishu,logger:this.opts.logger,loggerLevel:this.opts.loggerLevel,httpInstance:this.opts.httpInstance,autoReconnect:!0,source:this.opts.source,extraUaTags:["channel"],agent:this.opts.agent,wsConfig:this.opts.wsConfig,handshakeTimeoutMs:this.opts.handshakeTimeoutMs,onReady:()=>{o||(o=!0,clearTimeout(t),r())},onError:s=>{o||(o=!0,clearTimeout(t),a(new su("not_connected",`WebSocket connect failed: ${s.message}`,{cause:s})))},onReconnecting:()=>{var s,d;return(d=(s=this.handlers).reconnecting)===null||d===void 0?void 0:d.call(s)},onReconnected:()=>{var s,d;return(d=(s=this.handlers).reconnected)===null||d===void 0?void 0:d.call(s)}}),this.rawWsClient.start({eventDispatcher:this.dispatcher})})}disconnect(){var e;return K(this,void 0,void 0,function*(){if(this.connected){try{(e=this.rawWsClient)===null||e===void 0||e.close({})}catch{}try{yield this.safety.dispose()}catch{}this.connected=!1,this.connectPromise=void 0}})}getConnectionStatus(){var e;return(e=this.rawWsClient)===null||e===void 0?void 0:e.getConnectionStatus()}on(e,r){if(typeof e=="string")return this.attachSingle(e,r);let a=[];return Object.keys(e).forEach(i=>{let o=e[i];o&&a.push(this.attachSingle(i,o))}),()=>a.forEach(i=>i())}attachSingle(e,r){return this.handlers[e]&&this.logger.warn(`channel: handler for "${e}" is being overwritten`),this.handlers[e]=r,()=>{this.handlers[e]===r&&delete this.handlers[e]}}send(e,r,a){return K(this,void 0,void 0,function*(){return this.sender.send(e,r,a)})}stream(e,r,a){return K(this,void 0,void 0,function*(){return this.sender.stream(e,r,a)})}updateCard(e,r){return K(this,void 0,void 0,function*(){yield this.sender.patchCard(e,r)})}editMessage(e,r){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.update({path:{message_id:e},data:{msg_type:"text",content:JSON.stringify({text:r})}})})}recallMessage(e){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.delete({path:{message_id:e}})})}addReaction(e,r){var a,i;return K(this,void 0,void 0,function*(){let o=yield this.rawClient.im.v1.messageReaction.create({path:{message_id:e},data:{reaction_type:{emoji_type:r}}}),t=(i=(a=o?.data)===null||a===void 0?void 0:a.reaction_id)!==null&&i!==void 0?i:o?.reaction_id;if(!t)throw new su("unknown","messageReaction.create returned no reaction_id");return t})}removeReaction(e,r){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.messageReaction.delete({path:{message_id:e,reaction_id:r}})})}removeReactionByEmoji(e,r){var a,i;return K(this,void 0,void 0,function*(){let o=yield this.rawClient.im.v1.messageReaction.list({path:{message_id:e},params:{reaction_type:r,page_size:50}}),s=((i=(a=o?.data)===null||a===void 0?void 0:a.items)!==null&&i!==void 0?i:[]).find(d=>{var I;return((I=d.operator)===null||I===void 0?void 0:I.operator_type)==="app"});return s?.reaction_id?(yield this.removeReaction(e,s.reaction_id),!0):!1})}downloadResource(e,r){return K(this,void 0,void 0,function*(){if(r==="image"){let i=yield this.rawClient.im.v1.image.get({path:{image_key:e}});return yield jDr(i)}let a=yield this.rawClient.im.v1.file.get({path:{file_key:e}});return yield jDr(a)})}getChatInfo(e){var r,a;return K(this,void 0,void 0,function*(){let o=(r=(yield this.rawClient.im.v1.chat.get({path:{chat_id:e}})).data)!==null&&r!==void 0?r:{};return{chatId:e,name:o.name,description:o.description,chatType:(a=o.chat_mode)!==null&&a!==void 0?a:"group",ownerId:o.owner_id,memberCount:o.user_count}})}getChatMode(e){var r;return K(this,void 0,void 0,function*(){let i=(r=(yield this.rawClient.im.v1.chat.get({path:{chat_id:e}})).data)===null||r===void 0?void 0:r.chat_mode;return i==="p2p"?"p2p":i==="topic"?"topic":"group"})}updatePolicy(e){this.safety.updatePolicy(e)}getPolicy(){return this.safety.getPolicy()}fetchBotIdentity(){var e;return K(this,void 0,void 0,function*(){let r;try{let o=yield this.rawClient.request({url:"/open-apis/bot/v3/info",method:"GET"}),t=o.bot;if(t?.open_id)return{openId:t.open_id,name:(e=t.app_name)!==null&&e!==void 0?e:"bot"};r=new Error(`bot/v3/info response missing open_id: ${JSON.stringify(o).slice(0,200)}`)}catch(o){r=o}let a=EGt(r),i=a.code==="unknown"?"not_connected":a.code;throw new su(i,"could not resolve bot identity via /open-apis/bot/v3/info \u2014 required for channel to function",{cause:r})})}registerDispatcherHandlers(){var e,r;let a=t=>K(this,void 0,void 0,function*(){var s,d,I,u;try{return(d=(s=(yield this.rawClient.im.v1.message.get({path:{message_id:t}})).data)===null||s===void 0?void 0:s.items)!==null&&d!==void 0?d:[]}catch(h){return(u=(I=this.logger).warn)===null||u===void 0||u.call(I,"channel: fetchSubMessages failed",h),[]}}),i=(r=(e=this.opts.includeRawEvent)!==null&&e!==void 0?e:this.opts.includeRawInMessage)!==null&&r!==void 0?r:!1,o={botIdentity:this.botIdentity,stripBotMentions:!0,includeRaw:i,fetchSubMessages:a};this.dispatcher.register({"im.message.receive_v1":t=>K(this,void 0,void 0,function*(){try{let s=yield mOr(t,o);yield this.safety.pushMessage(s)}catch(s){this.emitError(s)}}),"card.action.trigger":t=>K(this,void 0,void 0,function*(){let s=dOr(t,{includeRaw:i});if(!s)return;let d=hza(s.action);yield this.safety.pushAction(`card:${s.messageId}:${s.operator.openId}:${d}`,s.chatId,()=>K(this,void 0,void 0,function*(){let I=this.handlers.cardAction;I&&(yield I(s))}))}),"im.message.reaction.created_v1":t=>K(this,void 0,void 0,function*(){let s=wGt(t,"added",{includeRaw:i});if(!s)return;let d=qDr(s);yield this.safety.pushLight(d,()=>{var I,u;return(u=(I=this.handlers).reaction)===null||u===void 0?void 0:u.call(I,s)})}),"im.message.reaction.deleted_v1":t=>K(this,void 0,void 0,function*(){let s=wGt(t,"removed",{includeRaw:i});if(!s)return;let d=qDr(s);yield this.safety.pushLight(d,()=>{var I,u;return(u=(I=this.handlers).reaction)===null||u===void 0?void 0:u.call(I,s)})}),"im.chat.member.bot.added_v1":t=>{var s,d;let I=IOr(t,{includeRaw:i});if(I)try{(d=(s=this.handlers).botAdded)===null||d===void 0||d.call(s,I)}catch(u){this.emitError(u)}},"drive.notice.comment_add_v1":t=>K(this,void 0,void 0,function*(){var s;let d=hOr(t,{includeRaw:i});d&&(yield this.safety.pushAction(`comment:${d.fileToken}:${d.commentId}:${(s=d.replyId)!==null&&s!==void 0?s:""}`,d.fileToken,()=>K(this,void 0,void 0,function*(){let I=this.handlers.comment;I&&(yield I(d))})))})})}emitError(e){var r,a,i;let o=e instanceof su?e:new su("unknown",String((r=e?.message)!==null&&r!==void 0?r:e),{cause:e}),t=this.handlers.error;t?t(o):(i=(a=this.logger).error)===null||i===void 0||i.call(a,"channel: unhandled error",o)}};function dza(n){return new lCe(n)}function jDr(n){return K(this,void 0,void 0,function*(){if(Buffer.isBuffer(n))return n;if(n instanceof Uint8Array)return Buffer.from(n);if(typeof n=="object"&&n!==null){let e=n;if(typeof e.getReadableStream=="function")return yield Iza(e.getReadableStream());if(Buffer.isBuffer(e.data))return e.data;if(e.data instanceof Uint8Array)return Buffer.from(e.data)}throw new su("unknown","unexpected download response type")})}function Iza(n){return new Promise((e,r)=>{let a=[];n.on("data",i=>{a.push(Buffer.isBuffer(i)?i:Buffer.from(i))}),n.on("end",()=>e(Buffer.concat(a))),n.on("error",r)})}function qDr(n){var e;return`rx:${n.messageId}:${n.operator.openId}:${n.emojiType}:${n.action}:${(e=n.actionTime)!==null&&e!==void 0?e:0}`}function hza(n){var e,r,a;let i=typeof n.value=="string"?n.value:JSON.stringify((e=n.value)!==null&&e!==void 0?e:""),o=i.length>128?i.slice(0,128):i;return`${n.tag}|${(r=n.name)!==null&&r!==void 0?r:""}|${(a=n.option)!==null&&a!==void 0?a:""}|${o}`}Qa.AESCipher=Xue;Qa.Aily=hGt;Qa.CAppTicket=Hue;Qa.CTenantAccessToken=Dft;Qa.CardActionHandler=cGt;Qa.Client=eCe;Qa.DefaultCache=$xe;Qa.EventDispatcher=rCe;Qa.LarkChannel=lCe;Qa.LarkChannelError=su;Qa.LoggerProxy=hH;Qa.WSClient=aCe;Qa.adaptDefault=NUa;Qa.adaptExpress=FUa;Qa.adaptKoa=wUa;Qa.adaptKoaRouter=RUa;Qa.createLarkChannel=dza;Qa.defaultHttpInstance=EP;Qa.defaultLogger=iC;Qa.generateChallenge=Sue;Qa.internalCache=kue;Qa.messageCard=EUa;Qa.normalize=mOr;Qa.normalizeBotAdded=IOr;Qa.normalizeCardAction=dOr;Qa.normalizeComment=hOr;Qa.normalizeReaction=wGt;Qa.registerApp=JUa;Qa.withAll=GUa;Qa.withHelpDeskCredential=vUa;Qa.withTenantKey=gUa;Qa.withTenantToken=yUa;Qa.withUserAccessToken=ZUa});import CGt from"node:os";import mH from"node:path";import Nv from"node:fs";function pza(){return process.env.EASYCODE_FEISHU_CARDKIT_V2==="1"}function fza(n){let e=n/1e3;if(e<60)return`${e.toFixed(1)}s`;let r=Math.floor(e/60),a=Math.round(e%60);return`${r}m ${a}s`}function dCe(n){let e=[],r=!1;if(n.status){let i=n.status,o=n.status.toLowerCase();o.includes("error")||o.includes("failed")||o.includes("\u51FA\u9519")||o.includes("\u5931\u8D25")?(i=`<font color='red'>${n.status}</font>`,r=!0):o.includes("processing")||o.includes("thinking")||o.includes("\u601D\u8003\u4E2D")||o.includes("\u8FD0\u884C")?i=`<font color='grey'>${n.status}</font>`:i=`<font color='green'>${n.status}</font>`,e.push(i)}if(n.elapsedMs!=null&&e.push(`\u8017\u65F6 ${fza(n.elapsedMs)}`),n.model&&e.push(n.model),n.delegateTokenDisplay?e.push(n.delegateTokenDisplay):n.tokens&&e.push(`\u2191${n.tokens.input.toLocaleString()} \u2193${n.tokens.output.toLocaleString()}`),n.cacheRead!=null&&n.cacheRead>0){let i=`\u7F13\u5B58\u8BFB\u53D6 ${n.cacheRead.toLocaleString()}`;n.cacheHitRate!=null&&n.cacheHitRate>0&&(i+=` (${n.cacheHitRate.toFixed(1)}%)`),e.push(i)}if(!n.delegateTokenDisplay&&n.contextPercentage!=null){let i=Math.max(0,100-n.contextPercentage);e.push(`\u4E0A\u4E0B\u6587\u5269\u4F59 ${i.toFixed(0)}%`)}if(n.quota&&e.push(n.quota),e.length===0)return"";let a=e.join(" \xB7 ");return r?`<font color='red'>${a}</font>`:a}function GOr(n){let e=dCe(n);return e?[{tag:"hr"},{tag:"markdown",content:e}]:[]}function Gza(n="",e=""){let r=[{tag:"markdown",element_id:YGt,content:n?rP(n,2):" ",text_align:"left",text_size:"normal_v2"},{tag:"markdown",element_id:mza,content:" ",icon:{tag:"custom_icon",img_key:bza,size:"16px 16px"}}];return e?r.push({tag:"markdown",element_id:uCe,content:e,text_size:"notation"}):r.push({tag:"markdown",element_id:uCe,content:" ",text_size:"notation"}),{schema:"2.0",config:{streaming_mode:!0,summary:{content:"Processing...",i18n_content:{zh_cn:"\u5904\u7406\u4E2D...",en_us:"Processing..."}}},body:{elements:r}}}function pH(n,e,r){let a=[{tag:"markdown",element_id:YGt,content:n?rP(n,2):" ",text_align:"left",text_size:"normal_v2"}],i=e?dCe(e):"";i&&a.push({tag:"markdown",element_id:uCe,content:i,text_size:"notation"});let t={schema:"2.0",config:{streaming_mode:!1,summary:{content:n.replace(/[*_`#>[\]()~]/g,"").trim().slice(0,120)||"Done"}},body:{elements:a}};return r&&(t.header={title:{tag:"plain_text",content:r},template:"blue"}),t}var bOr,fOr,YGt,uCe,mza,bza,ICe,gOr=De(()=>{"use strict";vI();SEe();j9r();vpt();bOr={feishu:"https://open.feishu.cn",lark:"https://open.larksuite.com"},fOr=1800*1e3,YGt="streaming_content",uCe="footer_content",mza="loading_icon";bza="img_v3_02vb_496bec09-4b43-4773-ad6b-0cdd103cd2bg";ICe=class n{appId;appSecret;domain;tenantToken="";tokenExpiresAt=0;wsClient=null;_onReady=null;_onDisconnect=null;processedMessages=new Map;maxProcessedMessages=5e3;processedRetentionMs=2880*60*1e3;inFlightMessages=new Set;getProcessedMessagesFilePath(){let e=CGt.homedir(),r=mH.join(e,gl);return mH.join(r,"feishu-processed-messages.json")}loadProcessedMessages(){this.processedMessages=new Map;try{let e=this.getProcessedMessagesFilePath();if(!Nv.existsSync(e))return;let r=JSON.parse(Nv.readFileSync(e,"utf8"));if(!Array.isArray(r))return;let a=Date.now();for(let i of r){let o,t;if(typeof i=="string")o=i,t=a;else if(Array.isArray(i)&&typeof i[0]=="string")o=i[0],t=typeof i[1]=="number"?i[1]:a;else continue;o.startsWith("om_")&&(a-t>=this.processedRetentionMs||this.processedMessages.set(o,t))}Kn(`[Feishu] Loaded ${this.processedMessages.size} processed message IDs from persistent cache.`)}catch(e){ka(`[Feishu] Failed to load processed messages: ${e?.message||e}`),this.processedMessages=new Map}}saveProcessedMessages(){try{let e=this.getProcessedMessagesFilePath(),r=mH.dirname(e);Nv.existsSync(r)||Nv.mkdirSync(r,{recursive:!0});let a=Array.from(this.processedMessages.entries());Nv.writeFileSync(e,JSON.stringify(a,null,2),"utf8"),Kn(`[Feishu] Saved ${a.length} processed message IDs to persistent cache.`)}catch(e){ka(`[Feishu] Failed to save processed messages: ${e?.message||e}`)}}recordProcessedMessage(e){if(!e||!e.startsWith("om_"))return;let r=Date.now();this.processedMessages.delete(e),this.processedMessages.set(e,r);for(let[a,i]of this.processedMessages)r-i>=this.processedRetentionMs&&this.processedMessages.delete(a);for(;this.processedMessages.size>this.maxProcessedMessages;){let a=this.processedMessages.keys().next().value;if(a===void 0)break;this.processedMessages.delete(a)}this.saveProcessedMessages()}recentContents=new Map;dedupWindowMs=5e3;connectedAtMs=0;STALE_CLOCK_SKEW_MS=5e3;static HIGH_RISK_KEYWORDS=["/feishu restart","/\u98DE\u4E66 restart","/update","self_update","self-update","\u81EA\u66F4\u65B0","\u91CD\u542F","\u70ED\u91CD\u542F","\u66F4\u65B0\u4E00\u4E0B\u4F60\u81EA\u5DF1","\u66F4\u65B0\u81EA\u5DF1","\u5347\u7EA7\u4E00\u4E0B\u4F60\u81EA\u5DF1","\u5347\u7EA7\u81EA\u5DF1"];static HIGH_RISK_DEDUP_WINDOW_MS=10800*1e3;highRiskHashes=new Map;getHighRiskDedupFilePath(){let e=CGt.homedir(),r=mH.join(e,gl);return mH.join(r,"feishu-highrisk-dedup.json")}loadHighRiskDedup(){try{let e=this.getHighRiskDedupFilePath();if(Nv.existsSync(e)){let r=Nv.readFileSync(e,"utf8"),a=JSON.parse(r);if(Array.isArray(a)){let i=Date.now();for(let[o,t]of a)typeof o=="string"&&typeof t=="number"&&i-t<n.HIGH_RISK_DEDUP_WINDOW_MS&&this.highRiskHashes.set(o,t);Kn(`[Feishu] Loaded ${this.highRiskHashes.size} active high-risk dedup entries from disk.`)}}}catch(e){ka(`[Feishu] Failed to load high-risk dedup cache: ${e?.message||e}`)}}saveHighRiskDedup(){try{let e=this.getHighRiskDedupFilePath(),r=mH.dirname(e);Nv.existsSync(r)||Nv.mkdirSync(r,{recursive:!0});let a=Array.from(this.highRiskHashes.entries());Nv.writeFileSync(e,JSON.stringify(a,null,2),"utf8")}catch(e){ka(`[Feishu] Failed to save high-risk dedup cache: ${e?.message||e}`)}}isHighRiskMessage(e){let r=e.toLowerCase();return n.HIGH_RISK_KEYWORDS.some(a=>r.includes(a))}computeContentHash(e,r){let a=`${e}:${r}`,i=5381;for(let o=0;o<a.length;o++)i=(i<<5)+i+a.charCodeAt(o)&2147483647;return`hr_${i.toString(36)}`}checkHighRiskDedup(e,r){if(!this.isHighRiskMessage(r))return!1;let a=this.computeContentHash(e,r),i=Date.now(),o=this.highRiskHashes.get(a);if(o!==void 0&&i-o<n.HIGH_RISK_DEDUP_WINDOW_MS)return Kn(`[Feishu] High-risk dedup: skipping duplicate "${r.slice(0,40)}" (hash=${a}, age=${Math.round((i-o)/6e4)}min)`),!0;this.highRiskHashes.set(a,i);for(let[t,s]of this.highRiskHashes)i-s>=n.HIGH_RISK_DEDUP_WINDOW_MS&&this.highRiskHashes.delete(t);return this.saveHighRiskDedup(),!1}chatNameCache=new Map;chatModeCache=new Map;userNameCache=new Map;botOpenId=null;onMessage=null;onCardAction=null;cardCallbacks=new Map;textChoiceCallback=null;lastCardMessageId=null;getLastCardMessageId(){return this.lastCardMessageId}get onReady(){return this._onReady}set onReady(e){this._onReady=e}get onDisconnect(){return this._onDisconnect}set onDisconnect(e){this._onDisconnect=e}getAppId(){return this.appId}getAppSecret(){return this.appSecret}getDomain(){return this.domain}constructor(e,r,a="feishu"){this.appId=e,this.appSecret=r,this.domain=a,this.loadProcessedMessages(),this.loadHighRiskDedup()}get apiBaseUrl(){return bOr[this.domain]||bOr.feishu}async getTenantToken(){if(this.tenantToken&&Date.now()<this.tokenExpiresAt-6e4)return this.tenantToken;let r=await(await fetch(`${this.apiBaseUrl}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.appId,app_secret:this.appSecret})})).json();if(!r.tenant_access_token)throw new Error(`Failed to fetch tenant_access_token: ${JSON.stringify(r)}`);return this.tenantToken=r.tenant_access_token,this.tokenExpiresAt=Date.now()+(r.expire||7200)*1e3,this.tenantToken}async resolveUserName(e){if(!e)return;let r=this.userNameCache.get(e);if(r!==void 0)return r||void 0;try{let a=await this.getTenantToken(),o=await(await fetch(`${this.apiBaseUrl}/open-apis/contact/v3/users/${encodeURIComponent(e)}?user_id_type=open_id`,{headers:{Authorization:`Bearer ${a}`}})).json(),t=typeof o?.data?.user?.name=="string"?o.data.user.name.trim():"";return this.userNameCache.set(e,t),t||void 0}catch(a){ka(`resolveUserName(${e}) failed:`,a);return}}async getBotOpenId(){if(this.botOpenId)return this.botOpenId;try{let e=await this.getTenantToken(),a=await(await fetch(`${this.apiBaseUrl}/open-apis/bot/v3/info`,{headers:{Authorization:`Bearer ${e}`}})).json(),i=typeof a?.bot?.open_id=="string"?a.bot.open_id:typeof a?.data?.bot?.open_id=="string"?a.data.bot.open_id:"";return this.botOpenId=i||null,this.botOpenId}catch(e){return ka("getBotOpenId failed:",e),null}}parseSingleMessageContent(e,r,a,i,o){let t="";if(r==="text")try{let s=JSON.parse(a||"{}");t=typeof s.text=="string"?s.text:String(s.text||"")}catch{t=typeof a=="string"?a:String(a||"")}else if(r==="image")try{let d=JSON.parse(a||"{}").image_key;d?(t="[\u56FE\u7247\u6D88\u606F]",i.push({imageKey:d,placeholder:"[\u56FE\u7247\u6D88\u606F]"})):t="[\u56FE\u7247\u6D88\u606F]"}catch{t="[\u56FE\u7247\u6D88\u606F]"}else if(r==="file")try{let s=JSON.parse(a||"{}"),d=s.file_key,I=s.file_name||"unnamed_file";if(d){let u=`[\u6587\u4EF6\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t=`[\u6587\u4EF6\u6D88\u606F: ${I}]`}catch{t="[\u6587\u4EF6\u6D88\u606F]"}else if(r==="audio")try{let d=JSON.parse(a||"{}").file_key;if(d){let I=`audio_${e||"unnamed"}.opus`,u=`[\u97F3\u9891\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t="[\u97F3\u9891\u6D88\u606F]"}catch{t="[\u97F3\u9891\u6D88\u606F]"}else if(r==="media")try{let d=JSON.parse(a||"{}").file_key;if(d){let I=`video_${e||"unnamed"}.mp4`,u=`[\u89C6\u9891\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t="[\u89C6\u9891\u6D88\u606F]"}catch{t="[\u89C6\u9891\u6D88\u606F]"}else if(r==="post")try{let s=JSON.parse(a||"{}"),d=[],I="",h=Object.keys(s)[0];h&&s[h]&&Array.isArray(s[h].content)?(d=s[h].content,I=s[h].title||""):Array.isArray(s.content)?(d=s.content,I=s.title||""):Array.isArray(s)&&(d=s);let c=[];I&&c.push(`**${I}**`);for(let m of d){if(!Array.isArray(m))continue;let y="";for(let g of m)if(!(!g||typeof g!="object")){if(g.tag==="text")y+=g.text||"";else if(g.tag==="a")y+=`[${g.text||""}](${g.href||""})`;else if(g.tag==="at")y+=g.text||"";else if(g.tag==="img"){let Z=g.image_key;if(Z){let v=`[\u56FE\u7247_${i.length+1}]`;i.push({imageKey:Z,placeholder:v}),y+=v}}}y.trim()&&c.push(y)}t=c.join(`
6569
+ </vote>`,resources:[]}}),cza=new Map([["text",aza],["post",K7a],["image",M7a],["file",T7a],["audio",S7a],["video",_Dr],["media",_Dr],["sticker",rza],["interactive",z7a],["merge_forward",P7a],["share_chat",eza],["share_user",tza],["location",_7a],["system",nza],["vote",lza],["todo",iza],["calendar",L7a],["general_calendar",J7a],["share_calendar_event",B7a],["folder",D7a],["hongbao",O7a],["video_chat",oza]]);function PDr(n,e,r){var a;return K(this,void 0,void 0,function*(){let i=(a=cza.get(e))!==null&&a!==void 0?a:zDr;try{return yield i(n,r)}catch{return zDr(n)}})}function dOr(n,e){var r,a,i,o,t,s,d,I,u,h,c,m;let y=(a=(r=n.context)===null||r===void 0?void 0:r.open_message_id)!==null&&a!==void 0?a:n.open_message_id,g=(o=(i=n.context)===null||i===void 0?void 0:i.open_chat_id)!==null&&o!==void 0?o:n.open_chat_id,Z=(t=n.operator)===null||t===void 0?void 0:t.open_id;return!y||!g||!Z?null:{messageId:y,chatId:g,operator:{openId:Z,userId:(s=n.operator)===null||s===void 0?void 0:s.user_id,name:(d=n.operator)===null||d===void 0?void 0:d.name},action:{value:(I=n.action)===null||I===void 0?void 0:I.value,tag:(h=(u=n.action)===null||u===void 0?void 0:u.tag)!==null&&h!==void 0?h:"unknown",name:(c=n.action)===null||c===void 0?void 0:c.name,option:(m=n.action)===null||m===void 0?void 0:m.option},raw:e?.includeRaw?n:void 0}}function wGt(n,e,r){var a,i,o,t;let s=n.message_id,d=(a=n.reaction_type)===null||a===void 0?void 0:a.emoji_type,I=(i=n.user_id)===null||i===void 0?void 0:i.open_id;if(!s||!d||!I)return null;let u=n.action_time,h=u?parseInt(u,10):void 0;return{messageId:s,operator:{openId:I,userId:(t=(o=n.user_id)===null||o===void 0?void 0:o.user_id)!==null&&t!==void 0?t:void 0},emojiType:d,action:e,actionTime:h!=null&&Number.isFinite(h)?h:void 0,raw:r?.includeRaw?n:void 0}}function IOr(n,e){var r,a,i,o,t,s,d,I,u;let h=n.chat_id,c=(r=n.operator_id)===null||r===void 0?void 0:r.open_id;if(!h||!c)return null;let m=(s=(o=(a=n.name)!==null&&a!==void 0?a:(i=n.i18n_names)===null||i===void 0?void 0:i.zh_cn)!==null&&o!==void 0?o:(t=n.i18n_names)===null||t===void 0?void 0:t.en_us)!==null&&s!==void 0?s:(d=n.i18n_names)===null||d===void 0?void 0:d.ja_jp;return{chatId:h,operator:{openId:c,userId:(u=(I=n.operator_id)===null||I===void 0?void 0:I.user_id)!==null&&u!==void 0?u:void 0},botName:m,external:n.external,raw:e?.includeRaw?n:void 0}}function hOr(n,e){var r,a,i,o,t,s,d,I,u,h,c,m,y;let g=(r=n.file_token)!==null&&r!==void 0?r:(a=n.notice_meta)===null||a===void 0?void 0:a.file_token,Z=(i=n.file_type)!==null&&i!==void 0?i:(o=n.notice_meta)===null||o===void 0?void 0:o.file_type,v=n.comment_id,E=(s=(t=n.notice_meta)===null||t===void 0?void 0:t.from_user_id)!==null&&s!==void 0?s:n.user_id,w=E?.open_id;if(!g||!Z||!v||!w)return null;let R=(u=(d=n.create_time)!==null&&d!==void 0?d:(I=n.notice_meta)===null||I===void 0?void 0:I.timestamp)!==null&&u!==void 0?u:n.action_time,b=R?parseInt(R,10):Date.now();return{fileToken:g,fileType:Z,commentId:v,replyId:n.reply_id,operator:{openId:w,userId:(h=E?.user_id)!==null&&h!==void 0?h:void 0,unionId:E?.union_id},mentionedBot:!!((y=(c=n.is_mentioned)!==null&&c!==void 0?c:(m=n.notice_meta)===null||m===void 0?void 0:m.is_mentioned)!==null&&y!==void 0?y:n.is_mention),timestamp:Number.isFinite(b)?b:Date.now(),raw:e?.includeRaw?n:void 0}}function mOr(n,e){var r,a,i,o,t;return K(this,void 0,void 0,function*(){let s=n.message,d=(r=e.botIdentity)===null||r===void 0?void 0:r.openId,{mentions:I,mentionsByOpenId:u,mentionList:h,mentionAll:c,mentionedBot:m}=x7a(s.mentions,d),y=c||uza(s.content),g={messageId:s.message_id,botOpenId:d,mentions:I,mentionsByOpenId:u,stripBotMentions:(a=e.stripBotMentions)!==null&&a!==void 0?a:!0,fetchSubMessages:e.fetchSubMessages,resolveUserName:e.resolveUserName,batchResolveNames:e.batchResolveNames,dispatch:PDr},{content:Z,resources:v}=yield PDr(s.content,s.message_type,g),E=C7a(Z,g),w=n.sender.sender_id.open_id,R=(o=(i=n.sender.sender_id.user_id)!==null&&i!==void 0?i:n.sender.sender_id.union_id)!==null&&o!==void 0?o:"",b=w??R,W=w?(t=e.resolveSenderName)===null||t===void 0?void 0:t.call(e,w):void 0,N=s.create_time?parseInt(s.create_time,10):0;return{messageId:s.message_id,chatId:s.chat_id,chatType:s.chat_type,senderId:b,senderName:W,content:E,rawContentType:s.message_type,resources:v,mentions:h,mentionAll:y,mentionedBot:m,rootId:s.root_id,threadId:s.thread_id,replyToMessageId:s.parent_id,createTime:Number.isFinite(N)?N:0,raw:e.includeRaw?n:void 0}})}function uza(n){return n?/@_all\b/.test(n):!1}var lCe=class{constructor(e){var r,a,i,o,t,s,d;this.handlers={},this.connected=!1,this.opts=e,this.logger=new hH((r=e.loggerLevel)!==null&&r!==void 0?r:Qa.LoggerLevel.info,(a=e.logger)!==null&&a!==void 0?a:iC),this.rawClient=new eCe({appId:e.appId,appSecret:e.appSecret,domain:(i=e.domain)!==null&&i!==void 0?i:Qa.Domain.Feishu,cache:e.cache,httpInstance:e.httpInstance,logger:e.logger,loggerLevel:e.loggerLevel,source:e.source,extraUaTags:["channel"]}),this.dispatcher=new rCe({verificationToken:(o=e.webhook)===null||o===void 0?void 0:o.verificationToken,encryptKey:(t=e.webhook)===null||t===void 0?void 0:t.encryptKey,cache:e.cache,logger:e.logger,loggerLevel:e.loggerLevel}),this.sender=new gGt(this.rawClient,(s=e.outbound)!==null&&s!==void 0?s:{},this.logger),this.safety=new FGt({config:e.safety,policy:e.policy,cache:(d=e.cache)!==null&&d!==void 0?d:kue,logger:this.logger,onReject:I=>{var u,h;(h=(u=this.handlers).reject)===null||h===void 0||h.call(u,I)},onMessage:I=>K(this,void 0,void 0,function*(){let u=this.handlers.message;u&&(yield u(I))})})}connect(){return K(this,void 0,void 0,function*(){return this.connectPromise?this.connectPromise:(this.connectPromise=this.doConnect().catch(e=>{throw this.connectPromise=void 0,e}),this.connectPromise)})}doConnect(){var e;return K(this,void 0,void 0,function*(){this.botIdentity=yield this.fetchBotIdentity(),this.safety.setBotIdentity(this.botIdentity),this.registerDispatcherHandlers(),((e=this.opts.transport)!==null&&e!==void 0?e:"websocket")==="websocket"&&(yield this.connectWebSocket(15e3)),this.connected=!0})}connectWebSocket(e){return new Promise((r,a)=>{var i;let o=!1,t=setTimeout(()=>{o||(o=!0,a(new su("not_connected",`WebSocket handshake did not complete within ${e}ms`)))},e);this.rawWsClient=new aCe({appId:this.opts.appId,appSecret:this.opts.appSecret,domain:(i=this.opts.domain)!==null&&i!==void 0?i:Qa.Domain.Feishu,logger:this.opts.logger,loggerLevel:this.opts.loggerLevel,httpInstance:this.opts.httpInstance,autoReconnect:!0,source:this.opts.source,extraUaTags:["channel"],agent:this.opts.agent,wsConfig:this.opts.wsConfig,handshakeTimeoutMs:this.opts.handshakeTimeoutMs,onReady:()=>{o||(o=!0,clearTimeout(t),r())},onError:s=>{o||(o=!0,clearTimeout(t),a(new su("not_connected",`WebSocket connect failed: ${s.message}`,{cause:s})))},onReconnecting:()=>{var s,d;return(d=(s=this.handlers).reconnecting)===null||d===void 0?void 0:d.call(s)},onReconnected:()=>{var s,d;return(d=(s=this.handlers).reconnected)===null||d===void 0?void 0:d.call(s)}}),this.rawWsClient.start({eventDispatcher:this.dispatcher})})}disconnect(){var e;return K(this,void 0,void 0,function*(){if(this.connected){try{(e=this.rawWsClient)===null||e===void 0||e.close({})}catch{}try{yield this.safety.dispose()}catch{}this.connected=!1,this.connectPromise=void 0}})}getConnectionStatus(){var e;return(e=this.rawWsClient)===null||e===void 0?void 0:e.getConnectionStatus()}on(e,r){if(typeof e=="string")return this.attachSingle(e,r);let a=[];return Object.keys(e).forEach(i=>{let o=e[i];o&&a.push(this.attachSingle(i,o))}),()=>a.forEach(i=>i())}attachSingle(e,r){return this.handlers[e]&&this.logger.warn(`channel: handler for "${e}" is being overwritten`),this.handlers[e]=r,()=>{this.handlers[e]===r&&delete this.handlers[e]}}send(e,r,a){return K(this,void 0,void 0,function*(){return this.sender.send(e,r,a)})}stream(e,r,a){return K(this,void 0,void 0,function*(){return this.sender.stream(e,r,a)})}updateCard(e,r){return K(this,void 0,void 0,function*(){yield this.sender.patchCard(e,r)})}editMessage(e,r){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.update({path:{message_id:e},data:{msg_type:"text",content:JSON.stringify({text:r})}})})}recallMessage(e){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.message.delete({path:{message_id:e}})})}addReaction(e,r){var a,i;return K(this,void 0,void 0,function*(){let o=yield this.rawClient.im.v1.messageReaction.create({path:{message_id:e},data:{reaction_type:{emoji_type:r}}}),t=(i=(a=o?.data)===null||a===void 0?void 0:a.reaction_id)!==null&&i!==void 0?i:o?.reaction_id;if(!t)throw new su("unknown","messageReaction.create returned no reaction_id");return t})}removeReaction(e,r){return K(this,void 0,void 0,function*(){yield this.rawClient.im.v1.messageReaction.delete({path:{message_id:e,reaction_id:r}})})}removeReactionByEmoji(e,r){var a,i;return K(this,void 0,void 0,function*(){let o=yield this.rawClient.im.v1.messageReaction.list({path:{message_id:e},params:{reaction_type:r,page_size:50}}),s=((i=(a=o?.data)===null||a===void 0?void 0:a.items)!==null&&i!==void 0?i:[]).find(d=>{var I;return((I=d.operator)===null||I===void 0?void 0:I.operator_type)==="app"});return s?.reaction_id?(yield this.removeReaction(e,s.reaction_id),!0):!1})}downloadResource(e,r){return K(this,void 0,void 0,function*(){if(r==="image"){let i=yield this.rawClient.im.v1.image.get({path:{image_key:e}});return yield jDr(i)}let a=yield this.rawClient.im.v1.file.get({path:{file_key:e}});return yield jDr(a)})}getChatInfo(e){var r,a;return K(this,void 0,void 0,function*(){let o=(r=(yield this.rawClient.im.v1.chat.get({path:{chat_id:e}})).data)!==null&&r!==void 0?r:{};return{chatId:e,name:o.name,description:o.description,chatType:(a=o.chat_mode)!==null&&a!==void 0?a:"group",ownerId:o.owner_id,memberCount:o.user_count}})}getChatMode(e){var r;return K(this,void 0,void 0,function*(){let i=(r=(yield this.rawClient.im.v1.chat.get({path:{chat_id:e}})).data)===null||r===void 0?void 0:r.chat_mode;return i==="p2p"?"p2p":i==="topic"?"topic":"group"})}updatePolicy(e){this.safety.updatePolicy(e)}getPolicy(){return this.safety.getPolicy()}fetchBotIdentity(){var e;return K(this,void 0,void 0,function*(){let r;try{let o=yield this.rawClient.request({url:"/open-apis/bot/v3/info",method:"GET"}),t=o.bot;if(t?.open_id)return{openId:t.open_id,name:(e=t.app_name)!==null&&e!==void 0?e:"bot"};r=new Error(`bot/v3/info response missing open_id: ${JSON.stringify(o).slice(0,200)}`)}catch(o){r=o}let a=EGt(r),i=a.code==="unknown"?"not_connected":a.code;throw new su(i,"could not resolve bot identity via /open-apis/bot/v3/info \u2014 required for channel to function",{cause:r})})}registerDispatcherHandlers(){var e,r;let a=t=>K(this,void 0,void 0,function*(){var s,d,I,u;try{return(d=(s=(yield this.rawClient.im.v1.message.get({path:{message_id:t}})).data)===null||s===void 0?void 0:s.items)!==null&&d!==void 0?d:[]}catch(h){return(u=(I=this.logger).warn)===null||u===void 0||u.call(I,"channel: fetchSubMessages failed",h),[]}}),i=(r=(e=this.opts.includeRawEvent)!==null&&e!==void 0?e:this.opts.includeRawInMessage)!==null&&r!==void 0?r:!1,o={botIdentity:this.botIdentity,stripBotMentions:!0,includeRaw:i,fetchSubMessages:a};this.dispatcher.register({"im.message.receive_v1":t=>K(this,void 0,void 0,function*(){try{let s=yield mOr(t,o);yield this.safety.pushMessage(s)}catch(s){this.emitError(s)}}),"card.action.trigger":t=>K(this,void 0,void 0,function*(){let s=dOr(t,{includeRaw:i});if(!s)return;let d=hza(s.action);yield this.safety.pushAction(`card:${s.messageId}:${s.operator.openId}:${d}`,s.chatId,()=>K(this,void 0,void 0,function*(){let I=this.handlers.cardAction;I&&(yield I(s))}))}),"im.message.reaction.created_v1":t=>K(this,void 0,void 0,function*(){let s=wGt(t,"added",{includeRaw:i});if(!s)return;let d=qDr(s);yield this.safety.pushLight(d,()=>{var I,u;return(u=(I=this.handlers).reaction)===null||u===void 0?void 0:u.call(I,s)})}),"im.message.reaction.deleted_v1":t=>K(this,void 0,void 0,function*(){let s=wGt(t,"removed",{includeRaw:i});if(!s)return;let d=qDr(s);yield this.safety.pushLight(d,()=>{var I,u;return(u=(I=this.handlers).reaction)===null||u===void 0?void 0:u.call(I,s)})}),"im.chat.member.bot.added_v1":t=>{var s,d;let I=IOr(t,{includeRaw:i});if(I)try{(d=(s=this.handlers).botAdded)===null||d===void 0||d.call(s,I)}catch(u){this.emitError(u)}},"drive.notice.comment_add_v1":t=>K(this,void 0,void 0,function*(){var s;let d=hOr(t,{includeRaw:i});d&&(yield this.safety.pushAction(`comment:${d.fileToken}:${d.commentId}:${(s=d.replyId)!==null&&s!==void 0?s:""}`,d.fileToken,()=>K(this,void 0,void 0,function*(){let I=this.handlers.comment;I&&(yield I(d))})))})})}emitError(e){var r,a,i;let o=e instanceof su?e:new su("unknown",String((r=e?.message)!==null&&r!==void 0?r:e),{cause:e}),t=this.handlers.error;t?t(o):(i=(a=this.logger).error)===null||i===void 0||i.call(a,"channel: unhandled error",o)}};function dza(n){return new lCe(n)}function jDr(n){return K(this,void 0,void 0,function*(){if(Buffer.isBuffer(n))return n;if(n instanceof Uint8Array)return Buffer.from(n);if(typeof n=="object"&&n!==null){let e=n;if(typeof e.getReadableStream=="function")return yield Iza(e.getReadableStream());if(Buffer.isBuffer(e.data))return e.data;if(e.data instanceof Uint8Array)return Buffer.from(e.data)}throw new su("unknown","unexpected download response type")})}function Iza(n){return new Promise((e,r)=>{let a=[];n.on("data",i=>{a.push(Buffer.isBuffer(i)?i:Buffer.from(i))}),n.on("end",()=>e(Buffer.concat(a))),n.on("error",r)})}function qDr(n){var e;return`rx:${n.messageId}:${n.operator.openId}:${n.emojiType}:${n.action}:${(e=n.actionTime)!==null&&e!==void 0?e:0}`}function hza(n){var e,r,a;let i=typeof n.value=="string"?n.value:JSON.stringify((e=n.value)!==null&&e!==void 0?e:""),o=i.length>128?i.slice(0,128):i;return`${n.tag}|${(r=n.name)!==null&&r!==void 0?r:""}|${(a=n.option)!==null&&a!==void 0?a:""}|${o}`}Qa.AESCipher=Xue;Qa.Aily=hGt;Qa.CAppTicket=Hue;Qa.CTenantAccessToken=Dft;Qa.CardActionHandler=cGt;Qa.Client=eCe;Qa.DefaultCache=$xe;Qa.EventDispatcher=rCe;Qa.LarkChannel=lCe;Qa.LarkChannelError=su;Qa.LoggerProxy=hH;Qa.WSClient=aCe;Qa.adaptDefault=NUa;Qa.adaptExpress=FUa;Qa.adaptKoa=wUa;Qa.adaptKoaRouter=RUa;Qa.createLarkChannel=dza;Qa.defaultHttpInstance=EP;Qa.defaultLogger=iC;Qa.generateChallenge=Sue;Qa.internalCache=kue;Qa.messageCard=EUa;Qa.normalize=mOr;Qa.normalizeBotAdded=IOr;Qa.normalizeCardAction=dOr;Qa.normalizeComment=hOr;Qa.normalizeReaction=wGt;Qa.registerApp=JUa;Qa.withAll=GUa;Qa.withHelpDeskCredential=vUa;Qa.withTenantKey=gUa;Qa.withTenantToken=yUa;Qa.withUserAccessToken=ZUa});import CGt from"node:os";import mH from"node:path";import Nv from"node:fs";function pza(){return process.env.EASYCODE_FEISHU_CARDKIT_V2==="1"}function fza(n){let e=n/1e3;if(e<60)return`${e.toFixed(1)}s`;let r=Math.floor(e/60),a=Math.round(e%60);return`${r}m ${a}s`}function dCe(n){let e=[],r=!1;if(n.status){let i=n.status,o=n.status.toLowerCase();o.includes("error")||o.includes("failed")||o.includes("\u51FA\u9519")||o.includes("\u5931\u8D25")?(i=`<font color='red'>${n.status}</font>`,r=!0):o.includes("processing")||o.includes("thinking")||o.includes("\u601D\u8003\u4E2D")||o.includes("\u8FD0\u884C")?i=`<font color='grey'>${n.status}</font>`:i=`<font color='green'>${n.status}</font>`,e.push(i)}if(n.elapsedMs!=null&&e.push(`\u8017\u65F6 ${fza(n.elapsedMs)}`),n.model&&e.push(n.model),n.delegateTokenDisplay?e.push(n.delegateTokenDisplay):n.tokens&&e.push(`\u2191${n.tokens.input.toLocaleString()} \u2193${n.tokens.output.toLocaleString()}`),n.cacheRead!=null&&n.cacheRead>0){let i=`\u7F13\u5B58\u8BFB\u53D6 ${n.cacheRead.toLocaleString()}`;n.cacheHitRate!=null&&n.cacheHitRate>0&&(i+=` (${n.cacheHitRate.toFixed(1)}%)`),e.push(i)}if(!n.delegateTokenDisplay&&n.contextPercentage!=null){let i=Math.max(0,100-n.contextPercentage);e.push(`\u4E0A\u4E0B\u6587\u5269\u4F59 ${i.toFixed(0)}%`)}if(n.quota&&e.push(n.quota),e.length===0)return"";let a=e.join(" \xB7 ");return r?`<font color='red'>${a}</font>`:a}function GOr(n){let e=dCe(n);return e?[{tag:"hr"},{tag:"markdown",content:e}]:[]}function Gza(n="",e=""){let r=[{tag:"markdown",element_id:YGt,content:n?rP(n,2):" ",text_align:"left",text_size:"normal_v2"},{tag:"markdown",element_id:mza,content:" ",icon:{tag:"custom_icon",img_key:bza,size:"16px 16px"}}];return e?r.push({tag:"markdown",element_id:uCe,content:e,text_size:"notation"}):r.push({tag:"markdown",element_id:uCe,content:" ",text_size:"notation"}),{schema:"2.0",config:{streaming_mode:!0,summary:{content:"Processing...",i18n_content:{zh_cn:"\u5904\u7406\u4E2D...",en_us:"Processing..."}}},body:{elements:r}}}function pH(n,e,r){let a=[{tag:"markdown",element_id:YGt,content:n?rP(n,2):" ",text_align:"left",text_size:"normal_v2"}],i=e?dCe(e):"";i&&a.push({tag:"markdown",element_id:uCe,content:i,text_size:"notation"});let t={schema:"2.0",config:{streaming_mode:!1,summary:{content:n.replace(/[*_`#>[\]()~]/g,"").trim().slice(0,120)||"Done"}},body:{elements:a}};return r&&(t.header={title:{tag:"plain_text",content:r},template:"blue"}),t}var bOr,fOr,YGt,uCe,mza,bza,ICe,gOr=De(()=>{"use strict";vI();SEe();j9r();vpt();bOr={feishu:"https://open.feishu.cn",lark:"https://open.larksuite.com"},fOr=1800*1e3,YGt="streaming_content",uCe="footer_content",mza="loading_icon";bza="img_v3_02vb_496bec09-4b43-4773-ad6b-0cdd103cd2bg";ICe=class n{appId;appSecret;domain;tenantToken="";tokenExpiresAt=0;wsClient=null;_onReady=null;_onDisconnect=null;processedMessages=new Map;maxProcessedMessages=5e3;processedRetentionMs=2880*60*1e3;inFlightMessages=new Set;getProcessedMessagesFilePath(){let e=CGt.homedir(),r=mH.join(e,gl);return mH.join(r,"feishu-processed-messages.json")}loadProcessedMessages(){this.processedMessages=new Map;try{let e=this.getProcessedMessagesFilePath();if(!Nv.existsSync(e))return;let r=JSON.parse(Nv.readFileSync(e,"utf8"));if(!Array.isArray(r))return;let a=Date.now();for(let i of r){let o,t;if(typeof i=="string")o=i,t=a;else if(Array.isArray(i)&&typeof i[0]=="string")o=i[0],t=typeof i[1]=="number"?i[1]:a;else continue;o.startsWith("om_")&&(a-t>=this.processedRetentionMs||this.processedMessages.set(o,t))}Kn(`[Feishu] Loaded ${this.processedMessages.size} processed message IDs from persistent cache.`)}catch(e){ka(`[Feishu] Failed to load processed messages: ${e?.message||e}`),this.processedMessages=new Map}}saveProcessedMessages(){try{let e=this.getProcessedMessagesFilePath(),r=mH.dirname(e);Nv.existsSync(r)||Nv.mkdirSync(r,{recursive:!0});let a=Array.from(this.processedMessages.entries());Nv.writeFileSync(e,JSON.stringify(a,null,2),"utf8"),Kn(`[Feishu] Saved ${a.length} processed message IDs to persistent cache.`)}catch(e){ka(`[Feishu] Failed to save processed messages: ${e?.message||e}`)}}recordProcessedMessage(e){if(!e||!e.startsWith("om_"))return;let r=Date.now();this.processedMessages.delete(e),this.processedMessages.set(e,r);for(let[a,i]of this.processedMessages)r-i>=this.processedRetentionMs&&this.processedMessages.delete(a);for(;this.processedMessages.size>this.maxProcessedMessages;){let a=this.processedMessages.keys().next().value;if(a===void 0)break;this.processedMessages.delete(a)}this.saveProcessedMessages()}recentContents=new Map;dedupWindowMs=5e3;connectedAtMs=0;STALE_CLOCK_SKEW_MS=5e3;static HIGH_RISK_KEYWORDS=["/feishu restart","/\u98DE\u4E66 restart","/update","self_update","self-update","\u81EA\u66F4\u65B0","\u91CD\u542F","\u70ED\u91CD\u542F","\u66F4\u65B0\u4E00\u4E0B\u4F60\u81EA\u5DF1","\u66F4\u65B0\u81EA\u5DF1","\u5347\u7EA7\u4E00\u4E0B\u4F60\u81EA\u5DF1","\u5347\u7EA7\u81EA\u5DF1"];static HIGH_RISK_DEDUP_WINDOW_MS=10800*1e3;highRiskHashes=new Map;getHighRiskDedupFilePath(){let e=CGt.homedir(),r=mH.join(e,gl);return mH.join(r,"feishu-highrisk-dedup.json")}loadHighRiskDedup(){try{let e=this.getHighRiskDedupFilePath();if(Nv.existsSync(e)){let r=Nv.readFileSync(e,"utf8"),a=JSON.parse(r);if(Array.isArray(a)){let i=Date.now();for(let[o,t]of a)typeof o=="string"&&typeof t=="number"&&i-t<n.HIGH_RISK_DEDUP_WINDOW_MS&&this.highRiskHashes.set(o,t);Kn(`[Feishu] Loaded ${this.highRiskHashes.size} active high-risk dedup entries from disk.`)}}}catch(e){ka(`[Feishu] Failed to load high-risk dedup cache: ${e?.message||e}`)}}saveHighRiskDedup(){try{let e=this.getHighRiskDedupFilePath(),r=mH.dirname(e);Nv.existsSync(r)||Nv.mkdirSync(r,{recursive:!0});let a=Array.from(this.highRiskHashes.entries());Nv.writeFileSync(e,JSON.stringify(a,null,2),"utf8")}catch(e){ka(`[Feishu] Failed to save high-risk dedup cache: ${e?.message||e}`)}}isDirectLifecycleSlashCommand(e){let r=e.trim();return/^\/(?:update|self-update|self_update)\s*$/i.test(r)||/^\/(?:feishu|飞书)\s+restart\b/i.test(r)}isHighRiskMessage(e){if(this.isDirectLifecycleSlashCommand(e))return!1;let r=e.toLowerCase();return n.HIGH_RISK_KEYWORDS.some(a=>r.includes(a))}computeContentHash(e,r){let a=`${e}:${r}`,i=5381;for(let o=0;o<a.length;o++)i=(i<<5)+i+a.charCodeAt(o)&2147483647;return`hr_${i.toString(36)}`}checkHighRiskDedup(e,r){if(!this.isHighRiskMessage(r))return!1;let a=this.computeContentHash(e,r),i=Date.now(),o=this.highRiskHashes.get(a);if(o!==void 0&&i-o<n.HIGH_RISK_DEDUP_WINDOW_MS)return Kn(`[Feishu] High-risk dedup: skipping duplicate "${r.slice(0,40)}" (hash=${a}, age=${Math.round((i-o)/6e4)}min)`),!0;this.highRiskHashes.set(a,i);for(let[t,s]of this.highRiskHashes)i-s>=n.HIGH_RISK_DEDUP_WINDOW_MS&&this.highRiskHashes.delete(t);return this.saveHighRiskDedup(),!1}chatNameCache=new Map;chatModeCache=new Map;userNameCache=new Map;botOpenId=null;onMessage=null;onCardAction=null;cardCallbacks=new Map;textChoiceCallback=null;lastCardMessageId=null;getLastCardMessageId(){return this.lastCardMessageId}get onReady(){return this._onReady}set onReady(e){this._onReady=e}get onDisconnect(){return this._onDisconnect}set onDisconnect(e){this._onDisconnect=e}getAppId(){return this.appId}getAppSecret(){return this.appSecret}getDomain(){return this.domain}constructor(e,r,a="feishu"){this.appId=e,this.appSecret=r,this.domain=a,this.loadProcessedMessages(),this.loadHighRiskDedup()}get apiBaseUrl(){return bOr[this.domain]||bOr.feishu}async getTenantToken(){if(this.tenantToken&&Date.now()<this.tokenExpiresAt-6e4)return this.tenantToken;let r=await(await fetch(`${this.apiBaseUrl}/open-apis/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.appId,app_secret:this.appSecret})})).json();if(!r.tenant_access_token)throw new Error(`Failed to fetch tenant_access_token: ${JSON.stringify(r)}`);return this.tenantToken=r.tenant_access_token,this.tokenExpiresAt=Date.now()+(r.expire||7200)*1e3,this.tenantToken}async resolveUserName(e){if(!e)return;let r=this.userNameCache.get(e);if(r!==void 0)return r||void 0;try{let a=await this.getTenantToken(),o=await(await fetch(`${this.apiBaseUrl}/open-apis/contact/v3/users/${encodeURIComponent(e)}?user_id_type=open_id`,{headers:{Authorization:`Bearer ${a}`}})).json(),t=typeof o?.data?.user?.name=="string"?o.data.user.name.trim():"";return this.userNameCache.set(e,t),t||void 0}catch(a){ka(`resolveUserName(${e}) failed:`,a);return}}async getBotOpenId(){if(this.botOpenId)return this.botOpenId;try{let e=await this.getTenantToken(),a=await(await fetch(`${this.apiBaseUrl}/open-apis/bot/v3/info`,{headers:{Authorization:`Bearer ${e}`}})).json(),i=typeof a?.bot?.open_id=="string"?a.bot.open_id:typeof a?.data?.bot?.open_id=="string"?a.data.bot.open_id:"";return this.botOpenId=i||null,this.botOpenId}catch(e){return ka("getBotOpenId failed:",e),null}}parseSingleMessageContent(e,r,a,i,o){let t="";if(r==="text")try{let s=JSON.parse(a||"{}");t=typeof s.text=="string"?s.text:String(s.text||"")}catch{t=typeof a=="string"?a:String(a||"")}else if(r==="image")try{let d=JSON.parse(a||"{}").image_key;d?(t="[\u56FE\u7247\u6D88\u606F]",i.push({imageKey:d,placeholder:"[\u56FE\u7247\u6D88\u606F]"})):t="[\u56FE\u7247\u6D88\u606F]"}catch{t="[\u56FE\u7247\u6D88\u606F]"}else if(r==="file")try{let s=JSON.parse(a||"{}"),d=s.file_key,I=s.file_name||"unnamed_file";if(d){let u=`[\u6587\u4EF6\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t=`[\u6587\u4EF6\u6D88\u606F: ${I}]`}catch{t="[\u6587\u4EF6\u6D88\u606F]"}else if(r==="audio")try{let d=JSON.parse(a||"{}").file_key;if(d){let I=`audio_${e||"unnamed"}.opus`,u=`[\u97F3\u9891\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t="[\u97F3\u9891\u6D88\u606F]"}catch{t="[\u97F3\u9891\u6D88\u606F]"}else if(r==="media")try{let d=JSON.parse(a||"{}").file_key;if(d){let I=`video_${e||"unnamed"}.mp4`,u=`[\u89C6\u9891\u6D88\u606F: ${I}]`;t=u,o.push({fileKey:d,fileName:I,placeholder:u})}else t="[\u89C6\u9891\u6D88\u606F]"}catch{t="[\u89C6\u9891\u6D88\u606F]"}else if(r==="post")try{let s=JSON.parse(a||"{}"),d=[],I="",h=Object.keys(s)[0];h&&s[h]&&Array.isArray(s[h].content)?(d=s[h].content,I=s[h].title||""):Array.isArray(s.content)?(d=s.content,I=s.title||""):Array.isArray(s)&&(d=s);let c=[];I&&c.push(`**${I}**`);for(let m of d){if(!Array.isArray(m))continue;let y="";for(let g of m)if(!(!g||typeof g!="object")){if(g.tag==="text")y+=g.text||"";else if(g.tag==="a")y+=`[${g.text||""}](${g.href||""})`;else if(g.tag==="at")y+=g.text||"";else if(g.tag==="img"){let Z=g.image_key;if(Z){let v=`[\u56FE\u7247_${i.length+1}]`;i.push({imageKey:Z,placeholder:v}),y+=v}}}y.trim()&&c.push(y)}t=c.join(`
6570
6570
  `)}catch(s){Mo("Parse feishu post message failed in sub-parser:",s),t="[\u89E3\u6790\u5BCC\u6587\u672C\u6D88\u606F\u5931\u8D25]"}else if(r==="interactive")try{let s=JSON.parse(a||"{}");this.dumpCardContentForDebug(e,a);let d=null;if(typeof s?.user_dsl=="string")try{d=JSON.parse(s.user_dsl)}catch{}let I=d??s?.data?.card??s,u=I?.header?.title,h=typeof u?.content=="string"&&u.content||(typeof u?.i18n_content=="object"?Object.values(u.i18n_content)[0]:"")||"",c=I?.header?.subtitle,m=typeof c?.content=="string"&&c.content||"",y=[],g=new Set,Z=h?String(h).trim():"",v=m?String(m).trim():"";Z&&g.add(Z),v&&g.add(v);let E=I?.body?.elements??I?.elements??s?.elements??I;this.extractCardText(E,y,g),y.length===0&&s?.elements&&this.extractCardText(s.elements,y,g);let w=["[\u5361\u7247]"];Z&&w.push(`**${Z}**`),v&&w.push(v);for(let R of y)R&&R.trim()&&w.push(R.trim());t=w.length>1?w.join(`
6571
6571
  `):"[\u5361\u7247\u6D88\u606F]"}catch(s){Mo("Parse feishu interactive card failed in sub-parser:",s),t="[\u5361\u7247\u6D88\u606F]"}else t=`[\u4E0D\u652F\u6301\u7684\u6D88\u606F\u7C7B\u578B: ${r}]`;return t}extractCardText(e,r,a){if(e!=null){if(typeof e=="string"){let i=e.trim().replace(/<\/?font[^>]*>/gi,"");i&&!a.has(i)&&(a.add(i),r.push(i));return}if(Array.isArray(e)){for(let i of e)this.extractCardText(i,r,a);return}if(typeof e=="object"){if(e.tag==="table"&&Array.isArray(e.columns)){let i=this.renderCardTable(e);i&&!a.has(i)&&(a.add(i),r.push(i));return}typeof e.content=="string"&&this.extractCardText(e.content,r,a),typeof e.text=="string"&&this.extractCardText(e.text,r,a);for(let i of["text","elements","columns","fields","actions","options"]){let o=e[i];o&&typeof o=="object"&&this.extractCardText(o,r,a)}}}}renderCardTable(e){let r=Array.isArray(e.columns)?e.columns:[];if(r.length===0)return"";let a=r.map((s,d)=>String(s?.display_name??s?.name??`\u5217${d+1}`).trim()||`\u5217${d+1}`),i=s=>{if(s==null)return"";if(typeof s=="string")return s.replace(/\|/g,"\\|").replace(/\n/g," ").trim();if(typeof s=="number"||typeof s=="boolean")return String(s);if(Array.isArray(s))return s.map(d=>d==null?"":typeof d=="string"||typeof d=="number"?String(d):String(d.text??d.content??"").trim()).filter(d=>d).join(", ");if(typeof s=="object"){let d=s.property;if(d&&Array.isArray(d.elements)){let I=d.elements.map(u=>u?.property?.content??u?.content??u?.text??"").filter(u=>u);if(I.length>0)return I.join(", ")}if(d&&Array.isArray(d.markdownElements)&&d.markdownElements.length>0){let I=d.markdownElements.map(u=>u?.property?.content??u?.content??u?.text??"").filter(u=>u);if(I.length>0)return I.join(", ")}return String(s.text??s.content??"").trim()}return""},o=Array.isArray(e.rows)?e.rows:[],t=[];t.push(`| ${a.join(" | ")} |`),t.push(`| ${a.map(()=>"---").join(" | ")} |`);for(let s of o){let d=r.map(I=>i(s?.[I?.name]));t.push(`| ${d.join(" | ")} |`)}return t.join(`
6572
6572
  `)}dumpCardContentForDebug(e,r){try{let a=mH.join(CGt.homedir(),gl);Nv.existsSync(a)||Nv.mkdirSync(a,{recursive:!0});let i=mH.join(a,"feishu-card-dumps.jsonl"),o=r;try{o=JSON.parse(r||"{}")}catch{}let t={ts:new Date().toISOString(),messageId:e||"(unknown)",content:o};Nv.appendFileSync(i,JSON.stringify(t)+`
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "hwjcode-cli",
3
- "version": "1.1.133",
3
+ "version": "1.1.134",
4
4
  "type": "module"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hwjcode-personal",
3
- "version": "1.1.133",
3
+ "version": "1.1.134",
4
4
  "engines": {
5
5
  "node": ">=20.0.0"
6
6
  },