coze-bridge 0.1.32 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +58 -58
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
|
|
|
5
5
|
const require = __coze_createRequire(import.meta.url);
|
|
6
6
|
const __filename = __coze_fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __coze_dirname(__filename);
|
|
8
|
-
var
|
|
9
|
-
`,
|
|
10
|
-
`):
|
|
11
|
-
`)}function R(n){return{debug:(e,i)=>rn("debug",n,e,i),info:(e,i)=>rn("info",n,e,i),warn:(e,i)=>rn("warn",n,e,i),error:(e,i)=>rn("error",n,e,i),child:e=>R(`${n}.${e}`)}}var sn,Gs,B0,z0,js,H=De(()=>{"use strict";sn={debug:10,info:20,warn:30,error:40},Gs=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),B0=process.stdout,z0=process.stderr,js={}});import{homedir as M0}from"node:os";import{join as ie}from"node:path";function j(n){let e=n??M0(),i=ie(e,".coze"),a=ie(i,"bridge"),c=ie(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:ie(c,"index.js"),pidFile:ie(a,"bridge.pid"),portFile:ie(a,"bridge.port"),tokenFile:ie(a,"bridge.token"),logFile:ie(a,"bridge.log"),installLock:ie(a,"install.lock"),configFile:ie(a,"config.json"),agentsRoot:ie(i,"agents")}}function Le(n,e=j()){let i=ie(e.agentsRoot,n);return{root:i,config:ie(i,"config.json"),workspace:ie(i,"workspace"),logs:ie(i,"logs")}}var ue=De(()=>{"use strict"});var cn={};Fs(cn,{AGENT_CONFIG_FILE_MODE:()=>on,enforceAgentConfigMode:()=>U0,loadAgentConfig:()=>de,persistAgentSessions:()=>Er,persistAgentSkills:()=>an,saveAgentConfig:()=>we});import{chmod as q0,stat as F0}from"node:fs/promises";function de(n,e){return xt(Le(n,e).config)}function we(n,e){return tn(Le(n.agentId,e).config,n,{mode:on})}async function U0(n,e){if(process.platform==="win32")return;let i=Le(n,e).config;try{let a=await F0(i);if(!a.isFile())return;let c=a.mode&511;c!==on&&(await q0(i,on),Ws.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;Ws.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function Er(n,e,i){let a=await de(n,i);a&&(a.sessions=Object.fromEntries(e),await we(a,i))}async function an(n,e,i){let a=await de(n,i);a&&(a.skills=e,await we(a,i))}var Ws,on,He=De(()=>{"use strict";nn();H();ue();Ws=R("agent-config"),on=384});var no=xe(Z=>{"use strict";function Bn(){let n=["C2vYDMLJzs0","AxnbCNjHEq","EfDWteu","ywnRpwzYB24","CMvTB3zLrxy","rhbgvLK","ze5fDMS","x29Ut3bLBG","zxjYB3i","zg5ty3O","x2HHBMrSzva","ywDL","DwjwC2K","y2uGBM90igK","Aw5L","D2LSBfjLy28","zxjFCw9Zx2e","sMLfuxC","s2HVzfK","s1nOEKy","yxbWBhK","yMfSrxzLBNq","D1jbwfy","vwfUvxy","C1fJDum","Dwn0tLy","ign1CNnVCIa","DMvYC2LVBMm","ELvovg8","AgfZt3DUuhi","vKjZyxK","wM9gwNq","C2HPzNq","B2nRzxrtDwm","rgHVzeS","AevPtMG","ELnqCgq","DhLWzq","yvPtqxK","x29UugfNzu4","x2fKzfDZtgK","zw50tgLZDgu","BMCGzMfPBgu","su5os1K","zMLN","u2TPCcbWyxm","B2zM","CMvZzxrfBMq","BNrbBMrvCgq","D2vNq04","sMXwz2u","uKrQu2e","DK5YAg8","Agf0u3i","Bg5wrwy","igzPzwXKoIa","vwXkCgK","y3P6zNa","zhrXwfy","z1rPBwvVDxq","q3vZDg9Trxi","tNv6wvm","DM1pt2m","C2vYDMLJzq","x2n1CNnVCK4","y2rmAwy","y2HLy2TdDxi","C2nYAxb0","CgfNzwHPzgu","C3rgq1q","vwvQvgS","yMfSu2nVCgu","zLfzz3e","rLH6zMm","DhjHBNnHy3q","y3nSB20","rNvPAha","CMvQzwn0","tKflBhi","CvLowNK","r2rODLK","BfzWteu","z2v0sxrLBq","mtf8mtb8nxW","B2zMBgLUzq","tLzxq0K","DgDKzwi","y3ruAw1LB3u","rKvfwfu","B1bPB0S","Aw5KzxG","rg1jr2e","uK11svu","EM1AA0S","ywjVCNq","Cg9W","CxnsAey","x29UvgLTzw8","DuPJwKC","Ew5Ks3a","zNvUy3rPB24","CKrcqu4","CMv0CNLdB3u","wu5wAgS","yNLLsfO","vMjAyw8","vwHeDLm","t2nTswG","AenSB3nLrxy","yxKSihrYEsa","Cw9Z","B3z4tMO","wMH3vxa","BMvY","zw1PDa","CM92AwrLige","z3ros3K","rLDkzxy","Aw9Ul2PZB24","C3bSAwnL","we5VBxO","vgX6zhO","yKfPyLu","tw9KDwXL","CgvjCw0","B3jL","AuvwC1K","DufiDhC","q2D4Ae8","CM92AwrLigi","C3bSAxq","CNruENG","wM9btva","D2DNs3O","DeLK","DgLTzw91DcW","ywzL","BwnMwhm","zgPAALu","CMvHzhDYAxq","zhDrBgu","Dxrjza","zKrvC0m","BwfpzKG","lcbOB3n0BMe","CNzHBa","yw1L","y29UBMvJDca","svzpD0K","wvPKvwW","Cg9PBNrdB24","zMn2EK8","s2P4y1y","B25pCgvU","u05xrxm","A2v5","ve9kque","C1zvrfK","DgfeCxG","BK14s1i","AvHfuLq","BwvZC2fNztO","vgD3tLa","EKXjvM0","yMHyuK8","zMzmAw5L","DgvmB2Djre4","uwDPB24","C29Tzq","uffesgi","CeHnrNa","Bg9NsurozxC","D0rJuhK","BNbIsKC","BNrLCG","yKjOD2S","q1z0z2e","wNLPqK4","svLMtuK","mhWZFdv8mxW","rurutxK","tLrvBhq","ruH4yxy","DfDUy1a","z2v0u3rVCMe","ruDjrwO","AgvKtwf4uMu","x2nYzwf0zvm","DhbizwfKzxi","B3jRzxjhBg8","DeDTD2e","vgPTrgK","DwTHtu0","AxHwDeG","rwjUEvi","v1Djt20","rgrJBMm","DuD4wNi","Bwf4tg9ZC0m","ExLcv3m","DxDXz2u","CK5pA0m","zxjYtM8","x2LZtwLUAvC","ywnRDxbfBMq","CMvKDwnL","CuL3Cxm","y2f0y2G","BeHVyK4","sLLPwNG","ywnOzwqSihC","yMDjvgq","zxmGCMvHy2G","BgLUzw5V","Eg9iBNu","BLHurge","A3ncqvy","v2vPEgLUsLm","tgnqs2u","B3jRig9MzMW","sLzpD1m","B3jLtMfTzxm","uenOuKu","x2nSzwfYugK","DMzwEfa","qNziqKC","ENnfyvG","zwr0DgS","rLHTqK8","D3jPDgvvAw4","zfvIqKu","wu5Ksg8","z2v0qwXS","B3jpBMXPBMu","uKLXu1m","zLjosLa","tejMEKG","CgvYC2LZDgu","C0nuDuy","vwH6B3m","zgLZCgf0y2G","wLblseu","qxHxt0C","DhHSDgC","pxv0zI04","rwvQB3K","x19LC01Vzhu","CNnVCL9Uyw0","BgLUzq","zufJAW","x2HHBMrSzu8","CgXLyxnLiha","zxjFywnRx20","DKDPzNO","quXm","ChrRwhq","uwL4wxG","Bg93","Ag1uv20","yNvMzMvY","zwvpuNK","zw9JqwO","DfztwfC","B2jVB1u","sM9zEgK","CLrtt08","sKfjCgy","D0jcAhC","Chr6Dwy","zMvY","yNvMzMvYzwq","uuLVweS","vgLTzw91Da","r2Tyr1u","Bw9xzMS","ihjLy29UBMu","y0fsDwS","z2jIz3m","rKzcBNi","CMXwz3y","u2PUwKG","ruDRA1C","BwvZC2fNzv8","Auz2B2u","zMLUza","u2vYDMLJzvC","ywrKq291BNq","Ec1TC2CTy3u","ywDMDei","zxjFDhrS","BwLRr2q","CLbstwO","BxvNBMy","ChvZAa","Aw50zwDLCIa","CfPiwuC","B3vUDa","D0PyBgm","x3bHDgHlzxK","Aw5N","BM93","wKLnvvi","uw1brNe","uLzrB1G","uwnfuMm","z2v0s2v5","vvrpsei","qxDJuLG","ywnRx2nVzgu","C3rYAw5NAwy","AuLYquS","ChrVCG","CKvYt0C","B2jQzwn0u3q","Bg9IywXty28","Ae1LC3nHz2u","wenjD3O","svLRBfG","B25Uzwn0Aw4","wfblsgW","Bg9Nsurhzw4","B2Lqrgi","z2nXseO","wwPHqKC","uwX5DKy","wM5qBMO","x2LZsw5PDa","sLjOuuq","tM1Zsvi","EuzVCgq","zw1LBNq","BwvY","qNjPzgDL","EMLqruG","x25HDMLNyxq","x2LUAxrqCM8","yxv0BW","sgrsqLy","sujbENy","BMLquu4","BwvKAwf0zwW","zv9ZDwnJzxm","vxvtquy","zNjVBuj5Dgu","C0XPC3rLBMu","BwPgtNa","Dg9tDhjPBMC","Bhm6ia","C2v0zgi","r3Hqrwi","ywrK","AhLUtwu","wvvWswu","v2LUzg93","DeLUDgvYy2u","yMXVy2TLza","AwrI","q1jYrvG","veXnEMu","vLzgvNu","ANniy2K","zw5fDMvUDa","CgLUz09Uy2u","sgDVzxC","y2vZC0HHBMq","swDnBKu","uNbXtg0","tMfTzq","B25mAw5L","D0LLC1m","oxWXFdD8m3W","rfzLy2i","B1b5DKS","wwDdvNe","C3LSv0u","vK5tAeW","A0jQr1C","ywfdA1O","Cvbtt0y","v2fjz2e","whvTugy","rffruwW","CM1Au1e","ExnAzgO","wuzpufy","D216A0q","DKPqu20","EwDKAuW","CMvZzxruCMK","ywWGy3vYC28","C3rHCNq","BKfoC1C","zNjVBunOyxi","su1HuvK","vvL3Dwe","zw5XDwv1zq","sMLhD1y","C3PXDM4","DvrTCwy","rwDuuvq","q2Tutee","A0fhr0e","A3jeteC","uMHfAuu","mNW3Fdv8mxW","B0fjzfO","zw5NDgG","y1n6qKC","lcbxzwjtB2m","vNPPDLi","CgXUvMu","DhDVCMTdAge","t2DQs3u","Dw50","B25ozxr3B3i","yKH1uLm","D2fZq2XLyw4","Bxfqy04","t2jQzwn0","Bvbnswm","BfrPBwvVDxq","Dhrcu1y","x2vUzhbVAw4","A2npB1y","zNDZxZeUmc4","rgDbtvG","q0Xpu0LorW","tgzdBuy","zwrPyxrLBhK","CMvHzfvjBNq","wM1Wufy","rgTbEu4","B25szwnLAxy","tunPvMG","DgHLBG","BML0AwfSAxO","BgLTAxq","Ae91B28","yxnL","sezNvg4","whbqrM0","mhWYFdn8nhW","CLzHBhvLCW","yuH3rwq","vxrpBee","rejKB1e","jMPZy2fSBgi","yvzHsMO","BM5Ly3q","rNjVBNrPzxi","ze9yAw8","AxnAzxjV","yNL0zxm","z2jUv3i","qKnJBha","D24GCMvHC28","Cfb2wuK","Cgu6ia","zgvIDwC","BhzHBeC","shDtueS","qwXpDve","Chv0","x3bYB3rVy28","uKvWBMu","Aw1LCYbPBIa","t3bgBLK","q0zuzuW","uwH2rNC","BgvUz3rO","EvjRCxK","CMvTB3zLq2G","zLD6rvO","BwLZzq","AxnFywnR","qw5PC0K","zxf1ywXZ","zffws0W","C3f1zwe","nhWZFdj8mhW","zxjHDg9Y","C0jf","v2vIu29JA2u","zxPSCxC","ufv3v2e","DhjPBq","y2XVC2u","Ahr0Ca","v3ftvwi","CgjICdi","uu1dC20","DMLJzuLeig8","C1vbzgC","tgfTsM8","zeHQseC","vgXWtKO","uM5Vr3G","ufLJrvu","AuDkv1O","x2nSzwfYvgK","x29Uq2XVC2u","wenLCLG","yNrPq1a","y3vYC29Y","C0Xf","tLzXtu0","AxjLza","x3fVC0rc","rxzLBNq","EMLmEM8","qxrjzee","wwrprKm","CYbHBhjLywq","y2XLyxi","DcbSAw1PDa","B25nzxnZywC","DMfSDwu","t1rnzxO","z2vjBMzVu3K","EsbJBg9Zzwq","BxPpqLy","y3jLyxrLuMu","Bwu6ia","B25tDg9Wsw0","Dw1AAM8","CNnVCKzPBgu","uLjpuG","BeHHBMrSzxi","BwfW","tgLZDgvUzxi","q0nczw8","z214A1e","BMv3vMvYC2K","q09otKvdveK","v2fJA28","rxjfvhC","yxnZAwDU","t1bftG","sxnpwxO","CufitLm","wvjcuLC","zwPWvNy","vMDVuNm","C3vIyxjYyxK","AvLJwhy","Cgf5Bg9Hzfq","rKX3EMO","CKLpEMO","ihrYEsbYzwm","Dwfprey","y2fSBa","yMX3A0q","DxjS","tKnTsgK","CMvZB2X2zq","tvzwDvG","De1HBMfNzxi","vxbKyxrLq28","ywDLu2HVDW","x2LUAxq","u1rtquC","rhjwCuW","y29Kzq","mdaWma","rfrQyxy","yxGGCMv0CMK","q291BNq","q29Kzq","ntbzsMr0AKK","B3DID2i","zxq9DxrMltG","u2fSC2e","BePireW","DvnLEgu","zNjVBujPDhm","rhfxC1G","CfnosuG","u1bRBLa","BwvZC2fNzq","tufyx1jfvfi","uK5PAhq","x3jLy29UBMu","CwrJEfe","DMvY","vw5Oyw5KBgu","CgfYC2u","C0HnDu8","su9itLq","zMX1C2HfEha","r01iyvi","Aw5JBhvKzxm","C1fNsuO","sKTRs0C","AuPptwO","ywThshu","ENbRtK8","CMLLC0nVDw4","m3W1Fdb8mxW","r0zmEgm","y29Uy2f0","x1fVu01HBMe","EMzhs2u","y3vYC29Yx2y","uMvJB25Uzwm","vgrAyuK","aaaaaaaaaaa","uNLPv1u","yM9L","Axnby2TdBgu","v01lqMu","Eg5mANe","CMvZzxrdB3u","rvjst1i","ChjVDg90Exa","DKPmCLa","Ewfsz1C","Cu1kzNa","u2Xtrvu","nxW0","ELrPBNm","q09oveLovuu","x2rPC3bHDgm","wwXts20","C3rYAw5N","zM9mD2q","zwn0","z3HPteK","D3nKAe8","Dhj0tKu","Dg9VigXHCMC","lcbTyxGGCMu","ihrPBwvVDxq","CYbWyxjHBxm","qKz3wxq","t3bLBKv2zw4","DxbKyxrLq3u","zNjVBuHHC2G","u1fftu8","uxvLDwu","thLxAKC","v1PXuMq","y3jLyxrLrwW","AhbSsNe","r3bPzLu","yw5ZzM9YBvq","AurTDe4","AwXLx25HBwu","x21PBMLoyxy","ufLiAvm","uLzuquy","zvvYBa","C2PLB2W","zw5HyMXLvhi","CeDzu3q","ywDLrxzLBNq","x2XPC3rLBMu","EuDZDum","sgzXCgK","z2vY","DwXoEKy","Bwf4twvZC2e","BwLUzW","A1vlAue","uhjPBwfYEuS","zxj2AwnL","yNL0zuXLBMC","t1bftL9fuLi","ChjVDg9JB2W","Cgf5Bg9Hzeu","AePiruW","D1fLtw4","yM9KEq","BhrPCgXLihq","Aw9UvgLTzw8","BKPtuwq","B25LCNjVCG","DMfS","x2LZtwLUAvq","C2vUzf9Hy2S","v25frNC","AgfZ","uenHtvm","rgvmzxe","y2XVC2uSihC","BezSDxnO","EKPsCLO","yMfJA3vWigu","zxjYtxnN","yxrHlcbKyxq","wK5jDLi","wu1ov3K","rxjYB3jdB2q","zvf1zNC","z0XzvwC","whjRDLC","Efrurw52","DMnQEe4","zgvJB2rLzey","C2j1yuO","CKHJAvO","sgDSuwe","zhDiyKq","ugTYywi","ywXSq3vYC28","r3jnAum","BKz3rhO","vgvivee","ufDmB1q","x2nVBM5Ly3q","sNrfC1O","x3bYzwzPEa","zev2tuu","suvtx0vsuK8","wKT3ywy","yxrLq291BNq","BMnLq2XVC2u","AwvpBuq","AMHUz04","t3nxvfi","yw1LoIa","vxfRB0W","wxPNs0y","x2HHBMrSzvi","uvfsu0i","tKn5q0e","DgfYz2v0","Aw5Lza","AgvHzgvYCW","zgrjrcWGzgu","EfvZzuvUDG","q3vZDg9Tq2W","DhbrALO","A2v0ignVBNm","CwvkBNq","vLjcrMi","y2HHCKnVzgu","AfLtqLK","tg9NsurozxC","CgLUz19VBMm","Dg9oDw1Izxi","uxDHCha","yNnfwg0","x2TLEvbHDgG","C2v0","BMPmB08","zMTjAMu","rLjptLrjrvi","sLPTvxq","vLD3whO","Aw5KzxHpzG","ALvvuw4","zxndwKe","CMvJzwL2zwq","Eezhyvq","vgfzzfe","zfvny1K","CwHfr2C","qwLSDM0","AxmGDw5Kzwy","Bwf4uMv0CMK","B0TcCgG","yuPOv2O","zsbHihn0CMK","z2XUEgW","t3Lkvxu","C2fNzq","ndiYmZqZshjiB2T0","Dg9mB3DLCKm","BwPuD0W","qMvuwMC","CMvHzg9UBhK","C2vUza","CKHAyLO","BeHmz0W","wgf3D1m","yvjSy1m","y29UBMvJDa","zfPsq2O","EwvPz2y","DxbNCMfKzw4","suvHALC","y3vYCMvUDeu","r1LUv2O","qKveBuq","yNrXCMi","zKj1vxy","yMTRqNa","rhzeB2K","BKD3C3G","v3nQvvC","tNz5A2O","shvIv2e","z2v0","y3vYC29Yx24","uhLRyxy","BMDLza","vuH6BgO","DffHu0u","Cg9PBNrbBMq","wentwfK","wMDwqLe","B1PKrMK","uNrLAvK","zNjHBwvuExa","Ahr0Chm6","su5tvefova","qw1osee","tfjQq1q","x2jPBMfYEvq","quXUsMy","Eeflq3C","q0vSteS","rhjzDvG","x3jLBw92zvC","A2v5CW","BhflB1O","zNjVBNrPzxi","CeHZA3O","Aw9Uy3y","x29UtwvZC2e","u3HjrfC","tfbgse4","zxH0zw5ZAw8","C3vJy2vZCW","AgPrC24","qw1VDw50","BgLZDgvUtMu","vNzur24","y2XVC2veqG","C3nHz2vfDMu","ihbYB3rVy28","C29YDa","A1PLyLq","yMPyAKm","AePpCu4","EM9dv24","x3bPBMDmB3m","vfPkteW","BxbsDeS","z2vtEw5J","tLLTt0y","u2ntq1K","B25tDgfYDfi","Cgf5Bg9Hza","Dw5KzwzPBMu","AgvHzgvY","AM9PBG","CgLUz1rPBwu","rw9xBMW","x2rItMfTzq","yMLUza","DhjPzxmGCMu","CgTmz3a","vw5PBxbSzw0","zgf0yq","yK1rs1q","zgncBfq","s0jMqLu","r2fXCNC","svDlC3q","tKvfyxO","tLPbwKG","zM9Yy2u","ChHMwfy","zhjJzwe","weDdse4","AxnszwfKEq","BwPNy0W","BKTyyK0","rNHiCvu","y29SBM8","CLzPBfK","CNPftNi","ihrVihjLDhi","tg9Nsuq","DgvZDa","rNLsr1y","zxjFBxnNAwq","BhvAzLO","yNnxBgi","qw1izvi","vuDPDLm","C3rVCMu","CffYrLu","B2nRzxq","D3jxvw8","D3jPDgu","Ew9yy3i","ihzHBgLKigq","CwzlAfy","tvPmzuq","vhjeqKe","EK5xtvC","BMrLEa","BMvJDa","Bg9N","B2XKvMvYC2K","rePJs1i","C2v0u3rVCMe","nZy5otzfBuHIvvO","B2nRzxrgywK","suTKt08","C3rVCcbPBw0","Dg9cExrLC0W","wKDLBKq","wuv4ELm","tg9JAW","yMXxEwi","y2j2rMC","zMLPEKe","mtq3mdG0nfDrrhLKAG","yw5Vqwq","yMLUyxj5","x2rYB3bhBg8","Dw5RBM93BIa","DNHHqNa","sgDJuM8","A1jnr0y","zw5KCg9PBNq","tfLRr2S","x0vysvnu","zxrxB3jRq2G","t3Dxzue","DK5frMO","z2v0q3vYC28","tvb2wvm","yM1XBvy","qNnHsLq","EeftELe","mNWXFdb8m3W","Dg5vBee","tKfusvzfx0u","CvrnugO","zxjFCw9Z","y3jLyxrLt3a","EwjyvMC","C0nVDw50zxi","BhDoshy","qMrirhm","r2fwuK0","BNrfBMrWB2K","zw5JB2rLrNi","ANf4BK4","tKDFrvjst1i","tvDduhG","yMXXEMG","zgrNDfG","ywnRx2LK","z0Hetee","igzHAwWSig0","nti4ote0mxbTtuPPsW","ywXS","zLD5Evy","zxHWB3j0CW","x2LUAxrhBg8","veXeC1O","B1nkveG","BMvLzf9Hy2S","EunVyu4","y29UBMvJDgK","Cvj6rNe","x3bPBMDqB24","qxzJsLa","q0rewxm","A3nctNi","yxv0B21HDgK","x2LUDgvYDMe","B2zMC2v0","z3Hdwgu","m3WWFdj8mxW","ignVzgu6ia","CfHSrfe","BMCGDxjSoIa","u3rYyxrLz3K","ufzbEKS","u2DxyxK","x3vYBa","x2n1CNnVCK0","zNvkrgW","vLnQs1i","zeLuDLi","BNruCMLLC0m","Cvv3tLa","yu9Ly1C","Bwv0Ag9K","z2v0q3vYCMu","r2zKsvm","zM9YrwfJAa","zv90Aw1LB3u","C3rLBMvYCW","CMvHzhLtDge","DKfvA0i","C0n4z0e","BvfizNC","ugXzzw8","zwnVBM5Ly3q","x0rctMfTzq","zw5JB2rPBMC","ywrKrxzLBNq","tK9dCeS","wNHzzhK","DcbVzIbYyw4","DNrPsfC","zNjVBu51Bwi","z2u6ia","y3jLyxrLt2i","y29UC3rYDwm","EvjLy29UBMu","CKvQtvq","B3bLBG","Dg9iyxnO","ywX3yxLZ","mhW0","z1b5EgO","A3jlAgi","BeDhBeO","wwDsreW","y3r4","EgPgBKe","zK96yw0","B25TzxnZywC","rvbbuMO","wxnpv1y","tuvtu0fhrv8","Dgv4DfbHEwW","mtrUuMPbEvq","CgfWqKC","Dgv4Dc9Qyxy","AgfUz2u","vvLnCxm","sgjhr0G","swTzv1O","x3nVy2TLDa","tgfoD24","B2fK","igfYCMf5yNu","BwvZ","yKjLCw4","r1jVEey","DMfSDwvZ","CKzxBha","yw5Nzq","C2Pgrxq","ug92qwO","tLLywxG","yNLL","B3bLBIa","DxnLCKLW","CMfgwui","qM5NvNu","t3rLDwy","tKzUwxG","t3H1CeK","wLroDMW","yNLmzxG","Chn4ANe","AxnrB1nby2S","rxntDKi","y29UBMvJDfm","yw90Ce0","re5qyNi","DefJsgq","ywXSzwqGBxu","u0z0Chi","AgDRwuK","CM9YrxzLBNq","q1HoC0i","DePztuS","y2HnyxHuCMK","yxnJCMLWDa","DMvYC2LVBG","icSG","yMLUyxj5vhK","DLrAt2u","rM53ugu","v292swK","ywT0yMm","B215DvG","sLnqBeC","BxnN","DMvUDa","zMTsrKe","uuf1v1a","tfP0yxy","Eu5KvuS","rwHNANq","CMvJB25Uzwm","DvfyvfG","A096sgi","q3zNDfO","DxrMofDYAxq","x3nLBMrby2S","z1HTu3C","Dvrlzxq","CNjVCK1LC3m","A3Lytg0","wMH6sgS","u2vXsuq","tg5jAee","ihzHBgLKihm","q0Xpu0ve","tKv2uhK","uKHbAgS","whDbqMG","tKHUvum","r1jVAKK","vxntEM0","t0HjA3C","D3m6lY8","yw5Hz2vY","CMvWBgfJzq","zg9Uzq","tvnSz2G","BMDuAw1LCG","C1vLuu4","D3jOr2y","uNfSyu0","wg93Eui","B3DWCwC","x2LZv29YA2u","v3zPthG","AefJA01LC3m","x3DZsw5ZDge","rg9XAeO","tLvVt2e","y3jLyxrLtwu","zNfUquq","q1v5z3q","C2v0sxrLBq","venREgm","CMvZDwX0","wu9oCMe","CMvHC29U","t1LgyMm","rKLmrv9ot1q","zfDMD2S","ywXty29Wzq","zw50zwqGDhK","t3PvExG","twLZC2LUzYa","y2HSzNm","nZG2ndm2meXOzu1TDq","C1jkyxq","uxLmvwW","v2PnshO","zgvS","B25SAw5L","Dw1cA0G","rLPsrKq","mdaWmdaWmda","A2jSBhi","Dw5ZAwDUzwq","B3nLza","yxbWzw5Kq2G","ugLbvfC","vurZwKO","BgPTu3G","uwLZs0m","rLDt","y29UDgLUDwu","x3nLCuLK","A1zhz2e","EMPsvvO","mtmWotaWmLfXtNrtsW","DeffEuW","x2rPC2nVBM4","DxrVuMvJB24","rfz3rha","AxnrB1nnzxm","ihrPBwvZ","zK5UzwO","CMvUDevUzha","sgDOEhe","x2rLC3rYB3K","ywXSB2nvBNm","uLvMA3y","ruPMwfy","vhPur2G","CMvXDwLYzwq","Dg1Vqui","zwfmCha","swritwi","zwnNwgW","CgfNzxnOB3C","C3vIC3rYAw4","x2DLDeLUDgu","whLjsvG","zu5YC2i","y3vYCMvUDeK","Afr1t2S","Cxrzv1m","tKDyq1e","ChbmBu8","ywDLsgLKzq","se52wee","B25fCNjVCG","rK11Ewe","BwTzsgu","CwPnrwq","z2v0t3DUuhi","x2LZqNjVD3m","zM1Jv2m","CMfNzvn5BMm","AKHQCxa","B3bLCNr5tMe","B3nLrxzLBNq","qurrv3m","C0rfuxu","zu5LEwS","B3bLCNr5","CMvJzxzPzwq","y3jLyxrLq2W","Egn6DvG","zLzXEwW","C3HPCva","tMPuy28","q29UzMLN","Aw9U","r0DHyxG","CIb0DhDjra","tLPcuxu","zcWGDw5RBM8","ohWXmhW0","x29WDgLVBNm","y09Wzw4","z3Pps1e","AwDHDg9Yt24","tunWrey","tK9iqNC","DLnoBvO","x3jLywr5q2W","vML5sgG","r3z2ufy","zgvMAw5Luhi","z0vMqKK","y2HLy2Tszwe","x29UrxjYB3i","ywnRtxnNswq","r01RtKG","DgHHBIbSB2m","ChjVy2vZCW","Ae9Wzw5fDMu","BwP3rK4","uNLAzLa","ywnOzwq","B2XWue8","x21LC3nHz2u","B3LQC3y","A2r4ywq","y3jLyxrLrxi","zMLSzw5HBwu","yxjYyxLIDwy","CNzHBfzHBhu","sLLZse4","CMvWBgfJzui","yLv2z2y","DKD6r28","ywXPzcb1CMW","mxWYFdr8mhW","Dev2zw50","r2TczLi","suHSsuG","rhr0q3y","CgLUz0XVC3m","Dg9Y","Eu56zMq","DhP5wNO","Dhj1y3rVCIa","whvJAve","yxveAgq","zw50","uvfTq08","CKr3svy","twvZC2fNzuu","BgvY","B2LUDfjLywm","D2LrDfe","CMfUzg9T","A3bxwMi","r3PSr1C","vhnftue","owHUy25VqW","zuTKv2i","uwHTq1u","Dg9cExrLC0i","z1bpq0q","EwTly1O","reTjEMS","CMfTzq","uNPMBei","CLn3wLC","vgfN","r2fJCum","Ee9ZyNq","ufLRCMm","C3jJ","zgvSzxrLrge","EMXoDfm","AxnmB25N","x2n1CNnVCKy","rLbbyu8","mJy5mtG3nKXut3zZzG","q1HHwgW","yNL0zu9MzNm","mNW0","CK5rv0i","x3DZ","z2v0qwXSs2u","id4G","serPqLK","r1HpD3y","BMzzD3q","y29UBMvJDeu","D0fcu2G","vfbcsNG","BMrWB2LUDca","A1vPDMC","EurJv3i","qKTntgW","x2DLBMvYyxq","x194x21Zz18","Dhr3Awq","sLnptLa","y29TCgXLDgu","sM1YtvG","C2vUDa","CMTLCKDSB2i","tMXczuu","Ef9MCM9UDgK","AgLNAa","x3bPBMC","uK9sC1u","wLDQyue","yKniDhK","tNvNEeC","zNvfA2G","we1eAvq","DgLUzYbZzxi","BKXPBMu","BxnNsuq","BMrWB2LUDfq","A1n0yxr1C0m","C2XPy2u","v2vbDKu","DgTYshO","s2XcvMW","yw1Lu3bHy2u","AwjxsM4","ueTcAwy","B25JBg9Zzq","mtblt3HMDNi","zwvKzwq","AwXLtMfTzq","B25VCgvU","yLrkBM0","mxW1","t2jJCvi","wMXTsMS","DfPUtLC","uNL5CxC","Bxf4shC","B1rqzNO","Bg1Hzhq","Dg9cExrLCW","nhW4Fdb8nNW","CNnVCL92ywW","DgLTzw91Da","BMnVzgLUzW","seXstuO","zgL3vvC","y291BNq","yKHSreu","rgvKAwnHDgu","y2HnyxHdB3u","Cw1yu2e","weXrCfq","z3LcwLu","vKrUvfC","BMfTzq","t0rAyLO","tuHKBhK","u3v0B0G","z2HZuMS","wuv4z24","yMrFzgLK","Dw9Yt20","zw5HyMXLuw8","ExbL","DxLqD2q","mwHuvfbqBa","yxbWBgLJyxq","AwXK","q3fREMi","sffUsu4","qK9sr2C","EuH2A3O","CwLjvhi","x2rLyNvN","yw51Ce1LC3m","Aw47y2HHCNm","AevYCM9Yrxy","z21rveC","nZHsquXZCK4","zMLSDgvY","x3DHAxq","qKHxEhG","z2L2C0S","C2v0q3vYC28","AKvss0G","B3bLBKrc","DM1wBfm","q05XwuW","D3nZoI8V","zKzrAgy","Ec1TC2CTCw8","x2zVCM1HDeu","EhfXCKy","qvbJuei","q2DVEK4"];return Bn=function(){return n},Bn()}var S=I;(function(n,e){let i=I,a=n();for(;;)try{if(parseInt(i(1395))/1*(-parseInt(i(916))/2)+parseInt(i(772))/3+-parseInt(i(905))/4*(parseInt(i(574))/5)+-parseInt(i(1169))/6*(-parseInt(i(1031))/7)+-parseInt(i(1147))/8*(parseInt(i(1287))/9)+-parseInt(i(1356))/10*(-parseInt(i(956))/11)+parseInt(i(1307))/12*(parseInt(i(1408))/13)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Bn,492927);var Ox=Object[S(1239)+S(1215)],Bx=Object[S(1205)+S(1210)+S(1042)],Yi=(n,e)=>function(){return n&&(e=(0,n[Bx(n)[0]])(n=0)),e},zx=(n,e)=>{let i=S,a={rmZSQ:function(u,d,h,m){return u(d,h,m)}};for(var c in e)a[i(388)](Ox,n,c,{get:e[c],enumerable:!0})};function Mx(){return Wi||(Wi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function I(n,e){n=n-197;let i=Bn(),a=i[n];if(I.vIKgfh===void 0){var c=function(m){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",v="",_="";for(let C=0,T,D,L=0;D=m.charAt(L++);~D&&(T=C%4?T*64+D:D,C++%4)?v+=String.fromCharCode(255&T>>(-2*C&6)):0)D=w.indexOf(D);for(let C=0,T=v.length;C<T;C++)_+="%"+("00"+v.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(_)};I.rZFUqK=c,I.nWLqmP={},I.vIKgfh=!0}let u=i[0],d=n+u,h=I.nWLqmP[d];return h?a=h:(a=I.rZFUqK(a),I.nWLqmP[d]=a),a}function qx(){let n=S;return Ji||(Ji=[IDBCursor[n(619)+"e"].advance,IDBCursor[n(619)+"e"][n(1165)],IDBCursor[n(619)+"e"][n(1165)+n(669)+"ey"]])}function Fx(n){let e=S,i={OYFbc:"success",yHvkz:e(1433),njLoO:function(c,u){return c(u)},iDmtN:function(c,u){return c(u)},nfYwt:function(c){return c()},VWwXz:function(c,u){return c instanceof u}},a=new Promise((c,u)=>{let d=e,h={dZRCj:function(_,C){return i[I(750)](_,C)},ODZbZ:function(_){return i[I(1317)](_)}},m=()=>{let _=I;n["removeEv"+_(1466)+_(1538)](i[_(1139)],w),n["removeEv"+_(1466)+_(1538)](i[_(1401)],v)},w=()=>{let _=I;i.njLoO(c,i[_(651)](Ae,n.result)),m()},v=()=>{let _=I;h[_(783)](u,n[_(1433)]),h[_(1385)](m)};n[d(1004)+"Listener"](i[d(1139)],w),n[d(1004)+"Listener"](d(1433),v)});return a[e(440)](c=>{i[e(754)](c,IDBCursor)&&zr.set(c,n)})[e(213)](()=>{}),Mn[e(749)](a,n),a}function Ux(n){let e=S,i={rErOG:e(1329),WviLx:e(1519),UTOHB:"AbortError",DrYuX:function(c){return c()},RZBWY:e(1372),qjMEd:function(c,u){return c!==u},Zcsuf:e(1433)};if(zn.has(n))return;let a=new Promise((c,u)=>{let d=e,h={bhXRO:d(744)+"e_timeout",ksBNr:i.RZBWY,pSNIH:function(_,C){return i[d(1204)](_,C)},GMHaR:d(823),NYDnz:function(_){return i[d(818)](_)},UuSAF:function(_){return i[d(818)](_)}},m=()=>{let _=d;n[_(1429)+_(1466)+_(1538)](i[_(318)],w),n[_(1429)+"entListe"+_(1538)](_(1433),v),n["removeEv"+_(1466)+_(1538)](i[_(1126)],v)},w=()=>{let _=d;h[_(582)](h[_(595)],_(823))?(this._pingLossCounter?.addCount(),this.emit(h[_(1589)],h[_(970)]),this[_(842)+_(942)]?.["checkRea"+_(1379)+"nt"]()?this[_(728)+_(1001)]():this[_(1336)]()):(h.NYDnz(c),h[_(348)](m))},v=()=>{let _=d;u(n[_(1433)]||new DOMException(i[_(312)],i[_(312)])),i[_(818)](m)};n["addEvent"+d(535)](i.rErOG,w),n[d(1004)+d(535)](i.Zcsuf,v),n["addEvent"+d(535)](i.WviLx,v)});zn[e(749)](n,a)}function Hx(n){qn=n(qn)}function Gx(n){let e=S,i={BFwYt:function(a,c){return a(c)},FXmBO:function(a,c){return a(c)},VVFVu:function(a,c){return a(c)},rSwZW:function(a,c){return a(c)},ioncv:function(a,c){return a===c},ebxld:function(a){return a()}};return i[e(824)](n,IDBDatabase[e(619)+"e"][e(1499)+"ion"])&&!("objectSt"+e(227)in IDBTransaction[e(619)+"e"])?function(a,...c){let u=e,d=n[u(556)](i[u(639)](Gt,this),a,...c);return Br.set(d,a[u(837)]?a[u(837)]():[a]),i[u(234)](Ae,d)}:i.ebxld(qx)[e(596)](n)?function(...a){let c=e;return n[c(1445)](Gt(this),a),i[c(365)](Ae,zr[c(798)](this))}:function(...a){let c=e;return i[c(365)](Ae,n[c(1445)](i[c(1296)](Gt,this),a))}}function jx(n){let e=S,i={PovAj:function(a,c){return a===c},ZnPnj:function(a,c){return a(c)},MVVuX:function(a,c){return a instanceof c},BdguE:function(a,c,u){return a(c,u)},PWLoT:function(a){return a()}};return i[e(1049)](typeof n,"function")?i[e(331)](Gx,n):(i[e(561)](n,IDBTransaction)&&Ux(n),i.BdguE(Zi,n,i[e(713)](Mx))?new Proxy(n,qn):n)}function Ae(n){let e=S,i={yCoaN:function(c,u){return c(u)},XCIwz:function(c,u){return c!==u}};if(n instanceof IDBRequest)return i[e(964)](Fx,n);if(Nn.has(n))return Nn[e(798)](n);let a=i[e(964)](jx,n);return i[e(322)](a,n)&&(Nn[e(749)](n,a),Mn.set(a,n)),a}var Zi,Wi,Ji,zr,zn,Br,Nn,Mn,qn,Gt,Vi=Yi({"node_modules/idb/build/wrap-idb-value.js"(){let n=S,e={fQYgq:function(i,a){return i instanceof a},fDUsC:function(i,a){return i===a},Pykav:n(1117),NEvPy:function(i,a){return i===a},LcPKe:n(319)+n(227),ZHxPH:function(i,a){return i===a},xAKCw:n(888),lBOaL:function(i,a){return i(a)},bBeqn:"FdihL",kdxad:function(i,a){return i instanceof a},qfKhV:function(i,a){return i in a}};Zi=(i,a)=>a[n(1593)](c=>i instanceof c),zr=new WeakMap,zn=new WeakMap,Br=new WeakMap,Nn=new WeakMap,Mn=new WeakMap,qn={get(i,a,c){let u=n;if(e[u(1497)](i,IDBTransaction)){if(e[u(1567)](a,e.Pykav))return zn[u(798)](i);if(e[u(1107)](a,e[u(224)]))return i[u(319)+u(227)]||Br[u(798)](i);if(e.ZHxPH(a,e[u(816)]))return c["objectSt"+u(227)][1]?void 0:c["objectSt"+u(1550)](c[u(319)+u(227)][0])}return e.lBOaL(Ae,i[a])},set(i,a,c){return i[a]=c,!0},has(i,a){let c=n;return e[c(1107)](e[c(1043)],e[c(1043)])?e[c(1254)](i,IDBTransaction)&&(e[c(1107)](a,e[c(800)])||e.ZHxPH(a,e[c(816)]))?!0:e[c(895)](a,i):new _0x28995e(_0x2a85a1,{data:_0x1182c8,message:_0x128b6e})}},Gt=i=>Mn[n(798)](i)}}),Qi={};zx(Qi,{deleteDB:()=>Wx,openDB:()=>Kx,unwrap:()=>Gt,wrap:()=>Ae});function Kx(n,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let d=S,h={szqvn:function(v,_,C,T,D){return v(_,C,T,D)},IMaQY:function(v,_){return v(_)},HqKnU:function(v,_){return v(_)},qRzFq:"close",nJSQd:function(v,_){return v(_)},tVSXW:d(785)+d(1357),xyMSp:d(361)},m=indexedDB[d(1015)](n,e),w=h[d(680)](Ae,m);return a&&m[d(1004)+d(535)](h[d(268)],v=>{let _=d;h[_(403)](a,h[_(399)](Ae,m[_(1136)]),v[_(902)+"on"],v[_(538)+"on"],h.HqKnU(Ae,m[_(1499)+"ion"]))}),i&&m[d(1004)+d(535)](h.xyMSp,()=>i()),w.then(v=>{let _=d;u&&v["addEvent"+_(535)](h[_(966)],()=>u()),c&&v["addEvent"+_(535)](_(1452)+"hange",()=>c())})[d(213)](()=>{}),w}function Wx(n,{blocked:e}={}){let i=S,a={nzweB:"blocked",ZNIvR:function(u,d){return u(d)}},c=indexedDB[i(1302)+"tabase"](n);return e&&c[i(1004)+i(535)](a.nzweB,()=>e()),a[i(695)](Ae,c)[i(440)](()=>{})}function Xi(n,e){let i=S,a={UXuJK:i(1493),DQokT:function(m,w){return m===w},SutoH:"lowFf",jVBuY:i(1148),EgTQT:i(1564)+"e",QQmCO:function(m,w){return m instanceof w},aZSAy:function(m,w){return m in w},oKBph:i(629)};if(!(a[i(1277)](n,IDBDatabase)&&!a[i(1463)](e,n)&&typeof e===a[i(766)]))return;if(On[i(798)](e))return On[i(798)](e);let c=e[i(1116)](/FromIndex$/,""),u=e!==c,d=to[i(596)](c);if(!a[i(1463)](c,(u?IDBIndex:IDBObjectStore)[i(619)+"e"])||!(d||eo[i(596)](c)))return;let h=async function(m,...w){let v=i,_={byLex:v(1152),CVtga:a.UXuJK,YlFCY:v(1189)};if(a.DQokT(a[v(1387)],a.jVBuY))this._isBrowser&&_0x4c8496[v(1004)+"Listener"](_[v(1060)],this["_handleO"+v(1344)]),this[v(1206)+"er"]&&_0x52a44a["addEvent"+v(535)](v(1509),this._handleOffLine),this[v(1206)+"er"]&&_0x30d7ff["addEvent"+v(535)](_[v(1601)],this[v(1435)+"ageHide"]),this[v(1206)+"er"]&&_0x4d23a4[v(1004)+v(535)](_.YlFCY,this["_handleP"+v(564)]);else{let C=this[v(1499)+v(1223)](m,d?a[v(405)]:v(776)),T=C[v(888)];return u&&(T=T[v(1515)](w.shift())),(await Promise[v(957)]([T[c](...w),d&&C[v(1117)]]))[0]}};return On.set(e,h),h}var eo,to,On,Jx=Yi({"node_modules/idb/build/index.js"(){let n=S,e={qJYbJ:n(975)+n(624),TrDBA:function(c){return c()},bMQKT:n(356),tZnNW:"delete",vcjxN:n(519),HNvXA:n(798),rzENr:n(238),tAcHd:"getAllKeys",DoqhJ:n(1376),DpFVY:function(c,u){return c(u)}},i=e.qJYbJ[n(1555)]("|"),a=0;for(;;){switch(i[a++]){case"0":e[n(897)](Vi);continue;case"1":to=[n(468),e[n(861)],e[n(1364)],e[n(702)]];continue;case"2":eo=[e[n(1200)],n(311),e[n(878)],e[n(1067)],e[n(1129)]];continue;case"3":Vi();continue;case"4":e[n(1430)](Hx,c=>({...c,get:(u,d,h)=>Xi(u,d)||c.get(u,d,h),has:(u,d)=>!!Xi(u,d)||c[n(686)](u,d)}));continue;case"5":On=new Map;continue}break}}}),Vx={idb:function(n){let e=S,i={WeYYy:function(a,c){return a!==c},ecgXl:e(1341)};n[e(959)]=Promise[e(560)]().then(()=>(Jx(),Qi)).then(function(a){let c=e;if(i.WeYYy(i[c(1188)],i[c(1188)])){let u=this[c(513)][c(1507)](this[c(716)]),d=_0x44ed27[c(591)](u||"{}");return d[_0x353e05]=void 0,this._qosDB.setItem(this[c(716)],_0x5b3fdb.stringify(d))}else return a})}},$i={};function ke(n){let e=S,i={ixVtH:function(u,d){return u!==d}};var a=$i[n];if(i[e(199)](void 0,a))return a[e(959)];var c=$i[n]={exports:{}};return Vx[n](c,c[e(959)],ke),c[e(959)]}ke.d=(n,e)=>{let i=I;for(var a in e)ke.o(e,a)&&!ke.o(n,a)&&Object["definePr"+i(1215)](n,a,{enumerable:!0,get:e[a]})},(()=>{let n=S;ke.o=(e,i)=>Object[n(619)+"e"][n(1454)+n(1215)][n(556)](e,i)})(),(()=>{let n=S,e={ZJXBQ:function(i,a){return i!==a},zNWMW:"DMVGB",ZWjaA:n(393),JSPlG:function(i,a){return i!=a},PiATW:n(850)+"d",zvHjW:n(252)+"le"};ke.r=i=>{let a=n;e.ZJXBQ(e[a(898)],e[a(1338)])?(e[a(1084)](e[a(1160)],typeof Symbol)&&Symbol[a(352)+a(1297)]&&Object[a(1239)+a(1215)](i,Symbol[a(352)+a(1297)],{value:a(1548)}),Object[a(1239)+a(1215)](i,e.zvHjW,{value:!0})):(++_0x1b2ef8,_0xf9cab2+=4)}})();var X={};(()=>{let n=S,e={lVpLE:function(s,t){return s+t},dQVKL:function(s,t){return s+t},yDFsL:function(s,t){return s<t},auDhd:function(s,t){return s>t},HgcRo:function(s,t){return s(t)},RMuIU:function(s,t){return s+t},YlSKm:function(s,t){return s&t},blWyb:function(s,t){return s|t},vfVxP:function(s,t){return s||t},rNQWB:function(s,t){return s!==t},aOecW:n(634),CRrEX:function(s,t){return s*t},EbnyR:function(s,t,r){return s(t,r)},HglQa:function(s,t,r){return s(t,r)},CNqYL:function(s,t){return s(t)},RyZfP:function(s,t){return s(t)},OcmIh:n(569),ddgtX:function(s,t){return s===t},maOfH:function(s,t){return s===t},XNomz:function(s,t){return s+t},ZunAv:n(1530),xjksg:n(1155)+n(1155)+"00000000"+n(1155),PUwWa:n(1156),CUygt:function(s,t){return s<t},uctNV:function(s,t){return s>t},oiPDb:function(s,t){return s<t},ZPKHE:function(s,t){return s===t},ZMfCH:n(985),Llaar:"Xguan",OHIkw:function(s,t){return s-t},XpPFm:function(s,t){return s-t},kAGGA:function(s,t){return s-t},EPARj:function(s,t){return s<t},nMxKR:function(s,t){return s!==t},owbwb:function(s,t){return s!==t},qTMPj:function(s,t,r){return s(t,r)},UYwua:function(s,t,r){return s(t,r)},dITvR:function(s,t){return s(t)},aHwEd:function(s,t){return s(t)},FyRGV:function(s,t){return s>>>t},Hghxq:function(s,t,r){return s(t,r)},UanUv:function(s,t){return s(t)},HQnIN:function(s,t){return s===t},JAIpf:n(1145)+n(1184)+n(1480)+n(1580),gEfBI:function(s,t){return s===t},AvcJP:n(1145)+"required"+n(1480)+"value",OyJUu:function(s){return s()},GvvPV:function(s,t){return s(t)},XrkvW:function(s,t){return s!==t},uTmqf:function(s,t,r){return s(t,r)},LaNwn:function(s,t){return s(t)},LYkGk:function(s,t,r){return s(t,r)},ptzuf:function(s,t,r){return s(t,r)},UhDvS:function(s,t){return s(t)},pgobf:function(s,t){return s!==t},BGoho:function(s,t,r){return s(t,r)},lpxSv:function(s,t,r){return s(t,r)},gXmSw:function(s,t){return s!==t},drcea:function(s,t){return s!==t},Tlzdz:n(865),IYklX:function(s,t,r){return s(t,r)},PlYeo:function(s,t,r){return s(t,r)},kVGga:function(s,t){return s!==t},lHLgL:function(s,t,r){return s(t,r)},esCZA:function(s,t){return s!==t},TgwNP:function(s,t,r){return s(t,r)},RnoGx:function(s,t){return s!==t},VaVbk:function(s,t){return s(t)},jBIWG:function(s,t,r){return s(t,r)},NlBeE:function(s,t){return s(t)},tAEyL:function(s,t){return s(t)},ZoAMP:function(s,t){return s(t)},FxHqU:function(s,t){return s(t)},YgCVq:function(s,t,r){return s(t,r)},SFtpr:function(s,t){return s(t)},TOJAA:function(s,t,r){return s(t,r)},NHnUC:function(s,t){return s(t)},mpRtK:function(s,t){return s(t)},iEVsY:function(s,t){return s===t},Szgxf:n(1145)+n(1184)+" field: LogID",NVqMM:n(1145)+n(1184)+n(1480)+n(1488),OFSIj:"Missing "+n(1184)+" field: "+n(990),OsWTR:function(s,t){return s+t},IKdOO:function(s,t,r){return s(t,r)},ZhwUp:function(s,t){return s+t},cslom:function(s,t){return s>>t},GkXGU:function(s,t){return s>=t},bAibU:function(s,t){return s+t},lnVEf:function(s,t){return s>t},QAnFu:function(s,t){return s>t},AnisI:function(s,t){return s+t},HLRMJ:"Read pas"+n(520),SxIDW:function(s,t,r){return s(t,r)},hDvwZ:function(s,t,r){return s(t,r)},wsdhO:function(s,t){return s&t},ppLmO:function(s,t){return s>>t},PChRE:function(s,t,r){return s(t,r)},iWqAB:function(s,t){return s+t},sUeQN:function(s,t){return s===t},NEEaz:function(s,t){return s&t},Ehgjt:function(s,t){return s+t},zzDpB:function(s,t){return s+t},rtTzx:function(s,t){return s&t},EoWnl:function(s,t){return s===t},ScSCY:"UczqP",XyIIX:function(s,t){return s|t},sxiqP:function(s,t){return s<<t},rPRMj:function(s,t){return s&t},txltg:function(s,t){return s+t},AtIdA:function(s,t){return s!==t},CkTLA:function(s,t){return s<<t},omyuX:function(s,t){return s|t},qIwqs:function(s,t){return s<t},sbuaJ:function(s,t){return s<=t},MZLeD:function(s,t){return s(t)},BeTZg:function(s,t){return s>=t},wrhGf:function(s,t){return s+t},pkLgp:function(s,t){return s+t},agftB:function(s,t){return s|t},XPKHl:function(s,t){return s|t},lJHDL:function(s,t){return s<<t},blwkD:function(s,t){return s>>t},KShzF:function(s,t){return s&t},RyiWU:function(s,t){return s-t},DTjav:function(s,t){return s+t},QyLUl:function(s,t){return s<t},HILnk:function(s,t){return s<t},sQcuC:function(s,t){return s<t},luZfZ:function(s,t){return s<=t},IkYWZ:function(s,t){return s+t},qFOSf:n(1322),CvgtZ:n(1226),djZjU:function(s,t){return s|t},lmadt:function(s,t){return s&t},dHjHG:function(s,t){return s>>t},byeHZ:function(s,t){return s|t},mPMIc:function(s,t){return s>>t},MWCPx:function(s,t){return s|t},AwcRX:function(s,t){return s>>t},BCclp:function(s,t){return s|t},GdhvY:function(s,t){return s&t},PYkrc:function(s,t,r){return s(t,r)},TZJLL:function(s,t){return s<t},esBEU:function(s,t,r){return s(t,r)},NGXCQ:function(s,t){return s<<t},Cqkzb:function(s,t){return s&t},wABSh:function(s,t){return s>=t},TCkxc:n(1123),TjmDi:function(s,t,r){return s(t,r)},RVTAF:function(s,t,r){return s(t,r)},wiQtQ:function(s,t){return s(t)},tnUlA:function(s,t){return s&t},NugxG:function(s,t){return s(t)},GfdIS:function(s,t){return s<<t},qdcxQ:function(s,t){return s(t)},btqrb:function(s,t){return s<<t},UejTk:function(s,t){return s&t},npbJG:function(s,t){return s<<t},ZTNvl:function(s,t){return s&t},uGxZr:function(s,t){return s(t)},mqPcN:function(s,t){return s(t)},gtNKy:function(s,t){return s<<t},pxfXV:function(s,t){return s<<t},yndKp:function(s,t){return s&t},SQEMO:function(s,t){return s&t},rEjMT:function(s,t){return s&t},uSexe:function(s,t){return s(t)},TPBJx:function(s,t){return s>>>t},QMCsm:"waTcU",LnIhA:function(s,t){return s|t},cbvFg:function(s,t){return s>>>t},rFWlp:function(s,t){return s===t},gmQTG:function(s,t){return s<t},WWIOm:function(s,t){return s<t},mjTwL:function(s,t){return s+t},eQufw:function(s,t){return s>>>t},NYmOF:function(s,t){return s>>>t},AGpDL:function(s,t){return s+t},KvRwv:function(s,t){return s!==t},ukaMM:function(s,t){return s>>>t},tqZbz:function(s,t){return s>>>t},nGwsx:function(s,t){return s|t},aktbc:function(s,t){return s>>>t},Qwapp:function(s,t){return s>>>t},dwQle:function(s,t){return s!==t},AmHeR:function(s,t){return s+t},TFBlI:function(s,t){return s|t},VRBFb:function(s,t){return s&t},fVqyl:function(s,t){return s>>>t},zlNtS:function(s,t){return s!==t},RUfkv:function(s,t){return s>>>t},WeAvE:function(s,t){return s>>>t},DRsel:function(s,t){return s!==t},JoYxi:function(s,t){return s|t},RQuPz:function(s,t){return s>>>t},QmAFq:function(s,t){return s!==t},xnLjq:function(s,t){return s(t)},TeHTA:function(s,t){return s(t)},wPFXG:function(s,t){return s|t},oAIdZ:function(s,t){return s|t},RpqLm:function(s,t){return s|t},lHobN:function(s,t){return s<<t},ieOmD:function(s,t){return s|t},Ryyqw:function(s,t){return s|t},dNEvk:function(s,t){return s|t},DVwDp:function(s,t){return s<<t},XnNmt:function(s,t){return s<<t},papBG:function(s,t){return s|t},YdOFC:function(s,t){return s<<t},pZHYG:function(s,t){return s|t},tGmwa:function(s,t){return s|t},GGaax:function(s,t){return s<<t},niPQN:function(s,t,r){return s(t,r)},TaYdQ:function(s,t){return s===t},BngVu:n(245),JHpSj:function(s,t){return s&t},RufBX:function(s,t){return s&t},LZtav:function(s,t){return s&t},WsjUW:function(s,t){return s&t},YgRDL:function(s,t){return s|t},LwQSa:function(s,t){return s%t},iFvoe:function(s,t){return s/t},ViyHh:function(s,t){return s*t},JYsHN:function(s,t){return s>>>t},sUAdg:n(1308),zsEaX:function(s,t){return s&t},ghsRk:function(s,t){return s>>>t},gzOKQ:function(s,t){return s>>>t},AmNHA:function(s,t){return s===t},edttk:function(s,t){return s===t},zjRUZ:function(s,t){return s===t},rDBAN:function(s,t){return s+t},eeORy:n(933),XMDiT:function(s,t){return s&t},ybXVg:function(s,t){return s>>>t},BvHBG:function(s,t){return s>>>t},JmrMX:function(s,t){return s&t},TLDsZ:function(s,t){return s>>>t},umBkH:function(s,t){return s>>>t},RDjSa:function(s,t){return s&t},DrVqL:function(s,t){return s&t},CCBeo:n(603)+n(1310),yRkqy:n(585)+"IES_ERROR",ZilxB:n(1029)+n(618),Fuihp:n(672)+"OR",gPOCD:n(937)+n(532),oyjsv:n(539)+n(949),STSAG:n(1195),fBuUv:"ujATB",FXzfc:n(1600),HbGGH:n(1264)+"3",QIoXK:function(s,t){return s!=t},IHlIH:n(850)+"d",ALnJf:n(1579),CElLK:function(s,t){return s>=t},bHlDE:function(s,t){return s===t},nFwDz:function(s,t){return s==t},vmVlS:function(s,t){return s>t},xRIzu:n(786),dEvME:"error",whyJM:function(s,t){return s instanceof t},XCSXY:function(s,t){return s===t},wQeMn:function(s,t){return s===t},UGivS:function(s,t,r){return s(t,r)},YsOWV:n(492),mkYHe:function(s,t,r){return s(t,r)},UHzlj:n(1015),NOHBw:n(584),ZgVBQ:function(s,t){return s&t},kOzHb:function(s,t){return s>=t},mzOBV:function(s,t){return s&t},taDqx:function(s,t){return s|t},BKMLl:function(s,t){return s<<t},RlLVg:function(s,t){return s&t},TlpNJ:"vJLrP",REpne:function(s,t){return s||t},YzgKF:function(s,t){return s!=t},RHAhk:"KIdOs",VEvhK:n(447)+"1",UDsZJ:function(s,t){return s||t},LBfzH:function(s,t){return s===t},ksBAV:n(1602),yolAz:n(873),YmmwQ:function(s,t){return s||t},DJcKR:function(s,t){return s===t},cUsdB:function(s,t){return s&t},HubWa:function(s,t){return s+t},aJhWj:n(1477),sQgIJ:function(s,t){return s<t},VNShL:function(s,t){return s<=t},PnhLY:function(s,t){return s<t},wRAXV:function(s,t){return s|t},pvQHN:function(s,t){return s&t},RXNOP:function(s,t){return s>=t},LAfqc:function(s,t){return s<<t},gLYUg:function(s,t){return s&t},yaRgW:function(s,t){return s>=t},dUbBE:function(s,t){return s-t},DBdoQ:function(s,t){return s<<t},GYnWj:function(s,t){return s<<t},RORsU:function(s,t){return s&t},chlfs:function(s,t){return s+t},DeLeq:function(s,t){return s>>t},DWerQ:function(s,t){return s|t},LyWjG:function(s,t){return s===t},cdLif:n(1604)+n(1310),ziPEH:function(s,t){return s+t},ysaUX:function(s,t){return s&t},hatSr:function(s,t){return s|t},anoAd:function(s,t){return s&t},TzTGh:function(s,t){return s>>t},IVOwI:function(s,t){return s|t},VZzHP:function(s,t){return s&t},cZJJe:function(s,t){return s|t},mcfXs:function(s,t){return s>>t},qVcAR:function(s,t){return s|t},tgdeb:function(s,t){return s&t},bHuRS:function(s,t){return s<t},iYcXv:function(s,t){return s===t},sCxgA:"mXNqs",DgAMX:function(s,t){return s===t},RDHyY:function(s,t){return s===t},acDPI:function(s,t){return s&t},gPyxj:function(s,t){return s+t},eavML:function(s,t){return s|t},obooU:function(s,t){return s|t},zdfhI:function(s,t){return s+t},ttBSV:function(s,t){return s+t},zLIVm:function(s,t){return s&t},ovxNj:function(s,t){return s|t},rSGdg:function(s,t){return s&t},aRlcS:function(s,t){return s-t},IOHNT:"string",moWfk:function(s,t,r,o){return s(t,r,o)},qMJfp:function(s,t){return s instanceof t},kcOoV:function(s,t){return s instanceof t},SlSEU:function(s,t){return s!=t},stFCT:n(1396)+n(1543),uaODF:function(s,t){return s==t},FLwzj:"text/pla"+n(1405)+n(576),ndZXW:n(613),uJcZG:"ppe",JiEQw:function(s,t){return s|t},CFTeL:function(s,t){return s&t},PNamw:function(s,t){return s<<t},QjJDQ:function(s,t){return s<<t},rxgxh:function(s,t){return s<t},dOXio:function(s,t,r){return s(t,r)},BEDmD:function(s,t){return s>>t},KlBVl:function(s,t){return s===t},NZAZH:n(586),iGJWZ:function(s,t){return s===t},qUwNP:n(215),wmzkD:n(436),MZQgs:n(920)+n(1138),glnxl:n(1492),UlJpi:n(452)+n(1428)+"tierJSONP",VvTGn:n(827),DqWsX:"AbortError",DjtJP:n(1514),oSJTH:function(s,t){return s!==t},QxmgW:n(1607),akGHu:n(607),zUNTo:n(362),Nvykj:function(s){return s()},lIcPF:function(s,t){return s(t)},deWoL:n(1323),PVAzK:function(s,t){return s(t)},JbIVS:n(237),CgxhO:n(599),gbbgs:n(841),JVEeF:n(1182),jqxnN:function(s,t){return s>=t},DNPbr:n(489),eNrsb:n(630),uTKet:function(s,t){return s||t},AlOuQ:function(s,t){return s||t},ejpVv:n(1213),jvSQp:"RUAbK",UtOlA:function(s,t){return s||t},wDcPy:n(1419),krDLG:function(s,t){return s<t},tKsah:function(s,t){return s-t},blqzh:function(s,t){return s&t},tzyZz:function(s,t){return s&t},RyNAw:function(s,t){return s|t},Oteuf:function(s,t){return s&t},eKdWb:function(s,t){return s|t},Pkrab:function(s,t){return s&t},IsOYz:function(s,t){return s<<t},RzflB:function(s,t){return s!==t},aotpM:n(793),Gaqrw:n(1111),YZdUl:n(1380),mqxHw:n(719),YOqLg:function(s,t){return s||t},NmsIR:function(s,t){return s||t},MCpDF:function(s,t){return s!=t},CgozN:n(1535),qiITr:function(s,t){return s(t)},gxiLI:"going aw"+n(1534)+n(1092)+n(1343)+n(589),vGifz:function(s,t){return s===t},GpifU:function(s,t,r,o){return s(t,r,o)},GRoxF:"x_fronti"+n(939),JtEsZ:n(1334)+n(1441)+"ck",JZmUt:function(s,t,r,o){return s(t,r,o)},NprHD:function(s,t,r){return s(t,r)},XumPf:n(1334)+n(258)+"sgid",hOuoo:function(s,t){return s&&t},LamJo:"is_ack",oZdFi:n(953),yNzfd:function(s,t){return s||t},rHciZ:n(314),GzlGW:n(799)+n(1571),peIqm:n(1080),uwqge:n(1396)+n(1543)+";charset"+n(250),lRNbq:"none_none",wrWUo:function(s,t){return s+t},OxupI:function(s,t){return s|t},Eejoy:function(s,t){return s(t)},HzpJM:function(s,t){return s+t},FMuya:function(s,t){return s+t},LlMfM:function(s,t){return s+t},Hfqpi:"index ou"+n(1007)+n(1010),HDiBY:n(1077),alSJM:n(300)+n(635)+"e",DhodK:function(s,t){return s>=t},QHieJ:function(s,t){return s&t},xqqrF:n(1510),kUKiA:function(s,t,r){return s(t,r)},OLXdg:"1|0|4|2|3",JiGwV:function(s,t){return s+t},vTZOe:function(s,t){return s+t},MHdly:function(s,t,r,o){return s(t,r,o)},dUMcY:function(s,t){return s+t},wegCN:function(s,t){return s|t},nEhCw:function(s,t){return s<<t},nEumu:function(s,t){return s+t},oPyvK:function(s,t){return s<<t},ZxYdy:function(s,t){return s+t},rNOkC:function(s,t){return s|t},fmcWc:function(s,t){return s|t},dtncv:function(s,t){return s|t},cSzBG:function(s,t){return s<<t},TLjaI:function(s,t){return s+t},lgUjr:function(s,t){return s+t},dnScz:function(s,t){return s&t},xFGaT:function(s,t){return s>>>t},rlVgv:function(s,t){return s&t},RhEiE:function(s,t){return s+t},squea:"omfgn",yGsuC:function(s,t){return s>>>t},OpFnY:function(s,t){return s|t},BETLS:function(s,t){return s<<t},ImadJ:function(s,t,r,o){return s(t,r,o)},Nrifg:function(s,t){return s&t},BchnH:function(s,t){return s<t},pPvYI:function(s,t){return s|t},QhmCU:function(s,t){return s>>>t},tJYMK:function(s,t){return s(t)},IBAzv:n(1425)+n(1384),SPknP:n(1488),QpbCG:n(1384),gatre:function(s,t){return s(t)},jHjqp:function(s,t,r){return s(t,r)},ubVsi:function(s,t,r,o){return s(t,r,o)},uQXTX:"cursor_f"+n(652),raFYB:n(1140)+n(926),ZeCTN:n(709)+n(448),hbhim:n(260),vcaGo:n(811),jERKH:n(626),yyBWs:function(s){return s()},kyXLm:n(354),yNdUK:"setcursor",QLnzO:function(s,t){return s>t},xOsbt:n(1603),ibWJn:function(s,t){return s===t},OzUyx:n(928),qhEGg:"JRDRX",zmZkK:function(s,t){return s>>>t},hjQsn:function(s,t){return s*t},lwNHv:function(s,t){return s>>>t},FEEXU:function(s,t){return s||t},jSSii:function(s,t){return s===t},KBfBU:n(1339),tZVLH:"skZur",GMkNH:n(1334)+n(883),NFnYx:"x_fronti"+n(295),pQrFU:function(s,t,r,o){return s(t,r,o)},tWrVq:function(s,t,r){return s(t,r)},NCmHi:n(293)+n(253)+"e",NuzYS:n(293)+n(1371)+"ue",DKIzk:function(s,t){return s>t},bMWJl:function(s,t){return s+t},QisKC:function(s,t){return s<t},ErETw:function(s){return s()},xWpLE:function(s){return s()},sVUDY:function(s,t){return s&&t},iXERT:function(s){return s()},VDnTW:function(s,t){return s===t},jUUQn:n(377),FFBnr:function(s,t){return s!==t},JRhQD:function(s){return s()},uAHtw:function(s,t){return s===t},FPAaO:function(s,t){return s!==t},ObcqR:function(s,t){return s!==t},JCxEw:n(839),GaVRM:function(s,t){return s===t},NCyCA:n(1017),WXlkd:n(342),tkrHz:"success",MHDUU:function(s,t,r){return s(t,r)},tWncP:function(s,t,r,o){return s(t,r,o)},vtiHW:function(s,t){return s===t},sCTuF:"manual r"+n(1001)+n(305),GacqC:n(1088),WZqRd:n(1051),jhngN:function(s,t){return s*t},YNVhk:n(1257)+n(275),fiizA:function(s,t){return s==t},bgITd:n(257)+"rovide v"+n(1263),hEiNh:function(s,t){return s(t)},WovIi:n(257)+"rovide w"+n(638)+n(414)+n(738)+n(1273)+n(764)+n(732),YUpIe:n(1118),daXxc:function(s,t){return s!==t},tmoAB:n(303),fHdTX:function(s,t,r){return s(t,r)},btiCP:"reconnect",briCO:n(908)+n(434)+n(281)+"ct",rVilY:n(1152),hplJq:n(1509),sylWE:n(1493),ZIMUR:n(1189),GxPEb:n(610),yoXcr:function(s,t){return s!==t},PYcEU:n(810),HdRBV:n(1418),eaLpp:n(1114),ysZdj:n(1390),gHDLA:n(1327),INNKY:"device_id",ckhfI:function(s,t){return s||t},UCNfm:n(257)+n(1554)+n(734)+n(497)+n(1225),pGYSt:n(1525),eocAj:"web",sHMuO:function(s,t){return s!==t},tpQjZ:n(1504),NCBUl:n(657),ZoFZt:n(396),owpqg:function(s,t){return s>t},mQHfw:function(s,t,r){return s(t,r)},VBsay:function(s,t){return s(t)},QlyvF:n(752)+">",fOzam:n(744)+n(994)+"t",ymhzZ:"timeout",dhnal:function(s,t){return s|t},tQaSE:function(s,t){return s!==t},hynMe:n(1218),HJQkY:n(1560)+n(554)+n(324)+"g",kBjGW:function(s,t){return s===t},TsEMA:n(684),kRMGF:n(1354),UTHTd:n(598),DmIGa:"going away, netw"+n(225)+n(1439),MCiVh:"cjsfm",fuJDl:n(1391),mugnf:"6|1|7|3|4|5|2|0",FWJev:n(689)+"s instan"+n(1438)+n(441)+"ed",cUEHy:function(s,t){return s+t},ulNzF:n(257)+n(1540)+n(894)+n(694)+"a must b"+n(768)+"ng or an"+n(1041)+"ffer",gxCXe:"number",LfCmF:function(s,t){return s!=t},ykKcZ:function(s,t){return s instanceof t},zSPpd:function(s,t){return s(t)},VzivR:function(s,t){return s(t)},lZeUQ:function(s,t){return s(t)},yeeOb:function(s,t){return s||t},dcBlT:function(s,t){return s instanceof t},guGJA:function(s,t){return s instanceof t},WnEFw:function(s,t){return s(t)},xjFnA:n(921),UqkoL:function(s,t){return s!==t},ADQWs:n(1112),jdDOe:"rwLHN",Hgoew:function(s,t){return s==t},tfhQN:function(s,t){return s!==t},ukyxP:n(311),eNeyk:n(238),IdHMb:n(1313)+"ys",yDovM:n(1376),YMNWy:n(468),dDvTx:function(s,t){return s(t)},XGCHN:n(739),fkIje:"lqtJc",wIesS:function(s,t){return s===t},uIEkz:n(1248),AxWOG:function(s,t){return s(t)},fqnAD:n(611),Ailvm:function(s,t){return s*t},umZjo:function(s,t){return s/t},lvalG:function(s,t){return s!=t},hkMyj:function(s,t){return s===t},kAmAk:n(359),vSNmZ:function(s,t){return s!=t},XCerX:function(s,t){return s===t},HwSPK:n(424),fcvzO:n(1378)+"dWorkerG"+n(320)+"pe",fDHCo:function(s,t){return s!=t},EDTMy:"SharedWo"+n(1332)+n(1142),xASzQ:n(291)+n(1614)+n(1496),ZhzHk:function(s,t){return s!=t},UNDof:function(s,t){return s!=t},bUvgf:function(s,t){return s===t},aVaJj:n(1326)+"qos__"};ke.r(X),ke.d(X,{FWS:()=>b0,CustomErrorEvent:()=>Es,createCloseEvent:()=>me,ReconnectEvent:()=>Ss,createErrorEvent:()=>le,decodedFrame:()=>ws,createOpenEvent:()=>Ts,CustomCloseEvent:()=>Cs,createReconnectEvent:()=>dr,FrontierMessageEvent:()=>As,encodeFrame:()=>ur,createMessageEvent:()=>Is,OpenEvent:()=>Ps,ErrorCode:()=>Fe,Event:()=>ot,MessageEvent:()=>ks});let i="";function a(s=""){let t=n,r="02",o=""+Date[t(306)](),x=i||(i=m(s)),f=Math[t(1283)]()[t(352)](16).slice(-6);return e.lVpLE(e[t(483)](r,o)+x,f)}function c(){let s=n;if(e[s(1311)](e[s(989)],s(316)))return 1e4*Date.now()+Math.floor(e.CRrEX(1e4,Math.random()));{let t={hJHEL:function(g,p){return e.yDFsL(g,p)},fRNJP:function(g,p){return e[s(1275)](g,p)},xoHnu:function(g,p){return e[s(922)](g,p)},psxjq:function(g,p){return e[s(1275)](g,p)},vAUkB:function(g,p){return e.RMuIU(g,p)},XLQpT:function(g,p){return e[s(628)](g,p)},OgjKu:function(g,p){return g+p},qPSOF:function(g,p){return e[s(913)](g,p)}},r=e[s(230)](_0x4ad9e6,8192),o=r>>>1,x=null,f=r;return function(g){let p=s;if(t[p(675)](g,1)||t[p(241)](g,o))return t[p(220)](_0x22bbd6,g);t[p(1061)](t[p(997)](f,g),r)&&(x=_0x3a89ff(r),f=0);let l=_0xbce59e[p(556)](x,f,f+=g);return t[p(1381)](7,f)&&(f=t[p(418)](t[p(384)](7,f),1)),l}}}function u(s){let t=n;return e[t(1506)](Array(8)[t(852)]("0"),e[t(200)](parseInt,s,10)[t(352)](2)).slice(-8)}function d(s){let t=n;return e[t(1517)](e.HgcRo(Array,4)[t(852)]("0"),e[t(706)](parseInt,s,2)[t(352)](16)).slice(-4)}function h(s){let t=n,r=s[t(1555)](/\./)[t(534)](f=>u(f)),o=[];return o[0]=e[t(1417)](d,r[0]+r[1]),o[1]=e[t(1249)](d,r[2]+r[3]),["0000",e.OcmIh,e[t(1532)],t(569),e.OcmIh,"ffff",o[0],o[1]][t(852)]("")}function m(s){let t=n;if(e.ZunAv===t(1266))return this.low===-1&&e.ddgtX(-1,this[t(1335)])?_0x4f3242[t(580)](0,0,this[t(1157)]):e[t(1568)](-1,this[t(263)])?_0x105d0e[t(580)](0,e.XNomz(this[t(1335)],1),this[t(1157)]):_0x515915[t(580)](e[t(1517)](this[t(263)],1),this.high,this[t(1157)]);{let r=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[t(881)](s),o=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[t(881)](s);return r?h(s):o?w(s):e.xjksg}}function w(s){let t=n;if(e[t(1311)](e.PUwWa,e[t(490)]))_0x55566d.d=(r,o)=>{let x=t;for(var f in o)_0x365f40.o(o,f)&&!_0x39111d.o(r,f)&&_0x414a62[x(1239)+x(1215)](r,f,{enumerable:!0,get:o[f]})};else{let r="",o=[],x=0,f=0,g=!0,p=e[t(1532)];if(e[t(1275)](s[t(755)]("::"),-1)){let l=s[t(1555)]("::");for(let b=0;e[t(1133)](b,l.length);b++){let k=l[b];if(e[t(1450)](k[t(755)](":"),0)){let P=k.split(":");g&&(x=P[t(475)]),f+=P[t(475)];for(let O=0;e.oiPDb(O,P[t(475)]);O++)if(e[t(1311)](4,P[O].length))if(e[t(247)](e.ZMfCH,e.Llaar)){let N=_0x44bc1c(_0x1534dc),ee=_0x113bd9.limit;return _0x508d91.limit=e.RMuIU(_0x4db8b4.offset,N),ee}else{let N=p.substring(0,e[t(1113)](4,P[O].length)),ee=N[t(605)](P[O]);o[t(299)](ee)}else o[t(299)](P[O]);g=!1}else{if(e[t(1311)](4,k[t(475)])){let P=p.substring(0,e[t(446)](4,k.length)),O=P[t(605)](k);o[t(299)](O)}else o[t(299)](k);g&&(x+=1),f+=1,g=!1}}let y="";for(let b=0;e.yDFsL(b,e.kAGGA(8,f));b++)y=y[t(605)](p);for(let b=0;e[t(1027)](b,o.length);b++)e[t(247)](b,x)&&(r=r[t(605)](y)),r=r[t(605)](o[b]);return r}{let l=s[t(1555)](":");for(let y=0;y<l.length;y++){let b=l[y];if(e[t(1584)](4,l[y][t(475)])){let k=p[t(1190)+"g"](0,e[t(407)](4,l[y][t(475)])),P=k[t(605)](b);r=r[t(605)](P)}else r=r[t(605)](b)}return r}}}function v(s,t){let r=n,o=s.key;e[r(575)](void 0,o)&&(e[r(200)](J,t,10),e[r(938)](ve,t,o));let x=s[r(522)];x!==void 0&&(e[r(400)](J,t,18),e[r(938)](ve,t,x))}function _(s){let t=n,r={};e:for(;!e[t(986)](Ie,s);){let o=e[t(449)](M,s);switch(e[t(882)](o,3)){case 0:break e;case 1:r[t(1580)]=e.Hghxq(ye,s,M(s));break;case 2:r.value=ye(s,e[t(1448)](M,s));break;default:e[t(1178)]($,s,7&o)}}if(e[t(1399)](void 0,r.key))throw new Error(e[t(272)]);if(e[t(1240)](void 0,r.value))throw new Error(e[t(968)]);return r}function C(s){let t=n,r=e.OyJUu(Y);return e[t(706)](T,s,r),e[t(1238)](K,r)}function T(s,t){let r=n,o=s.SeqID;e[r(700)](void 0,o)&&(J(t,8),e.UYwua(At,t,o));let x=s[r(880)];e[r(700)](void 0,x)&&(e[r(400)](J,t,16),e[r(404)](At,t,x));let f=s[r(1488)];f!==void 0&&(e.uTmqf(J,t,24),e[r(200)](At,t,e[r(1039)](re,f)));let g=s[r(990)];e[r(700)](void 0,g)&&(e[r(925)](J,t,32),e[r(274)](At,t,e.UhDvS(re,g)));let p=s[r(733)];if(e.pgobf(void 0,p))for(let ee of p){e[r(706)](J,t,42);let ce=Y();e.BGoho(v,ee,ce),J(t,ce[r(442)]),e[r(404)](Qt,t,ce),A(ce)}let l=s[r(674)+r(1373)];l!==void 0&&(e[r(404)](J,t,50),ve(t,l));let y=s[r(551)+"ype"];y!==void 0&&(e[r(400)](J,t,58),e.lpxSv(ve,t,y));let b=s.payload;if(e[r(1098)](void 0,b))if(e[r(870)](e[r(1546)],e.Tlzdz)){let ee=this[r(513)][r(1609)+"geInfoSync"](this[r(716)]),ce=_0x1e8eab[r(591)](ee||"{}");return _0x3f91ef[r(820)](ce)}else e[r(323)](J,t,66),J(t,b[r(475)]),e[r(274)](Zt,t,b);let k=s.LogIDNew;e.XrkvW(void 0,k)&&(e.PlYeo(J,t,74),e[r(706)](ve,t,k));let P=s["serverTi"+r(667)];e.kVGga(void 0,P)&&(e.lHLgL(J,t,82),ve(t,P));let O=s[r(1345)];e[r(757)](void 0,O)&&(e.TgwNP(J,t,90),e[r(323)](ve,t,O));let N=s[r(809)+"e"];e[r(502)](void 0,N)&&(J(t,96),At(t,e.VaVbk(re,N)))}function D(s){return L(U(s))}function L(s){let t=n,r={};e:for(;!e[t(1417)](Ie,s);){let o=M(s);switch(o>>>3){case 0:break e;case 1:r[t(1103)]=Te(s,!0);break;case 2:r[t(880)]=e.jBIWG(Te,s,!0);break;case 3:r[t(1488)]=e[t(1333)](M,s);break;case 4:r[t(990)]=M(s);break;case 5:{let x=F(s);(r[t(733)]||(r[t(733)]=[]))[t(299)](e[t(1170)](_,s)),s[t(442)]=x;break}case 6:r["payloadE"+t(1373)]=e[t(779)](ye,s,e[t(1557)](M,s));break;case 7:r.payloadType=ye(s,e.FxHqU(M,s));break;case 8:r[t(849)]=e[t(379)](kt,s,e[t(1069)](M,s));break;case 9:r[t(743)]=ye(s,M(s));break;case 10:r["serverTi"+t(667)]=e[t(1581)](ye,s,e[t(1110)](M,s));break;case 11:r[t(1345)]=ye(s,e[t(1170)](M,s));break;case 12:r[t(809)+"e"]=e[t(844)](M,s);break;default:$(s,e[t(628)](7,o))}}if(e[t(952)](void 0,r[t(1103)]))throw new Error(t(1145)+"required"+t(1480)+t(1103));if(e[t(1551)](void 0,r.LogID))throw new Error(e.Szgxf);if(e[t(247)](void 0,r[t(1488)]))throw new Error(e[t(511)]);if(e[t(1240)](void 0,r[t(990)]))throw new Error(e.OFSIj);return r}function F(s){let t=n,r=e[t(1170)](M,s),o=s[t(442)];return s[t(442)]=e[t(724)](s[t(973)],r),o}function $(s,t){let r=n;switch(t){case 0:for(;e[r(628)](128,e.aHwEd(ae,s)););break;case 2:se(s,e[r(1039)](M,s));break;case 5:e[r(907)](se,s,4);break;case 1:se(s,8);break;default:throw new Error(e[r(1537)](r(859)+r(1143)+r(463),t))}}function re(s){let t=n;return s|=0,{low:s,high:e.cslom(s,31),unsigned:e[t(279)](s,0)}}let Q=[];function Y(){let s=n,t=Q[s(1520)]();return t?(t[s(973)]=t[s(442)]=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function A(s){Q[n(299)](s)}function U(s){return{bytes:s,offset:0,limit:s.length}}function K(s){let t=n,r=s[t(458)],o=s[t(442)];return e[t(1399)](r[t(475)],o)?r:r.subarray(0,o)}function se(s,t){let r=n;if(e.auDhd(s[r(973)]+t,s[r(442)]))throw new Error(r(1470)+r(520));s[r(973)]+=t}function Ie(s){let t=n;return e[t(279)](s[t(973)],s[t(442)])}function pe(s,t){let r=n,o=s[r(458)],x=s[r(973)],f=s[r(442)],g=e[r(1547)](x,t);if(e[r(1479)](g,o[r(475)])){let p=new Uint8Array(e[r(363)](2,g));p[r(749)](o),s[r(458)]=p}return s[r(973)]=g,g>f&&(s[r(442)]=g),x}function Xe(s,t){let r=n,o=s.offset;if(e.QAnFu(e[r(481)](o,t),s[r(442)]))throw new Error(e[r(1374)]);return s[r(973)]+=t,o}function kt(s,t){let r=n,o=e[r(826)](Xe,s,t);return s[r(458)][r(549)](o,e[r(483)](o,t))}function Zt(s,t){let r=n,o=e.hDvwZ(pe,s,t[r(475)]);s[r(458)][r(749)](t,o)}function ye(s,t){let r=n,o={NTUlt:function(y,b){return y<b},yeigf:function(y,b){return y|b},GugQw:function(y,b){return y|b},XuciQ:function(y,b){return e[I(628)](y,b)},WaIga:function(y,b){return e[I(1500)](y,b)},hmTWm:function(y,b){return y&b},sZtAD:function(y,b){return e[I(633)](y,b)},UYMqs:function(y,b){return e[I(1198)](y,b)},lGGlJ:function(y,b){return e.blWyb(y,b)}},x=e[r(228)](Xe,s,t),f=String[r(398)+r(573)],g=s.bytes,p="\uFFFD",l="";for(let y=0;e[r(1027)](y,t);y++){let b=g[e.iWqAB(y,x)],k,P,O,N;e[r(633)](128,b)===0?l+=e[r(1417)](f,b):e[r(1120)](e[r(866)](224,b),192)?e.Ehgjt(y,1)>=t?l+=p:(k=g[e[r(1547)](e.zzDpB(y,x),1)],e.rtTzx(192,k)!==128?l+=p:e[r(854)](e[r(847)],e.ScSCY)?(N=e[r(1192)](e[r(1220)](e[r(1556)](31,b),6),63&k),e[r(1133)](N,128)?l+=p:(l+=e[r(844)](f,N),y++)):(o[r(1606)](_0x21ea35,2048)?_0x49b8bc[_0x294a49++]=o[r(784)](_0x7bdd3c>>6&31,192):(o.NTUlt(_0x31e665,65536)?_0x20692d[_0x4d28ee++]=o.GugQw(o.XuciQ(o.WaIga(_0x280def,12),15),224):(_0x329134[_0x253f94++]=o.GugQw(o[r(264)](o[r(385)](_0xda0b20,18),7),240),_0x4941e1[_0x44fea2++]=o[r(784)](o.sZtAD(o[r(385)](_0x10015f,12),63),128)),_0x3d78b6[_0x182b1e++]=o.GugQw(o[r(1035)](_0xfc1f19,6)&63,128)),_0x2c0b9c[_0xadcff4++]=o[r(1021)](o[r(1274)](63,_0x36325a),128))):e[r(297)](240,b)==224?e[r(249)](y,2)>=t?l+=p:(k=g[e[r(1506)](e.XNomz(y,x),1)],P=g[e[r(1517)](e[r(1091)](y,x),2)],e[r(516)](e[r(628)](e[r(1192)](k,e[r(406)](P,8)),49344),32896)?l+=p:(N=e[r(1192)](e[r(1083)](e.NEEaz(15,b)<<12,e[r(406)](e[r(633)](63,k),6)),e[r(633)](63,P)),e.qIwqs(N,2048)||e[r(279)](N,55296)&&e[r(704)](N,57343)?l+=p:(l+=e.MZLeD(f,N),y+=2))):e.wsdhO(248,b)==240?e[r(775)](e[r(1121)](y,3),t)?l+=p:(k=g[e.AnisI(y,x)+1],P=g[e.txltg(y+x,2)],O=g[e[r(858)](y+x,3)],e[r(502)](e[r(1083)](e[r(1192)](k,P<<8),e[r(1220)](O,16))&12632256,8421504)?l+=p:(N=e[r(294)](e[r(913)](e[r(325)](e.CkTLA(7&b,18),e[r(406)](e[r(1556)](63,k),12)),e[r(578)](63&P,6)),e[r(1556)](63,O)),N<65536||N>1114111?l+=p:(N-=65536,l+=f(e.blwkD(N,10)+55296,e[r(858)](e[r(1444)](1023,N),56320)),y+=3))):l+=p}return l}function ve(s,t){let r=n,o=t.length,x=0;for(let p=0;e.EPARj(p,o);p++){let l=t[r(741)+"At"](p);e[r(775)](l,55296)&&l<=56319&&e[r(327)](e.AnisI(p,1),o)&&(l=e[r(612)](e[r(570)](l<<10,t.charCodeAt(++p)),56613888)),x+=e[r(1149)](l,128)?1:e.HILnk(l,2048)?2:e.qIwqs(l,65536)?3:4}e[r(938)](J,s,x);let f=e.LYkGk(pe,s,x),g=s[r(458)];for(let p=0;e[r(1449)](p,o);p++){let l=t[r(741)+"At"](p);e.GkXGU(l,55296)&&e[r(884)](l,56319)&&e[r(1037)](p,1)<o&&(l=e.AnisI(l<<10,t[r(741)+"At"](++p))-56613888),e.sQcuC(l,128)?g[f++]=l:e.esCZA(e.qFOSf,e[r(1095)])?(e.sQcuC(l,2048)?g[f++]=e[r(1563)](e[r(1368)](e[r(500)](l,6),31),192):(e[r(1149)](l,65536)?g[f++]=e[r(1529)](e[r(1500)](l,12)&15,224):(g[f++]=e[r(1192)](e[r(628)](e[r(425)](l,18),7),240),g[f++]=e[r(950)](e.KShzF(e[r(1198)](l,12),63),128)),g[f++]=e[r(1368)](e[r(313)](l,6),63)|128),g[f++]=e.BCclp(e[r(1505)](63,l),128)):this[r(683)+"T"]?_0x2aa014[r(420)+r(1347)+r(1034)](({isConnected:y})=>{let b=r;this["_miniNavigatorOn"+b(254)]=y,y?this[b(256)+b(1344)]():this._handleOffLine()}):this[r(209)+"X"]&&_0x2ff42d[r(420)+r(1347)+"hange"](({isConnected:y})=>{let b=r;this[b(653)+b(1232)+b(254)]=y,y?this[b(256)+b(1344)]():this[b(256)+"ffLine"]()})}}function Qt(s,t){let r=n,o=e[r(1300)](pe,s,t[r(442)]),x=s[r(458)],f=t[r(458)];for(let g=0,p=t[r(442)];e[r(843)](g,p);g++)x[e.IkYWZ(g,o)]=f[g]}function ae(s){return s[n(458)][Xe(s,1)]}function en(s,t){let r=e.esBEU(pe,s,1);s.bytes[r]=t}function M(s){let t=n,r=0,o=0,x;do x=ae(s),e[t(1149)](r,32)&&(o|=e[t(1197)](e[t(1398)](127,x),r)),r+=7;while(128&x);return o}function J(s,t){let r=n;for(t>>>=0;e[r(1319)](t,128);)if(e[r(247)](r(1123),e[r(1135)]))e[r(197)](en,s,127&t|128),t>>>=7;else return this[r(1038)][r(1078)+"pe"];e.RVTAF(en,s,t)}function Te(s,t){let r=n,o=0,x=0,f=0,g;return g=e[r(1282)](ae,s),o=127&g,e.tnUlA(128,g)&&(g=e[r(1340)](ae,s),o|=e.GfdIS(e[r(936)](127,g),7),e[r(1556)](128,g)&&(g=e[r(588)](ae,s),o|=e.btqrb(e[r(1556)](127,g),14),e[r(1495)](128,g)&&(g=e.aHwEd(ae,s),o|=e[r(1598)](127&g,21),e[r(1059)](128,g)&&(g=e[r(203)](ae,s),x=127&g,128&g&&(g=e[r(423)](ae,s),x|=e[r(1541)](e.GdhvY(127,g),7),e[r(633)](128,g)&&(g=ae(s),x|=e[r(869)](e[r(1524)](127,g),14),e[r(643)](128,g)&&(g=e[r(875)](ae,s),x|=(127&g)<<21,e[r(1014)](128,g)&&(g=e[r(203)](ae,s),f=e[r(1444)](127,g),e.NEEaz(128,g)&&(g=e[r(579)](ae,s),f|=e.GfdIS(e[r(1524)](127,g),7)))))))))),{low:o|x<<28,high:e[r(294)](e.TPBJx(x,4),f<<24),unsigned:t}}function At(s,t){let r=n;if(e.QMCsm===e[r(496)]){let o=t.low>>>0,x=e.TPBJx(e[r(1104)](t[r(263)]>>>28,e[r(992)](t[r(1335)],4)),0),f=e.cbvFg(t[r(1335)],24),g=e[r(1046)](0,f)?x===0?e[r(843)](o,16384)?o<128?1:2:e[r(212)](o,2097152)?3:4:e[r(1407)](x,16384)?e[r(1449)](x,128)?5:6:e[r(201)](x,2097152)?7:8:e[r(1027)](f,128)?9:10,p=e.ptzuf(pe,s,g),l=s[r(458)];switch(g){case 10:l[e[r(774)](p,9)]=e.wsdhO(e[r(698)](f,7),1);case 9:l[e[r(774)](p,8)]=g!==9?128|f:127&f;case 8:l[e[r(858)](p,7)]=e.rNQWB(8,g)?e[r(1320)](x,21)|128:e[r(1014)](e[r(846)](x,21),127);case 7:l[e.AGpDL(p,6)]=e.KvRwv(7,g)?e[r(1192)](e.ukaMM(x,14),128):e[r(1524)](e.tqZbz(x,14),127);case 6:l[e[r(249)](p,5)]=e[r(516)](6,g)?e[r(794)](e[r(1082)](x,7),128):e[r(628)](e[r(746)](x,7),127);case 5:l[e[r(570)](p,4)]=e[r(1565)](5,g)?128|x:127&x;case 4:l[e[r(886)](p,3)]=g!==4?e.TFBlI(e[r(198)](o,21),128):e[r(740)](e[r(1219)](o,21),127);case 3:l[e.IkYWZ(p,2)]=e[r(1303)](3,g)?e.RUfkv(o,14)|128:e[r(1349)](o,14)&127;case 2:l[e[r(570)](p,1)]=e.DRsel(2,g)?e[r(270)](e[r(198)](o,7),128):e[r(936)](e.RQuPz(o,7),127);case 1:l[p]=e[r(308)](1,g)?128|o:e[r(1524)](127,o)}}else{if(e.pgobf(4,_0x19d0df[r(475)])){let o=_0x8e1e25.substring(0,e[r(1113)](4,_0x25741d.length)),x=o[r(605)](_0x429808);_0x2b66ba[r(299)](x)}else _0x150b84.push(_0x46a150);_0x327511&&(_0x56902e+=1),_0x40bc32+=1,_0x548f2c=!1}}function ws(s){return e[n(616)](D,s)}function ur(s){return e[n(712)](C,s)}let _s=65536,La=e[n(1132)],it=e[n(763)](_s,_s),ys=it*it,vs=e[n(530)](ys,2),qe=String.prototype[n(741)+"At"];class q{constructor(t,r,o){let x=n;this[x(1304)]=!0,this[x(263)]=e.wPFXG(0,t),this[x(1335)]=e[x(1192)](0,r),this[x(1157)]=!!o}static isLong(t){return t&&e[n(247)](!0,t.isLong)}static[n(580)](t,r,o){return new q(t,r,o)}static[n(349)+"s"](t,r,o){let x=n;return o?q[x(349)+x(510)](t,r):q["fromByte"+x(487)](t,r)}static[n(349)+"sLE"](t,r){let o=n;return new q(e[o(411)](e[o(372)](t[0]|e.btqrb(t[1],8),e[o(1598)](t[2],16)),e[o(214)](t[3],24)),e[o(722)](e[o(1365)](t[4],t[5]<<8),t[6]<<16)|e[o(1220)](t[7],24),r)}static[n(349)+n(487)](t,r){let o=n;return new q(e[o(1431)](e[o(325)](t[4]<<24,e[o(1173)](t[5],16)),e.XnNmt(t[6],8))|t[7],e[o(1032)](e[o(1220)](t[0],24)|e[o(790)](t[1],16),e[o(517)](t[2],8))|t[3],r)}static[n(642)](t){let r=n;return t===La?bs:new q(e[r(198)](e[r(372)](e.BCclp(e[r(1192)](qe.call(t,0),e.YdOFC(qe.call(t,1),8)),e[r(1197)](qe[r(556)](t,2),16)),qe[r(556)](t,3)<<24),0),e[r(301)](e[r(1615)](qe[r(556)](t,4),qe[r(556)](t,5)<<8)|qe[r(556)](t,6)<<16,e[r(1224)](qe[r(556)](t,7),24))>>>0,!0)}[n(1016)](){let t=n,r={uObgx:function(o,x,f){return e[I(345)](o,x,f)}};if(e[t(760)](e[t(1055)],t(245)))return String[t(398)+"Code"](e.JHpSj(255,this[t(263)]),e[t(1524)](e[t(882)](this.low,8),255),e.RufBX(e.ukaMM(this[t(263)],16),255),e[t(698)](this.low,24),e.LZtav(255,this.high),e[t(1524)](e.ukaMM(this[t(1335)],8),255),e[t(795)](e.RQuPz(this[t(1335)],16),255),this[t(1335)]>>>24);_0x362a88(_0x49e2cd,50),zVYZcQ.uObgx(_0x53f6ef,_0x105266,_0x449f3a)}static[n(1009)+"er"](t,r=!0){let o=n;if(e.UanUv(isNaN,t))return r?Na:bs;if(r){if(t>=ys)return Ba}else{if(e.luZfZ(t,-vs))return za;if(e[o(1319)](e[o(570)](t,1),vs))return Oa}return q.fromBits(e[o(1022)](e.LwQSa(t,it),0),e[o(460)](e.iFvoe(t,it),0),r)}[n(745)](){let t=n;return this.unsigned?e[t(1237)](this[t(1335)]>>>0,it)+e[t(1259)](this[t(263)],0):e[t(1517)](e[t(363)](this[t(1335)],it),this[t(263)]>>>0)}[n(457)](){let t=n;if(e[t(498)]!==e.sUAdg)this[t(332)]=!0,this[t(714)]();else return e.ddgtX(0,this[t(1335)])&&e[t(1120)](0,this[t(263)])}[n(356)](t){let r=n;q[r(1304)](t)||(t=q[r(1009)+"er"](t));let o=e[r(882)](this.high,16),x=e.zsEaX(65535,this.high),f=e.aktbc(this[r(263)],16),g=65535&this[r(263)],p=e[r(1388)](t.high,16),l=65535&t.high,y=t[r(263)]>>>16,b=e[r(633)](65535,t[r(263)]),k=0,P=0,O=0,N=0;return N+=g+b,O+=e[r(882)](N,16),N&=65535,O+=e[r(1545)](f,y),P+=O>>>16,O&=65535,P+=x+l,k+=e[r(914)](P,16),P&=65535,k+=e[r(858)](o,p),k&=65535,q.fromBits(e.BCclp(e.CkTLA(O,16),N),e[r(950)](e[r(578)](k,16),P),this[r(1157)])}[n(482)](t){let r=n;return q.isLong(t)||(t=q[r(1009)+"er"](t)),this[r(1157)]!==t.unsigned&&e[r(1240)](this[r(1335)]>>>31,1)&&e[r(1231)](t[r(1335)],31)===1?!1:e[r(812)](this[r(1335)],t[r(1335)])&&e[r(812)](this[r(263)],t[r(263)])}addOne(){let t=n;return e[t(233)](-1,this[t(263)])&&e[t(1168)](-1,this[t(1335)])?q[t(580)](0,0,this.unsigned):this.low===-1?q.fromBits(0,e.IkYWZ(this[t(1335)],1),this[t(1157)]):q[t(580)](e[t(1526)](this[t(263)],1),this[t(1335)],this[t(1157)])}[n(1369)](t){let r=n;return t?this[r(909)+"E"]():this[r(1290)+"E"]()}[n(909)+"E"](){let t=n;if(e.zjRUZ(e[t(266)],e.eeORy)){let r=this[t(1335)],o=this.low;return[e[t(1342)](255,o),e.ZTNvl(e[t(941)](o,8),255),e.Cqkzb(e[t(1181)](o,16),255),e[t(231)](o,24),e.yndKp(255,r),e[t(643)](e[t(746)](r,8),255),e[t(1330)](e[t(961)](r,16),255),e[t(1153)](r,24)]}else e[t(655)](_0x264994,_0x351902,this[t(1191)+t(1258)+"e"](_0x127307))}[n(1290)+"E"](){let t=n,r=this[t(1335)],o=this[t(263)];return[r>>>24,e[t(1476)](r>>>16,255),e[t(1368)](r>>>8,255),e.Cqkzb(255,r),e[t(1231)](o,24),e.lmadt(e.ghsRk(o,16),255),e[t(567)](e[t(231)](o,8),255),e[t(1342)](255,o)]}}let bs=new q(0,0,!1),Na=new q(0,0,!0),Oa=q[n(580)](-1,2147483647,!1),Ba=q[n(580)](-1,-1,!0),za=q[n(580)](0,-2147483648,!1);var Fe=(function(s){let t=n,r=e[t(536)][t(1555)]("|"),o=0;for(;;){switch(r[o++]){case"0":s[s[e[t(476)]]=5003]=e[t(476)];continue;case"1":s[s[t(1029)+"ERROR"]=5004]=e.ZilxB;continue;case"2":s[s[e[t(1501)]]=5005]=e[t(1501)];continue;case"3":s[s[e[t(1291)]]=5001]=e[t(1291)];continue;case"4":return s;case"5":s[s[e[t(1253)]]=5002]=e.oyjsv;continue}break}})({});class ot{constructor(t){let r=n;this[r(1462)]=t,this.target=null}}class Ss extends ot{constructor(t,r){let o=n;if(e[o(566)]!==e[o(791)])super(t),this[o(584)]=r&&r.message||null;else return _0x3b1599.resolve()}}class Es extends ot{constructor(t,r){let o=n;super(t),this.error=r&&r[o(1433)]||null,this[o(876)]=r&&r.colno||0,this[o(1256)]=r&&r[o(1256)]||"",this.lineno=r&&r[o(219)]||0,this[o(584)]=r&&r[o(584)]||"",this[o(568)]=r&&r[o(568)]||5001}}class Cs extends ot{constructor(t,r){let o=n;super(t),this[o(568)]=r&&r[o(568)]||0,this.reason=r&&r[o(1138)]||"",this.wasClean=r&&r[o(422)]||!1,this[o(1440)+"nnect"]=r&&r[o(1440)+o(454)]||!1}}class ks extends ot{constructor(t,r){let o=n;super(t),this[o(860)]=r&&r.data||null}}class As extends ks{constructor(t,r){let o=n;super(t),this[o(860)]=r&&r[o(860)]||null,this[o(584)]=r&&r.message||null}}class Ps extends ot{constructor(t,r){let o=n;super(t),this.data=r&&r[o(860)]||null}}function le(s,{message:t,code:r,error:o}){let x=n,f={RVQoX:function(g,p){return e[I(1282)](g,p)}};return e[x(1240)](e[x(1498)],x(1600))?new Es(s,{message:t,code:r,error:o}):_0x180382(BgWbGm[x(309)](_0x22a2d7,_0x1999f8))}function me(s,{code:t,reason:r,wasClean:o,willReconnect:x}){return new Cs(s,{code:t,reason:r,wasClean:o,willReconnect:x})}function Is(s,{data:t,message:r}){let o=n;if(e[o(815)]===e[o(815)])return new As(s,{data:t,message:r});{let x=e[o(1036)][o(1555)]("|"),f=0;for(;;){switch(x[f++]){case"0":if(e[o(230)](_0x454ee7,_0xffb405)&&e[o(277)](e[o(1267)],typeof _0x18c6cb)&&_0x2a9646)return!0;continue;case"1":if(_0x14b800)return!0;continue;case"2":if(_0x4e8226&&_0x546e56[o(1064)+o(890)])return!0;continue;case"3":return!1;case"4":if(_0x412d9d&&_0x1ffbfd["connectS"+o(890)])return!0;continue}break}}}function Ts(s,{data:t}){return new Ps(s,{data:t})}function dr(s,{message:t}){return new Ss(s,{message:t})}class Ds{constructor(t,r){let o=n;this.endpoints=t,this[o(765)+"es"]=r,this[o(1194)+o(899)]=0,this[o(787)+"ndpointT"+o(602)+"t"]=0}[n(1472)+n(1575)+n(1469)](){let t=n;this[t(1194)+t(899)]=0,this["currentE"+t(1346)+t(602)+"t"]=0}[n(394)+"es"](){let t=n;this["currentEndpointT"+t(602)+"t"]=0}getCurrentEndpoint(){let t=n;return this[t(924)+"s"][this[t(1194)+t(899)]]}[n(991)+n(946)+"ntTriesC"+n(302)](){let t=n;return this[t(787)+"ndpointT"+t(602)+"t"]}[n(1241)+"chMaxTries"](){let t=n;return!!(e[t(817)](this[t(1194)+t(899)],this[t(924)+"s"][t(475)])||this[t(1194)+t(899)]===e[t(1113)](this.endpoints.length,1)&&e[t(1377)](this["currentE"+t(1346)+t(602)+"t"],this[t(765)+"es"]))}[n(1491)+n(1177)+"ointReac"+n(1611)+"tries"](){let t=n;return e[t(711)](this[t(1194)+t(899)],this[t(924)+"s"][t(475)])?!0:e[t(1416)](this[t(787)+t(1346)+t(602)+"t"],this.maxRetries)}[n(1260)+n(210)+"pointAnd"+n(563)+n(419)](){let t=n;return this[t(787)+t(1346)+t(602)+"t"]=1,this[t(1194)+t(899)]++,this[t(924)+"s"][this["currentI"+t(899)]]}["getCurre"+n(946)+n(1473)+n(720)](){let t=n;if(e[t(854)](t(786),e.xRIzu))return this[t(787)+t(1346)+t(602)+"t"]++,this[t(991)+t(946)+"nt"]();{let r=_0xc0230[t(1555)](":");_0x1b918f&&(_0x1b1318=r[t(475)]),_0x523b35+=r[t(475)];for(let o=0;o<r[t(475)];o++)if(e[t(1167)](4,r[o][t(475)])){let x=_0x2e73f5[t(1190)+"g"](0,e[t(407)](4,r[o].length)),f=x[t(605)](r[o]);_0x51ec61[t(299)](f)}else _0x10d5e4[t(299)](r[o]);_0x2b7457=!1}}}let at=(e.lvalG(e[n(1267)],typeof globalThis)&&e.hkMyj(e.kAmAk,globalThis["construc"+n(1270)][n(1384)])||e[n(1267)]!=typeof window&&e[n(1120)](n(359),window.constructor[n(1384)]))&&e[n(1235)](e[n(1267)],typeof document),$e=e[n(433)](n(850)+"d",typeof globalThis)&&(e[n(507)](e[n(466)],globalThis[n(1012)+n(1270)][n(1384)])||e[n(805)](e[n(1576)],globalThis[n(1012)+"tor"][n(1384)]))&&e.fDHCo(e.IHlIH,typeof tt),Pt=(e[n(465)](e[n(1267)],typeof globalThis)&&e.HwSPK===globalThis[n(1012)+n(1270)][n(1384)]||n(850)+"d"==typeof globalThis||e[n(1233)](e[n(1267)],typeof globalThis)&&!!globalThis[n(223)+n(338)])&&e.LfCmF(e[n(1267)],typeof wx),It=typeof globalThis<"u"&&(e[n(1576)]===globalThis[n(1012)+n(1270)][n(1384)]||e[n(1605)]===globalThis[n(1012)+n(1270)][n(1384)]||e[n(676)](e[n(934)],globalThis["construc"+n(1270)][n(1384)]))&&e[n(1102)](e[n(1267)],typeof self),Ma=e.UNDof(e.IHlIH,typeof globalThis)&&e[n(466)]===globalThis[n(1012)+n(1270)][n(1384)]&&n(850)+"d"!=typeof global&&e[n(1261)](e[n(466)],global.constructor.name)&&n(850)+"d"!=typeof process&&!!process[n(1076)];class fr{constructor(){let t=n;this[t(661)+"rs"]={}}[n(1539)](t,...r){let o=n,x=this._listeners[t];if(x)x[o(1348)]()[o(993)](f=>f.fn[o(1445)](f[o(1023)],r));else if(e.dEvME===t&&!this[o(681)]){let f=r.length&&r[0];if(e.whyJM(f,Error))throw f;let g=new Error(e[o(1517)](o(590)+"d error.",f?e.RMuIU(" (",f[o(584)])+")":""));throw g.context=f,f}return this}[n(1471)](t,r){let o=n;if(t===void 0)this._listeners={};else if(e[o(805)](void 0,r))this[o(661)+"rs"][t]=null;else{let x=this[o(661)+"rs"][t];if(x)for(let f=0;f<x[o(475)];)e[o(676)](x[f].fn,r)?x[o(1544)](f,1):++f}return this}on(t,r,o){let x=n;return(this._listeners[t]||(this[x(661)+"rs"][t]=[])).push({fn:r,ctx:o||this}),this}}class qa extends fr{["_formatE"+n(1100)+n(1436)](t){let r=n;return t[r(693)]||t[r(208)]?(r(1586)+" "+(t.errMsg||"")+r(976)+(t[r(208)]||""))[r(491)]():JSON[r(315)+"y"](t)}constructor(t,r,o){let x=n;super(),this[x(1038)]=null,Pt&&wx["connectS"+x(890)]&&(this._socket=wx[x(1064)+x(890)]({url:t,protocols:r,header:o,fail:this[x(1612)+"ocketFai"+x(533)][x(856)](this),success:this[x(1612)+"ocketSuc"+x(370)+x(1280)][x(856)](this)})),$e&&tt[x(1064)+x(890)]&&(this[x(1038)]=tt[x(1064)+"ocket"]({url:t,protocols:r,header:o,fail:this[x(1612)+x(906)+"lHandler"][x(856)](this),success:this[x(1612)+x(1458)+"cessHand"+x(1280)][x(856)](this)}))}[n(1612)+"ocketSuc"+n(370)+n(1280)](){let t=n;Promise[t(560)]().then(()=>{let r=t;this[r(1465)+r(995)]()})}[n(1612)+"ocketFailHandler"](t){let r=n,o={CDDYs:function(x,f,g){return e[I(887)](x,f,g)},PIShn:e[r(717)],NYXYx:e[r(1028)]};Promise.resolve().then(()=>{let x=r,f=o[x(969)](le,o.PIShn,{message:this[x(1421)+x(1100)+x(1436)](t)});this[x(1539)](x(1433),f);let g=o[x(969)](me,o[x(1050)],{reason:this[x(1421)+x(1100)+"age"](t)});this.emit("close",g)})}["_addWsLi"+n(995)](){let t=n,r={dtqXV:e[t(1028)],YRBRW:function(o,x,f){return e[t(200)](o,x,f)},wggKz:e[t(717)]};this[t(1038)][t(1578)](o=>{let x=t;this.emit(x(1015),e[x(1203)](Ts,e.UHzlj,{...o,data:o[x(693)]||""}))}),this[t(1038)].onClose(o=>{let x=t;this[x(1539)](r[x(1483)],r[x(546)](me,"close",{...o}))}),this._socket[t(521)+"e"](o=>{let x=t;this[x(1539)](x(584),e.qTMPj(Is,e.NOHBw,{...o}))}),this[t(1038)][t(1201)](o=>{let x=t;this[x(1539)](r.wggKz,le(r[x(1558)],{...o,message:o[x(693)]||""}))})}send(t){let r=n,o={phaxB:function(x,f){return x<=f},dhpnk:function(x,f){return e.HILnk(x,f)},wBBhw:function(x,f){return e.ieOmD(x,f)},KjxcV:function(x,f){return e[I(806)](x,f)},mikGd:function(x,f){return e[I(1556)](x,f)},Qgion:function(x,f){return e[I(1094)](x,f)},hJOqN:function(x,f){return e[I(1083)](x,f)},fNnej:function(x,f){return x<<f},QQRSB:function(x,f){return e[I(526)](x,f)},ljmSx:function(x,f){return x&f},JVOwS:function(x,f){return x-f},bmqmV:function(x,f){return e[I(1583)](x,f)},EsSvB:function(x,f){return e[I(372)](x,f)},OTMez:function(x,f){return x|f},Salsa:function(x,f){return e[I(1324)](x,f)},NjTco:function(x,f){return e.RlLVg(x,f)},jsHci:function(x,f){return x+f},lqKoZ:function(x,f){return x>>f}};if(e[r(233)](e[r(501)],r(620)))if(t instanceof Uint8Array){let x=t[r(265)][r(1348)](t[r(1309)+"et"],t[r(671)+"th"]+t[r(1309)+"et"]);this[r(1038)]&&this._socket[r(777)]({data:x,fail:f=>{let g=r;this.emit(e[g(717)],e[g(228)](le,e[g(717)],{message:this[g(1421)+"rrorMess"+g(1436)](f)}))}})}else this[r(1038)]&&this._socket[r(777)]({data:t,fail:x=>{let f=r;this[f(1539)](e[f(717)],e[f(779)](le,e[f(717)],{message:this["_formatE"+f(1100)+f(1436)](x)}))}});else{let x=_0x23b191[_0x1fc202++];if(o.phaxB(x,127))_0x369281+=_0x7d123d[r(398)+"Code"](x);else if(x>=192&&o.dhpnk(x,224))_0x628f2b+=_0x514b63["fromChar"+r(573)](o[r(273)](o[r(1577)](31,x)<<6,o[r(296)](63,_0x42bae0[_0x15615a++])));else if(o[r(1592)](x,224)&&x<240)_0x300098+=_0x2ebf4b[r(398)+r(573)](o[r(840)](o[r(1176)](o[r(729)](15,x),12),o[r(1176)](o[r(296)](63,_0x4aadb0[_0x9e89b7++]),6))|o[r(1162)](63,_0x5bed7b[_0x27edcb++]));else if(o[r(1592)](x,240)){let f=o[r(226)](o[r(932)](o[r(1063)](o[r(523)]((7&x)<<18,o[r(577)](o[r(729)](63,_0x66f2e2[_0x1977a2++]),12)),o[r(1221)](63,_0x3de15c[_0x16ed6e++])<<6),o[r(1221)](63,_0x13f34b[_0x19382d++])),65536);_0x564832+=_0x4fc10e[r(398)+r(573)](o[r(366)](55296,o[r(821)](f,10))),_0x5f5aa5+=_0x4a2843[r(398)+r(573)](o.jsHci(56320,1023&f))}}}[n(492)](t,r){let o=n;this[o(1038)]&&this[o(1038)][o(492)]({code:t,reason:r})}[n(1004)+"Listener"](t,r){this.on(t,r)}[n(1429)+n(1466)+n(1538)](t,r){this[n(1471)](t,r)}get[n(996)+"te"](){let t=n;return this[t(1038)][t(996)+"te"]}get[n(1078)+"pe"](){let t=n;return this[t(1038)][t(1078)+"pe"]}set[n(1078)+"pe"](t){}get[n(558)](){let t=n;return this[t(1038)][t(558)]}get[n(673)](){let t=n;return this[t(1038)][t(673)]}get[n(828)+"ns"](){let t=n;return this[t(1038)][t(828)+"ns"]}get[n(276)+"Amount"](){return 0}}function Fa(s,t){let r=n;if(t)return new t(s[r(558)],s.protocol);if(e[r(230)](Pt,$e))return new qa(s[r(558)],s[r(673)],s.headers);if(e[r(470)](at,It)&&e[r(727)](e[r(1267)],typeof WebSocket)&&WebSocket)return new WebSocket(s[r(558)],s[r(673)+"s"])}function Ua(s){let t=n;if(e[t(700)](e[t(1108)],e[t(1108)]))_0x1616e7 instanceof _0x98595c&&_0x4d1de4[t(749)](_0x56a7c4,_0x18fc40);else{let r=e.VEvhK.split("|"),o=0;for(;;){switch(r[o++]){case"0":if(s)return!0;continue;case"1":return!1;case"2":if(Pt&&wx[t(1064)+t(890)])return!0;continue;case"3":if($e&&tt[t(1064)+t(890)])return!0;continue;case"4":if(e[t(1161)](at,It)&&e[t(727)](e.IHlIH,typeof WebSocket)&&WebSocket)return!0;continue}break}}}function Rs(s,t,r){let o=n;if(e[o(242)](e[o(222)],e.yolAz))this[o(627)+o(321)+o(514)](_0x21563c),_0x1697c9[o(749)](_0x3c11f2,_0x10278b,_0x5a68ab.message[o(1488)]);else{let x=-1;async function f(g){let p=o;return e.sbuaJ(g,x)?Promise[p(1502)](new Error("next() c"+p(1068)+p(678)+p(471)+p(1246))):(x=g,e.ZPKHE(g,r.length)?Promise[p(560)]():r[g][p(856)](s)(t,f.bind(null,e.pkLgp(g,1))))}e[o(203)](f,0)}}function Ls(s){let t=n,r={rDwIV:function(f,g){return e.YmmwQ(f,g)}},o=0,x=0;for(let f=0;f<s[t(475)];++f)if(x=s[t(741)+"At"](f),e[t(327)](x,128))o+=1;else if(x<2048)o+=2;else if(e.gEfBI(64512&x,55296)&&e[t(903)](e.cUsdB(64512,s[t(741)+"At"](e[t(797)](f,1))),56320))if(e[t(757)](e.aJhWj,e[t(767)])){let g=this._qosDB[t(1609)+"geSync"](this[t(716)]),p=_0x3b2eef[t(591)](r[t(1278)](g,"{}"));return p[_0x43552e]=void 0,this[t(513)][t(904)+t(845)](this[t(716)],_0xbd0be9[t(315)+"y"](p))}else++f,o+=4;else o+=3;return o}function Ns(s,t,r){let o=n;if(e[o(597)](r-t,1))return"";let x="";for(let f=t;e[o(597)](f,r);){let g=s[f++];if(e[o(381)](g,127))x+=String[o(398)+"Code"](g);else if(e.BeTZg(g,192)&&e.PnhLY(g,224))x+=String.fromCharCode(e[o(1447)](e[o(1089)](31,g)<<6,e.pvQHN(63,s[f++])));else if(e.RXNOP(g,224)&&g<240)x+=String["fromChar"+o(573)](e.taDqx(e[o(325)](e[o(1324)](15&g,12),e.LAfqc(e[o(699)](63,s[f++]),6)),63&s[f++]));else if(e[o(621)](g,240)){let p=e.dUbBE(e.pZHYG(e[o(950)](e[o(1220)](e[o(1495)](7,g),18),e[o(451)](63&s[f++],12))|e[o(788)](e[o(232)](63,s[f++]),6),e[o(1337)](63,s[f++])),65536);x+=String[o(398)+o(573)](e[o(1146)](55296,e[o(688)](p,10))),x+=String[o(398)+o(573)](e[o(1526)](56320,e.rtTzx(1023,p)))}}return x}function lr(s,t,r){let o=n,x=r,f,g;for(let p=0;p<s[o(475)];++p)if(f=s.charCodeAt(p),e[o(421)](f,128))t[r++]=f;else if(f<2048)if(e[o(550)](e.sCxgA,e[o(998)]))t[r++]=e[o(270)](f>>6,192),t[r++]=e.UejTk(63,f)|128;else if(_0x31a22b=_0x41b11e[o(741)+"At"](_0x4abeee),_0x5da752<128)_0x12f710[_0xd6cefb++]=_0x4d5394;else if(_0x3d56e8<2048)_0x34bda1[_0x21a7ee++]=e.DWerQ(e[o(557)](_0x47b26d,6),192),_0x36a2ea[_0x1a43f0++]=e.RpqLm(e.yndKp(63,_0x409a60),128);else if(e[o(645)](64512&_0x543d51,55296)&&e[o(1046)](64512&(_0x2172fb=_0x4f4418[o(741)+"At"](e[o(570)](_0x1666f5,1))),56320)){let l=e[o(1490)][o(1555)]("|"),y=0;for(;;){switch(l[y++]){case"0":_0x168a30=e[o(339)](65536+e[o(992)](1023&_0x53fa14,10),e.ysaUX(1023,_0x5ac5f5));continue;case"1":_0x56ac1b[_0x4a4ebe++]=e[o(1478)](e[o(917)](e[o(1183)](_0x31dd9f,12),63),128);continue;case"2":_0x1e1e1d[_0x2079db++]=e[o(1573)](e[o(567)](_0x447330>>6,63),128);continue;case"3":++_0x19ea84;continue;case"4":_0x339d75[_0x26591a++]=e.VZzHP(63,_0x376337)|128;continue;case"5":_0xf026a1[_0x2e23ef++]=e[o(557)](_0x2a9813,18)|240;continue}break}}else _0x404fa3[_0x5eea26++]=e[o(1500)](_0x4dcf9e,12)|224,_0x4416a3[_0xc6c7be++]=e.cZJJe(e[o(1562)](_0x3a9890,6)&63,128),_0x1aa4da[_0x505dc3++]=e.qVcAR(e[o(1511)](63,_0xd3292),128);else if(e[o(431)](64512&f,55296)&&e.RDHyY(e.acDPI(64512,g=s[o(741)+"At"](e.gPyxj(p,1))),56320)){let l=("3|1|2|5|"+o(1018))[o(1555)]("|"),y=0;for(;;){switch(l[y++]){case"0":t[r++]=e.eavML(e[o(643)](e.TzTGh(f,6),63),128);continue;case"1":++p;continue;case"2":t[r++]=e[o(269)](f>>18,240);continue;case"3":f=e.zdfhI(e[o(427)](65536,e.lHobN(1023&f,10)),e[o(1588)](1023,g));continue;case"4":t[r++]=e[o(1192)](63&f,128);continue;case"5":t[r++]=e[o(1536)](e[o(1337)](e.mcfXs(f,12),63),128);continue}break}}else t[r++]=e[o(294)](e.mcfXs(f,12),224),t[r++]=e[o(913)](e.tnUlA(f>>6,63),128),t[r++]=e.rSGdg(63,f)|128;return e[o(781)](r,x)}async function Os(s){let t=n;if(e[t(593)]==typeof s){let r=new Uint8Array(e.VaVbk(Ls,s));return e[t(280)](lr,s,r,0),r}return e.qMJfp(s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s[t(265)],s[t(1309)+"et"],s.byteLength)}function Ha(s){let t=n;try{return e[t(727)](t(629),typeof s)&&(s instanceof ArrayBuffer||s[t(265)]&&e[t(429)](s[t(265)],ArrayBuffer))||e[t(623)](e.IOHNT,typeof s)?"":(JSON[t(591)](s),e[t(1494)])}catch{return e.uaODF(e[t(593)],typeof s)?e[t(552)]:""}}let Ga=(s,t)=>{let r=n;switch(s){case e.ndZXW:case e[r(1523)]:return{["x-use-"+s]:1,"x-tt-env":t};default:return{}}};class ja{constructor(t){let r=n,o={pHMFp:function(x,f){return e[I(1442)](x,f)},MPvYS:function(x,f){return e[I(1536)](x,f)},KhodY:function(x,f){return e[I(269)](x,f)},nANsW:function(x,f){return e.YdOFC(x,f)},hgkYI:function(x,f){return e[I(473)](x,f)},kZebT:function(x,f){return e.PNamw(x,f)},TDrtj:function(x,f){return e.QjJDQ(x,f)},gcqHJ:function(x,f){return x&f},Bqxsz:function(x,f){return e.rxgxh(x,f)},nXTDa:function(x,f,g){return e[I(456)](x,f,g)},aaCkZ:function(x,f){return e[I(1517)](x,f)},IgMnE:function(x,f){return e[I(789)](x,f)},kpWZb:function(x,f){return e[I(481)](x,f)}};e[r(1351)](e[r(867)],e.NZAZH)?(this[r(204)+r(302)]=t,this.count=0):(_0x189b9f=cNXuHG[r(1595)](cNXuHG[r(931)](cNXuHG[r(1443)](cNXuHG[r(397)](cNXuHG[r(1070)](7,_0x317955),18),cNXuHG[r(838)](63&_0x1909c7,12)),cNXuHG.TDrtj(63&_0x344c19,6)),cNXuHG[r(328)](63,_0x42dc0a)),cNXuHG.Bqxsz(_0x31144a,65536)||_0x3e2990>1114111?_0x10143a+=_0x9be625:(_0x406c63-=65536,_0x5b277a+=cNXuHG[r(221)](_0x1b66da,cNXuHG[r(383)](cNXuHG[r(371)](_0x197b87,10),55296),cNXuHG[r(1284)](1023&_0xdcd503,56320)),_0x10c829+=3))}[n(292)](){let t=n;if(e[t(504)](e[t(988)],e[t(391)]))return e[t(1094)](_0xbdc14a[t(973)],_0x46c0c7[t(442)]);this[t(1376)]++}["checkRea"+n(1379)+"nt"](){let t=n;return e.wABSh(this[t(1376)],this["maxLossC"+t(302)])}[n(617)+n(1599)](t=0){let r=n;this[r(204)+r(302)]=t,this[r(1376)]=0}}async function Ka(s){let t=n;if(e.rNQWB(e.DjtJP,t(1130)))return new Promise(r=>{let o=t,x={euYEb:e.MZQgs};if(!at)return r(e.MZQgs);try{let f=document[o(647)+o(336)](e[o(769)]);window[o(822)+o(1328)]=g=>{let p=o;document[p(677)][p(477)+"ild"](f),window["frontier"+p(1328)]=void 0,r(g&&g[p(1085)]||x.euYEb)},f[o(1462)]=o(1033)+o(1075),f[o(1301)]=e[o(339)](s[o(1116)](/^ws/,o(493)),e[o(1481)]);try{document[o(677)][o(1159)+o(1397)](f)}catch{if(e[o(1399)](e[o(833)],"LPFHN"))document[o(677)][o(477)+o(1397)](f);else return this[o(787)+o(1346)+"riesCount"]++,this[o(991)+"ntEndpoint"]()}}catch{window[o(822)+o(1328)]=void 0,r(e.MZQgs)}});_0x2aa9ed(_0x435224.error||new _0x2f602f(dAdEYp[t(581)],dAdEYp.DqWsX)),dAdEYp[t(770)](_0xb39103)}function Ue(s,t,r){let o=n;return!!s?.[o(290)](x=>x[o(1580)]===t&&x[o(522)]===r)}function ct(s,t){let r=n;return s?.[r(290)](o=>o[r(1580)]===t)?.value}let hr=null;async function Wa(){let s=n;if(e[s(962)](e.QxmgW,e[s(600)]))return hr||(hr=Promise.resolve()[s(440)](ke[s(856)](ke,e[s(1453)]))),hr;_0x205de2[s(901)](_0x1b350a)}class Ja extends fr{constructor(t,r){let o=n;super(),this._dbName=t,this[o(748)]=r,this[o(513)]=void 0,this[o(341)+"mise"]=null}async[n(1415)](){await this[n(565)]()}async[n(565)](){let t=n,r={DkAyN:function(o,x){return e.lIcPF(o,x)}};if(!this[t(513)]){if(this[t(341)+t(479)])return this[t(341)+t(479)];try{let o=this[t(855)],x=this[t(748)];this["_initPro"+t(479)]=(async()=>{let f=t,{openDB:g}=await e[f(796)](Wa);this[f(513)]=await g(f(822)+"_"+o,1,{upgrade(p){p[f(1011)+"jectStore"](o,{keyPath:x})}})})(),await this[t(341)+t(479)]}catch(o){if(e.deWoL!==t(1394))console[t(901)](o);else return _0x1a39d6&&(_0x38cb0a=(0,_0x1a2e15[ZIBbrP[t(437)](_0x1e1932,_0xbd7aac)[0]])(_0x3ec59e=0)),_0x5a56cd}finally{this[t(341)+"mise"]=null}}}async get(t){let r=n;try{return await this[r(565)](),this._qosDB?.get(this[r(855)],t)}catch(o){console[r(901)](o)}}async[n(749)](t,r){let o=n;return await this[o(565)](),this[o(513)]?.put(this[o(855)],t)}async del(t){let r=n;try{return await this[r(565)](),this[r(513)]?.delete(this._dbName,t)}catch(o){console[r(901)](o)}}async clear(){let t=n;try{return await this[t(565)](),this[t(513)]?.[t(519)](this[t(855)])}catch(r){console.log(r)}}async[n(820)](){let t=n;return await this[t(565)](),this[t(513)]?.[t(1313)+"ys"](this[t(855)])}async[n(238)](){let t=n;return await this[t(565)](),this[t(513)]?.[t(238)](this[t(855)])}async[n(834)](){let t=n;try{this._qosDB?.[t(492)](),this._qosDB=void 0}catch(r){console[t(901)](r)}}get[n(872)](){let t=n,r={zTins:function(o,x){return e[I(980)](o,x)}};if(e.JbIVS===e[t(1553)])_0x1df725+=oAvDpr[t(625)](_0x464ae1,_0x3268b5),_0x3cb9c0+=2;else try{return!!this[t(513)]}catch(o){if(e.zlNtS(e[t(283)],e.JVEeF))return console[t(901)](o),!1;this[t(594)+t(512)]()}}}class Va{constructor(t,r){let o=n,x={PfBfN:function(f,g){return e[I(948)](f,g)}};if(e[o(1066)]===e[o(1193)])return gteeIR.PfBfN(this.count,this[o(204)+o(302)]);this[o(1002)]=t,this[o(304)]=r,this[o(513)]=localStorage}async openDB(){}get[n(716)](){let t=n;return t(822)+"_"+this[t(1002)]}async[n(798)](t){let r=n,o=this[r(513)][r(1507)](this._prefix);return JSON[r(591)](e[r(1099)](o,"{}"))[t]}async set(t,r){let o=n,x=this[o(513)][o(1507)](this[o(716)]),f=JSON[o(591)](e[o(1161)](x,"{}"));return f[r||t[this[o(304)]]]=t,this[o(513)][o(1134)](this._prefix,JSON.stringify(f)),r||t[this[o(304)]]}async[n(1151)](t){let r=n,o=this._qosDB[r(1507)](this[r(716)]),x=JSON[r(591)](e[r(467)](o,"{}"));return x[t]=void 0,this[r(513)][r(1134)](this._prefix,JSON.stringify(x))}async[n(519)](){let t=n;return e[t(547)]===e.jvSQp?{bytes:_0x4d39a1,offset:0,limit:_0x5ebd4b[t(475)]}:this[t(513)][t(519)]()}async[n(820)](){let t=n,r=this[t(513)].getItem(this[t(716)]),o=JSON[t(591)](e[t(450)](r,"{}"));return Object.keys(o)}async[n(238)](){let t=n,r=this[t(513)].getItem(this[t(716)]),o=JSON[t(591)](e.AlOuQ(r,"{}"));return Object[t(1045)](o)}[n(834)](){return Promise.resolve()}get[n(872)](){return!!this[n(513)]}}class Xa{constructor(t,r){let o=n;this._DBName=t,this[o(304)]=r,this[o(513)]=$e?tt:Pt?wx:null}async[n(1415)](){}get[n(716)](){return n(822)+"_"+this._DBName}async get(t){let r=n;if(e[r(1597)]!==e[r(1597)])_0x5897fb[r(749)](_0x333534,_0x1ff147),_0x4d33df[r(749)](_0x278751,_0x372c03);else{let o=this[r(513)][r(1609)+r(845)](this[r(716)]);return JSON[r(591)](e[r(1161)](o,"{}"))[t]}}async[n(749)](t,r){let o=n,x=this[o(513)][o(1609)+o(845)](this[o(716)]),f=JSON.parse(e[o(1099)](x,"{}"));return f[r||t[this[o(304)]]]=t,this._qosDB[o(904)+o(845)](this[o(716)],JSON.stringify(f)),r||t[this[o(304)]]}async del(t){let r=n,o=this[r(513)]["getStora"+r(845)](this[r(716)]),x=JSON[r(591)](e[r(450)](o,"{}"));return x[t]=void 0,this[r(513)][r(904)+r(845)](this[r(716)],JSON.stringify(x))}async[n(519)](){let t=n,r={WMKBe:function(o,x){return e[I(408)](o,x)},gbnWr:function(o,x){return e.tKsah(o,x)},YExzS:function(o,x){return e[I(704)](o,x)},TLMze:function(o,x){return e[I(775)](o,x)},LRjCT:function(o,x){return o<x},VgoRs:function(o,x){return e[I(1224)](o,x)},czzfp:function(o,x){return e.blqzh(o,x)},GhznO:function(o,x){return e[I(1272)](o,x)},hYSBY:function(o,x){return e.RyNAw(o,x)},RIqSS:function(o,x){return e[I(1056)](o,x)},olpPO:function(o,x){return e[I(1288)](o,x)},XwABh:function(o,x){return o|x},YFOPV:function(o,x){return o<<x},EKwaH:function(o,x){return e[I(708)](o,x)},QixYx:function(o,x){return e[I(544)](o,x)},WqSUb:function(o,x){return e.UejTk(o,x)},bTJnm:function(o,x){return e.wsdhO(o,x)}};if(e[t(1295)](e[t(1065)],e[t(864)]))return this[t(513)]["clearSto"+t(1208)]();{if(dwTgGr[t(615)](dwTgGr[t(459)](_0x254075,_0x1341b6),1))return"";let o="";for(let x=_0x1b510d;x<_0x2c7fc3;){let f=_0x4d6c1b[x++];if(dwTgGr[t(911)](f,127))o+=_0x2555ac[t(398)+t(573)](f);else if(dwTgGr.TLMze(f,192)&&dwTgGr[t(813)](f,224))o+=_0x479178["fromChar"+t(573)](dwTgGr[t(548)](dwTgGr[t(1482)](31,f),6)|dwTgGr.GhznO(63,_0x1e378f[x++]));else if(f>=224&&dwTgGr.LRjCT(f,240))o+=_0x444936[t(398)+"Code"](dwTgGr.hYSBY(dwTgGr[t(742)](dwTgGr.czzfp(15,f)<<12,dwTgGr[t(240)](63,_0xcb3b95[x++])<<6),dwTgGr[t(240)](63,_0x4e35c1[x++])));else if(dwTgGr[t(364)](f,240)){let g=dwTgGr[t(1251)](dwTgGr[t(1109)](dwTgGr.hYSBY(dwTgGr[t(548)](dwTgGr.GhznO(7,f),18),dwTgGr[t(390)](dwTgGr.EKwaH(63,_0x57978f[x++]),12)),dwTgGr[t(262)](dwTgGr[t(494)](63,_0x121b96[x++]),6)),dwTgGr[t(1360)](63,_0xcfcf6e[x++]))-65536;o+=_0x2a6f6e[t(398)+"Code"](55296+(g>>10)),o+=_0x335b1a["fromChar"+t(573)](56320+dwTgGr[t(1482)](1023,g))}}return o}}async[n(820)](){let t=n;if(e[t(1574)]!==e[t(1366)]){let r=this[t(513)]["getStora"+t(524)+"nc"](this._prefix),o=JSON[t(591)](e.YOqLg(r,"{}"));return Object.keys(o)}else throw this["_connect"+t(912)]=!1,_0x23e640}async[n(238)](){let t=n,r=this._qosDB[t(1609)+t(524)+"nc"](this._prefix),o=JSON[t(591)](e[t(450)](r,"{}"));return Object[t(1045)](o)}[n(834)](){return Promise.resolve()}get[n(872)](){return!!this[n(513)]}}function Bs(s,t){let r=n;if(e[r(334)]($e,$e))return new Xa(s,t);if(e[r(230)](at,It)&&e[r(1233)](e.IHlIH,typeof indexedDB))return new Ja(s,t);if((at||It)&&e.YzgKF(e[r(1267)],typeof localStorage))return new Va(s,t);throw new Error("init QoSDB failed")}class $a{constructor(){let t=n;this[t(972)+t(426)+"Id"]=null,this[t(972)+"l"]=36e5,this[t(513)]=e[t(826)](Bs,e[t(1424)],"message_id")}async[n(972)+n(690)](){let t=n;clearInterval(this[t(972)+t(426)+"Id"]),this[t(972)+t(426)+"Id"]=e[t(456)](setInterval,()=>{this[t(594)+"ired"]()},this[t(972)+"l"])}async[n(1415)](){let t=n;await this[t(513)].openDB()[t(440)](()=>{let r=t;this[r(972)+r(690)]()})}async[n(594)+"ired"](){let t=n;(await this._qosDB?.[t(238)]()||[]).filter(({timestamp:x})=>x<Date.now())[t(993)](x=>{let f=t;this._qosDB?.[f(1151)](x[f(288)+"id"])})}async del(t){return this[n(513)]?.del(t)}async[n(749)](t,r){let o=n;return this[o(513)]?.[o(749)]({message_id:t,timestamp:r})}async[n(798)](t){let r=n;return this[r(513)]?.[r(798)](t)}async closeDB(){let t=n;e[t(1402)](clearInterval,this[t(972)+t(426)+"Id"]),await this[t(513)]?.[t(834)]()}get isReady(){let t=n;if(e[t(259)](t(335),t(261))){if(!this[t(340)+t(239)]()||this["_readyCl"+t(1158)])return;this[t(428)+t(562)]?.["resetEnd"+t(1575)+t(1469)](),this[t(842)+t(942)]?.[t(617)+t(1599)](),this[t(1312)]?this["_disconn"+t(631)](1001,e.gxiLI,!0):this[t(714)]()}else return this[t(513)]?.isReady}}function gr(s){let t=n,r=!!this._options.enableQoS;if(!r)return{enabled:r,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=e[t(649)](Ue,s[t(584)].headers,e[t(1044)],"2"),x=o&&e[t(280)](Ue,s[t(584)][t(733)],e[t(715)],"1"),f=o&&e[t(753)](Ue,s[t(584)][t(733)],t(1334)+"er_is_ack","1"),g=f?e.NprHD(ct,s[t(584)][t(733)],e[t(386)])?.[t(1555)](",").filter(Boolean)||[]:[];return{enabled:r,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:f,ackMsgIds:g}}async function zs(){let s=n;return this["_QoSMana"+s(664)]||(this[s(606)+"ger"]=new $a),this["_QoSMana"+s(664)][s(872)]||await this[s(606)+"ger"].openDB(),this[s(606)+s(664)]}async function Ya(s,t){let r=n,{enableAutoAck:o}=this[r(1229)],x=Ue(s[r(584)][r(733)],r(963),"1"),f=e[r(753)](Ue,s[r(584)][r(733)],r(480),"1"),g=gr.call(this,s);if(e[r(443)](o,x)){let{SeqID:p,LogID:l,service:y,LogIDNew:b,method:k}=s.message;this[r(1097)]({SeqID:p,LogID:l,LogIDNew:b,service:y,method:k,headers:[{key:e.LamJo,value:"1"},{key:e[r(807)],value:e[r(1271)](b,"")},{key:e[r(705)],value:"0"}]})}f&&!g[r(1062)]&&this["_dispatc"+r(1127)+r(660)](s),e[r(770)](t)}async function Za(s,t){let r=n,o={FrXKu:function(x,f,g){return x(f,g)},vJPSm:e.GzlGW};e[r(1584)](e[r(1549)],e[r(1549)])?(this[r(1489)+r(1352)]=_0x1763b4,this[r(1305)+r(1358)]=_0xf8b396,this[r(1252)+r(979)]=_0xad7f96,this[r(513)]=o.FrXKu(_0x7ed51a,this[r(1489)+r(1352)],o[r(392)])):(this[r(1403)](r(758),s[r(584)]),t())}async function Qa(s,t){let r=n,o=e[r(1531)](ws,await e[r(1417)](Os,s[r(860)]));try{if(e[r(622)](o[r(849)],Uint8Array)){let x=e[r(429)](this[r(1229)][r(674)+r(1373)],Object)?{force:!!this._options[r(674)+"ncoding"][r(868)],encoding:this._options["payloadE"+r(1373)][r(1003)]?this[r(1229)][r(674)+r(1373)][r(1003)][r(1116)](/\s/g,"")[r(773)+"ase"]():""}:{force:!1,encoding:this[r(1229)]["payloadE"+r(1373)]?this[r(1229)][r(674)+r(1373)][r(1116)](/\s/g,"")[r(773)+r(444)]():""},f=o[r(674)+r(1373)]?o[r(674)+r(1373)][r(1116)](/\s/g,"")[r(773)+"ase"]():"",g=e[r(622)](this._options[r(551)+r(1393)],Object)?{force:!!this[r(1229)][r(551)+r(1393)][r(868)],type:this[r(1229)]["payloadT"+r(1393)][r(1462)]?this._options[r(551)+r(1393)].type.replace(/\s/g,"")[r(773)+r(444)]():""}:{force:!1,type:this[r(1229)][r(551)+r(1393)]?this[r(1229)][r(551)+r(1393)][r(1116)](/\s/g,"")["toLowerC"+r(444)]():""},p=o[r(551)+r(1393)]?o[r(551)+r(1393)].replace(/\s/g,"")[r(773)+r(444)]():"",l=g[r(868)]?g[r(1462)]:p||g.type,y=x[r(868)]?x[r(1003)]:f||x[r(1003)],b=[e[r(552)],e.stFCT,e[r(206)],e[r(593)]],k=[e.lRNbq,r(918)];this[r(1229)][r(658)+r(650)+"extPayload"]&&b.includes(l)&&(!y||k[r(596)](y))?o[r(1030)+r(1040)]=e[r(280)](Ns,o[r(849)],0,o[r(849)][r(671)+"th"]):o["textPayl"+r(1040)]=""}else o[r(1030)+r(1040)]=""}catch(x){o[r(1030)+r(1040)]="",console.log(x)}s.message=o,e[r(770)](t)}function e0(s,t,r){let o=n,x={BkUuO:function(y,b){return e[I(1402)](y,b)},APcPB:function(y,b){return e[I(891)](y,b)},plnVe:function(y,b){return e[I(1058)](y,b)}},f=e[o(450)](r,8192),g=e[o(1388)](f,1),p=null,l=f;return function(y){let b=o;if(y<1||y>g)return s(y);l+y>f&&(p=x.BkUuO(s,f),l=0);let k=t.call(p,l,l+=y);return 7&l&&(l=x[b(1423)](x[b(416)](7,l),1)),k}}let t0=4294967295;function n0(s,t,r){let o=n;return e[o(251)](RangeError,e[o(1517)](e.HzpJM(e[o(1202)](e.LlMfM(e[o(663)],s),e[o(1315)]),e[o(450)](t,1))+o(1314),r))}function r0(s,t,r){let o=n;if(r>t0)throw new Error(e.alSJM);let x=3;for(;e[o(1459)](x,0);){let f=e.QHieJ(255,r);e[o(649)](mr,f,s,e.ziPEH(t,x)),r>>>=8,x--}return e[o(1091)](t,4)}function s0(s,t){let r=n,o=0,x=t,f=t+4;for(;x<f;){if(e.RnoGx(e[r(1422)],r(1510)))return this[r(1312)]?this[r(1312)][r(558)]:this[r(982)];{let{value:g,offset:p}=e[r(668)](pr,s,x);x=p,o=e[r(231)](o<<8,0),o+=g}}return{value:o,offset:f}}function i0(s,t,r){let o=n,x=e.OLXdg[o(1555)]("|"),f=0;for(;;){switch(x[f++]){case"0":if(s[o(475)]<40)return e[o(280)](lr,s,t,r)+r;continue;case"1":if(!s)return r;continue;case"2":if(t[o(892)])return e[o(402)](t[o(892)](s,r),r);continue;case"3":return e[o(1079)](e[o(1386)](lr,s,t,r),r);case"4":if(t[o(1096)+"e"])return e.dUMcY(t[o(1096)+"e"](s,r),r);continue}break}}function o0(s,t){let r=n,o=new q(e[r(1536)](e[r(1474)](e.nEhCw(s[e[r(1526)](t,4)],24),s[e.nEumu(t,5)]<<16),e[r(378)](s[e[r(1006)](t,6)],8))|s[t+7],e[r(207)](e[r(1207)](e.dtncv(e[r(413)](s[e.nEumu(t,0)],24),e[r(1224)](s[t+1],16)),e[r(1541)](s[e.TLjaI(t,2)],8)),s[e.lgUjr(t,3)]),!0);return t+=8,{value:o,offset:e.Ehgjt(t,8)}}function a0(s,t,r){let o=n,x=s[o(263)],f=s[o(1335)];return t[r]=e[o(914)](f,24),t[e[o(402)](r,1)]=e[o(882)](f,16)&255,t[e[o(1019)](r,2)]=e[o(1505)](e[o(1320)](f,8),255),t[r+3]=e[o(1434)](255,f),t[e.ZxYdy(r,4)]=e[o(759)](x,24),t[r+5]=e[o(914)](x,16)&255,t[e[o(1037)](r,6)]=e[o(1219)](x,8)&255,t[r+7]=e[o(285)](255,x),r+=8,r}function pr(s,t){let r=n;return s[r(435)+"8"]?{value:s.readUInt8(t),offset:e[r(409)](t,1)}:{value:e[r(1495)](255,s[t]),offset:e[r(1006)](t,1)}}function mr(s,t,r){let o=n;return t[o(235)+"t8"]?t[o(235)+"t8"](s,r):t[r]=255&s,e.ziPEH(r,1)}let c0=function(s){return new Uint8Array(s)},x0=e[n(1267)]!=typeof Buffer?Buffer[n(1180)+n(1561)]:e[n(200)](e0,c0,Uint8Array[n(619)+"e"][n(549)]);(()=>{let s=n,t={VSmPE:function(o,x){return e[I(1098)](o,x)},givsK:e[s(484)],zJRrZ:function(o,x){return e[s(662)](o,x)},cARuk:function(o,x){return e[s(472)](o,x)},qtYWS:function(o,x){return e.BETLS(o,x)},EWxzm:function(o,x){return e[s(951)](o,x)},NFVqL:function(o,x){return o>x},fkRFA:function(o,x,f,g){return e.ImadJ(o,x,f,g)},dXypl:function(o,x){return o>>>x},RqlaM:function(o,x){return e.Nrifg(o,x)},QcERc:function(o,x){return e[s(1368)](o,x)},bsEXm:function(o,x){return e[s(327)](o,x)},WjMHz:function(o,x){return o|x},AyQwr:function(o,x){return e.BchnH(o,x)},fWzEZ:function(o,x){return e.taDqx(o,x)},Khhzt:function(o,x){return e[s(913)](o,x)},dYJhv:function(o,x){return e[s(462)](o,x)},GrMiC:function(o,x){return e[s(1289)](o,x)}},r=4294967295;return function(o,x,f=!0){let g=s;if(t.VSmPE(t[g(1412)],t[g(1412)]))this[g(1252)+"Queue"].shift(),this[g(1252)+g(644)][g(299)](_0x208f2d);else{let p=(g(1370)+g(1508)+g(376)+"2")[g(1555)]("|"),l=0;for(;;){switch(p[l++]){case"0":r=t.zJRrZ(t.cARuk(r,t[g(1196)](t.EWxzm(127,o[x]),7)),0);continue;case"1":r=t[g(691)](t[g(282)](r,t[g(1196)](15&o[x],28)),0);continue;case"2":return{value:f?r:t.cARuk(0,r),offset:x};case"3":if(t.NFVqL(x+=5,o[g(475)]))throw x=o.length,t[g(1087)](n0,x,10,o[g(475)]);continue;case"4":r=t.dXypl(t[g(1122)](127,o[x]),0);continue;case"5":r=(r|t[g(310)](127,o[x])<<21)>>>0;continue;case"6":if(t[g(747)](o[x++],128))return{value:f?r:t[g(1150)](0,r),offset:x};continue;case"7":if(t.AyQwr(o[x++],128))return{value:f?r:t.fWzEZ(0,r),offset:x};continue;case"8":if(t[g(747)](o[x++],128))return{value:f?r:t.Khhzt(0,r),offset:x};continue;case"9":if(t.AyQwr(o[x++],128))return{value:f?r:t.WjMHz(0,r),offset:x};continue;case"10":if(t.AyQwr(o[x++],128))return{value:f?r:t.dYJhv(0,r),offset:x};continue;case"11":r=t[g(710)](t[g(478)](r,t[g(1196)](127&o[x],14)),0);continue}break}}}})();let u0=16,wr=32;function d0(s){let t=n,r=0,o={};for(let x=0;e[t(1449)](x,s[t(475)]);x++)o[s[x][t(799)+t(1571)]]=e[t(1073)](Ls,s[x]["cursor_n"+t(1571)]),r+=e[t(761)](14,o[s[x][t(799)+t(1571)]]);return[r,o]}function Ms(s,t,r){let o=n,x={jevxP:e[o(344)],GXOwv:"cursor.s"+o(670),qAHNS:e[o(583)],YONra:function(y,b,k,P){return y(b,k,P)},bkkBp:e.QpbCG,JlVge:function(y,b,k,P){return y(b,k,P)}},[f,g]=e.gatre(d0,s),p=e.LaNwn(x0,f),l=0;return s[o(993)](y=>{let b=o,k=(b(410)+"6|9|0|3|"+b(1228))[b(1555)]("|"),P=0;for(;;){switch(k[P++]){case"0":console[b(901)](x.jevxP,l);continue;case"1":l=r0(p,l,y[b(1488)]||0);continue;case"2":console[b(901)](x[b(1316)],y,y[b(1488)]);continue;case"3":l=i0(y[b(799)+b(1571)],p,l);continue;case"4":console[b(901)]("curvalue",l);continue;case"5":console[b(901)](b(851),l);continue;case"6":console[b(901)](x[b(545)],l);continue;case"7":l=x.YONra(mr,0,p,l);continue;case"8":console[b(901)](x[b(792)],l);continue;case"9":l=x[b(1137)](mr,g[y[b(799)+b(1571)]],p,l);continue;case"10":l=x[b(1475)](a0,q[b(1009)+"er"](y.cursor||t),p,l);continue}break}}),{frameType:wr,headers:[{key:o(608)+o(652),value:r}],payload:p}}function f0(s){let t=n,r=0,o=[];for(;e.EPARj(r,s.byteLength);){let{offset:x}=pr(s,r);r=x;let f={cursor_name:"",cursor:0,service:0},{value:g,offset:p}=e[t(1209)](s0,s,r);f.service=g,r=p;let{value:l,offset:y}=e.EbnyR(pr,s,r);r=y,f[t(799)+t(1571)]=e[t(1437)](Ns,s,r,r+l),r+=l;let{value:b,offset:k}=e[t(228)](o0,s,r);f[t(509)]=b[t(745)](),r=k,o[t(299)](f)}return o}function l0(){let s=n;return{frameType:wr,headers:[{key:e[s(1093)],value:e[s(1054)]}],payload:void 0}}class h0{constructor(t,r,o){let x=n;this[x(1489)+"ameSpace"]=t,this["_cursorF"+x(1358)]=r,this[x(1252)+x(979)]=o,this._qosDB=e.dOXio(Bs,this[x(1489)+x(1352)],e[x(1285)])}async[n(1415)](){await this[n(513)].openDB()}async getCursors(){let t=n;if(!this[t(513)][t(872)])return;let r=this["_message"+t(979)],o=await this[t(513)][t(238)]();switch(console[t(901)](e.ZeCTN,o),r){case e.hbhim:return o&&o[t(475)]?e[t(280)](Ms,o,0,this[t(1305)+t(1358)]):void 0;case e.vcaGo:return;case e[t(1414)]:return o&&o[t(475)]?e[t(1386)](Ms,o,0,this[t(1305)+t(1358)]):e[t(205)](l0)}}async set(t,r,o){let x=n;return console[x(901)](e[x(1101)],t,r,o),this._qosDB.set({cursor_name:t,cursor:r,service:o})}async setCursors(t){let r=n,o=e.uSexe(f0,t);for(let x of o)console.log(e[r(1090)],o),await this[r(513)].set(x)}async[n(798)](t){let r=n;return(await this[r(513)][r(798)](t))?.[r(509)]}async[n(834)](){let t=n;if(e[t(757)](t(1603),e[t(1299)])){if(e.QLnzO(_0xa54ac8.offset+_0x570a18,_0x39cc75.limit))throw new _0x330fc4(t(1470)+t(520));_0x2b507e[t(973)]+=_0x3ea1d8}else await this[t(513)].closeDB()}[n(641)+"rsorFile"+n(373)](t){let r=n;e[r(1353)](e[r(1144)],e[r(762)])?_0x2bb06f[r(901)](_0x2ccfc8):this[r(1305)+r(1358)]=t}get[n(872)](){let t=n;return this[t(513)][t(872)]}}let g0=e[n(453)];async function qs(s){let t=n;if(!this[t(1229)][t(1392)+"S"])return null;let{aID:r,fpID:o,messageStrategy:x}=this[t(1229)],f=e[t(1513)](s,g0);try{return e.jSSii(e[t(863)],e.tZVLH)?this[t(1157)]?e[t(1545)](e[t(1518)](this[t(1335)],0)*_0x25e5d9,e.xFGaT(this[t(263)],0)):e[t(830)](this[t(1335)],_0x40083e)+e[t(943)](this[t(263)],0):(this[t(983)+t(1115)]?s&&this[t(983)+t(1115)][t(641)+t(531)+t(373)](s):this["_cursorM"+t(1115)]=new h0(o+"_"+r+"_"+f,f,x),this["_cursorM"+t(1115)][t(872)]||await this["_cursorM"+t(1115)][t(1415)](),this["_cursorM"+t(1115)])}catch{if(e.esCZA("AzjaK",t(1487)))return null;this[t(513)]?.[t(1151)](_0x58ec50.message_id)}}async function p0(s,t){let r=n,o=e[r(649)](Ue,s[r(584)][r(733)],r(568),"-1"),x=Ue(s[r(584)][r(733)],e[r(499)],"1"),f=ct(s.message[r(733)],e[r(1244)]),g=Number(e[r(1587)](ct,s.message.headers,e[r(1057)]))||0,p=gr[r(556)](this,s),l=e[r(889)](Ue,s.message[r(733)],r(1420)+"s","2"),y=e.tWrVq(ct,s[r(584)].headers,e[r(559)]),b=e[r(1557)](Number,ct(s[r(584)][r(733)],e[r(1486)]));if(p[r(1062)])return t();let k=p[r(1174)+"sage"]?await zs.call(this):null;if(e[r(1293)](s[r(584)][r(1488)],0)&&x&&!o||e[r(1450)](s[r(584)][r(1488)],0)){if(f&&p["isQoSMes"+r(771)]&&k)return!!!await k[r(798)](f)&&(this[r(627)+r(321)+r(514)](s),await k[r(749)](f,e.bMWJl(Date.now(),g))),t();if(l){let P=await qs[r(556)](this);if(!P)return this[r(627)+r(321)+r(514)](s),t();let O=await P[r(798)](y)??-1;if(e[r(1163)](O,b))this[r(627)+r(321)+r(514)](s),P[r(749)](y,b,s[r(584)][r(1488)]);else throw new Error(r(1216)+" message"+r(1451)+b+(" larger "+r(1245)+r(395)+"r ")+O);return t()}return this[r(627)+r(321)+r(514)](s),e.ErETw(t)}}async function m0(s,t){let r=n,o=gr[r(556)](this,s);if(!o[r(1174)+r(771)])return e[r(541)](t);let x=await zs[r(556)](this);if(o[r(614)+r(1404)+r(1436)]&&o[r(1243)+"s"][r(475)])for(let f of o[r(1243)+"s"])await x[r(1151)](f);e[r(1427)](t)}async function w0(s,t){let r=n,o=s[r(584)][r(809)+"e"]===u0,x=e.LBfzH(s[r(584)][r(809)+"e"],wr);if(e[r(1582)](!o,!x))return e[r(1427)](t);let f=ct(s[r(584)][r(733)],e[r(1093)]);if(!f)return e.Nvykj(t);let g=await qs[r(556)](this,f);if(!g)return e[r(1585)](t);if(o){let p=await g[r(930)+"rs"](),l={frameType:p?.[r(809)+"e"],SeqID:q[r(1009)+"er"](this[r(1166)]++),LogID:q[r(1009)+"er"](this[r(1229)].logIDGenerator()),service:9e3,method:5,headers:p?.[r(733)],payload:p?.[r(849)]},y=e[r(1073)](C,l);this[r(1312)]&&this._ws.readyState&&this._ws[r(777)](y)}if(x){let p=s[r(584)][r(849)];p&&g[r(1413)+"rs"](p)}}let _0=async function(s,t){let r=n;this[r(332)]=!1,e[r(588)](clearTimeout,this["_connect"+r(679)+r(1566)]),e[r(1585)](t)},y0=async function(s,t){let r=n;if(e[r(1383)](r(377),e[r(756)])){if(!this[r(1312)]||e[r(284)](this[r(1312)][r(996)+"te"],this[r(543)]))return e[r(333)](t);let{pingInterval:o}=this._options;this["_endpoin"+r(562)]?.[r(1472)+r(1575)+r(1469)]();for(let f=0;e[r(1149)](f,this[r(1252)+r(644)][r(475)]);f++){let g=this[r(1252)+r(644)][f];if(e[r(1552)](this._ws.readyState,this[r(543)])&&e[r(1306)](null,g))this[r(1312)]&&this[r(1312)][r(777)](g),this._messageQueue[f]=null;else break}this[r(1252)+r(644)]=this[r(1252)+r(644)][r(1409)](f=>!!f),this[r(967)+r(1484)+"Id"]=setTimeout(()=>this._ping(),o),this[r(627)+r(1247)+"nt"](s),this[r(1206)+"er"]&&this[r(1312)]&&(this[r(1312)][r(1078)+"pe"]=this[r(814)+"ype"]);let x=this[r(428)+"tManager"]?.["getCurre"+r(946)+"nt"]();this[r(1403)](r(1052)+x+" success"),e[r(333)](t)}else return this[r(513)]?.[r(1151)](_0x4286ad)},v0=async function(s,t){let r=n;if(e[r(1362)](e.JCxEw,r(202))){let o=this[r(428)+r(562)]?.[r(991)+r(946)+"nt"]();this._debug(r(1052)+o),e.iXERT(t)}else try{return!!this._qosDB}catch(o){return _0x473fa0[r(901)](o),!1}};class b0 extends fr{constructor(t){let r=n,o={rHZbZ:function(p,l,y,b){return e[I(1608)](p,l,y,b)},HuHYF:function(p,l){return e[I(1008)](p,l)},XcdOB:r(707),EGIEj:e.dEvME,rIOzj:function(p,l,y){return p(l,y)},gmxkQ:function(p,l,y){return e[r(1178)](p,l,y)},ZGenD:function(p,l){return e.REpne(p,l)},DWPdq:function(p,l){return e[r(711)](p,l)},WLOaY:e.sCTuF,DttCv:e[r(1298)],HiUZR:function(p,l,y){return e[r(706)](p,l,y)},mjFNp:function(p,l){return p!==l},bsWlb:function(p,l,y){return p(l,y)},BORGg:e[r(1028)],PQDHb:e[r(646)],Wacko:function(p,l){return p!==l},OoMzC:function(p,l){return e[r(980)](p,l)},XawwS:function(p,l,y){return p(l,y)},JmojW:function(p,l){return e[r(723)](p,l)},pXlDQ:function(p,l){return e[r(612)](p,l)}};super(),this[r(653)+"igatorOn"+r(254)]=!0,this[r(1206)+"er"]=at,this._isNode=Ma,this[r(683)+"T"]=$e,this._isMiniWX=Pt,this[r(1125)+"r"]=It,this[r(1252)+r(644)]=[],this[r(428)+r(562)]=null,this[r(1236)+"osed"]=!1,this["_binaryT"+r(1393)]=e[r(1528)],this[r(714)+r(912)]=!1,this["_connect"+r(679)+r(1566)]=null,this[r(587)+r(1512)+r(1559)]=null,this[r(967)+r(1484)+"Id"]=null,this._seqId=0,this._isInit=!1,this[r(982)]="",this[r(606)+"ger"]=null,this._cursorManager=null,this[r(842)+r(942)]=null,this[r(469)+"ls"]=r(495),this.CLOSED=3,this.CONNECTING=0,this[r(543)]=1,this[r(432)]=2,this._onOpen=p=>{let l=r,y={CXNsB:function(b){return b()}};try{o[l(778)](Rs,this,p,[_0,y0,v0])}catch(b){if(o.HuHYF(o.XcdOB,"dwHbD")){let k=le(o.EGIEj,{message:b[l(584)],code:Fe[l(672)+"OR"],error:b});this[l(627)+"hErrorEvent"](k)}else this[l(332)]=!1,_0x18b8e9(this["_connect"+l(679)+"utId"]),AVnXim[l(1072)](_0x53773a)}},this._onMessage=async p=>{let l=r,{pingInterval:y,pingFrequency:b}=this[l(1229)];if((e[l(945)]("hi",p[l(860)])&&e[l(730)]===b||e.vGifz(e.WXlkd,b))&&(this[l(229)+l(1119)](),this.emit(l(744)+l(347)+"s",e[l(1350)]),this[l(967)+l(1484)+"Id"]=e.MHDUU(setTimeout,this[l(1336)].bind(this),y)),p[l(860)]!=="hi")try{Rs(this,p,[Qa,Ya,m0,w0,p0,Za])}catch(k){let P=le(e[l(717)],{message:k[l(584)],code:Fe[l(1029)+"ERROR"],error:k});this[l(627)+l(1406)+l(1276)](P)}},this[r(1242)]=p=>{let l=r,y=this[l(428)+l(562)]?.["checkRea"+l(1074)+"es"](),b=this[l(428)+"tManager"]?.[l(991)+l(946)+"nt"]();if(y&&!p[l(584)]){let k=l(1572)+b+(l(955)+l(571)+l(218)+"ed");this[l(627)+l(1406)+l(1276)](o[l(553)](le,o[l(1610)],{message:k,code:Fe["MAX_RETR"+l(718)+"R"],error:p}));return}this[l(1312)]&&o.HuHYF(this[l(1312)][l(996)+"te"],this[l(543)])&&this[l(1171)+l(631)](),this[l(627)+l(1406)+l(1276)](o[l(537)](le,l(1433),{message:p[l(584)],code:Fe["NATIVE_E"+l(532)],error:p}))},this._onClose=async p=>{let l=r,y={rTSOO:function(k,P){return o[I(910)](k,P)},fWyyV:function(k,P){return o.DWPdq(k,P)},dWfwk:l(629),YjaBG:function(k,P){return k!==P},nKXbM:o.WLOaY};this[l(505)+l(337)](),this[l(229)+"ngTimer"](),this[l(819)+l(350)+"rs"](),this[l(1312)]=null,this[l(714)+l(912)]=!1;let b=this[l(428)+"tManager"]?.[l(1241)+l(1074)+"es"]();if(!b&&this[l(340)+l(239)]()&&!this[l(1236)+"osed"])if(o[l(1268)]!==o.DttCv){let{url:k}=y[l(271)](_0x3c9918,{}),P=_0x488808[l(1426)](k)?k:y[l(958)](y[l(1141)],typeof k)?[k]:[];_0x8924d4&&_0x44306e.assign(this._options,_0x5eadfa),P&&P[l(475)]?this["_endpoin"+l(562)]=new _0x1fcc3b(P,this[l(1229)][l(765)+"es"]):this[l(428)+l(562)]?.[l(1472)+l(1575)+l(1469)](),this[l(842)+l(942)]?.[l(617)+l(1599)](this._options[l(1269)+l(572)]),this[l(1236)+"osed"]=!1,this[l(1312)]&&y[l(329)](this[l(1312)].readyState,this[l(1106)])?this[l(1171)+l(631)](1e3,y[l(874)],!0):(this[l(332)]=!0,this[l(714)]())}else{let k=this[l(428)+l(562)]?.[l(991)+l(946)+"nt"](),P=this._options[l(1092)+l(360)+l(317)](p[l(568)],p[l(1138)]);this["_dispatc"+l(1533)+l(1276)](o.HiUZR(me,l(492),{code:1006,reason:p[l(1138)]||l(965)+l(1467)+"d, unkno"+l(461)+"n, hostn"+l(725)+k,willReconnect:P})),P&&this._connect();return}if(o[l(351)](1e3,p[l(568)])&&this[l(1236)+l(1158)]){this[l(627)+l(1533)+l(1276)](o[l(885)](me,o[l(1400)],{code:1e3,reason:o[l(1594)]})),this["_endpoin"+l(562)]?.["resetEnd"+l(1575)+l(1469)](),this[l(842)+l(942)]?.[l(617)+l(1599)]();return}if(o[l(540)](1e3,p[l(568)])&&b){let k=this[l(428)+l(562)]?.["getCurre"+l(946)+"nt"](),P=p.reason;P||(P=await o.OoMzC(Ka,this[l(982)])),P=l(965)+l(1467)+"d, "+P+(l(1569)+l(528))+k+(", max retries re"+l(1250)),this[l(627)+"hCloseEv"+l(1276)](o[l(537)](me,o[l(1400)],{code:p[l(568)],reason:P}));let O="connect "+k+(l(955)+l(571)+l(218)+"ed");this._dispatchErrorEvent(o[l(780)](le,o[l(1610)],{message:O,code:Fe[l(585)+"IES_ERROR"]})),this[l(428)+l(562)]?.[l(1472)+l(1575)+l(1469)](),this["_pingLos"+l(942)]?.["resetCou"+l(1599)]();return}if(p[l(568)]!==1e3&&!p[l(1138)]){let k=this[l(428)+l(562)]?.[l(991)+"ntEndpoint"]();this["_dispatc"+l(1533)+l(1276)](o[l(553)](me,o[l(1400)],{code:p.code,reason:l(965)+l(1467)+l(1227)+"wn reason, hostname: "+k})),this[l(428)+l(562)]?.[l(1472)+"pointConfig"](),this[l(842)+"sCounter"]?.resetCounter();return}this[l(627)+l(1533)+"ent"](p),this._endpointManager?.[l(1472)+l(1575)+l(1469)](),this[l(842)+l(942)]?.resetCounter()},this[r(1355)]=null,this[r(681)]=null,this[r(1026)+"e"]=null,this.onopen=null,this[r(848)+"econnect"]=null,this[r(438)+r(255)]=null,this[r(529)+r(346)+r(1013)+"ct"]=null,this[r(256)+r(1344)]=this[r(256)+r(1344)][r(856)](this),this[r(256)+r(1590)]=this[r(256)+r(1590)].bind(this),this[r(1435)+r(1199)]=this[r(1435)+"ageHide"].bind(this),this[r(1435)+r(564)]=this[r(1435)+r(564)][r(856)](this),this[r(1229)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[r(289)](1,0),service:0,logIDGenerator:c,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e.WXlkd,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[r(1414)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:f}=t,g=Array[r(1426)](x)?x:e[r(915)](e[r(593)],typeof x)?[x]:[];if(!g||g.length===0)throw new Error(e[r(217)]);if(!e[r(1460)](Ua,f))throw new Error(e[r(1081)]);if(Object.assign(this[r(1229)],t),this[r(428)+r(562)]=new Ds(g,this[r(1229)].maxRetries),this[r(842)+r(942)]=new ja(this[r(1229)][r(1269)+"Count"]),this[r(1229)][r(971)+r(1230)]&&(this[r(332)]=!0,this[r(714)]()),this[r(1229)]["listenNe"+r(417)+r(801)])if(e.YUpIe===e[r(358)])this[r(683)+"T"]||this[r(209)+"X"]?this[r(1464)+"etWorkCh"+r(1047)]():this[r(1206)+"er"]&&this[r(960)+"balEvent"+r(535)]();else{let{initReconnectInterval:p,maxReconnectInterval:l,reconnectIntervalGrowFactor:y}=this._options,b=o.JmojW(p,_0x119df7.pow(y,o[r(977)](_0x1b7319,1)));return b>l?l:b}}[n(256)+n(1344)](){let t=n,r={gyBZU:e.NOHBw};if(e.daXxc(e.tmoAB,e[t(1185)]))this[t(1539)](ivDUau[t(1382)],_0x408968("message",{..._0x412f82}));else{if(this._options["disableA"+t(1172)+t(900)]||this["_readyCl"+t(1158)])return;this[t(728)+t(1001)]()}}[n(256)+"ffLine"](){let t=n;this[t(1179)+"WebSocket"]();let r=e.fHdTX(dr,e[t(508)],{message:e.briCO});this[t(529)+t(346)+"yReconnect"]&&this[t(529)+t(346)+"yReconnect"](r)}["_initGlo"+n(1446)+n(535)](){let t=n;this[t(1206)+"er"]&&window[t(1004)+t(535)](e[t(877)],this[t(256)+"nLine"]),this._isBrowser&&window[t(1004)+t(535)](e.hplJq,this[t(256)+t(1590)]),this[t(1206)+"er"]&&window["addEvent"+t(535)](e[t(380)],this[t(1435)+t(1199)]),this[t(1206)+"er"]&&window["addEvent"+t(535)](e[t(307)],this[t(1435)+t(564)])}[n(919)+"balEvent"+n(535)](){let t=n;this[t(1206)+"er"]&&window[t(1429)+t(1466)+t(1538)]("online",this["_handleO"+t(1344)]),this[t(1206)+"er"]&&window[t(1429)+"entListe"+t(1538)](e[t(648)],this["_handleO"+t(1590)]),this[t(1206)+"er"]&&window[t(1429)+t(1466)+t(1538)](e[t(380)],this._handlePageHide),this[t(1206)+"er"]&&window[t(1429)+t(1466)+t(1538)](e[t(307)],this._handlePageShow)}[n(1435)+n(1199)](t){let r=n;if(e[r(355)]===e[r(355)])!t[r(243)+"d"]&&(this[r(1206)+"er"]&&window[r(1429)+r(1466)+r(1538)](r(1493),this[r(1435)+r(1199)]),this[r(1206)+"er"]&&window[r(1429)+r(1466)+r(1538)](r(1189),this[r(1435)+"ageShow"]),this.close()),this[r(1206)+"er"]&&window[r(1429)+"entListe"+r(1538)](r(1152),this[r(256)+r(1344)]),this[r(1206)+"er"]&&window[r(1429)+r(1466)+r(1538)](e[r(648)],this["_handleO"+r(1590)]);else return this[r(1312)]?this[r(1312)][r(996)+"te"]:this._options[r(971)+r(1230)]?this[r(539)+"NG"]:this.CLOSED}[n(1435)+n(564)](t){let r=n;t.persisted&&(this["_navigat"+r(239)]()&&(!this[r(1312)]||e.gXmSw(this[r(1312)].readyState,this[r(543)])||e.yoXcr(this[r(1312)][r(996)+"te"],this[r(539)+"NG"]))&&this[r(256)+r(1344)](),this._isBrowser&&window[r(1004)+r(535)](r(1152),this[r(256)+r(1344)]),this[r(1206)+"er"]&&window[r(1004)+r(535)](e[r(648)],this["_handleO"+r(1590)]))}async[n(1325)+n(656)](t){let r=n,{fpID:o,deviceID:x,bddID:f,ttwID:g,accessKey:p,aID:l,customParams:y={},enableAutoAck:b,enableQoS:k,QoSLevel:P,env:O}=this._options,N,ee,ce;this[r(1206)+"er"]||this._isMiniWX||this[r(683)+"T"]?(N=location&&e.nFwDz(e[r(503)],location[r(673)])?e[r(343)]:e[r(1186)],ee=t[r(1116)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ce=/^wss(.*:\/\/)/[r(881)](t)?t:""+N+ee):(N=e.HdRBV,ee=t[r(1116)](/(^http)((?:[s]*:\/\/))/,""),ce=/(^ws)((?:[s]*:\/\/))/[r(881)](ee)?ee:""+N+ee);let Ye=f?e[r(389)]:g?e[r(954)]:e[r(1468)],Tt=f||g||x;if(e.ckhfI(!Tt,!Ye))throw new Error(e.UCNfm);let S0=e.uaODF(e[r(659)],typeof y)?await e[r(1585)](y):y,E0=O?e[r(887)](Ga,O[r(735)],O[r(701)]):{},_r=Object.assign({device_platform:e[r(267)],version_code:r(430)+"0",access_key:p,fpid:o,aid:l,[Ye]:Tt,xsack:b?1:0,xaack:b?1:0,xsqos:k?1:0,qos_level:k?P:void 0,qos_sdk_version:2,...E0},S0),C0=Object.keys(_r).reduce((yr,vr)=>_r[vr]!==void 0?""+yr+(yr?"&":"?")+vr+"="+_r[vr]:yr,"");return ce+"/ws/v2"+C0}async _connect(){let t=n;if(!(this[t(714)+"Lock"]||this[t(1236)+t(1158)])){this[t(714)+t(912)]=!0;try{let r=this[t(428)+t(562)]?.[t(1491)+t(1177)+t(1281)+"hedMaxRetries"](),{timeoutInterval:o}=this._options;if(r){let f=this[t(428)+t(562)]?.[t(991)+t(946)+"nt"](),g=this[t(428)+t(562)]?.["replaceB"+t(210)+t(804)+t(563)+t(419)](),p=this[t(428)+t(562)]?.[t(991)+t(946)+t(987)+t(302)]();if(g){let l="connect "+f+(t(637)+t(636)+t(857)+t(216)+"ill use "+t(692)+t(1321))+g+(t(879)+"y"),y=le(e[t(717)],{message:l,code:Fe["MAX_RETR"+t(718)+"R"]});this[t(1403)](l),this[t(627)+"hErrorEvent"](y),this._url=await this["_generat"+t(656)](g),this[t(1403)](t(1572)+g+" "+p+t(1175)),this[t(819)+t(350)+"rs"]()}else if(e[t(592)](e[t(737)],e.NCBUl)){let l=t(1572)+f+(t(637)+t(636)+t(857)+t(1250));this[t(1403)](l),this[t(627)+t(1406)+t(1276)](e[t(706)](le,e[t(717)],{message:l,code:Fe[t(585)+"IES_ERROR"]}));return}else{let l=_0xddd3be[t(1190)+"g"](0,e[t(236)](4,_0x437e20[_0xec1fb1][t(475)])),y=l.concat(_0x20ca5d);_0x51f33c=_0x5b076b[t(605)](y)}}else{let f=this[t(428)+t(562)]?.[t(991)+t(946)+t(1473)+"ateCount"](),g=this[t(428)+t(562)]?.["getCurre"+t(946)+t(987)+t(302)]();this[t(982)]=await this[t(1325)+t(656)](e.YmmwQ(f,"")),this[t(1403)](t(1572)+f+" "+g+" times"),this[t(819)+t(350)+"rs"]()}if(this[t(332)])this._isInit=!1;else{let f=e[t(925)](dr,e[t(508)],{message:e[t(1456)]});this[t(848)+t(1001)]&&this[t(848)+t(1001)](f)}let x=this[t(428)+"tManager"]?.[t(991)+t(946)+t(987)+t(302)]()||0;e[t(1124)](x,1)&&await this[t(1410)](e[t(407)](x,1)),this[t(1403)](t(965)+t(978)+this[t(982)]+(t(836)+t(353))+this._protocols),this[t(1312)]=e[t(999)](Fa,{url:this[t(982)],protocols:[this._protocols],headers:this[t(1229)].miniProgramParams["customHt"+t(1613)]},this[t(1229)].ws),(this[t(1206)+"er"]||this[t(1125)+"r"])&&this[t(1312)]&&(this[t(1312)].binaryType=this[t(814)+t(1393)]),this["_addWsLi"+t(995)](),this["_connect"+t(679)+t(1566)]=e[t(1203)](setTimeout,this[t(1522)+"ut"].bind(this),o)}catch(r){throw this[t(714)+t(912)]=!1,r}}}[n(505)+"mer"](){let t=n;clearTimeout(this[t(714)+t(679)+t(1566)]),this["_connect"+t(679)+t(1566)]=null}[n(229)+"ngTimer"](){let t=n;e[t(896)](clearTimeout,this[t(967)+t(1484)+"Id"]),e[t(1455)](clearTimeout,this[t(587)+t(1512)+t(1559)]),this[t(967)+t(1484)+"Id"]=null,this[t(587)+t(1512)+t(1559)]=null}[n(1403)](...t){let r=n;this[r(1229)][r(464)]&&console.log[r(1445)](console,[e[r(330)],...t])}[n(1191)+"rvalValue"](t){let r=n,{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:f}=this[r(1229)],g=e.hjQsn(o,Math.pow(f,e.kAGGA(t,1)));return e.DKIzk(g,x)?x:g}[n(1336)](){let t=n;if(this._ws&&this._ws.readyState===this.CONNECTING){this["_clearPi"+t(1119)](),this[t(967)+t(1484)+"Id"]=setTimeout(this[t(1336)].bind(this),this[t(1229)].pingInterval);return}if(!this[t(1312)]||e[t(893)](this._ws[t(996)+"te"],this[t(543)]))return void this["_handleR"+t(1001)]();this[t(1312)]&&this[t(1312)][t(777)]("hi"),this[t(587)+t(1512)+"tId"]=setTimeout(this["_handleR"+t(1001)+t(278)].bind(this),this[t(1229)][t(853)+"outInter"+t(682)])}[n(728)+n(1001)+"Timeout"](){let t=n;this[t(842)+t(942)]?.addCount(),this.emit(e[t(1025)],e.ymhzZ),this[t(842)+t(942)]?.["checkRea"+t(1379)+"nt"]()?this[t(728)+t(1001)]():this[t(1336)]()}[n(340)+"orOnline"](){let t=n;return this._isMiniTT||this[t(209)+"X"]?this[t(653)+t(1232)+t(254)]:(this[t(1206)+"er"]||this[t(1125)+"r"])&&this[t(1229)][t(832)+t(417)+t(801)]?navigator[t(374)]:!0}[n(728)+"econnect"](){let t=n,r={FZRFD:function(o,x){return e[I(1431)](o,x)},HFgTn:function(o,x){return o&x},oTPfz:function(o,x){return e[I(1198)](o,x)},qsRhF:function(o,x){return e.dhnal(o,x)}};if(e.nMxKR(t(1262),"vGzGo"))_0x415c5d[_0x4142fc++]=aKxVmr[t(1154)](aKxVmr[t(445)](aKxVmr[t(1367)](_0x4307bb,18),7),240),_0x586e49[_0x1da109++]=aKxVmr[t(1521)](_0x42eacb>>12&63,128);else{if(!this[t(340)+t(239)]()||this[t(1236)+t(1158)])return;this[t(428)+t(562)]?.["resetEnd"+t(1575)+"fig"](),this["_pingLos"+t(942)]?.[t(617)+"nter"](),this[t(1312)]?this._disconnect(1001,e[t(632)],!0):this[t(714)]()}}[n(1464)+n(927)+n(1047)](){let t=n,r={FkRgB:function(o,x,f){return e[I(456)](o,x,f)},PCaMS:function(o,x){return e[I(247)](o,x)},sjFEt:t(1389)};this._isMiniTT?tt[t(420)+t(1347)+"hange"](({isConnected:o})=>{let x=t;this[x(653)+x(1232)+x(254)]=o,o?this[x(256)+x(1344)]():this["_handleO"+x(1590)]()}):this[t(209)+"X"]&&wx[t(420)+t(1347)+t(1034)](({isConnected:o})=>{let x=t,f={RteiY:function(g,p,l){return r.FkRgB(g,p,l)}};r[x(687)](r[x(1048)],r[x(1048)])?(this[x(653)+x(1232)+x(254)]=o,o?this[x(256)+"nLine"]():this["_handleO"+x(1590)]()):(QaKrKV[x(808)](_0x2ef4d8,_0x426db0,10),QaKrKV[x(808)](_0x332990,_0x29c224,_0x3a5aeb))})}[n(1410)](t){let r={zpkNO:function(o,x,f){return o(x,f)}};return new Promise(o=>{let x=I;r[x(601)](setTimeout,o,this[x(1191)+x(1258)+"e"](t))})}[n(1171)+"ect"](t=1e3,r="",o=!1){let x=n;this[x(1312)]&&this[x(1179)+"WebSocket"](t,r,o)}[n(1522)+"ut"](){let t=n,r={BdHDs:function(o,x){return e[I(1198)](o,x)},vNEFj:function(o,x){return e[I(1319)](o,x)}};if(e[t(803)](e.hynMe,e[t(357)]))return _0x2ee753|=0,{low:_0x1b9e43,high:prQRgg[t(944)](_0x12df43,31),unsigned:prQRgg[t(929)](_0x386acb,0)};{let o=this[t(428)+"tManager"]?.[t(991)+t(946)+"nt"]();this[t(1403)](t(1572)+o+" timeout"),this[t(1171)+t(631)](1001,e.HJQkY,!0)}}[n(1097)](t){let r=n,o=e[r(1448)](ur,t);this[r(1312)]&&e[r(382)](this[r(1312)][r(996)+"te"],this[r(543)])&&(this[r(1312)]&&this._ws[r(777)](o),this[r(1403)](e[r(1286)],t))}[n(819)+n(350)+"rs"](){let t=n;this[t(1312)]&&(this._ws[t(1429)+"entListe"+t(1538)](e[t(802)],this[t(1432)]),this._ws[t(1429)+t(1466)+t(1538)](e[t(1028)],this[t(506)]),this[t(1312)]["removeEv"+t(1466)+"ner"](t(584),this[t(825)+"ge"]),this[t(1312)][t(1429)+"entListener"]("error",this._onError))}[n(1465)+n(995)](){let t=n,r=(t(485)+"1")[t(1555)]("|"),o=0;for(;;){switch(r[o++]){case"0":this[t(1312)]["addEvent"+t(535)](e[t(1234)],this[t(825)+"ge"]);continue;case"1":this[t(1312)]["addEvent"+t(535)](e[t(717)],this[t(1242)]);continue;case"2":this[t(1312)][t(1004)+t(535)](e[t(1028)],this[t(506)]);continue;case"3":this[t(1312)]["addEvent"+t(535)](e[t(802)],this[t(1432)]);continue;case"4":if(!this[t(1312)])return;continue}break}}[n(1128)+n(721)](t=1e3,r=""){let o=n;if(e.HQnIN("qrBQX",e[o(923)]))this[o(1462)]=_0x47e3a8,this[o(731)]=null;else try{this[o(1312)]&&this[o(1312)].close(t,r)}catch{}}[n(1179)+n(488)+"t"](t=1e3,r="",o=!1){let x=n;if(e.UTHTd!==e.UTHTd)_0x43b969&&_0x44c77a[x(1004)+x(535)](dAdEYp[x(1028)],()=>_0x51c61d()),_0x32f8e8&&_0x3cde19[x(1004)+x(535)](x(1452)+"hange",()=>_0xf46f00());else{if(this[x(229)+x(1119)](),this[x(505)+x(337)](),this["_removeW"+x(350)+"rs"](),this[x(1128)+x(721)](1e3,r),this[x(714)+x(912)]=!1,o&&this[x(340)+x(239)]()&&!this["_readyCl"+x(1158)]){if(this[x(428)+"tManager"]?.checkReachMaxTries()){let g=this[x(428)+"tManager"]?.[x(991)+"ntEndpoint"]();this[x(627)+x(1533)+"ent"](e.BGoho(me,e[x(1028)],{code:1006,reason:x(1572)+g+(x(637)+x(636)+x(857)+x(1250)),wasClean:!0}))}else{let g=this[x(1229)]["reconnec"+x(360)+"ptor"](t,r);this[x(627)+x(1533)+x(1276)](me(x(492),{code:t,reason:r,wasClean:!0,willReconnect:g})),g&&this[x(714)]()}return}this[x(340)+"orOnline"]()||this[x(1236)+"osed"]?this[x(627)+x(1533)+"ent"](me(e[x(1028)],{code:t,reason:e.WZqRd})):this[x(627)+x(1533)+x(1276)](e[x(1e3)](me,"close",{code:1006,reason:e[x(1516)]})),this._ws=null,this[x(428)+x(562)]?.[x(1472)+x(1575)+"fig"](),this[x(842)+x(942)]?.[x(617)+x(1599)]()}}[n(627)+n(1247)+"nt"](t){let r=n;this[r(1539)](e[r(802)],t),this[r(1359)]&&this[r(1359)](t)}["_dispatc"+n(321)+n(514)](t){let r=n;this.emit(e[r(1234)],t),this[r(1026)+"e"]&&this.onmessage(t)}[n(627)+n(1127)+n(660)](t){let r=n;this.emit("ack",t),this[r(438)+"eAck"]&&this[r(438)+r(255)](t)}["_dispatc"+n(1406)+n(1276)](t){let r=n;this[r(1539)](e.dEvME,t),this[r(681)]&&this[r(681)](t)}[n(627)+n(1533)+n(1276)](t){let r=n;this[r(1539)](e[r(1028)],t),this.onclose&&this.onclose(t)}get[n(1078)+"pe"](){let t=n;return this[t(1312)]?this[t(1312)][t(1078)+"pe"]:this[t(814)+"ype"]}set[n(1078)+"pe"](t){let r=n;this[r(814)+"ype"]=t,this[r(1312)]&&(this[r(1312)][r(1078)+"pe"]=t)}get[n(1527)+"nt"](){let t=n;if(e[t(439)]===e[t(984)])_0x483265[t(677)][t(1159)+t(1397)](_0x108672);else return this[t(428)+t(562)]?.["getCurre"+t(946)+t(987)+t(302)]()||0}get[n(276)+n(831)](){let t=n;return this[t(1252)+"Queue"][t(211)]((o,x)=>(o+=x&&x[t(671)+"th"]||0,o),0)+(this[t(1312)]?this[t(1312)]["buffered"+t(831)]:0)}get[n(828)+"ns"](){let t=n;return this[t(1312)]?this[t(1312)][t(828)+"ns"]:""}get[n(673)](){let t=n;return this[t(1312)]?this[t(1312)].protocol:""}get[n(996)+"te"](){let t=n;return this[t(1312)]?this[t(1312)].readyState:this[t(1229)][t(971)+"cOpen"]?this[t(539)+"NG"]:this[t(1106)]}get[n(558)](){let t=n;return this[t(1312)]?this[t(1312)][t(558)]:this[t(982)]}close(t=1e3,r){let o=n,x=e[o(298)].split("|"),f=0;for(;;){switch(x[f++]){case"0":this[o(1179)+o(488)+"t"](t,r);continue;case"1":this[o(505)+o(337)]();continue;case"2":if(this[o(1312)][o(996)+"te"]===this[o(1106)]||e[o(952)](this._ws[o(996)+"te"],this[o(432)]))return void this[o(1403)](o(689)+o(518)+o(525));continue;case"3":this["_dropGlo"+o(1446)+o(535)]();continue;case"4":this[o(606)+o(664)]?.[o(834)]();continue;case"5":if(!this[o(1312)])return void this._debug(e[o(1542)]);continue;case"6":this[o(1236)+o(1158)]=!0;continue;case"7":this["_clearPi"+o(1119)]();continue}break}}async send(t,r){let o=n,x={PYHiS:function(ce,Ye){return e.cUEHy(ce,Ye)}};if(t==null)throw new Error(e[o(665)]);e[o(555)](e[o(974)],typeof t)&&(t=JSON[o(315)+"y"](t)),e[o(433)](e[o(593)],typeof t)&&!e[o(622)](t,ArrayBuffer)&&!(t[o(265)]&&e[o(1292)](t[o(265)],ArrayBuffer))&&(t=JSON.stringify(t));let f=await e[o(1461)](Os,t),g=e[o(415)](Ha,t),{method:p=0,service:l=this[o(1229)][o(1488)],logID:y=this[o(1229)][o(326)+o(486)](),headers:b=this._options[o(733)],payloadEncoding:k=this[o(1229)][o(674)+o(1373)],payloadType:P=this._options[o(551)+o(1393)],logIDNew:O=this[o(1229)]["logIDNew"+o(1222)]["enableAutoGenera"+o(1591)+"ew"]?e.lZeUQ(a,this[o(1229)][o(1596)+o(1222)][o(1053)]):""}=e.yeeOb(r,{});if(!l)throw new Error(o(257)+o(1540)+o(1105)+o(670));let N={SeqID:q.fromNumber(this[o(1166)]++),LogID:q[o(1009)+"er"](y),service:l,method:p,headers:b,payloadEncoding:e[o(862)](k,Object)?k[o(1003)]?k.encoding:"":k,payloadType:e.guGJA(P,Object)?P[o(1462)]?P[o(1462)]:g:P||g,payload:f,LogIDNew:O},ee=e[o(685)](ur,N);if(this._ws&&e.GaVRM(this[o(1312)][o(996)+"te"],this[o(543)]))if(e[o(1024)]===e[o(1024)])this[o(1312)]&&this[o(1312)][o(777)](ee),this[o(1403)](o(1331),N);else return this[o(1312)]?this._ws[o(1078)+"pe"]:this[o(814)+o(1393)];else if(e[o(1149)](this._messageQueue[o(475)],this[o(1229)][o(666)+"geQueueL"+o(412)]))this[o(1252)+"Queue"][o(299)](ee),this[o(1403)](o(401),N);else if(e[o(726)](e[o(1212)],e.jdDOe))this["_message"+o(644)][o(1457)](),this[o(1252)+o(644)].push(ee);else{let ce=this[o(1252)+o(644)].reduce((Ye,Tt)=>(Ye+=Tt&&Tt.byteLength||0,Ye),0);return BXnLRT[o(654)](ce,this._ws?this._ws[o(276)+o(831)]:0)}return{seqID:this[o(1166)],logID:y,logIDNew:O}}async[n(1092)+"t"](t){let r=n,{url:o}=t||{},x=Array[r(1426)](o)?o:e[r(369)](e[r(593)],typeof o)?[o]:[];t&&Object[r(542)](this[r(1229)],t),x&&x.length?this[r(428)+r(562)]=new Ds(x,this[r(1229)][r(765)+"es"]):this[r(428)+"tManager"]?.["resetEndpointCon"+r(1469)](),this[r(842)+r(942)]?.["resetCou"+r(1599)](this[r(1229)].pingLossCount),this[r(1236)+"osed"]=!1,this[r(1312)]&&e.tfhQN(this[r(1312)][r(996)+"te"],this[r(1106)])?this[r(1171)+"ect"](1e3,e[r(244)],!0):(this[r(332)]=!0,this[r(714)]())}async[n(782)](){let t=n,r={SgWay:t(798),DQQQl:e.ukyxP,EGkkW:e[t(1214)],krKhb:e[t(1187)],SjnZH:e.yDovM,GFLxc:function(o){return o()},vwJhV:e[t(696)],ziLzo:function(o,x){return e.dDvTx(o,x)}};if(!this[t(714)+t(912)])if(e[t(871)]!==e[t(751)]){let o=(t(935)+"4")[t(1555)]("|"),x=0;for(;;){switch(o[x++]){case"0":this[t(1236)+t(1158)]=!1;continue;case"1":this["_pingLos"+t(942)]?.[t(617)+t(1599)]();continue;case"2":this["_endpoin"+t(562)]?.[t(1472)+"pointCon"+t(1469)]();continue;case"3":this._isInit=!0;continue;case"4":this[t(714)]();continue}break}}else{let o=("3|2|0|4|"+t(1361))[t(1555)]("|"),x=0;for(;;){switch(o[x++]){case"0":_0x5a3589=[cgVXBp[t(981)],cgVXBp[t(387)],cgVXBp[t(287)],cgVXBp[t(1020)],cgVXBp[t(286)]];continue;case"1":_0x506528=new _0x425676;continue;case"2":cgVXBp[t(604)](_0x53b46b);continue;case"3":_0x267f78();continue;case"4":_0x24f9fe=[cgVXBp.vwJhV,t(356),"delete","clear"];continue;case"5":cgVXBp[t(515)](_0x106970,f=>({...f,get:(g,p,l)=>_0x5adb42(g,p)||f[t(798)](g,p,l),has:(g,p)=>!!_0x5e6b06(g,p)||f[t(686)](g,p)}));continue}break}}}[n(1004)+"Listener"](t,r){let o=n,x={BHWxx:function(g,p,l,y){return e[I(649)](g,p,l,y)}};if(e[o(375)](e.uIEkz,e.uIEkz))this.on(t,r);else for(var f in _0x2d9f71)XThEDT[o(1411)](_0xa25cd0,_0x107018,f,{get:_0x1540c9[f],enumerable:!0})}[n(246)+n(514)](t){let r=n,{type:o}=t;this[r(1539)](o,t)}[n(1429)+n(1466)+n(1538)](t,r){this.off(t,r)}[n(368)](){let t=n,r={diwUW:function(o,x){return e[I(248)](o,x)},ZlmJk:e.ymhzZ,NOCpK:"ping_onc"+t(994)+"t",NAKlr:t(829),AxIhS:function(o,x,f){return o(x,f)},QhvFw:t(744)+t(347)+"s"};return new Promise((o,x)=>{let f=t,g={GtGJf:function(y,b){return r[I(1375)](y,b)},dGywZ:r[f(1503)]};this[f(229)+"ngTimer"](),this["_pingPon"+f(1484)+"Id"]=r.AxIhS(setTimeout,this[f(1336)].bind(this),this[f(1229)]["pingInte"+f(1570)]);let p=()=>{let y=f;g.GtGJf(o,g.dGywZ),this[y(1471)](y(744)+"e_success",p),this[y(1471)](y(744)+"e_timeout",l)},l=()=>{let y=f;r[y(1375)](x,r[y(1363)]),this.off(y(744)+y(347)+"s",p),this.off(r.NOCpK,l)};this.on(r[f(474)],p),this.on(r[f(1005)],l),this._ping()})}}})(),Z[S(736)+S(1211)]=X[S(736)+S(1211)],Z[S(1485)+S(1071)]=X[S(1485)+S(1071)],Z[S(697)+"e"]=X[S(697)+"e"],Z[S(514)]=X[S(514)],Z[S(1164)]=X[S(1164)],Z[S(455)+S(1279)+"vent"]=X[S(455)+S(1279)+"vent"],Z[S(1279)+S(1086)]=X[S(1279)+"vent"],Z.OpenEvent=X[S(640)+"t"],Z["Reconnec"+S(1265)]=X[S(609)+S(1265)],Z[S(1217)+S(1211)]=X[S(1217)+S(1211)],Z[S(1255)+"rorEvent"]=X.createErrorEvent,Z["createMe"+S(835)+"nt"]=X[S(1131)+S(835)+"nt"],Z[S(940)+S(367)]=X["createOp"+S(367)],Z[S(527)+S(1318)+S(1086)]=X[S(527)+S(1318)+"vent"],Z["decodedF"+S(1294)]=X[S(703)+"rame"],Z[S(947)+S(1571)]=X[S(947)+"ame"];for(Ln in X)[S(736)+S(1211),S(1485)+S(1071),S(697)+"e",S(514),S(1164),S(455)+S(1279)+S(1086),S(1279)+S(1086),"OpenEvent","Reconnec"+S(1265),S(1217)+S(1211),S(1255)+S(1071),"createMe"+S(835)+"nt",S(940)+S(367),"createRe"+S(1318)+S(1086),"decodedF"+S(1294),S(947)+"ame"][S(755)](Ln)===-1&&(Z[Ln]=X[Ln]);var Ln;Object[S(1239)+S(1215)](Z,S(252)+"le",{value:!0})});var Oe=xe((vg,io)=>{"use strict";var ro=["nodebuffer","arraybuffer","fragments"],so=typeof Blob<"u";so&&ro.push("blob");io.exports={BINARY_TYPES:ro,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:so,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var jt=xe((bg,Fn)=>{"use strict";var{EMPTY_BUFFER:Xx}=Oe(),Mr=Buffer[Symbol.species];function $x(n,e){if(n.length===0)return Xx;if(n.length===1)return n[0];let i=Buffer.allocUnsafe(e),a=0;for(let c=0;c<n.length;c++){let u=n[c];i.set(u,a),a+=u.length}return a<e?new Mr(i.buffer,i.byteOffset,a):i}function oo(n,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=n[u]^e[u&3]}function ao(n,e){for(let i=0;i<n.length;i++)n[i]^=e[i&3]}function Yx(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function qr(n){if(qr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Mr(n):ArrayBuffer.isView(n)?e=new Mr(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),qr.readOnly=!1),e}Fn.exports={concat:$x,mask:oo,toArrayBuffer:Yx,toBuffer:qr,unmask:ao};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=V("bufferutil");Fn.exports.mask=function(e,i,a,c,u){u<48?oo(e,i,a,c,u):n.mask(e,i,a,c,u)},Fn.exports.unmask=function(e,i){e.length<32?ao(e,i):n.unmask(e,i)}}catch{}});var uo=xe((Sg,xo)=>{"use strict";var co=Symbol("kDone"),Fr=Symbol("kRun"),Ur=class{constructor(e){this[co]=()=>{this.pending--,this[Fr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Fr]()}[Fr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[co])}}};xo.exports=Ur});var _t=xe((Eg,go)=>{"use strict";var Kt=V("zlib"),fo=jt(),Zx=uo(),{kStatusCode:lo}=Oe(),Qx=Buffer[Symbol.species],eu=Buffer.from([0,0,255,255]),Hn=Symbol("permessage-deflate"),Be=Symbol("total-length"),mt=Symbol("callback"),We=Symbol("buffers"),wt=Symbol("error"),Un,Hr=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Un){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Un=new Zx(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[mt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let i=this._options,a=e.find(c=>!(i.serverNoContextTakeover===!1&&c.server_no_context_takeover||c.server_max_window_bits&&(i.serverMaxWindowBits===!1||typeof i.serverMaxWindowBits=="number"&&i.serverMaxWindowBits>c.server_max_window_bits)||typeof i.clientMaxWindowBits=="number"&&!c.client_max_window_bits));if(!a)throw new Error("None of the extension offers can be accepted");return i.serverNoContextTakeover&&(a.server_no_context_takeover=!0),i.clientNoContextTakeover&&(a.client_no_context_takeover=!0),typeof i.serverMaxWindowBits=="number"&&(a.server_max_window_bits=i.serverMaxWindowBits),typeof i.clientMaxWindowBits=="number"?a.client_max_window_bits=i.clientMaxWindowBits:(a.client_max_window_bits===!0||i.clientMaxWindowBits===!1)&&delete a.client_max_window_bits,a}acceptAsClient(e){let i=e[0];if(this._options.clientNoContextTakeover===!1&&i.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!i.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(i.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&i.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return i}normalizeParams(e){return e.forEach(i=>{Object.keys(i).forEach(a=>{let c=i[a];if(c.length>1)throw new Error(`Parameter "${a}" must have only a single value`);if(c=c[0],a==="client_max_window_bits"){if(c!==!0){let u=+c;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${c}`);c=u}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${a}": ${c}`)}else if(a==="server_max_window_bits"){let u=+c;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${c}`);c=u}else if(a==="client_no_context_takeover"||a==="server_no_context_takeover"){if(c!==!0)throw new TypeError(`Invalid value for parameter "${a}": ${c}`)}else throw new Error(`Unknown parameter "${a}"`);i[a]=c})}),e}decompress(e,i,a){Un.add(c=>{this._decompress(e,i,(u,d)=>{c(),a(u,d)})})}compress(e,i,a){Un.add(c=>{this._compress(e,i,(u,d)=>{c(),a(u,d)})})}_decompress(e,i,a){let c=this._isServer?"client":"server";if(!this._inflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Kt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Hn]=this,this._inflate[Be]=0,this._inflate[We]=[],this._inflate.on("error",nu),this._inflate.on("data",ho)}this._inflate[mt]=a,this._inflate.write(e),i&&this._inflate.write(eu),this._inflate.flush(()=>{let u=this._inflate[wt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=fo.concat(this._inflate[We],this._inflate[Be]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Be]=0,this._inflate[We]=[],i&&this.params[`${c}_no_context_takeover`]&&this._inflate.reset()),a(null,d)})}_compress(e,i,a){let c=this._isServer?"server":"client";if(!this._deflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Kt.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Kt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Be]=0,this._deflate[We]=[],this._deflate.on("data",tu)}this._deflate[mt]=a,this._deflate.write(e),this._deflate.flush(Kt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=fo.concat(this._deflate[We],this._deflate[Be]);i&&(u=new Qx(u.buffer,u.byteOffset,u.length-4)),this._deflate[mt]=null,this._deflate[Be]=0,this._deflate[We]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};go.exports=Hr;function tu(n){this[We].push(n),this[Be]+=n.length}function ho(n){if(this[Be]+=n.length,this[Hn]._maxPayload<1||this[Be]<=this[Hn]._maxPayload){this[We].push(n);return}this[wt]=new RangeError("Max payload size exceeded"),this[wt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[wt][lo]=1009,this.removeListener("data",ho),this.reset()}function nu(n){if(this[Hn]._inflate=null,this[wt]){this[mt](this[wt]);return}n[lo]=1007,this[mt](n)}});var yt=xe((Cg,Gn)=>{"use strict";var{isUtf8:po}=V("buffer"),{hasBlob:ru}=Oe(),su=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function iu(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Gr(n){let e=n.length,i=0;for(;i<e;)if((n[i]&128)===0)i++;else if((n[i]&224)===192){if(i+1===e||(n[i+1]&192)!==128||(n[i]&254)===192)return!1;i+=2}else if((n[i]&240)===224){if(i+2>=e||(n[i+1]&192)!==128||(n[i+2]&192)!==128||n[i]===224&&(n[i+1]&224)===128||n[i]===237&&(n[i+1]&224)===160)return!1;i+=3}else if((n[i]&248)===240){if(i+3>=e||(n[i+1]&192)!==128||(n[i+2]&192)!==128||(n[i+3]&192)!==128||n[i]===240&&(n[i+1]&240)===128||n[i]===244&&n[i+1]>143||n[i]>244)return!1;i+=4}else return!1;return!0}function ou(n){return ru&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Gn.exports={isBlob:ou,isValidStatusCode:iu,isValidUTF8:Gr,tokenChars:su};if(po)Gn.exports.isValidUTF8=function(n){return n.length<24?Gr(n):po(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=V("utf-8-validate");Gn.exports.isValidUTF8=function(e){return e.length<32?Gr(e):n(e)}}catch{}});var Vr=xe((kg,So)=>{"use strict";var{Writable:au}=V("stream"),mo=_t(),{BINARY_TYPES:cu,EMPTY_BUFFER:wo,kStatusCode:xu,kWebSocket:uu}=Oe(),{concat:jr,toArrayBuffer:du,unmask:fu}=jt(),{isValidStatusCode:lu,isValidUTF8:_o}=yt(),jn=Buffer[Symbol.species],he=0,yo=1,vo=2,bo=3,Kr=4,Wr=5,Kn=6,Jr=class extends au{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||cu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[uu]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=he}_write(e,i,a){if(this._opcode===8&&this._state==he)return a();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(a)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let a=this._buffers[0];return this._buffers[0]=new jn(a.buffer,a.byteOffset+e,a.length-e),new jn(a.buffer,a.byteOffset,e)}let i=Buffer.allocUnsafe(e);do{let a=this._buffers[0],c=i.length-e;e>=a.length?i.set(this._buffers.shift(),c):(i.set(new Uint8Array(a.buffer,a.byteOffset,e),c),this._buffers[0]=new jn(a.buffer,a.byteOffset+e,a.length-e)),e-=a.length}while(e>0);return i}startLoop(e){this._loop=!0;do switch(this._state){case he:this.getInfo(e);break;case yo:this.getPayloadLength16(e);break;case vo:this.getPayloadLength64(e);break;case bo:this.getMask();break;case Kr:this.getData(e);break;case Wr:case Kn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let i=this.consume(2);if((i[0]&48)!==0){let c=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(c);return}let a=(i[0]&64)===64;if(a&&!this._extensions[mo.extensionName]){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(this._fin=(i[0]&128)===128,this._opcode=i[0]&15,this._payloadLength=i[1]&127,this._opcode===0){if(a){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(!this._fragmented){let c=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let c=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}this._compressed=a}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let c=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(c);return}if(a){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let c=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(c);return}}else{let c=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(i[1]&128)===128,this._isServer){if(!this._masked){let c=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(c);return}}else if(this._masked){let c=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(c);return}this._payloadLength===126?this._state=yo:this._payloadLength===127?this._state=vo:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let i=this.consume(8),a=i.readUInt32BE(0);if(a>Math.pow(2,21)-1){let c=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(c);return}this._payloadLength=a*Math.pow(2,32)+i.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(i);return}this._masked?this._state=bo:this._state=Kr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Kr}getData(e){let i=wo;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}i=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&fu(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Wr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[mo.extensionName].decompress(e,this._fin,(c,u)=>{if(c)return i(c);if(u.length){if(this._messageLength+=u.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(d);return}this._fragments.push(u)}this.dataMessage(i),this._state===he&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=he;return}let i=this._messageLength,a=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let c;this._binaryType==="nodebuffer"?c=jr(a,i):this._binaryType==="arraybuffer"?c=du(jr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=he):(this._state=Kn,setImmediate(()=>{this.emit("message",c,!0),this._state=he,this.startLoop(e)}))}else{let c=jr(a,i);if(!this._skipUTF8Validation&&!_o(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===Wr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=he):(this._state=Kn,setImmediate(()=>{this.emit("message",c,!1),this._state=he,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,wo),this.end();else{let a=e.readUInt16BE(0);if(!lu(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new jn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_o(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");i(u);return}this._loop=!1,this.emit("conclude",a,c),this.end()}this._state=he;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=he):(this._state=Kn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=he,this.startLoop(i)}))}createError(e,i,a,c,u){this._loop=!1,this._errored=!0;let d=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(d,this.createError),d.code=u,d[xu]=c,d}};So.exports=Jr});var Yr=xe((Pg,ko)=>{"use strict";var{Duplex:Ag}=V("stream"),{randomFillSync:hu}=V("crypto"),Eo=_t(),{EMPTY_BUFFER:gu,kWebSocket:pu,NOOP:mu}=Oe(),{isBlob:vt,isValidStatusCode:wu}=yt(),{mask:Co,toBuffer:Qe}=jt(),ge=Symbol("kByteLength"),_u=Buffer.alloc(4),Wn=8*1024,et,bt=Wn,_e=0,yu=1,vu=2,Xr=class n{constructor(e,i,a){this._extensions=i||{},a&&(this._generateMask=a,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=_e,this.onerror=mu,this[pu]=void 0}static frame(e,i){let a,c=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||_u,i.generateMask?i.generateMask(a):(bt===Wn&&(et===void 0&&(et=Buffer.alloc(Wn)),hu(et,0,Wn),bt=0),a[0]=et[bt++],a[1]=et[bt++],a[2]=et[bt++],a[3]=et[bt++]),d=(a[0]|a[1]|a[2]|a[3])===0,u=6);let h;typeof e=="string"?(!i.mask||d)&&i[ge]!==void 0?h=i[ge]:(e=Buffer.from(e),h=e.length):(h=e.length,c=i.mask&&i.readOnly&&!d);let m=h;h>=65536?(u+=8,m=127):h>125&&(u+=2,m=126);let w=Buffer.allocUnsafe(c?h+u:u);return w[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(w[0]|=64),w[1]=m,m===126?w.writeUInt16BE(h,2):m===127&&(w[2]=w[3]=0,w.writeUIntBE(h,4,6)),i.mask?(w[1]|=128,w[u-4]=a[0],w[u-3]=a[1],w[u-2]=a[2],w[u-1]=a[3],d?[w,e]:c?(Co(e,a,w,u,h),[w]):(Co(e,a,e,0,h),[w,e])):[w,e]}close(e,i,a,c){let u;if(e===void 0)u=gu;else{if(typeof e!="number"||!wu(e))throw new TypeError("First argument must be a valid error code number");if(i===void 0||!i.length)u=Buffer.allocUnsafe(2),u.writeUInt16BE(e,0);else{let h=Buffer.byteLength(i);if(h>123)throw new RangeError("The message must not be greater than 123 bytes");u=Buffer.allocUnsafe(2+h),u.writeUInt16BE(e,0),typeof i=="string"?u.write(i,2):u.set(i,2)}}let d={[ge]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==_e?this.enqueue([this.dispatch,u,!1,d,c]):this.sendFrame(n.frame(u,d),c)}ping(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):vt(e)?(c=e.size,u=!1):(e=Qe(e),c=e.length,u=Qe.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ge]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(n.frame(e,d),a)}pong(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):vt(e)?(c=e.size,u=!1):(e=Qe(e),c=e.length,u=Qe.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ge]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(n.frame(e,d),a)}send(e,i,a){let c=this._extensions[Eo.extensionName],u=i.binary?2:1,d=i.compress,h,m;typeof e=="string"?(h=Buffer.byteLength(e),m=!1):vt(e)?(h=e.size,m=!1):(e=Qe(e),h=e.length,m=Qe.readOnly),this._firstFragment?(this._firstFragment=!1,d&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=h>=c._threshold),this._compress=d):(d=!1,u=0),i.fin&&(this._firstFragment=!0);let w={[ge]:h,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:m,rsv1:d};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,this._compress,w,a]):this.getBlobData(e,this._compress,w,a):this._state!==_e?this.enqueue([this.dispatch,e,this._compress,w,a]):this.dispatch(e,this._compress,w,a)}getBlobData(e,i,a,c){this._bufferedBytes+=a[ge],this._state=vu,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let h=new Error("The socket was closed while the blob was being read");process.nextTick($r,this,h,c);return}this._bufferedBytes-=a[ge];let d=Qe(u);i?this.dispatch(d,i,a,c):(this._state=_e,this.sendFrame(n.frame(d,a),c),this.dequeue())}).catch(u=>{process.nextTick(bu,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(n.frame(e,a),c);return}let u=this._extensions[Eo.extensionName];this._bufferedBytes+=a[ge],this._state=yu,u.compress(e,a.fin,(d,h)=>{if(this._socket.destroyed){let m=new Error("The socket was closed while data was being compressed");$r(this,m,c);return}this._bufferedBytes-=a[ge],this._state=_e,a.readOnly=!1,this.sendFrame(n.frame(h,a),c),this.dequeue()})}dequeue(){for(;this._state===_e&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ge],this._queue.push(e)}sendFrame(e,i){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],i),this._socket.uncork()):this._socket.write(e[0],i)}};ko.exports=Xr;function $r(n,e,i){typeof i=="function"&&i(e);for(let a=0;a<n._queue.length;a++){let c=n._queue[a],u=c[c.length-1];typeof u=="function"&&u(e)}}function bu(n,e,i){$r(n,e,i),n.onerror(e)}});var Oo=xe((Ig,No)=>{"use strict";var{kForOnEventAttribute:Wt,kListener:Zr}=Oe(),Ao=Symbol("kCode"),Po=Symbol("kData"),Io=Symbol("kError"),To=Symbol("kMessage"),Do=Symbol("kReason"),St=Symbol("kTarget"),Ro=Symbol("kType"),Lo=Symbol("kWasClean"),ze=class{constructor(e){this[St]=null,this[Ro]=e}get target(){return this[St]}get type(){return this[Ro]}};Object.defineProperty(ze.prototype,"target",{enumerable:!0});Object.defineProperty(ze.prototype,"type",{enumerable:!0});var nt=class extends ze{constructor(e,i={}){super(e),this[Ao]=i.code===void 0?0:i.code,this[Do]=i.reason===void 0?"":i.reason,this[Lo]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[Ao]}get reason(){return this[Do]}get wasClean(){return this[Lo]}};Object.defineProperty(nt.prototype,"code",{enumerable:!0});Object.defineProperty(nt.prototype,"reason",{enumerable:!0});Object.defineProperty(nt.prototype,"wasClean",{enumerable:!0});var Et=class extends ze{constructor(e,i={}){super(e),this[Io]=i.error===void 0?null:i.error,this[To]=i.message===void 0?"":i.message}get error(){return this[Io]}get message(){return this[To]}};Object.defineProperty(Et.prototype,"error",{enumerable:!0});Object.defineProperty(Et.prototype,"message",{enumerable:!0});var Jt=class extends ze{constructor(e,i={}){super(e),this[Po]=i.data===void 0?null:i.data}get data(){return this[Po]}};Object.defineProperty(Jt.prototype,"data",{enumerable:!0});var Su={addEventListener(n,e,i={}){for(let c of this.listeners(n))if(!i[Wt]&&c[Zr]===e&&!c[Wt])return;let a;if(n==="message")a=function(u,d){let h=new Jt("message",{data:d?u:u.toString()});h[St]=this,Jn(e,this,h)};else if(n==="close")a=function(u,d){let h=new nt("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});h[St]=this,Jn(e,this,h)};else if(n==="error")a=function(u){let d=new Et("error",{error:u,message:u.message});d[St]=this,Jn(e,this,d)};else if(n==="open")a=function(){let u=new ze("open");u[St]=this,Jn(e,this,u)};else return;a[Wt]=!!i[Wt],a[Zr]=e,i.once?this.once(n,a):this.on(n,a)},removeEventListener(n,e){for(let i of this.listeners(n))if(i[Zr]===e&&!i[Wt]){this.removeListener(n,i);break}}};No.exports={CloseEvent:nt,ErrorEvent:Et,Event:ze,EventTarget:Su,MessageEvent:Jt};function Jn(n,e,i){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,i):n.call(e,i)}});var Vn=xe((Tg,Bo)=>{"use strict";var{tokenChars:Vt}=yt();function Pe(n,e,i){n[e]===void 0?n[e]=[i]:n[e].push(i)}function Eu(n){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,d,h,m=-1,w=-1,v=-1,_=0;for(;_<n.length;_++)if(w=n.charCodeAt(_),d===void 0)if(v===-1&&Vt[w]===1)m===-1&&(m=_);else if(_!==0&&(w===32||w===9))v===-1&&m!==-1&&(v=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);v===-1&&(v=_);let T=n.slice(m,v);w===44?(Pe(e,T,i),i=Object.create(null)):d=T,m=v=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===void 0)if(v===-1&&Vt[w]===1)m===-1&&(m=_);else if(w===32||w===9)v===-1&&m!==-1&&(v=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);v===-1&&(v=_),Pe(i,n.slice(m,v),!0),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),m=v=-1}else if(w===61&&m!==-1&&v===-1)h=n.slice(m,_),m=v=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(c){if(Vt[w]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1?m=_:a||(a=!0),c=!1}else if(u)if(Vt[w]===1)m===-1&&(m=_);else if(w===34&&m!==-1)u=!1,v=_;else if(w===92)c=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(w===34&&n.charCodeAt(_-1)===61)u=!0;else if(v===-1&&Vt[w]===1)m===-1&&(m=_);else if(m!==-1&&(w===32||w===9))v===-1&&(v=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);v===-1&&(v=_);let T=n.slice(m,v);a&&(T=T.replace(/\\/g,""),a=!1),Pe(i,h,T),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),h=void 0,m=v=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(m===-1||u||w===32||w===9)throw new SyntaxError("Unexpected end of input");v===-1&&(v=_);let C=n.slice(m,v);return d===void 0?Pe(e,C,i):(h===void 0?Pe(i,C,!0):a?Pe(i,h,C.replace(/\\/g,"")):Pe(i,h,C),Pe(e,d,i)),e}function Cu(n){return Object.keys(n).map(e=>{let i=n[e];return Array.isArray(i)||(i=[i]),i.map(a=>[e].concat(Object.keys(a).map(c=>{let u=a[c];return Array.isArray(u)||(u=[u]),u.map(d=>d===!0?c:`${c}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Bo.exports={format:Cu,parse:Eu}});var Zn=xe((Lg,Vo)=>{"use strict";var ku=V("events"),Au=V("https"),Pu=V("http"),qo=V("net"),Iu=V("tls"),{randomBytes:Tu,createHash:Du}=V("crypto"),{Duplex:Dg,Readable:Rg}=V("stream"),{URL:Qr}=V("url"),Je=_t(),Ru=Vr(),Lu=Yr(),{isBlob:Nu}=yt(),{BINARY_TYPES:zo,CLOSE_TIMEOUT:Ou,EMPTY_BUFFER:Xn,GUID:Bu,kForOnEventAttribute:es,kListener:zu,kStatusCode:Mu,kWebSocket:te,NOOP:Fo}=Oe(),{EventTarget:{addEventListener:qu,removeEventListener:Fu}}=Oo(),{format:Uu,parse:Hu}=Vn(),{toBuffer:Gu}=jt(),Uo=Symbol("kAborted"),ts=[8,13],Me=["CONNECTING","OPEN","CLOSING","CLOSED"],ju=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,G=class n extends ku{constructor(e,i,a){super(),this._binaryType=zo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,i===void 0?i=[]:Array.isArray(i)||(typeof i=="object"&&i!==null?(a=i,i=[]):i=[i]),Ho(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){zo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,i,a){let c=new Ru({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new Lu(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[te]=this,u[te]=this,e[te]=this,c.on("conclude",Ju),c.on("drain",Vu),c.on("error",Xu),c.on("message",$u),c.on("ping",Yu),c.on("pong",Zu),u.onerror=Qu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",Ko),e.on("data",Yn),e.on("end",Wo),e.on("error",Jo),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Je.extensionName]&&this._extensions[Je.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,i){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,i,!this._isServer,a=>{a||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),jo(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,i,a){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(a=e,e=i=void 0):typeof i=="function"&&(a=i,i=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ns(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Xn,i,a)}pong(e,i,a){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(a=e,e=i=void 0):typeof i=="function"&&(a=i,i=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ns(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Xn,i,a)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,i,a){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof i=="function"&&(a=i,i={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ns(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[Je.extensionName]||(c.compress=!1),this._sender.send(e||Xn,c,a)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(G,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(G.prototype,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(G,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(G.prototype,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(G,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(G.prototype,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(G,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});Object.defineProperty(G.prototype,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(G.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(G.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[es])return e[zu];return null},set(e){for(let i of this.listeners(n))if(i[es]){this.removeListener(n,i);break}typeof e=="function"&&this.addEventListener(n,e,{[es]:!0})}})});G.prototype.addEventListener=qu;G.prototype.removeEventListener=Fu;Vo.exports=G;function Ho(n,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ou,protocolVersion:ts[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=c.autoPong,n._closeTimeout=c.closeTimeout,!ts.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${ts.join(", ")})`);let u;if(e instanceof Qr)u=e;else try{u=new Qr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}u.protocol==="http:"?u.protocol="ws:":u.protocol==="https:"&&(u.protocol="wss:"),n._url=u.href;let d=u.protocol==="wss:",h=u.protocol==="ws+unix:",m;if(u.protocol!=="ws:"&&!d&&!h?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:h&&!u.pathname?m="The URL's pathname is empty":u.hash&&(m="The URL contains a fragment identifier"),m){let L=new SyntaxError(m);if(n._redirects===0)throw L;$n(n,L);return}let w=d?443:80,v=Tu(16).toString("base64"),_=d?Au.request:Pu.request,C=new Set,T;if(c.createConnection=c.createConnection||(d?Wu:Ku),c.defaultPort=c.defaultPort||w,c.port=u.port||w,c.host=u.hostname.startsWith("[")?u.hostname.slice(1,-1):u.hostname,c.headers={...c.headers,"Sec-WebSocket-Version":c.protocolVersion,"Sec-WebSocket-Key":v,Connection:"Upgrade",Upgrade:"websocket"},c.path=u.pathname+u.search,c.timeout=c.handshakeTimeout,c.perMessageDeflate&&(T=new Je({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=Uu({[Je.extensionName]:T.offer()})),i.length){for(let L of i){if(typeof L!="string"||!ju.test(L)||C.has(L))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(L)}c.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(c.origin&&(c.protocolVersion<13?c.headers["Sec-WebSocket-Origin"]=c.origin:c.headers.Origin=c.origin),(u.username||u.password)&&(c.auth=`${u.username}:${u.password}`),h){let L=c.path.split(":");c.socketPath=L[0],c.path=L[1]}let D;if(c.followRedirects){if(n._redirects===0){n._originalIpc=h,n._originalSecure=d,n._originalHostOrSocketPath=h?c.socketPath:u.host;let L=a&&a.headers;if(a={...a,headers:{}},L)for(let[F,$]of Object.entries(L))a.headers[F.toLowerCase()]=$}else if(n.listenerCount("redirect")===0){let L=h?n._originalIpc?c.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:u.host===n._originalHostOrSocketPath;(!L||n._originalSecure&&!d)&&(delete c.headers.authorization,delete c.headers.cookie,L||delete c.headers.host,c.auth=void 0)}c.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(c.auth).toString("base64")),D=n._req=_(c),n._redirects&&n.emit("redirect",n.url,D)}else D=n._req=_(c);c.timeout&&D.on("timeout",()=>{fe(n,D,"Opening handshake has timed out")}),D.on("error",L=>{D===null||D[Uo]||(D=n._req=null,$n(n,L))}),D.on("response",L=>{let F=L.headers.location,$=L.statusCode;if(F&&c.followRedirects&&$>=300&&$<400){if(++n._redirects>c.maxRedirects){fe(n,D,"Maximum redirects exceeded");return}D.abort();let re;try{re=new Qr(F,e)}catch{let Y=new SyntaxError(`Invalid URL: ${F}`);$n(n,Y);return}Ho(n,re,i,a)}else n.emit("unexpected-response",D,L)||fe(n,D,`Unexpected server response: ${L.statusCode}`)}),D.on("upgrade",(L,F,$)=>{if(n.emit("upgrade",L),n.readyState!==G.CONNECTING)return;D=n._req=null;let re=L.headers.upgrade;if(re===void 0||re.toLowerCase()!=="websocket"){fe(n,F,"Invalid Upgrade header");return}let Q=Du("sha1").update(v+Bu).digest("base64");if(L.headers["sec-websocket-accept"]!==Q){fe(n,F,"Invalid Sec-WebSocket-Accept header");return}let Y=L.headers["sec-websocket-protocol"],A;if(Y!==void 0?C.size?C.has(Y)||(A="Server sent an invalid subprotocol"):A="Server sent a subprotocol but none was requested":C.size&&(A="Server sent no subprotocol"),A){fe(n,F,A);return}Y&&(n._protocol=Y);let U=L.headers["sec-websocket-extensions"];if(U!==void 0){if(!T){fe(n,F,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let K;try{K=Hu(U)}catch{fe(n,F,"Invalid Sec-WebSocket-Extensions header");return}let se=Object.keys(K);if(se.length!==1||se[0]!==Je.extensionName){fe(n,F,"Server indicated an extension that was not requested");return}try{T.accept(K[Je.extensionName])}catch{fe(n,F,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Je.extensionName]=T}n.setSocket(F,$,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(D,n):D.end()}function $n(n,e){n._readyState=G.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Ku(n){return n.path=n.socketPath,qo.connect(n)}function Wu(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=qo.isIP(n.host)?"":n.host),Iu.connect(n)}function fe(n,e,i){n._readyState=G.CLOSING;let a=new Error(i);Error.captureStackTrace(a,fe),e.setHeader?(e[Uo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick($n,n,a)):(e.destroy(a),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function ns(n,e,i){if(e){let a=Nu(e)?e.size:Gu(e).length;n._socket?n._sender._bufferedBytes+=a:n._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${n.readyState} (${Me[n.readyState]})`);process.nextTick(i,a)}}function Ju(n,e){let i=this[te];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=n,i._socket[te]!==void 0&&(i._socket.removeListener("data",Yn),process.nextTick(Go,i._socket),n===1005?i.close():i.close(n,e))}function Vu(){let n=this[te];n.isPaused||n._socket.resume()}function Xu(n){let e=this[te];e._socket[te]!==void 0&&(e._socket.removeListener("data",Yn),process.nextTick(Go,e._socket),e.close(n[Mu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Mo(){this[te].emitClose()}function $u(n,e){this[te].emit("message",n,e)}function Yu(n){let e=this[te];e._autoPong&&e.pong(n,!this._isServer,Fo),e.emit("ping",n)}function Zu(n){this[te].emit("pong",n)}function Go(n){n.resume()}function Qu(n){let e=this[te];e.readyState!==G.CLOSED&&(e.readyState===G.OPEN&&(e._readyState=G.CLOSING,jo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function jo(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Ko(){let n=this[te];if(this.removeListener("close",Ko),this.removeListener("data",Yn),this.removeListener("end",Wo),n._readyState=G.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[te]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Mo),n._receiver.on("finish",Mo))}function Yn(n){this[te]._receiver.write(n)||this.pause()}function Wo(){let n=this[te];n._readyState=G.CLOSING,n._receiver.end(),this.end()}function Jo(){let n=this[te];this.removeListener("error",Jo),this.on("error",Fo),n&&(n._readyState=G.CLOSING,this.destroy())}});var Zo=xe((Og,Yo)=>{"use strict";var Ng=Zn(),{Duplex:ed}=V("stream");function Xo(n){n.emit("close")}function td(){!this.destroyed&&this._writableState.finished&&this.destroy()}function $o(n){this.removeListener("error",$o),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function nd(n,e){let i=!0,a=new ed({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(u,d){let h=!d&&a._readableState.objectMode?u.toString():u;a.push(h)||n.pause()}),n.once("error",function(u){a.destroyed||(i=!1,a.destroy(u))}),n.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(c,u){if(n.readyState===n.CLOSED){u(c),process.nextTick(Xo,a);return}let d=!1;n.once("error",function(m){d=!0,u(m)}),n.once("close",function(){d||u(c),process.nextTick(Xo,a)}),i&&n.terminate()},a._final=function(c){if(n.readyState===n.CONNECTING){n.once("open",function(){a._final(c)});return}n._socket!==null&&(n._socket._writableState.finished?(c(),a._readableState.endEmitted&&a.destroy()):(n._socket.once("finish",function(){c()}),n.close()))},a._read=function(){n.isPaused&&n.resume()},a._write=function(c,u,d){if(n.readyState===n.CONNECTING){n.once("open",function(){a._write(c,u,d)});return}n.send(c,d)},a.on("end",td),a.on("error",$o),a}Yo.exports=nd});var rs=xe((Bg,Qo)=>{"use strict";var{tokenChars:rd}=yt();function sd(n){let e=new Set,i=-1,a=-1,c=0;for(c;c<n.length;c++){let d=n.charCodeAt(c);if(a===-1&&rd[d]===1)i===-1&&(i=c);else if(c!==0&&(d===32||d===9))a===-1&&i!==-1&&(a=c);else if(d===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);let h=n.slice(i,a);if(e.has(h))throw new SyntaxError(`The "${h}" subprotocol is duplicated`);e.add(h),i=a=-1}else throw new SyntaxError(`Unexpected character at index ${c}`)}if(i===-1||a!==-1)throw new SyntaxError("Unexpected end of input");let u=n.slice(i,c);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return e.add(u),e}Qo.exports={parse:sd}});var oa=xe((Mg,ia)=>{"use strict";var id=V("events"),Qn=V("http"),{Duplex:zg}=V("stream"),{createHash:od}=V("crypto"),ea=Vn(),rt=_t(),ad=rs(),cd=Zn(),{CLOSE_TIMEOUT:xd,GUID:ud,kWebSocket:dd}=Oe(),fd=/^[+/0-9A-Za-z]{22}==$/,ta=0,na=1,sa=2,ss=class extends id{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xd,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:cd,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Qn.createServer((a,c)=>{let u=Qn.STATUS_CODES[426];c.writeHead(426,{"Content-Length":u.length,"Content-Type":"text/plain"}),c.end(u)}),this._server.listen(e.port,e.host,e.backlog,i)):e.server&&(this._server=e.server),this._server){let a=this.emit.bind(this,"connection");this._removeListeners=ld(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(c,u,d)=>{this.handleUpgrade(c,u,d,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ta}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===sa){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xt,this);return}if(e&&this.once("close",e),this._state!==na)if(this._state=na,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Xt,this):process.nextTick(Xt,this);else{let i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{Xt(this)})}}shouldHandle(e){if(this.options.path){let i=e.url.indexOf("?");if((i!==-1?e.url.slice(0,i):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,i,a,c){i.on("error",ra);let u=e.headers["sec-websocket-key"],d=e.headers.upgrade,h=+e.headers["sec-websocket-version"];if(e.method!=="GET"){st(this,e,i,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){st(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!fd.test(u)){st(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(h!==13&&h!==8){st(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){$t(i,400);return}let m=e.headers["sec-websocket-protocol"],w=new Set;if(m!==void 0)try{w=ad.parse(m)}catch{st(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&v!==void 0){let C=new rt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let T=ea.parse(v);T[rt.extensionName]&&(C.accept(T[rt.extensionName]),_[rt.extensionName]=C)}catch{st(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${h===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(T,D,L,F)=>{if(!T)return $t(i,D||401,L,F);this.completeUpgrade(_,u,w,e,i,a,c)});return}if(!this.options.verifyClient(C))return $t(i,401)}this.completeUpgrade(_,u,w,e,i,a,c)}completeUpgrade(e,i,a,c,u,d,h){if(!u.readable||!u.writable)return u.destroy();if(u[dd])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ta)return $t(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${od("sha1").update(i+ud).digest("base64")}`],v=new this.options.WebSocket(null,void 0,this.options);if(a.size){let _=this.options.handleProtocols?this.options.handleProtocols(a,c):a.values().next().value;_&&(w.push(`Sec-WebSocket-Protocol: ${_}`),v._protocol=_)}if(e[rt.extensionName]){let _=e[rt.extensionName].params,C=ea.format({[rt.extensionName]:[_]});w.push(`Sec-WebSocket-Extensions: ${C}`),v._extensions=e}this.emit("headers",w,c),u.write(w.concat(`\r
|
|
8
|
+
var va=Object.create;var Ln=Object.defineProperty;var ka=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var xa=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var A=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var K=(n,e)=>()=>(n&&(e=n(n=0)),e);var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Mn=(n,e)=>{for(var t in e)Ln(n,t,{get:e[t],enumerable:!0})},Ra=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ia(e))!Ta.call(n,s)&&s!==t&&Ln(n,s,{get:()=>e[s],enumerable:!(r=ka(e,s))||r.enumerable});return n};var he=(n,e,t)=>(t=n!=null?va(xa(n)):{},Ra(e||!n||!n.__esModule?Ln(t,"default",{value:n,enumerable:!0}):t,n));import{chmod as Pa,mkdir as Aa,readFile as Ca,rename as cs,writeFile as ls}from"node:fs/promises";import{dirname as Oa}from"node:path";async function Le(n){try{let e=await Ca(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Pt(n,e,t){await Aa(Oa(n),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
|
|
9
|
+
`,s=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{t?.mode!==void 0?await ls(s,r,{encoding:"utf8",mode:t.mode}):await ls(s,r,"utf8"),await cs(s,n),t?.mode!==void 0&&await Pa(n,t.mode)}catch(i){await cs(s,s).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(s,{force:!0}).catch(()=>{}),i}}var At=K(()=>{"use strict"});function fs(n){return Ot[ds]<=Ot[n]}function Bn(n){us={...n}}function Ct(n,e,t,r){if(Ot[n]<Ot[ds])return;let s=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:t,...us,...r});n==="error"||n==="warn"?Na.write(`${s}
|
|
10
|
+
`):ba.write(`${s}
|
|
11
|
+
`)}function w(n){return{debug:(e,t)=>Ct("debug",n,e,t),info:(e,t)=>Ct("info",n,e,t),warn:(e,t)=>Ct("warn",n,e,t),error:(e,t)=>Ct("error",n,e,t),child:e=>w(`${n}.${e}`)}}var Ot,ds,ba,Na,us,k=K(()=>{"use strict";Ot={debug:10,info:20,warn:30,error:40},ds=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),ba=process.stdout,Na=process.stderr,us={}});import{homedir as Da}from"node:os";import{join as L}from"node:path";function T(n){let e=n??Da(),t=L(e,".coze"),r=L(t,"bridge"),s=L(r,"lib");return{cozeRoot:t,bridgeRoot:r,libDir:s,libEntry:L(s,"index.js"),pidFile:L(r,"bridge.pid"),portFile:L(r,"bridge.port"),tokenFile:L(r,"bridge.token"),logFile:L(r,"bridge.log"),installLock:L(r,"install.lock"),configFile:L(r,"config.json"),agentsRoot:L(t,"agents")}}function ae(n,e=T()){let t=L(e.agentsRoot,n);return{root:t,config:L(t,"config.json"),workspace:L(t,"workspace"),logs:L(t,"logs")}}var z=K(()=>{"use strict"});var Dt={};Mn(Dt,{AGENT_CONFIG_FILE_MODE:()=>bt,enforceAgentConfigMode:()=>Ba,loadAgentConfig:()=>q,persistAgentSessions:()=>Fn,persistAgentSkills:()=>Nt,saveAgentConfig:()=>X});import{chmod as La,stat as Ma}from"node:fs/promises";function q(n,e){return Le(ae(n,e).config)}function X(n,e){return Pt(ae(n.agentId,e).config,n,{mode:bt})}async function Ba(n,e){if(process.platform==="win32")return;let t=ae(n,e).config;try{let r=await Ma(t);if(!r.isFile())return;let s=r.mode&511;s!==bt&&(await La(t,bt),hs.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(r){if(r.code==="ENOENT")return;hs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(r)})}}async function Fn(n,e,t){let r=await q(n,t);r&&(r.sessions=Object.fromEntries(e),await X(r,t))}async function Nt(n,e,t){let r=await q(n,t);r&&(r.skills=e,await X(r,t))}var hs,bt,ge=K(()=>{"use strict";At();k();z();hs=w("agent-config"),bt=384});function Ol(){return gi||(gi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bl(){return pi||(pi=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Nl(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(W(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&mi.set(t,n)}).catch(()=>{}),Zn.set(e,n),e}function Dl(n){if(Xn.has(n))return;let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",o),n.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",o),n.addEventListener("abort",o)});Xn.set(n,e)}function wi(n){Yn=n(Yn)}function Ll(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let r=n.call(gt(this),e,...t);return _i.set(r,e.sort?e.sort():[e]),W(r)}:bl().includes(n)?function(...e){return n.apply(gt(this),e),W(mi.get(this))}:function(...e){return W(n.apply(gt(this),e))}}function Ml(n){return typeof n=="function"?Ll(n):(n instanceof IDBTransaction&&Dl(n),Cl(n,Ol())?new Proxy(n,Yn):n)}function W(n){if(n instanceof IDBRequest)return Nl(n);if(Kn.has(n))return Kn.get(n);let e=Ml(n);return e!==n&&(Kn.set(n,e),Zn.set(e,n)),e}var Cl,gi,pi,mi,Xn,_i,Kn,Zn,Yn,gt,er=K(()=>{Cl=(n,e)=>e.some(t=>n instanceof t);mi=new WeakMap,Xn=new WeakMap,_i=new WeakMap,Kn=new WeakMap,Zn=new WeakMap;Yn={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Xn.get(n);if(e==="objectStoreNames")return n.objectStoreNames||_i.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return W(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};gt=n=>Zn.get(n)});var Si={};Mn(Si,{deleteDB:()=>Fl,openDB:()=>Bl,unwrap:()=>gt,wrap:()=>W});function Bl(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){let o=indexedDB.open(n,e),a=W(o);return r&&o.addEventListener("upgradeneeded",c=>{r(W(o.result),c.oldVersion,c.newVersion,W(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function Fl(n,{blocked:e}={}){let t=indexedDB.deleteDatabase(n);return e&&t.addEventListener("blocked",()=>e()),W(t).then(()=>{})}function yi(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(tr.get(e))return tr.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,s=$l.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||Ul.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return tr.set(e,i),i}var Ul,$l,tr,Ei=K(()=>{er();er();Ul=["get","getKey","getAll","getAllKeys","count"],$l=["put","add","delete","clear"],tr=new Map;wi(n=>({...n,get:(e,t,r)=>yi(e,t)||n.get(e,t,r),has:(e,t)=>!!yi(e,t)||n.has(e,t)}))});var le=$((wm,Ji)=>{"use strict";var Wi=["nodebuffer","arraybuffer","fragments"],ji=typeof Blob<"u";ji&&Wi.push("blob");Ji.exports={BINARY_TYPES:Wi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ji,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var St=$((ym,cn)=>{"use strict";var{EMPTY_BUFFER:Gd}=le(),Ir=Buffer[Symbol.species];function Hd(n,e){if(n.length===0)return Gd;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Ir(t.buffer,t.byteOffset,r):t}function Vi(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Qi(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Wd(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function xr(n){if(xr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ir(n):ArrayBuffer.isView(n)?e=new Ir(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),xr.readOnly=!1),e}cn.exports={concat:Hd,mask:Vi,toArrayBuffer:Wd,toBuffer:xr,unmask:Qi};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=A("bufferutil");cn.exports.mask=function(e,t,r,s,i){i<48?Vi(e,t,r,s,i):n.mask(e,t,r,s,i)},cn.exports.unmask=function(e,t){e.length<32?Qi(e,t):n.unmask(e,t)}}catch{}});var Yi=$((Sm,Xi)=>{"use strict";var Ki=Symbol("kDone"),Tr=Symbol("kRun"),Rr=class{constructor(e){this[Ki]=()=>{this.pending--,this[Tr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Tr]()}[Tr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ki])}}};Xi.exports=Rr});var Ve=$((Em,no)=>{"use strict";var Et=A("zlib"),Zi=St(),jd=Yi(),{kStatusCode:eo}=le(),Jd=Buffer[Symbol.species],Vd=Buffer.from([0,0,255,255]),dn=Symbol("permessage-deflate"),de=Symbol("total-length"),je=Symbol("callback"),ye=Symbol("buffers"),Je=Symbol("error"),ln,Pr=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ln){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ln=new jd(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[je];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){ln.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){ln.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Et.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[dn]=this,this._inflate[de]=0,this._inflate[ye]=[],this._inflate.on("error",Kd),this._inflate.on("data",to)}this._inflate[je]=r,this._inflate.write(e),t&&this._inflate.write(Vd),this._inflate.flush(()=>{let i=this._inflate[Je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Zi.concat(this._inflate[ye],this._inflate[de]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[de]=0,this._inflate[ye]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Et.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[de]=0,this._deflate[ye]=[],this._deflate.on("data",Qd)}this._deflate[je]=r,this._deflate.write(e),this._deflate.flush(Et.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zi.concat(this._deflate[ye],this._deflate[de]);t&&(i=new Jd(i.buffer,i.byteOffset,i.length-4)),this._deflate[je]=null,this._deflate[de]=0,this._deflate[ye]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};no.exports=Pr;function Qd(n){this[ye].push(n),this[de]+=n.length}function to(n){if(this[de]+=n.length,this[dn]._maxPayload<1||this[de]<=this[dn]._maxPayload){this[ye].push(n);return}this[Je]=new RangeError("Max payload size exceeded"),this[Je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Je][eo]=1009,this.removeListener("data",to),this.reset()}function Kd(n){if(this[dn]._inflate=null,this[Je]){this[je](this[Je]);return}n[eo]=1007,this[je](n)}});var Qe=$((vm,un)=>{"use strict";var{isUtf8:ro}=A("buffer"),{hasBlob:Xd}=le(),Yd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Zd(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ar(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function eu(n){return Xd&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}un.exports={isBlob:eu,isValidStatusCode:Zd,isValidUTF8:Ar,tokenChars:Yd};if(ro)un.exports.isValidUTF8=function(n){return n.length<24?Ar(n):ro(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=A("utf-8-validate");un.exports.isValidUTF8=function(e){return e.length<32?Ar(e):n(e)}}catch{}});var Dr=$((km,uo)=>{"use strict";var{Writable:tu}=A("stream"),so=Ve(),{BINARY_TYPES:nu,EMPTY_BUFFER:io,kStatusCode:ru,kWebSocket:su}=le(),{concat:Cr,toArrayBuffer:iu,unmask:ou}=St(),{isValidStatusCode:au,isValidUTF8:oo}=Qe(),fn=Buffer[Symbol.species],J=0,ao=1,co=2,lo=3,Or=4,br=5,hn=6,Nr=class extends tu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||nu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[su]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=J}_write(e,t,r){if(this._opcode===8&&this._state==J)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new fn(r.buffer,r.byteOffset+e,r.length-e),new fn(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new fn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case J:this.getInfo(e);break;case ao:this.getPayloadLength16(e);break;case co:this.getPayloadLength64(e);break;case lo:this.getMask();break;case Or:this.getData(e);break;case br:case hn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[so.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ao:this._payloadLength===127?this._state=co:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=lo:this._state=Or}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Or}getData(e){let t=io;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&ou(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=br,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[so.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===J&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=J;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Cr(r,t):this._binaryType==="arraybuffer"?s=iu(Cr(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=J):(this._state=hn,setImmediate(()=>{this.emit("message",s,!0),this._state=J,this.startLoop(e)}))}else{let s=Cr(r,t);if(!this._skipUTF8Validation&&!oo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===br||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=J):(this._state=hn,setImmediate(()=>{this.emit("message",s,!1),this._state=J,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,io),this.end();else{let r=e.readUInt16BE(0);if(!au(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new fn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!oo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=J;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=J):(this._state=hn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=J,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ru]=s,o}};uo.exports=Nr});var Br=$((xm,go)=>{"use strict";var{Duplex:Im}=A("stream"),{randomFillSync:cu}=A("crypto"),fo=Ve(),{EMPTY_BUFFER:lu,kWebSocket:du,NOOP:uu}=le(),{isBlob:Ke,isValidStatusCode:fu}=Qe(),{mask:ho,toBuffer:Pe}=St(),V=Symbol("kByteLength"),hu=Buffer.alloc(4),gn=8*1024,Ae,Xe=gn,Z=0,gu=1,pu=2,Lr=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Z,this.onerror=uu,this[du]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||hu,t.generateMask?t.generateMask(r):(Xe===gn&&(Ae===void 0&&(Ae=Buffer.alloc(gn)),cu(Ae,0,gn),Xe=0),r[0]=Ae[Xe++],r[1]=Ae[Xe++],r[2]=Ae[Xe++],r[3]=Ae[Xe++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[V]!==void 0?a=t[V]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],o?[l,e]:s?(ho(e,r,l,i,a),[l]):(ho(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=lu;else{if(typeof e!="number"||!fu(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[V]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Z?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ke(e)?(s=e.size,i=!1):(e=Pe(e),s=e.length,i=Pe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[V]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Z?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ke(e)?(s=e.size,i=!1):(e=Pe(e),s=e.length,i=Pe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[V]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Z?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[fo.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Ke(e)?(a=e.size,c=!1):(e=Pe(e),a=e.length,c=Pe.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[V]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Z?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[V],this._state=pu,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mr,this,a,s);return}this._bufferedBytes-=r[V];let o=Pe(i);t?this.dispatch(o,t,r,s):(this._state=Z,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(mu,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[fo.extensionName];this._bufferedBytes+=r[V],this._state=gu,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Mr(this,c,s);return}this._bufferedBytes-=r[V],this._state=Z,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Z&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][V],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][V],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};go.exports=Lr;function Mr(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function mu(n,e,t){Mr(n,e,t),n.onerror(e)}});var ko=$((Tm,vo)=>{"use strict";var{kForOnEventAttribute:vt,kListener:Fr}=le(),po=Symbol("kCode"),mo=Symbol("kData"),_o=Symbol("kError"),wo=Symbol("kMessage"),yo=Symbol("kReason"),Ye=Symbol("kTarget"),So=Symbol("kType"),Eo=Symbol("kWasClean"),ue=class{constructor(e){this[Ye]=null,this[So]=e}get target(){return this[Ye]}get type(){return this[So]}};Object.defineProperty(ue.prototype,"target",{enumerable:!0});Object.defineProperty(ue.prototype,"type",{enumerable:!0});var Ce=class extends ue{constructor(e,t={}){super(e),this[po]=t.code===void 0?0:t.code,this[yo]=t.reason===void 0?"":t.reason,this[Eo]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[po]}get reason(){return this[yo]}get wasClean(){return this[Eo]}};Object.defineProperty(Ce.prototype,"code",{enumerable:!0});Object.defineProperty(Ce.prototype,"reason",{enumerable:!0});Object.defineProperty(Ce.prototype,"wasClean",{enumerable:!0});var Ze=class extends ue{constructor(e,t={}){super(e),this[_o]=t.error===void 0?null:t.error,this[wo]=t.message===void 0?"":t.message}get error(){return this[_o]}get message(){return this[wo]}};Object.defineProperty(Ze.prototype,"error",{enumerable:!0});Object.defineProperty(Ze.prototype,"message",{enumerable:!0});var kt=class extends ue{constructor(e,t={}){super(e),this[mo]=t.data===void 0?null:t.data}get data(){return this[mo]}};Object.defineProperty(kt.prototype,"data",{enumerable:!0});var _u={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[vt]&&s[Fr]===e&&!s[vt])return;let r;if(n==="message")r=function(i,o){let a=new kt("message",{data:o?i:i.toString()});a[Ye]=this,pn(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ce("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ye]=this,pn(e,this,a)};else if(n==="error")r=function(i){let o=new Ze("error",{error:i,message:i.message});o[Ye]=this,pn(e,this,o)};else if(n==="open")r=function(){let i=new ue("open");i[Ye]=this,pn(e,this,i)};else return;r[vt]=!!t[vt],r[Fr]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Fr]===e&&!t[vt]){this.removeListener(n,t);break}}};vo.exports={CloseEvent:Ce,ErrorEvent:Ze,Event:ue,EventTarget:_u,MessageEvent:kt};function pn(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var mn=$((Rm,Io)=>{"use strict";var{tokenChars:It}=Qe();function oe(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function wu(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,f=0;for(;f<n.length;f++)if(l=n.charCodeAt(f),o===void 0)if(d===-1&&It[l]===1)c===-1&&(c=f);else if(f!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f);let p=n.slice(c,d);l===44?(oe(e,p,t),t=Object.create(null)):o=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(d===-1&&It[l]===1)c===-1&&(c=f);else if(l===32||l===9)d===-1&&c!==-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f),oe(t,n.slice(c,d),!0),l===44&&(oe(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=n.slice(c,f),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(It[l]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(It[l]===1)c===-1&&(c=f);else if(l===34&&c!==-1)i=!1,d=f;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===34&&n.charCodeAt(f-1)===61)i=!0;else if(d===-1&&It[l]===1)c===-1&&(c=f);else if(c!==-1&&(l===32||l===9))d===-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f);let p=n.slice(c,d);r&&(p=p.replace(/\\/g,""),r=!1),oe(t,a,p),l===44&&(oe(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=f);let u=n.slice(c,d);return o===void 0?oe(e,u,t):(a===void 0?oe(t,u,!0):r?oe(t,a,u.replace(/\\/g,"")):oe(t,a,u),oe(e,o,t)),e}function yu(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Io.exports={format:yu,parse:wu}});var Sn=$((Cm,Mo)=>{"use strict";var Su=A("events"),Eu=A("https"),vu=A("http"),Ro=A("net"),ku=A("tls"),{randomBytes:Iu,createHash:xu}=A("crypto"),{Duplex:Pm,Readable:Am}=A("stream"),{URL:Ur}=A("url"),Se=Ve(),Tu=Dr(),Ru=Br(),{isBlob:Pu}=Qe(),{BINARY_TYPES:xo,CLOSE_TIMEOUT:Au,EMPTY_BUFFER:_n,GUID:Cu,kForOnEventAttribute:$r,kListener:Ou,kStatusCode:bu,kWebSocket:O,NOOP:Po}=le(),{EventTarget:{addEventListener:Nu,removeEventListener:Du}}=ko(),{format:Lu,parse:Mu}=mn(),{toBuffer:Bu}=St(),Ao=Symbol("kAborted"),zr=[8,13],fe=["CONNECTING","OPEN","CLOSING","CLOSED"],Fu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class n extends Su{constructor(e,t,r){super(),this._binaryType=xo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_n,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),Co(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new Tu({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Ru(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[O]=this,i[O]=this,e[O]=this,s.on("conclude",zu),s.on("drain",qu),s.on("error",Gu),s.on("message",Hu),s.on("ping",Wu),s.on("pong",ju),i.onerror=Ju,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",No),e.on("data",yn),e.on("end",Do),e.on("error",Lo),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Se.extensionName]&&this._extensions[Se.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){H(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),bo(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||_n,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||_n,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Se.extensionName]||(s.compress=!1),this._sender.send(e||_n,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){H(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(x.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(x.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[$r])return e[Ou];return null},set(e){for(let t of this.listeners(n))if(t[$r]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[$r]:!0})}})});x.prototype.addEventListener=Nu;x.prototype.removeEventListener=Du;Mo.exports=x;function Co(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Au,protocolVersion:zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zr.join(", ")})`);let i;if(e instanceof Ur)i=e;else try{i=new Ur(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let _=new SyntaxError(c);if(n._redirects===0)throw _;wn(n,_);return}let l=o?443:80,d=Iu(16).toString("base64"),f=o?Eu.request:vu.request,u=new Set,p;if(s.createConnection=s.createConnection||(o?$u:Uu),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Se({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Lu({[Se.extensionName]:p.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!Fu.test(_)||u.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(_)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let _=s.path.split(":");s.socketPath=_[0],s.path=_[1]}let m;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let _=r&&r.headers;if(r={...r,headers:{}},_)for(let[v,C]of Object.entries(_))r.headers[v.toLowerCase()]=C}else if(n.listenerCount("redirect")===0){let _=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!_||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,_||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),m=n._req=f(s),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=f(s);s.timeout&&m.on("timeout",()=>{H(n,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[Ao]||(m=n._req=null,wn(n,_))}),m.on("response",_=>{let v=_.headers.location,C=_.statusCode;if(v&&s.followRedirects&&C>=300&&C<400){if(++n._redirects>s.maxRedirects){H(n,m,"Maximum redirects exceeded");return}m.abort();let F;try{F=new Ur(v,e)}catch{let P=new SyntaxError(`Invalid URL: ${v}`);wn(n,P);return}Co(n,F,t,r)}else n.emit("unexpected-response",m,_)||H(n,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,v,C)=>{if(n.emit("upgrade",_),n.readyState!==x.CONNECTING)return;m=n._req=null;let F=_.headers.upgrade;if(F===void 0||F.toLowerCase()!=="websocket"){H(n,v,"Invalid Upgrade header");return}let b=xu("sha1").update(d+Cu).digest("base64");if(_.headers["sec-websocket-accept"]!==b){H(n,v,"Invalid Sec-WebSocket-Accept header");return}let P=_.headers["sec-websocket-protocol"],g;if(P!==void 0?u.size?u.has(P)||(g="Server sent an invalid subprotocol"):g="Server sent a subprotocol but none was requested":u.size&&(g="Server sent no subprotocol"),g){H(n,v,g);return}P&&(n._protocol=P);let E=_.headers["sec-websocket-extensions"];if(E!==void 0){if(!p){H(n,v,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=Mu(E)}catch{H(n,v,"Invalid Sec-WebSocket-Extensions header");return}let Q=Object.keys(I);if(Q.length!==1||Q[0]!==Se.extensionName){H(n,v,"Server indicated an extension that was not requested");return}try{p.accept(I[Se.extensionName])}catch{H(n,v,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Se.extensionName]=p}n.setSocket(v,C,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(m,n):m.end()}function wn(n,e){n._readyState=x.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Uu(n){return n.path=n.socketPath,Ro.connect(n)}function $u(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Ro.isIP(n.host)?"":n.host),ku.connect(n)}function H(n,e,t){n._readyState=x.CLOSING;let r=new Error(t);Error.captureStackTrace(r,H),e.setHeader?(e[Ao]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(wn,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function qr(n,e,t){if(e){let r=Pu(e)?e.size:Bu(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${fe[n.readyState]})`);process.nextTick(t,r)}}function zu(n,e){let t=this[O];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[O]!==void 0&&(t._socket.removeListener("data",yn),process.nextTick(Oo,t._socket),n===1005?t.close():t.close(n,e))}function qu(){let n=this[O];n.isPaused||n._socket.resume()}function Gu(n){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",yn),process.nextTick(Oo,e._socket),e.close(n[bu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function To(){this[O].emitClose()}function Hu(n,e){this[O].emit("message",n,e)}function Wu(n){let e=this[O];e._autoPong&&e.pong(n,!this._isServer,Po),e.emit("ping",n)}function ju(n){this[O].emit("pong",n)}function Oo(n){n.resume()}function Ju(n){let e=this[O];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,bo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function bo(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function No(){let n=this[O];if(this.removeListener("close",No),this.removeListener("data",yn),this.removeListener("end",Do),n._readyState=x.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[O]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",To),n._receiver.on("finish",To))}function yn(n){this[O]._receiver.write(n)||this.pause()}function Do(){let n=this[O];n._readyState=x.CLOSING,n._receiver.end(),this.end()}function Lo(){let n=this[O];this.removeListener("error",Lo),this.on("error",Po),n&&(n._readyState=x.CLOSING,this.destroy())}});var $o=$((bm,Uo)=>{"use strict";var Om=Sn(),{Duplex:Vu}=A("stream");function Bo(n){n.emit("close")}function Qu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Fo(n){this.removeListener("error",Fo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Ku(n,e){let t=!0,r=new Vu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(Bo,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(Bo,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Qu),r.on("error",Fo),r}Uo.exports=Ku});var Gr=$((Nm,zo)=>{"use strict";var{tokenChars:Xu}=Qe();function Yu(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&Xu[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}zo.exports={parse:Yu}});var Vo=$((Lm,Jo)=>{"use strict";var Zu=A("events"),En=A("http"),{Duplex:Dm}=A("stream"),{createHash:ef}=A("crypto"),qo=mn(),Oe=Ve(),tf=Gr(),nf=Sn(),{CLOSE_TIMEOUT:rf,GUID:sf,kWebSocket:of}=le(),af=/^[+/0-9A-Za-z]{22}==$/,Go=0,Ho=1,jo=2,Hr=class extends Zu{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nf,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=En.createServer((r,s)=>{let i=En.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=cf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Go}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===jo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==Ho)if(this._state=Ho,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xt,this):process.nextTick(xt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{xt(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Wo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){be(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){be(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!af.test(i)){be(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){be(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Tt(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=tf.parse(c)}catch{be(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&d!==void 0){let u=new Oe({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=qo.parse(d);p[Oe.extensionName]&&(u.accept(p[Oe.extensionName]),f[Oe.extensionName]=u)}catch{be(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let u={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(u,(p,m,_,v)=>{if(!p)return Tt(t,m||401,_,v);this.completeUpgrade(f,i,l,e,t,r,s)});return}if(!this.options.verifyClient(u))return Tt(t,401)}this.completeUpgrade(f,i,l,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[of])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Go)return Tt(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ef("sha1").update(t+sf).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(l.push(`Sec-WebSocket-Protocol: ${f}`),d._protocol=f)}if(e[Oe.extensionName]){let f=e[Oe.extensionName].params,u=qo.format({[Oe.extensionName]:[f]});l.push(`Sec-WebSocket-Extensions: ${u}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
12
12
|
`).join(`\r
|
|
13
|
-
`)),
|
|
14
|
-
`+Object.keys(
|
|
13
|
+
`)),i.removeListener("error",Wo),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(xt,this)})),a(d,s)}};Jo.exports=Hr;function cf(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function xt(n){n._state=jo,n.emit("close")}function Wo(){this.destroy()}function Tt(n,e,t,r){t=t||En.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${En.STATUS_CODES[e]}\r
|
|
14
|
+
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
15
15
|
`)+`\r
|
|
16
16
|
\r
|
|
17
|
-
`+
|
|
17
|
+
`+t)}function be(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,be),n.emit("wsClientError",o,t,e)}else Tt(t,r,s,i)}});import{spawn as Cf}from"node:child_process";import{existsSync as Of,openSync as bf}from"node:fs";import{mkdir as Nf}from"node:fs/promises";import{dirname as Df}from"node:path";import{fileURLToPath as Lf}from"node:url";function Jr(n=T()){return Of(n.libEntry)?n.libEntry:Lf(new URL("../index.ts",import.meta.url))}async function ca(n={}){let e=n.paths??T(),t=n.entryOverride??Jr(e);await Nf(Df(e.logFile),{recursive:!0});let r=bf(e.logFile,"a"),i=t.endsWith(".ts")?["--import","tsx/esm",t,"--daemon"]:[t,"--daemon"],o=Cf(process.execPath,i,{detached:!0,stdio:["ignore",r,r],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Mf.info("daemon spawned",{pid:o.pid,entry:t}),{pid:o.pid,entry:t}}var Mf,Vr=K(()=>{"use strict";k();z();Mf=w("spawn-daemon")});import{spawn as Hf}from"node:child_process";import{mkdir as Wf,unlink as jf,writeFile as Jf}from"node:fs/promises";import{dirname as Vf,join as Qf}from"node:path";function Rn(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ha(n,e){return new Promise((t,r)=>{let s=Hf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Tn,Xr,Yr,ga=K(()=>{"use strict";k();Tn=w("supervisor.launchd"),Xr="ai.coze.bridge",Yr={platform:"darwin",renderConfig(n){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
18
18
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
19
19
|
<plist version="1.0">
|
|
20
20
|
<dict>
|
|
21
21
|
<key>Label</key>
|
|
22
|
-
<string>${
|
|
22
|
+
<string>${Xr}</string>
|
|
23
23
|
<key>ProgramArguments</key>
|
|
24
24
|
<array>
|
|
25
|
-
<string>${
|
|
26
|
-
<string>${
|
|
25
|
+
<string>${Rn(n.nodeBin)}</string>
|
|
26
|
+
<string>${Rn(n.entry)}</string>
|
|
27
27
|
<string>--daemon</string>
|
|
28
28
|
</array>
|
|
29
29
|
<key>RunAtLoad</key>
|
|
@@ -33,12 +33,12 @@ var k0=Object.create;var br=Object.defineProperty;var A0=Object.getOwnPropertyDe
|
|
|
33
33
|
<key>ThrottleInterval</key>
|
|
34
34
|
<integer>10</integer>
|
|
35
35
|
<key>StandardOutPath</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${Rn(n.logFile)}</string>
|
|
37
37
|
<key>StandardErrorPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${Rn(n.logFile)}</string>
|
|
39
39
|
</dict>
|
|
40
40
|
</plist>
|
|
41
|
-
`},configPath(n){return
|
|
41
|
+
`},configPath(n){return Qf(n.homeDir,"Library","LaunchAgents",`${Xr}.plist`)},async install(n){let e=this.configPath(n);await Wf(Vf(e),{recursive:!0}),await Jf(e,this.renderConfig(n),"utf8"),Tn.info("plist written",{plistPath:e}),await ha("launchctl",["load","-w",e]),Tn.info("launchd job loaded",{label:Xr})},async uninstall(n){let e=this.configPath(n);await ha("launchctl",["unload","-w",e]).catch(t=>Tn.warn("launchctl unload failed (ignored)",{err:String(t)})),await jf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),Tn.info("launchd job removed",{plistPath:e})}}});import{spawn as Kf}from"node:child_process";import{mkdir as Xf,unlink as Yf,writeFile as Zf}from"node:fs/promises";import{dirname as eh,join as th}from"node:path";function Cn(n,e){return new Promise((t,r)=>{let s=Kf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Pn,An,Zr,pa=K(()=>{"use strict";k();Pn=w("supervisor.systemd"),An="coze-bridge.service",Zr={platform:"linux",renderConfig(n){return`[Unit]
|
|
42
42
|
Description=Coze Bridge daemon
|
|
43
43
|
After=network.target
|
|
44
44
|
|
|
@@ -52,7 +52,7 @@ StandardError=append:${n.logFile}
|
|
|
52
52
|
|
|
53
53
|
[Install]
|
|
54
54
|
WantedBy=default.target
|
|
55
|
-
`},configPath(n){return
|
|
55
|
+
`},configPath(n){return th(n.homeDir,".config","systemd","user",An)},async install(n){let e=this.configPath(n);await Xf(eh(e),{recursive:!0}),await Zf(e,this.renderConfig(n),"utf8"),Pn.info("systemd unit written",{unitPath:e}),await Cn("systemctl",["--user","daemon-reload"]),await Cn("systemctl",["--user","enable","--now",An]),Pn.info("systemd unit enabled",{unitName:An})},async uninstall(n){let e=this.configPath(n);await Cn("systemctl",["--user","disable","--now",An]).catch(t=>Pn.warn("systemctl disable failed (ignored)",{err:String(t)})),await Yf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),await Cn("systemctl",["--user","daemon-reload"]).catch(()=>{}),Pn.info("systemd unit removed",{unitPath:e})}}});import{spawn as nh}from"node:child_process";import{join as rh}from"node:path";function ma(n,e){return new Promise((t,r)=>{let s=nh(n,e,{stdio:["ignore","pipe","pipe"],shell:!1}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var es,On,ts,_a=K(()=>{"use strict";k();es=w("supervisor.taskscheduler"),On="CozeBridge",ts={platform:"win32",renderConfig(n){return`<?xml version="1.0" encoding="UTF-16"?>
|
|
56
56
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
57
57
|
<RegistrationInfo>
|
|
58
58
|
<Description>Coze Bridge daemon</Description>
|
|
@@ -76,25 +76,25 @@ WantedBy=default.target
|
|
|
76
76
|
</Exec>
|
|
77
77
|
</Actions>
|
|
78
78
|
</Task>
|
|
79
|
-
`},configPath(n){return
|
|
79
|
+
`},configPath(n){return rh(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await ma("schtasks",["/Create","/SC","ONLOGON","/TN",On,"/TR",e,"/RU",n.userName,"/F"]),es.info("task scheduler entry created",{task:On})},async uninstall(n){await ma("schtasks",["/Delete","/TN",On,"/F"]).catch(e=>es.warn("schtasks /Delete failed (ignored)",{err:String(e)})),es.info("task scheduler entry removed",{task:On})}}});var ns={};Mn(ns,{buildContext:()=>ah,getSupervisor:()=>oh,launchdSupervisor:()=>Yr,systemdSupervisor:()=>Zr,taskSchedulerSupervisor:()=>ts});import{homedir as sh,userInfo as ih}from"node:os";function oh(n=process.platform){switch(n){case"darwin":return Yr;case"linux":return Zr;case"win32":return ts;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function ah(){let n=T();return{nodeBin:process.execPath,entry:Jr(n),logFile:n.logFile,homeDir:sh(),userName:ih().username}}var rs=K(()=>{"use strict";z();Vr();ga();pa();_a()});ge();k();import{readdir as Ga}from"node:fs/promises";import{mkdir as Fa,writeFile as Ua}from"node:fs/promises";import{join as $a}from"node:path";var za={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Me(n,e,t,r){await Fa(n,{recursive:!0});let s=za[e],i=$a(n,s),o=qa(e,t,r);return await Ua(i,o,"utf8"),i}function qa(n,e,t){let r=`# Coze Agent: ${e}
|
|
80
80
|
|
|
81
81
|
> framework: \`${n}\`
|
|
82
82
|
|
|
83
|
-
`,
|
|
84
|
-
`)?
|
|
83
|
+
`,s=t?.trim()?t.endsWith(`
|
|
84
|
+
`)?t:`${t}
|
|
85
85
|
`:`_No instructions provided._
|
|
86
|
-
`;return`${
|
|
86
|
+
`;return`${r}---
|
|
87
87
|
|
|
88
|
-
${
|
|
89
|
-
`)}}function Ar(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ai(n,e){if(!n.modelToken||Lt(n.model))return null;let i=kr(e),a={baseUrl:`${Cr}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:n.model,name:n.model,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(a.headers=i),a}function ci(n,e){if(!n.modelToken)return[];let i=kr(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var oe=R("agent-handlers"),ui=5*1024*1024,rc=1,sc=6,ic=new Set(["node_modules",".git",".coze","dist","build",".next"]),ln=class{constructor(e){this.opts=e}opts;async listSkills(e){Ne(e._meta,"_agent/listSkills");let i=dt(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Le(i).workspace,u=a?.skills??[],d=[];for(let h of u){let m=Ee(c,h.relPath,"SKILL.md");await ec(m).then(v=>v.isFile()).catch(()=>!1)&&d.push(uc(h))}return{skills:d}}async addSkills(e){Ne(e._meta,"_agent/addSkills");let i=dt(e._meta),a=await this.requireAgentCfg(i),c=e.skills??[],u=[...a.skills??[]],d=new Map(u.map((m,w)=>[m.skillId,w])),h=[];for(let m of c){let w=await Ir({agentId:i,workspace:a.workspace,framework:a.framework,skill:m});Tr(u,d,w),h.push(m)}return await an(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:h}}async removeSkills(e){Ne(e._meta,"_agent/removeSkills");let i=dt(e._meta),a=await this.requireAgentCfg(i),c=new Set(e.skillIds??[]),u=a.skills??[],d=[];for(let h of u){if(!c.has(h.skillId)){d.push(h);continue}let m=Ee(a.workspace,h.relPath);await Q0(m,{recursive:!0,force:!0}),oe.info("skill removed",{agentId:i,skillId:h.skillId,relPath:h.relPath})}return await an(i,d),await this.reloadAgentSessions(i,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,i){return this.reloadAgentSessions(e,i)}async reloadAgentSessions(e,i){let a=this.opts.agents.get(e);if(a&&a.framework!=="codex"){for(let[c,u]of a.sessions)if(!(!u.downstream||!u.acpSessionId)){u.loadingSession=!0;try{await u.downstream.sessionLoad({sessionId:u.acpSessionId,cwd:a.workspace}),oe.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(d){oe.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId,err:String(d)})}finally{u.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return oe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await de(i);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(oe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await we(a),await ut(a.workspace,a.framework,i,e.cozeIdentity),oe.info("_agent/update: cozeIdentity rewritten",{agentId:i,framework:a.framework}),await this.reloadAgentSessions(i,"identity-changed"),{ok:!0})}async disconnectAgent(e){let i=e.agentId;if(!i)throw new E("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let a=await de(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await we(a),oe.info("agent disconnected",{agentId:i,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(i,e.reason??"disconnect"),{ok:!0}):(oe.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Ne(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:Ge,a=await de(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await we(a),oe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return oe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};c.model=i;let u=[];for(let[d,h]of c.allSessionQueues())u.push(h.enqueue(async()=>{let m=c.sessions.get(d);m?.downstream&&(await m.downstream.stop(`switchModel: ${i}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(u),oe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:i,cloudSessions:u.length}),{ok:!0}}async resetAgent(e){if(Ne(e._meta,Se.RESET),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Se.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Ne(e._meta,Se.REPAIR),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new E("IPC_BAD_REQUEST",`${Se.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){oe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(a)})}return await this.runDetailSync(e.agentId,Se.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){oe.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){oe.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(c)})}}async getFileTree(e){Ne(e._meta,"_agent/getFileTree");let i=e._meta,a=dt(i),c=await this.resolveWorkspace(a),u=e.filePath??"",d=this.safeJoin(c,u),h=await Pr(d).catch(()=>null);if(!h)throw new E("IPC_BAD_REQUEST",`path not found: ${u}`);if(h.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let m=pc(e.depth);return h.isDirectory()?{tree:await gi(c,d,u,m)}:{tree:[{name:mc(u),path:pi(u||"."),isDir:!1,size:h.size,modifiedAt:Math.floor(h.mtimeMs)}]}}async getFileContent(e){Ne(e._meta,"_agent/getFileContent");let i=dt(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new E("IPC_BAD_REQUEST","filePath required");let c=this.safeJoin(a,e.filePath),u=await Pr(c).catch(()=>null);if(!u||!u.isFile())throw new E("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>ui)throw new E("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${ui})`);let d=await fi(c);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:u.size}:{content:d.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await de(e).catch(()=>null))?.workspace??Le(e).workspace}safeJoin(e,i){let a=nc(e,i||"."),c=li(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${hi}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return de(e)}async requireAgentCfg(e){let i=await this.loadAgentCfg(e);if(!i)throw new E("AGENT_NOT_FOUND",`no config for agent: ${e}`);return i}};function oc(n){let e=Rt(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new E("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function ac(n){return n==="claude-code"?Ee(".claude","skills"):Ee(".agents","skills")}var cc=3e4,xc=50*1024*1024,hn=3e4;async function Ir(n){let{agentId:e,workspace:i,framework:a,skill:c}=n;if(!c.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let u=typeof c.content=="string"&&c.content.length>0,d=typeof c.downloadUrl=="string"&&c.downloadUrl.length>0;if(!u&&!d)throw new E("IPC_BAD_REQUEST",`skill ${c.skillId} missing both content and downloadUrl`);let h=oc(c.skillName),m=ac(a),w=Ee(m,h),v=Ee(i,w);if(await Y0(v,{recursive:!0}),u){let C=Buffer.from(c.content,"utf8");Nt(C.length),await xi(Ee(v,"SKILL.md"),C,"utf8")}else{let C=await dc(c.downloadUrl);lc(C)?await hc(C,v):await xi(Ee(v,"SKILL.md"),C.toString("utf8"),"utf8")}let _={skillId:c.skillId,skillName:c.skillName,relPath:w,installedAt:Date.now(),...c.description?{description:c.description}:{},...c.icon?{icon:c.icon}:{},...c.version?{version:c.version}:{},...c.downloadUrl?{downloadUrl:c.downloadUrl}:{},...c.config?{config:c.config}:{},...c.builtin?{builtin:c.builtin}:{}};return oe.info("skill installed",{agentId:e,skillId:c.skillId,skillName:c.skillName,relPath:w,source:u?"content":"downloadUrl"}),_}function Tr(n,e,i){let a=e.get(i.skillId);if(a!==void 0){n[a]=i;return}e.set(i.skillId,n.length),n.push(i)}function uc(n){return{skillId:n.skillId,skillName:n.skillName,...n.description?{description:n.description}:{},...n.icon?{icon:n.icon}:{},...n.version?{version:n.version}:{},...n.config?{config:n.config}:{},...n.builtin?{builtin:n.builtin}:{}}}async function dc(n){if(!n)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);Nt(e);let i=fc(n);return Nt(i.length),i}if(n.startsWith("file:")){let e=new URL(n).pathname,i=await fi(e);return Nt(i.length),i}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),cc);try{let a=await fetch(n,{signal:e.signal});if(!a.ok)throw new E("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${n}`);let c=await a.arrayBuffer();return Nt(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new E("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function Nt(n){if(n>xc)throw new E("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function fc(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new E("IPC_BAD_REQUEST","bad data URL");let i=!!e[2],a=e[3]??"";return i?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8")}function lc(n){return n.length>=2&&n[0]===31&&n[1]===139}async function hc(n,e){await gc(n),await new Promise((i,a)=>{let c=di("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";c.stderr?.on("data",h=>{u+=String(h)});let d=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar extract timeout (${hn}ms)`))},hn);c.on("error",h=>{clearTimeout(d),a(new E("IPC_BAD_REQUEST",`tar spawn failed: ${h.message}`,{cause:h}))}),c.on("exit",h=>{clearTimeout(d),h===0?i():a(new E("IPC_BAD_REQUEST",`tar exit ${h}${u?`: ${u.trim().slice(0,200)}`:""}`))}),c.stdin?.end(n)})}async function gc(n){let e=await new Promise((i,a)=>{let c=di("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",d="";c.stdout?.on("data",m=>{u+=String(m)}),c.stderr?.on("data",m=>{d+=String(m)});let h=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar list timeout (${hn}ms)`))},hn);c.on("error",m=>{clearTimeout(h),a(new E("IPC_BAD_REQUEST",`tar list spawn failed: ${m.message}`))}),c.on("exit",m=>{clearTimeout(h),m===0?i(u):a(new E("IPC_BAD_REQUEST",`tar list exit ${m}${d?`: ${d.trim().slice(0,200)}`:""}`))}),c.stdin?.end(n)});for(let i of e.split(`
|
|
90
|
-
`)){let
|
|
91
|
-
`)[0]?.trim()||void 0}catch{return}}async function
|
|
92
|
-
`}var
|
|
93
|
-
`);this.buffer=i.pop()??"";let a=[];for(let c of i){let u=c.replace(/\r$/,"").trim();if(u)try{a.push(JSON.parse(u))}catch(d){this.onError?.({line:u,error:d})}}return a}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(i){return this.onError?.({line:e,error:i}),[]}}};var Ci={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},Fl=Object.fromEntries(Object.entries(Ci).map(([n,e])=>[e,n])),Pc={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},lt=class{seq=0;next(e,i){this.seq+=1;let a=Ci[e]??Ic(e),c=Pc[a]??[],u=[a,String(this.seq)];if(c.length>0){let d=c.map(m=>Ei(i?.[m]??"")),h=Tc(d).join(":");h&&u.push(h)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>Ei(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function Ic(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Ei(n){return n.replace(/[:_\s]+/g,"-")}function Tc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}H();var Rc=3e4,Lc=50,Nc=20,ki=500;function Oc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=ki?n:`${e.slice(0,ki)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ai(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var je=class{constructor(e){this.opts=e;this.log=R(`downstream.${this.constructor.name}`),this.decoder=new Sn({onError:i=>this.log.warn("decode line failed",{line:i.line})})}opts;child;decoder;pending=new Map;idAllocator=new lt;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new E("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=Dc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=i,i.stdout?.setEncoding("utf8"),i.stdout?.on("data",a=>{for(let c of this.decoder.push(a))this.dispatch(c)}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{let c=a.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Lc&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.on("exit",(a,c)=>{this.stopped=!0,(a!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:a,signal:c,recentStderr:this.stderrRing.slice(-Nc)}),this.failAllPending(new E("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${c})`));for(let d of this.exitHandlers)d(a,c)}),i.on("error",a=>{this.log.error("child error",{err:String(a)}),this.failAllPending(new E("AGENT_SPAWN_FAILED",String(a),{cause:a}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let i=this.child,a=new Promise(u=>i.once("exit",()=>u()));Ai(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||Ai(i.pid,"SIGKILL")},5e3);try{await a}finally{clearTimeout(c)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(yn("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,i){if(!(!this.child||this.stopped))try{this.writeFrame(ft(e,i))}catch(a){this.log.warn("respondAgentRequest write failed",{id:e,err:String(a)})}}respondAgentRequestError(e,i){if(!(!this.child||this.stopped))try{this.writeFrame(Ze(e,i))}catch(a){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(a)})}}onExit(e){this.exitHandlers.push(e)}call(e,i,a=Rc){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=zt(c,e,i),d=a>0&&Number.isFinite(a);return new Promise((h,m)=>{let w=d?setTimeout(()=>{this.pending.delete(c),m(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(c,{resolve:h,reject:m,timer:w,method:e});try{this.writeFrame(u)}catch(v){w&&clearTimeout(w),this.pending.delete(c),m(v)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new E("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Si(e))}dispatch(e){if(bn(e)){let i=e.id!==null?this.pending.get(e.id):void 0;if(!i){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),i.timer&&clearTimeout(i.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:i.method,code:e.error.code,message:e.error.message,data:e.error.data}),i.reject(bi(e.error))):(this.log.info("downstream returned result",{id:e.id,method:i.method,result:Oc(e.result)}),i.resolve(e.result));return}if(vi(e)){if(e.method==="session/update")for(let i of this.updateHandlers)Promise.resolve(i(e.params)).catch(a=>this.log.warn("update handler failed",{err:String(a)}));else this.log.debug("unknown notification",{method:e.method});return}if(yi(e)){let i=e;this.handleAgentRequest(i).catch(a=>this.log.error("agent request handler failed",{method:i.method,err:String(a)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Ze(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let i of this.agentRequestHandlers)try{await i(e)}catch(a){this.log.error("agentRequestHandler threw",{method:e.method,err:String(a)});try{this.writeFrame(Ze(e.id,Mt(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var Bc="@agentclientprotocol/claude-agent-acp@latest";function zc(n){let e={};for(let[i,a]of Object.entries(n))a!==void 0&&(i.startsWith("CLAUDE")||i==="AI_AGENT"||i==="BAGGAGE"||(e[i]=a));return e}var En=class extends je{framework="claude-code";constructor(e){let i=_n("claude-code"),[a,c]=i?[i,[]]:["npx",["-y",Bc]],u=e.command??a,d=e.args??c,h={command:u,args:d,cwd:e.cwd,...e.env?{env:e.env}:{}};super(h)}sanitizeEnv(e){return zc(e)}};import{mkdtempSync as Mc,rmSync as qc}from"node:fs";import{tmpdir as Fc}from"node:os";import{join as Uc}from"node:path";var Hc="@zed-industries/codex-acp@latest",Cn=class extends je{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=_n("codex"),[a,c]=i?[i,[]]:["npx",["-y",Hc]],u=e.command??a,d=e.args??c,h=e.extraArgs?[...d,...e.extraArgs]:d,m=e.isolateCodexHome?Mc(Uc(Fc(),"coze-bridge-codex-home-")):void 0,w=m?{...e.env??{},CODEX_HOME:m}:e.env,v={command:u,args:h,cwd:e.cwd,...w?{env:w}:{}};super(v),this.authMethodId=e.authMethodId,this.codexHomeDir=m}async initialize(e){let i=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),i}async stop(e){if(await super.stop(e),this.codexHomeDir)try{qc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var qt=class extends je{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let i=e.sessionName??"default",a=["acp","--session",`agent:${e.agentId}:${i}`];e.gatewayToken&&a.push("--token",e.gatewayToken);let c={command:e.command,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(c),this.agentId=e.agentId,this.sessionName=i,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};H();ue();var ht=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((i,a)=>{this.slots.push({task:e,resolve:i,reject:a}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let i=await e.task();e.resolve(i)}catch(i){e.reject(i)}}}finally{this.running=!1}}}};var kn=class{agentId;framework;workspace;deployType;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local"}getSessionQueue(e){let i=this.sessionQueues.get(e);return i||(i=new ht,this.sessionQueues.set(e,i)),i}allSessionQueues(){return this.sessionQueues.entries()}async dispose(e){this.status="stopped";let i=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let a of this.sessionQueues.values())a.dispose(i);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let i=[];for(let[,a]of this.sessions)Ft(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Ft(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Gc}from"node:child_process";import{homedir as jc}from"node:os";import{join as Kc}from"node:path";nn();H();async function Ti(){let n=Kc(jc(),".openclaw/openclaw.json");return(await xt(n))?.gateway?.auth?.token??""}var Pi=R("openclaw.config"),Wc=[0,5e3,5e3],Ii="models.providers.",An="agents.defaults.models",Pn=class{command;env;retryDelaysMs;queue=new ht;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Wc}async withRetry(e,i){let a;for(let c=0;c<this.retryDelaysMs.length;c++){let u=this.retryDelaysMs[c]??0;u>0&&await new Promise(d=>setTimeout(d,u));try{return await i()}catch(d){a=d,Pi.warn("openclaw cli failed, will retry",{label:e,attempt:c+1,err:String(d)})}}throw new E("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${a?.message??"unknown"}`)}runCli(e){return new Promise((i,a)=>{let c=Gc(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`exit ${d}: ${u.trim().slice(0,500)}`))})})}async runCliTolerant(e,i){try{await this.runCli(e)}catch(a){let c=String(a);if(i.some(u=>c.includes(u)))return;throw a}}async bestEffortUnset(e,i){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",i])))}catch(a){Pi.warn(`${e} failed (best-effort)`,{configPath:i,err:String(a)})}}ensureProvider(e,i){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Ii}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Ii}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${An}[${e}]`,()=>this.runCli(["config","set",An,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${An}[${e}]`,`${An}.${e}`)}ensureAgent(e,i,a){let c=["agents","add",e,"--workspace",i,"--non-interactive"];return a&&c.push("--model",a),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(c,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var Ce=R("agent-manager"),Vc=(n,e,i,a,c,u,d)=>{switch(n){case"claude-code":{let h=c?{...ri(c),...oi(c,d)}:void 0;return new En({cwd:i,...h&&Object.keys(h).length>0?{env:h}:{}})}case"codex":{let h=c?[...si(c),...ci(c,d)]:[],m=c?ii(c):void 0,w=!!c;return new Cn({cwd:i,...h.length>0?{extraArgs:h}:{},...m&&Object.keys(m).length>0?{env:m}:{},...w?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new qt({command:e,cwd:i,agentId:a,...u?{sessionName:Rt(u)}:{}})}};function Di(n){return n==="claude-code"||n==="codex"}var Xc={path:"",version:"cloud-deployed"},$c={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Yc=6e4,In=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Vc,this.createTimeoutMs=e.createTimeoutMs??Yc}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new E("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new Pn({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new E("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new E("IPC_BAD_REQUEST","framework required");let i=Dt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new E("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")Ce.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>Ce.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else return Ce.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}if(!i&&!this.config.frameworksCache?.[e.framework])throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);i&&Di(e.framework)&&await _i(e.framework);let u=Le(e.agentId,this.paths),d=e.workspace??u.workspace,h=Dt(e._meta),m=new AbortController,w=setTimeout(()=>m.abort(new E("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),v,_=!1;try{let C=()=>{if(m.signal.aborted)throw m.signal.reason instanceof Error?m.signal.reason:new E("AGENT_TIMEOUT","_agent/create aborted")};await Rr(u.root,{recursive:!0}),await Rr(d,{recursive:!0}),await Rr(u.logs,{recursive:!0}),C(),await ut(d,e.framework,e.agentId,e.cozeIdentity),C();let T=await de(e.agentId,this.paths).catch(()=>null),D=ni({model:e.model??T?.model});if(v=new kn({agentId:e.agentId,framework:e.framework,workspace:d,model:D.model??Ge,deployType:h}),v.status="ok",T?.sessions){for(let[re,Q]of Object.entries(T.sessions))v.sessions.set(re,{acpSessionId:Q.acpSessionId,modelToken:Q.modelToken,tokenGeneratedAt:Q.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let $=Object.keys(T.sessions).length;$>0&&Ce.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:$})}this.registry.register(v),_=!0;let L={agentId:e.agentId,framework:e.framework,workspace:d,cozeIdentity:e.cozeIdentity,createdAt:T?.createdAt??Date.now(),sessions:T?.sessions??{},model:D.model};h==="cloud"&&(L.deployType="cloud"),T?.skills&&(L.skills=T.skills),T?.agentName&&(L.agentName=T.agentName),T?.description&&(L.description=T.description),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,d):Ce.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let F=e.initialSkills??[];if(F.length>0){let $=[...L.skills??[]],re=new Map($.map((Y,A)=>[Y.skillId,A])),Q=0;for(let Y of F)try{let A=await Ir({agentId:e.agentId,workspace:d,framework:e.framework,skill:Y});Tr($,re,A),Q++}catch(A){Ce.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:Y.skillId,skillName:Y.skillName,err:String(A)})}Q>0&&(L.skills=$,Ce.info("initialSkills installed",{agentId:e.agentId,installed:Q,requested:F.length}))}return await we(L,this.paths),Ce.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:d,framework:e.framework}}catch(C){throw Ce.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),_&&v&&(await v.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Jc(u.root,{recursive:!0,force:!0}).catch(T=>Ce.warn("rm agent dir failed (ignored)",{err:String(T)})),C instanceof E?C:new E("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(w)}}async spawnSessionDownstream(e,i,a,c){let d=this.config.frameworksCache?.[e.framework];if(!d)if(e.deployType==="cloud"&&Di(e.framework))d=Xc;else throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let h=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,m;e.framework==="openclaw"?m=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:a,cozeEnv:c,command:d.path}):m=this.factory(e.framework,d.path,e.workspace,e.agentId,h,a,c);try{return await m.start(),await m.initialize($c),m}catch(w){throw await m.stop("spawnSessionDownstream failed").catch(()=>{}),w instanceof E?w:new E("AGENT_SPAWN_FAILED",w instanceof Error?w.message:String(w),{cause:w})}}async buildOpenclawDownstream(e){let{session:i,modelConfig:a,cloudSessionId:c,cozeEnv:u,command:d}=e,h=Rt(c),m=await Ti(),w=a?.modelToken&&!Lt(a.model)?ai(a,u):null,v;if(w){let _=Ar(c),C=`${_}/${a.model}`;if(!this.ensuredProviders.has(C)){let T=this.getOpenclawConfig();await T.ensureProvider(_,w),await T.addModelToAllowlist(C),this.ensuredProviders.add(C)}v=C}return new qt({command:d,cwd:i.workspace,agentId:i.agentId,sessionName:h,...m?{gatewayToken:m}:{},...v?{slashModelOnStart:v}:{}})}async openclawRepair(e,i){let a=this.getOpenclawConfig();await a.deleteAgent(e),await a.ensureAgent(e,i)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache;for(let a of e.sessions.keys()){let c=Ar(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};H();import{execFile as Zc}from"node:child_process";import{promisify as Qc}from"node:util";var ex=Qc(Zc),Ke=R("coze-cli-installer"),Ri="@coze/cli@0.1.3-alpha.89c42a",Li="https://bnpm.byted.org",tx="coze",nx=5e3,rx=9e4,Ni=1e4,Ut=null,Lr=!1;async function Oi(n,e={}){if(Lr)return;if(Ut)return Ut;let i=e.exec??ex;return Ut=(async()=>{try{let a=await sx(tx,i);if(a){Ke.info("coze-cli already on PATH, skip install + config + auth",{path:a}),Lr=!0;return}Ke.info("coze-cli install start",{package:Ri,registry:Li});try{await i("npm",["i","-g",Ri,"--registry",Li],{timeout:rx,maxBuffer:10*1024*1024}),Ke.info("coze-cli install ok")}catch(c){Ke.warn("coze-cli install failed (skip subsequent steps)",{err:String(c)});return}if(n.env)try{await i("coze",["config","set","xTTEnv",n.env],{timeout:Ni}),Ke.info("coze config set xTTEnv ok",{env:n.env})}catch(c){Ke.warn("coze config set failed (continue to auth login)",{err:String(c)})}try{await i("coze",["auth","login","--token",n.patToken],{timeout:Ni}),Ke.info("coze auth login ok")}catch(c){Ke.warn("coze auth login failed",{err:String(c)});return}Lr=!0}finally{Ut=null}})(),Ut}async function sx(n,e){let i=process.platform==="win32"?"where":"which";try{let{stdout:a}=await e(i,[n],{timeout:nx});return a.split(`
|
|
94
|
-
`)[0]?.trim()||void 0}catch{return}}
|
|
95
|
-
`),
|
|
96
|
-
`)}return Ui.info("fs/read_text_file ok",{path:i,size:c.length}),{content:c}}async function ji(n,e){if(typeof n!="string"||n.length===0)throw new E("IPC_BAD_REQUEST","path must be a non-empty string");let[i,a]=await Promise.all([Fi(qi(e)),Fi(qi(n))]),c=vx(i,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${bx}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return a}async function Fi(n){let e=[],i=n;for(;i!==Nr(i);)try{let a=await px(i);return e.length?yx(a,...e.reverse()):a}catch{e.push(_x(i)),i=Nr(i)}return n}He();H();var z=R("core"),Ex=3e4,Cx=3e4,Dn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new lt;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Mi(e.bridgeConfig)}registerExtension(e,i){this.extensions[e]=i}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),z.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){z.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(i=>i.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),z.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){z.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(a)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&z.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,i,a){let c=a.downstream;c&&(c.onUpdate(u=>{a.loadingSession||this.forwardUpdate(e,u)}),c.onAgentRequest(u=>{this.handleAgentRequest(e,c,u)}),c.onExit((u,d)=>{z.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),Ft(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(bn(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let i="id"in e&&e.id!==void 0?e.id:null,a=e.params?._meta?.cozeEnv;a&&(this.currentCozeEnv=a);try{if(e.method.startsWith("_agent/")){let c=this.extensions[e.method];if(!c){i!==null?await this.sendError(i,W.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):z.warn("drop notification: extension not registered",{method:e.method});return}let u=await c(e,this);i!==null&&await this.upstream.send(ft(i,u));return}if(e.method.startsWith("session/")){let c=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(ft(i,c));return}if(e.method==="initialize"){i!==null&&await this.upstream.send(ft(i,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}i!==null?await this.sendError(i,W.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):z.warn("drop unknown notification",{method:e.method})}catch(c){z.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send(Ze(i,Mt(c)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new E("IPC_BAD_REQUEST",`${e.method} requires params`);let i=e.params,a=i._meta?.cozeAgentId;if(!a)throw new E("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let c=this.agents.get(a);if(!c)throw this.disconnectedAgents.has(a)?new E("AGENT_DISCONNECTED",`agent ${a} has been disconnected; cloud must _agent/create to revive`):new E("AGENT_NOT_FOUND",`agent not found: ${a}`);let u=typeof i.sessionId=="string"?i.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!u)return this.dispatchSessionCall(c,e.method,i);let d=Date.now(),h=!1;try{let m=await c.getSessionQueue(u).enqueue(()=>this.dispatchSessionCall(c,e.method,i));return h=!0,m}finally{z.info("session call done",{agentId:c.agentId,method:e.method,durationMs:Date.now()-d,ok:h})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:c}=Js(a);switch(i){case"session/new":{let u=kx();return z.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return z.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=c,d=u.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/prompt: missing sessionId");let h=await this.ensureRuntime(e,d);if(h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new E("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let m=a._meta?.cozeTriggerMsgId;m?e.activeTriggers.set(h.acpSessionId,m):e.activeTriggers.delete(h.acpSessionId);try{let w=await h.downstream.sessionPrompt({...u,sessionId:h.acpSessionId});return h.lastActiveAt=Date.now(),w}finally{e.activeTriggers.delete(h.acpSessionId),h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=c.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/cancel: missing sessionId");let h=e.sessions.get(d);return h?.downstream?.isAlive()&&h.acpSessionId&&await h.downstream.sessionCancel({sessionId:h.acpSessionId}),{ok:!0}}default:throw new E("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(i,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let c=await this.sendRequest(Se.GEN_MODEL_TOKEN,a,Cx);if(!c?.modelToken)throw new E("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return c.modelToken}catch(c){throw c instanceof E&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new E("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,i,a){if(Ft(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new E("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let c=await this.sessionSpawner(e,a.modelToken,i,this.currentCozeEnv);if(a.downstream=c,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await c.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),z.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){z.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(u)}),a.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});a.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let u=await c.sessionNew({cwd:e.workspace});a.acpSessionId=u.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&a.acpSessionId&&await c.afterSessionEstablished(a.acpSessionId)}armIdleTimer(e,i,a){if(Ft(a),this.isRuntimeBusy(e,a)){z.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:i});return}a.idleTimer=setTimeout(()=>{if(a.idleTimer=void 0,this.isRuntimeBusy(e,a)){z.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:i}),this.armIdleTimer(e,i,a);return}z.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:i});let c=a.downstream;a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId),c&&c.stop("idle timeout").catch(u=>z.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(u)}))},this.sessionIdleTimeoutMs),a.idleTimer.unref?.()}isRuntimeBusy(e,i){if(i.acpSessionId&&e.activeTriggers.has(i.acpSessionId))return!0;let a=i.downstream;if(!a)return!1;for(let c of this.pendingUpstream.values())if(c.downstream===a)return!0;return!1}forwardUpdate(e,i){let a=i.sessionId,c=this.reverseSessionId(e,a);if(!c){z.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){z.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}if(Ax(i)){z.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:a});return}let d={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},h=e.activeTriggers.get(a);h&&(d.cozeTriggerMsgId=h),this.upstream.send(yn("session/update",{...i,sessionId:c,_meta:d})).catch(m=>z.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,i,a){if(a.method==="session/request_permission"){this.forwardPermissionRequest(e,i,a);return}if(a.method==="fs/write_text_file"||a.method==="fs/read_text_file"){this.handleFsRpcRequest(e,i,a);return}z.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:a.method}),i.respondAgentRequestError(a.id,{code:W.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}async handleFsRpcRequest(e,i,a){try{let c=e.workspace;if(a.method==="fs/write_text_file"){let u=a.params??{},d=await Hi(u,c);i.respondAgentRequest(a.id,d)}else{let u=a.params??{},d=await Gi(u,c);i.respondAgentRequest(a.id,d)}}catch(c){z.warn("fs rpc handler failed",{agentId:e.agentId,method:a.method,err:String(c)}),i.respondAgentRequestError(a.id,Mt(c))}}forwardPermissionRequest(e,i,a){let c=this.upstreamIds.next("session/request_permission"),u=a.params??{},h=u.sessionId,m=h?e.activeTriggers.get(h):void 0,w={cozeAgentId:e.agentId};m&&(w.cozeTriggerMsgId=m);let v=h?this.reverseSessionId(e,h):void 0,_={...u,...v?{sessionId:v}:{},_meta:w};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),z.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:c,acpSessionId:h,cloudSessionId:v,toolCallId:u.toolCall?.toolCallId,options:u.options?.map(C=>({optionId:C.optionId,kind:C.kind,name:C.name}))}),this.upstream.send(zt(c,"session/request_permission",_)).catch(C=>{this.pendingUpstream.delete(c),z.error("forward permission request failed",{agentId:e.agentId,err:String(C)}),i.respondAgentRequestError(a.id,{code:W.INTERNAL_ERROR,message:`upstream send failed: ${String(C)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let i=this.pendingUpstream.get(e.id);if(i){this.pendingUpstream.delete(e.id),e.error?(z.info("upstream \u2192 permission response (error)",{agentId:i.agentId,upstreamId:e.id,method:i.method,error:e.error}),i.downstream.respondAgentRequestError(i.agentRequestId,e.error)):(z.info("upstream \u2192 permission response (result)",{agentId:i.agentId,upstreamId:e.id,method:i.method,result:e.result}),i.downstream.respondAgentRequest(i.agentRequestId,e.result));return}let a=this.pendingBridge.get(e.id);if(a){this.pendingBridge.delete(e.id),clearTimeout(a.timer),e.error?a.reject(new vn(e.error)):a.resolve(e.result);return}z.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=Ex){let c=this.upstreamIds.next(e);return new Promise((u,d)=>{let h=setTimeout(()=>{this.pendingBridge.delete(c),d(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(c,{method:e,resolve:u,reject:d,timer:h}),this.upstream.send(zt(c,e,i)).catch(m=>{let w=this.pendingBridge.get(c);w&&(clearTimeout(w.timer),this.pendingBridge.delete(c)),d(m)})})}async persistSessionMapping(e){if(this.paths)try{let i=new Map;for(let[a,c]of e.sessions){let u={modelToken:c.modelToken,tokenGeneratedAt:c.tokenGeneratedAt};c.acpSessionId&&(u.acpSessionId=c.acpSessionId),i.set(a,u)}await Er(e.agentId,i,this.paths)}catch(i){z.warn("persist session mapping failed",{agentId:e.agentId,err:String(i)})}}reverseSessionId(e,i){for(let[a,c]of e.sessions.entries())if(c.acpSessionId===i)return a}sendError(e,i,a){return this.upstream.send(Ze(e,{code:i,message:a}))}};function kx(){return Sx(16).toString("hex")}function Ax(n){let e=n.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let i=e.content;if(!i||typeof i!="object")return!1;let a=i;return a.type!=="text"||typeof a.text!="string"?!1:a.text.startsWith("Model metadata for `")}H();ue();import{randomBytes as Px}from"node:crypto";import{chmod as Ix,mkdir as Tx,writeFile as Ki}from"node:fs/promises";import{createServer as Dx}from"node:http";import{dirname as Rx}from"node:path";var Lx=1e6,Or=R("ipc"),Rn=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(i=>[`${i.method} ${i.path}`,i])),this.paths=e.paths??j()}async start(){this.token=Px(32).toString("hex");let e=Dx((a,c)=>{this.dispatch(a,c)});this.server=e,await new Promise((a,c)=>{e.once("error",c),e.listen(0,"127.0.0.1",()=>a())});let i=e.address();if(!i||typeof i!="object")throw new Error("failed to obtain IPC port");return this.port=i.port,await this.persistAuthFiles(),Or.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((i,a)=>{e.close(c=>c?a(c):i())}),this.server=null)}async persistAuthFiles(){await Tx(Rx(this.paths.portFile),{recursive:!0}),await Ki(this.paths.portFile,String(this.port),"utf8"),await Ki(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Ix(this.paths.tokenFile,384)}catch(e){Or.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Ht(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){Ht(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Nx(e)}catch(h){Ht(i,400,{error:"invalid json",detail:String(h)});return}try{let h=await u.handler(d,e);Ht(i,200,h??{ok:!0})}catch(h){Or.error("IPC handler failed",{key:c,err:String(h)}),Ht(i,500,{error:h instanceof Error?h.message:String(h)})}}};function Ht(n,e,i){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(i))}async function Nx(n){let e=[],i=0;for await(let c of n){let u=c;if(i+=u.length,i>Lx)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var ha=Re(no(),1);var hd=Re(Zo(),1),gd=Re(Vn(),1),pd=Re(_t(),1),md=Re(Vr(),1),wd=Re(Yr(),1),_d=Re(rs(),1),aa=Re(Zn(),1),yd=Re(oa(),1);var ca=aa.default;H();var ne=R("upstream.frontier"),ua="application/json",da="none",er=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:$s,...dn(this.opts.ppeOverride)};class i extends ca{constructor(h){super(h,Xs,{headers:e})}send(h,...m){if(Ks("debug"))try{let w;typeof h=="string"?w=Buffer.from(h,"utf8"):h instanceof Buffer?w=h:h instanceof ArrayBuffer?w=new Uint8Array(h):ArrayBuffer.isView(h)?w=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):w=new Uint8Array(0);let v=Buffer.from(w.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:w.byteLength,headHex:v})}catch(w){ne.warn("WS raw frame dump failed",{err:String(w)})}super.send(h,...m)}}let a=Qs(this.opts.urlOverride),c={url:a,ws:i,fpID:Vs,aID:un,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ua,force:!0},payloadEncoding:{encoding:da,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new ha.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;ne.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:d,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:d})).catch(h=>ne.warn("onConnect handler threw (ignored)",{err:String(h)}))},u.onclose=d=>{this.opened=!1,ne.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{ne.warn("frontier error",{code:d.code,msg:d.message})},u.onmessage=d=>this.handleMessage(d),this.fws=u,await u.connect()}async stop(e){let i=this.fws;if(i){this.fws=null,this.opened=!1;try{i.close(1e3,e??"bridge shutdown")}catch(a){ne.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new E("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),c=e;fa(c)||ne.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:ua,payloadEncoding:da})}catch(d){throw ne.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(d)}),new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(d)}`,{cause:d})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){ne.debug("drop non-adapter frontier frame",{service:i});return}let a=Ed(e);if(!a){ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ne.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(d){ne.warn("frontier message JSON parse failed",{err:String(d),head:a.slice(0,80)});return}let u=c;fa(u)||ne.info("frontier frame in",{logid:Sd(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:u.id,method:u.method,body:bd(a)}),Promise.resolve(this.handler(c)).catch(d=>ne.warn("frontier frame handler threw",{err:String(d)}))}};function fa(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}var la=2e3;function bd(n){return n.length<=la?n:`${n.slice(0,la)}...<truncated, total ${n.length} chars>`}function Sd(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function Ed(n){let e=n.message;if(e?.textPayload)return e.textPayload;let i=e?.payload;if(!i)return null;try{return Buffer.from(i).toString("utf8")}catch{return null}}H();var is=R("upstream.switchable"),tr=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;is.info("swap upstream",{reason:i});let a=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(c){throw is.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>is.warn("previous upstream stop threw (ignored)",{err:String(c)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};H();var os=R("upstream"),Yt=class{handler=null;async start(){os.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){os.info("NoopUpstream stopped",{reason:e})}async send(e){os.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};H();ue();H();ue();import{execSync as Cd}from"node:child_process";import{readFileSync as ga,unlinkSync as kd}from"node:fs";import{mkdir as Ad,readFile as pa,unlink as ma,writeFile as Pd}from"node:fs/promises";import{dirname as Id}from"node:path";var Td=R("single-instance"),nr=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??j().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(Td.warn("removing stale pid file",{stalePid:e}),await ma(this.pidFile).catch(()=>{})),await Ad(Id(this.pidFile),{recursive:!0}),await Pd(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await pa(this.pidFile,"utf8")).trim()===String(process.pid)&&await ma(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await pa(this.pidFile,"utf8"),i=Number.parseInt(e.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){try{process.kill(e,0)}catch(i){return i.code==="EPERM"}return this.matchesDaemonTitle(e)}matchesDaemonTitle(e){try{let i=ga(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=Cd(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return i.trim()?i.includes("coze-bridge-daemon")||i.includes("lib/index.js"):!1}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{ga(this.pidFile,"utf8").trim()===String(process.pid)&&kd(this.pidFile)}catch{}})}};var B=R("daemon"),Dd="coze-bridge-daemon";async function ya(){let n=new nr({processTitle:Dd}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await Tn(),a=i??{};Sr({pid:process.pid}),B.info(i?"loaded bridge config":"initialized bridge config");try{let A=new gt;a.frameworksCache=await A.detectAll(),B.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(A){B.warn("framework detection failed",{err:String(A)})}await pt(a);let c=new tr(new Yt),u=j(),d=null,h=new Dn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(A,U,K,se)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(A,U,K,se)}});await Ld(u,h);let m=new In({paths:u,config:a,registry:h});d=m;let w,v,_=null,C=null;h.registerExtension("_agent/create",async A=>m.createAgent(A.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let T={},D=new ln({agents:h.agents,disposeAndMarkDisconnected:async(A,U)=>{let K=h.agents.get(A);K&&(await m.cleanupOpenclawSessionProviders(K).catch(se=>B.warn("cleanup openclaw providers failed (ignored)",{agentId:A,err:String(se)})),await K.dispose(`disconnect: ${U}`).catch(se=>B.warn("dispose during disconnect failed (ignored)",{agentId:A,err:String(se)})),K.status="disconnected",h.unregister(A)),h.disconnectedAgents.add(A)},detailSyncer:async A=>{if(!T.ref)throw new Error("agent-detail-sync not initialized yet");await T.ref.syncOne(A)},openclawRepair:async(A,U)=>{await m.openclawRepair(A,U)}});h.registerExtension("_agent/listSkills",A=>D.listSkills(A.params)),h.registerExtension("_agent/addSkills",A=>D.addSkills(A.params)),h.registerExtension("_agent/removeSkills",A=>D.removeSkills(A.params)),h.registerExtension("_agent/getFileTree",A=>D.getFileTree(A.params)),h.registerExtension("_agent/getFileContent",A=>D.getFileContent(A.params)),h.registerExtension("_agent/update",A=>D.updateAgent(A.params)),h.registerExtension("_agent/disconnect",A=>D.disconnectAgent(A.params)),h.registerExtension("_agent/switchModel",A=>D.switchModel(A.params)),h.registerExtension("_agent/reset",A=>D.resetAgent(A.params)),h.registerExtension("_agent/repair",A=>D.repairAgent(A.params));let L=new xn({paths:u,handlers:D,sendDetail:A=>h.sendRequest("_agent/detail",A)});T.ref=L,c.onConnect(({initial:A})=>{B.info("frontier upstream connected, triggering detail sync",{initial:A}),L.syncAll(A?"initial-connect":"reconnect").catch(U=>B.warn("detail sync top-level error (ignored)",{err:String(U)}))});let F=new Rn({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...h.agents.keys()],deviceId:_??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async A=>{let U=A,K=U?.privatecode,se=U?.pairing_code;if(!K||!se)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ie=fn(U.env),pe=U.handshake_url,Xe=U.frontier_url,kt=Rd(U.env,pe,Xe),Zt=!!w&&w!==K,ye=v!==void 0&&v!==kt,ve=Zt||ye;if(ve){B.warn("pair config switched, resetting agents",{pcChanged:Zt,envChanged:ye,previousPc:w?wa(w):"",nextPc:wa(K),previousEnvKey:v??"",nextEnvKey:kt});for(let M of[...h.agents.values()])await M.dispose("pair config switch").catch(()=>{}),h.agents.delete(M.agentId);await c.swap(new Yt,"pair switch").catch(()=>{})}let Qt=await ti({privatecode:K,...pe?{endpoint:pe}:{},ppeOverride:Ie});_=Qt.deviceId,Sr({deviceId:_,pid:process.pid}),Oi({patToken:K,env:U.env}).catch(M=>B.warn("coze-cli setup error (ignored)",{err:String(M)}));let ae=new er({handshake:Qt,privatecode:K,...Xe?{urlOverride:Xe}:{},ppeOverride:Ie});await c.swap(ae,"pair");try{let M=new gt;a.frameworksCache=await M.detectAll(),await pt(a),B.info("frameworks_cache refreshed before pair",{detected:Object.keys(a.frameworksCache)})}catch(M){B.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(M)})}let en=Object.keys(a.frameworksCache??{});try{let M=await h.sendRequest("_agent/pair",{pairCode:se,patToken:K,frameworks:en,_meta:{cozeDeviceId:_}});B.info("_agent/pair ok",{pairResult:M}),w=K,v=kt,C||(C=new pn({core:h,getDeviceId:()=>_??""})),C.start(),ve&&_a(u,m).catch(Te=>B.warn("post-pair-switch auto-revive error (ignored)",{err:String(Te)}));let J;return U.agent_id&&(J=await Nd(U.agent_id,u,m,Te=>h.sendRequest("_agent/detail",Te)).catch(Te=>(B.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Te)}),{ok:!1,agentId:U.agent_id??"",note:String(Te)}))),{ok:!0,note:"paired with cloud",...J?{agent:J}:{}}}catch(M){return B.error("_agent/pair failed",{err:String(M)}),{ok:!1,note:`pair failed: ${String(M)}`}}}},{method:"POST",path:"/_agent/create",handler:async A=>{let U=A;return{ok:!0,result:await m.createAgent(U)}}},{method:"POST",path:"/refresh",handler:async()=>{B.info("IPC /refresh: re-detecting frameworks");let A=new gt;return a.frameworksCache=await A.detectAll(),await pt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(B.info("IPC /shutdown received"),setImmediate(()=>{Y.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:$,token:re}=await F.start();await h.start(),_a(u,m).catch(A=>B.warn("auto-revive top-level error (ignored)",{err:String(A)}));let Q=null,Y={port:$,token:re,core:h,ipc:F,shutdown(A){return Q||(B.info("daemon shutdown",{reason:A}),Q=(async()=>{C?.stop(),await h.stop(A),await F.stop(),await n.release()})(),Q)}};for(let A of["SIGTERM","SIGINT"])process.on(A,()=>{Y.shutdown(A).then(()=>process.exit(0))});return B.info("daemon ready",{port:$,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),Y}function wa(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function Rd(n,e,i){return`${n??""}|${e??""}|${i??""}`}async function Ld(n,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(n.agentsRoot)}catch{return}let{loadAgentConfig:c,enforceAgentConfigMode:u}=await Promise.resolve().then(()=>(He(),cn));for(let d of a){await u(d,n).catch(h=>B.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(h)}));try{let h=await c(d,n);h?.disconnectedAt&&(e.disconnectedAgents.add(d),B.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:h.disconnectedAt,reason:h.disconnectReason??""}))}catch(h){B.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(h)})}}}async function Nd(n,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(He(),cn)),u=await c(n,e);if(u){B.info("--agent-id: local config found, reconnecting",{agentId:n,framework:u.framework,hadDisconnect:!!u.disconnectedAt});let w={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{}};return await i.createAgent(w),{ok:!0,agentId:n,note:u.disconnectedAt?"revived from local config":"connected from local config"}}B.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let d=await a({_meta:{cozeAgentId:n}});if(!d.framework)throw new E("AGENT_NOT_FOUND",`agent ${n} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...d.deployType?{_meta:{cozeDeployType:d.deployType}}:{}};await i.createAgent(h);let m=d.deployType==="cloud"&&d.framework==="openclaw";return{ok:!0,agentId:n,note:m?"cloud agent acknowledged":"created from cloud detail"}}async function _a(n,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(n.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(a.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:c}=await Promise.resolve().then(()=>(He(),cn));B.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,d=0;for(let h of a){let m;try{m=await c(h,n)}catch(w){B.warn("auto-revive: load config failed (skipping)",{agentId:h,err:String(w)}),d+=1;continue}if(!m){d+=1;continue}if(m.disconnectedAt){B.info("auto-revive: skip disconnected agent",{agentId:h,disconnectedAt:m.disconnectedAt}),d+=1;continue}try{B.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:h,framework:m.framework}),await e.createAgent({agentId:m.agentId,framework:m.framework,...m.cozeIdentity?{cozeIdentity:m.cozeIdentity}:{},...m.model?{model:m.model}:{},...m.deployType?{_meta:{cozeDeployType:m.deployType}}:{}}),u+=1}catch(w){B.warn("auto-revive: createAgent failed (skipping)",{agentId:h,framework:m.framework,err:String(w)}),d+=1}}return B.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}cs();ue();import{readFile as ba}from"node:fs/promises";var Ve=class{paths;constructor(e){this.paths=e??j()}async probe(e=1e3){let i=await this.readAuth();if(!i)return{kind:"not-running"};try{let a=await this.fetch(i,{method:"GET",path:"/status",timeoutMs:e});return a.status===200?{kind:"connected",...i}:{kind:"stale",reason:`unexpected status ${a.status}`}}catch(a){return{kind:"stale",reason:Gd(a)}}}async request(e){let i=await this.readAuth();if(!i)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(i,e)}async readAuth(){try{let[e,i]=await Promise.all([ba(this.paths.portFile,"utf8"),ba(this.paths.tokenFile,"utf8")]),a=Number.parseInt(e.trim(),10),c=i.trim();return!Number.isFinite(a)||a<=0||!c?null:{port:a,token:c}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,i){let a=i.body!==void 0,c={Authorization:`Bearer ${e.token}`};a&&(c["content-type"]="application/json");let u=new AbortController,d=setTimeout(()=>u.abort(),i.timeoutMs??5e3);try{let h=await fetch(`http://127.0.0.1:${e.port}${i.path}`,{method:i.method,headers:c,body:a?JSON.stringify(i.body):void 0,signal:u.signal}),m=await h.text();return{status:h.status,body:Hd(m)}}finally{clearTimeout(d)}}};function Hd(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function Gd(n){return n instanceof Error?n.message:String(n)}H();ue();import{copyFile as Sa,mkdir as jd,readFile as xs,writeFile as Kd}from"node:fs/promises";import{dirname as Wd,resolve as us,sep as rr}from"node:path";import{fileURLToPath as Jd}from"node:url";H();ue();var Ea=R("dist-install");function Vd(n){let e=Jd(n),i=Wd(e),a=`${rr}src${rr}`;if(i.includes(a)||i.endsWith(`${rr}src${rr}cli`))return null;let c=us(i,"index.js"),u=us(i,"..","package.json");return{dist:c,pkgJson:u}}async function Ca(n={}){let e=n.paths??j(),i=Vd(import.meta.url),a=n.sourceDist??i?.dist,c=n.sourcePackageJson??i?.pkgJson;if(!a||!c)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let u;try{u=JSON.parse(await xs(c,"utf8")).version??"unknown"}catch(_){return Ea.warn("cannot read source package.json,skip dist install",{err:String(_)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(_)}`}}let d=await Tn(e.configFile)??{},h=d.libVersion;if(h===u)try{return await xs(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await jd(e.libDir,{recursive:!0}),await Sa(a,e.libEntry),await Sa(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let m=us(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
-
`;return await
|
|
88
|
+
${s}`}var ee=w("agent-detail-sync"),Lt=class{constructor(e){this.opts=e}opts;async syncAll(e){let t=this.opts.paths.agentsRoot,r;try{r=await Ga(t)}catch(s){ee.info("agents dir not found, skip detail sync",{root:t,err:String(s)});return}ee.info("starting detail sync",{reason:e,count:r.length});for(let s of r)try{await this.syncOne(s)}catch(i){ee.warn("detail sync failed for agent, skipping",{agentId:s,err:String(i)})}ee.info("detail sync done",{reason:e})}async syncOne(e){let t=await q(e,this.opts.paths);if(!t){ee.info("detail sync: agent config missing, skip",{agentId:e});return}let r;try{r=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(o){ee.warn("detail RPC failed, using local data",{agentId:e,err:String(o)});return}if(r.agentId&&r.agentId!==e){ee.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:r.agentId});return}let s=!1,i=!1;if(r.agentName&&r.agentName!==t.agentName&&(t.agentName=r.agentName,s=!0),r.description!==void 0&&r.description!==t.description&&(t.description=r.description,s=!0),r.cozeIdentity&&r.cozeIdentity!==t.cozeIdentity&&(t.cozeIdentity=r.cozeIdentity,s=!0,i=!0),r.deployType&&ee.info("detail.deployType",{agentId:e,deployType:r.deployType}),!s){ee.debug("detail sync: no diff",{agentId:e});return}await X(t,this.opts.paths),ee.info("detail sync: config updated",{agentId:e,identityChanged:i,agentName:t.agentName}),i&&(await Me(t.workspace,t.framework,e,t.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};ge();import{spawn as Ns}from"node:child_process";import{lstat as qn,mkdir as Ja,readFile as Ds,readdir as Va,rm as Qa,stat as Ka,writeFile as Os}from"node:fs/promises";import{join as re,normalize as Xa,relative as Ls,resolve as Ya,sep as Ms}from"node:path";var te={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",DELETE:"_agent/delete"};function rt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function gs(n){let{_meta:e,...t}=n;return{stripped:t,meta:e}}function Be(n){if(!n?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return n.cozeAgentId}var h=class extends Error{code;retriable;cause;constructor(e,t,r){super(t),this.name="BridgeError",this.code=e,this.retriable=r?.retriable??!1,r?.cause!==void 0&&(this.cause=r.cause)}};k();z();function ce(n,e){if(rt(n)!=="cloud")throw new h("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function st(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}k();var Mt="1008033",ps="1289";var ms="pbbp2",_s="https://www.coze.cn",ws="/api/coze_claw/resource/get_frontier_key",Ha="https://www.coze.cn",Wa="wss://frontier.coze.cn";function ys(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??Ha}function Ss(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??Wa}function Bt(n){let e={},t=n?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,r=n?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return t&&(e["x-tt-env"]=t),r&&(e["x-use-ppe"]=r),e}function Ft(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var Es=w("handshake");async function vs(n){let e=ys(n.endpoint),t=n.timeoutMs??1e4,r=`${ja(e)}${ws}?aid=${encodeURIComponent(Mt)}`,s={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...Bt(n.ppeOverride)},i=new AbortController,o=setTimeout(()=>i.abort(),t);Es.info("frontier key handshake",{base:e});try{let a=await fetch(r,{method:"GET",headers:s,signal:i.signal}),c=a.headers.get("x-tt-logid")??"",l=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let p=await a.text().catch(()=>"");throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${p.slice(0,200)}`)}let d=await a.json();if(d.code!==void 0&&d.code!==0)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${d.code} msg=${d.msg??"-"} logid=${c}`);let f=d.data?.access_key,u=d.data?.device_id;if(!f||!u)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${c}: ${JSON.stringify(d)}`);return Es.info("handshake ok",{remoteDeviceId:u,logid:c,traceId:l}),{accessKey:f,deviceId:u}}catch(a){throw a instanceof h?a:a.name==="AbortError"?new h("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${t}ms)`):new h("UPSTREAM_HANDSHAKE_FAILED",String(a),{cause:a})}finally{clearTimeout(o)}}function ja(n){return n.endsWith("/")?n.slice(0,-1):n}var Un="https://llm-gateway.coze.cn",ne="auto";function ks(n){return{model:n.model??ne,...n.modelToken?{modelToken:n.modelToken}:{}}}function Is(n){return!n||n===ne}function xs(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=Un,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||ne):Is(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function Ts(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||ne}"`):Is(n.model)||e.push("-c",`model="${n.model}"`),n.modelToken&&(e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Un}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"')),e}function Rs(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function $n(n){let{ttEnv:e,usePpe:t}=Ft(n),r={};return e&&(r["x-tt-env"]=e),t&&(r["x-use-ppe"]=t),r}function Ps(n,e){if(!n.modelToken)return{};let t=$n(e);return Object.keys(t).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(t).map(([s,i])=>`${s}:${i}`).join(`
|
|
89
|
+
`)}}function zn(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function As(n,e){if(!n.modelToken)return null;let t=n.model||ne,r=$n(e),s={baseUrl:`${Un}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:t,name:t,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(r).length>0&&(s.headers=r),s}function Cs(n,e){if(!n.modelToken)return[];let t=$n(e),r=[];for(let[s,i]of Object.entries(t))r.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return r}var M=w("agent-handlers"),bs=5*1024*1024,Za=1,ec=6,tc=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ut=class{constructor(e){this.opts=e}opts;async listSkills(e){ce(e._meta,"_agent/listSkills");let t=Be(e._meta),r=await this.loadAgentCfg(t),s=r?.workspace??ae(t).workspace,i=r?.skills??[],o=[];for(let a of i){let c=re(s,a.relPath,"SKILL.md");await Ka(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(oc(a))}return{skills:o}}async addSkills(e){ce(e._meta,"_agent/addSkills");let t=Be(e._meta),r=await this.requireAgentCfg(t),s=e.skills??[],i=[...r.skills??[]],o=new Map(i.map((c,l)=>[c.skillId,l])),a=[];for(let c of s){let l=await Gn({agentId:t,workspace:r.workspace,framework:r.framework,skill:c});Hn(i,o,l),a.push(c)}return await Nt(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){ce(e._meta,"_agent/removeSkills");let t=Be(e._meta),r=await this.requireAgentCfg(t),s=new Set(e.skillIds??[]),i=r.skills??[],o=[];for(let a of i){if(!s.has(a.skillId)){o.push(a);continue}let c=re(r.workspace,a.relPath);await Qa(c,{recursive:!0,force:!0}),M.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await Nt(t,o),await this.reloadAgentSessions(t,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,t){return this.reloadAgentSessions(e,t)}async reloadAgentSessions(e,t){let r=this.opts.agents.get(e);if(r&&r.framework!=="codex"){for(let[s,i]of r.sessions)if(!(!i.downstream||!i.acpSessionId)){i.loadingSession=!0;try{await i.downstream.sessionLoad({sessionId:i.acpSessionId,cwd:r.workspace}),M.info("session reloaded",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){M.warn("session reload failed",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId,err:String(o)})}finally{i.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return M.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,r=await q(t);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return r.cozeIdentity===e.cozeIdentity?(M.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(r.cozeIdentity=e.cozeIdentity,await X(r),await Me(r.workspace,r.framework,t,e.cozeIdentity),M.info("_agent/update: cozeIdentity rewritten",{agentId:t,framework:r.framework}),await this.reloadAgentSessions(t,"identity-changed"),{ok:!0})}async disconnectAgent(e){let t=e.agentId;if(!t)throw new h("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let r=await q(t);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await X(r),M.info("agent disconnected",{agentId:t,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(t,e.reason??"disconnect"),{ok:!0}):(M.warn("_agent/disconnect: agent not found, ignoring",{agentId:t}),{ok:!0})}async switchModel(e){if(ce(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:ne,r=await q(e.agentId);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=t,await X(r),M.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return M.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};s.model=t;let i=[];for(let[o,a]of s.allSessionQueues())i.push(a.enqueue(async()=>{let c=s.sessions.get(o);c?.downstream&&(await c.downstream.stop(`switchModel: ${t}`).catch(()=>{}),c.downstream=void 0)}));return await Promise.all(i),M.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:t,cloudSessions:i.length}),{ok:!0}}async resetAgent(e){if(ce(e._meta,te.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${te.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,te.RESET,e.reason),{ok:!0}}async repairAgent(e){if(ce(e._meta,te.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${te.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${te.REPAIR} only allowed for openclaw, got ${t.framework}`);if(t&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,t.workspace)}catch(r){M.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,te.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,r){if(!this.opts.detailSyncer){M.warn("detailSyncer not wired, skipping sync",{method:t,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){M.warn("detail sync failed (ignored)",{method:t,agentId:e,reason:r,err:String(s)})}}async getFileTree(e){ce(e._meta,"_agent/getFileTree");let t=e._meta,r=Be(t),s=await this.resolveWorkspace(r),i=e.filePath??"",o=this.safeJoin(s,i),a=await qn(o).catch(()=>null);if(!a)throw new h("IPC_BAD_REQUEST",`path not found: ${i}`);if(a.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${i}`);let c=fc(e.depth);return a.isDirectory()?{tree:await Bs(s,o,i,c)}:{tree:[{name:hc(i),path:Fs(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){ce(e._meta,"_agent/getFileContent");let t=Be(e._meta),r=await this.resolveWorkspace(t);if(!e.filePath)throw new h("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(r,e.filePath),i=await qn(s).catch(()=>null);if(!i||!i.isFile())throw new h("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(i.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(i.size>bs)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${bs})`);let o=await Ds(s);return o.includes(0)?{content:o.toString("base64"),encoding:"base64",size:i.size}:{content:o.toString("utf8"),encoding:"utf-8",size:i.size}}async resolveWorkspace(e){let t=this.opts.agents.get(e);return t?t.workspace:(await q(e).catch(()=>null))?.workspace??ae(e).workspace}safeJoin(e,t){let r=Ya(e,t||"."),s=Ls(e,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${Ms}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}loadAgentCfg(e){return q(e)}async requireAgentCfg(e){let t=await this.loadAgentCfg(e);if(!t)throw new h("AGENT_NOT_FOUND",`no config for agent: ${e}`);return t}};function nc(n){let e=st(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function rc(n){return n==="claude-code"?re(".claude","skills"):re(".agents","skills")}var sc=3e4,ic=50*1024*1024,$t=3e4;async function Gn(n){let{agentId:e,workspace:t,framework:r,skill:s}=n;if(!s.skillName)throw new h("IPC_BAD_REQUEST","skill missing skillName");let i=typeof s.content=="string"&&s.content.length>0,o=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!i&&!o)throw new h("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let a=nc(s.skillName),c=rc(r),l=re(c,a),d=re(t,l);if(await Ja(d,{recursive:!0}),i){let u=Buffer.from(s.content,"utf8");it(u.length),await Os(re(d,"SKILL.md"),u,"utf8")}else{let u=await ac(s.downloadUrl);lc(u)?await dc(u,d):await Os(re(d,"SKILL.md"),u.toString("utf8"),"utf8")}let f={skillId:s.skillId,skillName:s.skillName,relPath:l,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return M.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:l,source:i?"content":"downloadUrl"}),f}function Hn(n,e,t){let r=e.get(t.skillId);if(r!==void 0){n[r]=t;return}e.set(t.skillId,n.length),n.push(t)}function oc(n){return{skillId:n.skillId,skillName:n.skillName,...n.description?{description:n.description}:{},...n.icon?{icon:n.icon}:{},...n.version?{version:n.version}:{},...n.config?{config:n.config}:{},...n.builtin?{builtin:n.builtin}:{}}}async function ac(n){if(!n)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);it(e);let t=cc(n);return it(t.length),t}if(n.startsWith("file:")){let e=new URL(n).pathname,t=await Ds(e);return it(t.length),t}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),sc);try{let r=await fetch(n,{signal:e.signal});if(!r.ok)throw new h("IPC_BAD_REQUEST",`fetch skill failed HTTP ${r.status} ${n}`);let s=await r.arrayBuffer();return it(s.byteLength),Buffer.from(s)}finally{clearTimeout(t)}}throw new h("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function it(n){if(n>ic)throw new h("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function cc(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new h("IPC_BAD_REQUEST","bad data URL");let t=!!e[2],r=e[3]??"";return t?Buffer.from(r,"base64"):Buffer.from(decodeURIComponent(r),"utf8")}function lc(n){return n.length>=2&&n[0]===31&&n[1]===139}async function dc(n,e){await uc(n),await new Promise((t,r)=>{let s=Ns("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),i="";s.stderr?.on("data",a=>{i+=String(a)});let o=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar extract timeout (${$t}ms)`))},$t);s.on("error",a=>{clearTimeout(o),r(new h("IPC_BAD_REQUEST",`tar spawn failed: ${a.message}`,{cause:a}))}),s.on("exit",a=>{clearTimeout(o),a===0?t():r(new h("IPC_BAD_REQUEST",`tar exit ${a}${i?`: ${i.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)})}async function uc(n){let e=await new Promise((t,r)=>{let s=Ns("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),i="",o="";s.stdout?.on("data",c=>{i+=String(c)}),s.stderr?.on("data",c=>{o+=String(c)});let a=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar list timeout (${$t}ms)`))},$t);s.on("error",c=>{clearTimeout(a),r(new h("IPC_BAD_REQUEST",`tar list spawn failed: ${c.message}`))}),s.on("exit",c=>{clearTimeout(a),c===0?t(i):r(new h("IPC_BAD_REQUEST",`tar list exit ${c}${o?`: ${o.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)});for(let t of e.split(`
|
|
90
|
+
`)){let r=t.trim();if(!r)continue;let s=r.charCodeAt(0);if(s!==45&&s!==100)throw new h("IPC_BAD_REQUEST",`tar entry kind '${r[0]}' not allowed (symlink/hardlink/special): ${r.slice(0,100)}`);let o=(r.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!o)continue;if(o.startsWith("/"))throw new h("IPC_BAD_REQUEST",`tar entry absolute path: ${o}`);if(o.split(/[/\\]/).some(c=>c===".."))throw new h("IPC_BAD_REQUEST",`tar entry contains '..': ${o}`)}}async function Bs(n,e,t,r){if(r<=0)return[];let s;try{s=await Va(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(tc.has(o.name)||o.isSymbolicLink())continue;let a=re(e,o.name),c=Xa(re(t,o.name)),l=null;try{l=await qn(a)}catch{continue}if(l.isSymbolicLink())continue;let d={name:o.name,path:Fs(Ls(n,a)),isDir:l.isDirectory(),size:l.size,modifiedAt:Math.floor(l.mtimeMs)};l.isDirectory()&&r>1&&(d.children=await Bs(n,a,c,r-1)),i.push(d)}return i.sort((o,a)=>o.isDir!==a.isDir?o.isDir?-1:1:o.name.localeCompare(a.name)),i}function fc(n){return!n||n<=0?Za:Math.min(n,ec)}function hc(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function Fs(n){return n.split(Ms).join("/")}k();import{readFileSync as gg}from"node:fs";import{dirname as mg,join as _g}from"node:path";import{fileURLToPath as yg}from"node:url";var zt="0.1.33";var ot=w("agent-health-reporter"),gc=1e4,qt=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??gc}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),ot.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),ot.info("heartbeat stopped"))}async tick(){if(this.inFlight){ot.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){ot.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let t=[];for(let s of this.opts.core.agents.values()){let i=pc(s);i&&t.push({agentId:s.agentId,status:i})}if(t.length===0)return;let r={agents:t,bridgeVersion:zt,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",r)}catch(s){ot.warn("heartbeat batch send failed",{count:t.length,err:String(s)})}}finally{this.inFlight=!1}}};function pc(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}ge();import{mkdir as jn,rm as Gc}from"node:fs/promises";k();import{execFile as mc}from"node:child_process";import{promisify as _c}from"node:util";var $s=_c(mc),at=w("agents.acp-installer"),wc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},yc=5e4,Sc=5e3,Ec=5*6e4,Ht=new Map,Gt=new Map,Wn=new Map;async function Us(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:t}=await $s(e,[n],{timeout:Sc});return t.split(`
|
|
91
|
+
`)[0]?.trim()||void 0}catch{return}}async function vc(n){at.info("npm install -g start",{npmPackage:n}),await $s("npm",["install","-g",`${n}@latest`],{timeout:yc,maxBuffer:10*1024*1024}),at.info("npm install -g done",{npmPackage:n})}async function zs(n){let e=wc[n];if(!e)return;let t=Ht.get(n);if(t)return t;let r=Gt.get(n);if(r&&Date.now()-r<Ec)return;let s=Wn.get(n);if(s)return s;let i=(async()=>{let o=await Us(e.binary);if(o)return Ht.set(n,o),at.info("acp wrapper found on PATH",{binary:e.binary,path:o}),o;try{await vc(e.npmPackage)}catch(c){at.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(c)}),Gt.set(n,Date.now());return}let a=await Us(e.binary);if(!a){at.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),Gt.set(n,Date.now());return}return Ht.set(n,a),Gt.delete(n),a})().finally(()=>{Wn.delete(n)});return Wn.set(n,i),i}function Wt(n){return Ht.get(n)}import{spawn as Rc}from"node:child_process";function ct(n,e,t){return t===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:t}}function jt(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function Fe(n,e){return{jsonrpc:"2.0",id:n,result:e}}function ve(n,e){return{jsonrpc:"2.0",id:n,error:e}}var Jt=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},R={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009};function qs(n){return"method"in n&&"id"in n&&n.id!==void 0}function Gs(n){return"method"in n&&!("id"in n)}function Vt(n){return!("method"in n)&&"id"in n}var kc={AGENT_NOT_FOUND:R.AGENT_NOT_FOUND,AGENT_BUSY:R.AGENT_BUSY,AGENT_DISCONNECTED:R.AGENT_DISCONNECTED,AGENT_TIMEOUT:R.AGENT_TIMEOUT,AGENT_SPAWN_FAILED:R.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:R.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:R.INTERNAL_ERROR,BRIDGE_INTERNAL:R.INTERNAL_ERROR,IPC_AUTH_FAILED:R.INTERNAL_ERROR,IPC_BAD_REQUEST:R.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:R.MODEL_TOKEN_GEN_FAILED,OPERATION_NOT_ALLOWED_FOR_LOCAL:R.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:R.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:R.INTERNAL_ERROR};function lt(n){return n instanceof h?{code:kc[n.code]??R.INTERNAL_ERROR,message:n.message,data:{bridgeCode:n.code,retriable:n.retriable}}:{code:R.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)}}function Hs(n){let e=n.data,t=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new h(t,n.message,{retriable:e?.retriable??!1,cause:n.data})}function Ws(n){return`${JSON.stringify(n)}
|
|
92
|
+
`}var Qt=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let t=this.buffer.split(`
|
|
93
|
+
`);this.buffer=t.pop()??"";let r=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{r.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return r}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(t){return this.onError?.({line:e,error:t}),[]}}};var Js={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},Dg=Object.fromEntries(Object.entries(Js).map(([n,e])=>[e,n])),Ic={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},Ue=class{seq=0;next(e,t){this.seq+=1;let r=Js[e]??xc(e),s=Ic[r]??[],i=[r,String(this.seq)];if(s.length>0){let o=s.map(c=>js(t?.[c]??"")),a=Tc(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>js(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function xc(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function js(n){return n.replace(/[:_\s]+/g,"-")}function Tc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}k();var Pc=3e4,Ac=50,Cc=20,Vs=500;function Oc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=Vs?n:`${e.slice(0,Vs)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Qs(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var pe=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Qt({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Ue;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new h("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",t=Rc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=t,t.stdout?.setEncoding("utf8"),t.stdout?.on("data",r=>{for(let s of this.decoder.push(r))this.dispatch(s)}),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{let s=r.trimEnd();this.stderrRing.push(s),this.stderrRing.length>Ac&&this.stderrRing.shift(),this.log.debug("stderr",{text:s})}),t.on("exit",(r,s)=>{this.stopped=!0,(r!==0||s!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:r,signal:s,recentStderr:this.stderrRing.slice(-Cc)}),this.failAllPending(new h("AGENT_PROTOCOL_ERROR",`agent exited (${r}/${s})`));for(let o of this.exitHandlers)o(r,s)}),t.on("error",r=>{this.log.error("child error",{err:String(r)}),this.failAllPending(new h("AGENT_SPAWN_FAILED",String(r),{cause:r}))}),this.log.info("downstream started",{command:this.opts.command,pid:t.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let t=this.child,r=new Promise(i=>t.once("exit",()=>i()));Qs(t.pid,"SIGTERM");let s=setTimeout(()=>{t.killed||Qs(t.pid,"SIGKILL")},5e3);try{await r}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(jt("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Fe(e,t))}catch(r){this.log.warn("respondAgentRequest write failed",{id:e,err:String(r)})}}respondAgentRequestError(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(ve(e,t))}catch(r){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(r)})}}onExit(e){this.exitHandlers.push(e)}call(e,t,r=Pc){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=ct(s,e,t),o=r>0&&Number.isFinite(r);return new Promise((a,c)=>{let l=o?setTimeout(()=>{this.pending.delete(s),c(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r):null;this.pending.set(s,{resolve:a,reject:c,timer:l,method:e});try{this.writeFrame(i)}catch(d){l&&clearTimeout(l),this.pending.delete(s),c(d)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new h("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Ws(e))}dispatch(e){if(Vt(e)){let t=e.id!==null?this.pending.get(e.id):void 0;if(!t){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),t.timer&&clearTimeout(t.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:t.method,code:e.error.code,message:e.error.message,data:e.error.data}),t.reject(Hs(e.error))):(this.log.info("downstream returned result",{id:e.id,method:t.method,result:Oc(e.result)}),t.resolve(e.result));return}if(Gs(e)){if(e.method==="session/update")for(let t of this.updateHandlers)Promise.resolve(t(e.params)).catch(r=>this.log.warn("update handler failed",{err:String(r)}));else this.log.debug("unknown notification",{method:e.method});return}if(qs(e)){let t=e;this.handleAgentRequest(t).catch(r=>this.log.error("agent request handler failed",{method:t.method,err:String(r)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(ve(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let t of this.agentRequestHandlers)try{await t(e)}catch(r){this.log.error("agentRequestHandler threw",{method:e.method,err:String(r)});try{this.writeFrame(ve(e.id,lt(r)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var bc="@agentclientprotocol/claude-agent-acp@latest";function Nc(n){let e={};for(let[t,r]of Object.entries(n))r!==void 0&&(t.startsWith("CLAUDE")||t==="AI_AGENT"||t==="BAGGAGE"||(e[t]=r));return e}var Kt=class extends pe{framework="claude-code";constructor(e){let t=Wt("claude-code"),[r,s]=t?[t,[]]:["npx",["-y",bc]],i=e.command??r,o=e.args??s,a={command:i,args:o,cwd:e.cwd,...e.env?{env:e.env}:{}};super(a)}sanitizeEnv(e){return Nc(e)}};import{mkdtempSync as Dc,rmSync as Lc}from"node:fs";import{tmpdir as Mc}from"node:os";import{join as Bc}from"node:path";var Fc="@zed-industries/codex-acp@latest",Xt=class extends pe{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=Wt("codex"),[r,s]=t?[t,[]]:["npx",["-y",Fc]],i=e.command??r,o=e.args??s,a=e.extraArgs?[...o,...e.extraArgs]:o,c=e.isolateCodexHome?Dc(Bc(Mc(),"coze-bridge-codex-home-")):void 0,l=c?{...e.env??{},CODEX_HOME:c}:e.env,d={command:i,args:a,cwd:e.cwd,...l?{env:l}:{}};super(d),this.authMethodId=e.authMethodId,this.codexHomeDir=c}async initialize(e){let t=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),t}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Lc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var dt=class extends pe{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let t=e.sessionName??"default",r=["acp","--session",`agent:${e.agentId}:${t}`];e.gatewayToken&&r.push("--token",e.gatewayToken);let s={command:e.command,args:r,cwd:e.cwd,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=t,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};k();z();var $e=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((t,r)=>{this.slots.push({task:e,resolve:t,reject:r}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}}finally{this.running=!1}}}};var Yt=class{agentId;framework;workspace;deployType;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local"}getSessionQueue(e){let t=this.sessionQueues.get(e);return t||(t=new $e,this.sessionQueues.set(e,t)),t}allSessionQueues(){return this.sessionQueues.entries()}async dispose(e){this.status="stopped";let t=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let r of this.sessionQueues.values())r.dispose(t);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let t=[];for(let[,r]of this.sessions)ut(r),r.downstream&&(t.push(r.downstream.stop(e).catch(()=>{})),r.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function ut(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Uc}from"node:child_process";import{homedir as $c}from"node:os";import{join as zc}from"node:path";At();k();async function Ys(){let n=zc($c(),".openclaw/openclaw.json");return(await Le(n))?.gateway?.auth?.token??""}var Ks=w("openclaw.config"),qc=[0,5e3,5e3],Xs="models.providers.",Zt="agents.defaults.models",en=class{command;env;retryDelaysMs;queue=new $e;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??qc}async withRetry(e,t){let r;for(let s=0;s<this.retryDelaysMs.length;s++){let i=this.retryDelaysMs[s]??0;i>0&&await new Promise(o=>setTimeout(o,i));try{return await t()}catch(o){r=o,Ks.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(o)})}}throw new h("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${r?.message??"unknown"}`)}runCli(e){return new Promise((t,r)=>{let s=Uc(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`exit ${o}: ${i.trim().slice(0,500)}`))})})}async runCliTolerant(e,t){try{await this.runCli(e)}catch(r){let s=String(r);if(t.some(i=>s.includes(i)))return;throw r}}async bestEffortUnset(e,t){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",t])))}catch(r){Ks.warn(`${e} failed (best-effort)`,{configPath:t,err:String(r)})}}ensureProvider(e,t){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Xs}${e}`,JSON.stringify(t),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Xs}${e}`)}addModelToAllowlist(e,t){let r={[e]:t?{alias:t}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Zt}[${e}]`,()=>this.runCli(["config","set",Zt,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Zt}[${e}]`,`${Zt}.${e}`)}ensureAgent(e,t,r){let s=["agents","add",e,"--workspace",t,"--non-interactive"];return r&&s.push("--model",r),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var se=w("agent-manager"),Hc=(n,e,t,r,s,i,o)=>{switch(n){case"claude-code":{let a=s?{...xs(s),...Ps(s,o)}:void 0;return new Kt({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...Ts(s),...Cs(s,o)]:[],c=s?Rs(s):void 0,l=!!s;return new Xt({cwd:t,...a.length>0?{extraArgs:a}:{},...c&&Object.keys(c).length>0?{env:c}:{},...l?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new dt({command:e,cwd:t,agentId:r,...i?{sessionName:st(i)}:{}})}};function Zs(n){return n==="claude-code"||n==="codex"}var Wc={path:"",version:"cloud-deployed"},jc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Jc=6e4,tn=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Hc,this.createTimeoutMs=e.createTimeoutMs??Jc}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new h("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new en({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new h("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new h("IPC_BAD_REQUEST","framework required");let t=rt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let r=this.registry.get(e.agentId);if(r){if(r.framework!==e.framework)throw new h("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${r.framework})`);if(r.status==="error")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(u=>se.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else return se.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:r.agentId,workspace:r.workspace,framework:r.framework}}if(!t&&!this.config.frameworksCache?.[e.framework])throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);t&&Zs(e.framework)&&await zs(e.framework);let i=ae(e.agentId,this.paths),o=e.workspace??i.workspace,a=rt(e._meta),c=new AbortController,l=setTimeout(()=>c.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),d,f=!1;try{let u=()=>{if(c.signal.aborted)throw c.signal.reason instanceof Error?c.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await jn(i.root,{recursive:!0}),await jn(o,{recursive:!0}),await jn(i.logs,{recursive:!0}),u(),await Me(o,e.framework,e.agentId,e.cozeIdentity),u();let p=await q(e.agentId,this.paths).catch(()=>null),m=ks({model:e.model??p?.model});if(d=new Yt({agentId:e.agentId,framework:e.framework,workspace:o,model:m.model??ne,deployType:a}),d.status="ok",p?.sessions){for(let[F,b]of Object.entries(p.sessions))d.sessions.set(F,{acpSessionId:b.acpSessionId,modelToken:b.modelToken,tokenGeneratedAt:b.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let C=Object.keys(p.sessions).length;C>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:C})}this.registry.register(d),f=!0;let _={agentId:e.agentId,framework:e.framework,workspace:o,cozeIdentity:e.cozeIdentity,createdAt:p?.createdAt??Date.now(),sessions:p?.sessions??{},model:m.model};a==="cloud"&&(_.deployType="cloud"),p?.skills&&(_.skills=p.skills),p?.agentName&&(_.agentName=p.agentName),p?.description&&(_.description=p.description),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,o):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let v=e.initialSkills??[];if(v.length>0){let C=[..._.skills??[]],F=new Map(C.map((P,g)=>[P.skillId,g])),b=0;for(let P of v)try{let g=await Gn({agentId:e.agentId,workspace:o,framework:e.framework,skill:P});Hn(C,F,g),b++}catch(g){se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:P.skillId,skillName:P.skillName,err:String(g)})}b>0&&(_.skills=C,se.info("initialSkills installed",{agentId:e.agentId,installed:b,requested:v.length}))}return await X(_,this.paths),se.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:a}),{ok:!0,agentId:e.agentId,workspace:o,framework:e.framework}}catch(u){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),f&&d&&(await d.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Gc(i.root,{recursive:!0,force:!0}).catch(p=>se.warn("rm agent dir failed (ignored)",{err:String(p)})),u instanceof h?u:new h("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}async spawnSessionDownstream(e,t,r,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&Zs(e.framework))o=Wc;else throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let a=e.deployType==="cloud"?{model:e.model,modelToken:t}:void 0,c;e.framework==="openclaw"?c=await this.buildOpenclawDownstream({session:e,modelConfig:a,cloudSessionId:r,cozeEnv:s,command:o.path}):c=this.factory(e.framework,o.path,e.workspace,e.agentId,a,r,s);try{return await c.start(),await c.initialize(jc),c}catch(l){throw await c.stop("spawnSessionDownstream failed").catch(()=>{}),l instanceof h?l:new h("AGENT_SPAWN_FAILED",l instanceof Error?l.message:String(l),{cause:l})}}async buildOpenclawDownstream(e){let{session:t,modelConfig:r,cloudSessionId:s,cozeEnv:i,command:o}=e,a=st(s),c=await Ys(),l=r?As(r,i):null,d;if(l){let f=zn(s),p=l.models[0]?.id??ne,m=`${f}/${p}`;if(!this.ensuredProviders.has(m)){let _=this.getOpenclawConfig();await _.ensureProvider(f,l),await _.addModelToAllowlist(m),this.ensuredProviders.add(m)}d=m}return new dt({command:o,cwd:t.workspace,agentId:t.agentId,sessionName:a,...c?{gatewayToken:c}:{},...d?{slashModelOnStart:d}:{}})}async openclawRepair(e,t){let r=this.getOpenclawConfig();await r.deleteAgent(e),await r.ensureAgent(e,t)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let t=this.openclawConfigCache;for(let r of e.sessions.keys()){let s=zn(r),i=`${s}/${e.model}`;this.ensuredProviders.delete(i),await t.removeProvider(s),await t.removeModelFromAllowlist(i)}}};k();import{execFile as Vc}from"node:child_process";import{promisify as Qc}from"node:util";var Kc=Qc(Vc),me=w("coze-cli-installer"),ei="@coze/cli@0.1.3-alpha.89c42a",ti="https://bnpm.byted.org",Xc="coze",Yc=5e3,Zc=9e4,ni=1e4,ft=null,Jn=!1;async function ri(n,e={}){if(Jn)return;if(ft)return ft;let t=e.exec??Kc;return ft=(async()=>{try{let r=await el(Xc,t);if(r){me.info("coze-cli already on PATH, skip install + config + auth",{path:r}),Jn=!0;return}me.info("coze-cli install start",{package:ei,registry:ti});try{await t("npm",["i","-g",ei,"--registry",ti],{timeout:Zc,maxBuffer:10*1024*1024}),me.info("coze-cli install ok")}catch(s){me.warn("coze-cli install failed (skip subsequent steps)",{err:String(s)});return}if(n.env)try{await t("coze",["config","set","xTTEnv",n.env],{timeout:ni}),me.info("coze config set xTTEnv ok",{env:n.env})}catch(s){me.warn("coze config set failed (continue to auth login)",{err:String(s)})}try{await t("coze",["auth","login","--token",n.patToken],{timeout:ni}),me.info("coze auth login ok")}catch(s){me.warn("coze auth login failed",{err:String(s)});return}Jn=!0}finally{ft=null}})(),ft}async function el(n,e){let t=process.platform==="win32"?"where":"which";try{let{stdout:r}=await e(t,[n],{timeout:Yc});return r.split(`
|
|
94
|
+
`)[0]?.trim()||void 0}catch{return}}k();import{spawn as tl}from"node:child_process";import{constants as si,access as nl}from"node:fs/promises";import{delimiter as rl,join as sl}from"node:path";var il=w("framework-detector"),ii={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},ol=[".exe",".cmd",".bat",".ps1"],ze=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??tl,access:e.access??nl}}async detect(e){let t=ii[e],r=await this.which(t);if(!r)return il.debug("framework binary not found",{framework:e,bin:t}),null;let s=await this.probeVersion(r);return{path:r,version:s}}async detectAll(){let e=await Promise.all(Object.keys(ii).map(async r=>[r,await this.detect(r)])),t={};for(let[r,s]of e)s&&(t[r]=s);return t}async which(e){let t=this.env.pathEnv.split(rl).filter(Boolean),r=this.env.platform==="win32"?["",...ol]:[""];for(let s of t)for(let i of r){let o=sl(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?si.F_OK:si.X_OK;return await this.env.access(e,t),!0}catch{return!1}}async probeVersion(e){return new Promise(t=>{let r="",s=!1,i,o=a=>{s||(s=!0,i&&clearTimeout(i),t(a.trim()||"unknown"))};try{let a=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});i=setTimeout(()=>{a.kill("SIGKILL"),o("unknown")},5e3),a.stdout?.on("data",c=>{r+=c.toString("utf8")}),a.on("error",()=>o("unknown")),a.on("close",()=>{let c=cl(r).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},al=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function cl(n){return n.replace(al,"")}At();z();var ll=10*6e4;function oi(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ll:e}function nn(n){return Le(n??T().configFile)}function qe(n,e){return Pt(e??T().configFile,n)}import{randomBytes as wl}from"node:crypto";import{mkdir as dl,readFile as ul,realpath as fl,writeFile as hl}from"node:fs/promises";import{basename as gl,dirname as Vn,join as pl,relative as ml,resolve as ai,sep as _l}from"node:path";k();var li=w("fs-rpc");async function di(n,e){let t=await fi(n.path,e);return await dl(Vn(t),{recursive:!0}),await hl(t,n.content,"utf8"),li.info("fs/write_text_file ok",{path:t,size:n.content.length}),null}async function ui(n,e){let t=await fi(n.path,e),r=await ul(t,"utf8"),s=r;if(typeof n.line=="number"||typeof n.limit=="number"){let i=r.split(`
|
|
95
|
+
`),o=Math.max(0,(n.line??1)-1),a=typeof n.limit=="number"?o+n.limit:void 0;s=i.slice(o,a).join(`
|
|
96
|
+
`)}return li.info("fs/read_text_file ok",{path:t,size:s.length}),{content:s}}async function fi(n,e){if(typeof n!="string"||n.length===0)throw new h("IPC_BAD_REQUEST","path must be a non-empty string");let[t,r]=await Promise.all([ci(ai(e)),ci(ai(n))]),s=ml(t,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${_l}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return r}async function ci(n){let e=[],t=n;for(;t!==Vn(t);)try{let r=await fl(t);return e.length?pl(r,...e.reverse()):r}catch{e.push(gl(t)),t=Vn(t)}return n}ge();k();var S=w("core"),yl=3e4,Sl=3e4,rn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Ue;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=oi(e.bridgeConfig)}registerExtension(e,t){this.extensions[e]=t}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),S.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){S.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(t=>t.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),S.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(r){S.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(r)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&S.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,t,r){let s=r.downstream;s&&(s.onUpdate(i=>{r.loadingSession||this.forwardUpdate(e,i)}),s.onAgentRequest(i=>{this.handleAgentRequest(e,s,i)}),s.onExit((i,o)=>{S.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),ut(r),r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId)}))}async handleFrame(e){if(Vt(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let t="id"in e&&e.id!==void 0?e.id:null,r=e.params?._meta?.cozeEnv;r&&(this.currentCozeEnv=r);try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):S.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Fe(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Fe(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Fe(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):S.warn("drop unknown notification",{method:e.method})}catch(s){S.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(ve(t,lt(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new h("IPC_BAD_REQUEST",`${e.method} requires params`);let t=e.params,r=t._meta?.cozeAgentId;if(!r)throw new h("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(r);if(!s)throw this.disconnectedAgents.has(r)?new h("AGENT_DISCONNECTED",`agent ${r} has been disconnected; cloud must _agent/create to revive`):new h("AGENT_NOT_FOUND",`agent not found: ${r}`);let i=typeof t.sessionId=="string"?t.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!i)return this.dispatchSessionCall(s,e.method,t);let o=Date.now(),a=!1;try{let c=await s.getSessionQueue(i).enqueue(()=>this.dispatchSessionCall(s,e.method,t));return a=!0,c}finally{S.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,t,r){e.lastActiveAt=Date.now();let{stripped:s}=gs(r);switch(t){case"session/new":{let i=El();return S.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return S.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:i.sessionId}),{}}case"session/prompt":{let i=s,o=i.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new h("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=r._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);try{let l=await a.downstream.sessionPrompt({...i,sessionId:a.acpSessionId});return a.lastActiveAt=Date.now(),l}finally{e.activeTriggers.delete(a.acpSessionId),a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=s.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new h("IPC_BAD_REQUEST",`session method not supported: ${t}`)}}async ensureRuntime(e,t){let r=e.sessions.get(t);if(r)return r;let i={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,t):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(t,i),await this.persistSessionMapping(e),i}async requestSessionToken(e,t){let r={sessionId:t,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(te.GEN_MODEL_TOKEN,r,Sl);if(!s?.modelToken)throw new h("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${t})`);return s.modelToken}catch(s){throw s instanceof h&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new h("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,t,r){if(ut(r),r.downstream?.isAlive())return;if(!this.sessionSpawner)throw new h("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=await this.sessionSpawner(e,r.modelToken,t,this.currentCozeEnv);if(r.downstream=s,this.attachRuntimeHooks(e,t,r),r.acpSessionId){r.loadingSession=!0;try{await s.sessionLoad({sessionId:r.acpSessionId,cwd:e.workspace}),S.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId})}catch(i){S.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId,err:String(i)}),r.acpSessionId=void 0;let o=await s.sessionNew({cwd:e.workspace});r.acpSessionId=o.sessionId,await this.persistSessionMapping(e)}finally{r.loadingSession=!1}}else{let i=await s.sessionNew({cwd:e.workspace});r.acpSessionId=i.sessionId,await this.persistSessionMapping(e)}s.afterSessionEstablished&&r.acpSessionId&&await s.afterSessionEstablished(r.acpSessionId)}armIdleTimer(e,t,r){if(ut(r),this.isRuntimeBusy(e,r)){S.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:t});return}r.idleTimer=setTimeout(()=>{if(r.idleTimer=void 0,this.isRuntimeBusy(e,r)){S.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:t}),this.armIdleTimer(e,t,r);return}S.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:t});let s=r.downstream;r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId),s&&s.stop("idle timeout").catch(i=>S.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:t,err:String(i)}))},this.sessionIdleTimeoutMs),r.idleTimer.unref?.()}isRuntimeBusy(e,t){if(t.acpSessionId&&e.activeTriggers.has(t.acpSessionId))return!0;let r=t.downstream;if(!r)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===r)return!0;return!1}forwardUpdate(e,t){let r=t.sessionId,s=this.reverseSessionId(e,r);if(!s){S.debug("drop update for unknown session",{agentId:e.agentId,acpId:r});return}let i=e.sessions.get(s);if(!i){S.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(vl(t)){S.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:r});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++i.replySeq},a=e.activeTriggers.get(r);a&&(o.cozeTriggerMsgId=a),this.upstream.send(jt("session/update",{...t,sessionId:s,_meta:o})).catch(c=>S.warn("forward update failed",{agentId:e.agentId,err:String(c)}))}handleAgentRequest(e,t,r){if(r.method==="session/request_permission"){this.forwardPermissionRequest(e,t,r);return}if(r.method==="fs/write_text_file"||r.method==="fs/read_text_file"){this.handleFsRpcRequest(e,t,r);return}S.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:r.method}),t.respondAgentRequestError(r.id,{code:R.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${r.method}`})}async handleFsRpcRequest(e,t,r){try{let s=e.workspace;if(r.method==="fs/write_text_file"){let i=r.params??{},o=await di(i,s);t.respondAgentRequest(r.id,o)}else{let i=r.params??{},o=await ui(i,s);t.respondAgentRequest(r.id,o)}}catch(s){S.warn("fs rpc handler failed",{agentId:e.agentId,method:r.method,err:String(s)}),t.respondAgentRequestError(r.id,lt(s))}}forwardPermissionRequest(e,t,r){let s=this.upstreamIds.next("session/request_permission"),i=r.params??{},a=i.sessionId,c=a?e.activeTriggers.get(a):void 0,l={cozeAgentId:e.agentId};c&&(l.cozeTriggerMsgId=c);let d=a?this.reverseSessionId(e,a):void 0,f={...i,...d?{sessionId:d}:{},_meta:l};this.pendingUpstream.set(s,{agentRequestId:r.id,agentId:e.agentId,downstream:t,method:r.method}),S.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:a,cloudSessionId:d,toolCallId:i.toolCall?.toolCallId,options:i.options?.map(u=>({optionId:u.optionId,kind:u.kind,name:u.name}))}),this.upstream.send(ct(s,"session/request_permission",f)).catch(u=>{this.pendingUpstream.delete(s),S.error("forward permission request failed",{agentId:e.agentId,err:String(u)}),t.respondAgentRequestError(r.id,{code:R.INTERNAL_ERROR,message:`upstream send failed: ${String(u)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let t=this.pendingUpstream.get(e.id);if(t){this.pendingUpstream.delete(e.id),e.error?(S.info("upstream \u2192 permission response (error)",{agentId:t.agentId,upstreamId:e.id,method:t.method,error:e.error}),t.downstream.respondAgentRequestError(t.agentRequestId,e.error)):(S.info("upstream \u2192 permission response (result)",{agentId:t.agentId,upstreamId:e.id,method:t.method,result:e.result}),t.downstream.respondAgentRequest(t.agentRequestId,e.result));return}let r=this.pendingBridge.get(e.id);if(r){this.pendingBridge.delete(e.id),clearTimeout(r.timer),e.error?r.reject(new Jt(e.error)):r.resolve(e.result);return}S.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,r=yl){let s=this.upstreamIds.next(e);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(s),o(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r);this.pendingBridge.set(s,{method:e,resolve:i,reject:o,timer:a}),this.upstream.send(ct(s,e,t)).catch(c=>{let l=this.pendingBridge.get(s);l&&(clearTimeout(l.timer),this.pendingBridge.delete(s)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let t=new Map;for(let[r,s]of e.sessions){let i={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(i.acpSessionId=s.acpSessionId),t.set(r,i)}await Fn(e.agentId,t,this.paths)}catch(t){S.warn("persist session mapping failed",{agentId:e.agentId,err:String(t)})}}reverseSessionId(e,t){for(let[r,s]of e.sessions.entries())if(s.acpSessionId===t)return r}sendError(e,t,r){return this.upstream.send(ve(e,{code:t,message:r}))}};function El(){return wl(16).toString("hex")}function vl(n){let e=n.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let t=e.content;if(!t||typeof t!="object")return!1;let r=t;return r.type!=="text"||typeof r.text!="string"?!1:r.text.startsWith("Model metadata for `")}k();z();import{randomBytes as kl}from"node:crypto";import{chmod as Il,mkdir as xl,writeFile as hi}from"node:fs/promises";import{createServer as Tl}from"node:http";import{dirname as Rl}from"node:path";var Pl=1e6,Qn=w("ipc"),sn=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(t=>[`${t.method} ${t.path}`,t])),this.paths=e.paths??T()}async start(){this.token=kl(32).toString("hex");let e=Tl((r,s)=>{this.dispatch(r,s)});this.server=e,await new Promise((r,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>r())});let t=e.address();if(!t||typeof t!="object")throw new Error("failed to obtain IPC port");return this.port=t.port,await this.persistAuthFiles(),Qn.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((t,r)=>{e.close(s=>s?r(s):t())}),this.server=null)}async persistAuthFiles(){await xl(Rl(this.paths.portFile),{recursive:!0}),await hi(this.paths.portFile,String(this.port),"utf8"),await hi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Il(this.paths.tokenFile,384)}catch(e){Qn.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){ht(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){ht(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await Al(e)}catch(a){ht(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);ht(t,200,a??{ok:!0})}catch(a){Qn.error("IPC handler failed",{key:s,err:String(a)}),ht(t,500,{error:a instanceof Error?a.message:String(a)})}}};function ht(n,e,t){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(t))}async function Al(n){let e=[],t=0;for await(let s of n){let i=s;if(t+=i.length,t>Pl)throw new Error("body too large");e.push(i)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var vi="";function zl(n=""){let t=`${Date.now()}`,r=vi||(vi=Wl(n)),s=Math.random().toString(16).slice(-6);return"02"+t+r+s}function ql(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Gl(n){return(Array(8).join("0")+parseInt(n,10).toString(2)).slice(-8)}function ki(n){return(Array(4).join("0")+parseInt(n,2).toString(16)).slice(-4)}function Hl(n){let e=n.split(/\./).map(s=>Gl(s)),t=[];return t[0]=ki(e[0]+e[1]),t[1]=ki(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function Wl(n){let e=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(n),t=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(n);return e?Hl(n):t?jl(n):"00000000000000000000000000000000"}function jl(n){let e="",t=[],r=0,s=0,i=!0,o="0000";if(n.indexOf("::")>-1){let a=n.split("::");for(let l=0;l<a.length;l++){let d=a[l];if(d.indexOf(":")>0){let f=d.split(":");i&&(r=f.length),s+=f.length;for(let u=0;u<f.length;u++)if(f[u].length!==4){let m=o.substring(0,4-f[u].length).concat(f[u]);t.push(m)}else t.push(f[u]);i=!1}else{if(d.length!==4){let u=o.substring(0,4-d.length).concat(d);t.push(u)}else t.push(d);i&&(r+=1),s+=1,i=!1}}let c="";for(let l=0;l<8-s;l++)c=c.concat(o);for(let l=0;l<t.length;l++)l===r&&(e=e.concat(c)),e=e.concat(t[l]);return e}{let a=n.split(":");for(let c=0;c<a.length;c++){let l=a[c];if(a[c].length!==4){let f=o.substring(0,4-a[c].length).concat(l);e=e.concat(f)}else e=e.concat(l)}return e}}function Jl(n,e){let t=n.key;t!==void 0&&(N(e,10),xe(e,t));let r=n.value;r!==void 0&&(N(e,18),xe(e,r))}function Vl(n){let e={};e:for(;!Bi(n);){let t=B(n);switch(t>>>3){case 0:break e;case 1:e.key=Ie(n,B(n));break;case 2:e.value=Ie(n,B(n));break;default:Di(n,7&t)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function Ni(n){let e=Mi();return Ql(n,e),td(e)}function Ql(n,e){let t=n.SeqID;t!==void 0&&(N(e,8),pt(e,t));let r=n.LogID;r!==void 0&&(N(e,16),pt(e,r));let s=n.service;s!==void 0&&(N(e,24),pt(e,nr(s)));let i=n.method;i!==void 0&&(N(e,32),pt(e,nr(i)));let o=n.headers;if(o!==void 0)for(let m of o){N(e,42);let _=Mi();Jl(m,_),N(e,_.limit),sd(e,_),Zl(_)}let a=n.payloadEncoding;a!==void 0&&(N(e,50),xe(e,a));let c=n.payloadType;c!==void 0&&(N(e,58),xe(e,c));let l=n.payload;l!==void 0&&(N(e,66),N(e,l.length),rd(e,l));let d=n.LogIDNew;d!==void 0&&(N(e,74),xe(e,d));let f=n.serverTiming;f!==void 0&&(N(e,82),xe(e,f));let u=n.msgID;u!==void 0&&(N(e,90),xe(e,u));let p=n.frameType;p!==void 0&&(N(e,96),pt(e,nr(p)))}function Kl(n){return Xl(ed(n))}function Xl(n){let e={};e:for(;!Bi(n);){let t=B(n);switch(t>>>3){case 0:break e;case 1:e.SeqID=xi(n,!0);break;case 2:e.LogID=xi(n,!0);break;case 3:e.service=B(n);break;case 4:e.method=B(n);break;case 5:{let r=Yl(n);(e.headers||(e.headers=[])).push(Vl(n)),n.limit=r;break}case 6:e.payloadEncoding=Ie(n,B(n));break;case 7:e.payloadType=Ie(n,B(n));break;case 8:e.payload=nd(n,B(n));break;case 9:e.LogIDNew=Ie(n,B(n));break;case 10:e.serverTiming=Ie(n,B(n));break;case 11:e.msgID=Ie(n,B(n));break;case 12:e.frameType=B(n);break;default:Di(n,7&t)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function Yl(n){let e=B(n),t=n.limit;return n.limit=n.offset+e,t}function Di(n,e){switch(e){case 0:for(;128&j(n););break;case 2:rr(n,B(n));break;case 5:rr(n,4);break;case 1:rr(n,8);break;default:throw new Error("Unimplemented type: "+e)}}function nr(n){return n|=0,{low:n,high:n>>31,unsigned:n>=0}}var Li=[];function Mi(){let n=Li.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function Zl(n){Li.push(n)}function ed(n){return{bytes:n,offset:0,limit:n.length}}function td(n){let e=n.bytes,t=n.limit;return e.length===t?e:e.subarray(0,t)}function rr(n,e){if(n.offset+e>n.limit)throw new Error("Skip past limit");n.offset+=e}function Bi(n){return n.offset>=n.limit}function wt(n,e){let t=n.bytes,r=n.offset,s=n.limit,i=r+e;if(i>t.length){let o=new Uint8Array(2*i);o.set(t),n.bytes=o}return n.offset=i,i>s&&(n.limit=i),r}function Er(n,e){let t=n.offset;if(t+e>n.limit)throw new Error("Read past limit");return n.offset+=e,t}function nd(n,e){let t=Er(n,e);return n.bytes.subarray(t,t+e)}function rd(n,e){let t=wt(n,e.length);n.bytes.set(e,t)}function Ie(n,e){let t=Er(n,e),r=String.fromCharCode,s=n.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],l,d,f,u;(128&c)===0?o+=r(c):(224&c)===192?a+1>=e?o+=i:(l=s[a+t+1],(192&l)!==128?o+=i:(u=(31&c)<<6|63&l,u<128?o+=i:(o+=r(u),a++))):(240&c)==224?a+2>=e?o+=i:(l=s[a+t+1],d=s[a+t+2],((l|d<<8)&49344)!==32896?o+=i:(u=(15&c)<<12|(63&l)<<6|63&d,u<2048||u>=55296&&u<=57343?o+=i:(o+=r(u),a+=2))):(248&c)==240?a+3>=e?o+=i:(l=s[a+t+1],d=s[a+t+2],f=s[a+t+3],((l|d<<8|f<<16)&12632256)!==8421504?o+=i:(u=(7&c)<<18|(63&l)<<12|(63&d)<<6|63&f,u<65536||u>1114111?o+=i:(u-=65536,o+=r((u>>10)+55296,(1023&u)+56320),a+=3))):o+=i}return o}function xe(n,e){let t=e.length,r=0;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),r+=a<128?1:a<2048?2:a<65536?3:4}N(n,r);let s=wt(n,r),i=n.bytes;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?i[s++]=a:(a<2048?i[s++]=a>>6&31|192:(a<65536?i[s++]=a>>12&15|224:(i[s++]=a>>18&7|240,i[s++]=a>>12&63|128),i[s++]=a>>6&63|128),i[s++]=63&a|128)}}function sd(n,e){let t=wt(n,e.limit),r=n.bytes,s=e.bytes;for(let i=0,o=e.limit;i<o;i++)r[i+t]=s[i]}function j(n){return n.bytes[Er(n,1)]}function Ii(n,e){let t=wt(n,1);n.bytes[t]=e}function B(n){let e=0,t=0,r;do r=j(n),e<32&&(t|=(127&r)<<e),e+=7;while(128&r);return t}function N(n,e){for(e>>>=0;e>=128;)Ii(n,127&e|128),e>>>=7;Ii(n,e)}function xi(n,e){let t=0,r=0,s=0,i;return i=j(n),t=127&i,128&i&&(i=j(n),t|=(127&i)<<7,128&i&&(i=j(n),t|=(127&i)<<14,128&i&&(i=j(n),t|=(127&i)<<21,128&i&&(i=j(n),r=127&i,128&i&&(i=j(n),r|=(127&i)<<7,128&i&&(i=j(n),r|=(127&i)<<14,128&i&&(i=j(n),r|=(127&i)<<21,128&i&&(i=j(n),s=127&i,128&i&&(i=j(n),s|=(127&i)<<7))))))))),{low:t|r<<28,high:r>>>4|s<<24,unsigned:e}}function pt(n,e){let t=e.low>>>0,r=(e.low>>>28|e.high<<4)>>>0,s=e.high>>>24,i=s===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:s<128?9:10,o=wt(n,i),a=n.bytes;switch(i){case 10:a[o+9]=s>>>7&1;case 9:a[o+8]=i!==9?128|s:127&s;case 8:a[o+7]=i!==8?r>>>21|128:r>>>21&127;case 7:a[o+6]=i!==7?r>>>14|128:r>>>14&127;case 6:a[o+5]=i!==6?r>>>7|128:r>>>7&127;case 5:a[o+4]=i!==5?128|r:127&r;case 4:a[o+3]=i!==4?t>>>21|128:t>>>21&127;case 3:a[o+2]=i!==3?t>>>14|128:t>>>14&127;case 2:a[o+1]=i!==2?t>>>7|128:t>>>7&127;case 1:a[o]=i!==1?128|t:127&t}}function id(n){return Kl(n)}function Ti(n){return Ni(n)}var Ri=65536,od="\0\0\0\0\0\0\0\0",Ge=Ri*Ri,Fi=Ge*Ge,Pi=Fi/2,_e=String.prototype.charCodeAt,G=class n{constructor(e,t,r){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!r}static isLong(e){return e&&e.isLong===!0}static fromBits(e,t,r){return new n(e,t,r)}static fromBytes(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)}static fromBytesLE(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return e===od?Ai:new n((_e.call(e,0)|_e.call(e,1)<<8|_e.call(e,2)<<16|_e.call(e,3)<<24)>>>0,(_e.call(e,4)|_e.call(e,5)<<8|_e.call(e,6)<<16|_e.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,t=!0){if(isNaN(e))return t?ad:Ai;if(t){if(e>=Fi)return ld}else{if(e<=-Pi)return dd;if(e+1>=Pi)return cd}return n.fromBits(e%Ge|0,e/Ge|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*Ge+(this.low>>>0):this.high*Ge+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){n.isLong(e)||(e=n.fromNumber(e));let t=this.high>>>16,r=65535&this.high,s=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,l=65535&e.low,d=0,f=0,u=0,p=0;return p+=i+l,u+=p>>>16,p&=65535,u+=s+c,f+=u>>>16,u&=65535,f+=r+a,d+=f>>>16,f&=65535,d+=t+o,d&=65535,n.fromBits(u<<16|p,d<<16|f,this.unsigned)}equals(e){return n.isLong(e)||(e=n.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?n.fromBits(0,0,this.unsigned):this.low===-1?n.fromBits(0,this.high+1,this.unsigned):n.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}},Ai=new G(0,0,!1),ad=new G(0,0,!0),cd=G.fromBits(-1,2147483647,!1),ld=G.fromBits(-1,-1,!0),dd=G.fromBits(0,-2147483648,!1),ke=(function(n){return n[n.NATIVE_ERROR=5001]="NATIVE_ERROR",n[n.CONNECTING_ERROR=5002]="CONNECTING_ERROR",n[n.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",n[n.MESSAGE_ERROR=5004]="MESSAGE_ERROR",n[n.OPEN_ERROR=5005]="OPEN_ERROR",n})({}),Te=class{constructor(e){this.type=e,this.target=null}},ir=class extends Te{constructor(e,t){super(e),this.message=t&&t.message||null}},or=class extends Te{constructor(e,t){super(e),this.error=t&&t.error||null,this.colno=t&&t.colno||0,this.filename=t&&t.filename||"",this.lineno=t&&t.lineno||0,this.message=t&&t.message||"",this.code=t&&t.code||5001}},ar=class extends Te{constructor(e,t){super(e),this.code=t&&t.code||0,this.reason=t&&t.reason||"",this.wasClean=t&&t.wasClean||!1,this.willReconnect=t&&t.willReconnect||!1}},cr=class extends Te{constructor(e,t){super(e),this.data=t&&t.data||null}},lr=class extends cr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},dr=class extends Te{constructor(e,t){super(e),this.data=t&&t.data||null}};function Y(n,{message:e,code:t,error:r}){return new or(n,{message:e,code:t,error:r})}function ie(n,{code:e,reason:t,wasClean:r,willReconnect:s}){return new ar(n,{code:e,reason:t,wasClean:r,willReconnect:s})}function ud(n,{data:e,message:t}){return new lr(n,{data:e,message:t})}function fd(n,{data:e}){return new dr(n,{data:e})}function Ci(n,{message:e}){return new ir(n,{message:e})}var on=class{constructor(e,t){this.endpoints=e,this.maxRetries=t,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length?!0:this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}},We=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Re=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",yt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",mt=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",hd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,_t=class{constructor(){this._listeners={}}emit(e,...t){let r=this._listeners[e];if(r)r.slice().forEach(s=>s.fn.apply(s.ctx,t));else if(e==="error"&&!this.onerror){let s=t.length&&t[0];if(s instanceof Error)throw s;let i=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw i.context=s,s}return this}off(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=null;else{let r=this._listeners[e];if(r)for(let s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this}on(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this}},ur=class extends _t{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,t,r){super(),this._socket=null,yt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Re&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let t=Y("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let r=ie("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",fd("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",ie("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",ud("message",{...e}))}),this._socket.onError(e=>{this.emit("error",Y("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:r=>{this.emit("error",Y("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",Y("error",{message:this._formatErrorMessage(t)}))}})}close(e,t){this._socket&&this._socket.close({code:e,reason:t})}addEventListener(e,t){this.on(e,t)}removeEventListener(e,t){this.off(e,t)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}};function gd(n,e){if(e)return new e(n.url,n.protocol);if(yt||Re)return new ur(n.url,n.protocol,n.headers);if((We||mt)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(n.url,n.protocols)}function pd(n){return!!(n||yt&&wx.connectSocket||Re&&tt.connectSocket||(We||mt)&&typeof WebSocket<"u"&&WebSocket)}function Oi(n,e,t){let r=-1;async function s(i){return i<=r?Promise.reject(new Error("next() called multiple times in process")):(r=i,i===t.length?Promise.resolve():t[i].bind(n)(e,s.bind(null,i+1)))}s(0)}function Ui(n){let e=0,t=0;for(let r=0;r<n.length;++r)t=n.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(64512&t)===55296&&(64512&n.charCodeAt(r+1))===56320?(++r,e+=4):e+=3;return e}function $i(n,e,t){if(t-e<1)return"";let r="";for(let s=e;s<t;){let i=n[s++];if(i<=127)r+=String.fromCharCode(i);else if(i>=192&&i<224)r+=String.fromCharCode((31&i)<<6|63&n[s++]);else if(i>=224&&i<240)r+=String.fromCharCode((15&i)<<12|(63&n[s++])<<6|63&n[s++]);else if(i>=240){let o=((7&i)<<18|(63&n[s++])<<12|(63&n[s++])<<6|63&n[s++])-65536;r+=String.fromCharCode(55296+(o>>10)),r+=String.fromCharCode(56320+(1023&o))}}return r}function fr(n,e,t){let r=t,s,i;for(let o=0;o<n.length;++o)s=n.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=63&s|128):(64512&s)===55296&&(64512&(i=n.charCodeAt(o+1)))===56320?(s=65536+((1023&s)<<10)+(1023&i),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=63&s|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=63&s|128);return t-r}async function zi(n){if(typeof n=="string"){let e=new Uint8Array(Ui(n));return fr(n,e,0),e}return n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function md(n){try{return typeof n!="string"&&(n instanceof ArrayBuffer||n.buffer&&n.buffer instanceof ArrayBuffer)||typeof n!="string"?"":(JSON.parse(n),"application/json")}catch{return typeof n=="string"?"text/plain;charset=utf-8":""}}var _d=(n,e)=>{switch(n){case"boe":case"ppe":return{[`x-use-${n}`]:1,"x-tt-env":e};default:return{}}},hr=class{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}};async function wd(n){return new Promise(e=>{if(!We)return e("unknown reason");try{let t=document.createElement("script");window.frontierJSONP=r=>{document.body.removeChild(t),window.frontierJSONP=void 0,e(r&&r.msg||"unknown reason")},t.type="text/javascript",t.src=n.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(t)}catch{document.body.removeChild(t)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function we(n,e,t){return!!n?.find(r=>r.key===e&&r.value===t)}function He(n,e){return n?.find(t=>t.key===e)?.value}var sr=null;async function yd(){return sr||(sr=Promise.resolve().then(()=>(Ei(),Si))),sr}var gr=class extends _t{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,t=this._keyPath;this._initPromise=(async()=>{let{openDB:r}=await yd();this._qosDB=await r(`frontier_${e}`,1,{upgrade(s){s.createObjectStore(e,{keyPath:t})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(t){console.log(t)}}async set(e,t){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(t){console.log(t)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},pr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getItem(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getItem(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},mr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Re?tt:yt?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getStorageSync(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getStorageSync(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function qi(n,e){if(Re||Re)return new mr(n,e);if((We||mt)&&typeof indexedDB<"u")return new gr(n,e);if((We||mt)&&typeof localStorage<"u")return new pr(n,e);throw new Error("init QoSDB failed")}var _r=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=qi("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:r})=>r<Date.now()).forEach(r=>{this._qosDB?.del(r.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,t){return this._qosDB?.set({message_id:e,timestamp:t})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function vr(n){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=we(n.message.headers,"x_frontier_qos","2"),r=t&&we(n.message.headers,"x_frontier_qos_ack","1"),s=t&&we(n.message.headers,"x_frontier_is_ack","1"),i=s?He(n.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:r,isAckCleanupMessage:s,ackMsgIds:i}}async function Gi(){return this._QoSManager||(this._QoSManager=new _r),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function Sd(n,e){let{enableAutoAck:t}=this._options,r=we(n.message.headers,"need_ack","1"),s=we(n.message.headers,"is_ack","1"),i=vr.call(this,n);if(t&&r){let{SeqID:o,LogID:a,service:c,LogIDNew:l,method:d}=n.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:l,service:c,method:d,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:l||""},{key:"ack_code",value:"0"}]})}s&&!i.isQoSAck&&this._dispatchAckMessageEvent(n),e()}async function Ed(n,e){this._debug("received",n.message),e()}async function vd(n,e){let t=id(await zi(n.data));try{if(t.payload instanceof Uint8Array){let r=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},s=t.payloadEncoding?t.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=t.payloadType?t.payloadType.replace(/\s/g,"").toLowerCase():"",a=i.force?i.type:o||i.type,c=r.force?r.encoding:s||r.encoding,l=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],d=["none_none","binary"];this._options.enableTransformTextPayload&&l.includes(a)&&(!c||d.includes(c))?t.textPayload=$i(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(r){t.textPayload="",console.log(r)}n.message=t,e()}function kd(n,e,t){let r=t||8192,s=r>>>1,i=null,o=r;return function(a){if(a<1||a>s)return n(a);o+a>r&&(i=n(r),o=0);let c=e.call(i,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var Id=4294967295;function xd(n,e,t){if(t>Id)throw new Error("integer too large");let r=3;for(;r>=0;){let s=255&t;yr(s,n,e+r),t>>>=8,r--}return e+4}function Td(n,e){let t=0,r=e,s=e+4;for(;r<s;){let{value:i,offset:o}=wr(n,r);r=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function Rd(n,e,t){return n?n.length<40?fr(n,e,t)+t:e.utf8Write?e.utf8Write(n,t)+t:e.write?e.write(n,t)+t:fr(n,e,t)+t:t}function Pd(n,e){let t=new G(n[e+4]<<24|n[e+5]<<16|n[e+6]<<8|n[e+7],n[e+0]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3],!0);return e+=8,{value:t,offset:e+8}}function Ad(n,e,t){let r=n.low,s=n.high;return e[t]=s>>>24,e[t+1]=s>>>16&255,e[t+2]=s>>>8&255,e[t+3]=255&s,e[t+4]=r>>>24,e[t+5]=r>>>16&255,e[t+6]=r>>>8&255,e[t+7]=255&r,t+=8,t}function wr(n,e){return n.readUInt8?{value:n.readUInt8(e),offset:e+1}:{value:255&n[e],offset:e+1}}function yr(n,e,t){return e.writeUint8?e.writeUint8(n,t):e[t]=255&n,t+1}var Cd=function(n){return new Uint8Array(n)},Od=typeof Buffer<"u"?Buffer.allocUnsafe:kd(Cd,Uint8Array.prototype.subarray),bd=16,kr=32;function Nd(n){let e=0,t={};for(let r=0;r<n.length;r++)t[n[r].cursor_name]=Ui(n[r].cursor_name),e+=14+t[n[r].cursor_name];return[e,t]}function bi(n,e,t){let[r,s]=Nd(n),i=Od(r),o=0;return n.forEach(a=>{console.log("cursor.service",a,a.service),o=yr(0,i,o),console.log("header",o),o=xd(i,o,a.service||0),console.log("service",o),o=yr(s[a.cursor_name],i,o),console.log("service-name",o),o=Rd(a.cursor_name,i,o),console.log("name",o),o=Ad(G.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:kr,headers:[{key:"cursor_file_name",value:t}],payload:i}}function Dd(n){let e=0,t=[];for(;e<n.byteLength;){let{offset:r}=wr(n,e);e=r;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=Td(n,e);s.service=i,e=o;let{value:a,offset:c}=wr(n,e);e=c,s.cursor_name=$i(n,e,e+a),e+=a;let{value:l,offset:d}=Pd(n,e);s.cursor=l.toNumber(),e=d,t.push(s)}return t}function Ld(){return{frameType:kr,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var Sr=class{constructor(e,t,r){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=r,this._qosDB=qi(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,t=await this._qosDB.getAll();switch(console.log("allCursorValues",t),e){case"ALL":return t&&t.length?bi(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?bi(t,0,this._cursorFileName):Ld()}}async set(e,t,r){return console.log("setdb",e,t,r),this._qosDB.set({cursor_name:e,cursor:t,service:r})}async setCursors(e){let t=Dd(e);for(let r of t)console.log("setcursor",t),await this._qosDB.set(r)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},Md="__x_msg_qos__";async function Hi(n){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:r}=this._options,s=n||Md;try{return this._cursorManager?n&&this._cursorManager.updateCursorFileName(n):this._cursorManager=new Sr(`${t}_${e}_${s}`,s,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function Bd(n,e){let t=we(n.message.headers,"code","-1"),r=we(n.message.headers,"is_ack","1"),s=He(n.message.headers,"x_frontier_msgid"),i=Number(He(n.message.headers,"x_frontier_ttl"))||0,o=vr.call(this,n),a=we(n.message.headers,"x-msg-qos","2"),c=He(n.message.headers,"x-msg-cursor_name"),l=Number(He(n.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Gi.call(this):null;if(n.message.service>0&&r&&!t||n.message.service>0){if(s&&o.isQoSMessage&&d)return await d.get(s)||(this._dispatchMessageEvent(n),await d.set(s,Date.now()+i)),e();if(a){let f=await Hi.call(this);if(!f)return this._dispatchMessageEvent(n),e();let u=await f.get(c)??-1;if(u<l)this._dispatchMessageEvent(n),f.set(c,l,n.message.service);else throw new Error(`recevied message cursor ${l} larger than local cursor ${u}`);return e()}return this._dispatchMessageEvent(n),e()}}async function Fd(n,e){let t=vr.call(this,n);if(!t.isQoSMessage)return e();let r=await Gi.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await r.del(s);e()}async function Ud(n,e){let t=n.message.frameType===bd,r=n.message.frameType===kr;if(!t&&!r)return e();let s=He(n.message.headers,"cursor_file_name");if(!s)return e();let i=await Hi.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:G.fromNumber(this._seqId++),LogID:G.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Ni(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=n.message.payload;o&&i.setCursors(o)}}var $d=async function(n,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},zd=async function(n,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},qd=async function(n,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:t}=this._options;this._endpointManager?.resetEndpointConfig();for(let s=0;s<this._messageQueue.length;s++){let i=this._messageQueue[s];if(this._ws.readyState===this.OPEN&&i!==null)this._ws&&this._ws.send(i),this._messageQueue[s]=null;else break}this._messageQueue=this._messageQueue.filter(s=>!!s),this._pingPongTimeoutId=setTimeout(()=>this._ping(),t),this._dispatchOpenEvent(n),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r} success`),e()},an=class extends _t{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=We,this._isNode=hd,this._isMiniTT=Re,this._isMiniWX=yt,this._isWorker=mt,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=i=>{try{Oi(this,i,[$d,qd,zd])}catch(o){let a=Y("error",{message:o.message,code:ke.OPEN_ERROR,error:o});this._dispatchErrorEvent(a)}},this._onMessage=async i=>{let{pingInterval:o,pingFrequency:a}=this._options;if((i.data==="hi"&&a==="always"||a==="auto")&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),o)),i.data!=="hi")try{Oi(this,i,[vd,Sd,Fd,Ud,Bd,Ed])}catch(c){let l=Y("error",{message:c.message,code:ke.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(l)}},this._onError=i=>{let o=this._endpointManager?.checkReachMaxTries(),a=this._endpointManager?.getCurrentEndpoint();if(o&&!i.message){let c=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Y("error",{message:c,code:ke.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Y("error",{message:i.message,code:ke.NATIVE_ERROR,error:i}))},this._onClose=async i=>{this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;let o=this._endpointManager?.checkReachMaxTries();if(!o&&this._navigatorOnline()&&!this._readyClosed){let a=this._endpointManager?.getCurrentEndpoint(),c=this._options.reconnectInterceptor(i.code,i.reason);this._dispatchCloseEvent(ie("close",{code:1006,reason:i.reason||`connecting failed, unknown reason, hostname: ${a}`,willReconnect:c})),c&&this._connect();return}if(i.code!==1e3&&this._readyClosed){this._dispatchCloseEvent(ie("close",{code:1e3,reason:"bye"})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&o){let a=this._endpointManager?.getCurrentEndpoint(),c=i.reason;c||(c=await wd(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(ie("close",{code:i.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Y("error",{message:l,code:ke.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ie("close",{code:i.code,reason:`connecting failed, unknown reason, hostname: ${a}`})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}this._dispatchCloseEvent(i),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:ql,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:t,ws:r}=e,s=Array.isArray(t)?t:typeof t=="string"?[t]:[];if(!s||s.length===0)throw new Error("please provide valid url");if(!pd(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new on(s,this._options.maxRetries),this._pingLossCounter=new hr(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();let e=Ci("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:t,deviceID:r,bddID:s,ttwID:i,accessKey:o,aID:a,customParams:c={},enableAutoAck:l,enableQoS:d,QoSLevel:f,env:u}=this._options,p,m,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(p=location&&location.protocol=="https:"?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${p}${m}`):(p="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${p}${m}`);let v=s?"bd_did":i?"ttwid":"device_id",C=s||i||r;if(!C||!v)throw new Error("please provide bddID, deviceID or ttwID");let F=typeof c=="function"?await c():c,b=u?_d(u.xUseEnv,u.xTTEnv):{},P=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[v]:C,xsack:l?1:0,xaack:l?1:0,xsqos:d?1:0,qos_level:d?f:void 0,qos_sdk_version:2,...b},F),g=Object.keys(P).reduce((E,I)=>P[I]!==void 0?`${E}${E?"&":"?"}${I}=${P[I]}`:E,"");return`${_}/ws/v2${g}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:t}=this._options;if(e){let s=this._endpointManager?.getCurrentEndpoint(),i=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(i){let a=`connect ${s} timeout, max retries reached, will use backup endpoint ${i} to retry`,c=Y("error",{message:a,code:ke.MAX_RETRIES_ERROR});this._debug(a),this._dispatchErrorEvent(c),this._url=await this._generateUrl(i),this._debug(`connect ${i} ${o} times`),this._removeWsListeners()}else{let a=`connect ${s} timeout, max retries reached`;this._debug(a),this._dispatchErrorEvent(Y("error",{message:a,code:ke.MAX_RETRIES_ERROR}));return}}else{let s=this._endpointManager?.getCurrentEndpointAndUpdateCount(),i=this._endpointManager?.getCurrentEndpointTriesCount();this._url=await this._generateUrl(s||""),this._debug(`connect ${s} ${i} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{let s=Ci("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(s)}let r=this._endpointManager?.getCurrentEndpointTriesCount()||0;r>1&&await this._wait(r-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=gd({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),t)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:t,maxReconnectInterval:r,reconnectIntervalGrowFactor:s}=this._options,i=t*Math.pow(s,e-1);return i>r?r:i}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(t=>{setTimeout(t,this._getIntervalValue(e))})}_disconnect(e=1e3,t="",r=!1){this._ws&&this._destroyWebSocket(e,t,r)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let t=Ti(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch{}}_destroyWebSocket(e=1e3,t="",r=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,r&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let i=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ie("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(ie("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(ie("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(ie("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((t,r)=>(t+=r&&r.byteLength||0,t),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,t)}async send(e,t){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let r=await zi(e),s=md(e),{method:i=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:l=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:f=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?zl(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let u={SeqID:G.fromNumber(this._seqId++),LogID:G.fromNumber(a),service:o,method:i,headers:c,payloadEncoding:l instanceof Object?l.encoding?l.encoding:"":l,payloadType:d instanceof Object?d.type?d.type:s:d||s,payload:r,LogIDNew:f},p=Ti(u);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(p),this._debug("sent",u)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(p),this._debug("enqueue",u)):(this._messageQueue.shift(),this._messageQueue.push(p)),{seqID:this._seqId,logID:a,logIDNew:f}}async reconnect(e){let{url:t}=e||{},r=Array.isArray(t)?t:typeof t=="string"?[t]:[];e&&Object.assign(this._options,e),r&&r.length?this._endpointManager=new on(r,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){let{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let r=()=>{e("success"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)},s=()=>{t("timeout"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)};this.on("ping_once_success",r),this.on("ping_once_timeout",s),this._ping()})}};var lf=he($o(),1),df=he(mn(),1),uf=he(Ve(),1),ff=he(Dr(),1),hf=he(Br(),1),gf=he(Gr(),1),Qo=he(Sn(),1),pf=he(Vo(),1);var Ko=Qo.default;k();var D=w("upstream.frontier"),Yo="application/json",Zo="none",vn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){D.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:_s,...Bt(this.opts.ppeOverride)};class t extends Ko{constructor(a){super(a,ms,{headers:e})}send(a,...c){if(fs("debug"))try{let l;typeof a=="string"?l=Buffer.from(a,"utf8"):a instanceof Buffer?l=a:a instanceof ArrayBuffer?l=new Uint8Array(a):ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):l=new Uint8Array(0);let d=Buffer.from(l.slice(0,128)).toString("hex");D.debug("WS raw frame out",{bytes:l.byteLength,headHex:d})}catch(l){D.warn("WS raw frame dump failed",{err:String(l)})}super.send(a,...c)}}let r=Ss(this.opts.urlOverride),s={url:r,ws:t,fpID:ps,aID:Mt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Yo,force:!0},payloadEncoding:{encoding:Zo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new an(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;D.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:o,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:o})).catch(a=>D.warn("onConnect handler threw (ignored)",{err:String(a)}))},i.onclose=o=>{this.opened=!1,D.info("frontier closed",{code:o.code,reason:o.reason,willReconnect:o.willReconnect})},i.onerror=o=>{D.warn("frontier error",{code:o.code,msg:o.message})},i.onmessage=o=>this.handleMessage(o),this.fws=i,await i.connect()}async stop(e){let t=this.fws;if(t){this.fws=null,this.opened=!1;try{t.close(1e3,e??"bridge shutdown")}catch(r){D.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let t=this.fws;if(!t)throw new h("UPSTREAM_DISCONNECTED","frontier upstream not started");let r=JSON.stringify(e),s=e;ea(s)||D.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:r.length});try{await t.send(r,{service:33555712,method:1,payloadType:Yo,payloadEncoding:Zo})}catch(o){throw D.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(o)}),new h("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(o)}`,{cause:o})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let t=e.message?.service;if(t!==33555712){D.debug("drop non-adapter frontier frame",{service:t});return}let r=yf(e);if(!r){D.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){D.debug("frame received but no onFrame handler",{size:r.length});return}let s;try{s=JSON.parse(r)}catch(o){D.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let i=s;ea(i)||D.info("frontier frame in",{logid:wf(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:i.id,method:i.method,body:_f(r)}),Promise.resolve(this.handler(s)).catch(o=>D.warn("frontier frame handler threw",{err:String(o)}))}};function ea(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}var ta=2e3;function _f(n){return n.length<=ta?n:`${n.slice(0,ta)}...<truncated, total ${n.length} chars>`}function wf(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function yf(n){let e=n.message;if(e?.textPayload)return e.textPayload;let t=e?.payload;if(!t)return null;try{return Buffer.from(t).toString("utf8")}catch{return null}}k();var Wr=w("upstream.switchable"),kn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;Wr.info("swap upstream",{reason:t});let r=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(s){throw Wr.error("swap target start failed, reverting",{err:String(s)}),this.inner=r,s}await r.stop(t??"swapped").catch(s=>Wr.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};k();var jr=w("upstream"),Rt=class{handler=null;async start(){jr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jr.info("NoopUpstream stopped",{reason:e})}async send(e){jr.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};k();z();k();z();import{execSync as Sf}from"node:child_process";import{readFileSync as na,unlinkSync as Ef}from"node:fs";import{mkdir as vf,readFile as ra,unlink as sa,writeFile as kf}from"node:fs/promises";import{dirname as If}from"node:path";var xf=w("single-instance"),In=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??T().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(xf.warn("removing stale pid file",{stalePid:e}),await sa(this.pidFile).catch(()=>{})),await vf(If(this.pidFile),{recursive:!0}),await kf(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await ra(this.pidFile,"utf8")).trim()===String(process.pid)&&await sa(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await ra(this.pidFile,"utf8"),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return this.matchesDaemonTitle(e)}matchesDaemonTitle(e){try{let t=na(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=Sf(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return t.trim()?t.includes("coze-bridge-daemon")||t.includes("lib/index.js"):!1}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{na(this.pidFile,"utf8").trim()===String(process.pid)&&Ef(this.pidFile)}catch{}})}};var y=w("daemon"),Tf="coze-bridge-daemon";async function aa(){let n=new In({processTitle:Tf}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await nn(),r=t??{};Bn({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let g=new ze;r.frameworksCache=await g.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(r.frameworksCache)})}catch(g){y.warn("framework detection failed",{err:String(g)})}await qe(r);let s=new kn(new Rt),i=T(),o=null,a=new rn({upstream:s,paths:i,bridgeConfig:r,sessionSpawner:async(g,E,I,Q)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(g,E,I,Q)}});await Pf(i,a);let c=new tn({paths:i,config:r,registry:a});o=c;let l,d,f=null,u=null;a.registerExtension("_agent/create",async g=>c.createAgent(g.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let p={},m=new Ut({agents:a.agents,disposeAndMarkDisconnected:async(g,E)=>{let I=a.agents.get(g);I&&(await c.cleanupOpenclawSessionProviders(I).catch(Q=>y.warn("cleanup openclaw providers failed (ignored)",{agentId:g,err:String(Q)})),await I.dispose(`disconnect: ${E}`).catch(Q=>y.warn("dispose during disconnect failed (ignored)",{agentId:g,err:String(Q)})),I.status="disconnected",a.unregister(g)),a.disconnectedAgents.add(g)},detailSyncer:async g=>{if(!p.ref)throw new Error("agent-detail-sync not initialized yet");await p.ref.syncOne(g)},openclawRepair:async(g,E)=>{await c.openclawRepair(g,E)}});a.registerExtension("_agent/listSkills",g=>m.listSkills(g.params)),a.registerExtension("_agent/addSkills",g=>m.addSkills(g.params)),a.registerExtension("_agent/removeSkills",g=>m.removeSkills(g.params)),a.registerExtension("_agent/getFileTree",g=>m.getFileTree(g.params)),a.registerExtension("_agent/getFileContent",g=>m.getFileContent(g.params)),a.registerExtension("_agent/update",g=>m.updateAgent(g.params)),a.registerExtension("_agent/disconnect",g=>m.disconnectAgent(g.params)),a.registerExtension("_agent/switchModel",g=>m.switchModel(g.params)),a.registerExtension("_agent/reset",g=>m.resetAgent(g.params)),a.registerExtension("_agent/repair",g=>m.repairAgent(g.params));let _=new Lt({paths:i,handlers:m,sendDetail:g=>a.sendRequest("_agent/detail",g)});p.ref=_,s.onConnect(({initial:g})=>{y.info("frontier upstream connected, triggering detail sync",{initial:g}),_.syncAll(g?"initial-connect":"reconnect").catch(E=>y.warn("detail sync top-level error (ignored)",{err:String(E)}))});let v=new sn({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:f??"",frameworksCache:r.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async g=>{let E=g,I=E?.privatecode,Q=E?.pairing_code;if(!I||!Q)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ne=Ft(E.env),nt=E.handshake_url,bn=E.frontier_url,Nn=Rf(E.env,nt,bn),ss=!!l&&l!==I,is=d!==void 0&&d!==Nn,os=ss||is;if(os){y.warn("pair config switched, resetting agents",{pcChanged:ss,envChanged:is,previousPc:l?ia(l):"",nextPc:ia(I),previousEnvKey:d??"",nextEnvKey:Nn});for(let U of[...a.agents.values()])await U.dispose("pair config switch").catch(()=>{}),a.agents.delete(U.agentId);await s.swap(new Rt,"pair switch").catch(()=>{})}let as=await vs({privatecode:I,...nt?{endpoint:nt}:{},ppeOverride:Ne});f=as.deviceId,Bn({deviceId:f,pid:process.pid}),ri({patToken:I,env:E.env}).catch(U=>y.warn("coze-cli setup error (ignored)",{err:String(U)}));let Sa=new vn({handshake:as,privatecode:I,...bn?{urlOverride:bn}:{},ppeOverride:Ne});await s.swap(Sa,"pair");try{let U=new ze;r.frameworksCache=await U.detectAll(),await qe(r),y.info("frameworks_cache refreshed before pair",{detected:Object.keys(r.frameworksCache)})}catch(U){y.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(U)})}let Ea=Object.keys(r.frameworksCache??{});try{let U=await a.sendRequest("_agent/pair",{pairCode:Q,patToken:I,frameworks:Ea,_meta:{cozeDeviceId:f}});y.info("_agent/pair ok",{pairResult:U}),l=I,d=Nn,u||(u=new qt({core:a,getDeviceId:()=>f??""})),u.start(),os&&oa(i,c).catch(De=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(De)}));let Dn;return E.agent_id&&(Dn=await Af(E.agent_id,i,c,De=>a.sendRequest("_agent/detail",De)).catch(De=>(y.error("--agent-id ensureAgent failed",{agentId:E.agent_id,err:String(De)}),{ok:!1,agentId:E.agent_id??"",note:String(De)}))),{ok:!0,note:"paired with cloud",...Dn?{agent:Dn}:{}}}catch(U){return y.error("_agent/pair failed",{err:String(U)}),{ok:!1,note:`pair failed: ${String(U)}`}}}},{method:"POST",path:"/_agent/create",handler:async g=>{let E=g;return{ok:!0,result:await c.createAgent(E)}}},{method:"POST",path:"/refresh",handler:async()=>{y.info("IPC /refresh: re-detecting frameworks");let g=new ze;return r.frameworksCache=await g.detectAll(),await qe(r),{ok:!0,frameworks:r.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{P.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:C,token:F}=await v.start();await a.start(),oa(i,c).catch(g=>y.warn("auto-revive top-level error (ignored)",{err:String(g)}));let b=null,P={port:C,token:F,core:a,ipc:v,shutdown(g){return b||(y.info("daemon shutdown",{reason:g}),b=(async()=>{u?.stop(),await a.stop(g),await v.stop(),await n.release()})(),b)}};for(let g of["SIGTERM","SIGINT"])process.on(g,()=>{P.shutdown(g).then(()=>process.exit(0))});return y.info("daemon ready",{port:C,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(r.frameworksCache??{}),libVersion:r.libVersion??"dev"}),P}function ia(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function Rf(n,e,t){return`${n??""}|${e??""}|${t??""}`}async function Pf(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return}let{loadAgentConfig:s,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(ge(),Dt));for(let o of r){await i(o,n).catch(a=>y.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await s(o,n);a?.disconnectedAt&&(e.disconnectedAgents.add(o),y.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){y.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function Af(n,e,t,r){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ge(),Dt)),i=await s(n,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:n,framework:i.framework,hadDisconnect:!!i.disconnectedAt});let l={agentId:i.agentId,framework:i.framework,...i.cozeIdentity?{cozeIdentity:i.cozeIdentity}:{},...i.model?{model:i.model}:{}};return await t.createAgent(l),{ok:!0,agentId:n,note:i.disconnectedAt?"revived from local config":"connected from local config"}}y.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let o=await r({_meta:{cozeAgentId:n}});if(!o.framework)throw new h("AGENT_NOT_FOUND",`agent ${n} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let a={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...o.deployType?{_meta:{cozeDeployType:o.deployType}}:{}};await t.createAgent(a);let c=o.deployType==="cloud"&&o.framework==="openclaw";return{ok:!0,agentId:n,note:c?"cloud agent acknowledged":"created from cloud detail"}}async function oa(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(r.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ge(),Dt));y.info("auto-revive: scanning local agents on startup",{count:r.length});let i=0,o=0;for(let a of r){let c;try{c=await s(a,n)}catch(l){y.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){y.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{y.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework}),await e.createAgent({agentId:c.agentId,framework:c.framework,...c.cozeIdentity?{cozeIdentity:c.cozeIdentity}:{},...c.model?{model:c.model}:{},...c.deployType?{_meta:{cozeDeployType:c.deployType}}:{}}),i+=1}catch(l){y.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return y.info("auto-revive: done",{revived:i,skipped:o,total:r.length}),{revived:i,skipped:o,total:r.length}}Vr();z();import{readFile as la}from"node:fs/promises";var Ee=class{paths;constructor(e){this.paths=e??T()}async probe(e=1e3){let t=await this.readAuth();if(!t)return{kind:"not-running"};try{let r=await this.fetch(t,{method:"GET",path:"/status",timeoutMs:e});return r.status===200?{kind:"connected",...t}:{kind:"stale",reason:`unexpected status ${r.status}`}}catch(r){return{kind:"stale",reason:Ff(r)}}}async request(e){let t=await this.readAuth();if(!t)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(t,e)}async readAuth(){try{let[e,t]=await Promise.all([la(this.paths.portFile,"utf8"),la(this.paths.tokenFile,"utf8")]),r=Number.parseInt(e.trim(),10),s=t.trim();return!Number.isFinite(r)||r<=0||!s?null:{port:r,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,t){let r=t.body!==void 0,s={Authorization:`Bearer ${e.token}`};r&&(s["content-type"]="application/json");let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${t.path}`,{method:t.method,headers:s,body:r?JSON.stringify(t.body):void 0,signal:i.signal}),c=await a.text();return{status:a.status,body:Bf(c)}}finally{clearTimeout(o)}}};function Bf(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function Ff(n){return n instanceof Error?n.message:String(n)}k();z();import{copyFile as da,mkdir as Uf,readFile as Qr,writeFile as $f}from"node:fs/promises";import{dirname as zf,resolve as Kr,sep as xn}from"node:path";import{fileURLToPath as qf}from"node:url";k();z();var ua=w("dist-install");function Gf(n){let e=qf(n),t=zf(e),r=`${xn}src${xn}`;if(t.includes(r)||t.endsWith(`${xn}src${xn}cli`))return null;let s=Kr(t,"index.js"),i=Kr(t,"..","package.json");return{dist:s,pkgJson:i}}async function fa(n={}){let e=n.paths??T(),t=Gf(import.meta.url),r=n.sourceDist??t?.dist,s=n.sourcePackageJson??t?.pkgJson;if(!r||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let i;try{i=JSON.parse(await Qr(s,"utf8")).version??"unknown"}catch(f){return ua.warn("cannot read source package.json,skip dist install",{err:String(f)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(f)}`}}let o=await nn(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Qr(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await Uf(e.libDir,{recursive:!0}),await da(r,e.libEntry),await da(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Kr(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
+
`;return await Qr(c,"utf8").catch(()=>null)!==l&&await $f(c,l),o.libVersion=i,await qe(o,e.configFile),ua.info("dist installed",{libEntry:e.libEntry,fromVersion:a,toVersion:i}),a?{kind:"version-changed",fromVersion:a,toVersion:i,libEntry:e.libEntry}:{kind:"first-install",libVersion:i,libEntry:e.libEntry}}var ch=w("cli");function et(n,e){let t=[],r;for(let s=0;s<n.length;s++){let i=n[s];if(i===e){r=n[s+1],s+=1;continue}if(i.startsWith(`${e}=`)){r=i.slice(e.length+1);continue}t.push(i)}return{value:r,rest:t}}function lh(n){let e=n.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let t=e,{value:r,rest:s}=et(t,"--pat-token");t=s;let{value:i,rest:o}=et(t,"--pair-code");t=o;let{value:a,rest:c}=et(t,"--env");t=c;let{value:l,rest:d}=et(t,"--handshake-url");t=d;let{value:f,rest:u}=et(t,"--frontier-url");t=u;let{value:p}=et(t,"--agent-id");if(!r||!i)return{mode:"help"};let m={mode:"pair",privatecode:r,pairingCode:i};return a&&(m.env=a),l&&(m.handshakeUrl=l),f&&(m.frontierUrl=f),p&&(m.agentId=p),m}var dh=`
|
|
98
98
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
99
99
|
|
|
100
100
|
Usage:
|
|
@@ -122,36 +122,36 @@ Auto-connect agent (optional):
|
|
|
122
122
|
|
|
123
123
|
Internal:
|
|
124
124
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
125
|
-
`.trimStart();async function
|
|
126
|
-
`),0;case"daemon":{try{await
|
|
127
|
-
`),1;if(
|
|
128
|
-
`),1;let
|
|
129
|
-
${JSON.stringify(
|
|
130
|
-
`),0}async function
|
|
131
|
-
`),0;if(
|
|
132
|
-
`),0;try{return await
|
|
133
|
-
`),0}catch(
|
|
134
|
-
`),1}}async function
|
|
135
|
-
`),1;try{let
|
|
136
|
-
${JSON.stringify(
|
|
137
|
-
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(
|
|
138
|
-
`),1)}catch(
|
|
139
|
-
`),1}}async function
|
|
140
|
-
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(
|
|
141
|
-
`)}await new Promise(
|
|
142
|
-
`)}catch(
|
|
143
|
-
`)}let
|
|
144
|
-
`)}catch(
|
|
125
|
+
`.trimStart();async function wa(n=process.argv,e={}){let t=lh(n);switch(t.mode){case"help":return process.stdout.write(dh),0;case"version":return process.stdout.write(`${zt}
|
|
126
|
+
`),0;case"daemon":{try{await aa()}catch(r){return ch.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return uh(e);case"stop":return fh(e);case"refresh":return hh(e);case"uninstall":return gh(e);case"install-service":return ph();case"pair":{let r={};return t.env&&(r.env=t.env),t.handshakeUrl&&(r.handshakeUrl=t.handshakeUrl),t.frontierUrl&&(r.frontierUrl=t.frontierUrl),mh(t.privatecode,t.pairingCode,e,r,t.agentId)}}}async function ya(n){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(n.pidFile).catch(()=>{}),e(n.portFile).catch(()=>{}),e(n.tokenFile).catch(()=>{})])}async function uh(n){let e=n.paths??T(),t=new Ee(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
127
|
+
`),1;if(r.kind==="stale")return await ya(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
128
|
+
`),1;let s=await t.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
129
|
+
${JSON.stringify(s.body,null,2)}
|
|
130
|
+
`),0}async function fh(n){let e=n.paths??T(),t=new Ee(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
131
|
+
`),0;if(r.kind==="stale")return await ya(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
132
|
+
`),0;try{return await t.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
133
|
+
`),0}catch(s){return process.stdout.write(`coze-bridge: stop failed: ${String(s)}
|
|
134
|
+
`),1}}async function hh(n){let e=new Ee(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
135
|
+
`),1;try{let r=await e.request({method:"POST",path:"/refresh"});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
136
|
+
${JSON.stringify(r.body,null,2)}
|
|
137
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
|
|
138
|
+
`),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
|
|
139
|
+
`),1}}async function gh(n){let e=new Ee(n.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
140
|
+
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(i){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(i)}
|
|
141
|
+
`)}await new Promise(i=>setTimeout(i,500))}if(!n.skipSupervisor)try{let{getSupervisor:i,buildContext:o}=await Promise.resolve().then(()=>(rs(),ns)),a=i();await a.uninstall(o()),process.stdout.write(`coze-bridge: ${a.platform} supervisor unregistered
|
|
142
|
+
`)}catch(i){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(i)}
|
|
143
|
+
`)}let r=n.paths??T(),{rm:s}=await import("node:fs/promises");try{await s(r.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${r.cozeRoot}
|
|
144
|
+
`)}catch(i){return process.stderr.write(`coze-bridge: remove failed: ${String(i)}
|
|
145
145
|
`),1}return process.stdout.write(`coze-bridge: uninstalled
|
|
146
|
-
`),0}async function
|
|
147
|
-
`),await
|
|
146
|
+
`),0}async function ph(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(rs(),ns)),t=n(),r=e();return process.stdout.write(`coze-bridge: installing ${t.platform} supervisor...
|
|
147
|
+
`),await t.install(r),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
148
148
|
`),0}catch(n){return process.stderr.write(`coze-bridge: --install-service failed: ${String(n)}
|
|
149
|
-
`),1}}async function
|
|
150
|
-
`),(await
|
|
151
|
-
`)}let
|
|
152
|
-
`),await
|
|
153
|
-
`),1;let
|
|
154
|
-
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
155
|
-
`),1)}catch(
|
|
156
|
-
`),1}}async function
|
|
149
|
+
`),1}}async function mh(n,e,t,r={},s){let i=new Ee(t.paths),o=t.spawnDaemon??ca;if(!t.skipDistInstall){let l=await fa({paths:t.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
|
|
150
|
+
`),(await i.probe()).kind==="connected"&&(await i.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(f=>setTimeout(f,500)))):l.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${l.libVersion}
|
|
151
|
+
`)}let a=await i.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
152
|
+
`),await o({paths:t.paths}),a=await _h(i,t.waitTimeoutMs??1e4,t.sleep??wh),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
|
|
153
|
+
`),1;let c={privatecode:n,pairing_code:e};r.env&&(c.env=r.env),r.handshakeUrl&&(c.handshake_url=r.handshakeUrl),r.frontierUrl&&(c.frontier_url=r.frontierUrl),s&&(c.agent_id=s);try{let l=await i.request({method:"POST",path:"/pair",body:c,timeoutMs:35e3});return l.status===200&&l.body?.ok?(process.stdout.write(`coze-bridge: paired (${l.body.note??"ok"})
|
|
154
|
+
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(l.body)}
|
|
155
|
+
`),1)}catch(l){return process.stderr.write(`coze-bridge: pair failed: ${String(l)}
|
|
156
|
+
`),1}}async function _h(n,e,t){let r=Date.now()+e;for(;Date.now()<r;){let s=await n.probe(500);if(s.kind==="connected")return s;await t(200)}return n.probe(500)}function wh(n){return new Promise(e=>setTimeout(e,n))}wa(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
|
|
157
157
|
`),process.exit(1)});
|