coze-bridge 0.1.23 → 0.1.27
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 +65 -63
- 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 N(r){return{debug:(e,i)=>Qt("debug",r,e,i),info:(e,i)=>Qt("info",r,e,i),warn:(e,i)=>Qt("warn",r,e,i),error:(e,i)=>Qt("error",r,e,i),child:e=>N(`${r}.${e}`)}}var en,Bs,g0,p0,Ms,G=Te(()=>{"use strict";en={debug:10,info:20,warn:30,error:40},Bs=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),g0=process.stdout,p0=process.stderr,Ms={}});import{homedir as m0}from"node:os";import{join as re}from"node:path";function j(r){let e=r??m0(),i=re(e,".coze"),a=re(i,"bridge"),c=re(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:re(c,"index.js"),pidFile:re(a,"bridge.pid"),portFile:re(a,"bridge.port"),tokenFile:re(a,"bridge.token"),logFile:re(a,"bridge.log"),installLock:re(a,"install.lock"),configFile:re(a,"config.json"),agentsRoot:re(i,"agents")}}function Ne(r,e=j()){let i=re(e.agentsRoot,r);return{root:i,config:re(i,"config.json"),workspace:re(i,"workspace"),logs:re(i,"logs")}}var ue=Te(()=>{"use strict"});var rn={};Ns(rn,{AGENT_CONFIG_FILE_MODE:()=>tn,enforceAgentConfigMode:()=>y0,loadAgentConfig:()=>de,persistAgentSessions:()=>br,persistAgentSkills:()=>nn,saveAgentConfig:()=>we});import{chmod as w0,stat as _0}from"node:fs/promises";function de(r,e){return xt(Ne(r,e).config)}function we(r,e){return Xt(Ne(r.agentId,e).config,r,{mode:tn})}async function y0(r,e){if(process.platform==="win32")return;let i=Ne(r,e).config;try{let a=await _0(i);if(!a.isFile())return;let c=a.mode&511;c!==tn&&(await w0(i,tn),qs.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;qs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function br(r,e,i){let a=await de(r,i);a&&(a.sessions=Object.fromEntries(e),await we(a,i))}async function nn(r,e,i){let a=await de(r,i);a&&(a.skills=e,await we(a,i))}var qs,tn,Ke=Te(()=>{"use strict";Zt();G();ue();qs=N("agent-config"),tn=384});var Mi=ce(Y=>{"use strict";var S=D;(function(r,e){let i=D,a=r();for(;;)try{if(parseInt(i(966))/1*(parseInt(i(1250))/2)+parseInt(i(295))/3+parseInt(i(630))/4*(-parseInt(i(1273))/5)+-parseInt(i(968))/6*(parseInt(i(1191))/7)+-parseInt(i(186))/8+-parseInt(i(1471))/9+-parseInt(i(993))/10*(-parseInt(i(1352))/11)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Nn,468857);var $c=Object["definePr"+S(1524)],Xc=Object[S(1294)+"opertyNa"+S(1434)],Ri=(r,e)=>function(){return r&&(e=(0,r[{fObui:function(u,d){return u(d)}}[S(580)](Xc,r)[0]])(r=0)),e},Zc=(r,e)=>{let i=S,a={nYuXT:function(u,d,h,m){return u(d,h,m)}};for(var c in e)a[i(757)]($c,r,c,{get:e[c],enumerable:!0})};function Nn(){let r=["vhbhzwy","B2jQzwn0u3q","ysbTDxn0igi","z2v0t3DUuhi","DuvKrKK","x29WDgLVBNm","qwvvCwq","nNWXmhW3FdG","y3jLyxrLq2W","CM92AwrLihC","x29UtwvZC2e","ww9Zq1G","wxHwugG","z2v0u3rVCMe","yxjYyxLIDwy","BxnNsuq","yxPwqxe","BgfMrLm","shvTBvm","B3vUDa","DMvYC2LVBMm","uxjpq0G","Dw50","Cg1AsuW","ihrVihjLDhi","zw5XDwv1zq","DxnLCKLW","r1nduwq","vNzez3q","AxnAzxjV","ufrhyNi","DKLgtNq","zxnqC20","DMfS","CMfUzg9T","zcbLCNjVCI4","A3fyDKm","ywnOzwqSihC","x29Uq2XVC2u","Cw9TEgK","mdaWma","q29UzMLN","wujpv0y","t2XyBxy","vKjqBgm","Axnby2TdBgu","zg5qu1y","D1jrALq","vfPJD1u","ruLmwvy","BNrLCG","tg9eDe4","x2TLEvbHDgG","D3jPDgvvAw4","B21ds2q","zw50","BKTdsLG","v0r3yMK","DMLJzuLeig8","z29PBNq","v25ZA0i","nJG1ndfcwLnJuhG","ChrVCG","A29lC0O","zgf0yq","swnLAKG","C3bSAxq","wgL2Duq","rhvMDhC","v0fWC0q","zgvJB2rLzey","C2vUzf9Hy2S","rK1NEgm","B0PPEvq","z0P1DMq","rxjYB3jdB2q","qwjVCNrfCNi","CMvTB3zLrxy","Dg9mB3DLCKm","qu1fqMq","B25TzxnZywC","AxnFywnR","zw5JB2rPBMC","Dhj1y3rVCIa","C3bSAwnL","nNW1Fdm","Cgnstxi","D1DdAu8","CMfTzq","CMLLC0nVDw4","y2HLy2TdDxi","Ef9MCM9UDgK","z2zLCLK","CMvZzxrfBMq","zNjVBunOyxi","A1LisuG","q09oveLovuu","sNbHsLC","y29UC3rYDwm","A21br04","AxLdrKK","Cgf5Bg9Hzfq","EgPAtK0","uurXEwS","yw1L","zxmGCMvHy2G","A0X4sgu","AvL3Dxi","CMvWBgfJzq","qufuELC","vhrruxq","CgLUz19VBMm","DMfSDwu","uxbSEKW","yxnL","Dg9oDw1Izxi","vfbXsgS","yMLUza","Bg9N","qw1VDw50","q0rfvey","zhDItLK","uvHdwuC","u25Nu2W","tfLAtNC","DM1zEKm","D2vI","uLPQree","yNv5Agy","DgfIyxnL","rKDIuKm","ywXSB2nvBNm","Dgv4DfbHEwW","EfvZzuvUDG","qM5ZqNy","wfDowLO","u01ACMi","DuDIExm","CgvYC2LZDgu","u2HHCMvKv28","wxvtu0y","EgHbqNK","t1HdCui","BwvZ","uu1LEKW","txDbsMK","rvzHtLm","x2n1CNnVCK0","qNzIr1q","CMfNzvn5BMm","tgzrA2S","ref0q0G","v0zLCMu","zxj2AwnL","tuTLt2G","sLjtqwe","DuXLDvq","D2PIy3u","zw5NDgG","DfHPwNa","y1DiChK","D3jnrgG","ENH0Cxu","uuTpz1e","yMXVy2TLza","x2nSzwfYugK","AgvHzgvYCW","zgv2AwnLx2K","C2v0sxrLBq","A2v5CW","yMXmqxC","AgjtCNy","DMnsAxm","z0PIruS","A3PHquO","zxzRu3u","AxnmB25N","zw5HyMXLvhi","zwnVBM5Ly3q","BM5cvwO","nde0odu1qLjxt05L","x2n1CNnVCK4","yxKSihrYEsa","v093C2W","zMvY","yKnstfG","qwnorg8","zgvIDwC","Aw47y2HHCNm","DuX2A0O","CgfNzxnOB3C","y0zoufO","CM9YrxzLBNq","ANHXzvC","y09Wzw4","C0jf","z0vbEgK","CMvHzhDYAxq","EhrmDMG","t0HXEha","ChbL","DNjtyw0","ywXty29Wzq","BwfW","B1brt1u","DeLK","y3jLyxrLuMu","CNnVCL9Uyw0","y29Uy2f0","u2PIA3e","y29TCgXLDgu","CNDSthy","BKPIreC","u2Ptuue","yw5Nzq","y3jLyxrLt2i","x2LUAxrqCM8","zMnxtMm","x3nLBMrby2S","Chn2Dwm","yLDwBvm","CgfYC2u","u2HkCeC","A3jRrw8","wwfIweK","Cg93","yxKSig5LDhC","ywrKq291BNq","AgD5suu","x2vUzhbVAw4","A1zhv0G","ANbPqNu","C29Tzq","B3bLCNr5","A1LuuKC","zMLN","sgzYqMK","zxH0zw5ZAw8","Agn4BfC","uwnJBei","BwfADMW","B0vYvMK","uM5LA0G","twr0rNq","vML4uuy","AgfUz2u","werSwLK","wxnuEw8","rNzIC3u","B25qBLG","rw5lruO","ufzpwvu","Dxrjza","B3jpBMXPBMu","AeLwr20","sMvmt1K","vgLTzw91Da","ELvjDwi","seXhwKG","BIWGAg9ZDg4","C3vJy2vZCW","x19LC01Vzhu","AfzbCxC","rgnNweK","sxzbsw4","DgHLBG","r3DJzKC","C0HdvuC","yMfSrxzLBNq","v2LUzg93","Dev2zw50","AxnrB1nnzxm","EfDYvuO","x3bYB3rVy28","DK5NAK8","CgPkzfO","BMCGzMfPBgu","Dvnhwva","zMzLCG","zuH2B2u","x2jPBMfYEvq","DgLTzw91DcW","zg9Uzq","EM5mvhC","uuXjzfO","qK1Puxy","tvbszfa","BgvY","yMfSu2nVCgu","x2LZv29YA2u","Au5Zsxy","y0jSwvy","C3rVCMu","CgLUz09Uy2u","yNL0zxm","zvjQsgO","igzHAwWSig0","Dfn2wuW","y2XLyxi","Aw5L","qur6v3y","zezMB1a","uhLxswy","DgLTzw91Da","sKvuu2S","zgLZCgf0y2G","B25JBg9Zzq","BwvZC2fNztO","zhL3Auu","zcWGDw5RBM8","AvPIy3O","rxjhEeq","C3vIC3rYAw4","y01Orve","vKL3wvG","sKnkqMq","rMjeEMi","r1jhBgG","tKzPq3i","A1vnDgG","ueHwy2O","C0XPC3rLBMu","BfbAEuC","AufkDeC","CfzhEeS","qwHWtfm","Bwf4uMv0CMK","tKDQsgC","y29UBMvJDa","u0nmvNm","q0Xpu0ve","v2PfEhq","ywjVCNq","ndC4nZC2mgz6rNzrsa","Dg9tDhjPBMC","DxjS","zg1JuMO","rvjst1i","DM9Hsxy","DhjPBq","wNfPsvi","ANLJAwu","EuzvCLK","tg9Nsuq","ywzL","DxbKyxrLq3u","BMvLzf9Hy2S","ihzHBgLKigq","rhzzu3C","DwPNqNa","x21PBMLoyxy","B3jLtMfTzxm","AurYDhm","x2rLyNvN","vu9kALC","zxHWB3j0CW","CNzHBfzHBhu","z2v0qwXS","Bwf4tg9ZC0m","zwj2ugu","vM9VCgC","Ee5TtKW","BwvKAwf0zwW","rfrKsKe","z2u6ia","ugLPyNC","sMX4A2u","x3bHDgHlzxK","ChL2vKG","tKfusvzfx0u","zhbXsxe","sePgrvO","DKD5y3a","v0H5Ege","BeHHBMrSzxi","ywX3yxLZ","vxbKyxrLq28","EsbJBg9Zzwq","Eg5HvgO","yLLSs1a","Bxjcufe","x3jLy29UBMu","zwvKzwq","Bg5UzM0","AgfLB1y","CMvXDwLYzwq","wvnSwxe","BMDuAw1LCG","v0z2EvO","y3jkr0q","tuvtu0fhrv8","DxrMofDYAxq","DhjPzxmGCMu","yNPYyKu","x2fKzfDZtgK","svnYDwS","shryAei","zM9Yy2u","y2HnyxHdB3u","BMLAswi","B2zM","ihrPBwvVDxq","C2vYDMLJzq","wwXNBuu","q291BNq","C2XPy2u","B2nRzxrtDwm","zLr0D2K","EKfvvxq","qujjs2S","CvrUwNm","yxnZAwDU","Dgv4Dc9Qyxy","DcbSAw1PDa","mdaWmdaWmda","v2rQqui","yw51Ce1LC3m","u3zsDgG","yxbWzw5Kq2G","CMvHzhLtDge","ywnRtxnNswq","y2f0y2G","A2v5","sLLgzfK","wgfTt3G","q0f5ENa","v0X0Au8","A0vfEvC","z2vrDwv1zuW","zxrZtg8","zfDuu2C","uxntDgC","vMj2thq","zcWG","tuXluwO","B25SAw5L","qunOuNu","CNrjD3O","zxjYtxnN","wM9pBM8","sfPgsNy","BwfUDwfSihi","mJiYnti1mezXwfncDW","u0Thv0W","yM9KEq","EujeBKy","B3zTt1i","zwvtv2m","uwfltwS","ywDL","zwrPyxrLBhK","DgfYz2v0","x2rLC3rYB3K","Au9dy3q","Efbds1u","C2TcAwm","vw5Oyw5KBgu","q25eyKe","DgDVzLy","uLvmCuS","DgPYs08","Aw5Lza","CeTsAwS","y3vYC29Yx24","DhLWzq","sLbLDfu","y29SBM8","ugn3zeG","Bg9Nsurhzw4","ruXfuge","sur6De8","EwPPCLK","BMCGDxjSoIa","CMv0CNLdB3u","BwvY","tMH1s1e","C2fNzq","BMH1Evm","B25tDg9Wsw0","BvrVveS","Dg9hzw5LCMe","wNneqKS","CeHNt3K","uLjpuG","y3vYCMvUDeK","Eurdy3C","zNvUy3rPB24","EvDSsuy","x21LC3nHz2u","mxW0Fdb8mNW","sLDvu3i","BMrWB2LUDfq","B3jL","zNr1DKS","runxBe8","Bgvov0m","y2HJzNq","D3vfzxi","B1bryMm","sNnXuMO","ALnPr1O","ywr2yw5Jzq","swXlrgS","vhnUq2q","v3bguKC","s0jlv2O","BxnN","quXm","ywTvrgm","r050wwy","A2v0ignVBNm","s2D0q1K","zenbquq","ywnRDxbfBMq","CMvHzfvjBNq","yxrLq291BNq","u3rYyxrLz3K","BKXPBMu","z2vtEw5J","zwn0","tw9KDwXL","t2jQzwn0","t1bftG","q3vZDg9Trxi","zMLSDgvY","wuTdBw8","s01Ru28","CwrJuem","yNLL","AxjxzwG","C0Xmy2C","wMTurfy","y2niDwW","n3WXFdz8nhW","Cg9PBNrbBMq","zw5qtLu","uKDtAxm","x2n1CNnVCKy","A1n0yxr1C0m","CMvKDwnL","zxjFDhrS","Dg5xwe4","DgHHBIbSB2m","C2v0","CwLyA1C","y0TsAfu","tufyx1jfvfi","B2fK","yKP1wMC","AgvHzgvY","BfzhB2K","tNrnvMK","wKTUB1O","u0vVz0O","C2v0u3rVCMe","DxncwM0","x1fVu01HBMe","C0v2rwG","DvLTy2G","EevtyKy","qKHmt3G","rMXVt2C","nhWWFdj8mxW","zw5JB2rLrNi","sfDNB2W","ywnRx2nVzgu","tNDtCMq","ChjVDg9JB2W","rNDKEM0","ALPbvwW","q3vZDg9Tq2W","EvjLy29UBMu","q09otKvdveK","ywrKrxzLBNq","u3jgBvG","x194x21Zz18","BMrLEa","sezbzvq","Benwveu","t0XxELu","Ec1TC2CTCw8","DMzAqM8","zvDUq2G","B3nLza","wvPmENm","rhnNBfC","Dg9cExrLC0W","o2nOyxjZzxq","Dw5KzwzPBMu","t3bLBKv2zw4","C2zfDfO","swD2veq","x3nLCuLK","Dg9VigXHCMC","wMDrvKC","rgvsy08","D05bv0K","D1rQrfK","yvHiAMi","vLnADK4","sfrxyNq","rwLVugG","teXxtvy","ve15Dxi","vgfLq1e","BM5Ly3q","EK5KDha","Chv0","ywnRpwzYB24","BNzzB1C","ywXSzwqGBxu","CgHSAxO","uLLnA1G","D3m6lY8","AwrI","zMDYrhi","uxvLDwu","yNvSwxC","zgLRsLu","BNvTyMvY","wg9Qwe8","DgzYzuC","AvnuAvC","x2LZsw5PDa","CYbWyxjHBxm","twHhtNu","x2XPC3rLBMu","y3vYCMvUDeu","EhzAAwm","igfYCMf5yNu","rK5rB0G","B3j3s20","z2fZBhG","sfvwAee","AgvKtwf4uMu","AuzcrLe","zw5HyMXLuw8","rgvKAwnHDgu","lcbTyxGGCMu","BeTfu0O","x2HHBMrSzvi","DNHZC00","t2LQC00","Aw5KzxHpzG","uLHSB3i","r2vjsxC","uMvJB25Uzwm","C3vIyxjYyxK","C3rLBMvYCW","v090weK","x29UugfNzu4","wfnXsxC","BwLUAvbYB2C","zNjVBNrPzxi","zw5KCg9PBNq","zuflrhe","DwLwsKW","CK9TyMC","BNrfBMrWB2K","wgTiwKe","CM92AwrLihy","C3jJ","EfPzsgO","CMvQzwn0","Ce5rqNq","uhDss3e","zNjHBwvuExa","D1ruvKi","mNW1Fdb8mW","sfnLv0m","twLZC2LUzYa","tvzqsgq","vMDpy1y","De1Vy2i","wujlvva","u2H3A3u","z2TOrgG","sK1Zz24","zfDVCMTLCKC","sg1JtKO","BgLUzq","y29UDgv4Da","BwLZzq","x2HHBMrSzu8","C2vUza","DxbNCMfKzw4","AwXSihvZzsa","Aw5JBhvKzxm","q0nTv0K","nxWWFdf8mNW","AKfbA2u","zgvSzxrLrge","C25fuxG","r2TWqMS","ChvZAa","uNb2t0C","rvH3Be4","C2v0q3vYC28","Dg9fqva","thf2y2S","vgvgr0S","z2nMsLu","y29UBMvJDca","CgLUz1rPBwu","A0HMBhi","B2XKvMvYC2K","z3nbwMK","ueLWCwK","DenfsMm","sLnptLa","zw5fDMvUDa","yMHZA2m","zwzirxC","B2nRzxq","BNfVzgi","BLnkrwy","t0j5t1e","B2zMBgLUzq","y09Xs2e","BNrbBMrvCgq","DMfSDwvZ","uKjIwNi","AevYCM9Yrxy","AxjLza","tNPlvLK","sxHJBKO","sNrrD2K","zK9IDwK","tg9NsurozxC","x29UvgLTzw8","x3bPBMC","tgvwsNG","zK9crva","y3jLyxrLtwu","z1DewNK","BMnLq2XVC2u","Bg9NsurozxC","CvnHDwy","u3DZr2q","suHur2G","Cg1XBhO","q05NvhO","uKzWtve","reHpsM8","Fdr8mhWY","aaaaaaaaaaa","zNjVBujPDhm","Eff0Chi","Dgzysfa","y2X1zMm","yMLUyxj5","AfziuM4","x2LUAxrhBg8","y3vYC29Y","zMLPsMO","zu5rCfC","Cgu6ia","Bu1Irhm","DcbVzIbYyw4","CMvZzxruCMK","y2HnyxHuCMK","rM5RuuO","y3vZDg9Tshq","y29UBMvJDgK","CvL3zKC","x2nYzwf0zvm","CwHxvwC","y0rMAwm","yxv0B21HDgK","CwnJweq","wgvtDMi","x2LUAxq","uw1ODhm","ywDLrxzLBNq","zw50zwqGDhK","BKTIuKi","sxjhBey","mtK5nJrcCvPYEei","CKvSs1O","BNruCMLLC0m","x2LZtwLUAvq","y29Kzq","q3jUsNC","EezIq0S","s2vWuKe","rvL6y2W","vMfNy2K","igXHCMDLCIa","A3nvvhO","r01uv08","zLf4tNC","wfztzKW","r0nczhC","x3jLywr5q2W","ywDLu2HVDW","wvvUsNq","vLflDeS","v3DUA1O","rLDt","s2DwDuu","CNPOwwC","zuXZzNK","svf6Bva","BvvywuC","z2v0q3vYCMu","BwvZC2fNzv8","sNHxtMS","zgvS","EvHIBNy","Ee5RD24","qujdCMq","wM1sDxu","DuX1tKW","Aez1wuu","EwPSCfO","Chn6C1i","BNf2u3K","vMfYrhG","ihrPBwvZ","zw1LBNq","thjQtKu","Dg9Y","z3jNyNO","C2vUDa","v1jzA1u","y291BNq","z2v0sxrLBq","se9Kvuq","EM5drhC","B25dBg9Zzq","z3n2qKG","t1LfBvC","x2DLDeLUDgu","z2vY","Du1PsuW","r0zsCxm","AwDdCLu","q0r2sMO","Dw5tsg4","zgzoAhi","C2rhyuC","DhjPzxm","vMHfCKy","sLjKzKq","Ew1NzwK","r1v2s1C","tMHUyu0","zNnky3O","Bwrurgy","x2zVCM1HDeu","C2nYAxb0","vuPcs2q","EK9ksxC","we14ENG","tNfrsM0","zgrjrcWGzgu","rwPTEwG","rLfRu00","y3jLyxrLrxi","CMn0weO","swDMBhi","De1HBMfNzxi","CNjMDgq","x3fVC0rc","rwToB3a","DKnAwxK","B3nLrxzLBNq","EgrTCgy","CNjVCK1LC3m","CLzHBhvLCW","x3DHAxq","y3ruAw1LB3u","r2PAywm","rNjVBNrPzxi","Dgv4Dc9WBge","AxnbCNjHEq","DLbMrvi","Dej3DuS","Cgf5Bg9Hzeu","sK9bvMW","vKH1zeu","C0nVDw50zxi","EwfUAey","rujtEum","rLLeyMm","DMvY","mxWZFdj8mta","m3W0","C3nHz2vfDMu","sM5lvKi","CMvHC29U","Dg9iyxnO","tgrLuLe","BxLjzgW","DKDXzLG","DxjquLm","zgvMAw5Luhi","wfz4r2O","C3rYAw5N","rerwrNG","zvrYAhm","ywrKt25L","ywDLsgLKzq","DgLLCKPtt04","BLL1wfq","zxjFCw9Z","zw1PDa","AM9PBG","zhjurMq","yNL0zuXLBMC","DMTRCMu","D24GCMvHC28","ihjLy29UBMu","u2TPCcbWyxm","AvjovNq","yNPYA2i","tg5XCgq","yxbWBgLJyxq","wLbpB1i","C1fezuu","Bw1ktNm","D2fZq2XLyw4","A2jitfK","tffhsxq","sNPeqLu","CMvHzg9UBhK","AKvpALa","x3bPBMDqB24","quDvBeq","CM9zBKe","zMLUza","EuzyBxy","x0vysvnu","BMrWB2LUDca","v1bHwg8","Exntz2e","C2HPzNq","q05Nq2W","s1Diquu","Cw9wzeC","Aw9UvgLTzw8","CgjICdi","Cw9Z","DeLUDgvYy2u","sxjhuM4","u3v3Dhq","wuDtC00","x29UrxjYB3i","yNvMzMvYzwq","q0DbzLq","t2PQAxm","x2rItMfTzq","D1vRq00","BhDhtuq","q0zHC0O","vgXPALy","yMLUyxj5vhK","C3rHCNq","B3bLBIa","y2fSBa","y29UBMvJDeu","CNnVCKzPBgu","EuHuCNq","C3rYAw5NAwy","quH5wfi","y3vYC29Yx2y","x2LZqNjVD3m","BgLZDgvUtMu","q3LAwLu","mhWYFdn8nhW","y29UDgLUDwu","q0vsAgm","vhHgBw8","zufJAW","B0fvCfK","C29YDa","DeTpsfi","Aw50zwDLCIa","thHdzK0","whfzuui","x2LZtwLUAvC","r2Xztvu","yxGGCMv0CMK","BgvUz3rO","uwrhBLy","zxLVzg8","B25nzxnZywC","sM16ENi","u05cELq","Aw9Ul2PZB24","t2nJCuq","z01KzfG","ywnR","DhDVCMTdAge","z2nnB0C","EMDowMO","zMLSzw5HBwu","Bwf4twvZC2e","vgTfqui","rKLmrv9ot1q","Ae1LC3nHz2u","u2zAAMS","veLXB0m","vwTqr1y","Dw5ZAwDUzwq","uLrXueK","BMnVzgLUzW","CMfTugfYyw0","Fdf8oxWZFdu","uunjvK4","qw1ZDeu","DxfxtfK","BMvJDa","DhjHBNnHy3q","v3DXEwW","x3bPBMDmB3m","DuLYzfq","zNjVBuj5Dgu","EvfVq2e","y1fgqxC","EgfmBK0","x2LUDgvYDMe","CKXiCgK","teHbzvm","CMv4zuO","zLHJEvq","twnbzNq","yNLJDKK","uhjPBwfYEuS","AwPXyu8","t0reEM8","ihzHBgLKihm","x2nSzwfYvgK","BgT4D3C","q29Kzq","x2DLBMvYyxq","DvHRrNi","CMvJzxzPzwq","y0fmA0i","B25tDgfYDfi","BMvY","tKvezxq","AujsBKm","mxW0Fdn8nxW","CMvWBgfJzui","CMvUDevUzha","wxLiy2K","vNvgB1u","ihrYEsbYzwm","B2npwLy","x25HDMLNyxq","DhbizwfKzxi","zMX1C2HfEha","DMzZDM4","EvnuwhC","B25szwnLAxy","D2LSBfjLy28","z1bbB1K","ihn1y2nLC3m","ChjVDg90Exa","CIb0DhDjra","rxzLBNq","Bwv0Ag9K","B1v1EKG","ign1CNnVCIa","ExHtB0S","BMfTzq","zxq9DxrMltG","BfrPBwvVDxq","igzPzwXKoIa","EvbsCNi","DMvUDa","CNnVCL92ywW","Cw9Zx18","uLDhzxq","v05XEvO","x0rctMfTzq","quTnvxu","C2vYDMvYvgK","DMH2zee","z1vSDui","zennrLK","z2v0","CNvHCwO","yxv0BW","AwDHDg9Yt24","uwnrDe4","swPPvhe","CKvzA1a","r01jAfa","DwjmDva","yw5Hz2vY","x3jLBw92zvC","seTptMS","CwnVwM4","B25mAw5L","DKzwwMq","zxH0ugf5Bg8","x3DZ","yMfJA3vWigu","CMvZDwX0","AKrjww8","BMCGB3iGyw4","v0fpAuO","C2vYDMLJzs0","sw1qtLa","C2DPza","zv90Aw1LB3u","x29Ut3bLBG","uLDmDgm","Au5hu0C","uu1Zy1a","BwvZC2fNzq","ndmZmxHUAgzNrq","zMT4AeW","mJi3nffcD1zSBq","wuzZAgC","reXcBNe","m3W1","yMrFzgLK","B0vTrNG","zMzmAw5L","AwXK","DNDhC2G","x3vYBa","vxPrvNK","v2vPEgLUsLm","DwfWCeG","zw5HyMXLqxu","vMH5A2q","Ahr0Ca","ywrxweq","suvtx0vsuK8","wfrhsgu","BfHWsvy","yLjLz0W","Cw1dDKu","tKvQAuW","B3jRig9MzMW","yKfntLa","mty3mhfOD0XcDq","qLPYwK0","B3bLBKrc","lcbOB3n0BMe","ywrK","C2n0qKS","zv9ZDwnJzxm","vw5PBxbSzw0","Ec1TC2CTy3u","wMD3EK4","AuDlvvy","A1LxA2S","pxv0zI04","ueLeCgq","twzjAhm","B3jRzxjhBg8","ALjlBhG","r3vswvC","s1znAg0","v3bNzKW","qLL4uKi","x3DZsw5ZDge","vfHmC1e","z2vjBMzVu3K","ywnOzwq","B25LCNjVCG","tg9JAW","CMvZB2X2zq","yKT3C3C","EKP5yvy","jMPZy2fSBgi","y3vYC29YlNm","zxrxB3jRq2G","zMXVB3i","A3DbrxO","AgLNAa","t3bzCha","Dg9cExrLC0i","Dgvzv1m","vxjmrwG","q0Xpu0LorW","x3nVy2TLDa","C0Xf","uKPxuK0","tgLZDgvUzxi","DgLUzYbZzxi","AfnvsMO","s0j0yMO","EM5mr0C","B2Dft3e","z29PBMCGyxC","B2zMC2v0","ugrwEKC","B1Dhr2W","A1Pcq0S","DgvZDa","Axriv20","DfvMz1a","yxvssgO","A0P5yuy","z1rPBwvVDxq","x2nVBM5Ly3q","CNzHBa","D2D5Cvy","BwXQsu4","Aw9QBgW","r0zewg0","id4G","CLrgvhO","yNPZwvu","z1zgyNi","u25fzvy","AxmGDw5Kzwy","qwPzrLa","zNvjDxu","Dvz3uKO","CMvZzxrdB3u","BvPfqLy","yNvMzMvY","u2vXsuq","se5sz0S","rwXesxm","zxjFBxnNAwq","zsbHihn0CMK","END3uM0","rKvjtLi","CgXLyxnLiha","BM93","Be1RC0W","ywXPzcb1CMW","CM92AwrLige","B3vvBNO","zgfHCeO","Ew9KwNq","Efrurw52","rwPHqNy","Dw5RBM93BIa","AwXLtMfTzq","zMP1Egu","rLjptLrjrvi","rMHRsLe","veHbvw8","Cg9PBNrdB24","zxjYtM8","whf6q2W","tg9qDuu","zxjFAxnFywm","DKDqs1K","C0LguMi","ufzKuuG","rhrfzLy","Dhr3Awq","wM1xq0S","y05UEvK","Egj1vNC","v0fSCw4","BgLUzw5V","DKPAt3i","AvH2r0W","CMvTB3zLq2G","BwjcCwK","re5Yre0","tKPJEhC","D3nZoI8V","ugrQrw4","yxbWBhK","BezSDxnO","AxnrB1nby2S","AKzKyMC","rMTzAM4","CxzbuNy","AxDhu2m","CwDsswO","BwLUzW","zxjYB3i","DLbUDM4","tvrHD0W","nhWWFdf8mNW","shP4quu","su5tvefova","zw50tgLZDgu","v25QCe8","rhPuvgC","s01hq2q","sNfswNu","x2rPC3bHDgm","yxvgBNy","txDptve","ENr3whu","Dfj1rvG","D2fKuLC","qNjPzgDL","yLLqww0","DxDjy0O","rvbpseq","uMreuKu","EfnSEwu","tenAEey","rLjIvNu","CgfNzwHPzgu","AwLlEfO","Chrqu0C","z2nzCwq","qurbCxK","AwrmDKy","q0Dsq2O","y3r4","yw1Lu3bHy2u","sxnlBuq","C0HUy0G","yNL0zu9MzNm","ExbL","icSG","AMPiC2W","zxf1ywXZ","EwHmsw0","yLfOAxK","vfbxAge","ve1TBvK","uKPcsgi","C2T3Bwy","zfrbC2K","zezqBxm","vw5KyvO","B2nRzxrgywK","wNnTEwC","y1DJEMm","uhbtC3C","ChjVy2vZCW","AwvhC2i","BMT6CxK","wengD1y","AMTUzMK","uMPPCKC","EvjAz3q","yNfNz0W","wKLqzxK","y3vYDMfSDwu","mtqWmZvvre9Py1i","Cgf5Bg9Hza","tKjrBNG","ugHUuey","wvDvtM8","Aw5KzxG","y29UBMvJDfm","y2XVC2veqG","EgXNDKO","zvvYBa","AefJA01LC3m","s0nbB3O","B3v0sw50zxi","zxjHDg9Y","twvZC2fNzuu","AwXLx25HBwu","tvz2zKS","z2v0q3vYC28","zfnfsxK","BujJC1i","B2LUDfjLywm","B25VCgvU","Aw9U","uLbnueK","vuPMtKG","x3bYzwzPEa","t1bftL9fuLi","rhrVEeW","CxbPy3u","y2vZC0HHBMq","DMvYC2LVBG","Bwu6ia","y2XVC2u","AxnszwfKEq","CMvJB25Uzwm","Bhm6ia","y2HHCKnVzgu","Cu1vv20","l3DZl3yY","D3jPDgu","ENDssha","y3jLyxrLrwW","BM9szuS","qNvXEeC","yxrHlcbKyxq","BNnzCxy","AwDjzem","r1zOEKK","Bg93","DKjur3a","y29OzwW","tgLnu0C","B25ozxr3B3i","y2uGBM90igK","DuDhweK","x2rPC2nVBM4","DKvhCxG","zM9YrwfJAa","swT1DfC","mtC4D2Tkwgrm","CgLUz0LUDgu","zNjVBu51Bwi","uu5nyui","ignVzgu6ia","CgLUz0XVC3m","ywWGy3vYC28","u2vYDMLJzvC","Aw1LCYbPBIa","B3bLBG","y2XLyxjtDg8","A3jYtvC","wvrdze0","z2v0qwXSs2u","Cen1Chy","x2rYB3bhBg8","u2jQA2u","BgLTAxq","CLDiA0W","tujKB24","sKDxB2u","tKDFrvjst1i","txfIDxu","mJK1Awzur3vu","x2HHBMrSzva","AMnhugS","ihbYB3rVy28","y3jLyxrLt3a","Evnytxe","y2HLy2Tszwe","C2v0zgi","t011tNG","v2vIu29JA2u","BwzqBvy","AenSB3nLrxy","zMXXwgW","zxjFCw9Zx2e","s3n3wuu","ywnRx2LK","r2T6zfC","zMzMzG"];return Nn=function(){return r},Nn()}function Qc(){return Pi||(Pi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ex(){let r=S;return ki||(ki=[IDBCursor[r(912)+"e"][r(354)],IDBCursor[r(912)+"e"][r(823)],IDBCursor[r(912)+"e"]["continue"+r(881)+"ey"]])}function tx(r){let e=S,i={RTqPI:e(1551),TPWha:function(c,u){return c(u)},YnXct:function(c){return c()},ouUnz:function(c,u){return c(u)},QcQtN:function(c){return c()},nnBUj:function(c,u){return c instanceof u}},a=new Promise((c,u)=>{let d=e,h={voaIv:function(y,A){return i[D(1084)](y,A)},MBdon:function(y){return i[D(939)](y)}},m=()=>{let y=D;r[y(1368)+"entListener"](i[y(858)],w),r[y(1368)+y(1133)+y(893)](y(1127),_)},w=()=>{let y=D;i[y(1170)](c,i[y(1170)](Ae,r[y(953)])),i.YnXct(m)},_=()=>{let y=D;h[y(191)](u,r[y(1127)]),h[y(1269)](m)};r[d(426)+d(1037)](i[d(858)],w),r[d(426)+d(1037)]("error",_)});return a[e(1556)](c=>{let u=e;i[u(1470)](c,IDBCursor)&&Ir[u(396)](c,r)})[e(274)](()=>{}),On[e(396)](a,r),a}function nx(r){let e=S,i={ZgQVG:e(1501),mbBqi:e(1127),xPCKU:e(185),qiXkW:function(c){return c()},kYHIH:function(c,u){return c(u)},WwnkZ:e(1367)+"or"};if(Ln.has(r))return;let a=new Promise((c,u)=>{let d=e,h=()=>{let _=D;r[_(1368)+_(1133)+_(893)](i[_(447)],m),r[_(1368)+"entListe"+_(893)](i[_(1113)],w),r[_(1368)+_(1133)+_(893)](i[_(307)],w)},m=()=>{i[D(397)](c),i.qiXkW(h)},w=()=>{let _=D;i[_(1386)](u,r[_(1127)]||new DOMException(i.WwnkZ,i[_(650)])),i[_(397)](h)};r["addEvent"+d(1037)](d(1501),m),r[d(426)+d(1037)](i[d(1113)],w),r.addEventListener(i[d(307)],w)});Ln[e(396)](r,a)}function rx(r){Bn=r(Bn)}function sx(r){let e=S,i={VuFoU:function(a,c){return a(c)},OrCMT:function(a,c){return a!==c},ZhhRl:"rScxX",tCEJc:function(a,c){return a(c)},LCZxF:function(a,c){return a===c},zELIW:function(a,c){return a in c},nqodb:e(1292)+e(204),LYZNw:function(a){return a()}};return i[e(1150)](r,IDBDatabase[e(912)+"e"][e(866)+e(1213)])&&!i.zELIW(i[e(567)],IDBTransaction[e(912)+"e"])?function(a,...c){let u=e,d=r[u(812)](i[u(900)](qt,this),a,...c);return Dr.set(d,a.sort?a[u(828)]():[a]),i[u(900)](Ae,d)}:i[e(1415)](ex)[e(540)](r)?function(...a){let c=e;return i.OrCMT("rScxX",i.ZhhRl)?(this[c(480)+c(344)+c(1380)+"t"]++,this[c(657)+c(511)+"nt"]()):(r[c(1118)](i[c(900)](qt,this),a),i[c(900)](Ae,Ir.get(this)))}:function(...a){let c=e;return i[c(900)](Ae,r[c(1118)](i[c(561)](qt,this),a))}}function ix(r){let e=S,i={lKESJ:"function",OlXmv:function(a,c){return a(c)},bycvI:function(a,c){return a instanceof c},MoHqo:function(a,c){return a(c)},AjYFP:function(a,c,u){return a(c,u)},zwVGW:function(a){return a()}};return typeof r===i[e(492)]?i[e(1334)](sx,r):(i[e(880)](r,IDBTransaction)&&i.MoHqo(nx,r),i[e(1066)](Ni,r,i.zwVGW(Qc))?new Proxy(r,Bn):r)}function Ae(r){let e=S,i={UFedB:function(c,u){return c instanceof u},DeRcO:function(c,u){return c(u)},tgofV:function(c,u){return c!==u}};if(i.UFedB(r,IDBRequest))return i[e(448)](tx,r);if(Tn.has(r))return Tn.get(r);let a=i[e(448)](ix,r);return i[e(311)](a,r)&&(Tn.set(r,a),On[e(396)](a,r)),a}var Ni,Pi,ki,Ir,Ln,Dr,Tn,On,Bn,qt,Di=Ri({"node_modules/idb/build/wrap-idb-value.js"(){let r=S,e={akUDc:function(i,a){return i===a},KgVuE:r(1573),IBYTM:function(i,a){return i===a},IDztO:r(1292)+r(204),lwGMD:function(i,a){return i===a},wRQjT:r(1583),BvbGT:function(i,a){return i(a)},HTWbt:r(781),PMfpa:function(i,a){return i instanceof a},aRzWU:function(i,a){return i===a},WOwsl:function(i,a){return i in a}};Ni=(i,a)=>a[r(1523)](c=>i instanceof c),Ir=new WeakMap,Ln=new WeakMap,Dr=new WeakMap,Tn=new WeakMap,On=new WeakMap,Bn={get(i,a,c){let u=r;if(i instanceof IDBTransaction){if(e[u(361)](a,e[u(652)]))return Ln[u(935)](i);if(e.IBYTM(a,e[u(323)]))return i[u(1292)+u(204)]||Dr[u(935)](i);if(e.lwGMD(a,e[u(1338)]))return c[u(1292)+u(204)][1]?void 0:c.objectStore(c[u(1292)+u(204)][0])}return e[u(1439)](Ae,i[a])},set(i,a,c){return i[a]=c,!0},has(i,a){let c=r;return e[c(806)](e[c(453)],e[c(453)])?e.PMfpa(i,IDBTransaction)&&(e[c(806)](a,e.KgVuE)||e.aRzWU(a,e[c(1338)]))?!0:e[c(1474)](a,i):new _0x3b80a4(_0x554620,_0x265c40,_0x34a655)}},qt=i=>On[r(935)](i)}}),Li={};Zc(Li,{deleteDB:()=>ax,openDB:()=>ox,unwrap:()=>qt,wrap:()=>Ae});function ox(r,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let d=S,h={XPxPU:function(_,y,A,k,T){return _(y,A,k,T)},NGEAU:function(_,y){return _(y)},noWfx:function(_,y){return _(y)},HfrBi:d(1455)},m=indexedDB[d(1259)](r,e),w=h.noWfx(Ae,m);return a&&m["addEvent"+d(1037)](d(538)+d(235),_=>{let y=d;h.XPxPU(a,h.NGEAU(Ae,m[y(953)]),_[y(558)+"on"],_.newVersion,h.NGEAU(Ae,m[y(866)+y(1213)]))}),i&&m[d(426)+d(1037)](h[d(1527)],()=>i()),w[d(1556)](_=>{let y=d;u&&_[y(426)+y(1037)](y(1223),()=>u()),c&&_["addEvent"+y(1037)](y(1311)+y(1536),()=>c())}).catch(()=>{}),w}function D(r,e){r=r-185;let i=Nn(),a=i[r];if(D.mDUnnp===void 0){var c=function(m){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",_="",y="";for(let A=0,k,T,R=0;T=m.charAt(R++);~T&&(k=A%4?k*64+T:T,A++%4)?_+=String.fromCharCode(255&k>>(-2*A&6)):0)T=w.indexOf(T);for(let A=0,k=_.length;A<k;A++)y+="%"+("00"+_.charCodeAt(A).toString(16)).slice(-2);return decodeURIComponent(y)};D.FOzkfp=c,D.zBZjkY={},D.mDUnnp=!0}let u=i[0],d=r+u,h=D.zBZjkY[d];return h?a=h:(a=D.FOzkfp(a),D.zBZjkY[d]=a),a}function ax(r,{blocked:e}={}){let i=S,a={KBtbj:"blocked",hSyFl:function(u,d){return u(d)}},c=indexedDB[i(544)+i(1420)](r);return e&&c[i(426)+i(1037)](a[i(1040)],()=>e()),a.hSyFl(Ae,c)[i(1556)](()=>{})}function Ii(r,e){let i=S,a={xbuVw:function(m,w){return m===w},zgNZj:i(1327),clufc:i(1488)+"e",chcft:i(778),NEDet:function(m,w){return m instanceof w},zNdtp:i(751),kLxHe:function(m,w){return m in w}};if(!(a[i(894)](r,IDBDatabase)&&!(e in r)&&a[i(1107)](typeof e,a[i(459)])))return;if(Rn[i(935)](e))return Rn[i(935)](e);let c=e.replace(/FromIndex$/,""),u=e!==c,d=Bi[i(540)](c);if(!a[i(1397)](c,(u?IDBIndex:IDBObjectStore)[i(912)+"e"])||!(d||Oi[i(540)](c)))return;let h=async function(m,...w){let _=i;if(a[_(1107)](a[_(848)],a[_(848)])){let y=this["transact"+_(1213)](m,d?a[_(602)]:a[_(349)]),A=y[_(1583)];return u&&(A=A[_(1196)](w[_(789)]())),(await Promise.all([A[c](...w),d&&y[_(1573)]]))[0]}else return _0x5461fb[_(1020)]()};return Rn.set(e,h),h}var Oi,Bi,Rn,cx=Ri({"node_modules/idb/build/index.js"(){let r=S,e={HSeWC:r(342)+r(971),TsnCd:"get",zwwRm:"getKey",jEOjP:r(210),iXrKA:r(1263)+"ys",QplzL:r(678),qoVdG:r(997),QDqyk:function(c){return c()},sQDeE:function(c,u){return c(u)}},i=e[r(522)][r(1357)]("|"),a=0;for(;;){switch(i[a++]){case"0":Oi=[e[r(356)],e[r(1077)],e[r(779)],e.iXrKA,e[r(1404)]];continue;case"1":Di();continue;case"2":Bi=[r(460),e[r(792)],"delete",r(1589)];continue;case"3":Rn=new Map;continue;case"4":e[r(1394)](Di);continue;case"5":e[r(772)](rx,c=>({...c,get:(u,d,h)=>Ii(u,d)||c[r(935)](u,d,h),has:(u,d)=>!!Ii(u,d)||c.has(u,d)}));continue}break}}}),xx={idb:function(r){let e=S;r[e(208)]=Promise.resolve().then(()=>(cx(),Li))[e(1556)](function(i){return i})}},Ti={};function Ce(r){let e=S,i={OpYpp:function(u,d){return u!==d}};var a=Ti[r];if(i[e(1029)](void 0,a))return a[e(208)];var c=Ti[r]={exports:{}};return xx[r](c,c[e(208)],Ce),c[e(208)]}Ce.d=(r,e)=>{let i=D;for(var a in e)Ce.o(e,a)&&!Ce.o(r,a)&&Object["definePr"+i(1524)](r,a,{enumerable:!0,get:e[a]})},(()=>{let r=S;Ce.o=(e,i)=>Object.prototype["hasOwnPr"+r(1524)][r(812)](e,i)})(),(()=>{let r=S,e={GlYMU:function(i,a){return i&a},fcWNc:function(i,a){return i&a},AATzW:function(i,a){return i>>>a},empmZ:function(i,a){return i===a},VBPlc:r(351),WIDgq:r(441)+"d",nvYoW:r(373)};Ce.r=i=>{let a=r,c={xNkwn:function(u,d){return u&d},CBpZX:function(u,d){return e[D(834)](u,d)},iBRnC:function(u,d){return u>>>d},Shwku:function(u,d){return e[D(1508)](u,d)},VgOcV:function(u,d){return e[D(1400)](u,d)}};if(e.empmZ(a(1182),e[a(1335)])){let u=Y.high,d=Y.low;return[255&d,c.xNkwn(d>>>8,255),c.CBpZX(c[a(895)](d,16),255),d>>>24,c.CBpZX(255,u),c[a(662)](c[a(895)](u,8),255),c[a(528)](c[a(895)](u,16),255),c[a(525)](u,24)]}else e.WIDgq!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:e[a(462)]}),Object[a(749)+"operty"](i,"__esModule",{value:!0})}})();var Z={};(()=>{let r=S,e={Wwqyl:function(s,t){return s(t)},FRbVu:function(s,t){return s+t},sHCUG:function(s,t){return s+t},nsYqv:function(s,t){return s*t},Ejmyh:function(s,t){return s(t)},CGRCj:function(s,t){return s(t)},gMddX:function(s,t,n){return s(t,n)},JWUSr:r(642),YsTyo:"CoAna",WPYoB:function(s,t){return s(t)},bWVmS:function(s,t){return s+t},vGPKY:function(s,t){return s+t},nSJEf:"0000",tBwuK:r(703),fTtwi:r(265)+"ascript",ymgei:r(983),rEYkP:r(1023)+"ack=fron"+r(756)+"P",tUfgP:function(s,t){return s(t)},sdGaG:r(1089)+r(743),VHGqh:function(s,t){return s>t},dywiE:function(s,t){return s<t},yxSoK:function(s,t){return s>t},mdTDf:function(s,t){return s<t},FMgxc:function(s,t){return s!==t},WnjpO:function(s,t){return s===t},QMscP:r(620),YKCmo:function(s,t){return s-t},snEQx:function(s,t){return s!==t},cOqKa:function(s,t){return s-t},mrBPQ:function(s,t){return s<t},hSUJj:function(s,t){return s<t},gcfJU:function(s,t){return s-t},fiiJj:function(s,t){return s!==t},cFNPZ:function(s,t,n){return s(t,n)},znLGG:function(s,t){return s!==t},eNQpW:function(s,t,n){return s(t,n)},lMksL:function(s,t){return s>>>t},bCRLX:function(s,t,n){return s(t,n)},DTdJA:function(s,t){return s(t)},AChRu:function(s,t){return s(t)},Fwdzm:function(s,t,n){return s(t,n)},JCJBd:r(523)+r(238)+r(922)+r(275),loSPn:r(523)+r(238)+r(922)+r(1403),znLTw:function(s,t,n){return s(t,n)},JeLOY:function(s,t){return s(t)},VleeX:function(s,t){return s>t},leNWC:function(s,t){return s&t},UkPGV:function(s,t,n,o){return s(t,n,o)},nxcat:r(1462),EioPh:function(s,t){return s!==t},wadRW:r(324),RJWRM:function(s,t){return s!==t},jptqS:function(s,t){return s!==t},wuEer:function(s,t,n){return s(t,n)},IcejH:function(s,t,n){return s(t,n)},bzsYU:function(s,t){return s(t)},qccXD:function(s,t,n){return s(t,n)},EYzcl:function(s,t){return s!==t},KgtCY:function(s){return s()},uBRlV:function(s,t,n){return s(t,n)},ErGxD:function(s,t){return s===t},GRGlh:r(1592),RPMPI:function(s,t){return s!==t},CDvJj:"euCcR",xSlye:function(s,t,n){return s(t,n)},tSvYL:function(s,t,n){return s(t,n)},gkhDh:"nfgym",jycie:function(s,t,n){return s(t,n)},DHOJo:function(s,t,n){return s(t,n)},uIrdT:function(s,t){return s!==t},VQKtK:function(s,t){return s!==t},igIdC:r(827),JPetU:r(388),OYEmW:function(s,t,n){return s(t,n)},dikJU:function(s,t,n){return s(t,n)},ZoOno:function(s,t,n){return s(t,n)},nhuyS:function(s,t){return s(t)},goint:function(s,t){return s(t)},lkxww:function(s,t,n){return s(t,n)},McAft:function(s,t){return s(t)},jknfi:function(s,t,n){return s(t,n)},NGjHg:function(s,t,n){return s(t,n)},GCBdw:function(s,t,n){return s(t,n)},LiMSG:function(s,t){return s(t)},NPoqF:function(s,t){return s(t)},pmZIL:r(523)+r(238)+" field: SeqID",RJBHb:function(s,t){return s===t},rDsUi:r(523)+r(238)+" field: "+r(255),QLIdZ:"Missing required field: method",VarDx:function(s,t){return s&t},mMbDs:function(s,t){return s(t)},uVwRJ:function(s,t,n){return s(t,n)},JFCJQ:r(1e3)+r(627)+r(609),yBDnF:function(s,t){return s>>t},xdmpf:"error",hjZQq:function(s,t,n){return s(t,n)},cWczc:function(s,t){return s===t},ElTqA:r(1453),OgqYr:"cwGUA",onPnX:r(1223),unSHn:r(1240),ZgwzN:function(s,t){return s===t},WFere:function(s,t){return s+t},fXHRM:r(766)+r(266),bKwsw:function(s,t){return s+t},AKcgf:function(s,t){return s!==t},nkzqy:"pWPST",QXCYG:"OoFpD",YZLzs:function(s,t,n){return s(t,n)},PwRKq:function(s,t){return s===t},eRjHj:function(s,t){return s<t},ZkTDV:function(s,t){return s<t},FYDbc:function(s,t){return s===t},AcNDo:function(s,t){return s&t},iiKxZ:function(s,t){return s&t},crJGD:function(s,t){return s<<t},TXLsQ:function(s,t){return s<t},LoDtN:function(s,t){return s(t)},WDwbi:function(s,t){return s==t},iZbcz:function(s,t){return s!==t},TpGef:r(241),WnskB:r(669),MhGNu:function(s,t){return s+t},ySTXw:function(s,t){return s|t},vGycp:function(s,t){return s<<t},AHyXR:function(s,t){return s>=t},rzhYg:function(s,t){return s<=t},FGbRC:function(s,t){return s!==t},RjirG:r(1519),AMEBd:function(s,t){return s(t)},EnKEJ:function(s,t){return s+t},Fvbsu:function(s,t){return s+t},MwOMQ:function(s,t){return s+t},EBSyC:function(s,t){return s+t},ovmOR:function(s,t){return s+t},NqQJm:function(s,t){return s|t},DzTTg:function(s,t){return s|t},GSCQd:function(s,t){return s<<t},RULqK:function(s,t){return s|t},XkHZA:function(s,t){return s&t},YxVPh:function(s,t){return s<<t},qpicu:function(s,t){return s&t},pmqlz:function(s,t){return s&t},gsAZi:function(s,t){return s<t},vNgjO:function(s,t,n){return s(t,n)},uMiIL:function(s,t){return s>>t},WLtiO:function(s,t){return s>=t},VhErF:function(s,t){return s<=t},PIDpd:function(s,t){return s-t},Ojjis:function(s,t){return s<t},sCtRC:function(s,t,n){return s(t,n)},sIFRb:function(s,t){return s<t},EPOHD:function(s,t){return s>=t},cQfow:function(s,t){return s-t},NtMVi:function(s,t){return s+t},rtIwz:function(s,t){return s<t},eTrhs:function(s,t){return s&t},gWDZy:function(s,t){return s!==t},fIxaT:r(732),IjiTq:function(s,t){return s|t},bJuZg:function(s,t){return s&t},tnWXN:function(s,t){return s|t},XVSfL:function(s,t){return s&t},LrjNE:function(s,t){return s|t},bQhiy:function(s,t){return s|t},GUvKW:function(s,t,n){return s(t,n)},PdjEn:function(s,t){return s<t},qhWUg:function(s,t){return s+t},NKwUJ:r(202),HWgol:function(s,t){return s<t},Vagci:function(s,t,n){return s(t,n)},fsJcz:function(s,t){return s<t},bXFiG:function(s,t){return s>t},lPZyG:function(s,t){return s+t},ZqiIR:function(s,t){return s(t)},bYlKP:function(s,t){return s|t},UTAim:"BZbWl",iSTiW:r(973),ABIKk:function(s,t){return s&t},TIqoC:function(s,t){return s<<t},CnDbA:function(s,t){return s&t},CAyzp:function(s,t){return s<<t},bgrrf:function(s,t){return s<<t},ISruk:function(s,t){return s&t},TkEAB:"tbuSv",uSGYP:function(s,t){return s(t)},fXcyT:function(s,t){return s<<t},hwSVs:function(s,t){return s&t},opTAV:r(1358),RXlor:function(s,t){return s&t},tjrKO:function(s,t){return s(t)},maZvl:function(s,t){return s<<t},ABCrd:function(s,t){return s&t},itHWm:function(s,t){return s<<t},KHNwX:function(s,t){return s<<t},hVAqw:function(s,t){return s|t},MVPHd:function(s,t){return s>>>t},JqRZu:function(s,t){return s>>>t},LxCfM:function(s,t){return s<<t},xaLnM:function(s,t){return s===t},dzOWn:function(s,t){return s<t},DAtCH:function(s,t,n){return s(t,n)},SrFmX:function(s,t){return s+t},ZmRuu:function(s,t){return s>>>t},XqYQB:function(s,t){return s|t},Voopg:function(s,t){return s&t},JxWNk:function(s,t){return s+t},uYmch:function(s,t){return s+t},Piibw:function(s,t){return s!==t},xESbF:function(s,t){return s|t},iGKUV:function(s,t){return s>>>t},qSauf:function(s,t){return s>>>t},ljrUx:function(s,t){return s!==t},BMiQv:function(s,t){return s|t},mZEBV:function(s,t){return s&t},OXCqB:function(s,t){return s>>>t},RGSis:function(s,t){return s|t},QrOCH:function(s,t){return s>>>t},esPsm:function(s,t){return s&t},oPQOU:function(s,t){return s>>>t},lXpIV:function(s,t){return s!==t},GeIIw:function(s,t){return s===t},YuSSF:r(752),QCIVN:"XlNxs",toEAP:function(s,t){return s(t)},vmYzC:function(s,t){return s<<t},rLHpi:function(s,t){return s<<t},daapJ:function(s,t){return s|t},Jmzzr:function(s,t){return s|t},pKxCQ:function(s,t){return s|t},rOmbg:function(s,t){return s>>>t},WHyxa:function(s,t){return s|t},PHVcj:function(s,t){return s|t},wgyqV:function(s,t){return s<<t},pyvVH:function(s,t){return s>>>t},BuqxG:function(s,t){return s>=t},KCAoz:function(s,t){return s<=t},TggTB:function(s,t){return s%t},vJZOr:function(s,t){return s|t},znCDw:function(s,t){return s/t},uLvkJ:function(s,t){return s>>>t},noReK:function(s,t){return s>>>t},Jlxke:function(s,t){return s===t},PIpqi:function(s,t){return s&t},yanhF:function(s,t){return s&t},ysSga:function(s,t){return s<<t},roYnA:function(s,t){return s!==t},OByOQ:function(s,t){return s===t},mBcsR:function(s,t){return s>>>t},bRegL:function(s,t){return s===t},sLLcg:function(s,t){return s&t},vCZYy:function(s,t){return s>>>t},vPfER:function(s,t){return s>>>t},vhvdA:function(s,t){return s&t},uLeuT:function(s,t){return s>>>t},XVxGj:function(s,t){return s===t},uqWLY:r(1620),WAOiJ:function(s,t){return s&t},ADAqy:function(s,t){return s&t},pVGxK:r(896)+"0|2",MKeOh:r(1217)+"OR",JETSk:r(222)+r(336),kmAGN:r(399)+r(985)+"R",CERhc:r(425)+r(1271),SfZjk:r(243)+"ERROR",KMGCd:r(629),PhnPF:r(1130)+"3",SnEeV:function(s,t){return s===t},WApsD:r(352),bqggL:r(1013),ijqaO:"2|1|4|0|3",wUkCM:r(508),ftuvK:function(s,t){return s-t},fOBEP:function(s,t){return s>t},TMmmY:r(1573),YFshg:function(s,t){return s===t},LHpab:"objectSt"+r(204),yDCcw:function(s,t){return s===t},blLAw:r(1061),xhABy:function(s,t){return s instanceof t},XTGHe:function(s,t){return s+t},Vhykd:r(309)+r(1326),AEUtH:function(s,t){return s<t},iIWvI:function(s,t){return s===t},YSlYq:function(s,t,n){return s(t,n)},dCMFY:function(s,t,n){return s(t,n)},iojll:r(1259),xvZic:function(s,t,n){return s(t,n)},NEjiL:r(965),yhLIm:function(s,t){return s!==t},eyodo:r(636),iNGSG:function(s,t){return s===t},aMpVX:r(1262),IrGRn:r(1193),flqXl:function(s,t,n){return s(t,n)},usBZm:function(s,t){return s>t},FbDzb:function(s,t){return s===t},yodZt:r(930),kbHLY:function(s,t){return s instanceof t},GaNpk:r(818)+"ile_name",yFXmv:r(852)+r(785),gcMoG:r(976),VixQF:function(s,t){return s||t},gEAxi:r(441)+"d",VHudE:"1|0|2|3|4",yPRrr:function(s,t){return s||t},YabXI:function(s,t){return s!=t},zOJIw:function(s,t){return s<=t},qYwfG:"next() c"+r(463)+"ltiple t"+r(1258)+r(1181),TxFmo:function(s,t){return s<t},pszsR:function(s,t){return s<t},sHncH:function(s,t){return s&t},GwcfG:function(s,t){return s<t},qcoZn:function(s,t){return s>=t},pHgOy:function(s,t){return s<t},myIdl:function(s,t){return s|t},kJyaF:function(s,t){return s>=t},yQoCa:function(s,t){return s|t},OijsM:function(s,t){return s|t},QNMaB:function(s,t){return s&t},ZsDBK:function(s,t){return s&t},CyZZU:function(s,t){return s&t},eLsfy:function(s,t){return s&t},grgbz:function(s,t){return s!=t},CCmWI:r(751),IQzmP:"applicat"+r(842),hcxlW:r(676),sctBK:r(306),bhskc:function(s,t){return s>>t},DLBnq:function(s,t){return s|t},GMIhP:function(s,t){return s===t},pjJdZ:function(s,t){return s===t},xZYHj:"fVxsb",Lqvck:"sxWAM",suFJk:r(542)+r(740),hRmOO:function(s,t){return s&t},pcRMr:function(s,t){return s&t},PVOYU:function(s,t){return s|t},LbkvR:function(s,t){return s+t},WpFRG:function(s,t){return s&t},PcwdH:function(s,t){return s|t},AXxEl:function(s,t){return s&t},IsKmD:function(s,t){return s&t},VSZvN:function(s,t,n,o){return s(t,n,o)},eWnCh:function(s,t){return s!=t},oZFIg:function(s,t){return s instanceof t},ODDzo:function(s,t){return s instanceof t},bAMNP:function(s,t){return s!=t},KVMhm:r(727)+r(1479)+r(920),xuPVH:"boe",LQGIt:"stop imm"+r(303)+r(765)+"ct",MwAJi:function(s,t){return s===t},OMuNx:r(773),iNsIv:function(s,t){return s(t)},grMIv:function(s,t){return s+t},AmstE:r(1465),xNmNL:function(s,t){return s(t)},IvAIn:function(s,t){return s(t)},GzQvo:r(1545),EILYV:function(s,t,n){return s(t,n)},XSqIw:r(365),fgrDr:r(467),YlgmE:function(s,t,n,o){return s(t,n,o)},IjqPk:"success",SNBzT:function(s,t){return s!==t},pNQBt:r(1426),oOrcV:r(1268),iXvGL:r(1103),GNtYf:function(s,t,n){return s(t,n)},ltijy:function(s,t){return s+t},mFcxp:r(1510),RnekH:function(s,t){return s!==t},RWGet:r(288),NhuKQ:r(570),yFUrY:function(s,t){return s!==t},vcRis:r(355),onfme:"JfKsE",TZcwU:"TOXhb",vrSam:"kwqQZ",iRNVt:function(s,t){return s(t)},MPRdP:r(380),qTnZs:r(790),wNAWI:function(s,t){return s||t},mToTK:r(1031),fuIuu:r(1398),OHqxp:function(s,t){return s||t},DtoxL:r(1275),IbgQY:function(s,t){return s||t},dSEIy:function(s,t){return s||t},nKbRB:r(717),pKRik:r(382),HNRgK:function(s,t){return s||t},KBKWj:function(s,t){return s!=t},rctXJ:r(795),vcvHN:function(s,t){return s(t)},qiQmJ:function(s,t,n){return s(t,n)},uEdFI:function(s,t){return s+t},gVFbr:r(1231),IHTGh:function(s,t){return s-t},gferY:function(s,t){return s&t},OccqD:function(s,t){return s|t},azVAq:function(s,t){return s&t},iDrts:r(464),gAdcG:function(s,t,n,o){return s(t,n,o)},CrnJw:r(1382)+r(758),GkpBk:function(s,t,n,o){return s(t,n,o)},XqUWl:r(1382)+r(1286)+"ck",NzKVY:function(s,t,n,o){return s(t,n,o)},DNrDM:r(1382)+"er_ack_m"+r(959),orwKm:function(s,t){return s(t)},eeSWc:r(293),jpiBu:function(s,t,n,o){return s(t,n,o)},hVHRn:r(199),cMhEQ:function(s,t,n,o){return s(t,n,o)},fQxNw:r(1372),kVGWH:function(s,t){return s&&t},omCKd:r(1288),JkbOf:function(s,t){return s||t},AhpLS:"received",ocOZV:function(s,t){return s instanceof t},RpvOG:function(s,t){return s===t},kwAEz:r(398),SEogJ:function(s,t){return s!==t},dnPSV:r(656),KlAsr:"DBTOv",WpgfL:function(s,t){return s instanceof t},ElDIs:r(770)+r(842)+r(440)+r(1005),WRYkU:"none_none",IkutW:function(s,t,n,o){return s(t,n,o)},auRHj:function(s,t){return s>t},RZjDA:function(s,t){return s(t)},xnaTj:function(s,t){return s>t},TlijV:function(s,t){return s+t},QRKuj:function(s,t){return s||t},PpSsw:function(s,t){return s>>>t},lnnfm:function(s,t){return s!==t},fsZLh:r(829),THAUo:function(s,t){return s+t},CNgTz:"index ou"+r(611)+r(217),LeVJx:r(1165),hyPBs:function(s,t){return s||t},vPnvn:function(s,t){return s&t},HummS:function(s,t,n,o){return s(t,n,o)},skBic:function(s,t){return s+t},IxcnJ:function(s,t,n){return s(t,n)},LhEiz:"4|1|3|2|0",OOnel:function(s,t){return s+t},rwlLv:function(s,t,n,o){return s(t,n,o)},LHAeS:function(s,t){return s+t},mfPmV:function(s,t,n,o){return s(t,n,o)},ccHul:function(s,t){return s+t},yWlIF:function(s,t){return s+t},EKvhq:function(s,t){return s|t},wTjDY:function(s,t){return s<<t},QKOgQ:function(s,t){return s+t},ZKyjj:function(s,t){return s<<t},iwGSc:function(s,t){return s+t},kgVbb:function(s,t){return s+t},MscWo:function(s,t){return s+t},wTTVB:function(s,t){return s|t},AXUVN:function(s,t){return s<<t},UlpKB:function(s,t){return s+t},dWTSg:function(s,t){return s+t},GjZac:function(s,t){return s>>>t},SngSl:function(s,t){return s+t},dFPms:function(s,t){return s&t},CGAfT:function(s,t){return s+t},GFDXm:function(s,t){return s+t},gsvBH:function(s,t){return s&t},NwSrd:function(s,t){return s&t},lAMtm:function(s,t){return s&t},gJbEK:function(s,t){return s|t},zUIub:function(s,t){return s>>t},XojXO:function(s,t){return s===t},JGWoe:r(451),NJcxw:r(1046),rElKZ:function(s,t){return s!==t},YosCX:function(s,t){return s!==t},DRCCE:function(s,t){return s>>>t},IsEHg:function(s,t){return s|t},UloIV:function(s,t){return s&t},xWrUJ:function(s,t){return s|t},fkxhL:function(s,t){return s>>>t},mtLCZ:function(s,t){return s|t},SVBxF:function(s,t){return s<<t},CDETF:function(s,t){return s>>>t},JRdfD:function(s,t){return s&t},kYTRG:function(s,t){return s|t},pCupv:function(s,t){return s===t},ptPSG:r(1466),nJbDG:function(s,t){return s|t},JtQwi:function(s,t){return s!==t},wrMDh:"QWdzW",gcYqd:"JOxue",RWVrx:function(s,t){return s(t)},WAlqn:function(s,t){return s+t},TbXao:r(739)+"|7|4|9|6|8|5|0",DEjkR:r(1190),ROtCV:r(1024)+"ervice",bmFhL:function(s,t,n,o){return s(t,n,o)},uXkFr:r(919),vGqfX:function(s,t){return s(t)},gOHHJ:function(s,t){return s<t},XDlZY:function(s,t,n){return s(t,n)},EVaNS:function(s,t,n,o){return s(t,n,o)},Duftw:function(s,t,n){return s(t,n)},jFdbg:function(s,t,n){return s(t,n)},DvYSw:function(s,t){return s===t},KMkSo:r(1321),uappH:"allCurso"+r(722),gaslx:r(360),drTFd:function(s,t,n,o){return s(t,n,o)},rexeJ:r(1132),QMezL:r(1387),EjaBv:function(s,t,n,o){return s(t,n,o)},ZmWCK:r(1280),efHEw:function(s,t){return s|t},SqlkZ:function(s,t){return s<<t},uGGXI:function(s,t){return s<<t},RjCxG:function(s,t){return s<<t},XMxzx:function(s,t){return s|t},MdtFt:function(s,t){return s===t},dmcRj:r(1412),MLKQj:r(763),mljIN:function(s,t,n){return s(t,n)},yjlpZ:function(s,t){return s||t},ogEOq:r(455),HFAeT:function(s,t,n,o){return s(t,n,o)},mCIfX:r(634),JnKVB:"x_fronti"+r(1075),kUMth:function(s,t){return s(t)},kYWkk:r(1382)+r(393),odQcx:function(s,t,n,o){return s(t,n,o)},eHvoe:r(433)+"s",FloOg:r(1001)+r(1498)+"e",adWXD:function(s,t,n){return s(t,n)},QIOUJ:"x-msg-cu"+r(925)+"ue",HtXhB:function(s){return s()},wWCiO:function(s,t){return s<t},FtciR:function(s){return s()},WjExt:function(s,t,n){return s(t,n)},UJfNH:function(s){return s()},qmCvE:function(s,t){return s!==t},RjTYz:function(s,t){return s<t},HOdUD:function(s,t){return s===t},gUluB:function(s){return s()},bulYw:function(s,t,n){return s(t,n)},NFiCr:function(s,t,n){return s(t,n)},bzrkb:r(1425),HmcNJ:function(s){return s()},EXwlN:r(207),xlgvJ:function(s,t,n){return s(t,n)},WNqyZ:function(s,t){return s===t},KepRA:r(1614),sEvEh:function(s,t){return s!==t},Igflr:function(s,t,n){return s(t,n)},XamOx:function(s,t){return s!==t},jSiGZ:function(s,t,n){return s(t,n)},uwIcJ:function(s,t,n){return s(t,n)},iyCFI:r(228),auFnv:"pIwbk",cNnyY:r(794),qvARv:r(937),vEGqx:function(s,t){return s===t},FwdRg:r(1079)+r(1300)+r(477)+", WebSoc"+r(363)+r(1374)+r(1065)+r(314),ZPOoR:function(s,t,n){return s(t,n)},mwrRe:r(1225)+"t",YyHci:r(1481),dTAsi:r(1152),qomxi:r(466),yHTrt:r(972),RFpMQ:r(1104),lafFS:r(1458)+"d",Zsmyg:function(s,t,n){return s(t,n)},VAuJB:r(1417),oJqRZ:function(s,t,n){return s(t,n)},TXYHv:function(s,t){return s||t},hFuYE:function(s,t,n){return s(t,n)},rrftd:r(810),GVhzI:function(s,t){return s>t},FQkSM:function(s,t){return s-t},qgRIj:function(s,t){return s(t)},SMZrb:"WGRjF",UrLEh:r(1092)+">",igCrU:function(s,t){return s===t},oTpRp:"vtFvh",IXVZC:function(s,t){return s>t},MfIhs:function(s,t,n,o){return s(t,n,o)},YBOWF:"dCVVT",WEzxw:r(1402)+r(960)+"t",XeSvb:r(1594),GNTKM:r(1043)+r(1473)+r(1225)+r(1038)+r(738),JzDBU:r(1450),tMocb:"xAjMn",ebvPe:r(270),ySXMq:function(s,t,n,o){return s(t,n,o)},RYMkX:r(255),FkYjn:r(1572)+r(901)+"onnecting",jjHsl:r(1362),CFasJ:r(822)+"1",oUuzH:function(s,t){return s!==t},AeUqd:r(1141),CYOJw:function(s,t,n){return s(t,n)},cohel:"PdVzG",krkEo:function(s,t,n){return s(t,n)},JYFdY:function(s,t,n){return s(t,n)},JpaJW:r(1043)+r(1517)+r(991)+r(1590),lVGoi:r(1093),Qmhts:function(s,t){return s(t)},OzKSe:function(s,t){return s!==t},vxssM:r(457),HzxAE:function(s,t){return s|t},APQGM:"SiSjK",krrMW:r(509),efFvQ:r(1142),GkzdW:r(386)+r(521),iFBFQ:function(s,t){return s===t},GuRYW:"close, ws instan"+r(1244)+"nitialized",RBbZr:"please p"+r(1083)+r(200)+r(1235)+r(1293)+r(1076)+r(955)+r(482)+r(1569),zAUUt:r(472),YGSsM:function(s,t){return s!=t},sREcf:function(s,t){return s(t)},GTWJD:function(s,t){return s(t)},LoPuE:function(s,t){return s instanceof t},zJyaV:function(s,t){return s===t},LdeRQ:"LrNEO",btpOA:function(s,t){return s||t},yRZgt:function(s,t){return s==t},VPSjG:function(s,t){return s!==t},eBaWQ:r(294)+r(1469)+"ing",HJFEZ:"1|0|4|2|3",aTxZs:function(s,t,n){return s(t,n)},QcclB:function(s,t){return s(t)},SKGWL:r(598),bYPYm:function(s,t){return s*t},YBKUP:r(1560),vfsvn:function(s,t){return s===t},KswYE:r(374),idLvF:r(490)+r(531)+"lobalScope",GFRqs:function(s,t){return s!=t},tfXHP:function(s,t){return s===t},ADzWv:r(1257)+r(1008)+r(1579),TtQQt:function(s,t){return s!=t},ITwwy:function(s,t){return s===t},uLuNL:function(s,t){return s===t},gPAoY:function(s,t,n){return s(t,n)},TGCao:r(428)+r(926)};Ce.r(Z),Ce.d(Z,{FWS:()=>t0,CustomErrorEvent:()=>ms,createCloseEvent:()=>me,ReconnectEvent:()=>ps,createErrorEvent:()=>le,decodedFrame:()=>ds,createOpenEvent:()=>Ss,CustomCloseEvent:()=>ws,createReconnectEvent:()=>cr,FrontierMessageEvent:()=>ys,encodeFrame:()=>ar,createMessageEvent:()=>vs,OpenEvent:()=>bs,ErrorCode:()=>Ue,Event:()=>ot,MessageEvent:()=>_s});let i="";function a(s=""){let t=r,n="02",o=""+Date[t(1080)](),x=i||(i=e[t(867)](m,s)),l=Math[t(1325)]().toString(16)[t(258)](-6);return e.FRbVu(e[t(1151)](e[t(1151)](n,o),x),l)}function c(){let s=r;return e[s(1558)](e.nsYqv(1e4,Date.now()),Math[s(1026)](e[s(1236)](1e4,Math[s(1325)]())))}function u(s){let t=r;return e[t(1151)](e[t(709)](Array,8)[t(760)]("0"),parseInt(s,10)[t(187)](2)).slice(-8)}function d(s){let t=r;return e.FRbVu(e[t(1158)](Array,4).join("0"),e.gMddX(parseInt,s,2).toString(16))[t(258)](-4)}function h(s){let t=r;if(e[t(343)]!==e[t(1538)]){let n=s[t(1357)](/\./)[t(1494)](l=>u(l)),o=[];return o[0]=e.WPYoB(d,e[t(1511)](n[0],n[1])),o[1]=d(e[t(1100)](n[2],n[3])),[e[t(568)],e[t(568)],e[t(568)],t(1331),t(1331),t(1290),o[0],o[1]][t(760)]("")}else return _0x9432c0["objectSt"+t(204)]||_0x25bd17[t(935)](_0x5658b1)}function m(s){let t=r,n=/(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(1048)](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]))/.test(s);return n?h(s):o?w(s):"00000000"+t(267)+t(267)+"00000000"}function w(s){let t=r,n={plPWc:function(b,v){return e.tUfgP(b,v)},niZIb:e[t(693)]},o="",x=[],l=0,g=0,p=!0,f="0000";if(e.VHGqh(s[t(496)]("::"),-1)){let b=s[t(1357)]("::");for(let C=0;e[t(1599)](C,b[t(836)]);C++){let I=b[C];if(e[t(918)](I[t(496)](":"),0)){let O=I.split(":");p&&(l=O.length),g+=O[t(836)];for(let L=0;e[t(701)](L,O[t(836)]);L++)if(e[t(1363)](4,O[L][t(836)]))if(e[t(1134)](e[t(964)],e.QMscP)){let B=f[t(1603)+"g"](0,e.YKCmo(4,O[L][t(836)])),Q=B[t(1499)](O[L]);x[t(547)](Q)}else{let B=_0x21ffcb[t(1232)+t(672)](e[t(730)]);_0x40d8c1[t(506)+t(562)]=Q=>{let $=t;_0x349a1a[$(297)][$(1112)+$(975)](B),_0x1c19f9["frontier"+$(562)]=void 0,n.plPWc(_0x4db6ac,Q&&Q[$(359)]||n[$(252)])},B[t(317)]=e[t(260)],B.src=_0x5a6961[t(1399)](/^ws/,e[t(697)])+e[t(941)];try{_0x16e771.body[t(271)+t(975)](B)}catch{_0x10d54f[t(297)][t(1112)+"ild"](B)}}else x[t(547)](O[L]);p=!1}else{if(e[t(545)](4,I[t(836)]))if(e[t(545)](t(704),t(954))){let O=f[t(1603)+"g"](0,e[t(571)](4,I.length)),L=O[t(1499)](I);x.push(L)}else return this[t(480)+t(344)+t(1380)+"t"];else x[t(547)](I);p&&(l+=1),g+=1,p=!1}}let v="";for(let C=0;e.mrBPQ(C,e[t(378)](8,g));C++)v=v[t(1499)](f);for(let C=0;e[t(233)](C,x[t(836)]);C++)e[t(1134)](C,l)?(o=o.concat(v),o=o.concat(x[C])):o=o[t(1499)](x[C]);return o}{let b=s[t(1357)](":");for(let v=0;e[t(1039)](v,b.length);v++){let C=b[v];if(e[t(1363)](4,b[v][t(836)])){let I=f.substring(0,e[t(554)](4,b[v][t(836)])),O=I[t(1499)](C);o=o[t(1499)](O)}else o=o[t(1499)](C)}return o}}function _(s,t){let n=r,o=s.key;e[n(607)](void 0,o)&&(e[n(1482)](V,t,10),e[n(1482)](ve,t,o));let x=s.value;e.znLGG(void 0,x)&&(e[n(1482)](V,t,18),e[n(608)](ve,t,x))}function y(s){let t=r,n={};e:for(;!e[t(1050)](ke,s);){let o=e[t(1050)](H,s);switch(e[t(1081)](o,3)){case 0:break e;case 1:n[t(275)]=e.bCRLX(be,s,e[t(216)](H,s));break;case 2:n[t(1403)]=e[t(608)](be,s,e[t(289)](H,s));break;default:e[t(421)](oe,s,7&o)}}if(e[t(1134)](void 0,n[t(275)]))throw new Error(e[t(1606)]);if(e[t(1134)](void 0,n[t(1403)]))throw new Error(e.loSPn);return n}function A(s){let t=r,n=xe();return e[t(1574)](k,s,n),e[t(1546)](J,n)}function k(s,t){let n=r,o={BZrZM:function(l,g){return e.VleeX(l,g)},LtflP:n(830)+n(446)+"e",isOvN:function(l,g){return l>=g},ubLuP:function(l,g){return e[n(348)](l,g)},WOtXI:function(l,g,p,f){return e[n(856)](l,g,p,f)},DGnNn:function(l,g){return e[n(1558)](l,g)},wjbcu:function(l,g){return l+g}};if(n(1462)!==e.nxcat)this[n(476)]=!0,this[n(1054)]();else{let l=s.SeqID;if(e[n(454)](void 0,l))if(e[n(1143)]!==e.wadRW){if(o[n(994)](_0x5bee0c,_0x58db7f))throw new _0x3c63d9(o.LtflP);let $=3;for(;o.isOvN($,0);){let Ie=o[n(943)](255,_0x573375);o[n(502)](_0x1d4ae9,Ie,_0x4f782e,o.DGnNn(_0x19f8ad,$)),_0x1ca22a>>>=8,$--}return o[n(1448)](_0x5cf8cc,4)}else e[n(1476)](V,t,8),e[n(1482)](Ct,t,l);let g=s[n(196)];e[n(1036)](void 0,g)&&(e[n(1476)](V,t,16),e[n(608)](Ct,t,g));let p=s[n(255)];e.jptqS(void 0,p)&&(e[n(350)](V,t,24),e[n(1356)](Ct,t,e[n(1062)](te,p)));let f=s[n(915)];f!==void 0&&(V(t,32),e[n(622)](Ct,t,e[n(1546)](te,f)));let b=s[n(1457)];if(e[n(638)](void 0,b))for(let $ of b){e[n(1574)](V,t,42);let Ie=e.KgtCY(xe);_($,Ie),e[n(844)](V,t,Ie.limit),e.uBRlV(Yt,t,Ie),e[n(289)](P,Ie)}let v=s["payloadE"+n(859)];if(e[n(1036)](void 0,v))if(e[n(1602)](e[n(1608)],e[n(1608)]))V(t,50),e[n(421)](ve,t,v);else for(var x in _0x168721)VbOySU[n(502)](_0x1e0f73,_0x1036e5,x,{get:_0x5976b1[x],enumerable:!0});let C=s["payloadT"+n(1164)];e[n(545)](void 0,C)&&(V(t,58),ve(t,C));let I=s[n(1192)];if(I!==void 0){if(e[n(1214)](e.CDvJj,e[n(690)]))return this._socket[n(1528)+"ns"];e[n(1149)](V,t,66),V(t,I[n(836)]),e[n(1588)](Vt,t,I)}let O=s[n(581)];if(O!==void 0)if(e[n(1134)](e.gkhDh,e[n(529)]))e[n(194)](V,t,74),e.DHOJo(ve,t,O);else return new _0x29cfcd(_0x3149a0,{message:_0x1a39e3});let L=s[n(931)+n(1126)];e[n(869)](void 0,L)&&(e[n(1588)](V,t,82),ve(t,L));let B=s.msgID;if(e[n(1214)](void 0,B))if(e[n(649)](e[n(1237)],e[n(318)]))e[n(684)](V,t,90),ve(t,B);else{let $=new _0x373154(e[n(1236)](2,_0x4107d8));$[n(396)](_0xb343f2),_0x4fb73f[n(1585)]=$}let Q=s[n(519)+"e"];e[n(869)](void 0,Q)&&(e.dikJU(V,t,96),e[n(292)](Ct,t,e[n(330)](te,Q)))}}function T(s){let t=r;return e.tUfgP(R,e[t(1350)](F,s))}function R(s){let t=r,n={};e:for(;!ke(s);){let o=H(s);switch(e[t(1081)](o,3)){case 0:break e;case 1:n[t(1072)]=e[t(1476)](De,s,!0);break;case 2:n[t(196)]=e.lkxww(De,s,!0);break;case 3:n[t(255)]=H(s);break;case 4:n.method=e.McAft(H,s);break;case 5:{let x=e[t(1050)](q,s);(n.headers||(n.headers=[]))[t(547)](e[t(1062)](y,s)),s.limit=x;break}case 6:n[t(731)+"ncoding"]=e[t(471)](be,s,e[t(1062)](H,s));break;case 7:n["payloadT"+t(1164)]=e[t(1185)](be,s,H(s));break;case 8:n[t(1192)]=e.cFNPZ(Et,s,e[t(1158)](H,s));break;case 9:n[t(581)]=e[t(1618)](be,s,H(s));break;case 10:n[t(931)+t(1126)]=e[t(645)](be,s,e[t(1350)](H,s));break;case 11:n[t(1306)]=e[t(471)](be,s,e[t(1242)](H,s));break;case 12:n[t(519)+"e"]=e.NPoqF(H,s);break;default:oe(s,7&o)}}if(e[t(1602)](void 0,n.SeqID))throw new Error(e[t(1314)]);if(e.RJBHb(void 0,n.LogID))throw new Error("Missing "+t(238)+" field: "+t(196));if(e[t(1602)](void 0,n[t(255)]))throw new Error(e.rDsUi);if(n[t(915)]===void 0)throw new Error(e[t(1575)]);return n}function q(s){let t=r,n=e.CGRCj(H,s),o=s[t(1267)];return s[t(1267)]=s.offset+n,o}function oe(s,t){let n=r;switch(t){case 0:for(;e[n(670)](128,e[n(610)](ae,s)););break;case 2:e[n(292)](ne,s,H(s));break;case 5:e[n(1068)](ne,s,4);break;case 1:e[n(1618)](ne,s,8);break;default:throw new Error(e.JFCJQ+t)}}function te(s){let t=r;return s|=0,{low:s,high:e[t(298)](s,31),unsigned:s>=0}}let ye=[];function xe(){let s=r,t={gJuvd:e[s(720)],Sjbkq:function(n,o,x){return e.hjZQq(n,o,x)}};if(e[s(1179)](e.ElTqA,e.OgqYr))this[s(759)](t[s(1365)],t[s(1500)](_0x217a60,t[s(1365)],{message:this[s(702)+"rrorMess"+s(302)](_0x3cf098)}));else{let n=ye.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}}function P(s){let t=r;e[t(1041)](e.unSHn,e[t(691)])?(_0x1d5746&&_0x49a088[t(426)+t(1037)](WjnquI[t(1540)],()=>_0x37801b()),_0x16b6f8&&_0x159e21[t(426)+t(1037)](t(1311)+"hange",()=>_0x1d3e54())):ye[t(547)](s)}function F(s){return{bytes:s,offset:0,limit:s[r(836)]}}function J(s){let t=r,n=s.bytes,o=s[t(1267)];return e[t(1002)](n[t(836)],o)?n:n[t(500)](0,o)}function ne(s,t){let n=r;if(e.yxSoK(e[n(1443)](s[n(1044)],t),s.limit))throw new Error(e.fXHRM);s.offset+=t}function ke(s){let t=r;return s[t(1044)]>=s[t(1267)]}function pe(s,t){let n=r,o=s[n(1585)],x=s[n(1044)],l=s[n(1267)],g=e[n(1021)](x,t);if(g>o[n(836)]){let p=new Uint8Array(2*g);p[n(396)](o),s.bytes=p}return s[n(1044)]=g,g>l&&(s.limit=g),x}function $e(s,t){let n=r,o={ZPXgB:e[n(720)],vdNuy:function(x,l,g){return e[n(684)](x,l,g)},ruaqj:function(x,l){return x+l}};if(e.AKcgf(n(444),e[n(1183)])){let x=s[n(1044)];if(e[n(1021)](x,t)>s[n(1267)])throw new Error("Read pas"+n(266));return s[n(1044)]+=t,x}else{let x={PyWIf:o.ZPXgB,slbCU:function(g,p,f){return o.vdNuy(g,p,f)}},l=_0x12191c[n(1071)][n(258)](_0x28567b[n(1163)+"et"],o[n(936)](_0x5899dc[n(762)+"th"],_0x1a0d50[n(1163)+"et"]));this[n(1034)]&&this[n(1034)][n(537)]({data:l,fail:g=>{let p=n;this.emit(x.PyWIf,x.slbCU(_0x3148e0,x[p(1593)],{message:this["_formatE"+p(721)+p(302)](g)}))}})}}function Et(s,t){let n=r,o={euWAx:function(x){return e[D(364)](x)}};if(e[n(1172)](e[n(1413)],e[n(1413)])){let x=$e(s,t);return s[n(1585)][n(500)](x,e[n(1151)](x,t))}else this[n(476)]=!1,_0x16a899(this[n(1054)+n(793)+n(1543)]),o.euWAx(_0x1c118e)}function Vt(s,t){let n=r,o=e.YZLzs(pe,s,t[n(836)]);s[n(1585)][n(396)](t,o)}function be(s,t){let n=r,o={PZRuu:function(b,v){return e.CGRCj(b,v)}},x=e.IcejH($e,s,t),l=String["fromChar"+n(887)],g=s[n(1585)],p="\uFFFD",f="";for(let b=0;e[n(384)](b,t);b++){let v=g[b+x],C,I,O,L;if(e[n(737)](128&v,0))f+=l(v);else if(e.cWczc(e[n(1477)](224,v),192))e[n(1443)](b,1)>=t?f+=p:(C=g[e[n(1511)](b+x,1)],e[n(869)](e[n(1153)](192,C),128)?f+=p:(L=e[n(242)](e.leNWC(31,v),6)|e[n(670)](63,C),e[n(1015)](L,128)?f+=p:(f+=e.LoDtN(l,L),b++)));else if(e[n(1348)](240&v,224))if(e[n(1558)](b,2)>=t)f+=p;else if(e.iZbcz(e[n(1291)],e[n(1351)]))if(C=g[e[n(478)](e[n(1151)](b,x),1)],I=g[b+x+2],e[n(1601)](e.leNWC(C|e.crJGD(I,8),49344),32896))f+=p;else if(L=e.ySTXw((15&v)<<12,e[n(225)](e[n(670)](63,C),6))|e.VarDx(63,I),e[n(1586)](L,2048)||e[n(817)](L,55296)&&e[n(653)](L,57343))f+=p;else if(e[n(1421)](e[n(1186)],e.RjirG)){let B=new _0xa44acd(o.PZRuu(_0x30d343,_0x15df65));return _0x2aa328(_0x51b189,B,0),B}else f+=e[n(1370)](l,L),b+=2;else{if(e[n(518)](void 0,_0x83c1c0))this[n(479)+"rs"]={};else if(_0x1af374===void 0)this._listeners[_0x32b127]=null;else{let B=this._listeners[_0x5e182f];if(B)for(let Q=0;e[n(1586)](Q,B[n(836)]);)B[Q].fn===_0x5cd812?B[n(1375)](Q,1):++Q}return this}else e.VarDx(248,v)==240?e[n(1021)](b,3)>=t?f+=p:(C=g[e[n(1541)](e[n(1539)](b,x),1)],I=g[e[n(1140)](e[n(736)](b,x),2)],O=g[e[n(299)](b,x)+3],(e[n(707)](e[n(1135)](C,e[n(1318)](I,8)),O<<16)&12632256)!==8421504?f+=p:(L=e[n(312)](e[n(707)](e[n(225)](e[n(512)](7,v),18),e.leNWC(63,C)<<12)|e[n(1303)](e[n(1219)](63,I),6),e[n(593)](63,O)),e[n(559)](L,65536)||e.yxSoK(L,1114111)?f+=p:(L-=65536,f+=e[n(1565)](l,e[n(1021)](e.uMiIL(L,10),55296),(1023&L)+56320),b+=3))):f+=p}return f}function ve(s,t){let n=r,o=t.length,x=0;for(let p=0;e.mdTDf(p,o);p++){let f=t[n(1227)+"At"](p);e[n(279)](f,55296)&&e[n(695)](f,56319)&&e[n(1586)](e[n(1539)](p,1),o)&&(f=e[n(1006)](e[n(1511)](e[n(242)](f,10),t.charCodeAt(++p)),56613888)),x+=e[n(384)](f,128)?1:e[n(803)](f,2048)?2:e[n(384)](f,65536)?3:4}V(s,x);let l=e.sCtRC(pe,s,x),g=s[n(1585)];for(let p=0;e[n(1101)](p,o);p++){let f=t[n(1227)+"At"](p);if(e[n(1147)](f,55296)&&f<=56319&&e[n(1599)](p+1,o)&&(f=e.cQfow(e[n(404)](f<<10,t.charCodeAt(++p)),56613888)),e[n(290)](f,128))g[l++]=f;else{if(e[n(803)](f,2048))g[l++]=e[n(1477)](e[n(687)](f,6),31)|192;else{if(f<65536)g[l++]=e.RULqK(e[n(753)](f>>12,15),224);else{if(e[n(587)]("JOAVl",e.fIxaT))return(this._listeners[_0x2eb1e7]||(this._listeners[_0x11767d]=[]))[n(547)]({fn:_0x4d6fd1,ctx:_0x413bb6||this}),this;g[l++]=e.IjiTq(e[n(401)](e[n(687)](f,18),7),240),g[l++]=e[n(394)](e[n(644)](f>>12,63),128)}g[l++]=e[n(673)](f>>6&63,128)}g[l++]=e.bQhiy(e.leNWC(63,f),128)}}}function Yt(s,t){let n=r,o=e[n(698)](pe,s,t.limit),x=s[n(1585)],l=t[n(1585)];for(let g=0,p=t[n(1267)];e[n(1117)](g,p);g++)x[g+o]=l[g]}function ae(s){return s[r(1585)][e.YZLzs($e,s,1)]}function $t(s,t){let n=r;if(e[n(1602)](e.NKwUJ,n(202))){let o=pe(s,1);s[n(1585)][o]=t}else return _0x54bad2[n(367)+"8"]?{value:_0x4a1383[n(367)+"8"](_0x103b46),offset:e[n(619)](_0x15cbf3,1)}:{value:e[n(348)](255,_0x359a41[_0x5c583e]),offset:_0x10586b+1}}function H(s){let t=r,n=0,o=0,x;do x=ae(s),e[t(417)](n,32)&&(o|=e[t(593)](127,x)<<n),n+=7;while(128&x);return o}function V(s,t){let n=r;for(t>>>=0;t>=128;)e.cFNPZ($t,s,e[n(1135)](e[n(401)](127,t),128)),t>>>=7;e[n(1618)]($t,s,t)}function De(s,t){let n=r,o={FnkQJ:function(x,l,g){return e[D(639)](x,l,g)},haeoV:e.onPnX,JRSAa:function(x,l){return e[D(700)](x,l)},cQFAw:function(x,l){return e.bXFiG(x,l)},ImPNP:function(x,l){return e[D(1613)](x,l)},SgBDz:function(x,l){return e.ZqiIR(x,l)},PJopA:function(x,l){return e[D(232)](x,l)},MVvfK:function(x,l){return x||l},QdGnV:function(x,l){return x>>>l}};if(e.RJBHb(e.UTAim,e[n(475)]))this[n(203)+n(938)+n(533)]=_0x4cdec2,_0x3a81b7?this["_handleO"+n(370)]():this[n(536)+n(974)]();else{let x=0,l=0,g=0,p;if(p=ae(s),x=e[n(262)](127,p),128&p&&(p=e[n(1050)](ae,s),x|=e[n(855)](e[n(1477)](127,p),7),e[n(310)](128,p)&&(p=e[n(1158)](ae,s),x|=e[n(278)](e[n(1477)](127,p),14),128&p&&(p=e[n(1342)](ae,s),x|=e.bgrrf(e[n(248)](127,p),21),128&p&&(p=e[n(1546)](ae,s),l=127&p,e[n(512)](128,p)))))){if(e[n(1363)](e[n(851)],e[n(851)])){let f=this[n(1296)][n(1225)+n(796)+"ptor"](_0x26f1ed,_0x2dd72a);this[n(1138)+n(1284)+n(1346)](o[n(614)](_0x22eeb9,o[n(237)],{code:_0xef637b,reason:_0x5a2642,wasClean:!0,willReconnect:f})),f&&this._connect()}else if(p=e.uSGYP(ae,s),l|=e[n(878)](e.hwSVs(127,p),7),128&p)if(n(1358)===e.opTAV)p=e[n(879)](ae,s),l|=e[n(855)](e[n(512)](127,p),14),e[n(497)](128,p)&&(p=e[n(313)](ae,s),l|=e[n(1531)](e[n(663)](127,p),21),128&p&&(p=e[n(313)](ae,s),g=e[n(593)](127,p),128&p&&(p=ae(s),g|=e[n(1049)](e.CnDbA(127,p),7))));else{let f=o[n(1207)](_0x42756e,8192),b=o[n(837)](f,1),v=null,C=f;return function(I){let O=n;if(o[O(1446)](I,1)||I>b)return _0x3ac57f(I);o[O(872)](o.ImPNP(C,I),f)&&(v=o.SgBDz(_0x564687,f),C=0);let L=_0x1e10a1[O(812)](v,C,C+=I);return 7&C&&(C=o[O(958)](o.PJopA(7,C),1)),L}}}return{low:x|e.KHNwX(l,28),high:e[n(1553)](e[n(524)](l,4),g<<24),unsigned:t}}}function Ct(s,t){let n=r,o=e[n(1137)](t[n(1239)],0),x=(t[n(1239)]>>>28|e[n(831)](t[n(1028)],4))>>>0,l=e.JqRZu(t[n(1028)],24),g=e[n(873)](0,l)?x===0?e[n(559)](o,16384)?o<128?1:2:e[n(417)](o,2097152)?3:4:e.dzOWn(x,16384)?e.PdjEn(x,128)?5:6:e.mrBPQ(x,2097152)?7:8:e[n(803)](l,128)?9:10,p=e[n(1442)](pe,s,g),f=s[n(1585)];switch(g){case 10:f[e[n(427)](p,9)]=e.VarDx(e[n(664)](l,7),1);case 9:f[e[n(1443)](p,8)]=g!==9?e[n(832)](128,l):e[n(213)](127,l);case 8:f[e[n(659)](p,7)]=e[n(649)](8,g)?x>>>21|128:e[n(348)](x>>>21,127);case 7:f[e.uYmch(p,6)]=e[n(218)](7,g)?e[n(707)](e[n(1137)](x,14),128):e[n(497)](e[n(1081)](x,14),127);case 6:f[p+5]=e[n(638)](6,g)?e[n(412)](e[n(1003)](x,7),128):e[n(590)](x,7)&127;case 5:f[e[n(299)](p,4)]=e[n(649)](5,g)?e[n(940)](128,x):127&x;case 4:f[e[n(1151)](p,3)]=e.ljrUx(4,g)?e.xESbF(o>>>21,128):o>>>21&127;case 3:f[e[n(736)](p,2)]=g!==3?e[n(1576)](o>>>14,128):e.mZEBV(e[n(1433)](o,14),127);case 2:f[p+1]=e[n(869)](2,g)?e[n(389)](e[n(1312)](o,7),128):e[n(1323)](e.oPQOU(o,7),127);case 1:f[p]=e[n(987)](1,g)?e.BMiQv(128,o):e[n(1219)](127,o)}}function ds(s){return e.CGRCj(T,s)}function ar(s){let t=r,n={vhQMD:function(o,x){return o(x)},OLWzU:function(o,x){return e[D(659)](o,x)}};if(e[t(498)](e[t(1431)],e[t(862)])){let o=nBbWdd.vhQMD(_0x5c63ce,_0x2d76eb),x=_0x1713fa[t(1267)];return _0xb0317a[t(1267)]=nBbWdd[t(432)](_0xb8e439[t(1044)],o),x}else return e.toEAP(A,s)}let fs=65536,fa=e[r(296)],it=e.nsYqv(fs,fs),ls=e[r(1145)](it,it),hs=e[r(681)](ls,2),Fe=String.prototype.charCodeAt;class z{constructor(t,n,o){let x=r;this[x(1467)]=!0,this[x(1239)]=e[x(232)](0,t),this.high=e[x(832)](0,n),this[x(857)]=!!o}static[r(1467)](t){return t&&t[r(1467)]===!0}static[r(599)](t,n,o){return new z(t,n,o)}static[r(870)+"s"](t,n,o){return o?z["fromByte"+r(1035)](t,n):z.fromBytesBE(t,n)}static[r(870)+"sLE"](t,n){let o=r;return new z(e.bQhiy(e[o(1576)](e[o(232)](t[0],e[o(1416)](t[1],8)),e[o(875)](t[2],16)),e[o(855)](t[3],24)),e[o(232)](t[4]|e[o(1303)](t[5],8)|t[6]<<16,e[o(1531)](t[7],24)),n)}static["fromByte"+r(1486)](t,n){let o=r;return new z(e[o(1553)](e.XqYQB(e[o(1085)](t[4]<<24,t[5]<<16),t[6]<<8),t[7]),e[o(840)](e.pKxCQ(e[o(1169)](e[o(1318)](t[0],24),e[o(1531)](t[1],16)),t[2]<<8),t[3]),n)}static fromHash(t){let n=r;return e[n(1602)](t,fa)?gs:new z(e[n(510)](e[n(226)](e[n(312)](Fe[n(812)](t,0),e[n(278)](Fe[n(812)](t,1),8)),e[n(831)](Fe[n(812)](t,2),16))|Fe[n(812)](t,3)<<24,0),e[n(664)](e.PHVcj(e.IjiTq(Fe[n(812)](t,4),e[n(878)](Fe.call(t,5),8))|e.TIqoC(Fe[n(812)](t,6),16),e[n(1056)](Fe[n(812)](t,7),24)),0),!0)}[r(744)](){let t=r;return String[t(1385)+t(887)](e[t(670)](255,this[t(1239)]),this[t(1239)]>>>8&255,e[t(664)](this.low,16)&255,e[t(221)](this[t(1239)],24),e[t(644)](255,this.high),e[t(1137)](this[t(1028)],8)&255,e[t(644)](this[t(1028)]>>>16,255),this[t(1028)]>>>24)}static[r(1252)+"er"](t,n=!0){let o=r;if(e[o(551)](isNaN,t))return n?la:gs;if(n){if(e[o(1234)](t,ls))return ga}else{if(e[o(1202)](t,-hs))return pa;if(t+1>=hs)return ha}return z[o(599)](e[o(1576)](e.TggTB(t,it),0),e[o(1110)](e[o(681)](t,it),0),n)}[r(1406)](){let t=r;return this.unsigned?e[t(1613)](e[t(1236)](e[t(1480)](this[t(1028)],0),it),e[t(1233)](this[t(1239)],0)):e.Fvbsu(this[t(1028)]*it,e.pyvVH(this[t(1239)],0))}[r(1320)](){let t=r;return e[t(219)](0,this[t(1028)])&&this.low===0}[r(997)](t){let n=r;z[n(1467)](t)||(t=z.fromNumber(t));let o=e[n(1081)](this[n(1028)],16),x=e[n(560)](65535,this[n(1028)]),l=e.lMksL(this.low,16),g=65535&this[n(1239)],p=t.high>>>16,f=e[n(670)](65535,t[n(1028)]),b=e[n(1433)](t.low,16),v=e[n(735)](65535,t[n(1239)]),C=0,I=0,O=0,L=0;return L+=e[n(299)](g,v),O+=e[n(524)](L,16),L&=65535,O+=l+b,I+=e[n(1495)](O,16),O&=65535,I+=x+f,C+=e[n(664)](I,16),I&=65535,C+=o+p,C&=65535,z[n(599)](e[n(226)](e[n(788)](O,16),L),e[n(1553)](C<<16,I),this[n(857)])}[r(1167)](t){let n=r;return z.isLong(t)||(t=z[n(1252)+"er"](t)),e.roYnA(this[n(857)],t.unsigned)&&e[n(1137)](this.high,31)===1&&e[n(569)](e[n(1210)](t.high,31),1)?!1:this.high===t[n(1028)]&&e.PwRKq(this.low,t[n(1239)])}[r(754)](){let t=r;return e[t(988)](-1,this.low)&&this[t(1028)]===-1?z[t(599)](0,0,this[t(857)]):this[t(1239)]===-1?z.fromBits(0,e[t(478)](this[t(1028)],1),this[t(857)]):z[t(599)](e[t(619)](this.low,1),this[t(1028)],this[t(857)])}toBytes(t){return t?this.toBytesLE():this[r(1030)+"E"]()}[r(439)+"E"](){let t=r,n=this[t(1028)],o=this[t(1239)];return[e[t(1323)](255,o),e[t(383)](e[t(718)](o,8),255),e[t(512)](e[t(664)](o,16),255),e.vPfER(o,24),255&n,e.esPsm(n>>>8,255),e[t(932)](e[t(1081)](n,16),255),e[t(1447)](n,24)]}[r(1030)+"E"](){let t=r;if(e[t(750)](t(1407),e[t(864)]))this.on(_0x189863,_0x1166c1);else{let n=this[t(1028)],o=this[t(1239)];return[n>>>24,e[t(310)](e[t(590)](n,16),255),e[t(956)](e[t(729)](n,8),255),255&n,e.uLvkJ(o,24),e[t(753)](o>>>16,255),e[t(1480)](o,8)&255,e[t(1156)](255,o)]}}}let gs=new z(0,0,!1),la=new z(0,0,!0),ha=z[r(599)](-1,2147483647,!1),ga=z[r(599)](-1,-1,!0),pa=z[r(599)](0,-2147483648,!1);var Ue=(function(s){let t=r,n=e[t(1615)][t(1357)]("|"),o=0;for(;;){switch(n[o++]){case"0":s[s[e[t(1445)]]=5005]=e[t(1445)];continue;case"1":s[s[e[t(1595)]]=5001]=e[t(1595)];continue;case"2":return s;case"3":s[s[e[t(1390)]]=5003]=e[t(1390)];continue;case"4":s[s[e[t(824)]]=5002]=e[t(824)];continue;case"5":s[s[e[t(854)]]=5004]=e.SfZjk;continue}break}})({});class ot{constructor(t){let n=r;e[n(1136)]!==e[n(1136)]?(_0x41c46c(_0x37f002,50),_0x5021a2(_0x3a3a74,_0x13a220)):(this[n(317)]=t,this[n(304)]=null)}}class ps extends ot{constructor(t,n){let o=r;super(t),this[o(965)]=n&&n.message||null}}class ms extends ot{constructor(t,n){let o=r,x=(o(415)+o(1376)).split("|"),l=0;for(;;){switch(x[l++]){case"0":this[o(1127)]=n&&n.error||null;continue;case"1":this[o(849)]=n&&n.filename||"";continue;case"2":this.colno=n&&n[o(319)]||0;continue;case"3":this[o(634)]=n&&n[o(634)]||5001;continue;case"4":super(t);continue;case"5":this[o(965)]=n&&n.message||"";continue;case"6":this[o(1109)]=n&&n[o(1109)]||0;continue}break}}}class ws extends ot{constructor(t,n){let o=r,x=e[o(1194)][o(1357)]("|"),l=0;for(;;){switch(x[l++]){case"0":this.code=n&&n[o(634)]||0;continue;case"1":this[o(743)]=n&&n[o(743)]||"";continue;case"2":this[o(774)]=n&&n.wasClean||!1;continue;case"3":this[o(909)+"nnect"]=n&&n[o(909)+o(458)]||!1;continue;case"4":super(t);continue}break}}}class _s extends ot{constructor(t,n){let o=r;super(t),this[o(1355)]=n&&n[o(1355)]||null}}class ys extends _s{constructor(t,n){let o=r;super(t),this[o(1355)]=n&&n[o(1355)]||null,this.message=n&&n[o(965)]||null}}class bs extends ot{constructor(t,n){let o=r;super(t),this[o(1355)]=n&&n.data||null}}function le(s,{message:t,code:n,error:o}){return new ms(s,{message:t,code:n,error:o})}function me(s,{code:t,reason:n,wasClean:o,willReconnect:x}){return new ws(s,{code:t,reason:n,wasClean:o,willReconnect:x})}function vs(s,{data:t,message:n}){return new ys(s,{data:t,message:n})}function Ss(s,{data:t}){return new bs(s,{data:t})}function cr(s,{message:t}){return new ps(s,{message:t})}class Es{constructor(t,n){let o=r;e[o(1064)](e[o(1360)],e[o(1188)])?this[o(253)](_0x290f3a,_0x1c1004):(this[o(507)+"s"]=t,this.maxRetries=n,this["currentI"+o(429)]=0,this[o(480)+o(344)+o(1380)+"t"]=0)}["resetEnd"+r(1095)+"fig"](){let t=r;if(e.ljrUx(e[t(805)],t(1605)))this[t(337)+t(429)]=0,this[t(480)+"ndpointT"+t(1380)+"t"]=0;else{let n=e[t(882)].split("|"),o=0;for(;;){switch(n[o++]){case"0":this._isInit=!0;continue;case"1":this[t(868)+t(734)]?.[t(1069)+t(1341)]();continue;case"2":this["_endpoin"+t(714)]?.[t(1384)+t(1095)+"fig"]();continue;case"3":this[t(1054)]();continue;case"4":this._readyClosed=!1;continue}break}}}[r(612)+"es"](){let t=r;this[t(480)+t(344)+t(1380)+"t"]=0}[r(657)+r(511)+"nt"](){return this[r(507)+"s"][this.currentIndex]}["getCurre"+r(511)+r(632)+r(1310)](){let t=r;return this[t(480)+t(344)+t(1380)+"t"]}[r(1279)+"chMaxTries"](){let t=r;return!!(e[t(817)](this[t(337)+t(429)],this[t(507)+"s"][t(836)])||this[t(337)+t(429)]===e[t(346)](this.endpoints[t(836)],1)&&e[t(988)](this["currentE"+t(344)+t(1380)+"t"],this[t(1617)+"es"]))}[r(1381)+r(898)+r(1211)+r(487)+r(694)](){let t=r;return this[t(337)+t(429)]==this.endpoints[t(836)]?!0:e[t(585)](this[t(480)+"ndpointTriesCount"],this[t(1617)+"es"])}[r(897)+r(366)+r(387)+r(229)+r(1313)](){let t=r;return this["currentE"+t(344)+t(1380)+"t"]=1,this[t(337)+t(429)]++,this.endpoints[this["currentI"+t(429)]]}["getCurrentEndpointAndUpd"+r(368)](){let t=r;if(e[t(338)](e[t(1461)],e[t(1461)]))return this["currentE"+t(344)+"riesCount"]++,this[t(657)+"ntEndpoint"]();if(WjnquI[t(1602)](_0x6be0c9,WjnquI[t(1171)]))return _0x4c983a[t(935)](_0x288c1d);if(WjnquI[t(969)](_0x122bac,WjnquI.LHpab))return _0x546a9b[t(1292)+t(204)]||_0x5f0445.get(_0x448273);if(WjnquI[t(750)](_0x365217,t(1583)))return _0x55a3a8[t(1292)+t(204)][1]?void 0:_0x5772f1[t(1292)+t(345)](_0x2b6908[t(1292)+t(204)][0])}}let at=(e[r(675)]("undefined",typeof globalThis)&&e[r(750)](e[r(527)],globalThis.constructor[r(919)])||e[r(1487)]!=typeof window&&e[r(906)](e.YBKUP,window[r(1389)+r(674)][r(919)]))&&e[r(1515)](r(441)+"d",typeof document),Xe=e.gEAxi!=typeof globalThis&&(e[r(1287)]===globalThis[r(1389)+r(674)][r(919)]||e.idLvF===globalThis[r(1389)+r(674)][r(919)])&&e[r(1487)]!=typeof tt,At=(e[r(799)](e[r(1487)],typeof globalThis)&&e.KswYE===globalThis["construc"+r(674)][r(919)]||r(441)+"d"==typeof globalThis||e.YGSsM(e.gEAxi,typeof globalThis)&&!!globalThis[r(979)+r(1144)])&&e.grgbz(r(441)+"d",typeof wx),Pt=e[r(688)](e[r(1487)],typeof globalThis)&&(e[r(601)](e[r(1157)],globalThis[r(1389)+r(674)][r(919)])||e.MwAJi(r(1430)+"rkerGlob"+r(1493),globalThis[r(1389)+r(674)].name)||e[r(1591)]===globalThis[r(1389)+r(674)][r(919)])&&e[r(1401)]("undefined",typeof self),ma=e[r(992)](e.gEAxi,typeof globalThis)&&e.ITwwy(e[r(1287)],globalThis[r(1389)+r(674)][r(919)])&&e[r(1487)]!=typeof global&&e[r(665)](e[r(1287)],global["construc"+r(674)][r(919)])&&e[r(1487)]!=typeof process&&!!process[r(1221)];class xr{constructor(){this._listeners={}}[r(759)](t,...n){let o=r,x=this[o(479)+"rs"][t];if(x)x[o(258)]().forEach(l=>l.fn.apply(l[o(1159)],n));else if(e.xdmpf===t&&!this[o(1018)]){let l=n[o(836)]&&n[0];if(e[o(1432)](l,Error))throw l;let g=new Error(e[o(986)](e[o(982)],l?e.vGPKY(e[o(1539)](" (",l[o(965)]),")"):""));throw g[o(534)]=l,l}return this}off(t,n){let o=r;if(t===void 0)this._listeners={};else if(e[o(219)](void 0,n))this._listeners[t]=null;else{let x=this[o(479)+"rs"][t];if(x)for(let l=0;e.AEUtH(l,x[o(836)]);)e.iIWvI(x[l].fn,n)?x.splice(l,1):++l}return this}on(t,n,o){let x=r;return(this._listeners[t]||(this[x(479)+"rs"][t]=[])).push({fn:n,ctx:o||this}),this}}class wa extends xr{[r(702)+r(721)+r(302)](t){let n=r;return t[n(291)]||t[n(1096)]?("message: "+(t[n(291)]||"")+n(1254)+(t.errNo||""))[n(192)]():JSON[n(816)+"y"](t)}constructor(t,n,o){let x=r;super(),this._socket=null,At&&wx.connectSocket&&(this._socket=wx[x(1197)+x(566)]({url:t,protocols:n,header:o,fail:this[x(618)+x(1177)+"lHandler"][x(1408)](this),success:this[x(618)+x(259)+"cessHandler"][x(1408)](this)})),Xe&&tt[x(1197)+x(566)]&&(this[x(1034)]=tt[x(1197)+x(566)]({url:t,protocols:n,header:o,fail:this[x(618)+x(1177)+"lHandler"][x(1408)](this),success:this["_createS"+x(259)+x(1220)+"ler"][x(1408)](this)}))}[r(618)+"ocketSuc"+r(1220)+r(1578)](){let t=r;Promise[t(1020)]()[t(1556)](()=>{let n=t;this[n(247)+n(501)]()})}["_createSocketFai"+r(227)](t){let n=r;Promise[n(1020)]()[n(1556)](()=>{let o=n,x=e[o(239)](le,e[o(720)],{message:this[o(702)+o(721)+"age"](t)});this.emit(e[o(720)],x);let l=e[o(934)](me,"close",{reason:this[o(702)+o(721)+o(302)](t)});this[o(759)](o(1223),l)})}[r(247)+r(501)](){let t=r;this[t(1034)].onOpen(n=>{let o=t;this[o(759)](e[o(1058)],e[o(481)](Ss,o(1259),{...n,data:n.errMsg||""}))}),this._socket[t(682)](n=>{let o=t;this[o(759)](e[o(1540)],e[o(608)](me,e[o(1540)],{...n}))}),this._socket[t(839)+"e"](n=>{let o=t;this[o(759)](e.NEjiL,e[o(1565)](vs,e[o(990)],{...n}))}),this._socket.onError(n=>{let o=t;this[o(759)](e[o(720)],le(e.xdmpf,{...n,message:n[o(291)]||""}))})}[r(537)](t){let n=r,o={FEINR:function(x,l){return x==l},ESyfD:function(x,l){return e[D(408)](x,l)}};if(e[n(1607)](e[n(1086)],"AKMUu"))if(e[n(775)](t,Uint8Array)){let x=t[n(1071)][n(258)](t[n(1163)+"et"],e[n(619)](t.byteLength,t[n(1163)+"et"]));this[n(1034)]&&this[n(1034)][n(537)]({data:x,fail:l=>{let g=n;if(e[g(1168)](e[g(838)],e[g(838)]))return _0x470ef6[g(291)]||_0x5a29fa[g(1096)]?(g(1598)+" "+(_0x4414eb[g(291)]||"")+g(1254)+(_0xa6efed[g(1096)]||"")).trim():_0x119885.stringify(_0x305a39);this[g(759)](e[g(720)],e[g(608)](le,e[g(720)],{message:this[g(702)+"rrorMess"+g(302)](l)}))}})}else this[n(1034)]&&this._socket.send({data:t,fail:x=>{let l=n;e[l(963)](e.aMpVX,e[l(797)])?this.on(_0x3194d8,_0x4cbc46):this.emit(l(1127),e[l(1285)](le,e[l(720)],{message:this[l(702)+l(721)+l(302)](x)}))}});else return iiPNMi[n(1078)](this["currentI"+n(429)],this[n(507)+"s"][n(836)])?!0:iiPNMi.ESyfD(this[n(480)+n(344)+n(1380)+"t"],this[n(1617)+"es"])}[r(1223)](t,n){let o=r;this[o(1034)]&&this[o(1034)][o(1223)]({code:t,reason:n})}[r(426)+"Listener"](t,n){this.on(t,n)}["removeEventListe"+r(893)](t,n){let o=r;if(e[o(518)](e[o(847)],e.gcMoG))this[o(253)](t,n);else return{frameType:_0x5909be,headers:[{key:e.GaNpk,value:e[o(784)]}],payload:void 0}}get[r(272)+"te"](){return this[r(1034)].readyState}get[r(809)+"pe"](){let t=r;return this[t(1034)][t(809)+"pe"]}set[r(809)+"pe"](t){}get url(){return this[r(1034)].url}get[r(420)](){let t=r;return this._socket[t(420)]}get[r(1528)+"ns"](){let t=r;return this[t(1034)][t(1528)+"ns"]}get[r(801)+r(1410)](){return 0}}function _a(s,t){let n=r;if(t)return new t(s[n(188)],s[n(420)]);if(e[n(1535)](At,Xe))return new wa(s[n(188)],s[n(420)],s[n(1457)]);if(e[n(1535)](at,Pt)&&e[n(1487)]!=typeof WebSocket&&WebSocket)return new WebSocket(s.url,s[n(420)+"s"])}function ya(s){let t=r,n=e[t(733)].split("|"),o=0;for(;;){switch(n[o++]){case"0":if(At&&wx[t(1197)+t(566)])return!0;continue;case"1":if(s)return!0;continue;case"2":if(Xe&&tt[t(1197)+t(566)])return!0;continue;case"3":if(e[t(923)](at,Pt)&&e.YabXI(e.gEAxi,typeof WebSocket)&&WebSocket)return!0;continue;case"4":return!1}break}}function Cs(s,t,n){let o=-1;async function x(l){let g=D;return e[g(705)](l,o)?Promise[g(516)](new Error(e[g(617)])):(o=l,l===n[g(836)]?Promise[g(1020)]():n[l].bind(s)(t,x[g(1408)](null,e.WFere(l,1))))}e.CGRCj(x,0)}function As(s){let t=r,n=0,o=0;for(let x=0;e[t(825)](x,s[t(836)]);++x)o=s[t(1227)+"At"](x),e[t(668)](o,128)?n+=1:o<2048?n+=2:e.GeIIw(e[t(1162)](64512,o),55296)&&e[t(1002)](e[t(1070)](64512,s[t(1227)+"At"](x+1)),56320)?(++x,n+=4):n+=3;return n}function Ps(s,t,n){let o=r;if(e[o(1006)](n,t)<1)return"";let x="";for(let l=t;e[o(1557)](l,n);){let g=s[l++];if(g<=127)x+=String[o(1385)+o(887)](g);else if(e[o(947)](g,192)&&e[o(335)](g,224))x+=String[o(1385)+o(887)](e[o(746)](e[o(788)](31&g,6),e.esPsm(63,s[l++])));else if(e[o(1052)](g,224)&&e[o(335)](g,240))x+=String[o(1385)+o(887)](e[o(871)](e.OijsM(e[o(1156)](15,g)<<12,e[o(348)](63,s[l++])<<6),e[o(1253)](63,s[l++])));else if(g>=240){let p=e[o(378)](e[o(495)](e[o(871)](e.rLHpi(e[o(334)](7,g),18)|e[o(831)](e[o(956)](63,s[l++]),12),e[o(1049)](e[o(821)](63,s[l++]),6)),e[o(1477)](63,s[l++])),65536);x+=String[o(1385)+o(887)](e.SrFmX(55296,e[o(687)](p,10))),x+=String[o(1385)+o(887)](e.MhGNu(56320,e[o(654)](1023,p)))}}return x}function ur(s,t,n){let o=r,x={uaTaB:e[o(1529)]};if(e.yDCcw(e[o(998)],o(347)))this[o(951)]&&this[o(951)][o(537)](_0x1a67dd),this[o(206)](x.uaTaB,_0x253473);else{let l=n,g,p;for(let f=0;e[o(1101)](f,s.length);++f)if(g=s[o(1227)+"At"](f),e[o(701)](g,128))t[n++]=g;else if(e[o(668)](g,2048))t[n++]=e[o(746)](e[o(564)](g,6),192),t[n++]=e[o(970)](63&g,128);else if(e[o(942)](e[o(1219)](64512,g),55296)&&e[o(1566)](64512&(p=s[o(1227)+"At"](f+1)),56320))if(e[o(782)](e[o(515)],e[o(552)])){let b=e.suFJk[o(1357)]("|"),v=0;for(;;){switch(b[v++]){case"0":++f;continue;case"1":t[n++]=e[o(1085)](g>>18,240);continue;case"2":t[n++]=e.hRmOO(e[o(564)](g,12),63)|128;continue;case"3":t[n++]=e[o(1169)](e[o(1377)](e.yBDnF(g,6),63),128);continue;case"4":t[n++]=e[o(1542)](63&g,128);continue;case"5":g=e.LbkvR(e.sHCUG(65536,e[o(278)](e[o(1377)](1023,g),10)),e[o(357)](1023,p));continue}break}}else return e.grgbz(o(751),typeof _0x1691b5)&&(_0x5b037d instanceof _0x2644e4||_0x4f113f.buffer&&e[o(775)](_0x237106[o(1071)],_0x1b9d5e))||e[o(1515)](e[o(541)],typeof _0x5f3c34)?"":(_0x22c6e9[o(1512)](_0x2082ea),e[o(655)]);else t[n++]=e[o(1169)](g>>12,224),t[n++]=e[o(320)](e.AXxEl(g>>6,63),128),t[n++]=e[o(1161)](63,g)|128;return n-l}}async function ks(s){let t=r;if(e.CCmWI==typeof s){let n=new Uint8Array(e.ZqiIR(As,s));return e[t(452)](ur,s,n,0),n}return s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s[t(1071)],s.byteOffset,s[t(762)+"th"])}function ba(s){let t=r;try{return e[t(435)](t(751),typeof s)&&(e.oZFIg(s,ArrayBuffer)||s[t(1071)]&&e[t(883)](s[t(1071)],ArrayBuffer))||e[t(992)](e.CCmWI,typeof s)?"":(JSON[t(1512)](s),e[t(655)])}catch{return e[t(541)]==typeof s?e.KVMhm:""}}let va=(s,t)=>{let n=r;switch(s){case e.xuPVH:case n(1491):return{["x-use-"+s]:1,"x-tt-env":t};default:return{}}};class Sa{constructor(t){let n=r;if(e[n(1436)](e.OMuNx,e[n(1281)]))this[n(211)+"ount"]=t,this[n(678)]=0;else{this[n(305)+"WebSocket"]();let o=_0x5d62f1("reconnect",{message:e[n(776)]});this[n(331)+n(215)+n(424)+"ct"]&&this[n(331)+"mediatel"+n(424)+"ct"](o)}}[r(1518)](){let t=r;this[t(678)]++}["checkRea"+r(251)+"nt"](){let t=r;return this.count>=this[t(211)+t(1310)]}[r(1069)+"nter"](t=0){this.maxLossCount=t,this.count=0}}async function Ea(s){let t={ksUTz:function(n,o){return e[D(1555)](n,o)}};return new Promise(n=>{let o=D;if(!at)return e[o(1581)](n,e.sdGaG);try{let x=document[o(1232)+o(672)](e[o(730)]);window[o(506)+o(562)]=l=>{let g=o;document[g(297)][g(1112)+g(975)](x),window["frontier"+g(562)]=void 0,t[g(641)](n,l&&l.msg||"unknown "+g(743))},x[o(317)]=e[o(260)],x[o(514)]=e.grMIv(s[o(1399)](/^ws/,e.ymgei),"&jscallb"+o(461)+o(756)+"P");try{if(e.snEQx(e[o(863)],e.AmstE)){this[o(1456)+o(240)](),this._pingPongTimeoutId=_0xe94204(this._ping[o(1408)](this),this._options[o(1251)+o(1055)]);return}else document[o(297)]["appendCh"+o(975)](x)}catch{document[o(297)][o(1112)+"ild"](x)}}catch{window["frontier"+o(562)]=void 0,e[o(214)](n,e.sdGaG)}})}function Ge(s,t,n){let o=r;if(e.GzQvo!==o(280))return!!s?.[o(783)](x=>x[o(275)]===t&&x[o(1403)]===n);_0x8e967[o(1409)](_0x5bed20)}function ct(s,t){let n=r;return s?.[n(783)](o=>o[n(275)]===t)?.[n(1403)]}let dr=null;async function Ca(){let s=r,t={UndaZ:function(n,o,x){return e[D(1340)](n,o,x)},etsLo:s(1223)};if(s(1347)!==e[s(504)])return dr||(dr=Promise[s(1020)]().then(Ce[s(1408)](Ce,e[s(468)]))),dr;{let n=_0x12d1f6(s(1127),{message:this[s(702)+s(721)+s(302)](_0x3e510f)});this[s(759)]("error",n);let o=xOvZYA[s(1176)](_0x40fba4,xOvZYA[s(282)],{reason:this[s(702)+s(721)+s(302)](_0x36a03b)});this[s(759)](xOvZYA[s(282)],o)}}class Aa extends xr{constructor(t,n){let o=r;super(),this[o(804)]=t,this[o(1343)]=n,this[o(716)]=void 0,this[o(1507)+o(535)]=null}async openDB(){await this[r(624)]()}async[r(624)](){let t=r,n={fjuxe:function(o,x,l,g){return e[D(256)](o,x,l,g)},Mqbuu:e.IjqPk,jZAUl:e[t(720)]};if(!this._qosDB){if(this["_initPro"+t(535)])return this[t(1507)+t(535)];try{let o=this[t(804)],x=this[t(1343)];this[t(1507)+t(535)]=(async()=>{let l=t,{openDB:g}=await Ca();this[l(716)]=await n[l(1091)](g,l(506)+"_"+o,1,{upgrade(p){p[l(1506)+"jectStore"](o,{keyPath:x})}})})(),await this["_initPro"+t(535)]}catch(o){e[t(841)](t(1582),e[t(517)])?console[t(1409)](o):(_0x414022[t(1368)+"entListe"+t(893)](XnXpDf[t(1272)],_0x1a7272),_0xb5d63[t(1368)+t(1133)+"ner"](XnXpDf[t(422)],_0x5639e1))}finally{this[t(1507)+t(535)]=null}}}async[r(935)](t){let n=r;try{return await this[n(624)](),this[n(716)]?.[n(935)](this[n(804)],t)}catch(o){console[n(1409)](o)}}async set(t,n){let o=r,x={dfNhr:function(l,g){return e.yPRrr(l,g)}};if(e[o(942)](e.oOrcV,e[o(1111)])){let l=this[o(716)][o(679)](this._prefix);return _0x589d68[o(1512)](x[o(692)](l,"{}"))[_0x282428]}else return await this._init(),this[o(716)]?.[o(460)](this[o(804)],t)}async[r(660)](t){let n=r;try{return await this[n(624)](),this._qosDB?.delete(this[n(804)],t)}catch(o){console[n(1409)](o)}}async[r(1589)](){let t=r;try{return await this[t(624)](),this._qosDB?.[t(1589)](this[t(804)])}catch(n){console[t(1409)](n)}}async[r(1460)](){let t=r;if(e[t(1421)](e.mFcxp,t(431)))return await this._init(),this[t(716)]?.[t(1263)+"ys"](this[t(804)]);{let{offset:n}=e[t(886)](_0x303f9a,_0x94bbc9,_0x1bf061);_0x4a68d0=n;let o={cursor_name:"",cursor:0,service:0},{value:x,offset:l}=e.OYEmW(_0x334a75,_0x589505,_0x144984);o.service=x,_0x490dc7=l;let{value:g,offset:p}=e[t(362)](_0x3c1b5a,_0x57c695,_0xb00c16);_0x20d1ec=p,o[t(316)+t(1395)]=e[t(856)](_0x36e031,_0x8deb09,_0x20ad3c,e.ltijy(_0xa97060,g)),_0x2a512d+=g;let{value:f,offset:b}=e.dCMFY(_0x5825c8,_0x24b759,_0x56ca6d);o[t(606)]=f.toNumber(),_0x5856d3=b,_0x2320d2[t(547)](o)}}async[r(210)](){let t=r;return await this._init(),this[t(716)]?.[t(210)](this._dbName)}async[r(1198)](){let t=r,n={buyhf:function(o,x){return e.ljrUx(o,x)},tfreG:function(o,x){return e[D(1533)](o,x)},urPRS:e.RWGet,Suwtt:e[t(328)]};try{e.yFUrY(e[t(1463)],e.onfme)?(this[t(716)]?.[t(1223)](),this[t(716)]=void 0):_0x569d77.persisted&&(this["_navigat"+t(1544)]()&&(!this._ws||n[t(1419)](this[t(951)].readyState,this[t(375)])||n[t(474)](this._ws[t(272)+"te"],this[t(425)+"NG"]))&&this[t(536)+t(370)](),this[t(819)+"er"]&&_0xfbf8a0["addEvent"+t(1037)](n[t(748)],this[t(536)+t(370)]),this[t(819)+"er"]&&_0x25ecf2[t(426)+"Listener"](n[t(798)],this[t(536)+t(974)]))}catch(o){console[t(1409)](o)}}get[r(1224)](){let t=r;try{return!!this[t(716)]}catch(n){return console[t(1409)](n),!1}}}class Pa{constructor(t,n){let o=r;this[o(929)]=t,this._pathKey=n,this._qosDB=localStorage}async openDB(){}get[r(1216)](){let t=r,n={VvDgt:function(o,x,l){return e[D(362)](o,x,l)},vfZBo:function(o,x,l){return o(x,l)},wGTvI:function(o,x){return e[D(551)](o,x)}};if(e[t(1339)]!==e[t(1492)])return t(506)+"_"+this[t(929)];XdxPWh[t(1319)](_0x1239bc,_0x158b58,96),XdxPWh[t(434)](_0x435ff6,_0x242c4d,XdxPWh.wGTvI(_0x25859c,_0x3b2d4e))}async[r(935)](t){let n=r,o={mXEbH:function(x,l){return e[D(767)](x,l)},oJiyT:function(x,l){return e.xNmNL(x,l)}};{let x=this[n(716)].getItem(this[n(1216)]);return JSON[n(1512)](x||"{}")[t]}}async[r(396)](t,n){let o=r,x=this[o(716)].getItem(this[o(1216)]),l=JSON.parse(e.VixQF(x,"{}"));return l[n||t[this[o(220)]]]=t,this[o(716)][o(1459)](this[o(1216)],JSON[o(816)+"y"](l)),n||t[this._pathKey]}async[r(660)](t){let n=r;if(e[n(1577)]===e[n(263)])return this._ws?this._ws[n(420)]:"";{let o=this[n(716)].getItem(this[n(1216)]),x=JSON[n(1512)](e[n(923)](o,"{}"));return x[t]=void 0,this[n(716)].setItem(this[n(1216)],JSON[n(816)+"y"](x))}}async[r(1589)](){let t=r;return this[t(716)][t(1589)]()}async[r(1460)](){let t=r,n=this._qosDB[t(679)](this[t(1216)]),o=JSON[t(1512)](e[t(449)](n,"{}"));return Object[t(1460)](o)}async[r(210)](){let t=r;if(e[t(638)](e.mToTK,e[t(332)])){let x="3|2|1|0|4"[t(1357)]("|"),l=0;for(;;){switch(x[l++]){case"0":_0x5d2fbb[_0x2e3e73](n,n.exports,_0x7c2a5b);continue;case"1":var n=_0x3a33c1[_0x4beecc]={exports:{}};continue;case"2":if(WjnquI[t(195)](void 0,o))return o[t(208)];continue;case"3":var o=_0x15ac21[_0x1c3d16];continue;case"4":return n[t(208)]}break}}else{let x=this[t(716)][t(679)](this[t(1216)]),l=JSON.parse(e[t(1535)](x,"{}"));return Object[t(573)](l)}}[r(1198)](){let t=r;return t(553)===e[t(1067)]?new _0x364a57(_0x57f6d5,{code:_0x6916dc,reason:_0x3531dd,wasClean:_0x1eba26,willReconnect:_0x2ee9be}):Promise[t(1020)]()}get[r(1224)](){return!!this[r(716)]}}class ka{constructor(t,n){let o=r;this[o(929)]=t,this[o(220)]=n,this[o(716)]=Xe?tt:At?wx:null}async[r(995)](){}get[r(1216)](){return r(506)+"_"+this._DBName}async[r(935)](t){let n=r,o=this[n(716)][n(1304)+n(371)](this._prefix);return JSON.parse(e.wNAWI(o,"{}"))[t]}async[r(396)](t,n){let o=r,x=this[o(716)]["getStora"+o(371)](this._prefix),l=JSON[o(1512)](e[o(1535)](x,"{}"));return l[n||t[this[o(220)]]]=t,this[o(716)][o(407)+o(371)](this._prefix,JSON[o(816)+"y"](l)),n||t[this[o(220)]]}async[r(660)](t){let n=r,o=this._qosDB[n(1304)+n(371)](this[n(1216)]),x=JSON[n(1512)](e[n(1490)](o,"{}"));return x[t]=void 0,this[n(716)]["setStora"+n(371)](this._prefix,JSON.stringify(x))}async clear(){let t=r;if(e[t(841)](t(301),e[t(1218)]))return this[t(716)][t(1260)+t(1440)]();_0x195b68[t(396)](_0xf2e04d,_0x2f00fe)}async[r(1460)](){let t=r,n=this[t(716)][t(1304)+t(1016)+"nc"](this[t(1216)]),o=JSON.parse(e.IbgQY(n,"{}"));return Object[t(1460)](o)}async getAll(){let t=r,n=this[t(716)][t(1304)+t(1016)+"nc"](this._prefix),o=JSON[t(1512)](e[t(1209)](n,"{}"));return Object[t(573)](o)}[r(1198)](){let t=r;if(e[t(628)]===e[t(315)])_0x4b2dfb=_0x11ba49[t(1499)](_0x460006),_0x1d8b4d=_0x138318[t(1499)](_0x3211e8[_0xd9dcc9]);else return Promise[t(1020)]()}get[r(1224)](){return!!this._qosDB}}function Ds(s,t){let n=r;if(e[n(1073)](Xe,Xe))return new ka(s,t);if((at||Pt)&&e.bAMNP("undefined",typeof indexedDB))return new Aa(s,t);if(e[n(1490)](at,Pt)&&e[n(358)](e.gEAxi,typeof localStorage))return new Pa(s,t);throw new Error("init QoSDB failed")}class Da{constructor(){let t=r;this[t(874)+t(921)+"Id"]=null,this[t(874)+"l"]=36e5,this[t(716)]=e[t(1476)](Ds,e[t(712)],"message_id")}async[r(874)+r(1119)](){let t=r;e.vcvHN(clearInterval,this._intervalTimeoutId),this["_interva"+t(921)+"Id"]=e.qiQmJ(setInterval,()=>{let n=t;this[n(905)+n(576)]()},this[t(874)+"l"])}async[r(995)](){let t=r;await this[t(716)][t(995)]().then(()=>{let n=t;this[n(874)+n(1119)]()})}async flushExpired(){let t=r,n={vLELL:function(o,x){return e[D(1295)](o,x)},SjSQA:function(o,x){return o(x)},QefgP:function(o,x,l){return e.flqXl(o,x,l)}};if(t(1231)!==e[t(1063)])return zbETFi.vLELL(zbETFi[t(1504)](_0x57d385,4)[t(760)]("0"),zbETFi.QefgP(_0x4aba83,_0x5104bc,2)[t(187)](16))[t(258)](-4);(await this[t(716)]?.[t(210)]()||[]).filter(({timestamp:l})=>l<Date.now())[t(1248)](l=>{let g=t;this._qosDB?.del(l[g(658)+"id"])})}async del(t){return this[r(716)]?.del(t)}async[r(396)](t,n){let o=r;if(e[o(205)]===o(464))return this._qosDB?.[o(396)]({message_id:t,timestamp:n});{let x=_0x5a0b54[o(1227)+"At"](_0x22cbca);x>=55296&&x<=56319&&_0x2dc755+1<_0x4d2f78&&(x=e[o(592)]((x<<10)+_0x55dfdd[o(1227)+"At"](++_0x42c0fc),56613888)),e[o(335)](x,128)?_0x235be6[_0x5d2def++]=x:(e[o(1101)](x,2048)?_0x30da6c[_0x6a83ce++]=e.yQoCa(e[o(564)](x,6)&31,192):(e.PdjEn(x,65536)?_0x3f01c6[_0x368c35++]=e[o(907)](e[o(1162)](e[o(687)](x,12),15),224):(_0x13804d[_0xa14956++]=e[o(320)](e[o(1383)](e[o(564)](x,18),7),240),_0x2bd884[_0x3116f1++]=e[o(746)](e.pcRMr(e[o(564)](x,12),63),128)),_0x494a9a[_0x4c3e1e++]=e[o(843)](e[o(1307)](e[o(687)](x,6),63),128)),_0x8fef66[_0x3f625f++]=e[o(832)](e[o(1161)](63,x),128))}}async[r(935)](t){let n=r;return this[n(716)]?.[n(935)](t)}async[r(1198)](){let t=r;e[t(551)](clearInterval,this[t(874)+t(921)+"Id"]),await this[t(716)]?.[t(1198)]()}get isReady(){let t=r;return this._qosDB?.[t(1224)]}}function fr(s){let t=r,n=!!this._options.enableQoS;if(!n)return{enabled:n,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=e.gAdcG(Ge,s.message[t(1457)],e[t(635)],"2"),x=o&&e[t(546)](Ge,s.message[t(1457)],e.XqUWl,"1"),l=o&&e[t(577)](Ge,s[t(965)].headers,t(1382)+t(1099)+"k","1"),g=l?e.ZoOno(ct,s.message[t(1457)],e[t(1114)])?.[t(1357)](",").filter(Boolean)||[]:[];return{enabled:n,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:l,ackMsgIds:g}}async function Is(){let s=r;return e[s(300)]!==e[s(300)]?e[s(484)](_0x6b7a05,e[s(193)](_0x118b40,_0x4c575a)):(this[s(409)+s(686)]||(this[s(409)+"ger"]=new Da),this[s(409)+"ger"][s(1224)]||await this[s(409)+s(686)].openDB(),this[s(409)+s(686)])}async function Ia(s,t){let n=r,{enableAutoAck:o}=this[n(1296)],x=e[n(1522)](Ge,s[n(965)][n(1457)],e[n(604)],"1"),l=e[n(1604)](Ge,s[n(965)][n(1457)],e[n(643)],"1"),g=fr[n(812)](this,s);if(e[n(1521)](o,x)){let{SeqID:p,LogID:f,service:b,LogIDNew:v,method:C}=s.message;this[n(1509)]({SeqID:p,LogID:f,LogIDNew:v,service:b,method:C,headers:[{key:e[n(643)],value:"1"},{key:e[n(1345)],value:e.JkbOf(v,"")},{key:n(418),value:"0"}]})}l&&!g[n(1120)]&&this[n(1138)+n(1201)+n(626)](s),e[n(364)](t)}async function Ta(s,t){let n=r;this._debug(e[n(1616)],s[n(965)]),t()}async function Ra(s,t){let n=r,o={LfQkk:function(x,l){return e[D(902)](x,l)},kHflr:e[n(1011)],DOdby:e[n(655)],aefia:"none_none",xQtpr:function(x,l,g,p){return e[n(452)](x,l,g,p)},WPaXo:function(x,l){return e.cOqKa(x,l)}};if(e[n(548)]("DqlOq",e[n(1027)])){let x=o[n(1441)](this._options[n(731)+n(859)],_0x3b36b0)?{force:!!this[n(1296)][n(731)+n(859)][n(250)],encoding:this._options[n(731)+n(859)].encoding?this[n(1296)][n(731)+n(859)][n(1373)][n(1399)](/\s/g,"")["toLowerC"+n(1405)]():""}:{force:!1,encoding:this[n(1296)][n(731)+n(859)]?this[n(1296)]["payloadE"+n(859)][n(1399)](/\s/g,"")[n(1369)+n(1405)]():""},l=_0x5b8894.payloadEncoding?_0x2d1d57["payloadE"+n(859)][n(1399)](/\s/g,"")[n(1369)+"ase"]():"",g=o[n(1441)](this[n(1296)]["payloadT"+n(1164)],_0x54ab97)?{force:!!this[n(1296)]["payloadT"+n(1164)][n(250)],type:this._options[n(1392)+n(1164)].type?this[n(1296)][n(1392)+n(1164)][n(317)][n(1399)](/\s/g,"").toLowerCase():""}:{force:!1,type:this[n(1296)][n(1392)+n(1164)]?this[n(1296)][n(1392)+"ype"][n(1399)](/\s/g,"")[n(1369)+"ase"]():""},p=_0x12acbd[n(1392)+n(1164)]?_0x163618[n(1392)+n(1164)][n(1399)](/\s/g,"")[n(1369)+"ase"]():"",f=g[n(250)]?g[n(317)]:p||g.type,b=x[n(250)]?x.encoding:l||x[n(1373)],v=[o[n(557)],o.DOdby,n(770)+"ion/json"+n(440)+n(1005),"string"],C=[o.aefia,"binary"];this[n(1296)][n(1468)+"ansformT"+n(950)+"ad"]&&v.includes(f)&&(!b||C[n(540)](b))?_0x1c96a9[n(1423)+n(400)]=o[n(600)](_0x2a69cf,_0x1ba97b[n(1192)],0,_0x1293b0.payload[n(762)+"th"]):_0x49c29d[n(1423)+n(400)]=""}else{let x=ds(await ks(s[n(1355)]));try{if(x[n(1192)]instanceof Uint8Array)if(e[n(406)](e[n(1337)],e.KlAsr)){let l=this[n(1296)][n(731)+n(859)]instanceof Object?{force:!!this[n(1296)]["payloadE"+n(859)][n(250)],encoding:this[n(1296)][n(731)+"ncoding"][n(1373)]?this[n(1296)][n(731)+n(859)][n(1373)][n(1399)](/\s/g,"")["toLowerC"+n(1405)]():""}:{force:!1,encoding:this[n(1296)][n(731)+n(859)]?this[n(1296)][n(731)+n(859)][n(1399)](/\s/g,"")[n(1369)+n(1405)]():""},g=x[n(731)+n(859)]?x[n(731)+n(859)][n(1399)](/\s/g,"")[n(1369)+"ase"]():"",p=e[n(1012)](this._options[n(1392)+"ype"],Object)?{force:!!this._options[n(1392)+n(1164)][n(250)],type:this._options[n(1392)+"ype"][n(317)]?this[n(1296)]["payloadT"+n(1164)][n(317)].replace(/\s/g,"")["toLowerC"+n(1405)]():""}:{force:!1,type:this._options.payloadType?this[n(1296)][n(1392)+n(1164)].replace(/\s/g,"")[n(1369)+n(1405)]():""},f=x.payloadType?x[n(1392)+n(1164)].replace(/\s/g,"").toLowerCase():"",b=p[n(250)]?p[n(317)]:f||p[n(317)],v=l[n(250)]?l[n(1373)]:g||l.encoding,C=["text/pla"+n(1479)+n(920),e[n(655)],e[n(1074)],e[n(541)]],I=[e[n(677)],n(603)];this._options[n(1468)+"ansformT"+n(950)+"ad"]&&C[n(540)](b)&&(!v||I[n(540)](v))?x[n(1423)+n(400)]=e[n(1249)](Ps,x.payload,0,x[n(1192)].byteLength):x[n(1423)+n(400)]=""}else{let l=_0x73bbf8[n(1603)+"g"](0,jzNfBk[n(787)](4,_0x4a9098[n(836)])),g=l[n(1499)](_0x18adc2);_0x59a4a1[n(547)](g)}else x[n(1423)+"oad"]=""}catch(l){x[n(1423)+n(400)]="",console[n(1409)](l)}s.message=x,t()}}function Na(s,t,n){let o=r,x=e.QRKuj(n,8192),l=e[o(1180)](x,1),g=null,p=x;return function(f){let b=o;if(e[b(1599)](f,1)||e[b(1051)](f,l))return e[b(1418)](s,f);e[b(231)](e[b(808)](p,f),x)&&(g=e[b(867)](s,x),p=0);let v=t[b(812)](g,p,p+=f);return 7&p&&(p=e[b(970)](7,p)+1),v}}let La=4294967295;function Oa(s,t,n){let o=r;if(e[o(236)](e.fsZLh,e.fsZLh)){if(e[o(541)]==typeof _0x2846c6){let x=new _0x4f52f0(_0x4d5199(_0x5550d3));return e.gAdcG(_0x6f0383,_0x19dc8e,x,0),x}return e.xhABy(_0x5844d5,_0x1c66e6)?new _0x432b9e(_0x2fb08f):new _0x43fee8(_0x5c4762[o(1071)],_0x32faa2.byteOffset,_0x113922.byteLength)}else return e[o(879)](RangeError,e[o(411)](e[o(1094)](e[o(1558)](e[o(1021)](e[o(594)],s)+e[o(584)],e.hyPBs(t,1)),o(1060)),n))}function Ba(s,t,n){let o=r;if(n>La)throw new Error(o(830)+"too large");let x=3;for(;x>=0;){let l=e[o(1128)](255,n);e[o(1309)](hr,l,s,e[o(1140)](t,x)),n>>>=8,x--}return e[o(308)](t,4)}function Ma(s,t){let n=r,o=0,x=t,l=t+4;for(;e[n(1039)](x,l);){let{value:g,offset:p}=e[n(578)](lr,s,x);x=p,o=e[n(242)](o,8)>>>0,o+=g}return{value:o,offset:l}}function za(s,t,n){let o=r,x=e.LhEiz[o(1357)]("|"),l=0;for(;;){switch(x[l++]){case"0":return e.OOnel(e[o(1502)](ur,s,t,n),n);case"1":if(e[o(233)](s.length,40))return e[o(876)](e[o(1283)](ur,s,t,n),n);continue;case"2":if(t[o(1230)])return e[o(385)](t.write(s,n),n);continue;case"3":if(t[o(244)+"e"])return e[o(340)](t[o(244)+"e"](s,n),n);continue;case"4":if(!s)return n;continue}break}}function qa(s,t){let n=r,o=new z(e.EKvhq(e.yQoCa(e[n(450)](s[e[n(1454)](t,4)],24)|e.ZKyjj(s[e[n(1124)](t,5)],16),s[e.kgVbb(t,6)]<<8),s[e.MscWo(t,7)]),e.xESbF(e[n(520)](e.AXUVN(s[e[n(1454)](t,0)],24),s[e.UlpKB(t,1)]<<16)|e[n(242)](s[t+2],8),s[e[n(736)](t,3)]),!0);return t+=8,{value:o,offset:e[n(283)](t,8)}}function Fa(s,t,n){let o=r,x=s[o(1239)],l=s[o(1028)];return t[n]=e[o(725)](l,24),t[e[o(385)](n,1)]=e[o(334)](l>>>16,255),t[e[o(1414)](n,2)]=e[o(1175)](e[o(718)](l,8),255),t[e[o(1558)](n,3)]=255&l,t[e[o(802)](n,4)]=e[o(664)](x,24),t[e[o(1059)](n,5)]=e[o(644)](e[o(1233)](x,16),255),t[e[o(478)](n,6)]=e[o(683)](e[o(1081)](x,8),255),t[n+7]=e[o(419)](255,x),n+=8,n}function lr(s,t){let n=r;return s[n(367)+"8"]?{value:s[n(367)+"8"](t),offset:t+1}:{value:e.lAMtm(255,s[t]),offset:e[n(299)](t,1)}}function hr(s,t,n){let o=r;return t[o(1344)+"t8"]?t.writeUint8(s,n):t[n]=e[o(735)](255,s),e.EnKEJ(n,1)}let Ua=function(s){let t=r;if(e[t(473)](e[t(1270)],e[t(1115)]))_0x503fbc[_0x2cf9e0++]=e[t(1611)](e[t(298)](_0x10c707,12),224),_0x10b418[_0x282c2f++]=e.gJbEK(e[t(1548)](_0x5f474b,6)&63,128),_0xbcac73[_0x37ce8f++]=e.RGSis(63&_0x3721cd,128);else return new Uint8Array(s)},Ga=e[r(675)](e[r(1487)],typeof Buffer)?Buffer[r(1422)+r(197)]:e[r(910)](Na,Ua,Uint8Array[r(912)+"e"][r(500)]);(()=>{let s=r,t={cALkB:function(n,o){return e[D(1503)](n,o)},WdjAB:function(n,o){return e[D(1110)](n,o)},sKoKt:function(n,o){return e.CyZZU(n,o)}};if(e[s(579)](e[s(1452)],e[s(1155)])){let n=4294967295;return function(o,x,l=!0){let g=s,p={QsStg:function(f,b){return e[D(631)](f,b)},waawD:function(f,b){return e[D(1302)](f,b)},KFDYW:e[g(328)]};if(n=e[g(310)](127,o[x])>>>0,o[x++]<128)return{value:l?n:0|n,offset:x};if(n=e.DRCCE(e.IsEHg(n,e[g(875)](127&o[x],7)),0),o[x++]<128)return{value:l?n:e.RGSis(0,n),offset:x};if(n=e[g(1233)](e[g(1464)](n,e[g(878)](e.UloIV(127,o[x]),14)),0),o[x++]<128)return{value:l?n:e[g(1563)](0,n),offset:x};if(n=e[g(967)](e.mtLCZ(n,e.SVBxF(e[g(644)](127,o[x]),21)),0),o[x++]<128)return{value:l?n:0|n,offset:x};if(n=e[g(1411)](n|e[g(696)](15,o[x])<<28,0),e[g(559)](o[x++],128))return{value:l?n:e[g(1525)](0,n),offset:x};if(e[g(585)](x+=5,o[g(836)])){if(e[g(1264)](e.ptPSG,e[g(1154)]))throw x=o[g(836)],e[g(1249)](Oa,x,10,o[g(836)]);this[g(903)+g(1544)]()&&(!this[g(951)]||p[g(284)](this[g(951)].readyState,this[g(375)])||p.waawD(this[g(951)][g(272)+"te"],this.CONNECTING))&&this._handleOnLine(),this[g(819)+"er"]&&_0xb013d8["addEvent"+g(1037)](g(288),this[g(536)+g(370)]),this._isBrowser&&_0x321b8f[g(426)+g(1037)](p.KFDYW,this[g(536)+"ffLine"])}return{value:l?n:0|n,offset:x}}}else _0x521413[_0x2ed277++]=PdAXUL[s(891)](_0x881dc3>>6,192),_0x551842[_0x2180e6++]=PdAXUL[s(268)](PdAXUL.sKoKt(63,_0x27b07f),128)})();let Ka=16,gr=32;function Ha(s){let t=r,n=0,o={};for(let x=0;e[t(417)](x,s[t(836)]);x++)o[s[x][t(316)+t(1395)]]=e.RWVrx(As,s[x][t(316)+t(1395)]),n+=e[t(1108)](14,o[s[x][t(316)+t(1395)]]);return[n,o]}function Ts(s,t,n){let o=r,x={gaCeS:e.TbXao,zTRcx:e.DEjkR,PVdQH:e.ROtCV,YWUNo:function(b,v,C,I){return e.bmFhL(b,v,C,I)},KWHAE:function(b,v,C,I){return e.UkPGV(b,v,C,I)},UzQVy:o(255),xtLvh:e[o(889)],RdDRE:"service-"+o(919)},[l,g]=e[o(747)](Ha,s),p=Ga(l),f=0;return s[o(1248)](b=>{let v=o,C=x.gaCeS[v(1357)]("|"),I=0;for(;;){switch(C[I++]){case"0":console[v(1409)](x.zTRcx,f);continue;case"1":console.log(x[v(1102)],b,b.service);continue;case"2":console.log(v(402),f);continue;case"3":f=x[v(1195)](hr,0,p,f);continue;case"4":f=x[v(1195)](hr,g[b[v(316)+v(1395)]],p,f);continue;case"5":f=Fa(z[v(1252)+"er"](b.cursor||t),p,f);continue;case"6":f=x[v(791)](za,b[v(316)+v(1395)],p,f);continue;case"7":console[v(1409)](x[v(978)],f);continue;case"8":console[v(1409)](x[v(1489)],f);continue;case"9":console[v(1409)](x[v(1148)],f);continue;case"10":f=x[v(1195)](Ba,p,f,b[v(255)]||0);continue}break}}),{frameType:gr,headers:[{key:o(818)+o(1206),value:n}],payload:p}}function ja(s){let t=r,n=0,o=[];for(;e.gOHHJ(n,s.byteLength);){let{offset:x}=e.XDlZY(lr,s,n);n=x;let l={cursor_name:"",cursor:0,service:0},{value:g,offset:p}=e.GUvKW(Ma,s,n);l[t(255)]=g,n=p;let{value:f,offset:b}=e[t(684)](lr,s,n);n=b,l.cursor_name=e[t(1437)](Ps,s,n,e[t(1100)](n,f)),n+=f;let{value:v,offset:C}=e[t(1359)](qa,s,n);l[t(606)]=v[t(1406)](),n=C,o[t(547)](l)}return o}function Wa(){let s=r;return{frameType:gr,headers:[{key:e.GaNpk,value:e[s(784)]}],payload:void 0}}class Ja{constructor(t,n,o){let x=r;e[x(201)](x(1484),e[x(379)])?e[x(1121)](_0x4da140,_0x29395f,this[x(685)+x(209)+"e"](_0x9ff9c4)):(this[x(1472)+x(1160)]=t,this._cursorFileName=n,this[x(341)+x(369)]=o,this[x(716)]=e[x(596)](Ds,this[x(1472)+x(1160)],"cursor_n"+x(1395)))}async openDB(){let t=r;await this[t(716)][t(995)]()}async[r(1208)+"rs"](){let t=r;if(!this[t(716)][t(1224)])return;let n=this[t(341)+t(369)],o=await this[t(716)][t(210)]();switch(console[t(1409)](e[t(980)],o),n){case e[t(485)]:return o&&o[t(836)]?e[t(761)](Ts,o,0,this._cursorFileName):void 0;case e[t(877)]:return;case e[t(1435)]:return o&&o.length?e[t(1088)](Ts,o,0,this["_cursorF"+t(1090)]):Wa()}}async set(t,n,o){let x=r;return console[x(1409)](e[x(1105)],t,n,o),this[x(716)][x(396)]({cursor_name:t,cursor:n,service:o})}async[r(550)+"rs"](t){let n=r,o=ja(t);for(let x of o)console[n(1409)]("setcursor",o),await this._qosDB.set(x)}async[r(935)](t){let n=r;return(await this[n(716)][n(935)](t))?.[n(606)]}async[r(1198)](){let t=r;await this[t(716)][t(1198)]()}["updateCu"+r(814)+"Name"](t){let n=r;this[n(390)+n(1090)]=t}get isReady(){let t=r;return e[t(1534)](e[t(189)],e[t(287)])?new _0x30640c(e[t(1611)](e[t(907)](e[t(565)](_0x1bb437[0],e.SqlkZ(_0xab737f[1],8)),e[t(1245)](_0x149e8d[2],16)),e.RjCxG(_0x355173[3],24)),e[t(1110)](e[t(970)](e[t(706)](_0x4e5d4e[4],_0x28f314[5]<<8),_0xe4867[6]<<16),_0x4ef38a[7]<<24),_0x40defa):this._qosDB[t(1224)]}}let Va=e.TGCao;async function Rs(s){let t=r,n={DsglW:function(p,f,b){return e[D(1057)](p,f,b)}};if(!this[t(1296)][t(489)+"S"])return null;let{aID:o,fpID:x,messageStrategy:l}=this[t(1296)],g=e[t(667)](s,Va);try{if(this[t(1438)+t(944)])if(e.bRegL(t(455),e[t(1042)]))s&&this[t(1438)+t(944)][t(198)+t(814)+"Name"](s);else return new _0x4ebc04(p=>{let f=t;n[f(438)](_0x14a412,p,this[f(685)+f(209)+"e"](_0x5a6a30))});else this[t(1438)+"anager"]=new Ja(x+"_"+o+"_"+g,g,l);return this["_cursorM"+t(944)][t(1224)]||await this[t(1438)+"anager"][t(995)](),this[t(1438)+"anager"]}catch{return null}}async function Ya(s,t){let n=r,o=e[n(430)](Ge,s[n(965)][n(1457)],e.mCIfX,"-1"),x=e[n(1522)](Ge,s[n(965)][n(1457)],e[n(643)],"1"),l=e[n(1537)](ct,s.message[n(1457)],e[n(742)]),g=e[n(1610)](Number,e[n(362)](ct,s[n(965)][n(1457)],e[n(1004)]))||0,p=fr.call(this,s),f=e.odQcx(Ge,s[n(965)][n(1457)],e[n(1570)],"2"),b=ct(s.message.headers,e[n(414)]),v=e[n(867)](Number,e[n(984)](ct,s[n(965)][n(1457)],e.QIOUJ));if(p[n(1120)])return e[n(364)](t);let C=p[n(1562)+n(329)]?await Is[n(812)](this):null;if(e[n(1051)](s[n(965)][n(255)],0)&&x&&!o||e[n(1051)](s[n(965)][n(255)],0)){if(l&&p["isQoSMes"+n(329)]&&C)return!!!await C[n(935)](l)&&(this[n(1138)+n(853)+n(914)](s),await C.set(l,Date[n(1080)]()+g)),e[n(249)](t);if(f){let I=await Rs[n(812)](this);if(!I)return this[n(1138)+n(853)+"Event"](s),t();let O=await I[n(935)](b)??-1;if(e[n(1378)](O,v))if(e[n(1302)](n(246),n(543)))this._dispatchMessageEvent(s),I[n(396)](b,v,s.message[n(255)]);else return e.VhErF(_0x56b1a8,_0x39b306)?_0x6b28cc[n(516)](new _0x886571(e[n(617)])):(_0x429bb3=_0x17aafe,_0x5c0f7d===_0xaf0846[n(836)]?_0x3b91a9[n(1020)]():_0x37a306[_0x235c85][n(1408)](_0x69c92)(_0x55551f,_0x3a354d[n(1408)](null,_0x1d73a8+1)));else throw new Error(n(890)+" message"+n(917)+v+(n(640)+n(395)+n(1256)+"r ")+O);return e.KgtCY(t)}return this[n(1138)+n(853)+n(914)](s),t()}}async function $a(s,t){let n=r,o=fr[n(812)](this,s);if(!o[n(1562)+"sage"])return e.FtciR(t);let x=await Is[n(812)](this);if(o[n(1336)+n(269)+n(302)]&&o[n(273)+"s"][n(836)])for(let l of o.ackMsgIds)await x[n(660)](l);t()}async function Xa(s,t){let n=r,o=s[n(965)][n(519)+"e"]===Ka,x=e[n(1566)](s[n(965)][n(519)+"e"],gr);if(e[n(1521)](!o,!x))return t();let l=e[n(1622)](ct,s[n(965)][n(1457)],e.GaNpk);if(!l)return e[n(249)](t);let g=await Rs.call(this,l);if(!g)return e[n(1215)](t);if(o){let p=await g.getCursors(),f={frameType:p?.[n(519)+"e"],SeqID:z.fromNumber(this[n(445)]++),LogID:z.fromNumber(this._options[n(321)+n(1204)]()),service:9e3,method:5,headers:p?.[n(1457)],payload:p?.[n(1192)]},b=A(f);this[n(951)]&&this._ws.readyState&&this[n(951)][n(537)](b)}if(x){let p=s[n(965)][n(1192)];p&&g[n(550)+"rs"](p)}}let Za=async function(s,t){let n=r;this[n(476)]=!1,clearTimeout(this[n(1054)+n(793)+"utId"]),e[n(364)](t)},Qa=async function(s,t){let n=r;if(!this._ws||e[n(989)](this[n(951)].readyState,this[n(375)]))return e.HtXhB(t);let{pingInterval:o}=this[n(1296)];this[n(1520)+n(714)]?.[n(1384)+n(1095)+"fig"]();for(let l=0;e.RjTYz(l,this[n(341)+n(469)][n(836)]);l++){let g=this[n(341)+"Queue"][l];if(e[n(680)](this[n(951)][n(272)+"te"],this[n(375)])&&g!==null)this[n(951)]&&this[n(951)][n(537)](g),this[n(341)+n(469)][l]=null;else break}this._messageQueue=this[n(341)+n(469)][n(377)](l=>!!l),this[n(780)+n(1053)+"Id"]=e[n(437)](setTimeout,()=>this[n(583)](),o),this[n(1138)+"hOpenEvent"](s),this[n(819)+"er"]&&this[n(951)]&&(this[n(951)][n(809)+"pe"]=this[n(1571)+n(1164)]);let x=this["_endpoin"+n(714)]?.[n(657)+"ntEndpoint"]();this[n(206)](n(811)+x+n(911)),e[n(933)](t)},e0=async function(s,t){let n=r,o={vFVZd:function(x,l,g){return e[D(470)](x,l,g)},CrAJT:function(x,l,g){return e[D(1609)](x,l,g)},BHLOx:function(x,l){return e[D(1242)](x,l)}};if(e[n(201)](e[n(768)],n(769)))BzfTkO[n(949)](_0x346e03,_0x3dd79e,24),BzfTkO.CrAJT(_0x5c38b1,_0x92df24,BzfTkO[n(413)](_0x4ccdec,_0x311c12));else{let x=this[n(1520)+n(714)]?.[n(657)+n(511)+"nt"]();this[n(206)](n(811)+x),e[n(532)](t)}};class t0 extends xr{constructor(t){let n=r,o={HLGZH:function(p,f){return e[D(473)](p,f)},skwmf:e[n(1391)],XCFwV:n(937),ZIPey:e[n(1139)],yXbnv:n(1551),cWHpy:function(p,f,b){return e[n(645)](p,f,b)},NhnaM:function(p,f){return e[n(1436)](p,f)},JMsgn:function(p,f,b,v){return e.HFAeT(p,f,b,v)},FFkxr:e[n(720)],ELEPa:function(p,f){return e.OHqxp(p,f)}};super(),this[n(203)+"igatorOn"+n(533)]=!0,this[n(819)+"er"]=at,this._isNode=ma,this[n(633)+"T"]=Xe,this._isMiniWX=At,this[n(1580)+"r"]=Pt,this[n(341)+n(469)]=[],this[n(1520)+n(714)]=null,this[n(646)+n(436)]=!1,this[n(1571)+"ype"]=n(1305)+n(1475),this[n(1054)+n(1019)]=!1,this[n(1054)+n(793)+"utId"]=null,this[n(234)+"ctTimeoutId"]=null,this[n(780)+n(1053)+"Id"]=null,this._seqId=0,this._isInit=!1,this[n(977)]="",this[n(409)+n(686)]=null,this[n(1438)+n(944)]=null,this[n(868)+n(734)]=null,this[n(1564)+"ls"]=e[n(1106)],this[n(1621)]=3,this[n(425)+"NG"]=0,this[n(375)]=1,this[n(1033)]=2,this[n(961)]=p=>{let f=n;try{e[f(856)](Cs,this,p,[Za,Qa,e0])}catch(b){if(e[f(1134)](e[f(549)],f(223)))return this[f(1520)+f(714)]?.["getCurre"+f(511)+"ntTriesCount"]()||0;{let v=le(e[f(720)],{message:b[f(965)],code:Ue[f(1217)+"OR"],error:b});this[f(1138)+f(575)+"ent"](v)}}},this._onMessage=async p=>{let f=n,{pingInterval:b,pingFrequency:v}=this[f(1296)];if((p[f(1355)]==="hi"&&o[f(1549)](o[f(1173)],v)||o[f(1549)](o[f(1184)],v))&&(o[f(1189)]!==o[f(1189)]?(this[f(341)+f(469)].shift(),this[f(341)+f(469)][f(547)](_0x18da11)):(this[f(1456)+f(240)](),this[f(759)](f(1402)+f(999)+"s",o[f(661)]),this[f(780)+"gTimeoutId"]=o[f(1451)](setTimeout,this[f(583)][f(1408)](this),b))),!o[f(699)]("hi",p[f(1355)]))try{o[f(530)](Cs,this,p,[Ra,Ia,$a,Xa,Ya,Ta])}catch(C){let I=o[f(1451)](le,o.FFkxr,{message:C[f(965)],code:Ue[f(243)+f(190)],error:C});this[f(1138)+f(575)+f(1346)](I)}},this[n(800)]=p=>{let f=n,b=this[f(1520)+"tManager"]?.[f(1279)+f(613)+"es"](),v=this[f(1520)+f(714)]?.[f(657)+f(511)+"nt"]();if(b&&!p[f(965)]){let C=f(555)+v+(" fail, max retri"+f(1396)+"ed");this[f(1138)+f(575)+"ent"](e[f(1199)](le,e[f(720)],{message:C,code:Ue.MAX_RETRIES_ERROR,error:p}));return}this[f(951)]&&e.WNqyZ(this._ws[f(272)+"te"],this.OPEN)&&this[f(1246)+f(372)](),this["_dispatc"+f(575)+"ent"](le(e[f(720)],{message:p[f(965)],code:Ue[f(222)+"RROR"],error:p}))},this[n(1329)]=async p=>{let f=n;this[f(885)+f(327)](),this[f(1456)+f(240)](),this[f(945)+"sListeners"](),this._ws=null,this[f(1054)+f(1019)]=!1;let b=this[f(1520)+"tManager"]?.["checkRea"+f(613)+"es"]();if(!b&&this[f(903)+"orOnline"]()&&!this[f(646)+"osed"])if(e[f(637)]==="PHEhd"){let v=this._qosDB[f(679)](this[f(1216)]),C=_0x59de93[f(1512)](seCEHz[f(322)](v,"{}"));return C[_0x163975]=void 0,this._qosDB[f(1459)](this[f(1216)],_0x563196.stringify(C))}else{let v=this[f(1520)+f(714)]?.[f(657)+f(511)+"nt"](),C=this[f(1296)]["reconnec"+f(796)+"ptor"](p[f(634)],p[f(743)]);this["_dispatchCloseEv"+f(1346)](e[f(1622)](me,e[f(1540)],{code:1006,reason:p[f(743)]||f(616)+"ng faile"+f(1600)+f(764)+f(1550)+"ame: "+v,willReconnect:C})),C&&this[f(1054)]();return}if(e[f(410)](1e3,p[f(634)])&&this[f(646)+f(436)]){this[f(1138)+f(1284)+"ent"](e[f(713)](me,e.onPnX,{code:1e3,reason:f(381)})),this[f(1520)+"tManager"]?.["resetEndpointCon"+f(1526)](),this["_pingLos"+f(734)]?.[f(1069)+f(1341)]();return}if(e[f(277)](1e3,p.code)&&b){let v=this[f(1520)+"tManager"]?.[f(657)+f(511)+"nt"](),C=p.reason;C||(C=await e[f(1342)](Ea,this[f(977)])),C="connecti"+f(1567)+f(286)+C+(f(996)+f(1222))+v+(f(491)+"tries re"+f(1017)),this[f(1138)+"hCloseEv"+f(1346)](e[f(353)](me,e[f(1540)],{code:p.code,reason:C}));let I=f(555)+v+(f(1587)+f(835)+f(1396)+"ed");this["_dispatc"+f(575)+f(1346)](e[f(1146)](le,f(1127),{message:I,code:Ue[f(399)+f(985)+"R"]})),this[f(1520)+f(714)]?.[f(1384)+f(1095)+f(1526)](),this[f(868)+"sCounter"]?.["resetCou"+f(1341)]();return}if(e[f(579)](1e3,p[f(634)])&&!p.reason){let v=this[f(1520)+"tManager"]?.["getCurre"+f(511)+"nt"]();this[f(1138)+"hCloseEv"+f(1346)](me(e[f(1540)],{code:p[f(634)],reason:f(616)+"ng faile"+f(1600)+f(764)+f(1550)+"ame: "+v})),this[f(1520)+f(714)]?.["resetEnd"+f(1095)+f(1526)](),this[f(868)+f(734)]?.["resetCou"+f(1341)]();return}this[f(1138)+f(1284)+f(1346)](p),this[f(1520)+f(714)]?.[f(1384)+f(1095)+f(1526)](),this[f(868)+f(734)]?.[f(1069)+"nter"]()},this[n(1597)]=null,this[n(1018)]=null,this[n(1371)+"e"]=null,this[n(1212)]=null,this[n(892)+n(1469)]=null,this[n(908)+n(826)]=null,this[n(331)+"mediatel"+n(424)+"ct"]=null,this[n(536)+n(370)]=this[n(536)+"nLine"][n(1408)](this),this[n(536)+n(974)]=this[n(536)+n(974)][n(1408)](this),this["_handleP"+n(755)]=this[n(1274)+n(755)][n(1408)](this),this[n(1274)+n(647)]=this._handlePageShow[n(1408)](this),this[n(1296)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength: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[n(1123)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[n(1435)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:l}=t,g=Array.isArray(x)?x:e[n(541)]==typeof x?[x]:[];if(!g||e[n(1247)](0,g[n(836)]))throw new Error(n(1079)+n(513)+n(1082));if(!e[n(1568)](ya,l))throw new Error(e.FwdRg);Object[n(264)](this[n(1296)],t),this[n(1520)+"tManager"]=new Es(g,this[n(1296)][n(1617)+"es"]),this[n(868)+n(734)]=new Sa(this._options[n(1255)+n(257)]),this._options[n(621)+"cOpen"]&&(this[n(476)]=!0,this._connect()),this[n(1296)][n(820)+"tworkChanged"]&&(this[n(633)+"T"]||this[n(833)+"X"]?this[n(503)+n(1025)+n(1505)]():this._isBrowser&&this[n(605)+"balEvent"+n(1037)]())}[r(536)+"nLine"](){let t=r;this[t(1296)]["disableAutoRecon"+t(865)]||this["_readyCl"+t(436)]||this[t(493)+"econnect"]()}[r(536)+"ffLine"](){let t=r;this["_destroy"+t(1282)+"t"]();let n=e[t(771)](cr,e.mwrRe,{message:e[t(776)]});this["onStopImmediatel"+t(424)+"ct"]&&this[t(331)+t(215)+t(424)+"ct"](n)}[r(605)+"balEvent"+r(1037)](){let t=r;this._isBrowser&&window[t(426)+t(1037)](e[t(927)],this[t(536)+"nLine"]),this[t(819)+"er"]&&window.addEventListener(e.NhuKQ,this[t(536)+t(974)]),this._isBrowser&&window["addEvent"+t(1037)]("pagehide",this[t(1274)+t(755)]),this[t(819)+"er"]&&window[t(426)+t(1037)](e[t(899)],this[t(1274)+t(647)])}[r(1265)+"balEvent"+r(1037)](){let t=r;this._isBrowser&&window[t(1368)+t(1133)+t(893)](e[t(927)],this._handleOnLine),this[t(819)+"er"]&&window[t(1368)+"entListe"+t(893)](e.NhuKQ,this[t(536)+t(974)]),this[t(819)+"er"]&&window[t(1368)+t(1133)+t(893)](e[t(1174)],this[t(1274)+"ageHide"]),this[t(819)+"er"]&&window["removeEv"+t(1133)+t(893)](e[t(899)],this._handlePageShow)}["_handleP"+r(755)](t){let n=r;!t[n(1429)+"d"]&&(this._isBrowser&&window[n(1368)+"entListe"+n(893)](n(1152),this[n(1274)+n(755)]),this[n(819)+"er"]&&window["removeEv"+n(1133)+n(893)](e[n(899)],this[n(1274)+"ageShow"]),this.close()),this[n(819)+"er"]&&window[n(1368)+"entListe"+n(893)](e.RWGet,this[n(536)+"nLine"]),this[n(819)+"er"]&&window.removeEventListener(e[n(328)],this[n(536)+n(974)])}[r(1274)+r(647)](t){let n=r;t[n(1429)+"d"]&&(this[n(903)+n(1544)]()&&(!this[n(951)]||e[n(579)](this[n(951)][n(272)+"te"],this.OPEN)||e.XamOx(this[n(951)][n(272)+"te"],this[n(425)+"NG"]))&&this[n(536)+n(370)](),this._isBrowser&&window[n(426)+n(1037)]("online",this[n(536)+n(370)]),this[n(819)+"er"]&&window[n(426)+n(1037)](e.NhuKQ,this[n(536)+n(974)]))}async["_generat"+r(1200)](t){let n=r,{fpID:o,deviceID:x,bddID:l,ttwID:g,accessKey:p,aID:f,customParams:b={},enableAutoAck:v,enableQoS:C,QoSLevel:I,env:O}=this[n(1296)],L,B,Q;this[n(819)+"er"]||this._isMiniWX||this[n(633)+"T"]?(L=location&&location[n(420)]=="https:"?n(1116):e[n(1330)],B=t[n(1399)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),Q=/^wss(.*:\/\/)/[n(1048)](t)?t:""+L+B):(L=n(1116),B=t[n(1399)](/(^http)((?:[s]*:\/\/))/,""),Q=/(^ws)((?:[s]*:\/\/))/[n(1048)](B)?B:""+L+B);let $=l?e[n(815)]:g?e[n(595)]:e[n(1308)],Ie=l||g||x;if(!Ie||!$)throw new Error(n(1079)+"rovide b"+n(708)+n(1349)+n(913));let n0=n(339)==typeof b?await e.FtciR(b):b,r0=O?e[n(1178)](va,O[n(1424)],O[n(1087)]):{},pr=Object[n(264)]({device_platform:e.VAuJB,version_code:"fws_1.0.0",access_key:p,fpid:o,aid:f,[$]:Ie,xsack:v?1:0,xaack:v?1:0,xsqos:C?1:0,qos_level:C?I:void 0,qos_sdk_version:2,...r0},n0),s0=Object[n(1460)](pr)[n(392)]((mr,wr)=>pr[wr]!==void 0?""+mr+(mr?"&":"?")+wr+"="+pr[wr]:mr,"");return Q+n(1229)+s0}async[r(1054)](){let t=r;if(!(this[t(1054)+t(1019)]||this[t(646)+t(436)])){this[t(1054)+"Lock"]=!0;try{let n=this[t(1520)+t(714)]?.[t(1381)+"rentEndp"+t(1211)+"hedMaxRe"+t(694)](),{timeoutInterval:o}=this[t(1296)];if(n){let l=this[t(1520)+t(714)]?.[t(657)+t(511)+"nt"](),g=this["_endpoin"+t(714)]?.[t(897)+"ackupEnd"+t(387)+t(229)+t(1313)](),p=this[t(1520)+"tManager"]?.[t(657)+t(511)+t(632)+t(1310)]();if(g){let f=t(555)+l+(t(254)+t(491)+t(245)+t(1328)+t(539)+t(952)+t(786))+g+(t(1315)+"y"),b=e.oJqRZ(le,e.xdmpf,{message:f,code:Ue["MAX_RETR"+t(985)+"R"]});this[t(206)](f),this[t(1138)+t(575)+t(1346)](b),this[t(977)]=await this[t(888)+t(1200)](g),this[t(206)](t(555)+g+" "+p+t(671)),this[t(945)+t(1612)+"rs"]()}else{let f="connect "+l+(t(254)+t(491)+"tries re"+t(1017));this[t(206)](f),this[t(1138)+t(575)+"ent"](e[t(481)](le,e[t(720)],{message:f,code:Ue[t(399)+t(985)+"R"]}));return}}else{let l=this._endpointManager?.[t(657)+"ntEndpoi"+t(572)+"ateCount"](),g=this[t(1520)+t(714)]?.[t(657)+"ntEndpoi"+t(632)+t(1310)]();this._url=await this["_generat"+t(1200)](e.TXYHv(l,"")),this[t(206)](t(555)+l+" "+g+" times"),this[t(945)+t(1612)+"rs"]()}if(this._isInit)this[t(476)]=!1;else{let l=e[t(666)](cr,e.mwrRe,{message:e[t(715)]});this.onStartReconnect&&this[t(892)+t(1469)](l)}let x=this[t(1520)+t(714)]?.[t(657)+t(511)+t(632)+t(1310)]()||0;e[t(1238)](x,1)&&await this._wait(e[t(710)](x,1)),this[t(206)](t(616)+t(325)+this[t(977)]+(t(1276)+t(1226))+this._protocols),this[t(951)]=e[t(353)](_a,{url:this[t(977)],protocols:[this[t(1564)+"ls"]],headers:this[t(1296)][t(505)+t(860)+"s"][t(615)+t(904)]},this._options.ws),(this[t(819)+"er"]||this[t(1580)+"r"])&&this[t(951)]&&(this[t(951)][t(809)+"pe"]=this[t(1571)+"ype"]),this[t(247)+t(501)](),this[t(1054)+t(793)+t(1543)]=e.uVwRJ(setTimeout,this[t(582)+"ut"].bind(this),o)}catch(n){throw this[t(1054)+t(1019)]=!1,n}}}[r(885)+r(327)](){let t=r,n={oErVi:function(o,x){return e[D(1125)](o,x)}};if(e[t(1427)]===t(1129)){let o={RWLtc:function(x,l){let g=t;return CNGMDy[g(1532)](x,l)}};return function(x,...l){let g=t,p=_0x1dfba4[g(812)](_0x3af3c2(this),x,...l);return _0x27e33c[g(396)](p,x[g(828)]?x[g(828)]():[x]),o[g(962)](_0x12e4a6,p)}}else clearTimeout(this[t(1054)+"ionTimeo"+t(1543)]),this[t(1054)+t(793)+"utId"]=null}[r(1456)+r(240)](){let t=r;clearTimeout(this[t(780)+t(1053)+"Id"]),e.uSGYP(clearTimeout,this[t(234)+t(724)+"tId"]),this["_pingPon"+t(1053)+"Id"]=null,this[t(234)+"ctTimeou"+t(1496)]=null}[r(206)](...t){let n=r;this._options[n(1478)]&&console[n(1409)][n(1118)](console,[e[n(1032)],...t])}["_getInte"+r(209)+"e"](t){let n=r;if(e[n(689)](n(443),e.oTpRp))return new _0x19cd4b(_0x32659f,{data:_0x41f9ff,message:_0x306472});{let{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:l}=this[n(1296)],g=e[n(1236)](o,Math[n(1516)](l,e[n(571)](t,1)));return e.IXVZC(g,x)?x:g}}_ping(){let t=r,n={nLIrj:function(o,x){return o<x},vIFNt:function(o,x,l){return o(x,l)},BoUPG:function(o,x,l,g){return e[D(1007)](o,x,l,g)},qMUWm:function(o,x){return e[D(802)](o,x)}};if(this[t(951)]&&this._ws[t(272)+"te"]===this[t(425)+"NG"])if(e[t(1214)](e[t(1333)],e[t(1333)])){let o=0,x=[];for(;ljUkWg.nLIrj(o,_0x1aa2a4[t(762)+"th"]);){let{offset:l}=ljUkWg[t(1322)](_0x255cf8,_0x439c68,o);o=l;let g={cursor_name:"",cursor:0,service:0},{value:p,offset:f}=_0x4a0bc7(_0x49ae69,o);g[t(255)]=p,o=f;let{value:b,offset:v}=_0x27fb74(_0x3cbd1f,o);o=v,g[t(316)+"ame"]=ljUkWg.BoUPG(_0x15e0c4,_0x31efdf,o,ljUkWg[t(1228)](o,b)),o+=b;let{value:C,offset:I}=_0x51dd64(_0x1ebf93,o);g[t(606)]=C[t(1406)](),o=I,x[t(547)](g)}return x}else{this[t(1456)+"ngTimer"](),this[t(780)+t(1053)+"Id"]=e[t(1359)](setTimeout,this[t(583)][t(1408)](this),this[t(1296)][t(1251)+t(1055)]);return}if(!this[t(951)]||e[t(1363)](this[t(951)].readyState,this[t(375)]))return void this[t(493)+t(1469)]();this[t(951)]&&this[t(951)][t(537)]("hi"),this["_reconnectTimeou"+t(1496)]=e.jycie(setTimeout,this[t(493)+t(1469)+t(1547)][t(1408)](this),this[t(1296)][t(556)+t(1203)+t(1324)])}["_handleR"+r(1469)+r(1547)](){let t=r;this[t(868)+t(734)]?.[t(1518)](),this[t(759)](e.WEzxw,e[t(623)]),this[t(868)+t(734)]?.[t(1279)+t(251)+"nt"]()?this[t(493)+t(1469)]():this[t(583)]()}[r(903)+r(1544)](){let t=r;return this[t(633)+"T"]||this[t(833)+"X"]?this[t(203)+t(938)+t(533)]:(this[t(819)+"er"]||this[t(1580)+"r"])&&this[t(1296)]["listenNe"+t(846)+"nged"]?navigator[t(948)]:!0}["_handleR"+r(1469)](){let t=r;!this[t(903)+t(1544)]()||this[t(646)+t(436)]||(this[t(1520)+"tManager"]?.[t(1384)+t(1095)+t(1526)](),this[t(868)+"sCounter"]?.["resetCou"+t(1341)](),this[t(951)]?this["_disconn"+t(372)](1001,e.GNTKM,!0):this[t(1054)]())}[r(503)+r(1025)+r(1505)](){let t=r;this[t(633)+"T"]?tt["onNetwor"+t(391)+t(1536)](({isConnected:n})=>{let o=t;this[o(203)+o(938)+o(533)]=n,n?this[o(536)+o(370)]():this[o(536)+o(974)]()}):this[t(833)+"X"]&&wx[t(1243)+t(391)+t(1536)](({isConnected:n})=>{let o=t;if(e[o(942)](e[o(777)],e[o(526)]))return this[o(716)]?.[o(660)](_0x16daea);this[o(203)+o(938)+o(533)]=n,n?this["_handleO"+o(370)]():this[o(536)+"ffLine"]()})}[r(723)](t){let n=r,o={saqUt:n(1298)+n(861)+n(597),ShJpG:function(x,l,g,p){return e[n(1278)](x,l,g,p)},XqzCl:e[n(465)],SwsGd:n(1190),KYDrK:e[n(889)],jRKlx:n(1024)+"ervice",HKONk:function(x,l,g,p){return e[n(1278)](x,l,g,p)}};return new Promise(x=>{let l=n;if(e.ErGxD(e[l(212)],e[l(212)]))setTimeout(x,this[l(685)+l(209)+"e"](t));else{let g=o.saqUt[l(1357)]("|"),p=0;for(;;){switch(g[p++]){case"0":_0x37a8fe=bfBtxI[l(1513)](_0x36cfba,_0x5b9521[l(1252)+"er"](_0x49d0f6[l(606)]||_0xf6cac9),_0x4bae9f,_0xd91d39);continue;case"1":_0x4cd0af[l(1409)](bfBtxI[l(1097)],_0x2d7401);continue;case"2":_0x40aaa9[l(1409)](bfBtxI[l(591)],_0x881029);continue;case"3":_0x4cbae7[l(1409)](l(957)+l(919),_0x3d92ac);continue;case"4":_0xfad75[l(1409)](bfBtxI.KYDrK,_0x2c6dc2);continue;case"5":_0x3cf2f4=_0x5ab47d(_0x47dad1[l(316)+l(1395)],_0x4134c8,_0x21e090);continue;case"6":_0xf5a71c[l(1409)](bfBtxI[l(1009)],_0x5c1ac9,_0x41d04d[l(255)]);continue;case"7":_0x724c1b[l(1409)](l(402),_0x720c67);continue;case"8":_0x3fcd40=_0x2c2f5d(_0x8a1597,_0x1fffc5,_0x462157[l(255)]||0);continue;case"9":_0x3c5c76=bfBtxI[l(946)](_0x18dc5d,_0x251cf0[_0x43af9a[l(316)+l(1395)]],_0x4934fa,_0x226b78);continue;case"10":_0x365224=bfBtxI.HKONk(_0x55ca34,0,_0x2552f0,_0x672d75);continue}break}}})}[r(1246)+r(372)](t=1e3,n="",o=!1){let x=r;this._ws&&this[x(305)+x(1282)+"t"](t,n,o)}_onTimeout(){let t=r,n=this[t(1520)+t(714)]?.[t(657)+"ntEndpoint"]();this[t(206)](t(555)+n+" timeout"),this["_disconn"+t(372)](1001,e[t(1122)],!0)}[r(1509)](t){let n=r,o=e[n(1242)](ar,t);this[n(951)]&&e[n(498)](this[n(951)][n(272)+"te"],this[n(375)])&&(this[n(951)]&&this._ws.send(o),this[n(206)](e[n(1166)],t))}[r(945)+"sListeners"](){let t=r;this._ws&&(this[t(951)][t(1368)+t(1133)+t(893)](e.iojll,this[t(961)]),this[t(951)][t(1368)+t(1133)+"ner"](e.onPnX,this[t(1329)]),this._ws[t(1368)+t(1133)+t(893)](e.NEjiL,this[t(1301)+"ge"]),this[t(951)][t(1368)+t(1133)+"ner"](e[t(720)],this[t(800)]))}[r(247)+r(501)](){let t=r,n=e[t(807)][t(1357)]("|"),o=0;for(;;){switch(n[o++]){case"0":if(!this[t(951)])return;continue;case"1":this[t(951)].addEventListener(e[t(720)],this[t(800)]);continue;case"2":this[t(951)][t(426)+t(1037)](e[t(1058)],this[t(961)]);continue;case"3":this._ws[t(426)+t(1037)]("close",this._onClose);continue;case"4":this._ws[t(426)+"Listener"]("message",this[t(1301)+"ge"]);continue}break}}[r(1014)+r(588)](t=1e3,n=""){let o=r;if(e[o(916)](e[o(1297)],e[o(1297)]))this.emit(e[o(1058)],_0x277e1e),this[o(1212)]&&this[o(1212)](_0x42c8ef);else try{this[o(951)]&&this._ws[o(1223)](t,n)}catch{}}[r(305)+"WebSocket"](t=1e3,n="",o=!1){let x=r,l={Sbjke:function(g,p,f){return e.CYOJw(g,p,f)},xjZNM:e.onPnX};if(this[x(1456)+"ngTimer"](),this[x(885)+"mer"](),this[x(945)+x(1612)+"rs"](),this[x(1014)+"nceClose"](1e3,n),this[x(1054)+"Lock"]=!1,o&&this[x(903)+x(1544)]()&&!this["_readyCl"+x(436)]){if(this[x(1520)+"tManager"]?.[x(1279)+x(613)+"es"]())if(x(1045)===e[x(1241)]){let p=this[x(1520)+x(714)]?.["getCurre"+x(511)+"nt"]();this[x(1138)+x(1284)+x(1346)](e[x(1514)](me,x(1223),{code:1006,reason:x(555)+p+(x(254)+", max re"+x(245)+"ached"),wasClean:!0}))}else{if(this["_endpoin"+x(714)]?.[x(1279)+x(613)+"es"]()){let f=this[x(1520)+x(714)]?.[x(657)+x(511)+"nt"]();this[x(1138)+x(1284)+x(1346)](l[x(1266)](_0xeeec5e,l[x(1393)],{code:1006,reason:x(555)+f+(x(254)+x(491)+x(245)+x(1017)),wasClean:!0}))}else{let f=this[x(1296)][x(1225)+x(796)+x(1353)](_0x46a9c4,_0x110a10);this[x(1138)+"hCloseEv"+x(1346)](l.Sbjke(_0x4cf9ff,l[x(1393)],{code:_0x515380,reason:_0x4b8cfb,wasClean:!0,willReconnect:f})),f&&this[x(1054)]()}return}else{let p=this[x(1296)][x(1225)+"tInterceptor"](t,n);this[x(1138)+x(1284)+x(1346)](e[x(276)](me,x(1223),{code:t,reason:n,wasClean:!0,willReconnect:p})),p&&this[x(1054)]()}return}this[x(903)+x(1544)]()||this[x(646)+x(436)]?this[x(1138)+x(1284)+x(1346)](e[x(1178)](me,e.onPnX,{code:t,reason:x(381)})):this["_dispatc"+x(1284)+x(1346)](me(e[x(1540)],{code:1006,reason:e[x(1388)]})),this._ws=null,this[x(1520)+x(714)]?.[x(1384)+x(1095)+x(1526)](),this[x(868)+x(734)]?.[x(1069)+x(1341)]()}[r(1138)+"hOpenEvent"](t){let n=r;if(e[n(928)](e[n(403)],e[n(403)]))this[n(759)](e.iojll,t),this[n(1212)]&&this[n(1212)](t);else return!!this[n(716)]}[r(1138)+r(853)+"Event"](t){let n=r;this[n(759)](e[n(990)],t),this[n(1371)+"e"]&&this[n(1371)+"e"](t)}[r(1138)+"hAckMess"+r(626)](t){let n=r;this.emit(n(845),t),this[n(908)+n(826)]&&this["onReceiv"+n(826)](t)}[r(1138)+r(575)+"ent"](t){let n=r;this[n(759)](e[n(720)],t),this[n(1018)]&&this[n(1018)](t)}[r(1138)+r(1284)+r(1346)](t){let n=r;this.emit(e.onPnX,t),this[n(1597)]&&this.onclose(t)}get[r(809)+"pe"](){let t=r;return this._ws?this[t(951)][t(809)+"pe"]:this[t(1571)+t(1164)]}set[r(809)+"pe"](t){let n=r,o={kZBCK:function(x,l,g){return e[D(470)](x,l,g)},DcgXI:function(x,l){return e[D(625)](x,l)}};if(e.OzKSe(e[n(494)],e[n(494)])){let x=_0x19cdc5();return QMWKXW[n(1047)](_0x3d3e01,_0x5b4d17,x),QMWKXW[n(1554)](_0x2b315f,x)}else this["_binaryT"+n(1164)]=t,this._ws&&(this[n(951)][n(809)+"pe"]=t)}get[r(326)+"nt"](){let t=r;return this[t(1520)+"tManager"]?.[t(657)+"ntEndpoi"+t(632)+t(1310)]()||0}get["buffered"+r(1410)](){let t=r;return this[t(341)+"Queue"][t(392)]((o,x)=>(o+=x&&x[t(762)+"th"]||0,o),0)+(this[t(951)]?this[t(951)][t(801)+t(1410)]:0)}get[r(1528)+"ns"](){let t=r;return this[t(951)]?this._ws[t(1528)+"ns"]:""}get[r(420)](){let t=r;return this._ws?this._ws[t(420)]:""}get[r(272)+"te"](){let t=r,n={RDXXE:function(o,x){return e[D(1131)](o,x)},FNQoH:function(o,x){return e[D(843)](o,x)},koKsJ:function(o,x){return o<<x},uGbys:function(o,x){return e[D(1070)](o,x)},BuAOr:function(o,x){return e[D(653)](o,x)}};if(e[t(1601)](t(405),e.APQGM))return this._ws?this[t(951)][t(272)+"te"]:this[t(1296)][t(621)+t(1485)]?this.CONNECTING:this[t(1621)];_0x515cf5=VCnkoB.RDXXE(VCnkoB[t(483)](VCnkoB[t(1354)](VCnkoB[t(1428)](15,_0xbee6e9),12),VCnkoB[t(1354)](VCnkoB[t(1428)](63,_0x169540),6)),VCnkoB[t(1428)](63,_0x7d00f1)),_0x379ac2<2048||_0x3680aa>=55296&&VCnkoB.BuAOr(_0x45dcc4,57343)?_0x377855+=_0x5397a7:(_0x2d7cc3+=_0x1894e0(_0x1a6aa2),_0x103e7b+=2)}get url(){let t=r;return this[t(951)]?this[t(951)].url:this[t(977)]}close(t=1e3,n){let o=r,x={HUVhA:function(l,g){return e[D(1147)](l,g)}};if(e[o(1261)]===e.efFvQ)return eCIfPw[o(486)](this.count,this[o(211)+o(1310)]);{let l=e[o(1289)].split("|"),g=0;for(;;){switch(l[g++]){case"0":if(e[o(488)](this[o(951)][o(272)+"te"],this[o(1621)])||this[o(951)][o(272)+"te"]===this.CLOSING)return void this._debug("close, ws alread"+o(230));continue;case"1":this[o(885)+o(327)]();continue;case"2":this[o(409)+o(686)]?.[o(1198)]();continue;case"3":this._destroyWebSocket(t,n);continue;case"4":this[o(1265)+o(1559)+o(1037)]();continue;case"5":if(!this[o(951)])return void this._debug(e[o(1010)]);continue;case"6":this[o(1456)+o(240)]();continue;case"7":this[o(646)+o(436)]=!0;continue}break}}}async[r(537)](t,n){let o=r,x={VbvLt:function(Q,$){return e.WDwbi(Q,$)},qQAbk:e[o(541)],uYBbG:e[o(1011)]};if(t==null)throw new Error(e[o(574)]);e[o(1348)](e[o(261)],typeof t)&&(t=JSON[o(816)+"y"](t)),e.YGSsM(o(751),typeof t)&&!(t instanceof ArrayBuffer)&&!(t[o(1071)]&&t[o(1071)]instanceof ArrayBuffer)&&(t=JSON[o(816)+"y"](t));let l=await e[o(1555)](ks,t),g=e.sREcf(ba,t),{method:p=0,service:f=this[o(1296)][o(255)],logID:b=this[o(1296)][o(321)+o(1204)](),headers:v=this[o(1296)][o(1457)],payloadEncoding:C=this[o(1296)][o(731)+o(859)],payloadType:I=this[o(1296)].payloadType,logIDNew:O=this[o(1296)][o(589)+o(1332)][o(981)+o(333)+"teLogIDNew"]?e.GTWJD(a,this[o(1296)][o(589)+o(1332)][o(1317)]):""}=n||{};if(!f)throw new Error(o(1079)+"rovide a"+o(884)+o(1444));let L={SeqID:z[o(1252)+"er"](this[o(445)]++),LogID:z[o(1252)+"er"](b),service:f,method:p,headers:v,payloadEncoding:e[o(1098)](C,Object)?C.encoding?C.encoding:"":C,payloadType:e[o(1432)](I,Object)?I[o(317)]?I[o(317)]:g:I||g,payload:l,LogIDNew:O},B=e[o(214)](ar,L);if(this[o(951)]&&e[o(1436)](this[o(951)].readyState,this[o(375)]))this[o(951)]&&this[o(951)][o(537)](B),this[o(206)](e.hcxlW,L);else if(this[o(341)+o(469)][o(836)]<this._options[o(850)+o(281)+o(1449)])this[o(341)+o(469)][o(547)](B),this._debug(o(1316),L);else if(e[o(1022)](e[o(745)],e[o(745)]))this[o(341)+"Queue"][o(789)](),this[o(341)+o(469)][o(547)](B);else return iuVcwZ[o(285)](iuVcwZ.qQAbk,typeof _0x7f4e14)?iuVcwZ.uYBbG:"";return{seqID:this._seqId,logID:b,logIDNew:O}}async[r(1225)+"t"](t){let n=r,{url:o}=e.btpOA(t,{}),x=Array[n(728)](o)?o:e[n(1187)](e[n(541)],typeof o)?[o]:[];t&&Object[n(264)](this._options,t),x&&x[n(836)]?this[n(1520)+n(714)]=new Es(x,this[n(1296)][n(1617)+"es"]):this[n(1520)+"tManager"]?.["resetEnd"+n(1095)+n(1526)](),this._pingLossCounter?.[n(1069)+n(1341)](this[n(1296)]["pingLoss"+n(257)]),this[n(646)+n(436)]=!1,this[n(951)]&&e.VPSjG(this[n(951)][n(272)+"te"],this[n(1621)])?this["_disconn"+n(372)](1e3,e.eBaWQ,!0):(this[n(476)]=!0,this[n(1054)]())}async[r(1619)](){let t=r;if(!this[t(1054)+t(1019)]){let n=e[t(224)][t(1357)]("|"),o=0;for(;;){switch(n[o++]){case"0":this._pingLossCounter?.[t(1069)+"nter"]();continue;case"1":this[t(1520)+t(714)]?.[t(1384)+"pointCon"+t(1526)]();continue;case"2":this[t(476)]=!0;continue;case"3":this[t(1054)]();continue;case"4":this["_readyCl"+t(436)]=!1;continue}break}}}[r(426)+r(1037)](t,n){this.on(t,n)}[r(1596)+r(914)](t){let n=r,{type:o}=t;this[n(759)](o,t)}[r(1368)+"entListe"+r(893)](t,n){this[r(253)](t,n)}[r(1584)](){let t={eSIDC:function(n,o){return e[D(1530)](n,o)},YUnJt:"success"};return new Promise((n,o)=>{let x=D,l={TMyur:e.WEzxw};this[x(1456)+x(240)](),this[x(780)+x(1053)+"Id"]=e.aTxZs(setTimeout,this._ping[x(1408)](this),this._options[x(1251)+x(1055)]);let g=()=>{let f=x;t.eSIDC(n,t[f(648)]),this[f(253)](f(1402)+f(999)+"s",g),this.off("ping_onc"+f(960)+"t",p)},p=()=>{let f=x;o(f(1594)),this[f(253)](f(1402)+f(999)+"s",g),this.off(l[f(456)],p)};this.on(x(1402)+"e_success",g),this.on(x(1402)+x(960)+"t",p),this[x(583)]()})}}})(),Y[S(423)+S(719)]=Z[S(423)+S(719)],Y[S(376)+S(1483)]=Z[S(376)+"rorEvent"],Y[S(1366)+"e"]=Z[S(1366)+"e"],Y[S(914)]=Z.Event,Y[S(651)]=Z.FWS,Y[S(726)+S(1205)+S(924)]=Z[S(726)+"MessageE"+S(924)],Y[S(1205)+S(924)]=Z[S(1205)+S(924)],Y[S(442)+"t"]=Z.OpenEvent,Y[S(499)+S(1561)]=Z["Reconnec"+S(1561)],Y[S(1299)+S(719)]=Z.createCloseEvent,Y["createEr"+S(1483)]=Z[S(711)+S(1483)],Y[S(586)+S(741)+"nt"]=Z.createMessageEvent,Y[S(1277)+S(563)]=Z["createOp"+S(563)],Y[S(1497)+S(813)+S(924)]=Z[S(1497)+S(813)+S(924)],Y["decodedF"+S(1379)]=Z["decodedF"+S(1379)],Y.encodeFrame=Z[S(416)+S(1395)];for(In in Z)[S(423)+"oseEvent",S(376)+S(1483),S(1366)+"e",S(914),"FWS",S(726)+"MessageEvent","MessageE"+S(924),S(442)+"t",S(499)+S(1561),"createCl"+S(719),"createEr"+S(1483),S(586)+S(741)+"nt",S(1277)+"enEvent",S(1497)+S(813)+S(924),S(1361)+S(1379),S(416)+"ame"][S(496)](In)===-1&&(Y[In]=Z[In]);var In;Object[S(749)+S(1524)](Y,S(1552)+"le",{value:!0})});var Be=ce((ph,Fi)=>{"use strict";var zi=["nodebuffer","arraybuffer","fragments"],qi=typeof Blob<"u";qi&&zi.push("blob");Fi.exports={BINARY_TYPES:zi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:qi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ft=ce((mh,Mn)=>{"use strict";var{EMPTY_BUFFER:ux}=Be(),Tr=Buffer[Symbol.species];function dx(r,e){if(r.length===0)return ux;if(r.length===1)return r[0];let i=Buffer.allocUnsafe(e),a=0;for(let c=0;c<r.length;c++){let u=r[c];i.set(u,a),a+=u.length}return a<e?new Tr(i.buffer,i.byteOffset,a):i}function Ui(r,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=r[u]^e[u&3]}function Gi(r,e){for(let i=0;i<r.length;i++)r[i]^=e[i&3]}function fx(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Rr(r){if(Rr.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Tr(r):ArrayBuffer.isView(r)?e=new Tr(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Rr.readOnly=!1),e}Mn.exports={concat:dx,mask:Ui,toArrayBuffer:fx,toBuffer:Rr,unmask:Gi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=X("bufferutil");Mn.exports.mask=function(e,i,a,c,u){u<48?Ui(e,i,a,c,u):r.mask(e,i,a,c,u)},Mn.exports.unmask=function(e,i){e.length<32?Gi(e,i):r.unmask(e,i)}}catch{}});var ji=ce((wh,Hi)=>{"use strict";var Ki=Symbol("kDone"),Nr=Symbol("kRun"),Lr=class{constructor(e){this[Ki]=()=>{this.pending--,this[Nr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Nr]()}[Nr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ki])}}};Hi.exports=Lr});var mt=ce((_h,Yi)=>{"use strict";var Ut=X("zlib"),Wi=Ft(),lx=ji(),{kStatusCode:Ji}=Be(),hx=Buffer[Symbol.species],gx=Buffer.from([0,0,255,255]),qn=Symbol("permessage-deflate"),Me=Symbol("total-length"),gt=Symbol("callback"),Je=Symbol("buffers"),pt=Symbol("error"),zn,Or=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,!zn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zn=new lx(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[gt];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){zn.add(c=>{this._decompress(e,i,(u,d)=>{c(),a(u,d)})})}compress(e,i,a){zn.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"?Ut.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Ut.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[qn]=this,this._inflate[Me]=0,this._inflate[Je]=[],this._inflate.on("error",mx),this._inflate.on("data",Vi)}this._inflate[gt]=a,this._inflate.write(e),i&&this._inflate.write(gx),this._inflate.flush(()=>{let u=this._inflate[pt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=Wi.concat(this._inflate[Je],this._inflate[Me]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Me]=0,this._inflate[Je]=[],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"?Ut.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Ut.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Me]=0,this._deflate[Je]=[],this._deflate.on("data",px)}this._deflate[gt]=a,this._deflate.write(e),this._deflate.flush(Ut.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=Wi.concat(this._deflate[Je],this._deflate[Me]);i&&(u=new hx(u.buffer,u.byteOffset,u.length-4)),this._deflate[gt]=null,this._deflate[Me]=0,this._deflate[Je]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};Yi.exports=Or;function px(r){this[Je].push(r),this[Me]+=r.length}function Vi(r){if(this[Me]+=r.length,this[qn]._maxPayload<1||this[Me]<=this[qn]._maxPayload){this[Je].push(r);return}this[pt]=new RangeError("Max payload size exceeded"),this[pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pt][Ji]=1009,this.removeListener("data",Vi),this.reset()}function mx(r){if(this[qn]._inflate=null,this[pt]){this[gt](this[pt]);return}r[Ji]=1007,this[gt](r)}});var wt=ce((yh,Fn)=>{"use strict";var{isUtf8:$i}=X("buffer"),{hasBlob:_x}=Be(),yx=[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 bx(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Br(r){let e=r.length,i=0;for(;i<e;)if((r[i]&128)===0)i++;else if((r[i]&224)===192){if(i+1===e||(r[i+1]&192)!==128||(r[i]&254)===192)return!1;i+=2}else if((r[i]&240)===224){if(i+2>=e||(r[i+1]&192)!==128||(r[i+2]&192)!==128||r[i]===224&&(r[i+1]&224)===128||r[i]===237&&(r[i+1]&224)===160)return!1;i+=3}else if((r[i]&248)===240){if(i+3>=e||(r[i+1]&192)!==128||(r[i+2]&192)!==128||(r[i+3]&192)!==128||r[i]===240&&(r[i+1]&240)===128||r[i]===244&&r[i+1]>143||r[i]>244)return!1;i+=4}else return!1;return!0}function vx(r){return _x&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Fn.exports={isBlob:vx,isValidStatusCode:bx,isValidUTF8:Br,tokenChars:yx};if($i)Fn.exports.isValidUTF8=function(r){return r.length<24?Br(r):$i(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=X("utf-8-validate");Fn.exports.isValidUTF8=function(e){return e.length<32?Br(e):r(e)}}catch{}});var Ur=ce((bh,ro)=>{"use strict";var{Writable:Sx}=X("stream"),Xi=mt(),{BINARY_TYPES:Ex,EMPTY_BUFFER:Zi,kStatusCode:Cx,kWebSocket:Ax}=Be(),{concat:Mr,toArrayBuffer:Px,unmask:kx}=Ft(),{isValidStatusCode:Dx,isValidUTF8:Qi}=wt(),Un=Buffer[Symbol.species],he=0,eo=1,to=2,no=3,zr=4,qr=5,Gn=6,Fr=class extends Sx{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Ex[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ax]=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 Un(a.buffer,a.byteOffset+e,a.length-e),new Un(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 Un(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 eo:this.getPayloadLength16(e);break;case to:this.getPayloadLength64(e);break;case no:this.getMask();break;case zr:this.getData(e);break;case qr:case Gn: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[Xi.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=eo:this._payloadLength===127?this._state=to: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=no:this._state=zr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=zr}getData(e){let i=Zi;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&&kx(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=qr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[Xi.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=Mr(a,i):this._binaryType==="arraybuffer"?c=Px(Mr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=he):(this._state=Gn,setImmediate(()=>{this.emit("message",c,!0),this._state=he,this.startLoop(e)}))}else{let c=Mr(a,i);if(!this._skipUTF8Validation&&!Qi(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===qr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=he):(this._state=Gn,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,Zi),this.end();else{let a=e.readUInt16BE(0);if(!Dx(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new Un(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Qi(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=Gn,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[Cx]=c,d}};ro.exports=Fr});var Hr=ce((Sh,oo)=>{"use strict";var{Duplex:vh}=X("stream"),{randomFillSync:Ix}=X("crypto"),so=mt(),{EMPTY_BUFFER:Tx,kWebSocket:Rx,NOOP:Nx}=Be(),{isBlob:_t,isValidStatusCode:Lx}=wt(),{mask:io,toBuffer:Qe}=Ft(),ge=Symbol("kByteLength"),Ox=Buffer.alloc(4),Kn=8*1024,et,yt=Kn,_e=0,Bx=1,Mx=2,Gr=class r{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=Nx,this[Rx]=void 0}static frame(e,i){let a,c=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||Ox,i.generateMask?i.generateMask(a):(yt===Kn&&(et===void 0&&(et=Buffer.alloc(Kn)),Ix(et,0,Kn),yt=0),a[0]=et[yt++],a[1]=et[yt++],a[2]=et[yt++],a[3]=et[yt++]),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?(io(e,a,w,u,h),[w]):(io(e,a,e,0,h),[w,e])):[w,e]}close(e,i,a,c){let u;if(e===void 0)u=Tx;else{if(typeof e!="number"||!Lx(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(r.frame(u,d),c)}ping(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):_t(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};_t(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(r.frame(e,d),a)}pong(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):_t(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};_t(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(r.frame(e,d),a)}send(e,i,a){let c=this._extensions[so.extensionName],u=i.binary?2:1,d=i.compress,h,m;typeof e=="string"?(h=Buffer.byteLength(e),m=!1):_t(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};_t(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=Mx,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let h=new Error("The socket was closed while the blob was being read");process.nextTick(Kr,this,h,c);return}this._bufferedBytes-=a[ge];let d=Qe(u);i?this.dispatch(d,i,a,c):(this._state=_e,this.sendFrame(r.frame(d,a),c),this.dequeue())}).catch(u=>{process.nextTick(zx,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(r.frame(e,a),c);return}let u=this._extensions[so.extensionName];this._bufferedBytes+=a[ge],this._state=Bx,u.compress(e,a.fin,(d,h)=>{if(this._socket.destroyed){let m=new Error("The socket was closed while data was being compressed");Kr(this,m,c);return}this._bufferedBytes-=a[ge],this._state=_e,a.readOnly=!1,this.sendFrame(r.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)}};oo.exports=Gr;function Kr(r,e,i){typeof i=="function"&&i(e);for(let a=0;a<r._queue.length;a++){let c=r._queue[a],u=c[c.length-1];typeof u=="function"&&u(e)}}function zx(r,e,i){Kr(r,e,i),r.onerror(e)}});var po=ce((Eh,go)=>{"use strict";var{kForOnEventAttribute:Gt,kListener:jr}=Be(),ao=Symbol("kCode"),co=Symbol("kData"),xo=Symbol("kError"),uo=Symbol("kMessage"),fo=Symbol("kReason"),bt=Symbol("kTarget"),lo=Symbol("kType"),ho=Symbol("kWasClean"),ze=class{constructor(e){this[bt]=null,this[lo]=e}get target(){return this[bt]}get type(){return this[lo]}};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[fo]=i.reason===void 0?"":i.reason,this[ho]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[ao]}get reason(){return this[fo]}get wasClean(){return this[ho]}};Object.defineProperty(nt.prototype,"code",{enumerable:!0});Object.defineProperty(nt.prototype,"reason",{enumerable:!0});Object.defineProperty(nt.prototype,"wasClean",{enumerable:!0});var vt=class extends ze{constructor(e,i={}){super(e),this[xo]=i.error===void 0?null:i.error,this[uo]=i.message===void 0?"":i.message}get error(){return this[xo]}get message(){return this[uo]}};Object.defineProperty(vt.prototype,"error",{enumerable:!0});Object.defineProperty(vt.prototype,"message",{enumerable:!0});var Kt=class extends ze{constructor(e,i={}){super(e),this[co]=i.data===void 0?null:i.data}get data(){return this[co]}};Object.defineProperty(Kt.prototype,"data",{enumerable:!0});var qx={addEventListener(r,e,i={}){for(let c of this.listeners(r))if(!i[Gt]&&c[jr]===e&&!c[Gt])return;let a;if(r==="message")a=function(u,d){let h=new Kt("message",{data:d?u:u.toString()});h[bt]=this,Hn(e,this,h)};else if(r==="close")a=function(u,d){let h=new nt("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});h[bt]=this,Hn(e,this,h)};else if(r==="error")a=function(u){let d=new vt("error",{error:u,message:u.message});d[bt]=this,Hn(e,this,d)};else if(r==="open")a=function(){let u=new ze("open");u[bt]=this,Hn(e,this,u)};else return;a[Gt]=!!i[Gt],a[jr]=e,i.once?this.once(r,a):this.on(r,a)},removeEventListener(r,e){for(let i of this.listeners(r))if(i[jr]===e&&!i[Gt]){this.removeListener(r,i);break}}};go.exports={CloseEvent:nt,ErrorEvent:vt,Event:ze,EventTarget:qx,MessageEvent:Kt};function Hn(r,e,i){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,i):r.call(e,i)}});var jn=ce((Ch,mo)=>{"use strict";var{tokenChars:Ht}=wt();function Pe(r,e,i){r[e]===void 0?r[e]=[i]:r[e].push(i)}function Fx(r){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,d,h,m=-1,w=-1,_=-1,y=0;for(;y<r.length;y++)if(w=r.charCodeAt(y),d===void 0)if(_===-1&&Ht[w]===1)m===-1&&(m=y);else if(y!==0&&(w===32||w===9))_===-1&&m!==-1&&(_=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);_===-1&&(_=y);let k=r.slice(m,_);w===44?(Pe(e,k,i),i=Object.create(null)):d=k,m=_=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);else if(h===void 0)if(_===-1&&Ht[w]===1)m===-1&&(m=y);else if(w===32||w===9)_===-1&&m!==-1&&(_=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);_===-1&&(_=y),Pe(i,r.slice(m,_),!0),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),m=_=-1}else if(w===61&&m!==-1&&_===-1)h=r.slice(m,y),m=_=-1;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(c){if(Ht[w]!==1)throw new SyntaxError(`Unexpected character at index ${y}`);m===-1?m=y:a||(a=!0),c=!1}else if(u)if(Ht[w]===1)m===-1&&(m=y);else if(w===34&&m!==-1)u=!1,_=y;else if(w===92)c=!0;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(w===34&&r.charCodeAt(y-1)===61)u=!0;else if(_===-1&&Ht[w]===1)m===-1&&(m=y);else if(m!==-1&&(w===32||w===9))_===-1&&(_=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);_===-1&&(_=y);let k=r.slice(m,_);a&&(k=k.replace(/\\/g,""),a=!1),Pe(i,h,k),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),h=void 0,m=_=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);if(m===-1||u||w===32||w===9)throw new SyntaxError("Unexpected end of input");_===-1&&(_=y);let A=r.slice(m,_);return d===void 0?Pe(e,A,i):(h===void 0?Pe(i,A,!0):a?Pe(i,h,A.replace(/\\/g,"")):Pe(i,h,A),Pe(e,d,i)),e}function Ux(r){return Object.keys(r).map(e=>{let i=r[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(", ")}mo.exports={format:Ux,parse:Fx}});var Yn=ce((kh,Do)=>{"use strict";var Gx=X("events"),Kx=X("https"),Hx=X("http"),yo=X("net"),jx=X("tls"),{randomBytes:Wx,createHash:Jx}=X("crypto"),{Duplex:Ah,Readable:Ph}=X("stream"),{URL:Wr}=X("url"),Ve=mt(),Vx=Ur(),Yx=Hr(),{isBlob:$x}=wt(),{BINARY_TYPES:wo,CLOSE_TIMEOUT:Xx,EMPTY_BUFFER:Wn,GUID:Zx,kForOnEventAttribute:Jr,kListener:Qx,kStatusCode:eu,kWebSocket:ee,NOOP:bo}=Be(),{EventTarget:{addEventListener:tu,removeEventListener:nu}}=po(),{format:ru,parse:su}=jn(),{toBuffer:iu}=Ft(),vo=Symbol("kAborted"),Vr=[8,13],qe=["CONNECTING","OPEN","CLOSING","CLOSED"],ou=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,K=class r extends Gx{constructor(e,i,a){super(),this._binaryType=wo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.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]),So(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wo.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 Vx({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new Yx(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[ee]=this,u[ee]=this,e[ee]=this,c.on("conclude",xu),c.on("drain",uu),c.on("error",du),c.on("message",fu),c.on("ping",lu),c.on("pong",hu),u.onerror=gu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",Ao),e.on("data",Vn),e.on("end",Po),e.on("error",ko),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ve.extensionName]&&this._extensions[Ve.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,i){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,i,!this._isServer,a=>{a||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Co(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,i,a){if(this.readyState===r.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!==r.OPEN){Yr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Wn,i,a)}pong(e,i,a){if(this.readyState===r.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!==r.OPEN){Yr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Wn,i,a)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,i,a){if(this.readyState===r.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!==r.OPEN){Yr(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[Ve.extensionName]||(c.compress=!1),this._sender.send(e||Wn,c,a)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(K,"CONNECTING",{enumerable:!0,value:qe.indexOf("CONNECTING")});Object.defineProperty(K.prototype,"CONNECTING",{enumerable:!0,value:qe.indexOf("CONNECTING")});Object.defineProperty(K,"OPEN",{enumerable:!0,value:qe.indexOf("OPEN")});Object.defineProperty(K.prototype,"OPEN",{enumerable:!0,value:qe.indexOf("OPEN")});Object.defineProperty(K,"CLOSING",{enumerable:!0,value:qe.indexOf("CLOSING")});Object.defineProperty(K.prototype,"CLOSING",{enumerable:!0,value:qe.indexOf("CLOSING")});Object.defineProperty(K,"CLOSED",{enumerable:!0,value:qe.indexOf("CLOSED")});Object.defineProperty(K.prototype,"CLOSED",{enumerable:!0,value:qe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(K.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(K.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Jr])return e[Qx];return null},set(e){for(let i of this.listeners(r))if(i[Jr]){this.removeListener(r,i);break}typeof e=="function"&&this.addEventListener(r,e,{[Jr]:!0})}})});K.prototype.addEventListener=tu;K.prototype.removeEventListener=nu;Do.exports=K;function So(r,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Xx,protocolVersion:Vr[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(r._autoPong=c.autoPong,r._closeTimeout=c.closeTimeout,!Vr.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${Vr.join(", ")})`);let u;if(e instanceof Wr)u=e;else try{u=new Wr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}u.protocol==="http:"?u.protocol="ws:":u.protocol==="https:"&&(u.protocol="wss:"),r._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 R=new SyntaxError(m);if(r._redirects===0)throw R;Jn(r,R);return}let w=d?443:80,_=Wx(16).toString("base64"),y=d?Kx.request:Hx.request,A=new Set,k;if(c.createConnection=c.createConnection||(d?cu:au),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":_,Connection:"Upgrade",Upgrade:"websocket"},c.path=u.pathname+u.search,c.timeout=c.handshakeTimeout,c.perMessageDeflate&&(k=new Ve({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=ru({[Ve.extensionName]:k.offer()})),i.length){for(let R of i){if(typeof R!="string"||!ou.test(R)||A.has(R))throw new SyntaxError("An invalid or duplicated subprotocol was specified");A.add(R)}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 R=c.path.split(":");c.socketPath=R[0],c.path=R[1]}let T;if(c.followRedirects){if(r._redirects===0){r._originalIpc=h,r._originalSecure=d,r._originalHostOrSocketPath=h?c.socketPath:u.host;let R=a&&a.headers;if(a={...a,headers:{}},R)for(let[q,oe]of Object.entries(R))a.headers[q.toLowerCase()]=oe}else if(r.listenerCount("redirect")===0){let R=h?r._originalIpc?c.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:u.host===r._originalHostOrSocketPath;(!R||r._originalSecure&&!d)&&(delete c.headers.authorization,delete c.headers.cookie,R||delete c.headers.host,c.auth=void 0)}c.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(c.auth).toString("base64")),T=r._req=y(c),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=y(c);c.timeout&&T.on("timeout",()=>{fe(r,T,"Opening handshake has timed out")}),T.on("error",R=>{T===null||T[vo]||(T=r._req=null,Jn(r,R))}),T.on("response",R=>{let q=R.headers.location,oe=R.statusCode;if(q&&c.followRedirects&&oe>=300&&oe<400){if(++r._redirects>c.maxRedirects){fe(r,T,"Maximum redirects exceeded");return}T.abort();let te;try{te=new Wr(q,e)}catch{let xe=new SyntaxError(`Invalid URL: ${q}`);Jn(r,xe);return}So(r,te,i,a)}else r.emit("unexpected-response",T,R)||fe(r,T,`Unexpected server response: ${R.statusCode}`)}),T.on("upgrade",(R,q,oe)=>{if(r.emit("upgrade",R),r.readyState!==K.CONNECTING)return;T=r._req=null;let te=R.headers.upgrade;if(te===void 0||te.toLowerCase()!=="websocket"){fe(r,q,"Invalid Upgrade header");return}let ye=Jx("sha1").update(_+Zx).digest("base64");if(R.headers["sec-websocket-accept"]!==ye){fe(r,q,"Invalid Sec-WebSocket-Accept header");return}let xe=R.headers["sec-websocket-protocol"],P;if(xe!==void 0?A.size?A.has(xe)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":A.size&&(P="Server sent no subprotocol"),P){fe(r,q,P);return}xe&&(r._protocol=xe);let F=R.headers["sec-websocket-extensions"];if(F!==void 0){if(!k){fe(r,q,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let J;try{J=su(F)}catch{fe(r,q,"Invalid Sec-WebSocket-Extensions header");return}let ne=Object.keys(J);if(ne.length!==1||ne[0]!==Ve.extensionName){fe(r,q,"Server indicated an extension that was not requested");return}try{k.accept(J[Ve.extensionName])}catch{fe(r,q,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Ve.extensionName]=k}r.setSocket(q,oe,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(T,r):T.end()}function Jn(r,e){r._readyState=K.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function au(r){return r.path=r.socketPath,yo.connect(r)}function cu(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=yo.isIP(r.host)?"":r.host),jx.connect(r)}function fe(r,e,i){r._readyState=K.CLOSING;let a=new Error(i);Error.captureStackTrace(a,fe),e.setHeader?(e[vo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Jn,r,a)):(e.destroy(a),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Yr(r,e,i){if(e){let a=$x(e)?e.size:iu(e).length;r._socket?r._sender._bufferedBytes+=a:r._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${r.readyState} (${qe[r.readyState]})`);process.nextTick(i,a)}}function xu(r,e){let i=this[ee];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=r,i._socket[ee]!==void 0&&(i._socket.removeListener("data",Vn),process.nextTick(Eo,i._socket),r===1005?i.close():i.close(r,e))}function uu(){let r=this[ee];r.isPaused||r._socket.resume()}function du(r){let e=this[ee];e._socket[ee]!==void 0&&(e._socket.removeListener("data",Vn),process.nextTick(Eo,e._socket),e.close(r[eu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function _o(){this[ee].emitClose()}function fu(r,e){this[ee].emit("message",r,e)}function lu(r){let e=this[ee];e._autoPong&&e.pong(r,!this._isServer,bo),e.emit("ping",r)}function hu(r){this[ee].emit("pong",r)}function Eo(r){r.resume()}function gu(r){let e=this[ee];e.readyState!==K.CLOSED&&(e.readyState===K.OPEN&&(e._readyState=K.CLOSING,Co(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Co(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Ao(){let r=this[ee];if(this.removeListener("close",Ao),this.removeListener("data",Vn),this.removeListener("end",Po),r._readyState=K.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ee]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",_o),r._receiver.on("finish",_o))}function Vn(r){this[ee]._receiver.write(r)||this.pause()}function Po(){let r=this[ee];r._readyState=K.CLOSING,r._receiver.end(),this.end()}function ko(){let r=this[ee];this.removeListener("error",ko),this.on("error",bo),r&&(r._readyState=K.CLOSING,this.destroy())}});var No=ce((Ih,Ro)=>{"use strict";var Dh=Yn(),{Duplex:pu}=X("stream");function Io(r){r.emit("close")}function mu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function To(r){this.removeListener("error",To),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function wu(r,e){let i=!0,a=new pu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(u,d){let h=!d&&a._readableState.objectMode?u.toString():u;a.push(h)||r.pause()}),r.once("error",function(u){a.destroyed||(i=!1,a.destroy(u))}),r.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(c,u){if(r.readyState===r.CLOSED){u(c),process.nextTick(Io,a);return}let d=!1;r.once("error",function(m){d=!0,u(m)}),r.once("close",function(){d||u(c),process.nextTick(Io,a)}),i&&r.terminate()},a._final=function(c){if(r.readyState===r.CONNECTING){r.once("open",function(){a._final(c)});return}r._socket!==null&&(r._socket._writableState.finished?(c(),a._readableState.endEmitted&&a.destroy()):(r._socket.once("finish",function(){c()}),r.close()))},a._read=function(){r.isPaused&&r.resume()},a._write=function(c,u,d){if(r.readyState===r.CONNECTING){r.once("open",function(){a._write(c,u,d)});return}r.send(c,d)},a.on("end",mu),a.on("error",To),a}Ro.exports=wu});var $r=ce((Th,Lo)=>{"use strict";var{tokenChars:_u}=wt();function yu(r){let e=new Set,i=-1,a=-1,c=0;for(c;c<r.length;c++){let d=r.charCodeAt(c);if(a===-1&&_u[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=r.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=r.slice(i,c);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return e.add(u),e}Lo.exports={parse:yu}});var Uo=ce((Nh,Fo)=>{"use strict";var bu=X("events"),$n=X("http"),{Duplex:Rh}=X("stream"),{createHash:vu}=X("crypto"),Oo=jn(),rt=mt(),Su=$r(),Eu=Yn(),{CLOSE_TIMEOUT:Cu,GUID:Au,kWebSocket:Pu}=Be(),ku=/^[+/0-9A-Za-z]{22}==$/,Bo=0,Mo=1,qo=2,Xr=class extends bu{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Cu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Eu,...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=$n.createServer((a,c)=>{let u=$n.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=Du(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=Bo}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===qo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(jt,this);return}if(e&&this.once("close",e),this._state!==Mo)if(this._state=Mo,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(jt,this):process.nextTick(jt,this);else{let i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{jt(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",zo);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||!ku.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)){Wt(i,400);return}let m=e.headers["sec-websocket-protocol"],w=new Set;if(m!==void 0)try{w=Su.parse(m)}catch{st(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let _=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&_!==void 0){let A=new rt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let k=Oo.parse(_);k[rt.extensionName]&&(A.accept(k[rt.extensionName]),y[rt.extensionName]=A)}catch{st(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let A={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(A,(k,T,R,q)=>{if(!k)return Wt(i,T||401,R,q);this.completeUpgrade(y,u,w,e,i,a,c)});return}if(!this.options.verifyClient(A))return Wt(i,401)}this.completeUpgrade(y,u,w,e,i,a,c)}completeUpgrade(e,i,a,c,u,d,h){if(!u.readable||!u.writable)return u.destroy();if(u[Pu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Bo)return Wt(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${vu("sha1").update(i+Au).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(a.size){let y=this.options.handleProtocols?this.options.handleProtocols(a,c):a.values().next().value;y&&(w.push(`Sec-WebSocket-Protocol: ${y}`),_._protocol=y)}if(e[rt.extensionName]){let y=e[rt.extensionName].params,A=Oo.format({[rt.extensionName]:[y]});w.push(`Sec-WebSocket-Extensions: ${A}`),_._extensions=e}this.emit("headers",w,c),u.write(w.concat(`\r
|
|
8
|
+
var sa=Object.create;var Dn=Object.defineProperty;var ia=Object.getOwnPropertyDescriptor;var oa=Object.getOwnPropertyNames;var aa=Object.getPrototypeOf,ca=Object.prototype.hasOwnProperty;var P=(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 Q=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ln=(n,e)=>{for(var t in e)Dn(n,t,{get:e[t],enumerable:!0})},da=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oa(e))!ca.call(n,s)&&s!==t&&Dn(n,s,{get:()=>e[s],enumerable:!(r=ia(e,s))||r.enumerable});return n};var ue=(n,e,t)=>(t=n!=null?sa(aa(n)):{},da(e||!n||!n.__esModule?Dn(t,"default",{value:n,enumerable:!0}):t,n));import{chmod as la,mkdir as ua,readFile as fa,rename as rs,writeFile as ss}from"node:fs/promises";import{dirname as ha}from"node:path";async function De(n){try{let e=await fa(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function It(n,e,t){await ua(ha(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 ss(s,r,{encoding:"utf8",mode:t.mode}):await ss(s,r,"utf8"),await rs(s,n),t?.mode!==void 0&&await la(n,t.mode)}catch(i){await rs(s,s).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(s,{force:!0}).catch(()=>{}),i}}var Tt=Q(()=>{"use strict"});function as(n){return Pt[is]<=Pt[n]}function Mn(n){os={...n}}function Rt(n,e,t,r){if(Pt[n]<Pt[is])return;let s=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:t,...os,...r});n==="error"||n==="warn"?pa.write(`${s}
|
|
10
|
+
`):ga.write(`${s}
|
|
11
|
+
`)}function w(n){return{debug:(e,t)=>Rt("debug",n,e,t),info:(e,t)=>Rt("info",n,e,t),warn:(e,t)=>Rt("warn",n,e,t),error:(e,t)=>Rt("error",n,e,t),child:e=>w(`${n}.${e}`)}}var Pt,is,ga,pa,os,k=Q(()=>{"use strict";Pt={debug:10,info:20,warn:30,error:40},is=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),ga=process.stdout,pa=process.stderr,os={}});import{homedir as ma}from"node:os";import{join as N}from"node:path";function T(n){let e=n??ma(),t=N(e,".coze"),r=N(t,"bridge"),s=N(r,"lib");return{cozeRoot:t,bridgeRoot:r,libDir:s,libEntry:N(s,"index.js"),pidFile:N(r,"bridge.pid"),portFile:N(r,"bridge.port"),tokenFile:N(r,"bridge.token"),logFile:N(r,"bridge.log"),installLock:N(r,"install.lock"),configFile:N(r,"config.json"),agentsRoot:N(t,"agents")}}function se(n,e=T()){let t=N(e.agentsRoot,n);return{root:t,config:N(t,"config.json"),workspace:N(t,"workspace"),logs:N(t,"logs")}}var U=Q(()=>{"use strict"});var Ot={};Ln(Ot,{AGENT_CONFIG_FILE_MODE:()=>At,enforceAgentConfigMode:()=>ya,loadAgentConfig:()=>$,persistAgentSessions:()=>Bn,persistAgentSkills:()=>Ct,saveAgentConfig:()=>K});import{chmod as _a,stat as wa}from"node:fs/promises";function $(n,e){return De(se(n,e).config)}function K(n,e){return It(se(n.agentId,e).config,n,{mode:At})}async function ya(n,e){if(process.platform==="win32")return;let t=se(n,e).config;try{let r=await wa(t);if(!r.isFile())return;let s=r.mode&511;s!==At&&(await _a(t,At),cs.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(r){if(r.code==="ENOENT")return;cs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(r)})}}async function Bn(n,e,t){let r=await $(n,t);r&&(r.sessions=Object.fromEntries(e),await K(r,t))}async function Ct(n,e,t){let r=await $(n,t);r&&(r.skills=e,await K(r,t))}var cs,At,fe=Q(()=>{"use strict";Tt();k();U();cs=w("agent-config"),At=384});function Yc(){return Xs||(Xs=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Zc(){return Ys||(Ys=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function ed(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(G(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Zs.set(t,n)}).catch(()=>{}),Vn.set(e,n),e}function td(n){if(jn.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)});jn.set(n,e)}function ti(n){Jn=n(Jn)}function nd(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let r=n.call(ut(this),e,...t);return ei.set(r,e.sort?e.sort():[e]),G(r)}:Zc().includes(n)?function(...e){return n.apply(ut(this),e),G(Zs.get(this))}:function(...e){return G(n.apply(ut(this),e))}}function rd(n){return typeof n=="function"?nd(n):(n instanceof IDBTransaction&&td(n),Xc(n,Yc())?new Proxy(n,Jn):n)}function G(n){if(n instanceof IDBRequest)return ed(n);if(Wn.has(n))return Wn.get(n);let e=rd(n);return e!==n&&(Wn.set(n,e),Vn.set(e,n)),e}var Xc,Xs,Ys,Zs,jn,ei,Wn,Vn,Jn,ut,Qn=Q(()=>{Xc=(n,e)=>e.some(t=>n instanceof t);Zs=new WeakMap,jn=new WeakMap,ei=new WeakMap,Wn=new WeakMap,Vn=new WeakMap;Jn={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return jn.get(n);if(e==="objectStoreNames")return n.objectStoreNames||ei.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return G(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}};ut=n=>Vn.get(n)});var ri={};Ln(ri,{deleteDB:()=>id,openDB:()=>sd,unwrap:()=>ut,wrap:()=>G});function sd(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){let o=indexedDB.open(n,e),a=G(o);return r&&o.addEventListener("upgradeneeded",c=>{r(G(o.result),c.oldVersion,c.newVersion,G(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function id(n,{blocked:e}={}){let t=indexedDB.deleteDatabase(n);return e&&t.addEventListener("blocked",()=>e()),G(t).then(()=>{})}function ni(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Kn.get(e))return Kn.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,s=ad.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||od.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),d=c.store;return r&&(d=d.index(a.shift())),(await Promise.all([d[t](...a),s&&c.done]))[0]};return Kn.set(e,i),i}var od,ad,Kn,si=Q(()=>{Qn();Qn();od=["get","getKey","getAll","getAllKeys","count"],ad=["put","add","delete","clear"],Kn=new Map;ti(n=>({...n,get:(e,t,r)=>ni(e,t)||n.get(e,t,r),has:(e,t)=>!!ni(e,t)||n.has(e,t)}))});var ae=F((Rp,Ci)=>{"use strict";var Pi=["nodebuffer","arraybuffer","fragments"],Ai=typeof Blob<"u";Ai&&Pi.push("blob");Ci.exports={BINARY_TYPES:Pi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ai,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _t=F((Pp,an)=>{"use strict";var{EMPTY_BUFFER:ll}=ae(),yr=Buffer[Symbol.species];function ul(n,e){if(n.length===0)return ll;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 yr(t.buffer,t.byteOffset,r):t}function Oi(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ni(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function fl(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Sr(n){if(Sr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new yr(n):ArrayBuffer.isView(n)?e=new yr(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Sr.readOnly=!1),e}an.exports={concat:ul,mask:Oi,toArrayBuffer:fl,toBuffer:Sr,unmask:Ni};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=P("bufferutil");an.exports.mask=function(e,t,r,s,i){i<48?Oi(e,t,r,s,i):n.mask(e,t,r,s,i)},an.exports.unmask=function(e,t){e.length<32?Ni(e,t):n.unmask(e,t)}}catch{}});var Li=F((Ap,Di)=>{"use strict";var bi=Symbol("kDone"),Er=Symbol("kRun"),vr=class{constructor(e){this[bi]=()=>{this.pending--,this[Er]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Er]()}[Er](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bi])}}};Di.exports=vr});var Je=F((Cp,Ui)=>{"use strict";var wt=P("zlib"),Mi=_t(),hl=Li(),{kStatusCode:Bi}=ae(),gl=Buffer[Symbol.species],pl=Buffer.from([0,0,255,255]),dn=Symbol("permessage-deflate"),ce=Symbol("total-length"),We=Symbol("callback"),we=Symbol("buffers"),je=Symbol("error"),cn,kr=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,!cn){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;cn=new hl(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[We];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){cn.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){cn.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"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[dn]=this,this._inflate[ce]=0,this._inflate[we]=[],this._inflate.on("error",_l),this._inflate.on("data",Fi)}this._inflate[We]=r,this._inflate.write(e),t&&this._inflate.write(pl),this._inflate.flush(()=>{let i=this._inflate[je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Mi.concat(this._inflate[we],this._inflate[ce]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ce]=0,this._inflate[we]=[],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"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ce]=0,this._deflate[we]=[],this._deflate.on("data",ml)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Mi.concat(this._deflate[we],this._deflate[ce]);t&&(i=new gl(i.buffer,i.byteOffset,i.length-4)),this._deflate[We]=null,this._deflate[ce]=0,this._deflate[we]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ui.exports=kr;function ml(n){this[we].push(n),this[ce]+=n.length}function Fi(n){if(this[ce]+=n.length,this[dn]._maxPayload<1||this[ce]<=this[dn]._maxPayload){this[we].push(n);return}this[je]=new RangeError("Max payload size exceeded"),this[je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[je][Bi]=1009,this.removeListener("data",Fi),this.reset()}function _l(n){if(this[dn]._inflate=null,this[je]){this[We](this[je]);return}n[Bi]=1007,this[We](n)}});var Ve=F((Op,ln)=>{"use strict";var{isUtf8:$i}=P("buffer"),{hasBlob:wl}=ae(),yl=[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 Sl(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function xr(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 El(n){return wl&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}ln.exports={isBlob:El,isValidStatusCode:Sl,isValidUTF8:xr,tokenChars:yl};if($i)ln.exports.isValidUTF8=function(n){return n.length<24?xr(n):$i(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=P("utf-8-validate");ln.exports.isValidUTF8=function(e){return e.length<32?xr(e):n(e)}}catch{}});var Ar=F((Np,Ji)=>{"use strict";var{Writable:vl}=P("stream"),zi=Je(),{BINARY_TYPES:kl,EMPTY_BUFFER:qi,kStatusCode:xl,kWebSocket:Il}=ae(),{concat:Ir,toArrayBuffer:Tl,unmask:Rl}=_t(),{isValidStatusCode:Pl,isValidUTF8:Gi}=Ve(),un=Buffer[Symbol.species],W=0,Hi=1,Wi=2,ji=3,Tr=4,Rr=5,fn=6,Pr=class extends vl{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kl[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Il]=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=W}_write(e,t,r){if(this._opcode===8&&this._state==W)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 un(r.buffer,r.byteOffset+e,r.length-e),new un(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 un(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 W:this.getInfo(e);break;case Hi:this.getPayloadLength16(e);break;case Wi:this.getPayloadLength64(e);break;case ji:this.getMask();break;case Tr:this.getData(e);break;case Rr:case fn: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[zi.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=Hi:this._payloadLength===127?this._state=Wi: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=ji:this._state=Tr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Tr}getData(e){let t=qi;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&&Rl(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Rr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[zi.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===W&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=W;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=Ir(r,t):this._binaryType==="arraybuffer"?s=Tl(Ir(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=W):(this._state=fn,setImmediate(()=>{this.emit("message",s,!0),this._state=W,this.startLoop(e)}))}else{let s=Ir(r,t);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Rr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=W):(this._state=fn,setImmediate(()=>{this.emit("message",s,!1),this._state=W,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,qi),this.end();else{let r=e.readUInt16BE(0);if(!Pl(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new un(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Gi(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=W;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=W):(this._state=fn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=W,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[xl]=s,o}};Ji.exports=Pr});var Nr=F((Dp,Ki)=>{"use strict";var{Duplex:bp}=P("stream"),{randomFillSync:Al}=P("crypto"),Vi=Je(),{EMPTY_BUFFER:Cl,kWebSocket:Ol,NOOP:Nl}=ae(),{isBlob:Qe,isValidStatusCode:bl}=Ve(),{mask:Qi,toBuffer:Re}=_t(),j=Symbol("kByteLength"),Dl=Buffer.alloc(4),hn=8*1024,Pe,Ke=hn,Y=0,Ll=1,Ml=2,Cr=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=Y,this.onerror=Nl,this[Ol]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Dl,t.generateMask?t.generateMask(r):(Ke===hn&&(Pe===void 0&&(Pe=Buffer.alloc(hn)),Al(Pe,0,hn),Ke=0),r[0]=Pe[Ke++],r[1]=Pe[Ke++],r[2]=Pe[Ke++],r[3]=Pe[Ke++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[j]!==void 0?a=t[j]:(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 d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Qi(e,r,d,i,a),[d]):(Qi(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=Cl;else{if(typeof e!="number"||!bl(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={[j]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Y?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):Qe(e)?(s=e.size,i=!1):(e=Re(e),s=e.length,i=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Y?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):Qe(e)?(s=e.size,i=!1):(e=Re(e),s=e.length,i=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Y?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Vi.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Qe(e)?(a=e.size,c=!1):(e=Re(e),a=e.length,c=Re.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 d={[j]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Y?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[j],this._state=Ml,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Or,this,a,s);return}this._bufferedBytes-=r[j];let o=Re(i);t?this.dispatch(o,t,r,s):(this._state=Y,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Bl,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Vi.extensionName];this._bufferedBytes+=r[j],this._state=Ll,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Or(this,c,s);return}this._bufferedBytes-=r[j],this._state=Y,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Y&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][j],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][j],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)}};Ki.exports=Cr;function Or(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 Bl(n,e,t){Or(n,e,t),n.onerror(e)}});var io=F((Lp,so)=>{"use strict";var{kForOnEventAttribute:yt,kListener:br}=ae(),Xi=Symbol("kCode"),Yi=Symbol("kData"),Zi=Symbol("kError"),eo=Symbol("kMessage"),to=Symbol("kReason"),Xe=Symbol("kTarget"),no=Symbol("kType"),ro=Symbol("kWasClean"),de=class{constructor(e){this[Xe]=null,this[no]=e}get target(){return this[Xe]}get type(){return this[no]}};Object.defineProperty(de.prototype,"target",{enumerable:!0});Object.defineProperty(de.prototype,"type",{enumerable:!0});var Ae=class extends de{constructor(e,t={}){super(e),this[Xi]=t.code===void 0?0:t.code,this[to]=t.reason===void 0?"":t.reason,this[ro]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Xi]}get reason(){return this[to]}get wasClean(){return this[ro]}};Object.defineProperty(Ae.prototype,"code",{enumerable:!0});Object.defineProperty(Ae.prototype,"reason",{enumerable:!0});Object.defineProperty(Ae.prototype,"wasClean",{enumerable:!0});var Ye=class extends de{constructor(e,t={}){super(e),this[Zi]=t.error===void 0?null:t.error,this[eo]=t.message===void 0?"":t.message}get error(){return this[Zi]}get message(){return this[eo]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var St=class extends de{constructor(e,t={}){super(e),this[Yi]=t.data===void 0?null:t.data}get data(){return this[Yi]}};Object.defineProperty(St.prototype,"data",{enumerable:!0});var Fl={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[yt]&&s[br]===e&&!s[yt])return;let r;if(n==="message")r=function(i,o){let a=new St("message",{data:o?i:i.toString()});a[Xe]=this,gn(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ae("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Xe]=this,gn(e,this,a)};else if(n==="error")r=function(i){let o=new Ye("error",{error:i,message:i.message});o[Xe]=this,gn(e,this,o)};else if(n==="open")r=function(){let i=new de("open");i[Xe]=this,gn(e,this,i)};else return;r[yt]=!!t[yt],r[br]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[br]===e&&!t[yt]){this.removeListener(n,t);break}}};so.exports={CloseEvent:Ae,ErrorEvent:Ye,Event:de,EventTarget:Fl,MessageEvent:St};function gn(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var pn=F((Mp,oo)=>{"use strict";var{tokenChars:Et}=Ve();function ne(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Ul(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<n.length;u++)if(d=n.charCodeAt(u),o===void 0)if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let g=n.slice(c,l);d===44?(ne(e,g,t),t=Object.create(null)):o=g,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),ne(t,n.slice(c,l),!0),d===44&&(ne(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=n.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Et[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Et[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&n.charCodeAt(u-1)===61)i=!0;else if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let g=n.slice(c,l);r&&(g=g.replace(/\\/g,""),r=!1),ne(t,a,g),d===44&&(ne(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let f=n.slice(c,l);return o===void 0?ne(e,f,t):(a===void 0?ne(t,f,!0):r?ne(t,a,f.replace(/\\/g,"")):ne(t,a,f),ne(e,o,t)),e}function $l(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(", ")}oo.exports={format:$l,parse:Ul}});var yn=F((Up,yo)=>{"use strict";var zl=P("events"),ql=P("https"),Gl=P("http"),lo=P("net"),Hl=P("tls"),{randomBytes:Wl,createHash:jl}=P("crypto"),{Duplex:Bp,Readable:Fp}=P("stream"),{URL:Dr}=P("url"),ye=Je(),Jl=Ar(),Vl=Nr(),{isBlob:Ql}=Ve(),{BINARY_TYPES:ao,CLOSE_TIMEOUT:Kl,EMPTY_BUFFER:mn,GUID:Xl,kForOnEventAttribute:Lr,kListener:Yl,kStatusCode:Zl,kWebSocket:A,NOOP:uo}=ae(),{EventTarget:{addEventListener:eu,removeEventListener:tu}}=io(),{format:nu,parse:ru}=pn(),{toBuffer:su}=_t(),fo=Symbol("kAborted"),Mr=[8,13],le=["CONNECTING","OPEN","CLOSING","CLOSED"],iu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class n extends zl{constructor(e,t,r){super(),this._binaryType=ao[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mn,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]),ho(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ao.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 Jl({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Vl(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",cu),s.on("drain",du),s.on("error",lu),s.on("message",uu),s.on("ping",fu),s.on("pong",hu),i.onerror=gu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",mo),e.on("data",wn),e.on("end",_o),e.on("error",wo),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[ye.extensionName]&&this._extensions[ye.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){q(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())}),po(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){Br(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||mn,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){Br(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||mn,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){Br(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ye.extensionName]||(s.compress=!1),this._sender.send(e||mn,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){q(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:le.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:le.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:le.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:le.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:le.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:le.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:le.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:le.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[Lr])return e[Yl];return null},set(e){for(let t of this.listeners(n))if(t[Lr]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Lr]:!0})}})});x.prototype.addEventListener=eu;x.prototype.removeEventListener=tu;yo.exports=x;function ho(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Kl,protocolVersion:Mr[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,!Mr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Mr.join(", ")})`);let i;if(e instanceof Dr)i=e;else try{i=new Dr(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 _;_n(n,_);return}let d=o?443:80,l=Wl(16).toString("base64"),u=o?ql.request:Gl.request,f=new Set,g;if(s.createConnection=s.createConnection||(o?au:ou),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new ye({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=nu({[ye.extensionName]:g.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!iu.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.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[E,L]of Object.entries(_))r.headers[E.toLowerCase()]=L}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=u(s),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=u(s);s.timeout&&m.on("timeout",()=>{q(n,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[fo]||(m=n._req=null,_n(n,_))}),m.on("response",_=>{let E=_.headers.location,L=_.statusCode;if(E&&s.followRedirects&&L>=300&&L<400){if(++n._redirects>s.maxRedirects){q(n,m,"Maximum redirects exceeded");return}m.abort();let B;try{B=new Dr(E,e)}catch{let M=new SyntaxError(`Invalid URL: ${E}`);_n(n,M);return}ho(n,B,t,r)}else n.emit("unexpected-response",m,_)||q(n,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,E,L)=>{if(n.emit("upgrade",_),n.readyState!==x.CONNECTING)return;m=n._req=null;let B=_.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){q(n,E,"Invalid Upgrade header");return}let re=jl("sha1").update(l+Xl).digest("base64");if(_.headers["sec-websocket-accept"]!==re){q(n,E,"Invalid Sec-WebSocket-Accept header");return}let M=_.headers["sec-websocket-protocol"],p;if(M!==void 0?f.size?f.has(M)||(p="Server sent an invalid subprotocol"):p="Server sent a subprotocol but none was requested":f.size&&(p="Server sent no subprotocol"),p){q(n,E,p);return}M&&(n._protocol=M);let S=_.headers["sec-websocket-extensions"];if(S!==void 0){if(!g){q(n,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=ru(S)}catch{q(n,E,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(I);if(J.length!==1||J[0]!==ye.extensionName){q(n,E,"Server indicated an extension that was not requested");return}try{g.accept(I[ye.extensionName])}catch{q(n,E,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ye.extensionName]=g}n.setSocket(E,L,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(m,n):m.end()}function _n(n,e){n._readyState=x.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function ou(n){return n.path=n.socketPath,lo.connect(n)}function au(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=lo.isIP(n.host)?"":n.host),Hl.connect(n)}function q(n,e,t){n._readyState=x.CLOSING;let r=new Error(t);Error.captureStackTrace(r,q),e.setHeader?(e[fo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_n,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function Br(n,e,t){if(e){let r=Ql(e)?e.size:su(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${le[n.readyState]})`);process.nextTick(t,r)}}function cu(n,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[A]!==void 0&&(t._socket.removeListener("data",wn),process.nextTick(go,t._socket),n===1005?t.close():t.close(n,e))}function du(){let n=this[A];n.isPaused||n._socket.resume()}function lu(n){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",wn),process.nextTick(go,e._socket),e.close(n[Zl])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function co(){this[A].emitClose()}function uu(n,e){this[A].emit("message",n,e)}function fu(n){let e=this[A];e._autoPong&&e.pong(n,!this._isServer,uo),e.emit("ping",n)}function hu(n){this[A].emit("pong",n)}function go(n){n.resume()}function gu(n){let e=this[A];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,po(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function po(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function mo(){let n=this[A];if(this.removeListener("close",mo),this.removeListener("data",wn),this.removeListener("end",_o),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[A]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",co),n._receiver.on("finish",co))}function wn(n){this[A]._receiver.write(n)||this.pause()}function _o(){let n=this[A];n._readyState=x.CLOSING,n._receiver.end(),this.end()}function wo(){let n=this[A];this.removeListener("error",wo),this.on("error",uo),n&&(n._readyState=x.CLOSING,this.destroy())}});var ko=F((zp,vo)=>{"use strict";var $p=yn(),{Duplex:pu}=P("stream");function So(n){n.emit("close")}function mu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Eo(n){this.removeListener("error",Eo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function _u(n,e){let t=!0,r=new pu({...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(So,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(So,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",mu),r.on("error",Eo),r}vo.exports=_u});var Fr=F((qp,xo)=>{"use strict";var{tokenChars:wu}=Ve();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&&wu[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}xo.exports={parse:yu}});var Oo=F((Hp,Co)=>{"use strict";var Su=P("events"),Sn=P("http"),{Duplex:Gp}=P("stream"),{createHash:Eu}=P("crypto"),Io=pn(),Ce=Je(),vu=Fr(),ku=yn(),{CLOSE_TIMEOUT:xu,GUID:Iu,kWebSocket:Tu}=ae(),Ru=/^[+/0-9A-Za-z]{22}==$/,To=0,Ro=1,Ao=2,Ur=class extends Su{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ku,...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=Sn.createServer((r,s)=>{let i=Sn.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=Pu(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=To}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===Ao){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vt,this);return}if(e&&this.once("close",e),this._state!==Ro)if(this._state=Ro,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(vt,this):process.nextTick(vt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{vt(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",Po);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Oe(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Oe(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ru.test(i)){Oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){kt(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=vu.parse(c)}catch{Oe(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let f=new Ce({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Io.parse(l);g[Ce.extensionName]&&(f.accept(g[Ce.extensionName]),u[Ce.extensionName]=f)}catch{Oe(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={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(f,(g,m,_,E)=>{if(!g)return kt(t,m||401,_,E);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(f))return kt(t,401)}this.completeUpgrade(u,i,d,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Tu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>To)return kt(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Eu("sha1").update(t+Iu).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ce.extensionName]){let u=e[Ce.extensionName].params,f=Io.format({[Ce.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
12
12
|
`).join(`\r
|
|
13
|
-
`)),
|
|
14
|
-
`+Object.keys(
|
|
13
|
+
`)),i.removeListener("error",Po),l.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(vt,this)})),a(l,s)}};Co.exports=Ur;function Pu(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 vt(n){n._state=Ao,n.emit("close")}function Po(){this.destroy()}function kt(n,e,t,r){t=t||Sn.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} ${Sn.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 Oe(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Oe),n.emit("wsClientError",o,t,e)}else kt(t,r,s,i)}});import{spawn as Qu}from"node:child_process";import{existsSync as Ku,openSync as Xu}from"node:fs";import{mkdir as Yu}from"node:fs/promises";import{dirname as Zu}from"node:path";import{fileURLToPath as ef}from"node:url";function qr(n=T()){return Ku(n.libEntry)?n.libEntry:ef(new URL("../index.ts",import.meta.url))}async function Ho(n={}){let e=n.paths??T(),t=n.entryOverride??qr(e);await Yu(Zu(e.logFile),{recursive:!0});let r=Xu(e.logFile,"a"),i=t.endsWith(".ts")?["--import","tsx/esm",t,"--daemon"]:[t,"--daemon"],o=Qu(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 tf.info("daemon spawned",{pid:o.pid,entry:t}),{pid:o.pid,entry:t}}var tf,Gr=Q(()=>{"use strict";k();U();tf=w("spawn-daemon")});import{spawn as lf}from"node:child_process";import{mkdir as uf,unlink as ff,writeFile as hf}from"node:fs/promises";import{dirname as gf,join as pf}from"node:path";function Tn(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Qo(n,e){return new Promise((t,r)=>{let s=lf(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 In,jr,Jr,Ko=Q(()=>{"use strict";k();In=w("supervisor.launchd"),jr="ai.coze.bridge",Jr={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>${jr}</string>
|
|
23
23
|
<key>ProgramArguments</key>
|
|
24
24
|
<array>
|
|
25
|
-
<string>${
|
|
26
|
-
<string>${
|
|
25
|
+
<string>${Tn(n.nodeBin)}</string>
|
|
26
|
+
<string>${Tn(n.entry)}</string>
|
|
27
27
|
<string>--daemon</string>
|
|
28
28
|
</array>
|
|
29
29
|
<key>RunAtLoad</key>
|
|
@@ -33,65 +33,65 @@ var i0=Object.create;var _r=Object.defineProperty;var o0=Object.getOwnPropertyDe
|
|
|
33
33
|
<key>ThrottleInterval</key>
|
|
34
34
|
<integer>10</integer>
|
|
35
35
|
<key>StandardOutPath</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${Tn(n.logFile)}</string>
|
|
37
37
|
<key>StandardErrorPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${Tn(n.logFile)}</string>
|
|
39
39
|
</dict>
|
|
40
40
|
</plist>
|
|
41
|
-
`},configPath(
|
|
41
|
+
`},configPath(n){return pf(n.homeDir,"Library","LaunchAgents",`${jr}.plist`)},async install(n){let e=this.configPath(n);await uf(gf(e),{recursive:!0}),await hf(e,this.renderConfig(n),"utf8"),In.info("plist written",{plistPath:e}),await Qo("launchctl",["load","-w",e]),In.info("launchd job loaded",{label:jr})},async uninstall(n){let e=this.configPath(n);await Qo("launchctl",["unload","-w",e]).catch(t=>In.warn("launchctl unload failed (ignored)",{err:String(t)})),await ff(e).catch(t=>{if(t.code!=="ENOENT")throw t}),In.info("launchd job removed",{plistPath:e})}}});import{spawn as mf}from"node:child_process";import{mkdir as _f,unlink as wf,writeFile as yf}from"node:fs/promises";import{dirname as Sf,join as Ef}from"node:path";function An(n,e){return new Promise((t,r)=>{let s=mf(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 Rn,Pn,Vr,Xo=Q(()=>{"use strict";k();Rn=w("supervisor.systemd"),Pn="coze-bridge.service",Vr={platform:"linux",renderConfig(n){return`[Unit]
|
|
42
42
|
Description=Coze Bridge daemon
|
|
43
43
|
After=network.target
|
|
44
44
|
|
|
45
45
|
[Service]
|
|
46
46
|
Type=simple
|
|
47
|
-
ExecStart=${
|
|
47
|
+
ExecStart=${n.nodeBin} ${n.entry} --daemon
|
|
48
48
|
Restart=always
|
|
49
49
|
RestartSec=3
|
|
50
|
-
StandardOutput=append:${
|
|
51
|
-
StandardError=append:${
|
|
50
|
+
StandardOutput=append:${n.logFile}
|
|
51
|
+
StandardError=append:${n.logFile}
|
|
52
52
|
|
|
53
53
|
[Install]
|
|
54
54
|
WantedBy=default.target
|
|
55
|
-
`},configPath(
|
|
55
|
+
`},configPath(n){return Ef(n.homeDir,".config","systemd","user",Pn)},async install(n){let e=this.configPath(n);await _f(Sf(e),{recursive:!0}),await yf(e,this.renderConfig(n),"utf8"),Rn.info("systemd unit written",{unitPath:e}),await An("systemctl",["--user","daemon-reload"]),await An("systemctl",["--user","enable","--now",Pn]),Rn.info("systemd unit enabled",{unitName:Pn})},async uninstall(n){let e=this.configPath(n);await An("systemctl",["--user","disable","--now",Pn]).catch(t=>Rn.warn("systemctl disable failed (ignored)",{err:String(t)})),await wf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),await An("systemctl",["--user","daemon-reload"]).catch(()=>{}),Rn.info("systemd unit removed",{unitPath:e})}}});import{spawn as vf}from"node:child_process";import{join as kf}from"node:path";function Yo(n,e){return new Promise((t,r)=>{let s=vf(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 Qr,Cn,Kr,Zo=Q(()=>{"use strict";k();Qr=w("supervisor.taskscheduler"),Cn="CozeBridge",Kr={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>
|
|
59
59
|
</RegistrationInfo>
|
|
60
60
|
<Triggers>
|
|
61
61
|
<LogonTrigger>
|
|
62
|
-
<UserId>${
|
|
62
|
+
<UserId>${n.userName}</UserId>
|
|
63
63
|
</LogonTrigger>
|
|
64
64
|
</Triggers>
|
|
65
65
|
<Principals>
|
|
66
66
|
<Principal>
|
|
67
|
-
<UserId>${
|
|
67
|
+
<UserId>${n.userName}</UserId>
|
|
68
68
|
<LogonType>InteractiveToken</LogonType>
|
|
69
69
|
<RunLevel>LeastPrivilege</RunLevel>
|
|
70
70
|
</Principal>
|
|
71
71
|
</Principals>
|
|
72
72
|
<Actions>
|
|
73
73
|
<Exec>
|
|
74
|
-
<Command>${
|
|
75
|
-
<Arguments>"${
|
|
74
|
+
<Command>${n.nodeBin}</Command>
|
|
75
|
+
<Arguments>"${n.entry}" --daemon</Arguments>
|
|
76
76
|
</Exec>
|
|
77
77
|
</Actions>
|
|
78
78
|
</Task>
|
|
79
|
-
`},configPath(
|
|
79
|
+
`},configPath(n){return kf(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await Yo("schtasks",["/Create","/SC","ONLOGON","/TN",Cn,"/TR",e,"/RU",n.userName,"/F"]),Qr.info("task scheduler entry created",{task:Cn})},async uninstall(n){await Yo("schtasks",["/Delete","/TN",Cn,"/F"]).catch(e=>Qr.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Qr.info("task scheduler entry removed",{task:Cn})}}});var Xr={};Ln(Xr,{buildContext:()=>Rf,getSupervisor:()=>Tf,launchdSupervisor:()=>Jr,systemdSupervisor:()=>Vr,taskSchedulerSupervisor:()=>Kr});import{homedir as xf,userInfo as If}from"node:os";function Tf(n=process.platform){switch(n){case"darwin":return Jr;case"linux":return Vr;case"win32":return Kr;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function Rf(){let n=T();return{nodeBin:process.execPath,entry:qr(n),logFile:n.logFile,homeDir:xf(),userName:If().username}}var Yr=Q(()=>{"use strict";U();Gr();Ko();Xo();Zo()});fe();k();import{readdir as Ia}from"node:fs/promises";import{mkdir as Sa,writeFile as Ea}from"node:fs/promises";import{join as va}from"node:path";var ka={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Le(n,e,t,r){await Sa(n,{recursive:!0});let s=ka[e],i=va(n,s),o=xa(e,t,r);return await Ea(i,o,"utf8"),i}function xa(n,e,t){let r=`# Coze Agent: ${e}
|
|
80
80
|
|
|
81
|
-
> framework: \`${
|
|
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 Er(r){return`coze-session-${r.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ei(r,e){if(!r.modelToken||It(r.model))return null;let i=Sr(e),a={baseUrl:`${vr}/v1`,api:"openai-completions",apiKey:r.modelToken,models:[{id:r.model,name:r.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 ti(r,e){if(!r.modelToken)return[];let i=Sr(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var se=N("agent-handlers"),ni=5*1024*1024,M0=1,z0=6,q0=new Set(["node_modules",".git",".coze","dist","build",".next"]),un=class{constructor(e){this.opts=e}opts;async listSkills(e){Le(e._meta,"_agent/listSkills");let i=dt(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Ne(i).workspace,u=a?.skills??[],d=[];for(let h of u){let m=Oe(c,h.relPath,"SKILL.md");await N0(m).then(_=>_.isFile()).catch(()=>!1)&&d.push({skillId:h.skillId,skillName:h.skillName,downloadUrl:h.downloadUrl??"",...h.description?{description:h.description}:{},...h.version?{version:h.version}:{}})}return{skills:d}}async addSkills(e){Le(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){if(!m.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let w=F0(m.skillName),_=U0(a.framework),y=Oe(_,w),A=Oe(a.workspace,y);await I0(A,{recursive:!0});let k=await H0(m.downloadUrl);W0(k)?await J0(k,A):await L0(Oe(A,"SKILL.md"),k.toString("utf8"),"utf8");let T={skillId:m.skillId,skillName:m.skillName,relPath:y,installedAt:Date.now(),...m.description?{description:m.description}:{},...m.version?{version:m.version}:{},...m.downloadUrl?{downloadUrl:m.downloadUrl}:{}},R=d.get(m.skillId);R!==void 0?u[R]=T:(d.set(m.skillId,u.length),u.push(T)),h.push(m),se.info("skill installed",{agentId:i,skillId:m.skillId,skillName:m.skillName,relPath:y})}return await nn(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:h}}async removeSkills(e){Le(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=Oe(a.workspace,h.relPath);await R0(m,{recursive:!0,force:!0}),se.info("skill removed",{agentId:i,skillId:h.skillId,relPath:h.relPath})}return await nn(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}),se.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(d){se.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 se.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?(se.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),se.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),se.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}):(se.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Le(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:He,a=await de(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await we(a),se.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return se.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),se.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(Le(e._meta,Ee.RESET),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Ee.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Ee.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Le(e._meta,Ee.REPAIR),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Ee.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new E("IPC_BAD_REQUEST",`${Ee.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){se.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(a)})}return await this.runDetailSync(e.agentId,Ee.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){se.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){se.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(c)})}}async getFileTree(e){Le(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 Cr(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=Y0(e.depth);return h.isDirectory()?{tree:await ai(c,d,u,m)}:{tree:[{name:$0(u),path:ci(u||"."),isDir:!1,size:h.size,modifiedAt:Math.floor(h.mtimeMs)}]}}async getFileContent(e){Le(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 Cr(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>ni)throw new E("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${ni})`);let d=await si(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??Ne(e).workspace}safeJoin(e,i){let a=B0(e,i||"."),c=ii(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${oi}`))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 F0(r){let e=Dt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new E("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function U0(r){return r==="claude-code"?Oe(".claude","skills"):Oe(".agents","skills")}var G0=3e4,K0=50*1024*1024,dn=3e4;async function H0(r){if(!r)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);xn(e);let i=j0(r);return xn(i.length),i}if(r.startsWith("file:")){let e=new URL(r).pathname,i=await si(e);return xn(i.length),i}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),G0);try{let a=await fetch(r,{signal:e.signal});if(!a.ok)throw new E("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${r}`);let c=await a.arrayBuffer();return xn(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new E("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function xn(r){if(r>K0)throw new E("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function j0(r){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(r);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 W0(r){return r.length>=2&&r[0]===31&&r[1]===139}async function J0(r,e){await V0(r),await new Promise((i,a)=>{let c=ri("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 (${dn}ms)`))},dn);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(r)})}async function V0(r){let e=await new Promise((i,a)=>{let c=ri("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 (${dn}ms)`))},dn);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(r)});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 mi={"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"},Wf=Object.fromEntries(Object.entries(mi).map(([r,e])=>[e,r])),ac={"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=mi[e]??cc(e),c=ac[a]??[],u=[a,String(this.seq)];if(c.length>0){let d=c.map(m=>pi(i?.[m]??"")),h=xc(d).join(":");h&&u.push(h)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>pi(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function cc(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function pi(r){return r.replace(/[:_\s]+/g,"-")}function xc(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}G();var dc=3e4,fc=50,lc=20;function wi(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var je=class{constructor(e){this.opts=e;this.log=N(`downstream.${this.constructor.name}`),this.decoder=new yn({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=uc(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>fc&&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(-lc)}),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()));wi(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||wi(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(pn("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=dc){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=Nt(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(_){w&&clearTimeout(w),this.pending.delete(c),m(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new E("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(gi(e))}dispatch(e){if(wn(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(hi(e.error))):i.resolve(e.result);return}if(li(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(fi(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,_n(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var hc="@agentclientprotocol/claude-agent-acp@latest";function gc(r){let e={};for(let[i,a]of Object.entries(r))a!==void 0&&(i.startsWith("CLAUDE")||i==="AI_AGENT"||i==="BAGGAGE"||(e[i]=a));return e}var bn=class extends je{framework="claude-code";constructor(e){let i=gn("claude-code"),[a,c]=i?[i,[]]:["npx",["-y",hc]],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 gc(e)}};import{mkdtempSync as pc,rmSync as mc}from"node:fs";import{tmpdir as wc}from"node:os";import{join as _c}from"node:path";var yc="@zed-industries/codex-acp@latest",vn=class extends je{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=gn("codex"),[a,c]=i?[i,[]]:["npx",["-y",yc]],u=e.command??a,d=e.args??c,h=e.extraArgs?[...d,...e.extraArgs]:d,m=e.isolateCodexHome?pc(_c(wc(),"coze-bridge-codex-home-")):void 0,w=m?{...e.env??{},CODEX_HOME:m}:e.env,_={command:u,args:h,cwd:e.cwd,...w?{env:w}:{}};super(_),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{mc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var Lt=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}};G();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 Sn=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)Ot(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Ot(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}import{spawn as bc}from"node:child_process";import{homedir as vc}from"node:os";import{join as Sc}from"node:path";Zt();G();async function bi(){let r=Sc(vc(),".openclaw/openclaw.json");return(await xt(r))?.gateway?.auth?.token??""}var _i=N("openclaw.config"),Ec=[0,5e3,5e3],yi="models.providers.",En="agents.defaults.models",Cn=class{command;env;retryDelaysMs;queue=new ht;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Ec}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,_i.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=bc(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){_i.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",`${yi}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${yi}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${En}[${e}]`,()=>this.runCli(["config","set",En,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${En}[${e}]`,`${En}.${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 We=N("agent-manager"),Ac=(r,e,i,a,c,u,d)=>{switch(r){case"claude-code":{let h=c?{...$s(c),...Qs(c,d)}:void 0;return new bn({cwd:i,...h&&Object.keys(h).length>0?{env:h}:{}})}case"codex":{let h=c?[...Xs(c),...ti(c,d)]:[],m=c?Zs(c):void 0,w=!!c;return new vn({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 Lt({command:e,cwd:i,agentId:a,...u?{sessionName:Dt(u)}:{}})}};function vi(r){return r==="claude-code"||r==="codex"}var Pc={path:"",version:"cloud-deployed"},kc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Dc=6e4,An=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??Ac,this.createTimeoutMs=e.createTimeoutMs??Dc}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 Cn({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=kt(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")We.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(A=>We.warn("dispose stale agent failed (ignored)",{err:String(A)})),this.registry.unregister(e.agentId);else return We.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&&vi(e.framework)&&await di(e.framework);let u=Ne(e.agentId,this.paths),d=e.workspace??u.workspace,h=kt(e._meta),m=new AbortController,w=setTimeout(()=>m.abort(new E("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),_,y=!1;try{let A=()=>{if(m.signal.aborted)throw m.signal.reason instanceof Error?m.signal.reason:new E("AGENT_TIMEOUT","_agent/create aborted")};await Pr(u.root,{recursive:!0}),await Pr(d,{recursive:!0}),await Pr(u.logs,{recursive:!0}),A(),await ut(d,e.framework,e.agentId,e.cozeIdentity),A();let k=await de(e.agentId,this.paths).catch(()=>null),T=Ys({model:e.model??k?.model});if(_=new Sn({agentId:e.agentId,framework:e.framework,workspace:d,model:T.model??He,deployType:h}),_.status="ok",k?.sessions){for(let[oe,te]of Object.entries(k.sessions))_.sessions.set(oe,{acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let q=Object.keys(k.sessions).length;q>0&&We.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:q})}this.registry.register(_),y=!0;let R={agentId:e.agentId,framework:e.framework,workspace:d,cozeIdentity:e.cozeIdentity,createdAt:k?.createdAt??Date.now(),sessions:k?.sessions??{},model:T.model};return h==="cloud"&&(R.deployType="cloud"),k?.skills&&(R.skills=k.skills),k?.agentName&&(R.agentName=k.agentName),k?.description&&(R.description=k.description),await we(R,this.paths),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,d):We.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId})),We.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(A){throw We.error("agent create failed, rolling back",{agentId:e.agentId,err:String(A)}),y&&_&&(await _.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Cc(u.root,{recursive:!0,force:!0}).catch(k=>We.warn("rm agent dir failed (ignored)",{err:String(k)})),A instanceof E?A:new E("AGENT_SPAWN_FAILED",String(A),{cause:A})}finally{clearTimeout(w)}}async spawnSessionDownstream(e,i,a,c){let d=this.config.frameworksCache?.[e.framework];if(!d)if(e.deployType==="cloud"&&vi(e.framework))d=Pc;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(kc),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=Dt(c),m=await bi(),w=a?.modelToken&&!It(a.model)?ei(a,u):null,_;if(w){let y=Er(c),A=`${y}/${a.model}`;if(!this.ensuredProviders.has(A)){let k=this.getOpenclawConfig();await k.ensureProvider(y,w),await k.addModelToAllowlist(A),this.ensuredProviders.add(A)}_=A}return new Lt({command:d,cwd:i.workspace,agentId:i.agentId,sessionName:h,...m?{gatewayToken:m}:{},..._?{slashModelOnStart:_}:{}})}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=Er(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};G();import{spawn as Ic}from"node:child_process";import{constants as Si,access as Tc}from"node:fs/promises";import{delimiter as Rc,join as Nc}from"node:path";var Lc=N("framework-detector"),Ei={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Oc=[".exe",".cmd",".bat",".ps1"],Bt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Ic,access:e.access??Tc}}async detect(e){let i=Ei[e],a=await this.which(i);if(!a)return Lc.debug("framework binary not found",{framework:e,bin:i}),null;let c=await this.probeVersion(a);return{path:a,version:c}}async detectAll(){let e=await Promise.all(Object.keys(Ei).map(async a=>[a,await this.detect(a)])),i={};for(let[a,c]of e)c&&(i[a]=c);return i}async which(e){let i=this.env.pathEnv.split(Rc).filter(Boolean),a=this.env.platform==="win32"?["",...Oc]:[""];for(let c of i)for(let u of a){let d=Nc(c,e+u);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?Si.F_OK:Si.X_OK;return await this.env.access(e,i),!0}catch{return!1}}async probeVersion(e){return new Promise(i=>{let a="",c=!1,u,d=h=>{c||(c=!0,u&&clearTimeout(u),i(h.trim()||"unknown"))};try{let h=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});u=setTimeout(()=>{h.kill("SIGKILL"),d("unknown")},5e3),h.stdout?.on("data",m=>{a+=m.toString("utf8")}),h.on("error",()=>d("unknown")),h.on("close",()=>{let m=Mc(a).split(/\r?\n/)[0]??"";d(m)})}catch{d("unknown")}})}},Bc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Mc(r){return r.replace(Bc,"")}Zt();ue();var zc=10*6e4;function Ci(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?zc:e}function Pn(r){return xt(r??j().configFile)}function Mt(r,e){return Xt(e??j().configFile,r)}import{randomBytes as qc}from"node:crypto";Ke();G();var U=N("core"),Fc=3e4,Uc=3e4,kn=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=Ci(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(),U.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){U.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),U.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){U.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)&&U.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)=>{U.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),Ot(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(wn(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}`):U.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}`):U.warn("drop unknown notification",{method:e.method})}catch(c){U.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send(Ze(i,_n(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{U.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}=Fs(a);switch(i){case"session/new":{let u=Gc();return U.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return U.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(Ee.GEN_MODEL_TOKEN,a,Uc);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(Ot(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}),U.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){U.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(Ot(a),this.isRuntimeBusy(e,a)){U.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)){U.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:i}),this.armIdleTimer(e,i,a);return}U.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=>U.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){U.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){U.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}let d={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},h=e.activeTriggers.get(a);h&&(d.cozeTriggerMsgId=h),this.upstream.send(pn("session/update",{...i,sessionId:c,_meta:d})).catch(m=>U.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}U.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}`})}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 _=h?this.reverseSessionId(e,h):void 0,y={...u,..._?{sessionId:_}:{},_meta:w};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),this.upstream.send(Nt(c,"session/request_permission",y)).catch(A=>{this.pendingUpstream.delete(c),U.error("forward permission request failed",{agentId:e.agentId,err:String(A)}),i.respondAgentRequestError(a.id,{code:W.INTERNAL_ERROR,message:`upstream send failed: ${String(A)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let i=this.pendingUpstream.get(e.id);if(i){this.pendingUpstream.delete(e.id),e.error?i.downstream.respondAgentRequestError(i.agentRequestId,e.error):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 mn(e.error)):a.resolve(e.result);return}U.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=Fc){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(Nt(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 br(e.agentId,i,this.paths)}catch(i){U.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 Gc(){return qc(16).toString("hex")}G();ue();import{randomBytes as Kc}from"node:crypto";import{chmod as Hc,mkdir as jc,writeFile as Ai}from"node:fs/promises";import{createServer as Wc}from"node:http";import{dirname as Jc}from"node:path";var Vc=1e6,kr=N("ipc"),Dn=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=Kc(32).toString("hex");let e=Wc((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(),kr.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 jc(Jc(this.paths.portFile),{recursive:!0}),await Ai(this.paths.portFile,String(this.port),"utf8"),await Ai(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Hc(this.paths.tokenFile,384)}catch(e){kr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){zt(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){zt(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Yc(e)}catch(h){zt(i,400,{error:"invalid json",detail:String(h)});return}try{let h=await u.handler(d,e);zt(i,200,h??{ok:!0})}catch(h){kr.error("IPC handler failed",{key:c,err:String(h)}),zt(i,500,{error:h instanceof Error?h.message:String(h)})}}};function zt(r,e,i){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(i))}async function Yc(r){let e=[],i=0;for await(let c of r){let u=c;if(i+=u.length,i>Vc)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var Jo=Re(Mi(),1);var Iu=Re(No(),1),Tu=Re(jn(),1),Ru=Re(mt(),1),Nu=Re(Ur(),1),Lu=Re(Hr(),1),Ou=Re($r(),1),Go=Re(Yn(),1),Bu=Re(Uo(),1);var Ko=Go.default;G();var ie=N("upstream.frontier"),jo="application/json",Wo="none",Xn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){ie.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Ks,...an(this.opts.ppeOverride)};class i extends Ko{constructor(h){super(h,Gs,{headers:e})}send(h,...m){if(zs("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 _=Buffer.from(w.slice(0,128)).toString("hex");ie.debug("WS raw frame out",{bytes:w.byteLength,headHex:_})}catch(w){ie.warn("WS raw frame dump failed",{err:String(w)})}super.send(h,...m)}}let a=Ws(this.opts.urlOverride),c={url:a,ws:i,fpID:Us,aID:on,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:jo,force:!0},payloadEncoding:{encoding:Wo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new Jo.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;ie.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=>ie.warn("onConnect handler threw (ignored)",{err:String(h)}))},u.onclose=d=>{this.opened=!1,ie.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{ie.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){ie.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;ie.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:jo,payloadEncoding:Wo})}catch(u){throw new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}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){ie.debug("drop non-adapter frontier frame",{service:i});return}let a=qu(e);if(!a){ie.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ie.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(u){ie.warn("frontier message JSON parse failed",{err:String(u),head:a.slice(0,80)});return}ie.info("frontier frame in",{logid:zu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id}),Promise.resolve(this.handler(c)).catch(u=>ie.warn("frontier frame handler threw",{err:String(u)}))}};function zu(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function qu(r){let e=r.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}}G();var Zr=N("upstream.switchable"),Zn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;Zr.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 Zr.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>Zr.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()}};G();var Qr=N("upstream"),Jt=class{handler=null;async start(){Qr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Qr.info("NoopUpstream stopped",{reason:e})}async send(e){Qr.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)}};G();ue();G();ue();import{execSync as Fu}from"node:child_process";import{readFileSync as Vo,unlinkSync as Uu}from"node:fs";import{mkdir as Gu,readFile as Yo,unlink as $o,writeFile as Ku}from"node:fs/promises";import{dirname as Hu}from"node:path";var ju=N("single-instance"),Qn=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&&(ju.warn("removing stale pid file",{stalePid:e}),await $o(this.pidFile).catch(()=>{})),await Gu(Hu(this.pidFile),{recursive:!0}),await Ku(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Yo(this.pidFile,"utf8")).trim()===String(process.pid)&&await $o(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Yo(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=Vo(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=Fu(`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{Vo(this.pidFile,"utf8").trim()===String(process.pid)&&Uu(this.pidFile)}catch{}})}};var M=N("daemon"),Wu="coze-bridge-daemon";async function Qo(){let r=new Qn({processTitle:Wu}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await Pn(),a=i??{};yr({pid:process.pid}),M.info(i?"loaded bridge config":"initialized bridge config");try{let P=new Bt;a.frameworksCache=await P.detectAll(),M.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(P){M.warn("framework detection failed",{err:String(P)})}await Mt(a);let c=new Zn(new Jt),u=j(),d=null,h=new kn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(P,F,J,ne)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,F,J,ne)}});await Vu(u,h);let m=new An({paths:u,config:a,registry:h});d=m;let w,_,y=null,A=null;h.registerExtension("_agent/create",async P=>m.createAgent(P.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let k={},T=new un({agents:h.agents,disposeAndMarkDisconnected:async(P,F)=>{let J=h.agents.get(P);J&&(await m.cleanupOpenclawSessionProviders(J).catch(ne=>M.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(ne)})),await J.dispose(`disconnect: ${F}`).catch(ne=>M.warn("dispose during disconnect failed (ignored)",{agentId:P,err:String(ne)})),J.status="disconnected",h.unregister(P)),h.disconnectedAgents.add(P)},detailSyncer:async P=>{if(!k.ref)throw new Error("agent-detail-sync not initialized yet");await k.ref.syncOne(P)},openclawRepair:async(P,F)=>{await m.openclawRepair(P,F)}});h.registerExtension("_agent/listSkills",P=>T.listSkills(P.params)),h.registerExtension("_agent/addSkills",P=>T.addSkills(P.params)),h.registerExtension("_agent/removeSkills",P=>T.removeSkills(P.params)),h.registerExtension("_agent/getFileTree",P=>T.getFileTree(P.params)),h.registerExtension("_agent/getFileContent",P=>T.getFileContent(P.params)),h.registerExtension("_agent/update",P=>T.updateAgent(P.params)),h.registerExtension("_agent/disconnect",P=>T.disconnectAgent(P.params)),h.registerExtension("_agent/switchModel",P=>T.switchModel(P.params)),h.registerExtension("_agent/reset",P=>T.resetAgent(P.params)),h.registerExtension("_agent/repair",P=>T.repairAgent(P.params));let R=new sn({paths:u,handlers:T,sendDetail:P=>h.sendRequest("_agent/detail",P)});k.ref=R,c.onConnect(({initial:P})=>{M.info("frontier upstream connected, triggering detail sync",{initial:P}),R.syncAll(P?"initial-connect":"reconnect").catch(F=>M.warn("detail sync top-level error (ignored)",{err:String(F)}))});let q=new Dn({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...h.agents.keys()],deviceId:y??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async P=>{let F=P,J=F?.privatecode,ne=F?.pairing_code;if(!J||!ne)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ke=cn(F.env),pe=F.handshake_url,$e=F.frontier_url,Et=Ju(F.env,pe,$e),Vt=!!w&&w!==J,be=_!==void 0&&_!==Et,ve=Vt||be;if(ve){M.warn("pair config switched, resetting agents",{pcChanged:Vt,envChanged:be,previousPc:w?Xo(w):"",nextPc:Xo(J),previousEnvKey:_??"",nextEnvKey:Et});for(let H of[...h.agents.values()])await H.dispose("pair config switch").catch(()=>{}),h.agents.delete(H.agentId);await c.swap(new Jt,"pair switch").catch(()=>{})}let Yt=await Vs({privatecode:J,...pe?{endpoint:pe}:{},ppeOverride:ke});y=Yt.deviceId,yr({deviceId:y,pid:process.pid});let ae=new Xn({handshake:Yt,privatecode:J,...$e?{urlOverride:$e}:{},ppeOverride:ke});await c.swap(ae,"pair");let $t=Object.keys(a.frameworksCache??{});try{let H=await h.sendRequest("_agent/pair",{pairCode:ne,patToken:J,frameworks:$t,_meta:{cozeDeviceId:y}});M.info("_agent/pair ok",{pairResult:H}),w=J,_=Et,A||(A=new fn({core:h,getDeviceId:()=>y??""})),A.start(),ve&&Zo(u,m).catch(De=>M.warn("post-pair-switch auto-revive error (ignored)",{err:String(De)}));let V;return F.agent_id&&(V=await Yu(F.agent_id,u,m,De=>h.sendRequest("_agent/detail",De)).catch(De=>(M.error("--agent-id ensureAgent failed",{agentId:F.agent_id,err:String(De)}),{ok:!1,agentId:F.agent_id??"",note:String(De)}))),{ok:!0,note:"paired with cloud",...V?{agent:V}:{}}}catch(H){return M.error("_agent/pair failed",{err:String(H)}),{ok:!1,note:`pair failed: ${String(H)}`}}}},{method:"POST",path:"/_agent/create",handler:async P=>{let F=P;return{ok:!0,result:await m.createAgent(F)}}},{method:"POST",path:"/refresh",handler:async()=>{M.info("IPC /refresh: re-detecting frameworks");let P=new Bt;return a.frameworksCache=await P.detectAll(),await Mt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(M.info("IPC /shutdown received"),setImmediate(()=>{xe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:oe,token:te}=await q.start();await h.start(),Zo(u,m).catch(P=>M.warn("auto-revive top-level error (ignored)",{err:String(P)}));let ye=null,xe={port:oe,token:te,core:h,ipc:q,shutdown(P){return ye||(M.info("daemon shutdown",{reason:P}),ye=(async()=>{A?.stop(),await h.stop(P),await q.stop(),await r.release()})(),ye)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{xe.shutdown(P).then(()=>process.exit(0))});return M.info("daemon ready",{port:oe,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),xe}function Xo(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function Ju(r,e,i){return`${r??""}|${e??""}|${i??""}`}async function Vu(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.agentsRoot)}catch{return}let{loadAgentConfig:c,enforceAgentConfigMode:u}=await Promise.resolve().then(()=>(Ke(),rn));for(let d of a){await u(d,r).catch(h=>M.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(h)}));try{let h=await c(d,r);h?.disconnectedAt&&(e.disconnectedAgents.add(d),M.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:h.disconnectedAt,reason:h.disconnectReason??""}))}catch(h){M.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(h)})}}}async function Yu(r,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ke(),rn)),u=await c(r,e);if(u){M.info("--agent-id: local config found, reconnecting",{agentId:r,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:r,note:u.disconnectedAt?"revived from local config":"connected from local config"}}M.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let d=await a({_meta:{cozeAgentId:r}});if(!d.framework)throw new E("AGENT_NOT_FOUND",`agent ${r} \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:r,note:m?"cloud agent acknowledged":"created from cloud detail"}}async function Zo(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.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(()=>(Ke(),rn));M.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,r)}catch(w){M.warn("auto-revive: load config failed (skipping)",{agentId:h,err:String(w)}),d+=1;continue}if(!m){d+=1;continue}if(m.disconnectedAt){M.info("auto-revive: skip disconnected agent",{agentId:h,disconnectedAt:m.disconnectedAt}),d+=1;continue}try{M.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){M.warn("auto-revive: createAgent failed (skipping)",{agentId:h,framework:m.framework,err:String(w)}),d+=1}}return M.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}ts();ue();import{readFile as ta}from"node:fs/promises";var Ye=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:sd(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([ta(this.paths.portFile,"utf8"),ta(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:rd(m)}}finally{clearTimeout(d)}}};function rd(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function sd(r){return r instanceof Error?r.message:String(r)}G();ue();import{copyFile as na,mkdir as id,readFile as ns,writeFile as od}from"node:fs/promises";import{dirname as ad,resolve as rs,sep as er}from"node:path";import{fileURLToPath as cd}from"node:url";G();ue();var ra=N("dist-install");function xd(r){let e=cd(r),i=ad(e),a=`${er}src${er}`;if(i.includes(a)||i.endsWith(`${er}src${er}cli`))return null;let c=rs(i,"index.js"),u=rs(i,"..","package.json");return{dist:c,pkgJson:u}}async function sa(r={}){let e=r.paths??j(),i=xd(import.meta.url),a=r.sourceDist??i?.dist,c=r.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 ns(c,"utf8")).version??"unknown"}catch(y){return ra.warn("cannot read source package.json,skip dist install",{err:String(y)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(y)}`}}let d=await Pn(e.configFile)??{},h=d.libVersion;if(h===u)try{return await ns(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await id(e.libDir,{recursive:!0}),await na(a,e.libEntry),await na(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let m=rs(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
|
|
94
|
-
`;return await
|
|
88
|
+
${s}`}var Z=w("agent-detail-sync"),Nt=class{constructor(e){this.opts=e}opts;async syncAll(e){let t=this.opts.paths.agentsRoot,r;try{r=await Ia(t)}catch(s){Z.info("agents dir not found, skip detail sync",{root:t,err:String(s)});return}Z.info("starting detail sync",{reason:e,count:r.length});for(let s of r)try{await this.syncOne(s)}catch(i){Z.warn("detail sync failed for agent, skipping",{agentId:s,err:String(i)})}Z.info("detail sync done",{reason:e})}async syncOne(e){let t=await $(e,this.opts.paths);if(!t){Z.info("detail sync: agent config missing, skip",{agentId:e});return}let r;try{r=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(o){Z.warn("detail RPC failed, using local data",{agentId:e,err:String(o)});return}if(r.agentId&&r.agentId!==e){Z.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&&Z.info("detail.deployType",{agentId:e,deployType:r.deployType}),!s){Z.debug("detail sync: no diff",{agentId:e});return}await K(t,this.opts.paths),Z.info("detail sync: config updated",{agentId:e,identityChanged:i,agentName:t.agentName}),i&&(await Le(t.workspace,t.framework,e,t.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};fe();import{spawn as Ts}from"node:child_process";import{lstat as zn,mkdir as Aa,readFile as Rs,readdir as Ca,rm as Oa,stat as Na,writeFile as ba}from"node:fs/promises";import{join as oe,normalize as Da,relative as Ps,resolve as La,sep as As}from"node:path";var ee={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 nt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function ds(n){let{_meta:e,...t}=n;return{stripped:t,meta:e}}function Me(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();U();function ie(n,e){if(nt(n)!=="cloud")throw new h("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function rt(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}k();var bt="1008033",ls="1289";var us="pbbp2",fs="https://www.coze.cn",hs="/api/coze_claw/resource/get_frontier_key",Ta="https://www.coze.cn",Ra="wss://frontier.coze.cn";function gs(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??Ta}function ps(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??Ra}function Dt(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 Lt(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var ms=w("handshake");async function _s(n){let e=gs(n.endpoint),t=n.timeoutMs??1e4,r=`${Pa(e)}${hs}?aid=${encodeURIComponent(bt)}`,s={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...Dt(n.ppeOverride)},i=new AbortController,o=setTimeout(()=>i.abort(),t);ms.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")??"",d=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let g=await a.text().catch(()=>"");throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${g.slice(0,200)}`)}let l=await a.json();if(l.code!==void 0&&l.code!==0)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${l.code} msg=${l.msg??"-"} logid=${c}`);let u=l.data?.access_key,f=l.data?.device_id;if(!u||!f)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${c}: ${JSON.stringify(l)}`);return ms.info("handshake ok",{remoteDeviceId:f,logid:c,traceId:d}),{accessKey:u,deviceId:f}}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 Pa(n){return n.endsWith("/")?n.slice(0,-1):n}var Fn="https://llm-gateway.coze.cn",he="auto";function ws(n){return{model:n.model??he,...n.modelToken?{modelToken:n.modelToken}:{}}}function st(n){return!n||n===he}function ys(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=Fn,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||he):st(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function Ss(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||he}"`):st(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="${Fn}/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 Es(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function Un(n){let{ttEnv:e,usePpe:t}=Lt(n),r={};return e&&(r["x-tt-env"]=e),t&&(r["x-use-ppe"]=t),r}function vs(n,e){if(!n.modelToken)return{};let t=Un(e);return Object.keys(t).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(t).map(([s,i])=>`${s}:${i}`).join(`
|
|
89
|
+
`)}}function $n(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ks(n,e){if(!n.modelToken||st(n.model))return null;let t=Un(e),r={baseUrl:`${Fn}/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(t).length>0&&(r.headers=t),r}function xs(n,e){if(!n.modelToken)return[];let t=Un(e),r=[];for(let[s,i]of Object.entries(t))r.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return r}var b=w("agent-handlers"),Is=5*1024*1024,Ma=1,Ba=6,Fa=new Set(["node_modules",".git",".coze","dist","build",".next"]),Bt=class{constructor(e){this.opts=e}opts;async listSkills(e){ie(e._meta,"_agent/listSkills");let t=Me(e._meta),r=await this.loadAgentCfg(t),s=r?.workspace??se(t).workspace,i=r?.skills??[],o=[];for(let a of i){let c=oe(s,a.relPath,"SKILL.md");await Na(c).then(l=>l.isFile()).catch(()=>!1)&&o.push({skillId:a.skillId,skillName:a.skillName,downloadUrl:a.downloadUrl??"",...a.description?{description:a.description}:{},...a.version?{version:a.version}:{}})}return{skills:o}}async addSkills(e){ie(e._meta,"_agent/addSkills");let t=Me(e._meta),r=await this.requireAgentCfg(t),s=e.skills??[],i=[...r.skills??[]],o=new Map(i.map((c,d)=>[c.skillId,d])),a=[];for(let c of s){if(!c.skillName)throw new h("IPC_BAD_REQUEST","skill missing skillName");let d=Ua(c.skillName),l=$a(r.framework),u=oe(l,d),f=oe(r.workspace,u);await Aa(f,{recursive:!0});let g=await Ga(c.downloadUrl);Wa(g)?await ja(g,f):await ba(oe(f,"SKILL.md"),g.toString("utf8"),"utf8");let m={skillId:c.skillId,skillName:c.skillName,relPath:u,installedAt:Date.now(),...c.description?{description:c.description}:{},...c.version?{version:c.version}:{},...c.downloadUrl?{downloadUrl:c.downloadUrl}:{}},_=o.get(c.skillId);_!==void 0?i[_]=m:(o.set(c.skillId,i.length),i.push(m)),a.push(c),b.info("skill installed",{agentId:t,skillId:c.skillId,skillName:c.skillName,relPath:u})}return await Ct(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){ie(e._meta,"_agent/removeSkills");let t=Me(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=oe(r.workspace,a.relPath);await Oa(c,{recursive:!0,force:!0}),b.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await Ct(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}),b.info("session reloaded",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){b.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 b.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,r=await $(t);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return r.cozeIdentity===e.cozeIdentity?(b.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(r.cozeIdentity=e.cozeIdentity,await K(r),await Le(r.workspace,r.framework,t,e.cozeIdentity),b.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 $(t);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await K(r),b.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}):(b.warn("_agent/disconnect: agent not found, ignoring",{agentId:t}),{ok:!0})}async switchModel(e){if(ie(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:he,r=await $(e.agentId);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=t,await K(r),b.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return b.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),b.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(ie(e._meta,ee.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${ee.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,ee.RESET,e.reason),{ok:!0}}async repairAgent(e){if(ie(e._meta,ee.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${ee.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${ee.REPAIR} only allowed for openclaw, got ${t.framework}`);if(t&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,t.workspace)}catch(r){b.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,ee.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,r){if(!this.opts.detailSyncer){b.warn("detailSyncer not wired, skipping sync",{method:t,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){b.warn("detail sync failed (ignored)",{method:t,agentId:e,reason:r,err:String(s)})}}async getFileTree(e){ie(e._meta,"_agent/getFileTree");let t=e._meta,r=Me(t),s=await this.resolveWorkspace(r),i=e.filePath??"",o=this.safeJoin(s,i),a=await zn(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=Va(e.depth);return a.isDirectory()?{tree:await Cs(s,o,i,c)}:{tree:[{name:Qa(i),path:Os(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){ie(e._meta,"_agent/getFileContent");let t=Me(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 zn(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>Is)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${Is})`);let o=await Rs(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 $(e).catch(()=>null))?.workspace??se(e).workspace}safeJoin(e,t){let r=La(e,t||"."),s=Ps(e,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${As}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}loadAgentCfg(e){return $(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 Ua(n){let e=rt(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function $a(n){return n==="claude-code"?oe(".claude","skills"):oe(".agents","skills")}var za=3e4,qa=50*1024*1024,Ft=3e4;async function Ga(n){if(!n)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);Mt(e);let t=Ha(n);return Mt(t.length),t}if(n.startsWith("file:")){let e=new URL(n).pathname,t=await Rs(e);return Mt(t.length),t}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),za);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 Mt(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 Mt(n){if(n>qa)throw new h("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function Ha(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 Wa(n){return n.length>=2&&n[0]===31&&n[1]===139}async function ja(n,e){await Ja(n),await new Promise((t,r)=>{let s=Ts("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 (${Ft}ms)`))},Ft);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 Ja(n){let e=await new Promise((t,r)=>{let s=Ts("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 (${Ft}ms)`))},Ft);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 Cs(n,e,t,r){if(r<=0)return[];let s;try{s=await Ca(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(Fa.has(o.name)||o.isSymbolicLink())continue;let a=oe(e,o.name),c=Da(oe(t,o.name)),d=null;try{d=await zn(a)}catch{continue}if(d.isSymbolicLink())continue;let l={name:o.name,path:Os(Ps(n,a)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&r>1&&(l.children=await Cs(n,a,c,r-1)),i.push(l)}return i.sort((o,a)=>o.isDir!==a.isDir?o.isDir?-1:1:o.name.localeCompare(a.name)),i}function Va(n){return!n||n<=0?Ma:Math.min(n,Ba)}function Qa(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function Os(n){return n.split(As).join("/")}k();import{readFileSync as Dh}from"node:fs";import{dirname as Mh,join as Bh}from"node:path";import{fileURLToPath as Uh}from"node:url";var Ut="0.1.25";var it=w("agent-health-reporter"),Ka=1e4,$t=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Ka}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()}),it.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),it.info("heartbeat stopped"))}async tick(){if(this.inFlight){it.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){it.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=Xa(s);i&&t.push({agentId:s.agentId,status:i})}if(t.length===0)return;let r={agents:t,bridgeVersion:Ut,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",r)}catch(s){it.warn("heartbeat batch send failed",{count:t.length,err:String(s)})}}finally{this.inFlight=!1}}};function Xa(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}fe();import{mkdir as Gn,rm as Ic}from"node:fs/promises";k();import{execFile as Ya}from"node:child_process";import{promisify as Za}from"node:util";var bs=Za(Ya),ot=w("agents.acp-installer"),ec={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},tc=5e4,nc=5e3,rc=5*6e4,qt=new Map,zt=new Map,qn=new Map;async function Ns(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:t}=await bs(e,[n],{timeout:nc});return t.split(`
|
|
91
|
+
`)[0]?.trim()||void 0}catch{return}}async function sc(n){ot.info("npm install -g start",{npmPackage:n}),await bs("npm",["install","-g",`${n}@latest`],{timeout:tc,maxBuffer:10*1024*1024}),ot.info("npm install -g done",{npmPackage:n})}async function Ds(n){let e=ec[n];if(!e)return;let t=qt.get(n);if(t)return t;let r=zt.get(n);if(r&&Date.now()-r<rc)return;let s=qn.get(n);if(s)return s;let i=(async()=>{let o=await Ns(e.binary);if(o)return qt.set(n,o),ot.info("acp wrapper found on PATH",{binary:e.binary,path:o}),o;try{await sc(e.npmPackage)}catch(c){ot.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(c)}),zt.set(n,Date.now());return}let a=await Ns(e.binary);if(!a){ot.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),zt.set(n,Date.now());return}return qt.set(n,a),zt.delete(n),a})().finally(()=>{qn.delete(n)});return qn.set(n,i),i}function Gt(n){return qt.get(n)}import{spawn as dc}from"node:child_process";function at(n,e,t){return t===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:t}}function Ht(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function Be(n,e){return{jsonrpc:"2.0",id:n,result:e}}function Ee(n,e){return{jsonrpc:"2.0",id:n,error:e}}var Wt=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 Ls(n){return"method"in n&&"id"in n&&n.id!==void 0}function Ms(n){return"method"in n&&!("id"in n)}function jt(n){return!("method"in n)&&"id"in n}var ic={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 Jt(n){return n instanceof h?{code:ic[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 Bs(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 Fs(n){return`${JSON.stringify(n)}
|
|
92
|
+
`}var Vt=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 $s={"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"},eg=Object.fromEntries(Object.entries($s).map(([n,e])=>[e,n])),oc={"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:[]},Fe=class{seq=0;next(e,t){this.seq+=1;let r=$s[e]??ac(e),s=oc[r]??[],i=[r,String(this.seq)];if(s.length>0){let o=s.map(c=>Us(t?.[c]??"")),a=cc(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>Us(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function ac(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Us(n){return n.replace(/[:_\s]+/g,"-")}function cc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}k();var lc=3e4,uc=50,fc=20,zs=500;function hc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=zs?n:`${e.slice(0,zs)}...<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 ge=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Vt({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Fe;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=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=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>uc&&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(-fc)}),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(Ht("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(Be(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(Ee(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=lc){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=at(s,e,t),o=r>0&&Number.isFinite(r);return new Promise((a,c)=>{let d=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:d,method:e});try{this.writeFrame(i)}catch(l){d&&clearTimeout(d),this.pending.delete(s),c(l)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new h("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Fs(e))}dispatch(e){if(jt(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(Bs(e.error))):(this.log.info("downstream returned result",{id:e.id,method:t.method,result:hc(e.result)}),t.resolve(e.result));return}if(Ms(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(Ls(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(Ee(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(Ee(e.id,Jt(r)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var gc="@agentclientprotocol/claude-agent-acp@latest";function pc(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 Qt=class extends ge{framework="claude-code";constructor(e){let t=Gt("claude-code"),[r,s]=t?[t,[]]:["npx",["-y",gc]],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 pc(e)}};import{mkdtempSync as mc,rmSync as _c}from"node:fs";import{tmpdir as wc}from"node:os";import{join as yc}from"node:path";var Sc="@zed-industries/codex-acp@latest",Kt=class extends ge{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=Gt("codex"),[r,s]=t?[t,[]]:["npx",["-y",Sc]],i=e.command??r,o=e.args??s,a=e.extraArgs?[...o,...e.extraArgs]:o,c=e.isolateCodexHome?mc(yc(wc(),"coze-bridge-codex-home-")):void 0,d=c?{...e.env??{},CODEX_HOME:c}:e.env,l={command:i,args:a,cwd:e.cwd,...d?{env:d}:{}};super(l),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{_c(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var ct=class extends ge{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();U();var Ue=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 Xt=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 Ue,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)dt(r),r.downstream&&(t.push(r.downstream.stop(e).catch(()=>{})),r.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function dt(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Ec}from"node:child_process";import{homedir as vc}from"node:os";import{join as kc}from"node:path";Tt();k();async function Ws(){let n=kc(vc(),".openclaw/openclaw.json");return(await De(n))?.gateway?.auth?.token??""}var Gs=w("openclaw.config"),xc=[0,5e3,5e3],Hs="models.providers.",Yt="agents.defaults.models",Zt=class{command;env;retryDelaysMs;queue=new Ue;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??xc}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,Gs.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=Ec(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){Gs.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",`${Hs}${e}`,JSON.stringify(t),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Hs}${e}`)}addModelToAllowlist(e,t){let r={[e]:t?{alias:t}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Yt}[${e}]`,()=>this.runCli(["config","set",Yt,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Yt}[${e}]`,`${Yt}.${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 pe=w("agent-manager"),Tc=(n,e,t,r,s,i,o)=>{switch(n){case"claude-code":{let a=s?{...ys(s),...vs(s,o)}:void 0;return new Qt({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...Ss(s),...xs(s,o)]:[],c=s?Es(s):void 0,d=!!s;return new Kt({cwd:t,...a.length>0?{extraArgs:a}:{},...c&&Object.keys(c).length>0?{env:c}:{},...d?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new ct({command:e,cwd:t,agentId:r,...i?{sessionName:rt(i)}:{}})}};function js(n){return n==="claude-code"||n==="codex"}var Rc={path:"",version:"cloud-deployed"},Pc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ac=6e4,en=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??Tc,this.createTimeoutMs=e.createTimeoutMs??Ac}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 Zt({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=nt(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")pe.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(f=>pe.warn("dispose stale agent failed (ignored)",{err:String(f)})),this.registry.unregister(e.agentId);else return pe.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&&js(e.framework)&&await Ds(e.framework);let i=se(e.agentId,this.paths),o=e.workspace??i.workspace,a=nt(e._meta),c=new AbortController,d=setTimeout(()=>c.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),l,u=!1;try{let f=()=>{if(c.signal.aborted)throw c.signal.reason instanceof Error?c.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await Gn(i.root,{recursive:!0}),await Gn(o,{recursive:!0}),await Gn(i.logs,{recursive:!0}),f(),await Le(o,e.framework,e.agentId,e.cozeIdentity),f();let g=await $(e.agentId,this.paths).catch(()=>null),m=ws({model:e.model??g?.model});if(l=new Xt({agentId:e.agentId,framework:e.framework,workspace:o,model:m.model??he,deployType:a}),l.status="ok",g?.sessions){for(let[L,B]of Object.entries(g.sessions))l.sessions.set(L,{acpSessionId:B.acpSessionId,modelToken:B.modelToken,tokenGeneratedAt:B.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let E=Object.keys(g.sessions).length;E>0&&pe.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:E})}this.registry.register(l),u=!0;let _={agentId:e.agentId,framework:e.framework,workspace:o,cozeIdentity:e.cozeIdentity,createdAt:g?.createdAt??Date.now(),sessions:g?.sessions??{},model:m.model};return a==="cloud"&&(_.deployType="cloud"),g?.skills&&(_.skills=g.skills),g?.agentName&&(_.agentName=g.agentName),g?.description&&(_.description=g.description),await K(_,this.paths),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,o):pe.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId})),pe.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(f){throw pe.error("agent create failed, rolling back",{agentId:e.agentId,err:String(f)}),u&&l&&(await l.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ic(i.root,{recursive:!0,force:!0}).catch(g=>pe.warn("rm agent dir failed (ignored)",{err:String(g)})),f instanceof h?f:new h("AGENT_SPAWN_FAILED",String(f),{cause:f})}finally{clearTimeout(d)}}async spawnSessionDownstream(e,t,r,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&js(e.framework))o=Rc;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(Pc),c}catch(d){throw await c.stop("spawnSessionDownstream failed").catch(()=>{}),d instanceof h?d:new h("AGENT_SPAWN_FAILED",d instanceof Error?d.message:String(d),{cause:d})}}async buildOpenclawDownstream(e){let{session:t,modelConfig:r,cloudSessionId:s,cozeEnv:i,command:o}=e,a=rt(s),c=await Ws(),d=r?.modelToken&&!st(r.model)?ks(r,i):null,l;if(d){let u=$n(s),f=`${u}/${r.model}`;if(!this.ensuredProviders.has(f)){let g=this.getOpenclawConfig();await g.ensureProvider(u,d),await g.addModelToAllowlist(f),this.ensuredProviders.add(f)}l=f}return new ct({command:o,cwd:t.workspace,agentId:t.agentId,sessionName:a,...c?{gatewayToken:c}:{},...l?{slashModelOnStart:l}:{}})}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=$n(r),i=`${s}/${e.model}`;this.ensuredProviders.delete(i),await t.removeProvider(s),await t.removeModelFromAllowlist(i)}}};k();import{spawn as Cc}from"node:child_process";import{constants as Js,access as Oc}from"node:fs/promises";import{delimiter as Nc,join as bc}from"node:path";var Dc=w("framework-detector"),Vs={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Lc=[".exe",".cmd",".bat",".ps1"],$e=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Cc,access:e.access??Oc}}async detect(e){let t=Vs[e],r=await this.which(t);if(!r)return Dc.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(Vs).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(Nc).filter(Boolean),r=this.env.platform==="win32"?["",...Lc]:[""];for(let s of t)for(let i of r){let o=bc(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?Js.F_OK:Js.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=Bc(r).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},Mc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Bc(n){return n.replace(Mc,"")}Tt();U();var Fc=10*6e4;function Qs(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Fc:e}function tn(n){return De(n??T().configFile)}function ze(n,e){return It(e??T().configFile,n)}import{randomBytes as Uc}from"node:crypto";fe();k();var v=w("core"),$c=3e4,zc=3e4,nn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Fe;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=Qs(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(),v.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){v.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),v.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(r){v.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)&&v.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)=>{v.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),dt(r),r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId)}))}async handleFrame(e){if(jt(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}`):v.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Be(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Be(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Be(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):v.warn("drop unknown notification",{method:e.method})}catch(s){v.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(Ee(t,Jt(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{v.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}=ds(r);switch(t){case"session/new":{let i=qc();return v.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return v.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 d=await a.downstream.sessionPrompt({...i,sessionId:a.acpSessionId});return a.lastActiveAt=Date.now(),d}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(ee.GEN_MODEL_TOKEN,r,zc);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(dt(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}),v.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId})}catch(i){v.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(dt(r),this.isRuntimeBusy(e,r)){v.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)){v.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:t}),this.armIdleTimer(e,t,r);return}v.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=>v.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){v.debug("drop update for unknown session",{agentId:e.agentId,acpId:r});return}let i=e.sessions.get(s);if(!i){v.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(Gc(t)){v.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(Ht("session/update",{...t,sessionId:s,_meta:o})).catch(c=>v.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}v.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}`})}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,d={cozeAgentId:e.agentId};c&&(d.cozeTriggerMsgId=c);let l=a?this.reverseSessionId(e,a):void 0,u={...i,...l?{sessionId:l}:{},_meta:d};this.pendingUpstream.set(s,{agentRequestId:r.id,agentId:e.agentId,downstream:t,method:r.method}),this.upstream.send(at(s,"session/request_permission",u)).catch(f=>{this.pendingUpstream.delete(s),v.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),t.respondAgentRequestError(r.id,{code:R.INTERNAL_ERROR,message:`upstream send failed: ${String(f)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let t=this.pendingUpstream.get(e.id);if(t){this.pendingUpstream.delete(e.id),e.error?t.downstream.respondAgentRequestError(t.agentRequestId,e.error):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 Wt(e.error)):r.resolve(e.result);return}v.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,r=$c){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(at(s,e,t)).catch(c=>{let d=this.pendingBridge.get(s);d&&(clearTimeout(d.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 Bn(e.agentId,t,this.paths)}catch(t){v.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(Ee(e,{code:t,message:r}))}};function qc(){return Uc(16).toString("hex")}function Gc(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();U();import{randomBytes as Hc}from"node:crypto";import{chmod as Wc,mkdir as jc,writeFile as Ks}from"node:fs/promises";import{createServer as Jc}from"node:http";import{dirname as Vc}from"node:path";var Qc=1e6,Hn=w("ipc"),rn=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=Hc(32).toString("hex");let e=Jc((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(),Hn.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 jc(Vc(this.paths.portFile),{recursive:!0}),await Ks(this.paths.portFile,String(this.port),"utf8"),await Ks(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Wc(this.paths.tokenFile,384)}catch(e){Hn.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){lt(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){lt(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await Kc(e)}catch(a){lt(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);lt(t,200,a??{ok:!0})}catch(a){Hn.error("IPC handler failed",{key:s,err:String(a)}),lt(t,500,{error:a instanceof Error?a.message:String(a)})}}};function lt(n,e,t){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(t))}async function Kc(n){let e=[],t=0;for await(let s of n){let i=s;if(t+=i.length,t>Qc)throw new Error("body too large");e.push(i)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var ii="";function cd(n=""){let t=`${Date.now()}`,r=ii||(ii=fd(n)),s=Math.random().toString(16).slice(-6);return"02"+t+r+s}function dd(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function ld(n){return(Array(8).join("0")+parseInt(n,10).toString(2)).slice(-8)}function oi(n){return(Array(4).join("0")+parseInt(n,2).toString(16)).slice(-4)}function ud(n){let e=n.split(/\./).map(s=>ld(s)),t=[];return t[0]=oi(e[0]+e[1]),t[1]=oi(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function fd(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?ud(n):t?hd(n):"00000000000000000000000000000000"}function hd(n){let e="",t=[],r=0,s=0,i=!0,o="0000";if(n.indexOf("::")>-1){let a=n.split("::");for(let d=0;d<a.length;d++){let l=a[d];if(l.indexOf(":")>0){let u=l.split(":");i&&(r=u.length),s+=u.length;for(let f=0;f<u.length;f++)if(u[f].length!==4){let m=o.substring(0,4-u[f].length).concat(u[f]);t.push(m)}else t.push(u[f]);i=!1}else{if(l.length!==4){let f=o.substring(0,4-l.length).concat(l);t.push(f)}else t.push(l);i&&(r+=1),s+=1,i=!1}}let c="";for(let d=0;d<8-s;d++)c=c.concat(o);for(let d=0;d<t.length;d++)d===r&&(e=e.concat(c)),e=e.concat(t[d]);return e}{let a=n.split(":");for(let c=0;c<a.length;c++){let d=a[c];if(a[c].length!==4){let u=o.substring(0,4-a[c].length).concat(d);e=e.concat(u)}else e=e.concat(d)}return e}}function gd(n,e){let t=n.key;t!==void 0&&(C(e,10),xe(e,t));let r=n.value;r!==void 0&&(C(e,18),xe(e,r))}function pd(n){let e={};e:for(;!Si(n);){let t=D(n);switch(t>>>3){case 0:break e;case 1:e.key=ke(n,D(n));break;case 2:e.value=ke(n,D(n));break;default:_i(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 mi(n){let e=yi();return md(n,e),vd(e)}function md(n,e){let t=n.SeqID;t!==void 0&&(C(e,8),ft(e,t));let r=n.LogID;r!==void 0&&(C(e,16),ft(e,r));let s=n.service;s!==void 0&&(C(e,24),ft(e,Xn(s)));let i=n.method;i!==void 0&&(C(e,32),ft(e,Xn(i)));let o=n.headers;if(o!==void 0)for(let m of o){C(e,42);let _=yi();gd(m,_),C(e,_.limit),Id(e,_),Sd(_)}let a=n.payloadEncoding;a!==void 0&&(C(e,50),xe(e,a));let c=n.payloadType;c!==void 0&&(C(e,58),xe(e,c));let d=n.payload;d!==void 0&&(C(e,66),C(e,d.length),xd(e,d));let l=n.LogIDNew;l!==void 0&&(C(e,74),xe(e,l));let u=n.serverTiming;u!==void 0&&(C(e,82),xe(e,u));let f=n.msgID;f!==void 0&&(C(e,90),xe(e,f));let g=n.frameType;g!==void 0&&(C(e,96),ft(e,Xn(g)))}function _d(n){return wd(Ed(n))}function wd(n){let e={};e:for(;!Si(n);){let t=D(n);switch(t>>>3){case 0:break e;case 1:e.SeqID=ci(n,!0);break;case 2:e.LogID=ci(n,!0);break;case 3:e.service=D(n);break;case 4:e.method=D(n);break;case 5:{let r=yd(n);(e.headers||(e.headers=[])).push(pd(n)),n.limit=r;break}case 6:e.payloadEncoding=ke(n,D(n));break;case 7:e.payloadType=ke(n,D(n));break;case 8:e.payload=kd(n,D(n));break;case 9:e.LogIDNew=ke(n,D(n));break;case 10:e.serverTiming=ke(n,D(n));break;case 11:e.msgID=ke(n,D(n));break;case 12:e.frameType=D(n);break;default:_i(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 yd(n){let e=D(n),t=n.limit;return n.limit=n.offset+e,t}function _i(n,e){switch(e){case 0:for(;128&H(n););break;case 2:Yn(n,D(n));break;case 5:Yn(n,4);break;case 1:Yn(n,8);break;default:throw new Error("Unimplemented type: "+e)}}function Xn(n){return n|=0,{low:n,high:n>>31,unsigned:n>=0}}var wi=[];function yi(){let n=wi.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function Sd(n){wi.push(n)}function Ed(n){return{bytes:n,offset:0,limit:n.length}}function vd(n){let e=n.bytes,t=n.limit;return e.length===t?e:e.subarray(0,t)}function Yn(n,e){if(n.offset+e>n.limit)throw new Error("Skip past limit");n.offset+=e}function Si(n){return n.offset>=n.limit}function pt(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 mr(n,e){let t=n.offset;if(t+e>n.limit)throw new Error("Read past limit");return n.offset+=e,t}function kd(n,e){let t=mr(n,e);return n.bytes.subarray(t,t+e)}function xd(n,e){let t=pt(n,e.length);n.bytes.set(e,t)}function ke(n,e){let t=mr(n,e),r=String.fromCharCode,s=n.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],d,l,u,f;(128&c)===0?o+=r(c):(224&c)===192?a+1>=e?o+=i:(d=s[a+t+1],(192&d)!==128?o+=i:(f=(31&c)<<6|63&d,f<128?o+=i:(o+=r(f),a++))):(240&c)==224?a+2>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],((d|l<<8)&49344)!==32896?o+=i:(f=(15&c)<<12|(63&d)<<6|63&l,f<2048||f>=55296&&f<=57343?o+=i:(o+=r(f),a+=2))):(248&c)==240?a+3>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],u=s[a+t+3],((d|l<<8|u<<16)&12632256)!==8421504?o+=i:(f=(7&c)<<18|(63&d)<<12|(63&l)<<6|63&u,f<65536||f>1114111?o+=i:(f-=65536,o+=r((f>>10)+55296,(1023&f)+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}C(n,r);let s=pt(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 Id(n,e){let t=pt(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 H(n){return n.bytes[mr(n,1)]}function ai(n,e){let t=pt(n,1);n.bytes[t]=e}function D(n){let e=0,t=0,r;do r=H(n),e<32&&(t|=(127&r)<<e),e+=7;while(128&r);return t}function C(n,e){for(e>>>=0;e>=128;)ai(n,127&e|128),e>>>=7;ai(n,e)}function ci(n,e){let t=0,r=0,s=0,i;return i=H(n),t=127&i,128&i&&(i=H(n),t|=(127&i)<<7,128&i&&(i=H(n),t|=(127&i)<<14,128&i&&(i=H(n),t|=(127&i)<<21,128&i&&(i=H(n),r=127&i,128&i&&(i=H(n),r|=(127&i)<<7,128&i&&(i=H(n),r|=(127&i)<<14,128&i&&(i=H(n),r|=(127&i)<<21,128&i&&(i=H(n),s=127&i,128&i&&(i=H(n),s|=(127&i)<<7))))))))),{low:t|r<<28,high:r>>>4|s<<24,unsigned:e}}function ft(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=pt(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 Td(n){return _d(n)}function di(n){return mi(n)}var li=65536,Rd="\0\0\0\0\0\0\0\0",qe=li*li,Ei=qe*qe,ui=Ei/2,me=String.prototype.charCodeAt,z=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===Rd?fi:new n((me.call(e,0)|me.call(e,1)<<8|me.call(e,2)<<16|me.call(e,3)<<24)>>>0,(me.call(e,4)|me.call(e,5)<<8|me.call(e,6)<<16|me.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?Pd:fi;if(t){if(e>=Ei)return Cd}else{if(e<=-ui)return Od;if(e+1>=ui)return Ad}return n.fromBits(e%qe|0,e/qe|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*qe+(this.low>>>0):this.high*qe+(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,d=65535&e.low,l=0,u=0,f=0,g=0;return g+=i+d,f+=g>>>16,g&=65535,f+=s+c,u+=f>>>16,f&=65535,u+=r+a,l+=u>>>16,u&=65535,l+=t+o,l&=65535,n.fromBits(f<<16|g,l<<16|u,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]}},fi=new z(0,0,!1),Pd=new z(0,0,!0),Ad=z.fromBits(-1,2147483647,!1),Cd=z.fromBits(-1,-1,!0),Od=z.fromBits(0,-2147483648,!1),ve=(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})({}),Ie=class{constructor(e){this.type=e,this.target=null}},er=class extends Ie{constructor(e,t){super(e),this.message=t&&t.message||null}},tr=class extends Ie{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}},nr=class extends Ie{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}},rr=class extends Ie{constructor(e,t){super(e),this.data=t&&t.data||null}},sr=class extends rr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},ir=class extends Ie{constructor(e,t){super(e),this.data=t&&t.data||null}};function X(n,{message:e,code:t,error:r}){return new tr(n,{message:e,code:t,error:r})}function te(n,{code:e,reason:t,wasClean:r,willReconnect:s}){return new nr(n,{code:e,reason:t,wasClean:r,willReconnect:s})}function Nd(n,{data:e,message:t}){return new sr(n,{data:e,message:t})}function bd(n,{data:e}){return new ir(n,{data:e})}function hi(n,{message:e}){return new er(n,{message:e})}var sn=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()}},He=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Te=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",mt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",ht=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",Dd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,gt=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}},or=class extends gt{_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,mt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Te&&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=X("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let r=te("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",bd("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",te("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",Nd("message",{...e}))}),this._socket.onError(e=>{this.emit("error",X("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",X("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",X("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 Ld(n,e){if(e)return new e(n.url,n.protocol);if(mt||Te)return new or(n.url,n.protocol,n.headers);if((He||ht)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(n.url,n.protocols)}function Md(n){return!!(n||mt&&wx.connectSocket||Te&&tt.connectSocket||(He||ht)&&typeof WebSocket<"u"&&WebSocket)}function gi(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 vi(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 ki(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 ar(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 xi(n){if(typeof n=="string"){let e=new Uint8Array(vi(n));return ar(n,e,0),e}return n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Bd(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 Fd=(n,e)=>{switch(n){case"boe":case"ppe":return{[`x-use-${n}`]:1,"x-tt-env":e};default:return{}}},cr=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 Ud(n){return new Promise(e=>{if(!He)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 _e(n,e,t){return!!n?.find(r=>r.key===e&&r.value===t)}function Ge(n,e){return n?.find(t=>t.key===e)?.value}var Zn=null;async function $d(){return Zn||(Zn=Promise.resolve().then(()=>(si(),ri))),Zn}var dr=class extends gt{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 $d();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}}},lr=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}},ur=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Te?tt:mt?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 Ii(n,e){if(Te||Te)return new ur(n,e);if((He||ht)&&typeof indexedDB<"u")return new dr(n,e);if((He||ht)&&typeof localStorage<"u")return new lr(n,e);throw new Error("init QoSDB failed")}var fr=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Ii("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 _r(n){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=_e(n.message.headers,"x_frontier_qos","2"),r=t&&_e(n.message.headers,"x_frontier_qos_ack","1"),s=t&&_e(n.message.headers,"x_frontier_is_ack","1"),i=s?Ge(n.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:r,isAckCleanupMessage:s,ackMsgIds:i}}async function Ti(){return this._QoSManager||(this._QoSManager=new fr),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function zd(n,e){let{enableAutoAck:t}=this._options,r=_e(n.message.headers,"need_ack","1"),s=_e(n.message.headers,"is_ack","1"),i=_r.call(this,n);if(t&&r){let{SeqID:o,LogID:a,service:c,LogIDNew:d,method:l}=n.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:d,service:c,method:l,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:d||""},{key:"ack_code",value:"0"}]})}s&&!i.isQoSAck&&this._dispatchAckMessageEvent(n),e()}async function qd(n,e){this._debug("received",n.message),e()}async function Gd(n,e){let t=Td(await xi(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,d=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],l=["none_none","binary"];this._options.enableTransformTextPayload&&d.includes(a)&&(!c||l.includes(c))?t.textPayload=ki(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(r){t.textPayload="",console.log(r)}n.message=t,e()}function Hd(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 Wd=4294967295;function jd(n,e,t){if(t>Wd)throw new Error("integer too large");let r=3;for(;r>=0;){let s=255&t;gr(s,n,e+r),t>>>=8,r--}return e+4}function Jd(n,e){let t=0,r=e,s=e+4;for(;r<s;){let{value:i,offset:o}=hr(n,r);r=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function Vd(n,e,t){return n?n.length<40?ar(n,e,t)+t:e.utf8Write?e.utf8Write(n,t)+t:e.write?e.write(n,t)+t:ar(n,e,t)+t:t}function Qd(n,e){let t=new z(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 Kd(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 hr(n,e){return n.readUInt8?{value:n.readUInt8(e),offset:e+1}:{value:255&n[e],offset:e+1}}function gr(n,e,t){return e.writeUint8?e.writeUint8(n,t):e[t]=255&n,t+1}var Xd=function(n){return new Uint8Array(n)},Yd=typeof Buffer<"u"?Buffer.allocUnsafe:Hd(Xd,Uint8Array.prototype.subarray),Zd=16,wr=32;function el(n){let e=0,t={};for(let r=0;r<n.length;r++)t[n[r].cursor_name]=vi(n[r].cursor_name),e+=14+t[n[r].cursor_name];return[e,t]}function pi(n,e,t){let[r,s]=el(n),i=Yd(r),o=0;return n.forEach(a=>{console.log("cursor.service",a,a.service),o=gr(0,i,o),console.log("header",o),o=jd(i,o,a.service||0),console.log("service",o),o=gr(s[a.cursor_name],i,o),console.log("service-name",o),o=Vd(a.cursor_name,i,o),console.log("name",o),o=Kd(z.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:wr,headers:[{key:"cursor_file_name",value:t}],payload:i}}function tl(n){let e=0,t=[];for(;e<n.byteLength;){let{offset:r}=hr(n,e);e=r;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=Jd(n,e);s.service=i,e=o;let{value:a,offset:c}=hr(n,e);e=c,s.cursor_name=ki(n,e,e+a),e+=a;let{value:d,offset:l}=Qd(n,e);s.cursor=d.toNumber(),e=l,t.push(s)}return t}function nl(){return{frameType:wr,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var pr=class{constructor(e,t,r){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=r,this._qosDB=Ii(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?pi(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?pi(t,0,this._cursorFileName):nl()}}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=tl(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}},rl="__x_msg_qos__";async function Ri(n){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:r}=this._options,s=n||rl;try{return this._cursorManager?n&&this._cursorManager.updateCursorFileName(n):this._cursorManager=new pr(`${t}_${e}_${s}`,s,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function sl(n,e){let t=_e(n.message.headers,"code","-1"),r=_e(n.message.headers,"is_ack","1"),s=Ge(n.message.headers,"x_frontier_msgid"),i=Number(Ge(n.message.headers,"x_frontier_ttl"))||0,o=_r.call(this,n),a=_e(n.message.headers,"x-msg-qos","2"),c=Ge(n.message.headers,"x-msg-cursor_name"),d=Number(Ge(n.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let l=o.isQoSMessage?await Ti.call(this):null;if(n.message.service>0&&r&&!t||n.message.service>0){if(s&&o.isQoSMessage&&l)return await l.get(s)||(this._dispatchMessageEvent(n),await l.set(s,Date.now()+i)),e();if(a){let u=await Ri.call(this);if(!u)return this._dispatchMessageEvent(n),e();let f=await u.get(c)??-1;if(f<d)this._dispatchMessageEvent(n),u.set(c,d,n.message.service);else throw new Error(`recevied message cursor ${d} larger than local cursor ${f}`);return e()}return this._dispatchMessageEvent(n),e()}}async function il(n,e){let t=_r.call(this,n);if(!t.isQoSMessage)return e();let r=await Ti.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await r.del(s);e()}async function ol(n,e){let t=n.message.frameType===Zd,r=n.message.frameType===wr;if(!t&&!r)return e();let s=Ge(n.message.headers,"cursor_file_name");if(!s)return e();let i=await Ri.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:z.fromNumber(this._seqId++),LogID:z.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=mi(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=n.message.payload;o&&i.setCursors(o)}}var al=async function(n,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},cl=async function(n,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},dl=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()},on=class extends gt{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=He,this._isNode=Dd,this._isMiniTT=Te,this._isMiniWX=mt,this._isWorker=ht,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{gi(this,i,[al,dl,cl])}catch(o){let a=X("error",{message:o.message,code:ve.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{gi(this,i,[Gd,zd,il,ol,sl,qd])}catch(c){let d=X("error",{message:c.message,code:ve.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(d)}},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(X("error",{message:c,code:ve.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(X("error",{message:i.message,code:ve.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(te("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(te("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 Ud(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(te("close",{code:i.code,reason:c}));let d=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(X("error",{message:d,code:ve.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(te("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:dd,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(!Md(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new sn(s,this._options.maxRetries),this._pingLossCounter=new cr(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=hi("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:d,enableQoS:l,QoSLevel:u,env:f}=this._options,g,m,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(g=location&&location.protocol=="https:"?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${g}${m}`):(g="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${g}${m}`);let E=s?"bd_did":i?"ttwid":"device_id",L=s||i||r;if(!L||!E)throw new Error("please provide bddID, deviceID or ttwID");let B=typeof c=="function"?await c():c,re=f?Fd(f.xUseEnv,f.xTTEnv):{},M=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[E]:L,xsack:d?1:0,xaack:d?1:0,xsqos:l?1:0,qos_level:l?u:void 0,qos_sdk_version:2,...re},B),p=Object.keys(M).reduce((S,I)=>M[I]!==void 0?`${S}${S?"&":"?"}${I}=${M[I]}`:S,"");return`${_}/ws/v2${p}`}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=X("error",{message:a,code:ve.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(X("error",{message:a,code:ve.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=hi("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=Ld({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=di(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(te("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(te("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(te("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(te("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 xi(e),s=Bd(e),{method:i=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:d=this._options.payloadEncoding,payloadType:l=this._options.payloadType,logIDNew:u=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?cd(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let f={SeqID:z.fromNumber(this._seqId++),LogID:z.fromNumber(a),service:o,method:i,headers:c,payloadEncoding:d instanceof Object?d.encoding?d.encoding:"":d,payloadType:l instanceof Object?l.type?l.type:s:l||s,payload:r,LogIDNew:u},g=di(f);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(g),this._debug("sent",f)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(g),this._debug("enqueue",f)):(this._messageQueue.shift(),this._messageQueue.push(g)),{seqID:this._seqId,logID:a,logIDNew:u}}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 sn(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 Au=ue(ko(),1),Cu=ue(pn(),1),Ou=ue(Je(),1),Nu=ue(Ar(),1),bu=ue(Nr(),1),Du=ue(Fr(),1),No=ue(yn(),1),Lu=ue(Oo(),1);var bo=No.default;k();var O=w("upstream.frontier"),Lo="application/json",Mo="none",En=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){O.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:fs,...Dt(this.opts.ppeOverride)};class t extends bo{constructor(a){super(a,us,{headers:e})}send(a,...c){if(as("debug"))try{let d;typeof a=="string"?d=Buffer.from(a,"utf8"):a instanceof Buffer?d=a:a instanceof ArrayBuffer?d=new Uint8Array(a):ArrayBuffer.isView(a)?d=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):d=new Uint8Array(0);let l=Buffer.from(d.slice(0,128)).toString("hex");O.debug("WS raw frame out",{bytes:d.byteLength,headHex:l})}catch(d){O.warn("WS raw frame dump failed",{err:String(d)})}super.send(a,...c)}}let r=ps(this.opts.urlOverride),s={url:r,ws:t,fpID:ls,aID:bt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Lo,force:!0},payloadEncoding:{encoding:Mo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new on(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;O.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=>O.warn("onConnect handler threw (ignored)",{err:String(a)}))},i.onclose=o=>{this.opened=!1,O.info("frontier closed",{code:o.code,reason:o.reason,willReconnect:o.willReconnect})},i.onerror=o=>{O.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){O.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;Bo(s)||O.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:r.length});try{await t.send(r,{service:33555712,method:1,payloadType:Lo,payloadEncoding:Mo})}catch(o){throw O.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){O.debug("drop non-adapter frontier frame",{service:t});return}let r=Fu(e);if(!r){O.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){O.debug("frame received but no onFrame handler",{size:r.length});return}let s;try{s=JSON.parse(r)}catch(o){O.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let i=s;Bo(i)||O.info("frontier frame in",{logid:Bu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:i.id}),Promise.resolve(this.handler(s)).catch(o=>O.warn("frontier frame handler threw",{err:String(o)}))}};function Bo(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}function Bu(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function Fu(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 $r=w("upstream.switchable"),vn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;$r.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 $r.error("swap target start failed, reverting",{err:String(s)}),this.inner=r,s}await r.stop(t??"swapped").catch(s=>$r.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 zr=w("upstream"),xt=class{handler=null;async start(){zr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){zr.info("NoopUpstream stopped",{reason:e})}async send(e){zr.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();U();k();U();import{execSync as Uu}from"node:child_process";import{readFileSync as Fo,unlinkSync as $u}from"node:fs";import{mkdir as zu,readFile as Uo,unlink as $o,writeFile as qu}from"node:fs/promises";import{dirname as Gu}from"node:path";var Hu=w("single-instance"),kn=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&&(Hu.warn("removing stale pid file",{stalePid:e}),await $o(this.pidFile).catch(()=>{})),await zu(Gu(this.pidFile),{recursive:!0}),await qu(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Uo(this.pidFile,"utf8")).trim()===String(process.pid)&&await $o(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Uo(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=Fo(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=Uu(`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{Fo(this.pidFile,"utf8").trim()===String(process.pid)&&$u(this.pidFile)}catch{}})}};var y=w("daemon"),Wu="coze-bridge-daemon";async function Go(){let n=new kn({processTitle:Wu}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await tn(),r=t??{};Mn({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let p=new $e;r.frameworksCache=await p.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(r.frameworksCache)})}catch(p){y.warn("framework detection failed",{err:String(p)})}await ze(r);let s=new vn(new xt),i=T(),o=null,a=new nn({upstream:s,paths:i,bridgeConfig:r,sessionSpawner:async(p,S,I,J)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(p,S,I,J)}});await Ju(i,a);let c=new en({paths:i,config:r,registry:a});o=c;let d,l,u=null,f=null;a.registerExtension("_agent/create",async p=>c.createAgent(p.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let g={},m=new Bt({agents:a.agents,disposeAndMarkDisconnected:async(p,S)=>{let I=a.agents.get(p);I&&(await c.cleanupOpenclawSessionProviders(I).catch(J=>y.warn("cleanup openclaw providers failed (ignored)",{agentId:p,err:String(J)})),await I.dispose(`disconnect: ${S}`).catch(J=>y.warn("dispose during disconnect failed (ignored)",{agentId:p,err:String(J)})),I.status="disconnected",a.unregister(p)),a.disconnectedAgents.add(p)},detailSyncer:async p=>{if(!g.ref)throw new Error("agent-detail-sync not initialized yet");await g.ref.syncOne(p)},openclawRepair:async(p,S)=>{await c.openclawRepair(p,S)}});a.registerExtension("_agent/listSkills",p=>m.listSkills(p.params)),a.registerExtension("_agent/addSkills",p=>m.addSkills(p.params)),a.registerExtension("_agent/removeSkills",p=>m.removeSkills(p.params)),a.registerExtension("_agent/getFileTree",p=>m.getFileTree(p.params)),a.registerExtension("_agent/getFileContent",p=>m.getFileContent(p.params)),a.registerExtension("_agent/update",p=>m.updateAgent(p.params)),a.registerExtension("_agent/disconnect",p=>m.disconnectAgent(p.params)),a.registerExtension("_agent/switchModel",p=>m.switchModel(p.params)),a.registerExtension("_agent/reset",p=>m.resetAgent(p.params)),a.registerExtension("_agent/repair",p=>m.repairAgent(p.params));let _=new Nt({paths:i,handlers:m,sendDetail:p=>a.sendRequest("_agent/detail",p)});g.ref=_,s.onConnect(({initial:p})=>{y.info("frontier upstream connected, triggering detail sync",{initial:p}),_.syncAll(p?"initial-connect":"reconnect").catch(S=>y.warn("detail sync top-level error (ignored)",{err:String(S)}))});let E=new rn({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:u??"",frameworksCache:r.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async p=>{let S=p,I=S?.privatecode,J=S?.pairing_code;if(!I||!J)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ne=Lt(S.env),et=S.handshake_url,On=S.frontier_url,Nn=ju(S.env,et,On),Zr=!!d&&d!==I,es=l!==void 0&&l!==Nn,ts=Zr||es;if(ts){y.warn("pair config switched, resetting agents",{pcChanged:Zr,envChanged:es,previousPc:d?zo(d):"",nextPc:zo(I),previousEnvKey:l??"",nextEnvKey:Nn});for(let V of[...a.agents.values()])await V.dispose("pair config switch").catch(()=>{}),a.agents.delete(V.agentId);await s.swap(new xt,"pair switch").catch(()=>{})}let ns=await _s({privatecode:I,...et?{endpoint:et}:{},ppeOverride:Ne});u=ns.deviceId,Mn({deviceId:u,pid:process.pid});let na=new En({handshake:ns,privatecode:I,...On?{urlOverride:On}:{},ppeOverride:Ne});await s.swap(na,"pair");try{let V=new $e;r.frameworksCache=await V.detectAll(),await ze(r),y.info("frameworks_cache refreshed before pair",{detected:Object.keys(r.frameworksCache)})}catch(V){y.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(V)})}let ra=Object.keys(r.frameworksCache??{});try{let V=await a.sendRequest("_agent/pair",{pairCode:J,patToken:I,frameworks:ra,_meta:{cozeDeviceId:u}});y.info("_agent/pair ok",{pairResult:V}),d=I,l=Nn,f||(f=new $t({core:a,getDeviceId:()=>u??""})),f.start(),ts&&qo(i,c).catch(be=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(be)}));let bn;return S.agent_id&&(bn=await Vu(S.agent_id,i,c,be=>a.sendRequest("_agent/detail",be)).catch(be=>(y.error("--agent-id ensureAgent failed",{agentId:S.agent_id,err:String(be)}),{ok:!1,agentId:S.agent_id??"",note:String(be)}))),{ok:!0,note:"paired with cloud",...bn?{agent:bn}:{}}}catch(V){return y.error("_agent/pair failed",{err:String(V)}),{ok:!1,note:`pair failed: ${String(V)}`}}}},{method:"POST",path:"/_agent/create",handler:async p=>{let S=p;return{ok:!0,result:await c.createAgent(S)}}},{method:"POST",path:"/refresh",handler:async()=>{y.info("IPC /refresh: re-detecting frameworks");let p=new $e;return r.frameworksCache=await p.detectAll(),await ze(r),{ok:!0,frameworks:r.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{M.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:L,token:B}=await E.start();await a.start(),qo(i,c).catch(p=>y.warn("auto-revive top-level error (ignored)",{err:String(p)}));let re=null,M={port:L,token:B,core:a,ipc:E,shutdown(p){return re||(y.info("daemon shutdown",{reason:p}),re=(async()=>{f?.stop(),await a.stop(p),await E.stop(),await n.release()})(),re)}};for(let p of["SIGTERM","SIGINT"])process.on(p,()=>{M.shutdown(p).then(()=>process.exit(0))});return y.info("daemon ready",{port:L,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(r.frameworksCache??{}),libVersion:r.libVersion??"dev"}),M}function zo(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function ju(n,e,t){return`${n??""}|${e??""}|${t??""}`}async function Ju(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(()=>(fe(),Ot));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 Vu(n,e,t,r){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(fe(),Ot)),i=await s(n,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:n,framework:i.framework,hadDisconnect:!!i.disconnectedAt});let d={agentId:i.agentId,framework:i.framework,...i.cozeIdentity?{cozeIdentity:i.cozeIdentity}:{},...i.model?{model:i.model}:{}};return await t.createAgent(d),{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 qo(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(()=>(fe(),Ot));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(d){y.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(d)}),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(d){y.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(d)}),o+=1}}return y.info("auto-revive: done",{revived:i,skipped:o,total:r.length}),{revived:i,skipped:o,total:r.length}}Gr();U();import{readFile as Wo}from"node:fs/promises";var Se=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:rf(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([Wo(this.paths.portFile,"utf8"),Wo(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:nf(c)}}finally{clearTimeout(o)}}};function nf(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function rf(n){return n instanceof Error?n.message:String(n)}k();U();import{copyFile as jo,mkdir as sf,readFile as Hr,writeFile as of}from"node:fs/promises";import{dirname as af,resolve as Wr,sep as xn}from"node:path";import{fileURLToPath as cf}from"node:url";k();U();var Jo=w("dist-install");function df(n){let e=cf(n),t=af(e),r=`${xn}src${xn}`;if(t.includes(r)||t.endsWith(`${xn}src${xn}cli`))return null;let s=Wr(t,"index.js"),i=Wr(t,"..","package.json");return{dist:s,pkgJson:i}}async function Vo(n={}){let e=n.paths??T(),t=df(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 Hr(s,"utf8")).version??"unknown"}catch(u){return Jo.warn("cannot read source package.json,skip dist install",{err:String(u)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(u)}`}}let o=await tn(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Hr(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await sf(e.libDir,{recursive:!0}),await jo(r,e.libEntry),await jo(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Wr(e.libDir,"package.json"),d=`${JSON.stringify({type:"module"},null,2)}
|
|
94
|
+
`;return await Hr(c,"utf8").catch(()=>null)!==d&&await of(c,d),o.libVersion=i,await ze(o,e.configFile),Jo.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 Pf=w("cli");function Ze(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 Af(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}=Ze(t,"--pat-token");t=s;let{value:i,rest:o}=Ze(t,"--pair-code");t=o;let{value:a,rest:c}=Ze(t,"--env");t=c;let{value:d,rest:l}=Ze(t,"--handshake-url");t=l;let{value:u,rest:f}=Ze(t,"--frontier-url");t=f;let{value:g}=Ze(t,"--agent-id");if(!r||!i)return{mode:"help"};let m={mode:"pair",privatecode:r,pairingCode:i};return a&&(m.env=a),d&&(m.handshakeUrl=d),u&&(m.frontierUrl=u),g&&(m.agentId=g),m}var Cf=`
|
|
95
95
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
96
96
|
|
|
97
97
|
Usage:
|
|
@@ -100,6 +100,7 @@ Usage:
|
|
|
100
100
|
npx -y coze-bridge@latest --stop stop daemon
|
|
101
101
|
npx -y coze-bridge@latest --refresh re-detect agent binaries (claude/codex/openclaw)
|
|
102
102
|
npx -y coze-bridge@latest --uninstall stop daemon + remove ~/.coze
|
|
103
|
+
npx -y coze-bridge@latest --version print current Bridge version (D63)
|
|
103
104
|
|
|
104
105
|
Required (for pair):
|
|
105
106
|
--pat-token <sat_xxx> coze PAT token (\u4ECE coze \u5E73\u53F0\u62FF)
|
|
@@ -118,35 +119,36 @@ Auto-connect agent (optional):
|
|
|
118
119
|
|
|
119
120
|
Internal:
|
|
120
121
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
121
|
-
`.trimStart();async function
|
|
122
|
-
`),
|
|
123
|
-
`),1;
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
`),0;if(
|
|
127
|
-
`),0;
|
|
128
|
-
`),0
|
|
129
|
-
`),
|
|
130
|
-
`),1
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
`),
|
|
134
|
-
`),1}
|
|
135
|
-
`);
|
|
136
|
-
`)
|
|
137
|
-
`)}
|
|
138
|
-
`)}
|
|
139
|
-
`)}
|
|
122
|
+
`.trimStart();async function ea(n=process.argv,e={}){let t=Af(n);switch(t.mode){case"help":return process.stdout.write(Cf),0;case"version":return process.stdout.write(`${Ut}
|
|
123
|
+
`),0;case"daemon":{try{await Go()}catch(r){return Pf.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return Of(e);case"stop":return Nf(e);case"refresh":return bf(e);case"uninstall":return Df(e);case"install-service":return Lf();case"pair":{let r={};return t.env&&(r.env=t.env),t.handshakeUrl&&(r.handshakeUrl=t.handshakeUrl),t.frontierUrl&&(r.frontierUrl=t.frontierUrl),Mf(t.privatecode,t.pairingCode,e,r,t.agentId)}}}async function ta(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 Of(n){let e=n.paths??T(),t=new Se(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
124
|
+
`),1;if(r.kind==="stale")return await ta(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
125
|
+
`),1;let s=await t.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
126
|
+
${JSON.stringify(s.body,null,2)}
|
|
127
|
+
`),0}async function Nf(n){let e=n.paths??T(),t=new Se(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
128
|
+
`),0;if(r.kind==="stale")return await ta(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
129
|
+
`),0;try{return await t.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
130
|
+
`),0}catch(s){return process.stdout.write(`coze-bridge: stop failed: ${String(s)}
|
|
131
|
+
`),1}}async function bf(n){let e=new Se(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
132
|
+
`),1;try{let r=await e.request({method:"POST",path:"/refresh"});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
133
|
+
${JSON.stringify(r.body,null,2)}
|
|
134
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
|
|
135
|
+
`),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
|
|
136
|
+
`),1}}async function Df(n){let e=new Se(n.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
137
|
+
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(i){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(i)}
|
|
138
|
+
`)}await new Promise(i=>setTimeout(i,500))}if(!n.skipSupervisor)try{let{getSupervisor:i,buildContext:o}=await Promise.resolve().then(()=>(Yr(),Xr)),a=i();await a.uninstall(o()),process.stdout.write(`coze-bridge: ${a.platform} supervisor unregistered
|
|
139
|
+
`)}catch(i){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(i)}
|
|
140
|
+
`)}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}
|
|
141
|
+
`)}catch(i){return process.stderr.write(`coze-bridge: remove failed: ${String(i)}
|
|
140
142
|
`),1}return process.stdout.write(`coze-bridge: uninstalled
|
|
141
|
-
`),0}async function
|
|
142
|
-
`),await
|
|
143
|
-
`),0}catch(
|
|
144
|
-
`),1}}async function
|
|
145
|
-
`),(await
|
|
146
|
-
`)}let
|
|
147
|
-
`),await
|
|
148
|
-
`),1;let
|
|
149
|
-
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
150
|
-
`),1)}catch(
|
|
151
|
-
`),1}}async function
|
|
143
|
+
`),0}async function Lf(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(Yr(),Xr)),t=n(),r=e();return process.stdout.write(`coze-bridge: installing ${t.platform} supervisor...
|
|
144
|
+
`),await t.install(r),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
145
|
+
`),0}catch(n){return process.stderr.write(`coze-bridge: --install-service failed: ${String(n)}
|
|
146
|
+
`),1}}async function Mf(n,e,t,r={},s){let i=new Se(t.paths),o=t.spawnDaemon??Ho;if(!t.skipDistInstall){let d=await Vo({paths:t.paths});d.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${d.fromVersion} \u2192 ${d.toVersion}
|
|
147
|
+
`),(await i.probe()).kind==="connected"&&(await i.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(u=>setTimeout(u,500)))):d.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${d.libVersion}
|
|
148
|
+
`)}let a=await i.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
149
|
+
`),await o({paths:t.paths}),a=await Bf(i,t.waitTimeoutMs??1e4,t.sleep??Ff),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
|
|
150
|
+
`),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 d=await i.request({method:"POST",path:"/pair",body:c,timeoutMs:35e3});return d.status===200&&d.body?.ok?(process.stdout.write(`coze-bridge: paired (${d.body.note??"ok"})
|
|
151
|
+
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(d.body)}
|
|
152
|
+
`),1)}catch(d){return process.stderr.write(`coze-bridge: pair failed: ${String(d)}
|
|
153
|
+
`),1}}async function Bf(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 Ff(n){return new Promise(e=>setTimeout(e,n))}ea(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
|
|
152
154
|
`),process.exit(1)});
|