coze-bridge 0.1.12 → 0.1.14
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 +53 -52
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
|
|
|
5
5
|
const require = __coze_createRequire(import.meta.url);
|
|
6
6
|
const __filename = __coze_fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __coze_dirname(__filename);
|
|
8
|
-
var
|
|
9
|
-
`,
|
|
10
|
-
`):
|
|
11
|
-
`)}function R(r){return{debug:(e,i)=>Jt("debug",r,e,i),info:(e,i)=>Jt("info",r,e,i),warn:(e,i)=>Jt("warn",r,e,i),error:(e,i)=>Jt("error",r,e,i),child:e=>R(`${r}.${e}`)}}var Vt,Es,Q0,ea,As,K=Ie(()=>{"use strict";Vt={debug:10,info:20,warn:30,error:40},Es=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),Q0=process.stdout,ea=process.stderr,As={}});import{homedir as ta}from"node:os";import{join as ee}from"node:path";function H(r){let e=r??ta(),i=ee(e,".coze"),a=ee(i,"bridge"),x=ee(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:x,libEntry:ee(x,"index.js"),pidFile:ee(a,"bridge.pid"),portFile:ee(a,"bridge.port"),tokenFile:ee(a,"bridge.token"),logFile:ee(a,"bridge.log"),installLock:ee(a,"install.lock"),configFile:ee(a,"config.json"),agentsRoot:ee(i,"agents")}}function Te(r,e=H()){let i=ee(e.agentsRoot,r);return{root:i,config:ee(i,"config.json"),workspace:ee(i,"workspace"),logs:ee(i,"logs")}}var oe=Ie(()=>{"use strict"});var Zt={};vs(Zt,{AGENT_CONFIG_FILE_MODE:()=>Yt,enforceAgentConfigMode:()=>sa,loadAgentConfig:()=>ae,persistAgentSessions:()=>lr,persistAgentSkills:()=>Xt,saveAgentConfig:()=>ge});import{chmod as na,stat as ra}from"node:fs/promises";function ae(r,e){return Gt(Te(r,e).config)}function ge(r,e){return Wt(Te(r.agentId,e).config,r,{mode:Yt})}async function sa(r,e){if(process.platform==="win32")return;let i=Te(r,e).config;try{let a=await ra(i);if(!a.isFile())return;let x=a.mode&511;x!==Yt&&(await na(i,Yt),ks.warn("agent config mode auto-corrected to 0600",{path:i,from:x.toString(8)}))}catch(a){if(a.code==="ENOENT")return;ks.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function lr(r,e,i){let a=await ae(r,i);a&&(a.sessions=Object.fromEntries(e),await ge(a,i))}async function Xt(r,e,i){let a=await ae(r,i);a&&(a.skills=e,await ge(a,i))}var ks,Yt,Ue=Ie(()=>{"use strict";ur();K();oe();ks=R("agent-config"),Yt=384});var di=ie(j=>{"use strict";var S=P;(function(r,e){let i=P,a=r();for(;;)try{if(parseInt(i(1185))/1*(parseInt(i(1860))/2)+-parseInt(i(1009))/3+parseInt(i(1324))/4+parseInt(i(833))/5*(-parseInt(i(534))/6)+parseInt(i(1079))/7*(-parseInt(i(1533))/8)+-parseInt(i(931))/9*(-parseInt(i(1814))/10)+parseInt(i(526))/11*(parseInt(i(753))/12)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(vn,828896);function P(r,e){r=r-378;let i=vn(),a=i[r];if(P.WIebtq===void 0){var x=function(m){let _="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",b="",w="";for(let C=0,k,T,L=0;T=m.charAt(L++);~T&&(k=C%4?k*64+T:T,C++%4)?b+=String.fromCharCode(255&k>>(-2*C&6)):0)T=_.indexOf(T);for(let C=0,k=b.length;C<k;C++)w+="%"+("00"+b.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(w)};P.eZGfgU=x,P.ZQPubA={},P.WIebtq=!0}let f=i[0],l=r+f,h=P.ZQPubA[l];return h?a=h:(a=P.eZGfgU(a),P.ZQPubA[l]=a),a}var yx=Object[S(1676)+"operty"],bx=Object[S(400)+S(1366)+S(1308)],ai=(r,e)=>function(){return r&&(e=(0,r[{wupeG:function(x,f){return x(f)}}.wupeG(bx,r)[0]])(r=0)),e},vx=(r,e)=>{let i={wVjQY:function(x,f,l,h){return x(f,l,h)}};for(var a in e)i.wVjQY(yx,r,a,{get:e[a],enumerable:!0})};function Sx(){return ni||(ni=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Cx(){let r=S;return ri||(ri=[IDBCursor[r(1276)+"e"].advance,IDBCursor[r(1276)+"e"][r(1787)],IDBCursor[r(1276)+"e"][r(1787)+r(733)+"ey"]])}function Ex(r){let e=S,i={fjTlc:function(x,f){return x(f)},EwidR:function(x){return x()},KLNwn:function(x){return x()},VLkwd:e(831),GSaRr:e(1227),UrXVl:function(x,f,l){return x(f,l)},eAoeU:e(1559)+"t",CosvY:e(715),NKWdF:function(x,f){return x===f},JRgiL:e(1260)},a=new Promise((x,f)=>{let l=e,h={iaXjE:l(1227),mkUxG:function(w,C){return i[l(1443)](w,C)},jDFBG:function(w){return i[l(1854)](w)}},m=()=>{let w=l;r[w(447)+w(502)+w(1163)](w(831),_),r[w(447)+w(502)+"ner"](h[w(976)],b)},_=()=>{let w=l;x(i[w(1443)](Ce,r[w(721)])),i[w(452)](m)},b=()=>{let w=l;h[w(1638)](f,r[w(1227)]),h[w(1278)](m)};r[l(635)+"Listener"](i.VLkwd,_),r.addEventListener(i[l(1118)],b)});return a[e(1407)](x=>{let f=e;if(x instanceof IDBCursor)if(i[f(1747)](i[f(1241)],f(1370))){let l=i[f(1007)](_0x4ca72c,i[f(1773)],{message:i[f(1650)]});this["onStartR"+f(918)]&&this["onStartR"+f(918)](l)}else wr[f(756)](x,r)}).catch(()=>{}),Cn[e(756)](a,r),a}function vn(){let r=["Dvb6wLO","q0vkDge","DfbZyLG","Ef9MCM9UDgK","y2HHCKnVzgu","Cg9PBNrdB24","wM9SD0m","DgfIyxnL","z2v0sxrLBq","zw5JB2rLrNi","Ew50swi","t0Hutha","quHTvgW","swngrwe","rwPnBMq","y3jLyxrLt3a","x2rLC3rYB3K","Bg9Nsurhzw4","uvzmvK0","zxmGCMvHy2G","B21tv0e","AgjRtK8","DcbSAw1PDa","yMfSu2nVCgu","zMX1C2HfEha","twLZC2LUzYa","quzjuNu","x3bHDgHlzxK","Duz6yLK","zNbgvgi","sLr4CwC","DMvYC2LVBMm","y3jLyxrLq2W","wLDbt3u","zufns2G","CMfTugfYyw0","Ber5qxC","Bu9vyNi","uNn4z0S","Dgv6reW","y2vZC0HHBMq","tKTxzey","sfDsD3O","rgnjCem","zffjsLO","A01fy1y","x3vYBa","zujWBvq","u2vXsuq","ChvZAa","ChjVDg9JB2W","AxnrB1nnzxm","u2jlCg0","tfPhvLi","q2fRALK","BKLnEeO","zNjHBwvuExa","DLPXyva","B1Desuy","Dg9iyxnO","tuDoswu","x2jPBMfYEvq","swH3wwO","y3vYDMfSDwu","BLPztLi","zcWG","sKzQCfy","zufVzvu","vLv0r00","BNrczgG","Bw5xuxO","A05wtKC","ug1Vu2C","rfHwALi","EwDwruu","yMLUyxj5vhK","BgPfuhe","Be1OAhm","r0rtuuG","r1vmugu","Ag5yBhG","y29UDgLUDwu","BxrzD1q","shvuv24","zgvSzxrLrge","BffKCfK","sgHxCxy","yxv0B21HDgK","BMv3vMvYC2K","CMvXDwLYzwq","tgfrEM8","Bhb5u1K","x3fVC0rc","ExbL","C0TRvvu","B1zZAxa","CunuzuG","yNPeD2y","zLvZCMW","rMTSr04","tg9NsurozxC","C0XPC3rLBMu","DMvUDa","zNjVBunOyxi","BMXVsKW","yM9L","AxbrDg4","rLP2ExK","mtbxAfLKuLK","zLbkEhe","Bw9TCeq","A0jQA3u","CuP5Aei","sKX3q0K","Auz4ANG","t1fJwxm","s0T0s2y","zM1br0y","B2fK","BgLZDgvUtMu","z29PBMCGyxC","BwrXvKu","tefcDhC","BNrbBMrvCgq","ihn1y2nLC3m","tg9Nsuq","zwrWv0W","x29Uq2XVC2u","qw5TCNC","Dener3i","sLnptLa","tKfPqNq","v2LjsMS","yvfxA2y","txPkq28","vhnJtKK","sxLVDxO","DMfSDwu","suXxAMW","rw1wDgi","D3njDK8","BNruCMLLC0m","z1PgA3a","DhjHBNnHy3q","x2rPC3bHDgm","ExHyExK","DKffAwS","q2DOrey","s0XoD24","Aw5JBhvKzxm","zKPdzeW","AwDHDg9Yt24","D0jWCKu","z2PTDvi","mLjtq0LoqW","EwPnsfK","C3nHz2vfDMu","DuPNAuu","u0LSBxm","sgv0DMO","vejuzMK","Dwj6uuO","BLbhyLC","Axf4tgq","zenNBLC","v3fwC0C","ANfRy1q","EKrkrxm","y29UDgv4Da","A0HPzMu","ywXPzcb1CMW","ywDL","AffSuee","CMvHC29U","DhjPzxmGCMu","Dhj3vMq","x2XPC3rLBMu","m3W0Fdj8mhW","zxH0zw5ZAw8","AwrI","zMjIqKS","EeXMB1O","q291BNq","r1jKweO","ihrYEsbYzwm","BfDSBxu","qLrWt3i","EMjLwhe","C3L2C24","Aw50zwDLCIa","BvPbvLO","AfbyBee","txfREgi","BwvZC2fNzv8","igzPzwXKoIa","B3vIueW","y2uGBM90igK","x21LC3nHz2u","yuL1tuK","qLrxDNO","ExzjA1G","x2rItMfTzq","C2vYDMLJzq","y25PCeq","zg9Uzq","zgLZCgf0y2G","ENrxs3O","tNvYzMm","Cg9PBNrbBMq","sKTdtg8","CMvZzxrfBMq","Ahr0Chm6","BNrfBMrWB2K","suHxrxO","D3nZoI8V","EsbJBg9Zzwq","z2v0t3DUuhi","vLDKEu4","y29Kzq","C0z5yKS","BwvZC2fNztO","q2TJzuO","vNzgC1a","x3bPBMDqB24","uxDPzeG","AgjSB2S","DxbKyxrLq3u","uMfIuxy","DMzRANu","DhvJvey","rwzhCgm","vfbUz3O","vMXksve","DMvLtMq","Dg9cExrLCW","EwTcwxe","uK5Qz2e","BwjrCK8","y1rSCKK","t3bdDwC","Aw5Lza","y3jLyxrLt2i","BMDLza","wxn4Eg0","vxDUEw4","y3r4","u0zkre4","BMnrtfm","qwLHBMC","yMLUyxj5","zwn0","sg56vKS","CMfNzvn5BMm","yw1LoIa","BgD5C3O","wuTksKS","svnnCMG","zw5fDMvUDa","wxviz3q","qMzpEwi","zw50","tejewey","BNnqD1q","CMvTB3zLrxy","EfL2r0y","B25szwnLAxy","BvPtEhq","s0D2v0O","rxDPzfi","Dg9hzw5LCMe","thr2ywS","DLvXCLG","EwjkBha","uM14Ag0","D3f4vfO","sgjdufy","Dgv4Dc9Qyxy","CKz4y3K","ywrKq291BNq","DeLK","tMfTzq","s0net0S","DKDVzge","rKLmrv9ot1q","x2fKzfDZtgK","BM5ssgC","q3zsrhe","vLHruhe","s0zHuMS","zwvVA2i","D0vkDLO","C2vUza","AxjLza","wMf0B1m","yLvWwfi","CMfTzq","Cvj6ufG","wg90q0O","r0HnBNG","vNLpBxG","ywrK","BgLUzw5V","t0XdEgK","su5Pyue","wKPSwMm","C0ruDeW","mdaWma","BNrLCG","Dw50","wLf5wuK","AgLNAa","t1PMuuy","zKDduMC","q3vZDg9Tq2W","AM9PBG","revcANe","DeLUDgvYy2u","ig1LC3nHz2u","zw50tgLZDgu","BwvY","z2v0q3vYCMu","ANvYD2i","CM92AwrLige","zKH3vKq","AeXiENi","Dxrjza","B25dBg9Zzq","AwDjtKm","sKP3z1u","ueT4Aha","yMrtt2e","zxjYtM8","q3DJsw8","B25TzxnZywC","CwvvBM4","svfVAgK","AM5ytKO","uKXfrvG","C29YDa","svflCeS","CenxB1i","BMnLq2XVC2u","otLvv0TQwNG","zujvChC","vgfN","yMfJA3vWigu","B25nzxnZywC","zeXKCKq","DgvmB2Djre4","vgXsCKC","mZC5mZHHAvrwwMe","tLfjuvK","uNH2qLO","BuztCMG","zgHkzgm","ignVzgu6ia","rvjst1i","CMvQzwn0","re5lv0e","x2LZsw5PDa","y3vYC29YlNm","qw1VDw50","y29SBM8","AxzzuMS","yw5Nzq","uwPqBgq","z2v0","AMzoz3K","C2v0q3vYC28","Agriu2u","sKvOsvO","B3LvyuW","CwPYD08","zMLN","yMnsDMW","ugjHsgu","y2PmzhC","Dgv4Dc9WBge","y3ruAw1LB3u","zNvUy3rPB24","C3jJ","x2rLyNvN","uvzAuvi","AuzhBKq","uMvHzcbWyxm","B3jL","Ec1TC2CTCw8","r0npyw4","AgvHzgvYCW","uezvue0","qLL0Ewi","wxLJDg4","x21PBMLoyxy","x2vUzhbVAw4","ExDvv1O","BgLUzq","y0DwBwu","AefpC1a","yNLL","BM1uEvq","yxr0CgC","Cg93","CYbWyxjHBxm","CM92AwrLihC","zw50zwqGDhK","B25JBg9Zzq","CMvHzfvjBNq","nxWZFdz8mxW","x2HHBMrSzva","x2nVBM5Ly3q","AxfVAMS","AxLWC2i","tw9KDwXL","Aw9UvgLTzw8","qNfpy0K","y2XVC2uSihC","u3DQtfO","y3vYC29Yx2y","qvzJtNK","vMTss1O","Aw5XuMe","B3D4A1O","tufjBfK","wfLdzee","BxnNsuq","x3nLBMrby2S","B3bLBKrc","s2TusuC","q0HTDum","wND5Bg4","q05kBMC","y2HLy2TdDxi","rhjeyMO","rLjptLrjrvi","wvPOrKS","lcbOB3n0BMe","rLfTqLK","qwjYy20","D2LSBfjLy28","zw5HyMXLuw8","s2jVDuy","y2XVC2u","B25Uzwn0Aw4","DMDgA2e","Bwf4tg9ZC0m","C29Tzq","BezxA3O","Aejoz04","wgTvs2u","uMvJB25Uzwm","zLvVsgS","ywrKrxzLBNq","DxbrqM0","ChrVCG","u2fMwLm","uNHKwxu","CMvTB3zLq2G","B3jLtMfTzxm","t1bftL9fuLi","CNzHBfzHBhu","seXTwNm","CgLUz0XVC3m","zLDqsxO","Dw5KzwzPBMu","wMjNA2e","q2H4rey","ww1KAxq","CMP6uvu","tKLszgi","whbdA3i","BfHzugK","t3bLBKv2zw4","CgLUz09Uy2u","uhLTuvi","B25LCNjVCG","BKXPBMu","wgjwqLu","yNvMzMvY","CKP1qvK","CM92AwrLigi","DgfYz2v0","EMrxuxy","B2zM","Ae1LC3nHz2u","x194x21Zz18","tffPreS","AePPs1K","BeHHBMrSzxi","ve9yEhC","CxnPEgK","y2XLyxi","y2HnyxHdB3u","su5tvefova","ywTbvxK","BwLUzW","EezbD2m","AMHNCuO","zKnru0K","D24GCMvHC28","DgPqB20","tfrKs0S","ALv2yNu","ywzL","CMHqANm","Bg9N","x3jLBw92zvC","Dg9oDw1Izxi","ve5qB3C","uMzOwxi","y1zbvha","zLfvqLO","qNLSs0m","x3bPBMDmB3m","q0Xpu0LorW","qMD0AeG","rxjYB3jdB2q","CNnVCL9Uyw0","C2fNzq","we1lz28","ihbYB3rVy28","yvzNC0S","AxnmB25N","CNjVCK1LC3m","mNWZFdf8nhW","uNzNy2y","CgfNzxnOB3C","B2zMC2v0","zMLmrvO","y2HLy2Tszwe","BhfOBNO","zLPPAgK","C3rHCNq","sg1otKy","Cgf5Bg9Hzeu","DMfSDwvZ","CMnlr2q","C3bSAxq","CMvZDwX0","zxjFDhrS","vhPPvg8","ywrKt25L","AMz4EwW","sfLbq2W","ENfYqwq","Bwf4uMv0CMK","tLv6tu0","DNnNDxe","AejNrMC","DNHXue0","uhjPBwfYEuS","zw5HyMXLqxu","EwTVBLG","x3jLywr5q2W","v2vIu29JA2u","zw5JB2rPBMC","shrZy08","zgvS","zxq9DxrMltG","rxzQBum","zKrVsLG","yxHVA3i","r1rYA1e","Euruv1K","AKv1qva","mhWZFdr8mNW","zvfbt1O","B3nLza","DvPtuwO","AuDjsuK","ntmWndeYr0fstLHp","t3D2vNu","svjnEvq","C2v0","t1LvDKK","vfPhEu8","ENjUs3K","r25twwO","D2fZq2XLyw4","y1nJBK0","uxvLDwu","A2v5","AhfvCxC","zxDHyxy","A3zgA0q","Dw5RBM93BIa","z2v0qwXS","yxrLq291BNq","yxGGCMv0CMK","zfDVCMTLCKC","zw5NDgG","AwTzrfK","uePxz2u","yKTrAuO","rNvuCvy","vgLTzw91Da","vfHfAKK","AxnVwgC","vMXpvMi","veHPA2q","Aw1LCYbPBIa","qNfRCgS","Dg9cExrLC0W","shbvyMO","C2vYDMLJzs0","rvPYqLG","EvDQEue","BvzsD1u","zxrxB3jRq2G","BMCGB3iGyw4","tgLZDgvUzxi","y29UBMvJDgK","C3vIyxjYyxK","uKfMy0K","u2HHCMvKv28","EMXxDeG","B2LTEvq","x3nLCuLK","CgLUz0LUDgu","Ag1ru0G","D29Hrfm","yNvMzMvYzwq","sgXUA0e","C2vYDMvYvgK","z0ToEeW","AwXLx25HBwu","Du9Ryuu","CMTSrKW","sg9XuuC","Bwu6ia","s1zYtvu","vhDWC1a","u2TPCcbWyxm","rNzqBMi","z0XQBMe","zcbLCNjVCI4","CMvHzg9UBhK","CND5EwO","Au13tw0","CMrpwwC","Bg93","BvPHCNq","CMvWBgfJzui","CMT1swO","tgjhzve","Aw5KzxHpzG","zNjVBNrPzxi","tw1OAu4","C3vJy2vZCW","yM5euhe","nZe1B2Hvwenl","se9qyxm","zhLfDuS","zw5KCg9PBNq","yxHbrhe","Dxrlz2i","qKvlEhO","C0DrwKu","wurtuM4","sxjht3y","wuTRtKK","CMLLC0nVDw4","t1bAAvC","y29UBMvJDeu","yMP2y0C","Aw5KzxGGB3u","BMHHDeC","D1Dyvey","Bhm6ia","B2nRzxrgywK","A2DWvfa","q3H4CuK","sgDXwLa","EK5Lywe","u0nJyuy","t2jtDei","yu5VweO","r3bvzNe","ywjVCNq","vunwq2i","BxnxyNm","qNjPzgDL","mdaWmdaWmda","DxbNCMfKzw4","DgLTzw91Da","BIWGAg9ZDg4","EhnOAvG","vLnmtKG","zK5KDxe","C3bSAwnL","ywnR","DhbizwfKzxi","ywnRDxbfBMq","ihrPBwvVDxq","tgThue0","BwLUAvbYB2C","yxrHlcbKyxq","u2PMCLa","uuTpuMm","zgDHt24","AgfUz2u","AhfTDuu","uMnOz3e","yNL0zxm","y09Wzw4","C1Dbwwu","C3rLBMvYCW","vxDvq2e","ugvnyMu","A2v0ignVBNm","ywXSB2nvBNm","y0vVB3q","Dev2zw50","igzHAwWSig0","q3PoqxK","qNHqDxC","EfHAEKW","B25fCNjVCG","Cw9Z","vfD0B1G","EMLTEuu","v0TNy0m","z29py0W","A1H0yK8","CNfkvNi","x2LZtwLUAvq","vwjIC3e","rNLAuLu","zuvwvhG","x2n1CNnVCK0","zvnrB0S","wxDWC3y","z0XAy2C","y2XLyxjtDg8","ww9yy3m","zwnVBM5Ly3q","quXst1C","BhHbte4","rKzmExi","zLn1yvO","vKX3Aue","qurnELK","Bg9NsurozxC","AwXK","DgvZDa","vNzuqNq","zMzLCG","Cg9W","ote3ntq3m3nYt3rRqW","EMPjB0y","vxrYCwy","x0vysvnu","q3D1te8","D1vmzha","ywDLsgLKzq","AK1eCva","CKrUv2O","Dw5ZAwDUzwq","tgjythG","y29UC3rYDwm","zv9ZDwnJzxm","v3nduvy","z2v0u3rVCMe","AgfZ","DevYC2i","zMz1rvC","CerQAw0","u0LrqMG","tufyx1jfvfi","Auzovvy","tuvtu0fhrv8","Dhj1y3rVCIa","zwzWqKS","y3jLyxrLrxi","Dhvique","rLbIEuK","B3LxAMy","CMvHzhLtDge","zgvIDwC","zxjFAxnFywm","BMnVzgLUzW","nxWX","C2vUzf9Hy2S","BMfTzq","BezSDxnO","yxnZAwDU","Ae11vLi","rgH6C08","ChbL","z1v0rvy","DxrMofDYAxq","uhH0BLy","C3rVCMu","AwfyAKu","CLzvEK4","CNfjDw0","q1f4yLC","Egjpt2C","CgvYC2LZDgu","q1f1D1O","BxnN","CfHgrMG","DhjPzxm","mNWWFdn8nhW","wvfcEwS","Dg9mB3DLCKm","DKXjCxy","Cgu6ia","zgvSzxrL","ALPeB2W","x2LZtwLUAvC","q29UzMLN","y291BNq","yMfyvey","mhWZFdr8mxW","A2r0wMq","CgLUz19VBMm","DuXNr2e","Ahr0Ca","AKHSrKq","x19LC01Vzhu","y2fTzMW","AfznC2W","Du5xuxi","vxjyvMW","zw1LBNq","mZq1nJCYmhDmAeXfCG","z2vtEw5J","CYbPBNn0yw4","wMfkz08","vxbKyxrLq28","BMCGzMfPBgu","D3jPDgvvAw4","ANfOExq","swLUD2O","y29UBMvJDfm","qxL4zKW","zxHWB3j0CW","whjzCMC","C2nYAxb0","B2fqwLi","A29yBNK","tKHMEuy","rhbKvLu","x2HHBMrSzvi","CwzVvhG","tg9RDNO","tMnhzKu","ANDis2q","v3LlzK4","wxDqsNK","B25mAw5L","BwvKAwf0zwW","r2nHvKm","Chr5AeG","ChveruW","zhnZAwm","t3D3Axa","t1PXvMy","B0LJqMW","wvrhwwm","AxnrB1nby2S","ufPHAw0","y09usLe","uNnOuwi","EuryrvG","x3bPBMC","rvv4qKG","CKjPzNC","C1fXEwC","tfrNA1y","rKHbCey","Eu1ZCfC","B2rpD2u","BML0AwfSAxO","EhjsBwi","wvDLwfG","Afr2Avi","vvjUC0W","AMvJDfn0B3i","D1zou1y","Exvhyw4","tKDFrvjst1i","z01mvwG","q3HtA2C","x2nSzwfYugK","wgnmBvq","B2zMBgLUzq","BezvC3O","oxW4Fdf8nNW","sxPpDLi","tLnVs0q","B25ozxr3B3i","CxfTAxu","quXm","y21oque","n1H0rfHHuq","s1Ltuw0","zxjHDg9Y","swv2reC","x1fVu01HBMe","s3vJt0O","y29TCgXLDgu","igXHCMDLCIa","CNzHBa","DKP1Eue","DgHHBIbSB2m","DxrVuMvJB24","A2vfAgC","z09AEe4","ihzHBgLKihm","EfDJwNa","s1Dir2K","Dg9tDhjPBMC","q0nergW","Dg9VigXHCMC","zMzmAw5L","x2n1CNnVCK4","BfHOtwG","m3WWFdj8mxW","DcbVzIbYyw4","ve1ws0C","v1bWyum","y3jLyxrLuMu","x3nVy2TLDa","yMfSrxzLBNq","q3rMueS","tNnSwKO","Eevly3y","AMnwv2K","rgnVy0e","D0jZruW","Ec11C2uT","wNfsthC","C0nVDw50zxi","r1nHuNi","BMDNsgi","yKzuBgy","Dgv4DfbHEwW","B2LltKq","zcWGDw5RBM8","Aejbsvu","whLqzfC","rxDMD1u","sMDQDfa","Ew9OseC","AMvTzxe","yNL0zuXLBMC","C3nQq0O","tMHRBvu","x29UugfNzu4","B25tDgfYDfi","yKHuA0u","Cefgs3m","yxbWBhK","y29UBMvJDca","AejMBw8","seDAzM0","z1HLvNe","wM9vvwW","DvDNzxK","Bwv0Ag9K","uMXyC0y","sKTVCNy","x2n1CNnVCKy","sNntrxa","uufWrwm","swzLzMy","x2LUDgvYDMe","zw5XDwv1zq","BufmDwy","CKLpCNK","x3bYB3rVy28","CLLrz3m","yvriB1C","zw5HyMXLvhi","vwz5C3i","qKjmEge","x2LZqNjVD3m","s0zWBwS","BMvY","vhnLzK8","Chv0","CM92AwrLihy","x2LUAxrqCM8","ALzJBuu","yxbWzw5Kq2G","DKvirK4","x29UvgLTzw8","Bg9IywXty28","C2HPzNq","Cgzvs2u","A2fKExm","BhDRzMm","C2v0u3rVCMe","tvv3Beq","yxbWBgLJyxq","u1LnsNG","y3vYCMvUDeu","y2Pet2q","BM5Ly3q","x2LZtM9Kzq","nJy5ndmXChnxswDk","zgLZywjSzue","shz1uvy","DhLWzq","z2vjBMzVu3K","BMHwzha","B3bLBG","yMXVy2TLza","u3rhufC","zxjYtxnN","y3jLyxrLtwu","DgLLCKPtt04","BMrWB2LUDfq","zwrPyxrLBhK","vKrTshG","vhrnr2y","we51B2m","s1npCMm","x2DLDeLUDgu","tvv0whm","tuXiCuW","ExrfwMu","q29Kzq","t2zmq20","De1RDxm","CMvUDevUzha","yuvjB1i","BhP0qNi","sNDPqKi","y29Uy2f0","DgLUzYbZzxi","zv90Aw1LB3u","DhjPBq","z0DorgK","qLLYDNy","EvDeBxq","q09oveLovuu","sgLZC3C","qxbxEe4","zxjFywnRx20","vg15CgS","lcbTyxGGCMu","zxjYB3i","ExvTuui","zNjVBujPDhm","AenSB3nLrxy","AuzoshO","weDxueO","Dej6z20","DgDvtMG","ENvpB1O","D0TID0G","CMvWBgfJzq","AunryKC","BwvZC2fNzq","yM5lz20","sLjNAuW","vLzOvgK","u3rYyxrLz3K","te5Uwwi","AwXLtMfTzq","ihrPBwvZ","x2zVCM1HDeu","z3Hyrgy","C3rYAw5NAwy","reHzz0G","mtf8mtb8mNW","yxnJCMLWDa","BKPuu3e","x2nSzwfYvgK","A0vvB2y","y3LuDui","seTPtgK","BwfJCfq","B2nRzxrtDwm","sLjsz1a","s1DItgu","ue5Uy0S","re5pr28","vxv4vLG","B25SAw5L","BM93","yMLUza","C0PyBM4","y29UBMvJDa","Aw9Ul2PZB24","y01qEMS","v2firei","B3bLBIa","DgDbtK0","q29mrMu","ChjVDg90Exa","q3vZDg9Trxi","AKrgqKC","zgH3q1y","wML6vNy","CNnVCKzPBgu","rxzLBNq","y2TOAeW","wxPKvNm","C2HmtKe","sMfqyNq","wfPvrwO","x2nYzwf0zvm","quTlAee","tLHwqxK","q2HwEee","DuXws2K","txrxtKC","rNPKC0u","Ehnyy0m","D3jPDgu","uLnfv2S","AKTuzNu","swXhsxa","C2rQsNa","CKL1vwG","vMPizuG","zw1PDa","DMvY","AgDrCKO","DurABhG","lcbxzwjtB2m","BwvZ","CgLMywm","uhfcvw0","rhrHz3O","zgv2AwnLx2K","rvjtteS","q3z0qu0","D1P1A2q","sgLrwuK","yxKSihrYEsa","twjABui","Bvfgtfq","sKrvEe8","AMvIC2C","uMr6t1C","z0TUEeG","ntCYodG4mg53u3jgEa","tKfusvzfx0u","CKzyA3O","EvjLy29UBMu","t2X2ExO","y2fSBa","DwzgCwO","reiGzMfPBgu","DxjS","ELPZsNa","y2HmuMu","thnhrKO","x3DHAxq","s2XZBui","yxv0BW","A2Hrs08","Auv5s0K","vuXZzwC","y2XVC2veqG","ufHwyuG","ywnRpwzYB24","v1PorNi","sunlv2i","DxnLCKLW","y3vYC29Y","txLju2O","sxHzEKm","CgfYC2u","vhnPCwO","vw9UEhy","D3jVBeG","ywX3yxLZ","q0r6uMC","qLnrwg8","uNPJBu8","A2XuuNC","yw51Ce1LC3m","EgLyvxy","zvnctLy","tMzQqxi","AxLsz3G","qKLeu3G","B3bLCNr5tMe","BwfUDwfSihi","B3bLCNr5","zxj2AwnL","D25hrNG","ywXS","B2nRzxq","Dfr4vwG","yw1Lu3bHy2u","zgf0yq","yMXcsfC","CMvKDwnL","B2jQzwn0u3q","CMnqv2G","zuP4rhy","C2XPy2u","zxf1ywXZ","BwHqz3y","sNLeEu8","rxD0EwG","uhP0sLu","zwHbCNG","DKz2tvm","DNb1zuK","x2HHBMrSzu8","C2TWwvK","x29Ut3bLBG","z1rPBwvVDxq","Cgf5Bg9Hzfq","x2LUAxrhBg8","surhA1a","wgv6uwq","yxnL","z2jwAfy","tLHtCw8","wNnmyNG","uM1ywK8","zwPRv2G","zxHrsuG","sLnUBNK","CIb0DhDjra","DgHLBG","ywnOzwq","C3rYAw5N","BgvUz3rO","BwLZzq","D1DjB20","Ae1dqvO","CLzHBhvLCW","ug92swq","vvzRD2y","CxrPyLu","EgDRq00","DvHiywi","x3bYzwzPEa","z2v0q3vYC28","A1n0yxr1C0m","Aw5L","vuPjA1O","ugjcC08","DuvAq1K","x2rYB3bhBg8","uK1LtMW","BgTlDey","wfrUDLy","B25tDg9Wsw0","ywnRx2nVzgu","x2LZv29YA2u","CgXLyxnLiha","D2vI","EuLZuKG","x29WDgLVBNm","BfrPBwvVDxq","tMvrCwK","uvb1z0y","CMvJzwL2zwq","y01sz0W","zMPuBgm","uuLAu04","zNjVBu51Bwi","yuvZsg0","Cw9Zx18","BgD1A1m","rgvKAwnHDgu","sfrzqvG","tLfWCKy","A25Qz3y","EgDqv3q","x25HDMLNyxq","vuDKruS","x0rctMfTzq","CfnUvfa","Ber4CLq","yM9KEq","vuPorKG","DeXovNq","y3fvs3y","AefJA01LC3m","zfzSDfG","D21fEhK","Aw47y2HHCNm","qvnXtK0","AKPurMi","s0DYteK","yuDdDeK","ywXty29Wzq","C3vIC3rYAw4","wKzQBM4","CLPkteK","zwvKzwq","tMrrDuS","CMvJzxzPzwq","BgLTAxq","uLjpuG","CgLUz1rPBwu","ywnRtxnNswq","Aejyywm","ENPyr1u","ywDLu2HVDW","swvVEMm","vxPWD0e","CwTRsvG","uM5TALe","sMn1quC","sfnKCLC","y3vZDg9Tshq","u2v4zKC","qLDsyKe","BMDuAw1LCG","CgfNzwHPzgu","CMLADwG","zMXVB3i","tNzsr0C","y3vYC29Yx24","x2rPC2nVBM4","vM9YDhu","B3vUDa","CMTLCKDSB2i","zgvJB2rLzey","BMvJDa","yw5Hz2vY","BLvprgW","BMrWB2LUDca","Aw5KzxG","AevYCM9Yrxy","z2vY","ENbcA0S","D3m6lY8","rgnvDem","C1fdq0W","s2PJs3G","DhzQD1a","zMLSDgvY","jMPZy2fSBgi","rfLsAfe","CgXPuNG","x3jLy29UBMu","t1bftG","yxfHu3G","y3vYCMvUDeK","zufJAW","Cg9Yt0u","q3jxuha","zM9Yy2u","rfbkqK8","q0f3wwq","rLDt","nta2ota1nKf4Ew51Aa","v2vPEgLUsLm","vgnetgK","B2XKvMvYC2K","suvtx0vsuK8","x3DZ","v1vpsMq","A2v5CW","ywnRx2LK","CNnVCL92ywW","Ae9Wzw5fDMu","r2TOAvO","EwvYBKO","De1HBMfNzxi","Axnby2TdBgu","q0Huvhe","AgvKtwf4uMu","z2v0s2v5","C1rwr3a","wffZC2C","sKvzuMi","rNjVBNrPzxi","ANDmthi","u0rzyuC","Cxz3rM0","z1beB1e","CMvJB25Uzwm","uxjysLy","CxzjtLC","qu11v2u","tfzwCu4","q3n4v1m","sMj6Egm","BLH4wuS","t2HeDge","zePNugG","DLLnCNO","qwjVCNrfCNi","seXODeK","ExfZDgS","twvZC2fNzuu","sgvyDg0","ywXSq3vYC28","BwfW","A0HfwuK","uhfryNC","u2Leuhy","qxLgv2i","y2HnyxHuCMK","CMfUzg9T","vfvhshq","DKrNBg4","zerczee","B3jpBMXPBMu","D1nVA0O","zMLSzw5HBwu","zMLUza","EeHfqKq","x2DLBMvYyxq","uKrpuhG","CMvZB2X2zq","AxfoEgW","Egfxzum","DwHJuM8","uK5nBMu","zvvYBa","Aw9U","txzvt3C","we1rDLO","B1f1rfO","AxnszwfKEq","B2LUDfjLywm","z2v0qwXSs2u","z2TNsNe","BgvY","Dfj4ufa","AenMqxy","C2zvsKq","C3rVCcbPBw0","zxH0ugf5Bg8","q25pB1K","yw1L","BMrLEa","AxnFywnR","EK9ws1a","whbjtxi","BKXWu1q","tffqB0e","wff0Ae0","wKL5zfu","Dg9Y","wen5C3u","AxnAzxjV","EfjNt3m","EwrLs08","quTtDeO","suHIrge","C2v0zgi","B3nLrxzLBNq","CMvMtgy","rNrJAuu","x29UtwvZC2e","yw5ZzM9YBvq","Aw5PDcbrB1m","t0Psu3u","BwTvEeC","t1n4vhi","AgfZt3DUuhi","yNL0zu9MzNm","nxWW","CgjICdi","Buzpq1u","zKTvuuy","t2jQzwn0","C2DPza","EgjQweK","yKvhuKS","q29ZDLK","x2LUAxq","zwTtC28","vgXZt1C","CM9YrxzLBNq","tg9JAW","wgzWzha","tKPzqwK","A21kyMO","t0LusMO","vw5Oyw5KBgu","teD2sva","suHgr0K","rhHLD1i","EMLmr0q","vuvkrfC","Cgf5Bg9Hza","Ec1TC2CTy3u","sKTVsuG","q0Xpu0ve","sMjkswi","DgPLrwi","x29UrxjYB3i","ru1uAMS","q09otKvdveK","yvD6z0C","zgvMAw5Luhi","DgLTzw91DcW","EwrWyMW","r0jkweS","B25VCgvU","t3fKsMm","CMvZzxrdB3u","zNDZxZeUmc4","x3DZsw5ZDge","BxDvDhe","we1JsuO","vxvvr3a","zNjVBuj5Dgu","CKfeuMC","BLLQvgK","Dhr3Awq","x2TLEvbHDgG","ywDLrxzLBNq","C0jf","v3zcANa","tKHiv0S","BgjXCw4","zM9YrwfJAa","A0HzCeC","ALHmD3O","quDdy0y","y3HJtKK","B2nbzvy","r1Hctvq","EMr6uhK"];return vn=function(){return r},vn()}function Ax(r){let e=S,i={JlrIU:e(1085),SFJDN:e(1227),EjGOd:function(x,f){return x(f)},nJTSq:e(1570)+"or",omSWA:function(x){return x()},RfhYr:function(x,f){return x===f},bzoEY:"abort"};if(Sn[e(946)](r))return;let a=new Promise((x,f)=>{let l=e,h={dJgPh:l(1227),WvBjp:function(w,C){return i[l(692)](w,C)},tucTF:l(996),nWTgg:function(w){return w()}},m=()=>{let w=l;r[w(447)+"entListener"](i.JlrIU,_),r[w(447)+w(502)+w(1163)](i[w(430)],b),r["removeEventListe"+w(1163)](w(861),b)},_=()=>{let w=l,C={xaWeC:function(k,T,L){return k(T,L)},CwcIo:h[w(1568)]};if(h[w(1695)](h[w(413)],"baXTF"))h.nWTgg(x),m();else{let k=this[w(577)+w(1546)]?.["checkRea"+w(1581)+"es"](),T=this[w(577)+w(1546)]?.[w(504)+"ntEndpoint"]();if(k&&!_0xf685ec[w(1239)]){let L="connect "+T+(w(896)+"ax retri"+w(1725)+"ed");this["_dispatc"+w(1510)+w(444)](C[w(1595)](_0x4e578b,C[w(516)],{message:L,code:_0xd8d9e2[w(951)+"IES_ERROR"],error:_0x240e06}));return}this[w(1538)]&&this[w(1538)].readyState===this[w(1523)]&&this[w(1500)+w(434)](),this[w(1850)+w(1510)+w(444)](C.xaWeC(_0x2763e8,C[w(516)],{message:_0x19eb2b[w(1239)],code:_0x48ab7c[w(1325)+w(1479)],error:_0x316873}))}},b=()=>{let w=l;i.EjGOd(f,r[w(1227)]||new DOMException(i.nJTSq,i[w(1253)])),i[w(1726)](m)};r[l(635)+"Listener"](l(1085),_),r[l(635)+l(793)](i[l(430)],b),r["addEvent"+l(793)](i.bzoEY,b)});Sn.set(r,a)}function Dx(r){En=r(En)}function kx(r){let e=S,i={XMcIJ:function(a,x){return a==x},EqbUm:e(395),yWDmt:e(398),YKkNI:e(1513),FQmBY:function(a,x){return a(x)},JgjtP:function(a,x){return a(x)},ALROW:function(a,x){return a===x},XpIMr:e(1501),attpg:function(a,x){return a(x)},HpUbj:function(a,x){return a in x},kMEcV:e(507),wFZPV:function(a){return a()}};if(i.ALROW(r,IDBDatabase[e(1276)+"e"]["transact"+e(1599)])&&!i[e(786)](e(1378)+e(641),IDBTransaction[e(1276)+"e"]))if(i.ALROW(e(802),i[e(1751)]))_0xa555a4=_0x29ecf9&&i[e(1686)](i.EqbUm,_0x1a4349[e(1756)])?i[e(1220)]:i[e(843)],_0x3e29c4=_0x3d2b64.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x540d2b=/^wss(.*:\/\/)/[e(927)](_0x22624c)?_0x1ff454:""+_0xe569a+_0x274219;else return function(a,...x){let f=e,l=r[f(1329)](i[f(620)](Rt,this),a,...x);return mr[f(756)](l,a.sort?a[f(522)]():[a]),i[f(620)](Ce,l)};return i.wFZPV(Cx)[e(1855)](r)?function(...a){let x=e;return r[x(1137)](i[x(1127)](Rt,this),a),Ce(wr[x(550)](this))}:function(...a){let x=e;return i.XpIMr===i[x(1618)]?Ce(r[x(1137)](i[x(584)](Rt,this),a)):i[x(919)](0,this[x(494)])&&this.low===0}}function Ix(r){let e=S,i={hAOsP:"function",qeUnn:function(a,x){return a instanceof x},TscNI:function(a,x){return a(x)},CHmuC:function(a){return a()}};return typeof r===i[e(581)]?kx(r):(i[e(518)](r,IDBTransaction)&&i[e(1841)](Ax,r),xi(r,i[e(612)](Sx))?new Proxy(r,En):r)}function Ce(r){let e=S,i={pSnTP:function(x,f){return x instanceof f},yvIkX:function(x,f){return x(f)},uPzZZ:function(x,f){return x!==f}};if(i[e(1457)](r,IDBRequest))return i[e(384)](Ex,r);if(yn.has(r))return yn[e(550)](r);let a=Ix(r);return i[e(1706)](a,r)&&(yn[e(756)](r,a),Cn[e(756)](a,r)),a}var xi,ni,ri,wr,Sn,mr,yn,Cn,En,Rt,si=ai({"node_modules/idb/build/wrap-idb-value.js"(){let r=S,e={ASqNM:function(i,a,x){return i(a,x)},GcaVC:function(i,a){return i(a)},IrGOv:function(i,a){return i instanceof a},syvsn:function(i,a){return i===a},yumQB:r(1168),cEoot:"done",yIsRH:function(i,a){return i+a},AwGnK:r(1660)+r(818),UCVCb:function(i,a){return i+a},rjzQU:function(i,a){return i===a},mVRwU:r(1222),PbaHe:function(i,a){return i===a},Abrcm:r(975)};xi=(i,a)=>a[r(629)](x=>i instanceof x),wr=new WeakMap,Sn=new WeakMap,mr=new WeakMap,yn=new WeakMap,Cn=new WeakMap,En={get(i,a,x){let f=r;if(e[f(842)](i,IDBTransaction))if(e.syvsn(e[f(1228)],e[f(1228)])){if(a===e[f(894)])return Sn[f(550)](i);if(e[f(1894)](a,f(1378)+f(641)))return i["objectSt"+f(641)]||mr[f(550)](i);if(e[f(1894)](a,f(975)))return x[f(1378)+f(641)][1]?void 0:x[f(1378)+"ore"](x[f(1378)+f(641)][0])}else e[f(1467)](_0x1f4367,_0x53eb2d,32),e[f(1467)](_0x23715e,_0x69297e,e[f(1036)](_0x3b1b4b,_0xb8af83));return e[f(1036)](Ce,i[a])},set(i,a,x){let f=r;if(e.rjzQU(e[f(790)],f(1222)))return i[a]=x,!0;{let l=_0x5dba50[f(1410)]&&_0x3b3f92[0];if(e[f(842)](l,_0x235ce9))throw l;let h=new _0x1c82ec(e[f(1436)](e.AwGnK,l?e[f(862)](e[f(1436)](" (",l[f(1239)]),")"):""));throw h.context=l,l}},has(i,a){let x=r;return i instanceof IDBTransaction&&(e[x(651)](a,e[x(894)])||e[x(559)](a,e[x(621)]))?!0:a in i}},Rt=i=>Cn[r(550)](i)}}),ci={};vx(ci,{deleteDB:()=>Tx,openDB:()=>Px,unwrap:()=>Rt,wrap:()=>Ce});function Px(r,e,{blocked:i,upgrade:a,blocking:x,terminated:f}={}){let l=S,h={rdOYg:function(b,w){return b===w},yDXEX:l(1272),TOXxw:"SDgGs",WsCQV:function(b,w,C,k,T){return b(w,C,k,T)},BEKxz:function(b,w){return b(w)},eSQoK:function(b,w){return b||w},EwfwU:function(b,w){return b!==w},ffuEW:"nUQih",KwUms:l(1005),DPCWx:l(1737)+l(883),kWOUA:function(b,w){return b(w)},mQFLT:"blocked"},m=indexedDB[l(1191)](r,e),_=h.kWOUA(Ce,m);return a&&m[l(635)+l(793)]("upgradeneeded",b=>{let w=l;h[w(822)](h[w(1048)],h[w(672)])||h[w(944)](a,h[w(839)](Ce,m[w(721)]),b[w(1536)+"on"],b[w(1794)+"on"],Ce(m[w(1849)+w(1599)]))}),i&&m["addEvent"+l(793)](h[l(1319)],()=>i()),_.then(b=>{let w=l;if(h[w(1126)](h[w(948)],h.KwUms))f&&b[w(635)+w(793)](w(625),()=>f()),x&&b[w(635)+w(793)](h.DPCWx,()=>x());else{let C=this[w(1798)].getItem(this[w(1420)]),k=_0x4acf05.parse(h[w(913)](C,"{}"));return _0x3acc94.values(k)}}).catch(()=>{}),_}function Tx(r,{blocked:e}={}){let i=S,a={iGIII:function(f,l){return f(l)}},x=indexedDB[i(1790)+i(1713)](r);return e&&x[i(635)+i(793)](i(1192),()=>e()),a[i(752)](Ce,x)[i(1407)](()=>{})}function ii(r,e){let i=S,a={ntBdh:function(m,_){return m(_)},Mqkxb:i(1570)+"or",LTnQP:function(m){return m()},Ufysr:i(1152),KCDOK:"nbVmt",YiGJJ:"readwrite",jUvbu:i(819),wKbwH:function(m,_){return m instanceof _},VgpUC:function(m,_){return m in _},lztBr:i(1409),TlsOW:function(m,_){return m!==_},qJyhB:function(m,_){return m===_},XcLmT:"lkshk"};if(!(a[i(1236)](r,IDBDatabase)&&!a.VgpUC(e,r)&&typeof e===a[i(1212)]))return;if(bn[i(550)](e))return bn.get(e);let x=e[i(1237)](/FromIndex$/,""),f=a[i(1653)](e,x),l=ui[i(1855)](x);if(!(x in(f?IDBIndex:IDBObjectStore)[i(1276)+"e"])||!(l||fi.includes(x))){if(a[i(1818)](a[i(1069)],a[i(1069)]))return;zJIeZX[i(1775)](_0x55fe6c,_0x3b9c6f[i(1227)]||new _0xd0e62f("AbortError",zJIeZX[i(1898)])),zJIeZX.LTnQP(_0x23d350)}let h=async function(m,..._){let b=i,w={Rmxhm:a[b(1159)]};if(a[b(465)]!=="nbVmt")this[b(381)+b(763)][b(1755)](_0x2461bf),this[b(565)](w[b(457)],_0x46ceca);else{let C=this.transaction(m,l?a.YiGJJ:a[b(685)]),k=C[b(975)];return f&&(k=k[b(1509)](_[b(1173)]())),(await Promise[b(1371)]([k[x](..._),l&&C.done]))[0]}};return bn[i(756)](e,h),h}var fi,ui,bn,Lx=ai({"node_modules/idb/build/index.js"(){let r=S,e={WUOJd:function(i){return i()},PymQR:r(550),skpYY:r(1550),LkGPM:r(1605)+"ys",PqBUm:r(995),ZaJgO:r(484),HWRwz:r(991),jHTiV:r(674)};e[r(1539)](si),e[r(1539)](si),fi=[e[r(657)],e[r(1391)],r(769),e[r(877)],e[r(1310)]],ui=[r(1165),e[r(1012)],e[r(1748)],e.jHTiV],bn=new Map,Dx(i=>({...i,get:(a,x,f)=>ii(a,x)||i[r(550)](a,x,f),has:(a,x)=>!!ii(a,x)||i[r(946)](a,x)}))}}),Nx={idb:function(r){let e=S;r[e(1020)]=Promise.resolve().then(()=>(Lx(),ci)).then(function(i){return i})}},oi={};function Se(r){let e=S,i={tTxUh:e(1883)+"1"},a=i[e(1373)].split("|"),x=0;for(;;){switch(a[x++]){case"0":Nx[r](f,f[e(1020)],Se);continue;case"1":return f.exports;case"2":var f=oi[r]={exports:{}};continue;case"3":var l=oi[r];continue;case"4":if(l!==void 0)return l.exports;continue}break}}Se.d=(r,e)=>{let i=P;for(var a in e)Se.o(e,a)&&!Se.o(r,a)&&Object[i(1676)+i(1368)](r,a,{enumerable:!0,get:e[a]})},(()=>{let r=S;Se.o=(e,i)=>Object.prototype[r(1640)+r(1368)][r(1329)](e,i)})(),(()=>{let r=S,e={camfl:"undefined",ksqrQ:r(596),OqdJc:r(1003)+"le"};Se.r=i=>{let a=r;e[a(1004)]!=typeof Symbol&&Symbol["toString"+a(528)]&&Object[a(1676)+a(1368)](i,Symbol[a(1096)+"Tag"],{value:e.ksqrQ}),Object["definePr"+a(1368)](i,e[a(1681)],{value:!0})}})();var V={};(()=>{let r=S,e={ULseg:function(s,t){return s+t},tezDL:function(s,t){return s+t},puDEL:function(s,t){return s!==t},ydpbl:r(1213),tjPom:function(s,t){return s*t},nsPwT:r(1085),JFjpV:r(1227),rJuAY:"abort",ZIydU:function(s,t){return s===t},TNPow:r(673),Ewtyh:function(s,t){return s(t)},DxewR:function(s,t,n){return s(t,n)},XMKgo:function(s,t){return s+t},jnXNJ:r(1418),edpWL:function(s,t){return s(t)},bFTlf:function(s,t){return s+t},XCysu:r(490),xRgOs:function(s,t){return s(t)},koXny:r(865)+"000000000000000000000000",xgPWt:function(s,t){return s!=t},yxXyy:function(s,t){return s instanceof t},ILWjl:r(561)+r(1466)+r(741),ZWAOu:r(1891),jfxyl:"qKXSN",pcGUf:"ESUwI",XbVBU:function(s,t){return s>t},oVsip:function(s,t){return s<t},LABtw:function(s,t){return s!==t},iqNxl:function(s,t){return s-t},utKgb:function(s,t){return s<t},Xsbel:function(s,t){return s-t},vEHFN:function(s,t,n){return s(t,n)},OHTLp:function(s,t,n){return s(t,n)},xXZzL:function(s,t,n){return s(t,n)},kvFkD:function(s,t){return s>>>t},PqQbw:function(s,t){return s(t)},tErsb:function(s,t,n){return s(t,n)},OZfQF:function(s,t){return s&t},pliRx:r(1731)+r(1795)+r(378)+r(764),hBAIU:function(s,t){return s===t},pyvGg:r(1731)+r(1795)+" field: value",hqUqw:function(s){return s()},nloJL:function(s,t,n,o){return s(t,n,o)},vxqPM:"x_frontier_qos",sQCCL:r(1709)+"er_qos_ack",lXYPi:function(s,t,n,o){return s(t,n,o)},jqhyt:"x_fronti"+r(962)+"k",Lokvz:function(s,t,n){return s(t,n)},Olvyz:r(1239),DXVjR:function(s,t,n){return s(t,n)},wBprE:r(1545),wULdp:function(s,t){return s!==t},rqIum:function(s,t){return s===t},eBUpw:r(471),LBDXF:function(s,t,n){return s(t,n)},EMTjk:function(s){return s()},hLHzr:function(s,t,n){return s(t,n)},NSoKD:function(s,t,n){return s(t,n)},fPJxq:function(s,t){return s(t)},RxdYu:function(s,t,n){return s(t,n)},shLNA:function(s,t,n){return s(t,n)},UVkwf:function(s,t,n){return s(t,n)},CNJng:function(s,t,n){return s(t,n)},gjmuR:function(s,t,n){return s(t,n)},qCMBG:function(s,t){return s!==t},HhWqv:function(s,t,n){return s(t,n)},IqSbU:function(s,t){return s!==t},porOE:function(s,t){return s!==t},ZqRLw:function(s,t){return s(t)},zzXGU:function(s,t){return s(t)},jXLwz:function(s,t){return s(t)},cywoN:function(s,t,n){return s(t,n)},PNncK:function(s,t,n){return s(t,n)},rIuUh:function(s,t){return s(t)},BYtyb:function(s,t){return s(t)},HLmZs:function(s,t,n){return s(t,n)},EZrBX:function(s,t){return s(t)},rcKGd:function(s,t,n){return s(t,n)},fmAGF:function(s,t,n){return s(t,n)},QVLVM:function(s,t){return s(t)},LNnYb:function(s,t,n){return s(t,n)},tLNVt:"Missing required"+r(378)+"SeqID",BTpOr:function(s,t){return s===t},UJIkZ:"Missing required"+r(378)+r(386),wsIvO:function(s,t){return s===t},tuHAA:"Missing "+r(1795)+r(378)+r(1144),oaPZR:function(s,t){return s|t},uhcRo:function(s,t){return s&t},fCQSI:r(419),RBEzj:function(s,t){return s(t)},aqaSx:function(s,t){return s(t)},CoLFe:function(s,t,n){return s(t,n)},vYKQw:function(s,t,n){return s(t,n)},VSLNH:function(s,t,n){return s(t,n)},jurwb:function(s,t){return s+t},sOAtx:"Unimplem"+r(588)+r(990),ziLGD:function(s,t){return s>>t},gSkxr:function(s,t){return s!==t},gOZxN:r(1718),ZoUUl:function(s,t){return s>t},DNOGo:function(s,t){return s+t},KKtKf:"WgaLk",FROBS:r(1555),Uonxv:function(s,t){return s>t},sJXnn:function(s,t){return s>t},OhDta:r(568)+r(1728),UYFtA:function(s,t,n){return s(t,n)},wEJvZ:function(s,t){return s+t},gXeVq:function(s,t){return s+t},kmJbj:function(s,t){return s&t},GwDtQ:function(s,t){return s(t)},LVVqN:function(s,t){return s===t},ICKWb:function(s,t){return s&t},HiQYI:function(s,t){return s>=t},mbQrO:function(s,t){return s+t},lMhhs:function(s,t){return s<<t},CKOxP:function(s,t){return s!==t},wVNSV:r(1512),odOwe:function(s,t){return s==t},DBwwn:function(s,t){return s+t},rcPWh:function(s,t){return s+t},HuTWn:function(s,t){return s+t},CnOoY:function(s,t){return s!==t},HtscO:function(s,t){return s|t},yuGan:function(s,t){return s<<t},LsGFJ:function(s,t){return s|t},jJTFb:function(s,t){return s<<t},qvwFm:function(s,t){return s&t},isoXg:function(s,t){return s&t},EmVtb:function(s,t){return s>=t},kgpTP:function(s,t){return s<=t},hTviR:function(s,t){return s==t},dVltX:function(s,t){return s>=t},OfLCm:function(s,t){return s+t},gkbFt:function(s,t){return s+t},hnXlx:function(s,t){return s!==t},RNjga:function(s,t){return s<<t},nhatG:function(s,t){return s|t},cOTJQ:function(s,t){return s<<t},Ymdit:function(s,t){return s&t},OaVlU:function(s,t){return s<t},cVATp:function(s,t){return s>>t},RxvBZ:function(s,t){return s|t},rqJVr:function(s,t){return s<t},DYRhQ:function(s,t){return s<t},NHfyF:function(s,t){return s<t},CQuwZ:function(s,t){return s<t},DhzsO:function(s,t){return s<t},lDxrT:function(s,t){return s>=t},XyPdW:function(s,t){return s<=t},YtAHv:function(s,t){return s-t},TUGHt:function(s,t){return s===t},MUwlD:r(1294),hdHSe:function(s,t){return s|t},SiDPv:function(s,t){return s&t},Rchgq:function(s,t){return s|t},ztWKz:function(s,t){return s&t},etwVe:function(s,t){return s===t},pXFFh:r(1742),sdOfp:r(1091),xrRmb:function(s,t){return s|t},PXVaH:function(s,t){return s&t},QjPld:function(s,t){return s>>t},SneRU:function(s,t){return s&t},QppcK:function(s,t){return s|t},TlRrG:function(s,t){return s&t},opNHF:function(s,t,n){return s(t,n)},oIcBl:function(s,t){return s<t},zuOoZ:function(s,t,n){return s(t,n)},iqojk:function(s,t,n){return s(t,n)},vLIqv:function(s,t){return s(t)},FuTqV:function(s,t){return s>=t},xHEBD:function(s,t,n){return s(t,n)},nHUmw:function(s,t){return s-t},cjDOd:function(s,t,n){return s(t,n)},DEBjq:function(s,t,n){return s(t,n)},WyKfN:r(625),jHlFD:function(s,t){return s!==t},HmNNF:r(814),gKNxL:function(s,t){return s&t},ykonX:function(s,t){return s(t)},tgANM:function(s,t){return s&t},VjHeH:function(s,t){return s&t},dssic:function(s,t){return s(t)},FPbyI:function(s,t){return s<<t},vfkju:function(s,t){return s(t)},ybJlp:function(s,t){return s&t},CtfPK:r(1019),macpT:function(s,t){return s<<t},lwkfc:function(s,t){return s&t},fQUBZ:function(s,t){return s===t},jxmZk:r(1473),bcRvl:function(s,t){return s(t)},LUVGL:function(s,t){return s<<t},BIDSx:r(1112),MgkRU:r(551),HTYAX:function(s,t){return s(t)},QKORc:function(s,t){return s<<t},tMkus:function(s,t){return s|t},HeXtm:function(s,t){return s<<t},GRdXJ:function(s,t){return s|t},SIQBh:"dkmLx",Ifeff:function(s,t){return s>>>t},mhPgv:function(s,t){return s>>>t},gbVhV:function(s,t){return s>>>t},OSxTr:function(s,t){return s===t},VlOVb:function(s,t){return s<t},PFUPM:function(s,t){return s<t},Dtagz:function(s,t,n){return s(t,n)},GULPe:function(s,t){return s>>>t},nggHb:function(s,t){return s!==t},AKKhA:function(s,t){return s&t},bKQiJ:function(s,t){return s>>>t},OpCug:function(s,t){return s+t},NdQuK:function(s,t){return s|t},qRzPX:function(s,t){return s&t},DcocA:function(s,t){return s>>>t},sDTtL:function(s,t){return s|t},xshiX:function(s,t){return s>>>t},fjOJn:function(s,t){return s>>>t},aEIoR:function(s,t){return s+t},XZUEj:function(s,t){return s&t},RlXsF:function(s,t){return s>>>t},YWeXX:function(s,t){return s+t},gkgJq:function(s,t){return s!==t},iypsb:function(s,t){return s|t},LGvIP:function(s,t){return s>>>t},IzOvR:function(s,t){return s&t},CQxbW:function(s,t){return s>>>t},qfoTx:function(s,t){return s+t},QPugF:function(s,t){return s>>>t},YQByk:function(s,t){return s&t},inqRa:function(s,t){return s|t},BBLxa:function(s,t){return s&t},LaQzo:r(684),VuvCV:function(s,t){return s(t)},WwUPl:function(s,t){return s!==t},blBHW:function(s,t){return s(t)},hBNgN:function(s,t){return s|t},TZGyO:function(s,t){return s<<t},hqmuE:function(s,t){return s&t},hoyid:function(s,t){return s<<t},nLpST:function(s,t){return s&t},cmNAA:r(1204),RdzOW:function(s,t){return s===t},YDSRn:function(s,t){return s|t},MtWNG:function(s,t){return s<<t},eBpmT:function(s,t){return s<<t},eSBNV:function(s,t){return s|t},DrDbj:function(s,t){return s|t},VDmHx:function(s,t){return s<<t},Rvgcf:function(s,t){return s===t},yohHG:function(s,t){return s<<t},iFxjx:function(s,t){return s&t},IcFEa:function(s,t){return s>>>t},iyRgx:function(s,t){return s>>>t},mFSrh:function(s,t){return s>>>t},hCfAv:function(s,t){return s>=t},vgFka:function(s,t){return s<=t},NPLCn:function(s,t){return s+t},qiwTS:function(s,t){return s|t},XnEcc:function(s,t){return s%t},hPXlA:function(s,t){return s/t},cScnM:function(s,t){return s+t},lvRsB:function(s,t){return s*t},UzpwA:function(s,t){return s>>>t},SafZS:function(s,t){return s>>>t},wrolH:function(s,t){return s===t},xiXUv:function(s,t){return s===t},mbsVs:function(s,t){return s>>>t},GpUfq:function(s,t){return s+t},Nurfc:function(s,t){return s+t},xFAwc:function(s,t){return s|t},DHYgH:function(s,t){return s<<t},QApEc:function(s,t){return s|t},KlsmB:function(s,t){return s<<t},BZkRH:function(s,t){return s===t},XotCJ:function(s,t){return s===t},rFXkz:function(s,t){return s===t},uWgey:function(s,t){return s===t},ejkWh:function(s,t){return s&t},wDKCR:function(s,t){return s>>>t},VvTBt:function(s,t){return s&t},FHApF:function(s,t){return s>>>t},XpCkr:function(s,t){return s&t},zLmqb:function(s,t){return s&t},sifMa:r(707)+r(1642),KkTIG:r(951)+r(1537)+"R",TcDLi:r(1325)+r(1479),Mouli:"MESSAGE_"+r(540),GkhiZ:r(642)+"OR",IlGIp:function(s,t){return s!==t},knjgv:r(974),wBsEL:r(591)+"0|2|4",YoXcs:r(748)+"1",GXBMT:r(1191),tRxPP:r(1791),uJgiE:function(s,t){return s-t},kHEYI:function(s,t){return s===t},VHhJr:function(s,t){return s==t},sQqyg:function(s,t){return s instanceof t},zdWQv:r(1660)+r(818),sFybK:function(s,t){return s+t},ZxqDd:function(s,t){return s+t},SbKpm:function(s,t){return s===t},bjvcG:function(s,t,n){return s(t,n)},TBTfi:r(1030),qCTeH:"uWlnL",EfGpc:function(s,t,n){return s(t,n)},HYACl:"IxpqF",WhzhO:function(s,t,n){return s(t,n)},VVhTi:function(s,t,n){return s(t,n)},MbZmB:function(s,t,n){return s(t,n)},JbJIb:function(s,t){return s instanceof t},VUtGM:function(s,t){return s||t},Hetvj:r(986)+"1",kHYpG:function(s,t){return s!=t},GCOan:r(647)+"d",wmExy:function(s,t){return s<=t},CCDDl:"next() called multiple t"+r(783)+"process",zOVKP:function(s,t){return s===t},ApWxN:function(s,t){return s+t},uXHab:function(s,t){return s<t},nFWsh:function(s,t){return s<t},AyFWb:function(s,t){return s&t},nYjTi:function(s,t){return s+t},nnRHg:function(s,t){return s===t},uSytC:r(560),LTgkV:function(s,t){return s-t},ptyhH:function(s,t){return s<t},TkAst:function(s,t){return s|t},Tsiqj:function(s,t){return s<<t},fbbBK:function(s,t){return s&t},IQohi:function(s,t){return s>=t},XezQd:function(s,t){return s|t},nZYNR:function(s,t){return s&t},bHTkE:function(s,t){return s<<t},TXEjI:function(s,t){return s>>t},xbOOg:function(s,t){return s+t},UJNFH:function(s,t){return s&t},zDJEs:function(s,t){return s===t},pfUKe:function(s,t){return s|t},gKnxH:function(s,t){return s|t},vUqrX:function(s,t){return s|t},VvFsP:function(s,t){return s<<t},ywUWZ:function(s,t){return s<<t},QVZQR:function(s,t){return s<<t},XUeKZ:r(388),MmhiN:function(s,t){return s<t},lgukS:"pqcaS",YZhFK:"qdaJq",VWdyN:function(s,t){return s&t},fUsrl:function(s,t){return s===t},hBXac:"3|2|4|0|"+r(964),PovId:function(s,t){return s&t},jjEel:function(s,t){return s+t},gxXDf:function(s,t){return s&t},fZihi:function(s,t){return s|t},ADMzY:function(s,t){return s&t},MGNIe:function(s,t){return s!==t},NJYAi:r(1632),Xfpdp:function(s,t){return s|t},Yyctn:function(s,t){return s>>t},oiKND:function(s,t){return s>>t},woaDS:function(s,t){return s|t},vDgln:function(s){return s()},UmInX:r(903),kEUof:r(1409),YTGYc:function(s,t){return s instanceof t},NQprF:r(1179)+r(1270),qukAD:r(1811),DpdVU:r(971),jMDqP:function(s,t){return s===t},IhwYj:r(600),LZGVR:function(s,t){return s>=t},AMuWe:function(s,t){return s>=t},ZatoS:r(1061),poRZR:"owCNs",rhPjs:function(s,t){return s|t},YKJJK:function(s,t){return s<<t},jhgqJ:function(s,t){return s|t},hGDiM:function(s,t){return s<<t},nIMxJ:r(768)+r(1879),PJWge:r(460)+r(1252),sxPpN:r(1001),FDdgj:r(1519)+r(1344)+r(1196)+"P",lCehN:r(1084),EUxBH:function(s,t){return s(t)},GTrkQ:r(1295),dQIJZ:function(s,t){return s(t)},ssjCJ:r(677),KWHGi:function(s){return s()},NXVAy:function(s,t){return s>=t},cGVme:function(s,t){return s<t},mZart:function(s,t){return s<<t},vGoda:function(s,t){return s>>t},yjMHY:function(s,t){return s&t},TziTo:function(s,t){return s>>t},AtajX:function(s,t){return s!==t},lkKtF:r(906),Ltvak:r(1072)+r(1251)+"3|5|4|0|7",CghDF:function(s,t){return s>>>t},sGQZE:function(s,t){return s|t},BAYwG:function(s,t){return s<t},IQKpK:function(s,t){return s<t},KFpmk:function(s,t){return s|t},KYSQm:function(s,t){return s<<t},fKUQF:r(1047),bnDPq:function(s,t){return s||t},eJxDv:function(s,t){return s||t},ocAeV:function(s,t,n){return s(t,n)},rwyyj:function(s,t){return s===t},sKkUU:r(1006),fiLEZ:r(1777),mdqVE:function(s,t){return s===t},PPLEu:r(897),OQcYs:r(1633),Ewxov:"RUcYw",YzdVs:function(s,t){return s|t},fJCdL:function(s,t){return s|t},CsxWS:function(s,t){return s<<t},NAiBt:function(s,t){return s|t},sfUJD:function(s,t){return s===t},fSuaZ:r(1805),JyDyO:function(s,t){return s||t},DDagx:function(s,t){return s||t},uEZCY:function(s,t){return s||t},XTnvV:function(s,t){return s!=t},fWPIz:r(901),hblok:"message_id",NfjAr:function(s,t){return s(t)},RabQv:function(s,t){return s===t},jwHKd:r(1556),Zbgka:function(s,t){return s===t},uDZlx:r(1238),dyEuK:function(s,t,n,o){return s(t,n,o)},lpySY:"need_ack",OJRSu:r(1616),LQiDK:function(s,t){return s&&t},rklFL:r(1740),uLVKi:r(1541),htwCU:r(1432),zdzPy:function(s){return s()},cyTuB:r(1441),ehArx:function(s){return s()},hMuVR:"hsOjW",CDzRg:function(s,t){return s(t)},NbVoO:function(s,t){return s(t)},mwUtq:function(s,t){return s instanceof t},KSOrc:function(s,t){return s instanceof t},trwVd:"applicat"+r(1270)+";charset=utf-8",hBfmo:"none_none",oyWjf:r(433),MzJCo:function(s,t,n,o){return s(t,n,o)},XrYrg:function(s,t){return s>t},HKiLi:function(s,t){return s+t},zlWtH:function(s,t){return s+t},HlnkA:"iQeho",SexfG:function(s,t){return s||t},qtibU:function(s,t){return s>>>t},MLHqL:function(s,t){return s(t)},fDoJX:function(s,t){return s+t},CAwYd:function(s,t){return s+t},PKxhp:r(848)+r(1103)+"ge: ",VLwiA:" + ",GDSQH:function(s,t){return s||t},NUzMM:" > ",dCgnW:function(s,t){return s&t},LInEG:function(s,t,n,o){return s(t,n,o)},IHbDa:function(s,t){return s+t},xbjXI:r(1488),Utrqf:r(1895)+r(1098)+"e",JDUxO:function(s,t){return s>=t},SjfrP:function(s,t){return s!==t},Ywpsv:"CARbt",dYnzR:function(s,t){return s&t},HpUYH:function(s,t){return s+t},bdSMU:function(s,t){return s+t},iFNHz:function(s,t){return s===t},qvINW:"ydcQW",qkkIX:function(s,t){return s<t},CEJta:r(1102)+"4",QwidH:function(s,t){return s+t},ikYDY:function(s,t){return s===t},JcuAG:r(1234),ZsLbx:function(s,t){return s+t},JEhIZ:function(s,t){return s+t},vYMrz:function(s,t){return s<<t},gGNDi:function(s,t){return s<<t},PZaim:function(s,t){return s<<t},jEuAP:function(s,t){return s<<t},BTWvz:function(s,t){return s>>>t},aWzgG:function(s,t){return s&t},yWjyA:function(s,t){return s&t},JTxqg:function(s,t){return s&t},mZSxt:function(s,t){return s&t},nmTyT:function(s,t){return s+t},ISMrh:function(s,t){return s&t},NXSqo:function(s,t){return s+t},oyUaL:function(s,t){return s(t)},HGZfm:r(1566),RLEEX:function(s,t){return s===t},qjrwO:function(s,t){return s>>>t},gUtEV:function(s,t){return s===t},MiSJt:function(s,t){return s>>>t},SUGdJ:function(s,t){return s|t},ufFqj:function(s,t){return s<<t},rZJLI:function(s,t){return s|t},wWXTF:function(s,t,n,o){return s(t,n,o)},HKOXc:r(1697),chLRe:r(511),CakjY:function(s,t){return s!==t},fSzub:r(898),ivYRk:r(397),lgysz:function(s,t){return s(t)},klTRw:"idb",bnKgm:r(1507),LWsme:r(544)+r(1369),RzcmO:"header",Ubbsq:function(s,t,n,o){return s(t,n,o)},rDnWj:r(787)+r(966),Zwyln:r(966),kdtZd:function(s,t){return s+t},PbBsO:"THdjM",yntIb:r(1493),ewaav:function(s,t,n){return s(t,n)},Bqkpk:r(1499)+r(1614),qqmiu:r(1575)+r(1414),ThTMd:r(1077),JVEhp:r(676),JKoIH:r(1221),DcIpC:function(s,t,n,o){return s(t,n,o)},AJZKb:r(1630),rkuIj:"setcursor",LbGeQ:r(431),zbeXq:function(s,t,n){return s(t,n)},oWDIF:function(s,t){return s(t)},KbouF:r(1585),XMQvZ:r(1232),bEGRK:r(1200),hJiKY:function(s,t){return s!==t},pifac:"oKYIT",QNaaH:"WYgef",VlJIQ:function(s,t,n,o){return s(t,n,o)},UsuPc:r(402),UuxVX:function(s,t,n,o){return s(t,n,o)},HoqQG:r(1709)+r(722),HSdrW:r(570)+"s",ZQyYI:r(1667)+r(700)+"e",rPOKN:function(s,t){return s(t)},dhJdc:function(s,t,n){return s(t,n)},lrnwy:function(s){return s()},owxkZ:"jIpIh",HnzVK:r(1132),RAfcI:function(s,t){return s+t},JJwgU:function(s){return s()},MyISj:function(s){return s()},JDOYn:function(s){return s()},hQlPA:r(1070),CvtAM:function(s,t,n){return s(t,n)},rYVhd:function(s){return s()},XVzjZ:r(415),XQssg:function(s,t){return s(t)},awlhK:function(s,t){return s!==t},jZDol:function(s,t){return s<t},FFLyr:function(s,t){return s===t},ERSLK:function(s){return s()},iqxLd:function(s,t,n){return s(t,n)},uLgGa:function(s,t,n){return s(t,n)},NvRGG:r(582),JaPbt:r(857),sWAYe:r(1553),WqVsG:function(s,t){return s(t)},rIOry:function(s,t){return s!==t},sdjJp:function(s,t){return s!=t},mNJIA:function(s,t){return s===t},zrnKy:r(1355),CwuLO:function(s,t){return s===t},AKStJ:r(1338),BgthH:r(999)+r(943)+"s",NeQqi:r(1129),eZWDN:"arraybuffer",OlSWN:r(1643),WZNFr:function(s,t){return s/t},ydeKO:function(s,t){return s==t},fNduq:function(s,t){return s===t},gLjna:r(1434)+r(1166)+r(1876),ecjwC:r(1434)+r(587)+r(586)+r(1307)+r(892)+r(954)+"is undef"+r(424),IevDG:function(s,t,n){return s(t,n)},iFNUV:r(1559)+"t",ygVEE:r(1265),WPpaC:r(1495),KVrMU:r(709),RmXZO:function(s,t){return s!==t},HvuQV:function(s,t){return s!==t},AJAOh:function(s,t){return s==t},rVUzN:r(395),vZqaP:r(398),CkceJ:r(1513),YiDYk:r(1462),eQAOZ:r(902),JKorv:r(1691),joKeX:r(1434)+r(663)+"ddID, deviceID o"+r(1406),CHTTq:function(s,t){return s==t},YwPJy:r(563),rABbc:function(s,t,n){return s(t,n)},nSzTm:r(1435),Iyouz:r(1683)+"0",zNeaa:r(1817),fUoHk:function(s,t,n){return s(t,n)},StGPW:r(617)+">",ckhhL:function(s,t){return s*t},Jbzxc:function(s,t){return s-t},tPsbX:function(s,t,n){return s(t,n)},mtYwT:function(s,t,n){return s(t,n)},IDGkP:"ping_onc"+r(1216)+"t",Aiang:"going aw"+r(1317)+"reconnec"+r(1215)+r(1304),riZuh:function(s,t){return s!==t},PmoSg:function(s,t){return s!==t},KGvWJ:r(782),zLIIT:r(1677)+r(1890)+r(626)+"g",OPZiW:r(965),DDCVa:function(s,t){return s+t},efpBK:function(s,t){return s||t},wqxTZ:function(s,t){return s!==t},IHFGI:r(1867),FvPnb:r(1834),elXDL:r(1839),AcBzz:function(s,t,n){return s(t,n)},DNKWA:function(s,t,n){return s(t,n)},JKCLo:function(s,t){return s!==t},vAEik:r(473),LBxsn:r(1826)+"ay, network offl"+r(1423),tBzgm:r(873),UGdEK:r(1602),wQxDi:r(1219),fOwFZ:function(s,t){return s>>t},VkRKZ:r(1136),ZolwC:r(599)+r(1011)+r(380)+r(1057)+"ed",nhVdp:function(s,t){return s===t},QIZSN:function(s,t){return s===t},Uwnyn:r(599)+"s alread"+r(399),ObStB:r(1434)+"rovide a valid d"+r(879)+"a must be a stri"+r(792)+" arraybu"+r(929),OLCxi:"number",SYMJx:function(s,t){return s!=t},knEGD:function(s,t){return s(t)},pCWoR:function(s,t){return s(t)},CrWPp:r(1434)+r(506)+r(1093)+r(1369),sVHEj:function(s,t){return s instanceof t},CvRDq:function(s,t){return s(t)},rYQgs:"sent",HLhtI:function(s,t){return s==t},dhwCV:r(1367)+r(918)+"ing",AFIRu:function(s,t){return s(t)},lqhnz:function(s,t){return s!==t},Owwip:"OdrIL",LQPoA:function(s,t){return s*t},FtnpV:"Window",OwvVu:function(s,t){return s!=t},ZpqIa:function(s,t){return s===t},dgaOn:r(1646),LbXLx:function(s,t){return s!=t},SIlms:r(1449)+r(772)+r(1172)+"pe",DPJBO:r(797)+r(1503)+r(1471),WKgcC:"ServiceWorkerGlo"+r(1729),yDTWY:function(s,t){return s!=t},QrXJV:function(s,t){return s===t},jqkcT:function(s,t){return s!=t},bzDwf:r(668)+r(1447)};Se.r(V),Se.d(V,{FWS:()=>q0,CustomErrorEvent:()=>os,createCloseEvent:()=>he,ReconnectEvent:()=>is,createErrorEvent:()=>ce,decodedFrame:()=>es,createOpenEvent:()=>ds,CustomCloseEvent:()=>as,createReconnectEvent:()=>er,FrontierMessageEvent:()=>cs,encodeFrame:()=>Qn,createMessageEvent:()=>us,OpenEvent:()=>fs,ErrorCode:()=>Me,Event:()=>rt,MessageEvent:()=>xs});let i="";function a(s=""){let t=r,n="02",o=""+Date.now(),c=i||(i=m(s)),d=Math.random()[t(1096)](16)[t(1381)](-6);return e[t(1341)](e[t(1745)](e.tezDL(n,o),c),d)}function x(){let s=r;if(e[s(1038)](e[s(1678)],e[s(1678)])){let t=_0x45e832[s(930)]();return t?(t[s(710)]=t[s(1478)]=0,t):{bytes:new _0x492624(64),offset:0,limit:0}}else return e.tezDL(e[s(683)](1e4,Date.now()),Math[s(1497)](e.tjPom(1e4,Math[s(1582)]())))}function f(s){let t=r,n={ljEPq:e[t(446)],vsguq:e[t(1772)],YqdvW:e[t(662)]};if(e[t(1622)](t(673),e[t(691)]))return e[t(1341)](e.Ewtyh(Array,8)[t(498)]("0"),e.DxewR(parseInt,s,10)[t(1096)](2)).slice(-8);_0x4fe0ef[t(447)+t(502)+t(1163)](STlEyl[t(1782)],_0x144e7e),_0x151aac[t(447)+t(502)+t(1163)](STlEyl[t(730)],_0x1102d1),_0x4c2d68[t(447)+t(502)+t(1163)](STlEyl.YqdvW,_0x12ef14)}function l(s){let t=r;return e[t(702)](Array(4).join("0"),parseInt(s,2)[t(1096)](16))[t(1381)](-4)}function h(s){let t=r;if(e[t(520)]==="uwrIq")this[t(1538)]&&this[t(1538)][t(625)](_0x3f3254,_0x11a265);else{let n=s[t(720)](/\./)[t(1576)](d=>f(d)),o=[];return o[0]=e[t(1832)](l,e[t(1120)](n[0],n[1])),o[1]=l(n[2]+n[3]),[e.XCysu,t(490),e[t(1624)],e.XCysu,e[t(1624)],"ffff",o[0],o[1]][t(498)]("")}}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(927)](s),o=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[t(927)](s);return n?e[t(1626)](h,s):o?_(s):e[t(1024)]}function _(s){let t=r,n={BylKC:function(y,v){return y(v)},HgqZP:function(y,v){return e[P(1453)](y,v)},ytEZe:t(1409),zKzqJ:function(y,v){return e[t(1851)](y,v)},aIuMI:function(y,v){return e[t(1851)](y,v)},dpRtL:e[t(1844)]},o="",c=[],d=0,g=0,p=!0,u=t(490);if(s[t(828)]("::")>-1)if(t(809)!==e[t(1739)]){let y=s.split("::");for(let A=0;A<y[t(1410)];A++)if(e.puDEL(e[t(725)],e.pcGUf)){let N=y[A];if(e[t(660)](N[t(828)](":"),0)){let D=N[t(720)](":");p&&(d=D[t(1410)]),g+=D[t(1410)];for(let O=0;e.oVsip(O,D[t(1410)]);O++)if(e[t(1828)](4,D[O][t(1410)])){let ke=u[t(1472)+"g"](0,4-D[O][t(1410)]),$=ke[t(1214)](D[O]);c.push($)}else c[t(1755)](D[O]);p=!1}else{if(e.puDEL(4,N[t(1410)])){let D=u[t(1472)+"g"](0,4-N.length),O=D.concat(N);c[t(1755)](O)}else c[t(1755)](N);p&&(d+=1),g+=1,p=!1}}else _0x4a056b=gHmsQi[t(695)](_0x44bac3,_0x23ec7f);let v="";for(let A=0;e[t(1801)](A,e[t(1594)](8,g));A++)v=v[t(1214)](u);for(let A=0;A<c[t(1410)];A++)e[t(1622)](A,d)?(o=o[t(1214)](v),o=o.concat(c[A])):o=o[t(1214)](c[A]);return o}else try{return n[t(855)](n[t(1206)],typeof _0x1e82f9)&&(n.zKzqJ(_0x8c4e9f,_0x2acffb)||_0x41d358[t(661)]&&n[t(382)](_0x1f3fb9[t(661)],_0xe7d436))||n[t(855)](n[t(1206)],typeof _0x52ef12)?"":(_0x3a8b9b[t(1351)](_0x39426c),t(1179)+t(1270))}catch{return n.ytEZe==typeof _0x3459bf?n.dpRtL:""}{let y=s[t(720)](":");for(let v=0;e[t(838)](v,y[t(1410)]);v++){let A=y[v];if(e[t(1038)](4,y[v].length)){let N=u.substring(0,e.Xsbel(4,y[v][t(1410)])),D=N[t(1214)](A);o=o[t(1214)](D)}else o=o[t(1214)](A)}return o}}function b(s,t){let n=r,o=s[n(764)];e[n(1828)](void 0,o)&&(e[n(1170)](q,t,10),e[n(1717)](ye,t,o));let c=s[n(1843)];e.puDEL(void 0,c)&&(e[n(1663)](q,t,18),e.xXZzL(ye,t,c))}function w(s){let t=r,n={};e:for(;!we(s);){let o=e[t(1626)](X,s);switch(e[t(767)](o,3)){case 0:break e;case 1:n[t(764)]=e[t(899)](_e,s,e[t(1578)](X,s));break;case 2:n[t(1843)]=e[t(947)](_e,s,e.xRgOs(X,s));break;default:e[t(1717)](Q,s,e[t(495)](7,o))}}if(n[t(764)]===void 0)throw new Error(e[t(1521)]);if(e[t(1124)](void 0,n[t(1843)]))throw new Error(e.pyvGg);return n}function C(s){let t=r,n=e[t(765)](I);return k(s,n),e[t(1578)](me,n)}function k(s,t){let n=r,o={sKAeF:function($,se,ot){return $(se,ot)},YfVgm:e[n(1328)]},c=s.SeqID;e[n(1038)](void 0,c)&&(e[n(1717)](q,t,8),e[n(1779)](bt,t,c));let d=s[n(1831)];e.puDEL(void 0,d)&&(q(t,16),e.DXVjR(bt,t,d));let g=s[n(386)];e.puDEL(void 0,g)&&(e[n(1622)](e[n(1858)],e[n(1858)])?(e[n(1779)](q,t,24),e.xXZzL(bt,t,e.Ewtyh(ne,g))):this[n(1303)](n(1239),o.sKAeF(_0x3a4045,o.YfVgm,{..._0x363c2d})));let p=s[n(1144)];if(e[n(936)](void 0,p))if(e[n(978)](e[n(527)],e[n(527)]))e.Lokvz(q,t,32),e[n(445)](bt,t,e[n(1578)](ne,p));else{let $=!!this[n(1437)].enableQoS;if(!$)return{enabled:$,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let se=e[n(1810)](_0x19ad06,_0x1dfd51[n(1239)][n(572)],e[n(732)],"2"),ot=se&&_0x2e8824(_0x3031fc.message[n(572)],e[n(1515)],"1"),Ct=se&&e[n(654)](_0x259ac5,_0x4fcfeb[n(1239)][n(572)],e[n(1016)],"1"),xr=Ct?e[n(1029)](_0x5c41fd,_0x2c53fc[n(1239)][n(572)],n(1709)+n(1224)+"sgid")?.[n(720)](",")[n(1518)](_0x3d8a89)||[]:[];return{enabled:$,isQoSMessage:se,isQoSAck:ot,isAckCleanupMessage:Ct,ackMsgIds:xr}}let u=s.headers;if(u!==void 0)for(let $ of u){q(t,42);let se=e[n(1673)](I);e.hLHzr(b,$,se),e[n(508)](q,t,se[n(1478)]),e[n(1074)]($n,t,se),e[n(1815)](M,se)}let y=s["payloadE"+n(963)];e.LABtw(void 0,y)&&(e.RxdYu(q,t,50),e[n(1285)](ye,t,y));let v=s["payloadT"+n(1799)];e[n(1038)](void 0,v)&&(e.UVkwf(q,t,58),e[n(1779)](ye,t,v));let A=s[n(1666)];A!==void 0&&(e[n(614)](q,t,66),q(t,A[n(1410)]),e[n(1663)](jt,t,A));let N=s[n(1806)];e[n(1828)](void 0,N)&&(e[n(1859)](q,t,74),ye(t,N));let D=s[n(806)+n(678)];e.qCMBG(void 0,D)&&(q(t,82),e[n(1792)](ye,t,D));let O=s[n(608)];e.IqSbU(void 0,O)&&(e[n(1029)](q,t,90),e.HhWqv(ye,t,O));let ke=s[n(1762)+"e"];e[n(1527)](void 0,ke)&&(q(t,96),e.CNJng(bt,t,e[n(1116)](ne,ke)))}function T(s){let t=r;return e[t(1385)](L,e[t(1116)](Y,s))}function L(s){let t=r,n={};e:for(;!e[t(1483)](we,s);){let o=e[t(1700)](X,s);switch(o>>>3){case 0:break e;case 1:n[t(1754)]=e.cywoN(Qr,s,!0);break;case 2:n.LogID=e[t(1262)](Qr,s,!0);break;case 3:n[t(386)]=e[t(1578)](X,s);break;case 4:n[t(1144)]=X(s);break;case 5:{let c=F(s);(n[t(572)]||(n.headers=[]))[t(1755)](e[t(1700)](w,s)),s[t(1478)]=c;break}case 6:n[t(717)+t(963)]=e.hLHzr(_e,s,e[t(1301)](X,s));break;case 7:n[t(1394)+t(1799)]=e[t(1029)](_e,s,e[t(1301)](X,s));break;case 8:n[t(1666)]=Ht(s,e[t(574)](X,s));break;case 9:n[t(1806)]=e[t(644)](_e,s,e[t(788)](X,s));break;case 10:n[t(806)+t(678)]=e[t(719)](_e,s,e.zzXGU(X,s));break;case 11:n[t(608)]=e[t(1823)](_e,s,e[t(1578)](X,s));break;case 12:n.frameType=e[t(1724)](X,s);break;default:e[t(1244)](Q,s,e.OZfQF(7,o))}}if(e[t(1124)](void 0,n[t(1754)]))throw new Error(e[t(1461)]);if(e[t(978)](void 0,n[t(1831)]))throw new Error(t(1731)+"required"+t(378)+t(1831));if(e[t(1892)](void 0,n[t(386)]))throw new Error(e[t(1424)]);if(e[t(1846)](void 0,n.method))throw new Error(e[t(957)]);return n}function F(s){let t=r,n={tjeEb:function(o,c,d){return e[P(1074)](o,c,d)},mALuf:function(o,c){return e[P(1023)](o,c)},hVFpO:function(o,c){return e[P(1596)](o,c)}};if(e[t(1622)](e[t(681)],e[t(681)])){let o=e.RBEzj(X,s),c=s[t(1478)];return s[t(1478)]=s[t(710)]+o,c}else n[t(1671)](_0x219293,_0x44a1e3,n[t(1153)](n.hVFpO(127,_0x4cd6b9),128)),_0x1394fb>>>=7}function Q(s,t){let n=r;switch(t){case 0:for(;e[n(495)](128,e[n(1524)](re,s)););break;case 2:e[n(1275)](De,s,e.RBEzj(X,s));break;case 5:e.vYKQw(De,s,4);break;case 1:e[n(870)](De,s,8);break;default:throw new Error(e.jurwb(e.sOAtx,t))}}function ne(s){let t=r;return s|=0,{low:s,high:e[t(1664)](s,31),unsigned:s>=0}}let Ae=[];function I(){let s=r,t=Ae[s(930)]();return t?(t.offset=t[s(1478)]=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function M(s){let t=r;if(e.gSkxr(t(1718),e[t(1092)]))return this[t(1107)][t(960)+"te"];Ae[t(1755)](s)}function Y(s){return{bytes:s,offset:0,limit:s[r(1410)]}}function me(s){let t=r,n=s.bytes,o=s[t(1478)];return n[t(1410)]===o?n:n[t(795)](0,o)}function De(s,t){let n=r;if(e[n(1142)](e[n(1263)](s[n(710)],t),s[n(1478)]))throw new Error(n(815)+"t limit");s[n(710)]+=t}function we(s){let t=r;return e[t(1822)]===e.FROBS?new _0x227d5b(_0x343ef3,_0x2e5ae0,_0x25e408):s[t(710)]>=s[t(1478)]}function le(s,t){let n=r,o=s[n(886)],c=s[n(710)],d=s[n(1478)],g=c+t;if(e.Uonxv(g,o[n(1410)])){let p=new Uint8Array(e[n(683)](2,g));p[n(756)](o),s[n(886)]=p}return s[n(710)]=g,e[n(1268)](g,d)&&(s.limit=g),c}function We(s,t){let n=r,o=s[n(710)];if(e[n(660)](e.tezDL(o,t),s[n(1478)]))throw new Error(e[n(1567)]);return s[n(710)]+=t,o}function Ht(s,t){let n=r,o=e.UYFtA(We,s,t);return s[n(886)][n(795)](o,e[n(474)](o,t))}function jt(s,t){let n=r,o=le(s,t.length);s[n(886)][n(756)](t,o)}function _e(s,t){let n=r,o=e[n(445)](We,s,t),c=String[n(1809)+n(1207)],d=s.bytes,g="\uFFFD",p="";for(let u=0;u<t;u++){let y=d[e[n(1141)](u,o)],v,A,N,D;if(e.kmJbj(128,y)===0)p+=e.GwDtQ(c,y);else if(e[n(1563)](e.ICKWb(224,y),192))if(e.HiQYI(u+1,t))p+=g;else if(v=d[e.mbQrO(e[n(505)](u,o),1)],e[n(1658)](192,v)!==128)p+=g;else if(D=e.oaPZR(e[n(1783)](31&y,6),e[n(1346)](63,v)),e[n(1801)](D,128))p+=g;else{if(e.CKOxP(e[n(1063)],e[n(1063)]))return this._qosDB[n(916)+n(436)]();p+=e[n(1815)](c,D),u++}else e[n(1056)](e.kmJbj(240,y),224)?e.DBwwn(u,2)>=t?p+=g:(v=d[e[n(474)](u,o)+1],A=d[e.rcPWh(e.HuTWn(u,o),2)],e[n(1613)](e.OZfQF(e[n(739)](v,e.yuGan(A,8)),49344),32896)?p+=g:(D=e.LsGFJ(e[n(1468)](e[n(1557)](15,y),12)|e[n(780)](63,v)<<6,63&A),D<2048||e[n(1845)](D,55296)&&e[n(853)](D,57343)?p+=g:(p+=e[n(788)](c,D),u+=2))):e[n(1060)](248&y,240)?e[n(1464)](e[n(1789)](u,3),t)?p+=g:(v=d[e[n(1208)](u+o,1)],A=d[e[n(505)](u+o,2)],N=d[e[n(1208)](e.gkbFt(u,o),3)],e[n(1786)](e.qvwFm(e[n(739)](e[n(1023)](v,e[n(420)](A,8)),e[n(420)](N,16)),12632256),8421504)?p+=g:(D=e[n(849)](e[n(1335)](e.HtscO((7&y)<<18,e[n(1046)](e[n(650)](63,v),12)),e[n(1557)](63,A)<<6),e[n(650)](63,N)),e.OaVlU(D,65536)||e[n(660)](D,1114111)?p+=g:(D-=65536,p+=e.HhWqv(c,e[n(1341)](e[n(693)](D,10),55296),e[n(1557)](1023,D)+56320),u+=3))):p+=g}return p}function ye(s,t){let n=r,o={JLwCI:function(u,y){return e[P(536)](u,y)},CqzDT:function(u,y){return e[P(1658)](u,y)},FyZRU:function(u,y){return e[P(1557)](u,y)},TXcHv:function(u,y){return e[P(907)](u,y)},zuLgt:function(u,y){return e.jXLwz(u,y)}},c=t[n(1410)],d=0;for(let u=0;e.DYRhQ(u,c);u++){let y=t[n(1710)+"At"](u);e[n(1316)](y,55296)&&y<=56319&&e.NHfyF(u+1,c)&&(y=e[n(1594)]((y<<10)+t[n(1710)+"At"](++u),56613888)),d+=e[n(838)](y,128)?1:e.OaVlU(y,2048)?2:e[n(982)](y,65536)?3:4}q(s,d);let g=le(s,d),p=s[n(886)];for(let u=0;e.DhzsO(u,c);u++){let y=t[n(1710)+"At"](u);if(e[n(1458)](y,55296)&&e[n(1125)](y,56319)&&e[n(702)](u,1)<c&&(y=e.YtAHv(e[n(702)](y<<10,t[n(1710)+"At"](++u)),56613888)),e.rqJVr(y,128))p[g++]=y;else if(e[n(1583)](e[n(1178)],e[n(1178)]))e[n(1801)](y,2048)?p[g++]=e[n(553)](e[n(1579)](e[n(1664)](y,6),31),192):(e[n(970)](y,65536)?p[g++]=e.Rchgq(e[n(390)](y>>12,15),224):e.etwVe(e[n(984)],e.sdOfp)?(_0x3085f4=jUAkdv[n(1819)](jUAkdv.CqzDT(31,_0x3ce80d)<<6,jUAkdv[n(910)](63,_0x141022)),jUAkdv.TXcHv(_0x265453,128)?_0x31ee9c+=_0x134ba7:(_0x2f71b2+=jUAkdv.zuLgt(_0x5c6803,_0x4dc727),_0x4b2af7++)):(p[g++]=e[n(1058)](e[n(1343)](e[n(549)](y,18),7),240),p[g++]=e.RxvBZ(e.SneRU(e[n(1664)](y,12),63),128)),p[g++]=e.QppcK(e[n(693)](y,6)&63,128)),p[g++]=e.QppcK(e.TlRrG(63,y),128);else throw _0x329cae=_0xe6a4f[n(1410)],e[n(1810)](_0x24e92f,_0x33e89d,10,_0x42a4f4[n(1410)])}}function $n(s,t){let n=r,o=e.opNHF(le,s,t[n(1478)]),c=s.bytes,d=t[n(886)];for(let g=0,p=t.limit;e[n(1042)](g,p);g++)c[e[n(1341)](g,o)]=d[g]}function re(s){let t=r;return s.bytes[e[t(1235)](We,s,1)]}function be(s,t){let n=r,o=e[n(594)](le,s,1);s[n(886)][o]=t}function X(s){let t=r,n=0,o=0,c;do c=e.vLIqv(re,s),e.rqJVr(n,32)&&(o|=(127&c)<<n),n+=7;while(e[t(533)](128,c));return o}function q(s,t){let n=r;for(t>>>=0;e[n(777)](t,128);)e[n(1590)](be,s,127&t|128),t>>>=7;e[n(639)](be,s,t)}function Qr(s,t){let n=r,o={axADq:function(c,d,g){return e.cjDOd(c,d,g)},WiIJk:function(c,d){return e[P(849)](c,d)},rkmGy:function(c,d){return e[P(1579)](c,d)},vJuyA:function(c,d){return c>=d},UwUCa:function(c,d,g){return e[P(499)](c,d,g)},fGCRg:e[n(1032)]};if(e[n(1002)](e[n(716)],e[n(716)])){let c=_0xf4b199[n(1472)+"g"](0,e.nHUmw(4,_0x4dca91[n(1410)])),d=c[n(1214)](_0x35bd4a);_0x18696e[n(1755)](d)}else{let c=0,d=0,g=0,p;if(p=re(s),c=127&p,e[n(807)](128,p)&&(p=e[n(735)](re,s),c|=e[n(1346)](127,p)<<7,128&p&&(p=e[n(1815)](re,s),c|=e[n(1783)](e[n(1274)](127,p),14),e[n(1302)](128,p)&&(p=e.dssic(re,s),c|=e[n(958)](e[n(1274)](127,p),21),e[n(807)](128,p)&&(p=e[n(412)](re,s),d=127&p,e[n(456)](128,p)))))){if(e[n(1622)](e[n(1109)],"UZSYJ")){for(_0x43fa0b>>>=0;_0x5d1afd>=128;)VjsALS[n(837)](_0x21b851,_0x1781d1,VjsALS[n(1838)](VjsALS.rkmGy(127,_0x16b1dd),128)),_0x1b36ee>>>=7;VjsALS[n(837)](_0x4b9e91,_0x2818ef,_0xe7f4fb)}else if(p=e[n(1700)](re,s),d|=e[n(1258)](e.lwkfc(127,p),7),e[n(1274)](128,p)){if(e[n(694)](n(757),e.jxmZk))return VjsALS[n(1088)](_0x18149b[n(710)],_0x331a8f[n(1478)]);if(p=e[n(558)](re,s),d|=e.jJTFb(127&p,14),e.OZfQF(128,p)&&(p=e[n(1832)](re,s),d|=e.LUVGL(e[n(533)](127,p),21),e.uhcRo(128,p)))if(e[n(694)](e[n(1365)],e.MgkRU)){let u=this[n(577)+n(1546)]?.["getCurre"+n(396)+"nt"]();this[n(1850)+n(1230)+n(444)](o[n(890)](_0x37e4a8,o[n(496)],{code:_0x4e587e[n(402)],reason:"connecti"+n(1014)+"d, unkno"+n(682)+n(868)+n(437)+u})),this[n(577)+n(1546)]?.[n(394)+"pointCon"+n(557)](),this[n(696)+n(1117)]?.[n(1682)+n(491)]();return}else p=re(s),g=127&p,e.qvwFm(128,p)&&(p=e[n(1450)](re,s),g|=e[n(881)](e[n(495)](127,p),7))}}return{low:e.tMkus(c,e[n(1574)](d,28)),high:e[n(1889)](d>>>4,g<<24),unsigned:t}}}function bt(s,t){let n=r,o={rBifw:function(c,d){return e[P(1700)](c,d)},EuLLs:n(999)+n(1216)+"t"};if(n(1386)!==e[n(950)]){let c=e[n(767)](t[n(823)],0),d=e[n(1150)](e[n(885)](e.mhPgv(t[n(823)],28),e[n(420)](t[n(494)],4)),0),g=e[n(1399)](t[n(494)],24),p=e.LVVqN(0,g)?e[n(1639)](0,d)?c<16384?e.CQuwZ(c,128)?1:2:e[n(781)](c,2097152)?3:4:e[n(1520)](d,16384)?e[n(970)](d,128)?5:6:e[n(573)](d,2097152)?7:8:e[n(1520)](g,128)?9:10,u=e.Dtagz(le,s,p),y=s[n(886)];switch(p){case 10:y[e.XMKgo(u,9)]=e[n(1785)](g,7)&1;case 9:y[e[n(1120)](u,8)]=e[n(1119)](9,p)?128|g:127&g;case 8:y[e[n(1379)](u,7)]=p!==8?e.Ifeff(d,21)|128:e[n(1289)](e[n(776)](d,21),127);case 7:y[e[n(423)](u,6)]=p!==7?e[n(1476)](d>>>14,128):e[n(480)](e[n(1113)](d,14),127);case 6:y[e[n(1789)](u,5)]=p!==6?e[n(489)](e[n(869)](d,7),128):e.VjHeH(e.fjOJn(d,7),127);case 5:y[e.aEIoR(u,4)]=p!==5?e[n(1476)](128,d):e[n(1287)](127,d);case 4:y[e[n(1789)](u,3)]=p!==4?e.xrRmb(e[n(1145)](c,21),128):e.Ifeff(c,21)&127;case 3:y[e[n(1059)](u,2)]=e[n(1606)](3,p)?e[n(595)](e[n(1661)](c,14),128):e.IzOvR(e[n(979)](c,14),127);case 2:y[e[n(1028)](u,1)]=e[n(1606)](2,p)?e.QPugF(c,7)|128:e[n(987)](e[n(1145)](c,7),127);case 1:y[u]=p!==1?e.inqRa(128,c):e[n(1160)](127,c)}}else o[n(1051)](_0x362350,"success"),this[n(666)]("ping_once_success",_0x319b01),this[n(666)](o.EuLLs,_0x295870)}function es(s){let t=r;if(e[t(1606)](e[t(1796)],e[t(1796)]))this[t(1303)](e.JFjpV,_0x3dd518),this.onerror&&this[t(658)](_0x4bc2fa);else return e.VuvCV(T,s)}function Qn(s){let t=r;if(e.WwUPl(t(1514),t(949)))return e[t(1376)](C,s);_0x5eb2d8.d=(n,o)=>{let c=t;for(var d in o)_0x4b6f4d.o(o,d)&&!_0x2a5993.o(n,d)&&_0x4602e9[c(1676)+c(1368)](n,d,{enumerable:!0,get:o[d]})}}let ts=65536,Xo="\0\0\0\0\0\0\0\0",nt=ts*ts,ns=e[r(1620)](nt,nt),rs=e[r(1897)](ns,2),ze=String[r(1276)+"e"][r(1710)+"At"];class B{constructor(t,n,o){let c=r;this[c(705)]=!0,this[c(823)]=e[c(739)](0,t),this[c(494)]=e[c(631)](0,n),this[c(940)]=!!o}static isLong(t){let n=r,o={bUpXR:function(c,d){return e[P(536)](c,d)},LRIWw:function(c,d){return e[P(758)](c,d)},TsefO:function(c,d){return e[P(884)](c,d)},lxALN:function(c,d){return e.hoyid(c,d)},BqOcI:function(c,d){return e[P(1619)](c,d)},exQIH:function(c,d){return c<d},bdSOa:function(c,d){return e[P(1845)](c,d)},iFGnD:function(c,d){return c<=d}};if(n(1204)!==e[n(1078)])_0x4ce089=AyBwyg[n(478)](AyBwyg.LRIWw(AyBwyg[n(1164)](15,_0x4f638b),12),AyBwyg[n(920)](AyBwyg[n(598)](63,_0x4aa7d6),6))|AyBwyg.TsefO(63,_0xb33b2d),AyBwyg[n(1404)](_0x3c7f85,2048)||AyBwyg[n(514)](_0x1c3ae9,55296)&&AyBwyg[n(567)](_0x5941a3,57343)?_0x5a8d93+=_0x4db57b:(_0x52b858+=_0x9df4fe(_0xba943b),_0x117722+=2);else return t&&e[n(1322)](!0,t[n(705)])}static fromBits(t,n,o){return new B(t,n,o)}static[r(1688)+"s"](t,n,o){let c=r;return o?B[c(1688)+"sLE"](t,n):B["fromByte"+c(1694)](t,n)}static[r(1688)+"sLE"](t,n){let o=r;return new B(e[o(631)](e.xrRmb(e[o(604)](t[0],e[o(1064)](t[1],8)),t[2]<<16),e.jJTFb(t[3],24)),e.inqRa(e[o(595)](t[4],t[5]<<8)|e.lMhhs(t[6],16),e[o(1258)](t[7],24)),n)}static[r(1688)+"sBE"](t,n){let o=r;return new B(e.oaPZR(e[o(841)](e[o(885)](t[4]<<24,e[o(1293)](t[5],16)),e[o(1753)](t[6],8)),t[7]),e[o(1023)](e[o(1362)](e.DrDbj(e[o(958)](t[0],24),e[o(1199)](t[1],16)),t[2]<<8),t[3]),n)}static fromHash(t){let n=r;return e[n(708)](t,Xo)?ss:new B(e[n(1440)](e.eSBNV(e.xrRmb(ze[n(1329)](t,0),e[n(1128)](ze[n(1329)](t,1),8))|e[n(1468)](ze.call(t,2),16),ze[n(1329)](t,3)<<24),0),(e[n(616)](ze[n(1329)](t,4),ze[n(1329)](t,5)<<8)|ze[n(1329)](t,6)<<16|e.TZGyO(ze[n(1329)](t,7),24))>>>0,!0)}[r(1765)](){let t=r;return String["fromChar"+t(1207)](e[t(533)](255,this[t(823)]),e[t(1820)](this[t(823)]>>>8,255),e[t(456)](this[t(823)]>>>16,255),e[t(1719)](this[t(823)],24),255&this[t(494)],e.PXVaH(e[t(869)](this.high,8),255),e.SiDPv(e.iyRgx(this[t(494)],16),255),e[t(537)](this.high,24))}static[r(1445)+"er"](t,n=!0){let o=r;if(e.PqQbw(isNaN,t))return n?Zo:ss;if(n){if(e[o(1609)](t,ns))return Qo}else{if(e[o(627)](t,-rs))return e0;if(e.EmVtb(e.NPLCn(t,1),rs))return $o}return B[o(1229)](e.qiwTS(e.XnEcc(t,nt),0),e[o(1362)](e.hPXlA(t,nt),0),n)}toNumber(){let t=r;return this[t(940)]?e[t(762)](e.lvRsB(e.UzpwA(this[t(494)],0),nt),this[t(823)]>>>0):e[t(1120)](this[t(494)]*nt,e[t(638)](this[t(823)],0))}[r(1625)](){let t=r;return e.wrolH(0,this[t(494)])&&e[t(1361)](0,this[t(823)])}add(t){let n=r;B[n(705)](t)||(t=B.fromNumber(t));let o=e[n(979)](this[n(494)],16),c=65535&this.high,d=this[n(823)]>>>16,g=65535&this[n(823)],p=e.fjOJn(t[n(494)],16),u=e[n(1343)](65535,t[n(494)]),y=e.QPugF(t[n(823)],16),v=65535&t[n(823)],A=0,N=0,D=0,O=0;return O+=g+v,D+=e.mbsVs(O,16),O&=65535,D+=e[n(1059)](d,y),N+=D>>>16,D&=65535,N+=e[n(860)](c,u),A+=N>>>16,N&=65535,A+=e[n(391)](o,p),A&=65535,B.fromBits(e[n(679)](e[n(1250)](D,16),O),e[n(1149)](e[n(1337)](A,16),N),this.unsigned)}[r(1382)](t){let n=r;return B[n(705)](t)||(t=B[n(1445)+"er"](t)),this[n(940)]!==t[n(940)]&&e.BZkRH(e.bKQiJ(this.high,31),1)&&t[n(494)]>>>31===1?!1:e.XotCJ(this.high,t[n(494)])&&this[n(823)]===t[n(823)]}[r(724)](){let t=r;return e[t(1326)](-1,this[t(823)])&&e.uWgey(-1,this[t(494)])?B.fromBits(0,0,this[t(940)]):e[t(1563)](-1,this[t(823)])?B[t(1229)](0,e[t(1211)](this[t(494)],1),this[t(940)]):B[t(1229)](e.aEIoR(this[t(823)],1),this[t(494)],this[t(940)])}[r(418)](t){return t?this.toBytesLE():this.toBytesBE()}[r(785)+"E"](){let t=r,n=this.high,o=this.low;return[e[t(987)](255,o),e[t(1619)](o>>>8,255),o>>>16&255,o>>>24,255&n,e[t(1403)](n>>>8,255),e[t(1364)](n,16)&255,e.wDKCR(n,24)]}toBytesBE(){let t=r,n=this[t(494)],o=this.low;return[e.GULPe(n,24),e.VvTBt(e[t(1486)](n,16),255),e.ICKWb(e[t(1054)](n,8),255),255&n,e.wDKCR(o,24),e.XpCkr(e[t(1383)](o,16),255),e.zLmqb(e[t(1486)](o,8),255),255&o]}}let ss=new B(0,0,!1),Zo=new B(0,0,!0),$o=B.fromBits(-1,2147483647,!1),Qo=B[r(1229)](-1,-1,!0),e0=B[r(1229)](0,-2147483648,!1);var Me=(function(s){let t=r,n=e.sifMa[t(720)]("|"),o=0;for(;;){switch(n[o++]){case"0":return s;case"1":s[s[t(951)+"IES_ERROR"]=5003]=e[t(611)];continue;case"2":s[s[e[t(1535)]]=5001]=e.TcDLi;continue;case"3":s[s[t(1674)+"NG_ERROR"]=5002]=t(1674)+t(1065);continue;case"4":s[s[e.Mouli]=5004]=t(953)+t(540);continue;case"5":s[s[t(642)+"OR"]=5005]=e[t(1544)];continue}break}})({});class rt{constructor(t){let n=r;this[n(1188)]=t,this[n(664)]=null}}class is extends rt{constructor(t,n){let o=r;super(t),this[o(1239)]=n&&n.message||null}}class os extends rt{constructor(t,n){let o=r;if(e.IlGIp(e[o(1452)],e[o(1452)]))try{e[o(654)](_0x354eda,this,_0xde1186,[_0x155670,_0x34a731,_0x512bbe])}catch(c){let d=_0xe032ec(e[o(1772)],{message:c[o(1239)],code:_0x10d147[o(642)+"OR"],error:c});this[o(1850)+o(1510)+o(444)](d)}else{let c=e[o(1114)][o(720)]("|"),d=0;for(;;){switch(c[d++]){case"0":this[o(485)]=n&&n[o(485)]||0;continue;case"1":this[o(1588)]=n&&n[o(1588)]||"";continue;case"2":this[o(1239)]=n&&n.message||"";continue;case"3":this[o(1227)]=n&&n.error||null;continue;case"4":this[o(402)]=n&&n[o(402)]||5001;continue;case"5":super(t);continue;case"6":this[o(546)]=n&&n.colno||0;continue}break}}}}class as extends rt{constructor(t,n){let o=r;super(t),this[o(402)]=n&&n.code||0,this[o(1879)]=n&&n[o(1879)]||"",this[o(761)]=n&&n[o(761)]||!1,this[o(622)+o(1183)]=n&&n[o(622)+o(1183)]||!1}}class xs extends rt{constructor(t,n){let o=r;super(t),this[o(1375)]=n&&n.data||null}}class cs extends xs{constructor(t,n){let o=r;super(t),this[o(1375)]=n&&n[o(1375)]||null,this[o(1239)]=n&&n[o(1239)]||null}}class fs extends rt{constructor(t,n){let o=r;super(t),this[o(1375)]=n&&n[o(1375)]||null}}function ce(s,{message:t,code:n,error:o}){return new os(s,{message:t,code:n,error:o})}function he(s,{code:t,reason:n,wasClean:o,willReconnect:c}){return new as(s,{code:t,reason:n,wasClean:o,willReconnect:c})}function us(s,{data:t,message:n}){return new cs(s,{data:t,message:n})}function ds(s,{data:t}){return new fs(s,{data:t})}function er(s,{message:t}){let n=r;if(e[n(1613)](e.tRxPP,e[n(1608)])){let o=e[n(917)][n(720)]("|"),c=0;for(;;){switch(o[c++]){case"0":if(!this[n(1538)])return;continue;case"1":this._ws["addEvent"+n(793)](e[n(1772)],this[n(1672)]);continue;case"2":this._ws.addEventListener(e[n(1328)],this[n(1634)+"ge"]);continue;case"3":this[n(1538)]["addEvent"+n(793)](e[n(1704)],this[n(1392)]);continue;case"4":this[n(1538)][n(635)+n(793)](n(625),this[n(1833)]);continue}break}}else return new is(s,{message:t})}class ls{constructor(t,n){let o=r;this[o(836)+"s"]=t,this.maxRetries=n,this.currentIndex=0,this[o(1181)+o(1197)+o(844)+"t"]=0}[r(394)+r(1711)+r(557)](){let t=r;this[t(1525)+t(1615)]=0,this[t(1181)+t(1197)+"riesCount"]=0}resetTries(){let t=r;this["currentE"+t(1197)+t(844)+"t"]=0}[r(504)+r(396)+"nt"](){let t=r;return this[t(836)+"s"][this[t(1525)+t(1615)]]}[r(504)+r(396)+r(1847)+r(1502)](){let t=r;return this[t(1181)+t(1197)+t(844)+"t"]}[r(712)+"chMaxTries"](){let t=r;return!!(e[t(777)](this.currentIndex,this.endpoints.length)||this["currentI"+t(1615)]===e[t(1863)](this[t(836)+"s"][t(1410)],1)&&e.kHEYI(this[t(1181)+t(1197)+t(844)+"t"],this[t(728)+"es"]))}[r(615)+r(1210)+r(1604)+r(1549)+r(985)](){let t=r;return e.VHhJr(this[t(1525)+"ndex"],this[t(836)+"s"][t(1410)])?!0:e[t(1353)](this[t(1181)+t(1197)+"riesCount"],this[t(728)+"es"])}[r(825)+r(875)+r(392)+r(1013)+r(492)](){let t=r;return this[t(1181)+"ndpointT"+t(844)+"t"]=1,this[t(1525)+t(1615)]++,this.endpoints[this[t(1525)+t(1615)]]}[r(504)+"ntEndpointAndUpd"+r(770)](){let t=r;return this[t(1181)+"ndpointT"+t(844)+"t"]++,this[t(504)+"ntEndpoint"]()}}let st=(e.SYMJx(e.GCOan,typeof globalThis)&&e.FtnpV===globalThis[r(942)+r(1623)][r(966)]||r(647)+"d"!=typeof window&&e[r(1231)](e.FtnpV,window[r(942)+r(1623)][r(966)]))&&e[r(754)](e[r(571)],typeof document),Je=e[r(1699)](e[r(571)],typeof globalThis)&&(e[r(935)]("Object",globalThis[r(942)+"tor"][r(966)])||e.ZpqIa(r(1449)+r(772)+r(1172)+"pe",globalThis[r(942)+r(1623)].name))&&e[r(571)]!=typeof tt,vt=(e[r(1300)](e.GCOan,typeof globalThis)&&e[r(1873)](e[r(882)],globalThis[r(942)+"tor"][r(966)])||e[r(571)]==typeof globalThis||e.OwvVu("undefined",typeof globalThis)&&!!globalThis[r(1534)+r(864)])&&e[r(941)](e.GCOan,typeof wx),St=e[r(1180)](r(647)+"d",typeof globalThis)&&(e[r(1639)](e[r(1864)],globalThis["construc"+r(1623)][r(966)])||e[r(1354)](e[r(1530)],globalThis[r(942)+"tor"][r(966)])||e[r(411)](e[r(904)],globalThis[r(942)+r(1623)][r(966)]))&&e[r(571)]!=typeof self,t0=e[r(746)](r(647)+"d",typeof globalThis)&&e[r(1560)](r(1646),globalThis[r(942)+r(1623)][r(966)])&&r(647)+"d"!=typeof global&&r(1646)===global["construc"+r(1623)][r(966)]&&e[r(571)]!=typeof process&&!!process.version;class tr{constructor(){let t=r;this[t(1882)+"rs"]={}}[r(1303)](t,...n){let o=r,c=this[o(1882)+"rs"][t];if(c)c[o(1381)]().forEach(d=>d.fn[o(1137)](d[o(429)],n));else if(e.LVVqN(e[o(1772)],t)&&!this[o(658)]){let d=n[o(1410)]&&n[0];if(e[o(1052)](d,Error))throw d;let g=new Error(e[o(860)](e[o(665)],d?e[o(403)](e.ZxqDd(" (",d[o(1239)]),")"):""));throw g[o(1874)]=d,d}return this}[r(666)](t,n){let o=r;if(e[o(978)](void 0,t))this[o(1882)+"rs"]={};else if(n===void 0)this._listeners[t]=null;else{let c=this[o(1882)+"rs"][t];if(c)for(let d=0;e.VlOVb(d,c[o(1410)]);)e[o(1758)](c[d].fn,n)?c[o(872)](d,1):++d}return this}on(t,n,o){let c=r;return(this[c(1882)+"rs"][t]||(this[c(1882)+"rs"][t]=[])).push({fn:n,ctx:o||this}),this}}class n0 extends tr{[r(1247)+r(706)+r(1877)](t){let n=r;return t[n(1194)]||t.errNo?(n(404)+" "+(t[n(1194)]||"")+n(539)+(t[n(515)]||""))[n(1217)]():JSON.stringify(t)}constructor(t,n,o){let c=r;super(),this._socket=null,vt&&wx[c(1018)+"ocket"]&&(this[c(1107)]=wx[c(1018)+"ocket"]({url:t,protocols:n,header:o,fail:this[c(1288)+c(852)+c(671)][c(1267)](this),success:this[c(1288)+c(1259)+"cessHand"+c(1607)][c(1267)](this)})),Je&&tt[c(1018)+"ocket"]&&(this[c(1107)]=tt[c(1018)+"ocket"]({url:t,protocols:n,header:o,fail:this["_createSocketFai"+c(671)][c(1267)](this),success:this[c(1288)+c(1259)+c(1746)+"ler"][c(1267)](this)}))}[r(1288)+r(1259)+r(1746)+"ler"](){let t=r,n={EpFvN:function(o,c,d){return e[P(847)](o,c,d)}};e[t(1038)](e[t(1866)],e[t(1802)])?Promise[t(1593)]()[t(1407)](()=>{this[t(468)+"steners"]()}):n.EpFvN(_0x26428e,_0x344737,this["_getInte"+t(643)+"e"](_0x17df60))}[r(1288)+r(852)+"lHandler"](t){let n=r;if(e.LVVqN(e[n(726)],e.HYACl))Promise[n(1593)]().then(()=>{let o=n,c=ce(o(1227),{message:this[o(1247)+"rrorMess"+o(1877)](t)});this.emit(o(1227),c);let d=e[o(414)](he,o(625),{reason:this["_formatE"+o(706)+o(1877)](t)});this[o(1303)](e[o(1032)],d)});else{let o=new _0xa95e3(e[n(683)](2,_0xd75c0c));o.set(_0x5f178c),_0x4fa62e[n(886)]=o}}[r(468)+r(889)](){let t=r,n={lFUsz:t(1191),hgQrJ:function(o,c,d){return e[t(1242)](o,c,d)},pzsAM:e[t(1328)]};this._socket.onOpen(o=>{let c=t;this[c(1303)](n[c(1071)],n[c(1305)](ds,n[c(1071)],{...o,data:o[c(1194)]||""}))}),this[t(1107)][t(510)](o=>{let c=t;this[c(1303)](e[c(1032)],e.tErsb(he,c(625),{...o}))}),this[t(1107)][t(530)+"e"](o=>{let c=t;this[c(1303)](c(1239),n[c(1305)](us,n.pzsAM,{...o}))}),this[t(1107)][t(900)](o=>{let c=t;this.emit(e[c(1772)],e.WhzhO(ce,e[c(1772)],{...o,message:o.errMsg||""}))})}[r(475)](t){let n=r;if(e[n(1670)](t,Uint8Array)){let o=t[n(661)].slice(t[n(1641)+"et"],e[n(1341)](t[n(1130)+"th"],t.byteOffset));this[n(1107)]&&this[n(1107)][n(475)]({data:o,fail:c=>{let d=n;this[d(1303)](e[d(1772)],e[d(1416)](ce,e.JFjpV,{message:this[d(1247)+d(706)+d(1877)](c)}))}})}else this._socket&&this._socket.send({data:t,fail:o=>{let c=n;this[c(1303)](e[c(1772)],e[c(1318)](ce,e.JFjpV,{message:this[c(1247)+"rrorMessage"](o)}))}})}[r(625)](t,n){let o=r;this._socket&&this[o(1107)][o(625)]({code:t,reason:n})}["addEvent"+r(793)](t,n){this.on(t,n)}["removeEv"+r(502)+"ner"](t,n){this[r(666)](t,n)}get[r(960)+"te"](){let t=r;return this._socket[t(960)+"te"]}get[r(1781)+"pe"](){let t=r;return this[t(1107)][t(1781)+"pe"]}set[r(1781)+"pe"](t){}get[r(1332)](){let t=r;return this[t(1107)][t(1332)]}get protocol(){return this[r(1107)].protocol}get[r(1884)+"ns"](){return this[r(1107)].extensions}get bufferedAmount(){return 0}}function r0(s,t){let n=r;if(t)return new t(s.url,s[n(1756)]);if(e[n(1774)](vt,Je))return new n0(s.url,s.protocol,s[n(572)]);if(e[n(1774)](st,St)&&n(647)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(s[n(1332)],s.protocols)}function s0(s){let t=r,n=e[t(1865)].split("|"),o=0;for(;;){switch(n[o++]){case"0":if(vt&&wx[t(1018)+t(1372)])return!0;continue;case"1":return!1;case"2":if(s)return!0;continue;case"3":if(Je&&tt[t(1018)+t(1372)])return!0;continue;case"4":if((st||St)&&e[t(1699)](e[t(571)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function hs(s,t,n){let o=r,c=-1;async function d(g){let p=P;return e[p(1465)](g,c)?Promise[p(541)](new Error(e[p(1097)])):(c=g,e.zOVKP(g,n[p(1410)])?Promise[p(1593)]():n[g][p(1267)](s)(t,d.bind(null,e[p(1223)](g,1))))}e[o(989)](d,0)}function gs(s){let t=r,n=0,o=0;for(let c=0;e.uXHab(c,s.length);++c)o=s[t(1710)+"At"](c),e.nFWsh(o,128)?n+=1:e.oVsip(o,2048)?n+=2:e[t(1892)](e[t(533)](64512,o),55296)&&e[t(1639)](e[t(1580)](64512,s[t(1710)+"At"](e[t(1690)](c,1))),56320)?e[t(469)](t(560),e.uSytC)?(++c,n+=4):(e.blBHW(_0x5d9fed,this[t(1151)+"lTimeoutId"]),this["_interva"+t(1438)+"Id"]=_0xcb5046(()=>{let d=t;this[d(1730)+d(476)]()},this[t(1151)+"l"])):n+=3;return n}function ps(s,t,n){let o=r;if(e[o(1053)](n,t)<1)return"";let c="";for(let d=t;e[o(1037)](d,n);){let g=s[d++];if(g<=127)c+=String[o(1809)+o(1207)](g);else if(g>=192&&e[o(1520)](g,224))c+=String[o(1809)+o(1207)](e.TkAst(e[o(1352)](31&g,6),e[o(1886)](63,s[d++])));else if(e[o(519)](g,224)&&g<240)c+=String["fromChar"+o(1207)](e.XezQd(e[o(881)](e[o(1770)](15,g),12)|e[o(1135)](e[o(456)](63,s[d++]),6),63&s[d++]));else if(e[o(1845)](g,240)){let p=e[o(885)](e[o(679)](e[o(1209)]((7&g)<<18,e[o(1064)](e[o(1343)](63,s[d++]),12)),e[o(1135)](e[o(928)](63,s[d++]),6)),e[o(495)](63,s[d++]))-65536;c+=String[o(1809)+"Code"](e[o(1379)](55296,e[o(779)](p,10))),c+=String["fromChar"+o(1207)](e[o(980)](56320,e[o(1460)](1023,p)))}}return c}function nr(s,t,n){let o=r,c={mOUbr:function(u,y){return u===y},ZNqtE:e.XUeKZ,upQBm:function(u,y){return u in y}},d=n,g,p;for(let u=0;e[o(830)](u,s[o(1410)]);++u){if(e[o(1613)](e[o(1448)],e[o(1448)]))return _0x32ee6f instanceof _0x455d59&&(HJlqFv[o(1743)](_0x2baa9f,HJlqFv.ZNqtE)||HJlqFv[o(1743)](_0x4b3764,o(975)))?!0:HJlqFv[o(636)](_0x46716d,_0x9f29cd);if(g=s[o(1710)+"At"](u),e[o(1025)](g,128))t[n++]=g;else if(e[o(1037)](g,2048)){if(e[o(1038)](e[o(618)],e[o(618)]))return e[o(1873)](_0x26ed65,_0x50fd02)?_0x5a4812:new _0xe49048(e.mbsVs(e[o(1174)](e[o(1323)](e[o(455)](_0x14b823[o(1329)](_0x49c444,0),e[o(406)](_0x2fe112.call(_0xe5c757,1),8)),e[o(578)](_0x627ff4[o(1329)](_0x5b66f8,2),16)),_0x40212e[o(1329)](_0x421300,3)<<24),0),e[o(1661)](e.sDTtL(e.DrDbj(e[o(631)](_0x5d3b30[o(1329)](_0x4410c5,4),e[o(758)](_0x3b67f8[o(1329)](_0x5853f6,5),8)),e[o(566)](_0x54f23c.call(_0x45d83a,6),16)),_0x419c41[o(1329)](_0x3ae960,7)<<24),0),!0);t[n++]=e[o(679)](e[o(549)](g,6),192),t[n++]=e[o(1770)](63,g)|128}else if(e[o(401)](64512,g)===55296&&e[o(1804)](e.isoXg(64512,p=s.charCodeAt(u+1)),56320)){let y=e[o(1482)][o(720)]("|"),v=0;for(;;){switch(y[v++]){case"0":t[n++]=e[o(1596)](e[o(693)](g,12),63)|128;continue;case"1":t[n++]=e[o(536)](e[o(1415)](63,g),128);continue;case"2":++u;continue;case"3":g=e.jjEel(65536+e[o(1468)](e[o(1248)](1023,g),10),e[o(1596)](1023,p));continue;case"4":t[n++]=e[o(714)](g>>18,240);continue;case"5":t[n++]=e[o(924)](e.QjPld(g,6),63)|128;continue}break}}else if(e[o(1766)](e[o(1657)],e[o(1657)])){if(this[o(1437)][o(1186)+"utoRecon"+o(1505)]||this[o(736)+"osed"])return;this[o(1027)+o(918)]()}else t[n++]=e[o(1656)](e[o(575)](g,12),224),t[n++]=e[o(1289)](e[o(1122)](g,6),63)|128,t[n++]=e.woaDS(e[o(1557)](63,g),128)}return n-d}async function ms(s){let t=r;if(e[t(1124)](e.UmInX,e.UmInX)){if(e[t(1060)](e[t(1255)],typeof s)){let n=new Uint8Array(e[t(1450)](gs,s));return e[t(654)](nr,s,n,0),n}return e[t(1052)](s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s[t(661)],s[t(1641)+"et"],s[t(1130)+"th"])}else return this[t(1850)+t(667)+t(1282)](_0x20ccc0),e[t(1584)](_0x27fcd9)}function i0(s){let t=r;try{return e.kHYpG(e[t(1255)],typeof s)&&(s instanceof ArrayBuffer||s[t(661)]&&e[t(1043)](s[t(661)],ArrayBuffer))||e[t(1699)](t(1409),typeof s)?"":(JSON.parse(s),e[t(1451)])}catch{return e[t(1255)]==typeof s?e[t(1844)]:""}}let o0=(s,t)=>{let n=r;switch(s){case e.qukAD:case e[n(1026)]:return{[n(1115)+s]:1,"x-tt-env":t};default:return{}}};class a0{constructor(t){let n=r;if(e[n(938)](e[n(1768)],n(600)))this[n(628)+n(1502)]=t,this[n(995)]=0;else return(this[n(1882)+"rs"][_0x2f060d]||(this._listeners[_0x201ef7]=[])).push({fn:_0x4f19a5,ctx:_0x252afd||this}),this}addCount(){let t=r;this[t(995)]++}[r(712)+"chMaxCount"](){let t=r;return e[t(1759)](this[t(995)],this[t(628)+"ount"])}[r(1682)+"nter"](t=0){let n=r;if(e[n(1577)](e[n(477)],e.poRZR))return!!(e[n(1562)](this[n(1525)+"ndex"],this[n(836)+"s"].length)||this[n(1525)+"ndex"]===this[n(836)+"s"][n(1410)]-1&&this[n(1181)+"ndpointT"+n(844)+"t"]===this[n(728)+"es"]);this[n(628)+n(1502)]=t,this[n(995)]=0}}async function x0(s){return new Promise(t=>{let n=P,o={xEKcv:n(768)+n(1879),aTHoW:function(c,d){return e[n(687)](c,d)},XkUKe:function(c,d){return e[n(1783)](c,d)},NIRdb:function(c,d){return e[n(439)](c,d)},RsxgK:function(c,d){return e[n(680)](c,d)},UJOIp:function(c,d){return e.hGDiM(c,d)}};if(!st)return t(e.nIMxJ);try{let c=document["createEl"+n(1008)](n(1022));window[n(829)+n(1836)]=d=>{let g=n;g(911)!==g(911)?(this[g(1525)+g(1615)]=0,this[g(1181)+g(1197)+g(844)+"t"]=0):(document[g(1459)][g(640)+g(926)](c),window[g(829)+g(1836)]=void 0,t(d&&d.msg||o[g(1111)]))},c[n(1188)]=e[n(775)],c[n(564)]=e[n(421)](s.replace(/^ws/,e.sxPpN),e.FDdgj);try{document.body[n(1169)+n(926)](c)}catch{document.body[n(640)+n(926)](c)}}catch{if(e.lCehN!==n(1875))window[n(829)+n(1836)]=void 0,e[n(1050)](t,e[n(1761)]);else return new _0x1c5e66(GCSkVQ[n(1157)](_0x4a7066[0]|GCSkVQ[n(632)](_0x62778c[1],8),_0x59266e[2]<<16)|GCSkVQ[n(652)](_0x490c03[3],24),GCSkVQ[n(1157)](GCSkVQ[n(1157)](GCSkVQ[n(1744)](_0x364edd[4],GCSkVQ[n(632)](_0x2358f4[5],8)),_0x2bd16e[6]<<16),GCSkVQ.UJOIp(_0x167810[7],24)),_0x137552)}})}function qe(s,t,n){let o=r;return!!s?.find(c=>c[o(764)]===t&&c[o(1843)]===n)}function it(s,t){let n=r;return s?.[n(1589)](o=>o[n(764)]===t)?.value}let rr=null;async function c0(){let s=r;if(e[s(1786)]("wLWGP",e[s(745)]))return rr||(rr=Promise[s(1593)]()[s(1407)](Se[s(1267)](Se,s(1885)))),rr;_0x16fcc8&&this._cursorManager["updateCu"+s(1281)+s(464)](_0x36edec)}class f0 extends tr{constructor(t,n){let o=r;super(),this._dbName=t,this[o(1692)]=n,this[o(1798)]=void 0,this[o(1167)+"mise"]=null}async[r(610)](){await this[r(1651)]()}async _init(){let t=r;if(!this[t(1798)]){if(this[t(1167)+"mise"])return this[t(1167)+"mise"];try{let n=this[t(385)],o=this._keyPath;this[t(1167)+t(1411)]=(async()=>{let c=t,d={ipQtn:function(p,u){return p(u)},NQIQY:function(p,u){return e[P(1750)](p,u)},OZqVf:e[c(1131)]},{openDB:g}=await e.KWHGi(c0);this[c(1798)]=await g(c(829)+"_"+n,1,{upgrade(p){let u=c;d.OZqVf!==d[u(1041)]?(d[u(1812)](_0x320fb3,this[u(407)+u(1393)+"Id"]),d[u(535)](_0x2ece98,this["_reconnectTimeou"+u(463)]),this[u(407)+"gTimeoutId"]=null,this[u(1522)+u(562)+u(463)]=null):p[u(425)+u(1062)+"e"](n,{keyPath:o})}})})(),await this[t(1167)+t(1411)]}catch(n){console[t(688)](n)}finally{this[t(1167)+"mise"]=null}}}async[r(550)](t){let n=r;try{return await this[n(1651)](),this[n(1798)]?.[n(550)](this[n(385)],t)}catch(o){console[n(688)](o)}}async[r(756)](t,n){let o=r;return await this[o(1651)](),this._qosDB?.put(this[o(385)],t)}async del(t){let n=r;try{return await this[n(1651)](),this._qosDB?.[n(991)](this._dbName,t)}catch(o){console[n(688)](o)}}async clear(){let t=r;try{return await this._init(),this[t(1798)]?.clear(this[t(385)])}catch(n){console[t(688)](n)}}async[r(1540)](){let t=r;return await this[t(1651)](),this[t(1798)]?.[t(1605)+"ys"](this[t(385)])}async[r(769)](){let t=r;return await this[t(1651)](),this._qosDB?.getAll(this[t(385)])}async[r(1342)](){let t=r;try{this[t(1798)]?.close(),this._qosDB=void 0}catch(n){console[t(688)](n)}}get isReady(){let t=r;try{if(e.zOVKP(t(1813),t(1067))){let n=_0xd9d1ed[t(1710)+"At"](_0x304e5e);e[t(1290)](n,55296)&&e.vgFka(n,56319)&&e[t(580)](e[t(1379)](_0x436961,1),_0x25b0b5)&&(n=e[t(1594)](e.Nurfc(e[t(824)](n,10),_0x2b95bc[t(1710)+"At"](++_0x525441)),56613888)),n<128?_0x56d360[_0x3c5849++]=n:(e[t(781)](n,2048)?_0x40c5ce[_0x957f38++]=e[t(466)](n,6)&31|192:(e[t(1419)](n,65536)?_0x247d7c[_0x322fdd++]=e[t(616)](e[t(1861)](e[t(723)](n,12),15),224):(_0x41bbda[_0x3e718c++]=e.RxvBZ(e[t(1073)](e[t(1122)](n,18),7),240),_0x5e0b51[_0x416d09++]=e[t(1397)](e[t(1287)](e[t(1664)](n,12),63),128)),_0x204efb[_0x3dfb27++]=e[t(1397)](e.Yyctn(n,6)&63,128)),_0x118d15[_0x360dda++]=e.iypsb(e[t(653)](63,n),128))}else return!!this._qosDB}catch(n){return console[t(688)](n),!1}}}class u0{constructor(t,n){let o=r;if(e[o(1766)](e[o(1429)],e.lkKtF)){var c=_0x455212[_0xe2e545];if(lEwhDQ.AtajX(void 0,c))return c[o(1020)];var d=_0x545d31[_0x51eb72]={exports:{}};return _0x57693c[_0x2528c4](d,d.exports,_0x4a699d),d[o(1020)]}else this[o(1456)]=t,this[o(1733)]=n,this[o(1798)]=localStorage}async[r(610)](){}get[r(1420)](){let t=r,n={wSokJ:e[t(454)],goOcL:function(o,c){return o>c},OWzJv:function(o,c,d,g){return o(c,d,g)},zhKtP:function(o,c){return e[t(869)](o,c)},IRMyT:function(o,c){return o&c},vFvMS:function(o,c){return e[t(1853)](o,c)},cTlrI:function(o,c){return e[t(840)](o,c)},gPDoQ:function(o,c){return e[t(1403)](o,c)},KFaRk:function(o,c){return e[t(580)](o,c)},cnipD:function(o,c){return e[t(1174)](o,c)},HbCPV:function(o,c){return o|c},RDOPx:function(o,c){return e[t(1403)](o,c)},IxYzC:function(o,c){return e.BAYwG(o,c)},PeMbe:function(o,c){return e[t(803)](o,c)},OITJj:function(o,c){return e[t(523)](o,c)},XQthM:function(o,c){return e[t(1042)](o,c)},kadys:function(o,c){return e[t(1162)](o,c)},yYGdG:function(o,c){return e[t(1080)](o,c)}};if(e[t(1606)]("RshQb",e[t(1645)])){let o=4294967295;return function(c,d,g=!0){let p=t,u=n[p(1587)].split("|"),y=0;for(;;){switch(u[y++]){case"0":if(n[p(905)](d+=5,c[p(1410)]))throw d=c.length,n.OWzJv(_0x5c45ea,d,10,c[p(1410)]);continue;case"1":o=n.zhKtP(o|n[p(755)](127,c[d])<<7,0);continue;case"2":o=n[p(1388)](n.cTlrI(o,n.gPDoQ(127,c[d])<<21),0);continue;case"3":if(n[p(472)](c[d++],128))return{value:g?o:n[p(422)](0,o),offset:d};continue;case"4":if(c[d++]<128)return{value:g?o:n[p(387)](0,o),offset:d};continue;case"5":o=n[p(1388)](n[p(459)](o,n[p(1592)](15,c[d])<<28),0);continue;case"6":if(n[p(1350)](c[d++],128))return{value:g?o:n[p(387)](0,o),offset:d};continue;case"7":return{value:g?o:n[p(891)](0,o),offset:d};case"8":if(n[p(1659)](c[d++],128))return{value:g?o:0|o,offset:d};continue;case"9":o=(127&c[d])>>>0;continue;case"10":if(n[p(1621)](c[d++],128))return{value:g?o:n[p(1175)](0,o),offset:d};continue;case"11":o=n[p(1388)](o|n.yYGdG(n[p(1558)](127,c[d]),14),0);continue}break}}}else return"frontier_"+this[t(1456)]}async get(t){let n=r,o=this._qosDB.getItem(this[n(1420)]);return JSON[n(1351)](e[n(832)](o,"{}"))[t]}async set(t,n){let o=r,c=this[o(1798)][o(1714)](this[o(1420)]),d=JSON[o(1351)](e[o(1380)](c,"{}"));return d[n||t[this._pathKey]]=t,this._qosDB.setItem(this[o(1420)],JSON[o(1249)+"y"](d)),n||t[this[o(1733)]]}async[r(740)](t){let n=r,o={xYvGF:function(c,d,g){return e[P(1703)](c,d,g)}};if(e[n(820)](e[n(1800)],e[n(1800)])){let c=this[n(1798)][n(1714)](this[n(1420)]),d=JSON.parse(e[n(1380)](c,"{}"));return d[t]=void 0,this._qosDB.setItem(this[n(1420)],JSON.stringify(d))}else{let c={EvjmC:function(d,g,p){return o[n(448)](d,g,p)}};return new _0x1888a4(d=>{let g=n;c[g(742)](_0x4bdcee,d,this[g(1203)+g(643)+"e"](_0x47f8bf))})}}async[r(674)](){let t=r;return this[t(1798)][t(674)]()}async[r(1540)](){let t=r,n=this[t(1798)][t(1714)](this[t(1420)]),o=JSON[t(1351)](n||"{}");return Object[t(1540)](o)}async[r(769)](){let t=r,n={yeGQX:function(o,c){return e.blBHW(o,c)},cMRgL:function(o,c){return e[P(1460)](o,c)}};if(e[t(711)]===e[t(711)]){let o=this[t(1798)][t(1714)](this[t(1420)]),c=JSON[t(1351)](o||"{}");return Object[t(718)](c)}else _0x653641=qmCwnX.yeGQX(_0x51eb19,_0x1a7b0a),_0x2dba56<32&&(_0x3e468c|=qmCwnX[t(1442)](127,_0x1a69a3)<<_0x4c6941),_0x3389df+=7}[r(1342)](){return Promise[r(1593)]()}get[r(1603)](){return!!this[r(1798)]}}class d0{constructor(t,n){let o=r;if(e[o(1827)]("UQAag",e.PPLEu))return _0x56bffa+=_0x23c52a&&_0x147665[o(1130)+"th"]||0,_0x6512f2;this._DBName=t,this[o(1733)]=n,this._qosDB=Je?tt:vt?wx:null}async openDB(){}get[r(1420)](){let t=r;return e[t(1143)](e[t(1821)],e.Ewxov)?_0x1a2319[t(1378)+t(641)][1]?void 0:_0x256bf5["objectSt"+t(569)](_0x458b42["objectSt"+t(641)][0]):t(829)+"_"+this._DBName}async[r(550)](t){let n=r,o=this._qosDB["getStora"+n(1010)](this[n(1420)]);return JSON.parse(e[n(832)](o,"{}"))[t]}async[r(756)](t,n){let o=r,c=this[o(1798)][o(945)+o(1010)](this._prefix),d=JSON[o(1351)](c||"{}");return d[n||t[this[o(1733)]]]=t,this[o(1798)]["setStora"+o(1010)](this[o(1420)],JSON[o(1249)+"y"](d)),n||t[this[o(1733)]]}async del(t){let n=r,o=this[n(1798)][n(945)+n(1010)](this[n(1420)]),c=JSON[n(1351)](e[n(832)](o,"{}"));return c[t]=void 0,this[n(1798)][n(1177)+n(1010)](this[n(1420)],JSON[n(1249)+"y"](c))}async[r(674)](){let t=r;return this._qosDB["clearSto"+t(436)]()}async[r(1540)](){let t=r;if(e[t(1610)](e[t(922)],"MKKUD"))return new _0x2c7208(e[t(841)](e[t(1284)](e[t(1856)](e.CsxWS(_0x43fa83[4],24),_0x225e63[5]<<16),_0x41091b[6]<<8),_0xff98bb[7]),e[t(803)](e[t(1837)](e[t(536)](e[t(1352)](_0x56b6e6[0],24),e[t(406)](_0x2d697[1],16)),e[t(1564)](_0x46b574[2],8)),_0x3eaa0e[3]),_0x653994);{let n=this[t(1798)][t(945)+t(1189)+"nc"](this._prefix),o=JSON[t(1351)](e[t(1384)](n,"{}"));return Object[t(1540)](o)}}async[r(769)](){let t=r,n=this._qosDB[t(945)+t(1189)+"nc"](this[t(1420)]),o=JSON.parse(e.DDagx(n,"{}"));return Object[t(718)](o)}[r(1342)](){return Promise[r(1593)]()}get[r(1603)](){return!!this._qosDB}}function ws(s,t){let n=r;if(e[n(1774)](Je,Je))return new d0(s,t);if(e.uEZCY(st,St)&&e.xgPWt("undefined",typeof indexedDB))return new f0(s,t);if(e.DDagx(st,St)&&e[n(1430)](e[n(571)],typeof localStorage))return new u0(s,t);throw new Error(n(1636)+n(1331)+"d")}class l0{constructor(){let t=r;this[t(1151)+t(1438)+"Id"]=null,this[t(1151)+"l"]=36e5,this[t(1798)]=e.bjvcG(ws,e[t(646)],e[t(409)])}async _intervalFlush(){let t=r;e[t(1363)](clearInterval,this["_interva"+t(1438)+"Id"]),this[t(1151)+t(1438)+"Id"]=setInterval(()=>{let n=t;this[n(1730)+n(476)]()},this[t(1151)+"l"])}async openDB(){let t=r;if(e.RabQv(e[t(1031)],"rzTDl"))return new _0x419a0b(_0x2327f3,{data:_0xdff350});await this[t(1798)].openDB()[t(1407)](()=>{let n=t;this[n(1151)+n(967)]()})}async[r(1730)+r(476)](){let t=r;(await this._qosDB?.[t(769)]()||[])[t(1518)](({timestamp:c})=>c<Date.now())[t(1698)](c=>{let d=t;this[d(1798)]?.[d(740)](c[d(1899)+"id"])})}async[r(740)](t){return this._qosDB?.del(t)}async[r(756)](t,n){return this._qosDB?.set({message_id:t,timestamp:n})}async get(t){return this[r(1798)]?.get(t)}async[r(1342)](){let t=r;e[t(1363)](clearInterval,this[t(1151)+t(1438)+"Id"]),await this[t(1798)]?.closeDB()}get[r(1603)](){let t=r;if(e[t(648)](t(1238),e[t(1306)]))return this._qosDB?.[t(1603)];if(!this[t(1538)])return;this[t(1722)+"WebSocket"](_0xfbdad8,_0x4c04a1,_0x7f3c29)}}function sr(s){let t=r,n=!!this[t(1437)].enableQoS;if(!n)return{enabled:n,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=e[t(835)](qe,s[t(1239)][t(572)],e[t(732)],"2"),c=o&&qe(s[t(1239)][t(572)],e[t(1515)],"1"),d=o&&e[t(1810)](qe,s[t(1239)][t(572)],e[t(1016)],"1"),g=d?e[t(1275)](it,s[t(1239)][t(572)],t(1709)+t(1224)+t(1647))?.[t(720)](",")[t(1518)](Boolean)||[]:[];return{enabled:n,isQoSMessage:o,isQoSAck:c,isAckCleanupMessage:d,ackMsgIds:g}}async function _s(){let s=r;return this[s(1083)+s(1511)]||(this[s(1083)+s(1511)]=new l0),this[s(1083)+s(1511)][s(1603)]||await this[s(1083)+s(1511)].openDB(),this["_QoSMana"+s(1511)]}async function h0(s,t){let n=r,o={yqstk:function(u,y,v){return e.vEHFN(u,y,v)},jlErm:function(u,y,v){return e[P(1717)](u,y,v)},iEyKI:n(625)},{enableAutoAck:c}=this[n(1437)],d=e.lXYPi(qe,s[n(1239)][n(572)],e[n(1797)],"1"),g=e[n(1810)](qe,s[n(1239)][n(572)],e[n(1637)],"1"),p=sr.call(this,s);if(e[n(669)](c,d))if(e[n(411)](n(1315),e[n(810)])){let u=fxQETY[n(1572)](_0x2f72d0,"error",{message:this[n(1247)+n(706)+"age"](_0x2ead42)});this.emit("error",u);let y=fxQETY.jlErm(_0x44d029,fxQETY[n(1340)],{reason:this[n(1247)+n(706)+n(1877)](_0x428431)});this.emit(n(625),y)}else{let{SeqID:u,LogID:y,service:v,LogIDNew:A,method:N}=s[n(1239)];this[n(609)]({SeqID:u,LogID:y,LogIDNew:A,service:v,method:N,headers:[{key:e[n(1637)],value:"1"},{key:e[n(1292)],value:e[n(1426)](A,"")},{key:e.htwCU,value:"0"}]})}g&&!p[n(1044)]&&this[n(1850)+n(1463)+n(1693)](s),e[n(1705)](t)}async function g0(s,t){let n=r;this[n(565)](e[n(1256)],s[n(1239)]),e[n(1387)](t)}async function p0(s,t){let n=r;if(e[n(820)](e[n(969)],e[n(969)])){let o=e[n(1356)](es,await e.NbVoO(ms,s.data));try{if(o[n(1666)]instanceof Uint8Array){let c=e[n(1685)](this[n(1437)][n(717)+n(963)],Object)?{force:!!this[n(1437)][n(717)+"ncoding"].force,encoding:this[n(1437)][n(717)+n(963)].encoding?this[n(1437)][n(717)+n(963)].encoding[n(1237)](/\s/g,"")["toLowerC"+n(1398)]():""}:{force:!1,encoding:this[n(1437)]["payloadE"+n(963)]?this._options[n(717)+"ncoding"].replace(/\s/g,"")["toLowerC"+n(1398)]():""},d=o[n(717)+n(963)]?o[n(717)+"ncoding"][n(1237)](/\s/g,"").toLowerCase():"",g=e[n(1202)](this[n(1437)][n(1394)+"ype"],Object)?{force:!!this[n(1437)][n(1394)+"ype"][n(1529)],type:this[n(1437)][n(1394)+n(1799)][n(1188)]?this._options[n(1394)+n(1799)][n(1188)][n(1237)](/\s/g,"")["toLowerC"+n(1398)]():""}:{force:!1,type:this[n(1437)][n(1394)+"ype"]?this[n(1437)][n(1394)+n(1799)].replace(/\s/g,"")[n(988)+"ase"]():""},p=o[n(1394)+"ype"]?o[n(1394)+n(1799)][n(1237)](/\s/g,"").toLowerCase():"",u=g.force?g[n(1188)]:p||g[n(1188)],y=c[n(1529)]?c[n(738)]:d||c[n(738)],v=[e[n(1844)],e.NQprF,e[n(1881)],e[n(1255)]],A=[e[n(1139)],e[n(959)]];this[n(1437)][n(1158)+n(1635)+n(1612)+"ad"]&&v[n(1855)](u)&&(!y||A[n(1855)](y))?o[n(1121)+"oad"]=e[n(1840)](ps,o[n(1666)],0,o[n(1666)][n(1130)+"th"]):o["textPayl"+n(1824)]=""}else o[n(1121)+n(1824)]=""}catch(c){o["textPayl"+n(1824)]="",console[n(688)](c)}s[n(1239)]=o,e[n(1705)](t)}else this[n(1538)]&&this._ws.send(_0x5be088),this._debug("sent",_0x3e2eef)}function m0(s,t,n){let o=r;if(e[o(805)]!=="kADpp"){let c=e[o(1492)](n,8192),d=e[o(1417)](c,1),g=null,p=c;return function(u){let y=o;if(u<1||e[y(1353)](u,d))return e[y(1039)](s,u);e[y(1021)](e[y(1257)](p,u),c)&&(g=e[y(1450)](s,c),p=0);let v=t[y(1329)](g,p,p+=u);return e[y(1176)](7,p)&&(p=e[y(798)](7|p,1)),v}}else _0x504d7c[o(1459)].appendChild(_0x246d2f)}let w0=4294967295;function _0(s,t,n){let o=r;return e[o(1205)](RangeError,e[o(702)](e[o(743)](e[o(1531)](e[o(513)]+s,e[o(923)]),e[o(1784)](t,1)),e.NUzMM)+n)}function y0(s,t,n){let o=r;if(e.gkgJq(o(854),e[o(1648)])){if(e[o(1142)](n,w0))throw new Error(e[o(933)]);let c=3;for(;e[o(1320)](c,0);)if(e[o(880)](e[o(914)],e[o(914)]))this[o(576)+o(1857)+"line"]=_0x5db04f,_0x54a748?this[o(1390)+"nLine"]():this[o(1390)+"ffLine"]();else{let d=e.dYnzR(255,n);e[o(1840)](or,d,s,e.HpUYH(t,c)),n>>>=8,c--}return e.bdSMU(t,4)}else{let c=e[o(1870)](255,_0x257d79);e.LInEG(_0x588e92,c,_0x36fd3f,e[o(1629)](_0xbd6c40,_0x523157)),_0x18d542>>>=8,_0x1d73e8--}}function b0(s,t){let n=r;if(e[n(1561)]===e[n(1561)]){let o=0,c=t,d=t+4;for(;e[n(1487)](c,d);){let{value:g,offset:p}=e[n(1262)](ir,s,c);c=p,o=e[n(979)](o<<8,0),o+=g}return{value:o,offset:d}}else{let o=this[n(1882)+"rs"][_0x15cf4];if(o)for(let c=0;c<o[n(1410)];)e[n(1231)](o[c].fn,_0x255eaa)?o[n(872)](c,1):++c}}function v0(s,t,n){let o=r,c=e[o(1707)][o(720)]("|"),d=0;for(;;){switch(c[d++]){case"0":if(s.length<40)return e[o(762)](e[o(1810)](nr,s,t,n),n);continue;case"1":if(t.write)return e[o(1690)](t[o(1296)](s,n),n);continue;case"2":if(t[o(973)+"e"])return t[o(973)+"e"](s,n)+n;continue;case"3":if(!s)return n;continue;case"4":return e[o(408)](nr(s,t,n),n)}break}}function S0(s,t){let n=r,o={yMspW:function(c,d,g){return e[P(508)](c,d,g)},gLZcg:function(c,d){return c(d)}};if(e[n(774)](n(799),e[n(1489)]))WbgijN[n(1055)](_0x78729f,_0x2f7bef,96),_0x382c83(_0x500f4b,WbgijN[n(915)](_0x4c19cd,_0x5a8c4a));else{let c=new B(e[n(687)](e[n(1058)](e[n(1023)](e[n(958)](s[e[n(1401)](t,4)],24),e[n(1064)](s[e[n(554)](t,5)],16)),e[n(1569)](s[e[n(762)](t,6)],8)),s[e[n(1379)](t,7)]),e[n(616)](e[n(714)](e[n(1218)](s[e.JEhIZ(t,0)],24),e[n(1045)](s[t+1],16))|e[n(747)](s[e[n(702)](t,2)],8),s[e[n(1789)](t,3)]),!0);return t+=8,{value:c,offset:e[n(408)](t,8)}}}function C0(s,t,n){let o=r,c=s[o(823)],d=s[o(494)];return t[n]=e[o(383)](d,24),t[n+1]=e[o(1675)](e[o(767)](d,16),255),t[e[o(474)](n,2)]=e[o(789)](e[o(776)](d,8),255),t[e[o(421)](n,3)]=e.dYnzR(255,d),t[n+4]=c>>>24,t[n+5]=e[o(1736)](e[o(638)](c,16),255),t[e[o(505)](n,6)]=e.yjMHY(c>>>8,255),t[e[o(423)](n,7)]=e[o(450)](255,c),n+=8,n}function ir(s,t){let n=r;return s[n(590)+"8"]?{value:s[n(590)+"8"](t),offset:t+1}:{value:e[n(924)](255,s[t]),offset:e[n(583)](t,1)}}function or(s,t,n){let o=r;return t[o(1015)+"t8"]?t.writeUint8(s,n):t[n]=e.ISMrh(255,s),e[o(1400)](n,1)}let E0=function(s){let t=r,n={zZsJp:function(o,c){return e[P(555)](o,c)}};if(e[t(1617)](e[t(1140)],"NyAss"))_0x185570[t(635)+t(793)](t(866)+t(1475),o=>{let c=t;_0xed4cdf(wVkZVI[c(1333)](_0x29a5b3,_0x249f7e.result),o[c(1536)+"on"],o[c(1794)+"on"],_0x20bc5f(_0x5439d2.transaction))});else return new Uint8Array(s)},A0=e[r(1872)](e[r(571)],typeof Buffer)?Buffer[r(893)+r(686)]:m0(E0,Uint8Array[r(1276)+"e"].subarray);(()=>{let s=r,t={Ieozc:function(n,o){return e[P(1299)](n,o)},wpBhq:function(n,o){return e[P(521)](n,o)},sTVGp:function(n,o){return e[P(556)](n,o)},JsSEp:function(n,o){return e[P(972)](n,o)},ChxDF:function(n,o){return e.MiSJt(n,o)},HOPas:function(n,o){return e.DhzsO(n,o)},HLYEb:function(n,o){return e.SUGdJ(n,o)},iMwMm:function(n,o){return e[P(1330)](n,o)},aEsHm:function(n,o){return e[P(440)](n,o)},ZJlZc:function(n,o){return e[P(1474)](n,o)},cxcNI:function(n,o){return n>>>o},tvjwP:function(n,o){return e[P(595)](n,o)},mFOCU:function(n,o){return n<o},Tmypk:function(n,o){return e.hdHSe(n,o)},RNMne:function(n,o,c,d){return e[P(850)](n,o,c,d)}};if(e.HKOXc===e[s(1334)])return _0x332a3e[s(705)](_0x1c837d)||(_0x292ae7=_0x826772[s(1445)+"er"](_0x3c1309)),ZPtZIv[s(1485)](j[s(940)],_0x404bf4.unsigned)&&ZPtZIv.wpBhq(ZPtZIv.sTVGp(j.high,31),1)&&ZPtZIv[s(1148)](ZPtZIv.ChxDF(_0x111717[s(494)],31),1)?!1:j[s(494)]===_0x5b9438[s(494)]&&j[s(823)]===_0x421e2f[s(823)];{let n=4294967295;return function(o,c,d=!0){let g=s;if(n=t[g(1551)](127&o[c],0),t[g(834)](o[c++],128))return{value:d?n:0|n,offset:c};if(n=t.ChxDF(t.HLYEb(n,t.iMwMm(127&o[c],7)),0),o[c++]<128)return{value:d?n:0|n,offset:c};if(n=t[g(1551)](t.HLYEb(n,t[g(1446)](127,o[c])<<14),0),t[g(834)](o[c++],128))return{value:d?n:0|n,offset:c};if(n=t[g(649)](t[g(488)](n,t[g(821)](127&o[c],21)),0),t[g(834)](o[c++],128))return{value:d?n:t[g(488)](0,n),offset:c};if(n=t[g(1702)](t[g(1517)](n,(15&o[c])<<28),0),t[g(1644)](o[c++],128))return{value:d?n:t[g(1225)](0,n),offset:c};if((c+=5)>o.length)throw c=o[g(1410)],t[g(1597)](_0,c,10,o[g(1410)]);return{value:d?n:0|n,offset:c}}}})();let D0=16,ar=32;function k0(s){let t=r,n={MAIlY:function(o,c){return e[P(1774)](o,c)}};if(e[t(1760)](e.fSzub,e[t(547)])){let o=0,c={};for(let d=0;d<s[t(1410)];d++)c[s[d].cursor_name]=e[t(438)](gs,s[d]["cursor_n"+t(1614)]),o+=14+c[s[d]["cursor_n"+t(1614)]];return[o,c]}else{let o=this._qosDB.getItem(this[t(1420)]);return _0x1eb6bd[t(1351)](ncFpUi[t(606)](o,"{}"))[_0x14240d]}}function ys(s,t,n){let o=r,c={zjIoF:e[o(1359)],khQKO:function(y,v){return e[o(1892)](y,v)},msWbs:o(1110),hIrCF:e[o(1240)],mnWQz:e.LWsme,CkyDr:function(y,v,A,N){return e[o(654)](y,v,A,N)},rFxcy:e[o(1358)],Iinwj:o(386),jebsg:function(y,v,A,N){return e[o(909)](y,v,A,N)},nPGbW:e[o(939)],vmHgu:e[o(613)]},[d,g]=e[o(1376)](k0,s),p=e[o(1724)](A0,d),u=0;return s[o(1698)](y=>{let v=o;if(c[v(1339)](c[v(863)],c.hIrCF))return _0x2bbc3f||(_0x2c14f9=_0x4b3e2a[v(1593)]()[v(1407)](_0x3b2719[v(1267)](_0x2efae2,WLJgia[v(932)]))),_0x5bb31d;console[v(688)](c[v(1776)],y,y[v(386)]),u=c.CkyDr(or,0,p,u),console.log(c[v(461)],u),u=y0(p,u,y.service||0),console[v(688)](c[v(1017)],u),u=c[v(1321)](or,g[y[v(1499)+v(1614)]],p,u),console[v(688)](c[v(1868)],u),u=c[v(1321)](v0,y["cursor_n"+v(1614)],p,u),console[v(688)](c.vmHgu,u),u=C0(B.fromNumber(y[v(1348)]||t),p,u),console[v(688)](v(1769),u)}),{frameType:ar,headers:[{key:o(601)+o(808),value:n}],payload:p}}function I0(s){let t=r,n=0,o=[];for(;n<s.byteLength;){let{offset:c}=e[t(1311)](ir,s,n);n=c;let d={cursor_name:"",cursor:0,service:0},{value:g,offset:p}=e[t(1590)](b0,s,n);d[t(386)]=g,n=p;let{value:u,offset:y}=ir(s,n);n=y,d[t(1499)+t(1614)]=ps(s,n,e[t(998)](n,u)),n+=u;let{value:v,offset:A}=S0(s,n);d.cursor=v[t(690)](),n=A,o[t(1755)](d)}return o}function P0(){let s=r;return{frameType:ar,headers:[{key:s(601)+s(808),value:s(467)+s(934)}],payload:void 0}}class T0{constructor(t,n,o){let c=r;if(e.CakjY(e[c(1425)],e[c(1716)]))this[c(1100)+"ameSpace"]=t,this["_cursorF"+c(1245)]=n,this[c(381)+"Strategy"]=o,this[c(1798)]=e[c(766)](ws,this[c(1100)+c(1374)],e[c(784)]);else{let d=this[c(1437)][c(1559)+"tInterce"+c(637)](_0x2a4f26,_0xbf58e9);this[c(1850)+c(1230)+"ent"](e[c(1182)](_0x44ac60,c(625),{code:_0xe171cd,reason:_0x707bd,wasClean:!0,willReconnect:d})),d&&this[c(593)]()}}async[r(610)](){let t=r;await this[t(1798)][t(610)]()}async getCursors(){let t=r;if(!this[t(1798)][t(1603)])return;let n=this[t(381)+t(1243)],o=await this[t(1798)][t(769)]();switch(console[t(688)](e[t(1076)],o),n){case e.ThTMd:return o&&o[t(1410)]?ys(o,0,this["_cursorF"+t(1245)]):void 0;case e.JVEhp:return;case e.JKoIH:return o&&o[t(1410)]?e[t(1749)](ys,o,0,this[t(1147)+t(1245)]):e[t(1584)](P0)}}async[r(756)](t,n,o){let c=r;return console[c(688)](e.AJZKb,t,n,o),this[c(1798)][c(756)]({cursor_name:t,cursor:n,service:o})}async[r(552)+"rs"](t){let n=r,o=I0(t);for(let c of o)console[n(688)](e[n(826)],o),await this._qosDB.set(c)}async get(t){let n=r;return(await this._qosDB[n(550)](t))?.[n(1348)]}async[r(1342)](){let t=r;await this[t(1798)][t(1342)]()}[r(410)+r(1281)+r(464)](t){let n=r;if(e[n(827)]==="ncQLS")this["_cursorF"+n(1245)]=t;else return this[n(1107)][n(1756)]}get[r(1603)](){let t=r;return this[t(1798)][t(1603)]}}let L0=e[r(1803)];async function bs(s){let t=r,n={RSEWk:function(o,c,d){return e[P(1893)](o,c,d)},eriSJ:function(o,c){return e.nmTyT(o,c)},axokr:function(o,c){return e.PovId(o,c)},hMCAZ:function(o,c){return o|c},MvUOw:function(o,c){return e[P(1128)](o,c)},ywdbw:function(o,c){return e[P(830)](o,c)},lXhMh:function(o,c){return e[P(1764)](o,c)}};if(e[t(624)]!==e[t(1601)]){if(!this._options[t(623)+"S"])return null;let{aID:o,fpID:c,messageStrategy:d}=this[t(1437)],g=s||L0;try{if(this[t(912)+t(1506)])if(e.jHlFD(e[t(1649)],t(1469)))s&&this["_cursorM"+t(1506)][t(410)+"rsorFile"+t(464)](s);else{this[t(1068)+"ngTimer"](),this["_pingPon"+t(1393)+"Id"]=n[t(1297)](_0x3c2f79,this[t(1049)][t(1267)](this),this[t(1437)][t(801)+t(1087)]);return}else this[t(912)+t(1506)]=new T0(c+"_"+o+"_"+g,g,d);return this[t(912)+t(1506)].isReady||await this[t(912)+t(1506)][t(610)](),this._cursorManager}catch{return e.hJiKY(e[t(1309)],e.QNaaH)?null:this[t(1107)].url}}else _0x2069da=_0x34481d[aWQaNs.eriSJ(_0x1d09ab+_0x2e15f3,1)],aWQaNs[t(744)](192,_0x32ce7c)!==128?_0x272883+=_0x4a2a03:(_0x39b2e5=aWQaNs[t(1413)](aWQaNs[t(1600)](aWQaNs.axokr(31,_0x55ba13),6),aWQaNs[t(744)](63,_0x50c894)),aWQaNs.ywdbw(_0x322582,128)?_0x30c056+=_0x1cc9da:(_0x18eef6+=aWQaNs[t(1101)](_0x118070,_0x23395e),_0x98e56b++))}async function N0(s,t){let n=r,o={dLdrD:function(D,O){return D===O},GHMnx:function(D,O){return D<O}},c=e[n(416)](qe,s[n(1239)][n(572)],e.UsuPc,"-1"),d=e[n(1264)](qe,s[n(1239)].headers,e[n(1637)],"1"),g=it(s.message[n(572)],n(1709)+"er_msgid"),p=e.QVLVM(Number,e[n(1244)](it,s.message[n(572)],e[n(811)]))||0,u=sr.call(this,s),y=qe(s.message[n(572)],e[n(1490)],"2"),v=e.ewaav(it,s[n(1239)][n(572)],e[n(493)]),A=e.rPOKN(Number,e[n(538)](it,s.message[n(572)],n(1667)+n(1542)+"ue"));if(u.isQoSAck)return e.lrnwy(t);let N=u[n(1757)+n(701)]?await _s[n(1329)](this):null;if(s[n(1239)].service>0&&d&&!c||e[n(1353)](s.message[n(386)],0))if(n(731)!==e[n(605)]){if(g&&u[n(1757)+n(701)]&&N)return!!!await N.get(g)&&(e.HnzVK!==e[n(435)]?(this[n(1188)]=_0x272fa4,this[n(664)]=null):(this[n(1850)+n(667)+n(1282)](s),await N[n(756)](g,e[n(796)](Date[n(1266)](),p)))),t();if(y){let D=await bs[n(1329)](this);if(!D)return this[n(1850)+n(667)+n(1282)](s),e[n(512)](t);let O=await D[n(550)](v)??-1;if(e[n(982)](O,A))this["_dispatchMessage"+n(1282)](s),D[n(756)](v,A,s[n(1239)][n(386)]);else throw new Error(n(1477)+n(501)+" cursor "+A+(n(1086)+n(1089)+"al cursor ")+O);return t()}return this[n(1850)+n(667)+n(1282)](s),e[n(1349)](t)}else{if(_0x942f0===void 0)this[n(1882)+"rs"]={};else if(LjCCrH[n(531)](void 0,_0x224acc))this[n(1882)+"rs"][_0x1c9d80]=null;else{let D=this[n(1882)+"rs"][_0x3c5da1];if(D)for(let O=0;LjCCrH[n(482)](O,D[n(1410)]);)LjCCrH.dLdrD(D[O].fn,_0x554ccc)?D[n(872)](O,1):++O}return this}}async function R0(s,t){let n=r,o=sr[n(1329)](this,s);if(!o.isQoSMessage)return e[n(1705)](t);let c=await _s.call(this);if(o[n(1547)+n(1360)+"age"]&&o[n(1481)+"s"][n(1410)])for(let d of o[n(1481)+"s"])await c[n(740)](d);e.JDOYn(t)}async function O0(s,t){let n=r,o={fpFTb:e[n(1878)]},c=s[n(1239)].frameType===D0,d=e[n(1354)](s[n(1239)][n(1762)+"e"],ar);if(e[n(669)](!c,!d))return t();let g=e[n(1314)](it,s[n(1239)][n(572)],"cursor_f"+n(808));if(!g)return e.rYVhd(t);let p=await bs[n(1329)](this,g);if(!p)return e[n(512)](t);if(c){let u=await p[n(1421)+"rs"](),y={frameType:u?.["frameType"],SeqID:B[n(1445)+"er"](this._seqId++),LogID:B[n(1445)+"er"](this[n(1437)][n(1723)+n(1081)]()),service:9e3,method:5,headers:u?.[n(572)],payload:u?.[n(1666)]},v=e.edpWL(C,y);this[n(1538)]&&this._ws[n(960)+"te"]&&this._ws[n(475)](v)}if(d)if(e[n(481)](n(859),e.XVzjZ))!_0x531279.persisted&&(this._isBrowser&&_0x1dc5aa[n(447)+n(502)+"ner"](n(1495),this[n(592)+"ageHide"]),this._isBrowser&&_0x354062["removeEv"+n(502)+"ner"]("pageshow",this[n(592)+"ageShow"]),this.close()),this._isBrowser&&_0x440a19[n(447)+n(502)+"ner"](n(1265),this[n(1390)+n(659)]),this[n(1161)+"er"]&&_0x22b2b4[n(447)+"entListe"+n(1163)](o[n(1735)],this[n(1390)+n(1099)]);else{let u=s.message.payload;u&&p[n(552)+"rs"](u)}}let B0=async function(s,t){let n=r;this[n(543)]=!1,e[n(1552)](clearTimeout,this[n(593)+n(597)+"utId"]),t()},z0=async function(s,t){let n=r;if(!this[n(1538)]||e.awlhK(this[n(1538)][n(960)+"te"],this[n(1523)]))return e[n(1349)](t);let{pingInterval:o}=this[n(1437)];this["_endpoin"+n(1546)]?.[n(394)+"pointCon"+n(557)]();for(let d=0;e[n(992)](d,this[n(381)+"Queue"][n(1410)]);d++){let g=this["_message"+n(763)][d];if(e[n(921)](this._ws[n(960)+"te"],this[n(1523)])&&e[n(1002)](null,g))this[n(1538)]&&this._ws[n(475)](g),this[n(381)+n(763)][d]=null;else break}this[n(381)+n(763)]=this["_message"+n(763)][n(1518)](d=>!!d),this["_pingPon"+n(1393)+"Id"]=setTimeout(()=>this._ping(),o),this[n(1850)+n(1543)+"nt"](s),this._isBrowser&&this[n(1538)]&&(this[n(1538)][n(1781)+"pe"]=this[n(1767)+n(1799)]);let c=this[n(577)+n(1546)]?.[n(504)+"ntEndpoint"]();this[n(565)](n(1273)+c+n(1830)),e[n(1095)](t)},M0=async function(s,t){let n=r,o=this[n(577)+"tManager"]?.["getCurre"+n(396)+"nt"]();this[n(565)](n(1273)+o),e[n(1313)](t)};class q0 extends tr{constructor(t){let n=r,o={ZizVv:function(p,u,y,v){return p(u,y,v)},ChVxA:"wXBEN",GBJXK:function(p,u,y){return e[P(508)](p,u,y)},UEJDW:e[n(1772)],xLfoZ:n(997)+"2",Ysxxm:function(p,u){return e[n(1300)](p,u)},KjcKx:e[n(571)],gZFkp:function(p,u){return e.mNJIA(p,u)},JSnny:e[n(759)],veeNd:function(p,u){return e[n(935)](p,u)},XYCdA:e.AKStJ,KWbLe:e[n(698)],AGCcF:function(p,u,y){return e[n(1590)](p,u,y)},fcQic:e[n(1439)]};super(),this["_miniNav"+n(1857)+n(579)]=!0,this[n(1161)+"er"]=st,this[n(1184)]=t0,this[n(908)+"T"]=Je,this[n(993)+"X"]=vt,this[n(1433)+"r"]=St,this[n(381)+n(763)]=[],this[n(577)+"tManager"]=null,this[n(736)+n(750)]=!1,this[n(1767)+n(1799)]=e.eZWDN,this[n(593)+"Lock"]=!1,this[n(593)+n(597)+n(509)]=null,this[n(1522)+n(562)+n(463)]=null,this["_pingPon"+n(1393)+"Id"]=null,this[n(800)]=0,this[n(543)]=!1,this[n(1752)]="",this[n(1083)+"ger"]=null,this[n(912)+"anager"]=null,this[n(696)+"sCounter"]=null,this[n(1155)+"ls"]=e.OlSWN,this.CLOSED=3,this[n(1674)+"NG"]=0,this[n(1523)]=1,this[n(697)]=2,this._onOpen=p=>{let u=n,y={TWKvH:u(873)};try{o[u(1280)](hs,this,p,[B0,z0,M0])}catch(v){if(o[u(1291)]!==o.ChVxA)this[u(1303)](y.TWKvH,_0x318dfa),this[u(449)+u(1526)]&&this[u(449)+u(1526)](_0x354bc8);else{let A=o[u(1679)](ce,o[u(1665)],{message:v[u(1239)],code:Me[u(642)+"OR"],error:v});this[u(1850)+u(1510)+u(444)](A)}}},this[n(1634)+"ge"]=async p=>{let u=n,y={mZAVZ:o[u(1887)],cMPzk:function(N,D){return N||D},XNuoc:function(N,D){return o[u(427)](N,D)},TMVKG:o[u(1516)]},{pingInterval:v,pingFrequency:A}=this[u(1437)];if((o[u(1848)]("hi",p[u(1375)])&&o[u(1405)]===A||o[u(417)](o[u(607)],A))&&(this["_clearPi"+u(1494)](),this[u(1303)](o[u(1261)],u(831)),this[u(407)+u(1393)+"Id"]=o[u(1701)](setTimeout,this._ping[u(1267)](this),v)),p[u(1375)]!=="hi")try{if(o.veeNd(u(1389),o.fcQic)){let N=y[u(1896)].split("|"),D=0;for(;;){switch(N[D++]){case"0":if(_0x351629)return!0;continue;case"1":if(dpzfCZ[u(1271)](_0x1f224d,_0x472d6f)&&dpzfCZ[u(1201)](dpzfCZ[u(1104)],typeof _0x5bb1df)&&_0x487f76)return!0;continue;case"2":return!1;case"3":if(_0x4e07cc&&_0x5af0b2[u(1018)+"ocket"])return!0;continue;case"4":if(_0x32aaa4&&_0x182ce0.connectSocket)return!0;continue}break}}else hs(this,p,[p0,h0,R0,O0,N0,g0])}catch(N){let D=o[u(1679)](ce,o[u(1665)],{message:N[u(1239)],code:Me[u(953)+"ERROR"],error:N});this[u(1850)+"hErrorEv"+u(444)](D)}},this[n(1672)]=p=>{let u=n,y=this[u(577)+u(1546)]?.[u(712)+"chMaxTries"](),v=this[u(577)+u(1546)]?.[u(504)+u(396)+"nt"]();if(y&&!p.message){let A="connect "+v+(u(896)+u(771)+u(1725)+"ed");this[u(1850)+u(1510)+u(444)](ce(o[u(1665)],{message:A,code:Me[u(951)+"IES_ERROR"],error:p}));return}this._ws&&o[u(1848)](this[u(1538)][u(960)+"te"],this.OPEN)&&this[u(1500)+u(434)](),this[u(1850)+u(1510)+u(444)](ce(o[u(1665)],{message:p[u(1239)],code:Me[u(1325)+u(1479)],error:p}))},this[n(1833)]=async p=>{let u=n;this[u(1254)+"mer"](),this[u(1068)+u(1494)](),this[u(689)+"sListeners"](),this[u(1538)]=null,this[u(593)+"Lock"]=!1;let y=this[u(577)+"tManager"]?.[u(712)+u(1581)+"es"]();if(!y&&this[u(1454)+"orOnline"]()&&!this[u(736)+u(750)]){let v=this[u(577)+u(1546)]?.[u(504)+u(396)+"nt"](),A=this[u(1437)][u(1559)+u(500)+u(637)](p[u(402)],p[u(1879)]);this[u(1850)+u(1230)+u(444)](e[u(1869)](he,e.WyKfN,{code:1006,reason:p.reason||u(794)+u(1014)+u(1123)+"wn reaso"+u(868)+u(437)+v,willReconnect:A})),A&&this[u(593)]();return}if(e[u(670)](1e3,p[u(402)])&&this[u(736)+"osed"]){this[u(1850)+"hCloseEvent"](e[u(1e3)](he,e[u(1032)],{code:1e3,reason:e.NvRGG})),this[u(577)+u(1546)]?.[u(394)+u(1711)+u(557)](),this[u(696)+u(1117)]?.[u(1682)+u(491)]();return}if(e[u(1038)](1e3,p[u(402)])&&y)if(e[u(1827)](e[u(1286)],e[u(888)]))_0x3c13cf(_0x5f35a8,82),OqPYKz[u(1701)](_0x94ef49,_0x1ff08d,_0x1ac51c);else{let v=this[u(577)+"tManager"]?.[u(504)+u(396)+"nt"](),A=p[u(1879)];A||(A=await e[u(1871)](x0,this._url)),A=u(794)+u(1014)+u(1771)+A+(u(619)+u(812))+v+(", max re"+u(1880)+u(1408)),this[u(1850)+u(1230)+u(444)](e[u(1859)](he,u(625),{code:p[u(402)],reason:A}));let N="connect "+v+(" fail, max retri"+u(1725)+"ed");this[u(1850)+u(1510)+u(444)](ce(u(1227),{message:N,code:Me[u(951)+"IES_ERROR"]})),this["_endpoin"+u(1546)]?.["resetEnd"+u(1711)+u(557)](),this[u(696)+u(1117)]?.[u(1682)+u(491)]();return}if(e[u(1154)](1e3,p[u(402)])&&!p[u(1879)]){let v=this[u(577)+u(1546)]?.["getCurre"+u(396)+"nt"]();this[u(1850)+u(1230)+"ent"](he("close",{code:p[u(402)],reason:"connecting faile"+u(1123)+"wn reaso"+u(868)+u(437)+v})),this._endpointManager?.["resetEnd"+u(1711)+u(557)](),this[u(696)+u(1117)]?.[u(1682)+u(491)]();return}this[u(1850)+u(1230)+u(444)](p),this[u(577)+u(1546)]?.[u(394)+"pointCon"+u(557)](),this["_pingLos"+u(1117)]?.resetCounter()},this[n(589)]=null,this[n(658)]=null,this[n(517)+"e"]=null,this[n(1680)]=null,this[n(1134)+n(918)]=null,this[n(449)+n(1526)]=null,this[n(1431)+"mediatel"+n(1327)+"ct"]=null,this["_handleO"+n(659)]=this[n(1390)+n(659)][n(1267)](this),this[n(1390)+n(1099)]=this[n(1390)+"ffLine"][n(1267)](this),this[n(592)+n(937)]=this[n(592)+"ageHide"].bind(this),this["_handleP"+n(1484)]=this[n(592)+n(1484)][n(1267)](this),this[n(1437)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[n(1345)](1,0),service:0,logIDGenerator:x,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[n(1628)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[n(1668)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:c,ws:d}=t,g=Array.isArray(c)?c:e[n(1627)](e.kEUof,typeof c)?[c]:[];if(!g||e.fNduq(0,g[n(1410)]))throw new Error(e[n(817)]);if(!e[n(1626)](s0,d))throw new Error(e.ecjwC);Object[n(968)](this._options,t),this[n(577)+n(1546)]=new ls(g,this[n(1437)][n(728)+"es"]),this[n(696)+n(1117)]=new a0(this[n(1437)][n(645)+n(1888)]),this[n(1437)][n(1793)+n(887)]&&(this._isInit=!0,this[n(593)]()),this[n(1437)]["listenNetworkCha"+n(426)]&&(this[n(908)+"T"]||this[n(993)+"X"]?this["_onPageN"+n(791)+n(548)]():this[n(1161)+"er"]&&this._initGlobalEventListener())}[r(1390)+r(659)](){let t=r;this._options["disableA"+t(1090)+"nect"]||this[t(736)+t(750)]||this[t(1027)+t(918)]()}[r(1390)+r(1099)](){let t=r;this[t(1722)+t(737)+"t"]();let n=e[t(1082)](er,e.iFNUV,{message:t(1611)+t(1198)+" reconnect"});this[t(1431)+"mediatelyReconnect"]&&this[t(1431)+t(1035)+t(1327)+"ct"](n)}[r(1395)+r(1108)+r(793)](){let t=r;this[t(1161)+"er"]&&window["addEvent"+t(793)](e[t(1780)],this[t(1390)+t(659)]),this[t(1161)+"er"]&&window[t(635)+t(793)](e[t(1878)],this[t(1390)+t(1099)]),this[t(1161)+"er"]&&window["addEvent"+t(793)](e[t(1105)],this["_handleP"+t(937)]),this._isBrowser&&window[t(635)+t(793)](e[t(813)],this["_handleP"+t(1484)])}["_dropGlo"+r(1108)+"Listener"](){let t=r;this._isBrowser&&window[t(447)+"entListe"+t(1163)](e[t(1780)],this[t(1390)+"nLine"]),this._isBrowser&&window[t(447)+t(502)+t(1163)](t(1070),this[t(1390)+t(1099)]),this[t(1161)+"er"]&&window["removeEv"+t(502)+t(1163)](e[t(1105)],this[t(592)+t(937)]),this[t(1161)+"er"]&&window["removeEv"+t(502)+t(1163)](e.KVrMU,this[t(592)+t(1484)])}["_handleP"+r(937)](t){let n=r;!t[n(981)+"d"]&&(this[n(1161)+"er"]&&window[n(447)+n(502)+n(1163)](e[n(1105)],this[n(592)+n(937)]),this[n(1161)+"er"]&&window[n(447)+n(502)+"ner"](e.KVrMU,this[n(592)+n(1484)]),this.close()),this._isBrowser&&window["removeEv"+n(502)+"ner"](n(1265),this[n(1390)+n(659)]),this[n(1161)+"er"]&&window[n(447)+n(502)+n(1163)](e[n(1878)],this[n(1390)+n(1099)])}[r(592)+"ageShow"](t){let n=r;t.persisted&&(this[n(1454)+n(1586)]()&&(!this[n(1538)]||e[n(1402)](this[n(1538)][n(960)+"te"],this.OPEN)||e[n(1187)](this._ws[n(960)+"te"],this[n(1674)+"NG"]))&&this[n(1390)+n(659)](),this[n(1161)+"er"]&&window[n(635)+n(793)](e[n(1780)],this[n(1390)+"nLine"]),this[n(1161)+"er"]&&window[n(635)+n(793)](e[n(1878)],this[n(1390)+n(1099)]))}async[r(1591)+r(1598)](t){let n=r,o={BSQXo:function(Et,At,K0){return e.VVhTi(Et,At,K0)}},{fpID:c,deviceID:d,bddID:g,ttwID:p,accessKey:u,aID:y,customParams:v={},enableAutoAck:A,enableQoS:N,QoSLevel:D,env:O}=this[n(1437)],ke,$,se;this[n(1161)+"er"]||this[n(993)+"X"]||this[n(908)+"T"]?(ke=location&&e.AJAOh(e[n(977)],location.protocol)?e[n(1763)]:e[n(405)],$=t[n(1237)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),se=/^wss(.*:\/\/)/[n(927)](t)?t:""+ke+$):e.YiDYk!==e[n(749)]?(ke=e.vZqaP,$=t[n(1237)](/(^http)((?:[s]*:\/\/))/,""),se=/(^ws)((?:[s]*:\/\/))/[n(927)]($)?$:""+ke+$):(this[n(1100)+n(1374)]=_0x37ad92,this[n(1147)+n(1245)]=_0xa9d3f4,this[n(381)+"Strategy"]=_0x1a9d3e,this._qosDB=OakMRT[n(1357)](_0x2e6bc4,this[n(1100)+n(1374)],"cursor_name"));let ot=g?"bd_did":p?e[n(1146)]:n(1312)+"d",Ct=g||p||d;if(!Ct||!ot)throw new Error(e.joKeX);let xr=e[n(1548)](e[n(1033)],typeof v)?await e.lrnwy(v):v,U0=O?e.rABbc(o0,O.xUseEnv,O.xTTEnv):{},cr=Object.assign({device_platform:e.nSzTm,version_code:e[n(1842)],access_key:u,fpid:c,aid:y,[ot]:Ct,xsack:A?1:0,xaack:A?1:0,xsqos:N?1:0,qos_level:N?D:void 0,qos_sdk_version:2,...U0},xr),F0=Object.keys(cr)[n(1377)]((Et,At)=>cr[At]!==void 0?""+Et+(Et?"&":"?")+At+"="+cr[At]:Et,"");return se+"/ws/v2"+F0}async[r(593)](){let t=r;if(!(this[t(593)+"Lock"]||this._readyClosed)){this["_connect"+t(1655)]=!0;try{let n=this[t(577)+"tManager"]?.["checkCur"+t(1210)+t(1604)+t(1549)+t(985)](),{timeoutInterval:o}=this[t(1437)];if(n){let d=this[t(577)+t(1546)]?.[t(504)+t(396)+"nt"](),g=this["_endpoin"+t(1546)]?.[t(825)+t(875)+"pointAndUpdateCo"+t(492)](),p=this[t(577)+t(1546)]?.["getCurre"+t(396)+t(1847)+"ount"]();if(g){let u=t(1138)+d+(t(876)+", max retries reached, will use "+t(529)+t(1508))+g+" to retry",y=e[t(847)](ce,e[t(1772)],{message:u,code:Me[t(951)+t(1537)+"R"]});this[t(565)](u),this[t(1850)+t(1510)+"ent"](y),this._url=await this[t(1591)+t(1598)](g),this[t(565)](t(1138)+g+" "+p+t(1246)),this[t(689)+t(1807)+"rs"]()}else{let u="connect "+d+(" timeout"+t(1226)+t(1880)+t(1408));this[t(565)](u),this[t(1850)+t(1510)+t(444)](ce(e[t(1772)],{message:u,code:Me["MAX_RETR"+t(1537)+"R"]}));return}}else{let d=this[t(577)+t(1546)]?.[t(504)+t(396)+t(1829)+t(770)](),g=this[t(577)+t(1546)]?.["getCurre"+t(396)+t(1847)+t(1502)]();this._url=await this[t(1591)+"eUrl"](e[t(832)](d,"")),this[t(565)](t(1138)+d+" "+g+" times"),this[t(689)+t(1807)+"rs"]()}if(this[t(543)])this[t(543)]=!1;else if(e[t(856)]!==t(1817)){let d=_0x82d7bf[t(1239)][t(1666)];d&&_0x4348f0[t(552)+"rs"](d)}else{let d=e[t(634)](er,e[t(952)],{message:t(715)});this[t(1134)+"econnect"]&&this[t(1134)+t(918)](d)}let c=this[t(577)+"tManager"]?.[t(504)+t(396)+"ntTriesC"+t(1502)]()||0;e.sJXnn(c,1)&&await this[t(1336)](c-1),this[t(565)](t(794)+"ng url: "+this[t(1752)]+(t(703)+t(851))+this[t(1155)+"ls"]),this._ws=e[t(1262)](r0,{url:this[t(1752)],protocols:[this[t(1155)+"ls"]],headers:this._options[t(878)+t(1741)+"s"][t(1491)+t(874)]},this[t(1437)].ws),(this._isBrowser||this[t(1433)+"r"])&&this[t(1538)]&&(this[t(1538)][t(1781)+"pe"]=this[t(1767)+"ype"]),this[t(468)+"steners"](),this[t(593)+t(597)+"utId"]=setTimeout(this[t(1171)+"ut"][t(1267)](this),o)}catch(n){throw this[t(593)+"Lock"]=!1,n}}}[r(1254)+r(503)](){let t=r;e.vfkju(clearTimeout,this["_connect"+t(597)+t(509)]),this["_connect"+t(597)+t(509)]=null}[r(1068)+r(1494)](){let t=r;clearTimeout(this[t(407)+t(1393)+"Id"]),clearTimeout(this[t(1522)+t(562)+"tId"]),this[t(407)+"gTimeoutId"]=null,this[t(1522)+"ctTimeoutId"]=null}[r(565)](...t){let n=r;this[n(1437)][n(961)]&&console[n(688)][n(1137)](console,[e[n(1193)],...t])}[r(1203)+r(643)+"e"](t){let n=r,{initReconnectInterval:o,maxReconnectInterval:c,reconnectIntervalGrowFactor:d}=this[n(1437)],g=e[n(1283)](o,Math[n(585)](d,e[n(1565)](t,1)));return g>c?c:g}[r(1049)](){let t=r;if(e[t(1124)](t(1470),t(379)))return!!this._qosDB;if(this[t(1538)]&&e[t(871)](this[t(1538)].readyState,this[t(1674)+"NG"])){this._clearPingTimer(),this[t(407)+"gTimeoutId"]=e[t(1708)](setTimeout,this._ping[t(1267)](this),this[t(1437)][t(801)+t(1087)]);return}if(!this[t(1538)]||e.LABtw(this._ws[t(960)+"te"],this[t(1523)]))return void this[t(1027)+t(918)]();this[t(1538)]&&this[t(1538)][t(475)]("hi"),this[t(1522)+"ctTimeou"+t(463)]=e[t(1788)](setTimeout,this[t(1027)+t(918)+t(778)][t(1267)](this),this[t(1437)][t(1480)+"outInterval"])}[r(1027)+r(918)+"Timeout"](){let t=r;this[t(696)+t(1117)]?.[t(462)](),this.emit(e[t(1396)],t(867)),this[t(696)+t(1117)]?.["checkRea"+t(675)+"nt"]()?this[t(1027)+t(918)]():this[t(1049)]()}[r(1454)+r(1586)](){let t=r;return this[t(908)+"T"]||this._isMiniWX?this._miniNavigatorOnline:(this[t(1161)+"er"]||this[t(1433)+"r"])&&this[t(1437)][t(1825)+"tworkCha"+t(426)]?navigator[t(1034)]:!0}[r(1027)+"econnect"](){let t=r;!this[t(1454)+t(1586)]()||this[t(736)+"osed"]||(this[t(577)+t(1546)]?.["resetEnd"+t(1711)+"fig"](),this[t(696)+t(1117)]?.["resetCou"+t(491)](),this[t(1538)]?this[t(1500)+"ect"](1001,e[t(432)],!0):this[t(593)]())}[r(1133)+r(791)+r(548)](){let t=r;this._isMiniTT?tt[t(1075)+t(1422)+"hange"](({isConnected:n})=>{let o=t;this["_miniNavigatorOn"+o(579)]=n,n?this[o(1390)+o(659)]():this[o(1390)+"ffLine"]()}):this[t(993)+"X"]&&wx[t(1075)+t(1422)+t(883)](({isConnected:n})=>{let o=t;this[o(576)+o(1857)+o(579)]=n,n?this[o(1390)+o(659)]():this[o(1390)+"ffLine"]()})}[r(1336)](t){let n=r,o={tpcki:function(c,d){return e[P(1496)](c,d)},hbkNO:function(c,d,g){return e.xXZzL(c,d,g)},uFzbY:function(c,d){return e[P(1778)](c,d)},NHHWK:function(c,d,g){return e[P(1074)](c,d,g)},mompD:function(c,d,g){return e[P(1e3)](c,d,g)}};if(e[n(972)](e[n(451)],e[n(451)]))return new Promise(c=>{let d=n;setTimeout(c,this[d(1203)+d(643)+"e"](t))});{let c=_0x206247.key;KhJXio.tpcki(void 0,c)&&(_0x476e8a(_0x2688b5,10),KhJXio[n(1727)](_0x1e6db6,_0x6ac497,c));let d=_0x102738.value;KhJXio[n(1734)](void 0,d)&&(KhJXio[n(1696)](_0x51494d,_0x570f49,18),KhJXio[n(1816)](_0x20fd48,_0x2761ee,d))}}_disconnect(t=1e3,n="",o=!1){this[r(1538)]&&this._destroyWebSocket(t,n,o)}[r(1171)+"ut"](){let t=r,n=this[t(577)+t(1546)]?.[t(504)+t(396)+"nt"]();this[t(565)](t(1138)+n+t(876)),this[t(1500)+t(434)](1001,e.zLIIT,!0)}_sendAck(t){let n=r,o=e[n(1578)](Qn,t);this._ws&&e[n(1873)](this[n(1538)][n(960)+"te"],this[n(1523)])&&(this[n(1538)]&&this[n(1538)][n(475)](o),this._debug(e[n(845)],t))}[r(689)+r(1807)+"rs"](){let t=r;this[t(1538)]&&(this._ws[t(447)+t(502)+t(1163)](e[t(1704)],this[t(1392)]),this[t(1538)]["removeEv"+t(502)+t(1163)](e[t(1032)],this._onClose),this[t(1538)][t(447)+"entListe"+t(1163)](e.Olvyz,this[t(1634)+"ge"]),this[t(1538)][t(447)+t(502)+t(1163)](e[t(1772)],this[t(1672)]))}[r(468)+r(889)](){let t=r,n={aVgsK:function(o,c){return o(c)},EFlju:function(o,c){return e.CAwYd(o,c)},jKTfu:function(o,c){return e.jjEel(o,c)},NCuzY:function(o,c){return o+c},aKwKu:function(o,c){return e.DDCVa(o,c)},gMLUh:e[t(513)],YuHgt:e[t(923)],VyOmx:function(o,c){return e[t(955)](o,c)},BfOyb:e[t(729)]};if(e[t(458)](e[t(1662)],e[t(1662)]))return nHwgFT[t(704)](_0x1e7d80,nHwgFT.EFlju(nHwgFT[t(1298)](nHwgFT.NCuzY(nHwgFT.aKwKu(nHwgFT[t(1066)],_0x370139),nHwgFT[t(442)]),nHwgFT[t(483)](_0x47d0b7,1)),nHwgFT[t(443)])+_0x15e92d);if(!this._ws)return;this._ws[t(635)+t(793)](e[t(1704)],this[t(1392)]),this[t(1538)]["addEvent"+t(793)](e[t(1032)],this[t(1833)]),this._ws[t(635)+"Listener"](t(1239),this[t(1634)+"ge"]),this[t(1538)][t(635)+t(793)](e[t(1772)],this[t(1672)])}[r(1684)+r(525)](t=1e3,n=""){let o=r;if(e[o(648)](e[o(816)],e.elXDL))this[o(628)+"ount"]=_0x2b605e,this[o(995)]=0;else try{this[o(1538)]&&this[o(1538)][o(625)](t,n)}catch{}}[r(1722)+r(737)+"t"](t=1e3,n="",o=!1){let c=r,d={rADRg:function(g,p,u){return e.AcBzz(g,p,u)},uZSQj:function(g){return g()},AVcNy:function(g,p,u){return e.iqojk(g,p,u)},wWIom:function(g,p,u){return g(p,u)}};if(this._clearPingTimer(),this["_clearTi"+c(503)](),this[c(689)+"sListeners"](),this[c(1684)+c(525)](1e3,n),this[c(593)+"Lock"]=!1,o&&this[c(1454)+"orOnline"]()&&!this[c(736)+c(750)]){if(this[c(577)+"tManager"]?.[c(712)+c(1581)+"es"]()){let p=this[c(577)+c(1546)]?.[c(504)+"ntEndpoint"]();this["_dispatc"+c(1230)+c(444)](e[c(542)](he,e.WyKfN,{code:1006,reason:c(1138)+p+(c(876)+c(1226)+c(1880)+c(1408)),wasClean:!0}))}else if(e[c(393)](c(1835),e[c(1852)])){let p=this._options[c(1559)+c(500)+"ptor"](t,n);this[c(1850)+"hCloseEv"+c(444)](e[c(1311)](he,e.WyKfN,{code:t,reason:n,wasClean:!0,willReconnect:p})),p&&this._connect()}else{DCbbWi[c(1689)](_0x2ea0e2,_0xd8cbd7,42);let p=DCbbWi[c(751)](_0xc71a2a);DCbbWi[c(602)](_0x361429,_0x4f7d21,p),DCbbWi[c(1689)](_0x27a3cd,_0x14dc05,p[c(1478)]),DCbbWi[c(1412)](_0x58d1d2,_0x42d33f,p),_0x215b2e(p)}return}this._navigatorOnline()||this[c(736)+c(750)]?this[c(1850)+c(1230)+c(444)](he(e.WyKfN,{code:t,reason:e[c(1498)]})):this[c(1850)+c(1230)+c(444)](he(e[c(1032)],{code:1006,reason:e.LBxsn})),this[c(1538)]=null,this[c(577)+c(1546)]?.[c(394)+"pointConfig"](),this[c(696)+c(1117)]?.[c(1682)+c(491)]()}["_dispatc"+r(1543)+"nt"](t){let n=r;this[n(1303)](e[n(1704)],t),this.onopen&&this[n(1680)](t)}[r(1850)+r(667)+r(1282)](t){let n=r;this[n(1303)](e.Olvyz,t),this[n(517)+"e"]&&this[n(517)+"e"](t)}[r(1850)+r(1463)+r(1693)](t){let n=r;this[n(1303)](e[n(1233)],t),this[n(449)+n(1526)]&&this["onReceiv"+n(1526)](t)}[r(1850)+r(1510)+r(444)](t){let n=r;this[n(1303)](e[n(1772)],t),this[n(658)]&&this[n(658)](t)}["_dispatc"+r(1230)+r(444)](t){let n=r;this[n(1303)](e[n(1032)],t),this[n(589)]&&this[n(589)](t)}get[r(1781)+"pe"](){let t=r;return this[t(1538)]?this[t(1538)][t(1781)+"pe"]:this[t(1767)+t(1799)]}set[r(1781)+"pe"](t){let n=r;this._binaryType=t,this[n(1538)]&&(this[n(1538)][n(1781)+"pe"]=t)}get retryCount(){let t=r;return this["_endpoin"+t(1546)]?.[t(504)+t(396)+t(1847)+t(1502)]()||0}get[r(804)+r(545)](){let t=r;return e.riZuh(e[t(1455)],e.wQxDi)?this[t(381)+t(763)][t(1377)]((o,c)=>(o+=c&&c[t(1130)+"th"]||0,o),0)+(this._ws?this[t(1538)][t(804)+t(545)]:0):this[t(1798)][t(674)]()}get[r(1884)+"ns"](){let t=r;return this[t(1538)]?this[t(1538)].extensions:""}get[r(1756)](){let t=r;if(e[t(1617)](t(1136),e[t(603)]))return this[t(1538)]?this._ws[t(1756)]:"";_0x2710b7[_0x537c7d++]=e[t(1343)](e.fOwFZ(_0x253240,18),7)|240,_0x42d24c[_0x300347++]=e.vGoda(_0x137475,12)&63|128}get[r(960)+"te"](){let t=r;return this[t(1538)]?this._ws[t(960)+"te"]:this[t(1437)][t(1793)+t(887)]?this.CONNECTING:this[t(1669)]}get[r(1332)](){let t=r;return this._ws?this._ws[t(1332)]:this[t(1752)]}close(t=1e3,n){let o=r;if(this[o(736)+o(750)]=!0,this["_clearTi"+o(503)](),this._clearPingTimer(),this[o(1427)+o(1108)+o(793)](),this[o(1083)+"ger"]?.[o(1342)](),!this._ws)return void this[o(565)](e[o(1712)]);if(e[o(1190)](this[o(1538)][o(960)+"te"],this[o(1669)])||e[o(1444)](this._ws[o(960)+"te"],this[o(697)]))return void this[o(565)](e[o(428)]);this[o(1722)+o(737)+"t"](t,n)}async[r(475)](t,n){let o=r;if(e[o(1548)](null,t))throw new Error(e[o(858)]);e[o(486)]==typeof t&&(t=JSON[o(1249)+"y"](t)),e[o(1180)](e[o(1255)],typeof t)&&!(t instanceof ArrayBuffer)&&!(t[o(661)]&&e[o(1851)](t[o(661)],ArrayBuffer))&&(t=JSON[o(1249)+"y"](t));let c=await e.knEGD(ms,t),d=e[o(524)](i0,t),{method:g=0,service:p=this[o(1437)][o(386)],logID:u=this[o(1437)]["logIDGen"+o(1081)](),headers:y=this[o(1437)][o(572)],payloadEncoding:v=this[o(1437)][o(717)+o(963)],payloadType:A=this[o(1437)][o(1394)+o(1799)],logIDNew:N=this[o(1437)][o(925)+"Config"][o(734)+o(453)+o(532)+"ew"]?a(this[o(1437)][o(925)+o(994)][o(1347)]):""}=e[o(1380)](n,{});if(!p)throw new Error(e[o(1528)]);let D={SeqID:B[o(1445)+"er"](this._seqId++),LogID:B[o(1445)+"er"](u),service:p,method:g,headers:y,payloadEncoding:e.sVHEj(v,Object)?v[o(738)]?v.encoding:"":v,payloadType:e[o(1043)](A,Object)?A[o(1188)]?A[o(1188)]:d:A||d,payload:c,LogIDNew:N},O=e[o(470)](Qn,D);return this[o(1538)]&&this[o(1538)][o(960)+"te"]===this[o(1523)]?(this[o(1538)]&&this[o(1538)][o(475)](O),this._debug(e[o(1156)],D)):e.IQKpK(this[o(381)+o(763)].length,this[o(1437)]["maxMessageQueueL"+o(773)])?(this["_message"+o(763)].push(O),this._debug(o(1152),D)):(this[o(381)+"Queue"][o(1173)](),this[o(381)+"Queue"][o(1755)](O)),{seqID:this[o(800)],logID:u,logIDNew:N}}async[r(1559)+"t"](t){let n=r,{url:o}=t||{},c=Array.isArray(o)?o:e[n(1571)](e.kEUof,typeof o)?[o]:[];if(t&&Object[n(968)](this[n(1437)],t),c&&c[n(1410)]?this[n(577)+n(1546)]=new ls(c,this[n(1437)][n(728)+"es"]):this[n(577)+n(1546)]?.[n(394)+"pointCon"+n(557)](),this[n(696)+n(1117)]?.[n(1682)+n(491)](this[n(1437)][n(645)+"Count"]),this[n(736)+n(750)]=!1,this[n(1538)]&&this[n(1538)][n(960)+"te"]!==this[n(1669)])this[n(1500)+n(434)](1e3,e[n(1279)],!0);else if(e[n(871)](n(1720),n(1720)))this._isInit=!0,this[n(593)]();else return!0}async[r(1269)](){let t=r;!this[t(593)+t(1655)]&&(this[t(577)+t(1546)]?.[t(394)+"pointCon"+t(557)](),this[t(696)+t(1117)]?.[t(1682)+t(491)](),this[t(736)+"osed"]=!1,this[t(543)]=!0,this[t(593)]())}[r(635)+r(793)](t,n){this.on(t,n)}[r(389)+r(1282)](t){let n=r,{type:o}=t;this[n(1303)](o,t)}["removeEv"+r(502)+r(1163)](t,n){this[r(666)](t,n)}[r(656)](){let t=r,n={zqrAd:t(999)+t(943)+"s",lFWkz:function(o,c){return e[t(1732)](o,c)},LuWvB:function(o,c){return e[t(713)](o,c)},ekSso:e[t(1040)],GnSYj:e[t(1396)]};return new Promise((o,c)=>{let d=t,g={xWcZp:"success",RMeNl:n[d(727)],tasDw:function(p,u){return n[d(630)](p,u)},INiaA:d(867),UuUGp:d(999)+d(1216)+"t"};if(n.LuWvB("OdrIL",n[d(1652)]))_0x5b4384[d(1459)][d(640)+"ild"](_0x3fd234),_0x476e56["frontier"+d(1836)]=void 0,_0x448df2(_0x55ac34&&_0x56b061[d(983)]||d(768)+d(1879));else{this[d(1068)+d(1494)](),this[d(407)+d(1393)+"Id"]=setTimeout(this._ping.bind(this),this[d(1437)]["pingInte"+d(1087)]);let p=()=>{let y=d;o(g[y(1094)]),this[y(666)](g[y(1428)],p),this.off(y(999)+y(1216)+"t",u)},u=()=>{let y=d;g.tasDw(c,g[y(487)]),this[y(666)](g[y(1428)],p),this.off(g[y(1687)],u)};this.on("ping_once_success",p),this.on(n[d(760)],u),this[d(1049)]()}})}}})(),j["CustomCl"+S(1631)]=V[S(497)+S(1631)],j["CustomEr"+S(1654)]=V[S(1277)+S(1654)],j[S(699)+"e"]=V[S(699)+"e"],j[S(1282)]=V[S(1282)],j[S(1532)]=V[S(1532)],j[S(1554)+S(1573)+S(1808)]=V[S(1554)+S(1573)+S(1808)],j[S(1573)+"vent"]=V[S(1573)+S(1808)],j.OpenEvent=V[S(655)+"t"],j[S(633)+S(895)]=V[S(633)+S(895)],j[S(1738)+"oseEvent"]=V["createCl"+S(1631)],j[S(956)+S(1654)]=V[S(956)+S(1654)],j["createMe"+S(1862)+"nt"]=V[S(1195)+S(1862)+"nt"],j["createOp"+S(441)]=V[S(1721)+S(441)],j["createRe"+S(846)+"vent"]=V[S(1106)+"connectE"+S(1808)],j[S(1504)+S(479)]=V[S(1504)+S(479)],j[S(1715)+"ame"]=V.encodeFrame;for(_n in V)[S(497)+S(1631),S(1277)+"rorEvent",S(699)+"e",S(1282),S(1532),S(1554)+S(1573)+S(1808),S(1573)+"vent",S(655)+"t",S(633)+S(895),S(1738)+S(1631),S(956)+S(1654),S(1195)+S(1862)+"nt",S(1721)+"enEvent",S(1106)+S(846)+S(1808),"decodedF"+S(479),"encodeFrame"][S(828)](_n)===-1&&(j[_n]=V[_n]);var _n;Object.defineProperty(j,"__esModule",{value:!0})});var Ne=ie((vl,gi)=>{"use strict";var li=["nodebuffer","arraybuffer","fragments"],hi=typeof Blob<"u";hi&&li.push("blob");gi.exports={BINARY_TYPES:li,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:hi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ot=ie((Sl,An)=>{"use strict";var{EMPTY_BUFFER:Rx}=Ne(),_r=Buffer[Symbol.species];function Ox(r,e){if(r.length===0)return Rx;if(r.length===1)return r[0];let i=Buffer.allocUnsafe(e),a=0;for(let x=0;x<r.length;x++){let f=r[x];i.set(f,a),a+=f.length}return a<e?new _r(i.buffer,i.byteOffset,a):i}function pi(r,e,i,a,x){for(let f=0;f<x;f++)i[a+f]=r[f]^e[f&3]}function mi(r,e){for(let i=0;i<r.length;i++)r[i]^=e[i&3]}function Bx(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function yr(r){if(yr.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new _r(r):ArrayBuffer.isView(r)?e=new _r(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),yr.readOnly=!1),e}An.exports={concat:Ox,mask:pi,toArrayBuffer:Bx,toBuffer:yr,unmask:mi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=J("bufferutil");An.exports.mask=function(e,i,a,x,f){f<48?pi(e,i,a,x,f):r.mask(e,i,a,x,f)},An.exports.unmask=function(e,i){e.length<32?mi(e,i):r.unmask(e,i)}}catch{}});var yi=ie((Cl,_i)=>{"use strict";var wi=Symbol("kDone"),br=Symbol("kRun"),vr=class{constructor(e){this[wi]=()=>{this.pending--,this[br]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[br]()}[br](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wi])}}};_i.exports=vr});var ht=ie((El,Ci)=>{"use strict";var Bt=J("zlib"),bi=Ot(),zx=yi(),{kStatusCode:vi}=Ne(),Mx=Buffer[Symbol.species],qx=Buffer.from([0,0,255,255]),kn=Symbol("permessage-deflate"),Re=Symbol("total-length"),dt=Symbol("callback"),He=Symbol("buffers"),lt=Symbol("error"),Dn,Sr=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,!Dn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Dn=new zx(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[dt];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(x=>!(i.serverNoContextTakeover===!1&&x.server_no_context_takeover||x.server_max_window_bits&&(i.serverMaxWindowBits===!1||typeof i.serverMaxWindowBits=="number"&&i.serverMaxWindowBits>x.server_max_window_bits)||typeof i.clientMaxWindowBits=="number"&&!x.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 x=i[a];if(x.length>1)throw new Error(`Parameter "${a}" must have only a single value`);if(x=x[0],a==="client_max_window_bits"){if(x!==!0){let f=+x;if(!Number.isInteger(f)||f<8||f>15)throw new TypeError(`Invalid value for parameter "${a}": ${x}`);x=f}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${a}": ${x}`)}else if(a==="server_max_window_bits"){let f=+x;if(!Number.isInteger(f)||f<8||f>15)throw new TypeError(`Invalid value for parameter "${a}": ${x}`);x=f}else if(a==="client_no_context_takeover"||a==="server_no_context_takeover"){if(x!==!0)throw new TypeError(`Invalid value for parameter "${a}": ${x}`)}else throw new Error(`Unknown parameter "${a}"`);i[a]=x})}),e}decompress(e,i,a){Dn.add(x=>{this._decompress(e,i,(f,l)=>{x(),a(f,l)})})}compress(e,i,a){Dn.add(x=>{this._compress(e,i,(f,l)=>{x(),a(f,l)})})}_decompress(e,i,a){let x=this._isServer?"client":"server";if(!this._inflate){let f=`${x}_max_window_bits`,l=typeof this.params[f]!="number"?Bt.Z_DEFAULT_WINDOWBITS:this.params[f];this._inflate=Bt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[kn]=this,this._inflate[Re]=0,this._inflate[He]=[],this._inflate.on("error",Fx),this._inflate.on("data",Si)}this._inflate[dt]=a,this._inflate.write(e),i&&this._inflate.write(qx),this._inflate.flush(()=>{let f=this._inflate[lt];if(f){this._inflate.close(),this._inflate=null,a(f);return}let l=bi.concat(this._inflate[He],this._inflate[Re]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Re]=0,this._inflate[He]=[],i&&this.params[`${x}_no_context_takeover`]&&this._inflate.reset()),a(null,l)})}_compress(e,i,a){let x=this._isServer?"server":"client";if(!this._deflate){let f=`${x}_max_window_bits`,l=typeof this.params[f]!="number"?Bt.Z_DEFAULT_WINDOWBITS:this.params[f];this._deflate=Bt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Re]=0,this._deflate[He]=[],this._deflate.on("data",Ux)}this._deflate[dt]=a,this._deflate.write(e),this._deflate.flush(Bt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let f=bi.concat(this._deflate[He],this._deflate[Re]);i&&(f=new Mx(f.buffer,f.byteOffset,f.length-4)),this._deflate[dt]=null,this._deflate[Re]=0,this._deflate[He]=[],i&&this.params[`${x}_no_context_takeover`]&&this._deflate.reset(),a(null,f)})}};Ci.exports=Sr;function Ux(r){this[He].push(r),this[Re]+=r.length}function Si(r){if(this[Re]+=r.length,this[kn]._maxPayload<1||this[Re]<=this[kn]._maxPayload){this[He].push(r);return}this[lt]=new RangeError("Max payload size exceeded"),this[lt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[lt][vi]=1009,this.removeListener("data",Si),this.reset()}function Fx(r){if(this[kn]._inflate=null,this[lt]){this[dt](this[lt]);return}r[vi]=1007,this[dt](r)}});var gt=ie((Al,In)=>{"use strict";var{isUtf8:Ei}=J("buffer"),{hasBlob:Kx}=Ne(),Hx=[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 jx(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Cr(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 Gx(r){return Kx&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}In.exports={isBlob:Gx,isValidStatusCode:jx,isValidUTF8:Cr,tokenChars:Hx};if(Ei)In.exports.isValidUTF8=function(r){return r.length<24?Cr(r):Ei(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=J("utf-8-validate");In.exports.isValidUTF8=function(e){return e.length<32?Cr(e):r(e)}}catch{}});var Ir=ie((Dl,Li)=>{"use strict";var{Writable:Wx}=J("stream"),Ai=ht(),{BINARY_TYPES:Jx,EMPTY_BUFFER:Di,kStatusCode:Vx,kWebSocket:Yx}=Ne(),{concat:Er,toArrayBuffer:Xx,unmask:Zx}=Ot(),{isValidStatusCode:$x,isValidUTF8:ki}=gt(),Pn=Buffer[Symbol.species],ue=0,Ii=1,Pi=2,Ti=3,Ar=4,Dr=5,Tn=6,kr=class extends Wx{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Jx[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Yx]=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=ue}_write(e,i,a){if(this._opcode===8&&this._state==ue)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 Pn(a.buffer,a.byteOffset+e,a.length-e),new Pn(a.buffer,a.byteOffset,e)}let i=Buffer.allocUnsafe(e);do{let a=this._buffers[0],x=i.length-e;e>=a.length?i.set(this._buffers.shift(),x):(i.set(new Uint8Array(a.buffer,a.byteOffset,e),x),this._buffers[0]=new Pn(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 ue:this.getInfo(e);break;case Ii:this.getPayloadLength16(e);break;case Pi:this.getPayloadLength64(e);break;case Ti:this.getMask();break;case Ar:this.getData(e);break;case Dr:case Tn: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 x=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(x);return}let a=(i[0]&64)===64;if(a&&!this._extensions[Ai.extensionName]){let x=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(x);return}if(this._fin=(i[0]&128)===128,this._opcode=i[0]&15,this._payloadLength=i[1]&127,this._opcode===0){if(a){let x=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(x);return}if(!this._fragmented){let x=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(x);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let x=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(x);return}this._compressed=a}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let x=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(x);return}if(a){let x=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(x);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let x=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(x);return}}else{let x=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(x);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(i[1]&128)===128,this._isServer){if(!this._masked){let x=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(x);return}}else if(this._masked){let x=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(x);return}this._payloadLength===126?this._state=Ii:this._payloadLength===127?this._state=Pi: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 x=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(x);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=Ti:this._state=Ar}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ar}getData(e){let i=Di;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&&Zx(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Dr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[Ai.extensionName].decompress(e,this._fin,(x,f)=>{if(x)return i(x);if(f.length){if(this._messageLength+=f.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(l);return}this._fragments.push(f)}this.dataMessage(i),this._state===ue&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=ue;return}let i=this._messageLength,a=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let x;this._binaryType==="nodebuffer"?x=Er(a,i):this._binaryType==="arraybuffer"?x=Xx(Er(a,i)):this._binaryType==="blob"?x=new Blob(a):x=a,this._allowSynchronousEvents?(this.emit("message",x,!0),this._state=ue):(this._state=Tn,setImmediate(()=>{this.emit("message",x,!0),this._state=ue,this.startLoop(e)}))}else{let x=Er(a,i);if(!this._skipUTF8Validation&&!ki(x)){let f=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(f);return}this._state===Dr||this._allowSynchronousEvents?(this.emit("message",x,!1),this._state=ue):(this._state=Tn,setImmediate(()=>{this.emit("message",x,!1),this._state=ue,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Di),this.end();else{let a=e.readUInt16BE(0);if(!$x(a)){let f=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(f);return}let x=new Pn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ki(x)){let f=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");i(f);return}this._loop=!1,this.emit("conclude",a,x),this.end()}this._state=ue;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ue):(this._state=Tn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ue,this.startLoop(i)}))}createError(e,i,a,x,f){this._loop=!1,this._errored=!0;let l=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(l,this.createError),l.code=f,l[Vx]=x,l}};Li.exports=kr});var Lr=ie((Il,Oi)=>{"use strict";var{Duplex:kl}=J("stream"),{randomFillSync:Qx}=J("crypto"),Ni=ht(),{EMPTY_BUFFER:ec,kWebSocket:tc,NOOP:nc}=Ne(),{isBlob:pt,isValidStatusCode:rc}=gt(),{mask:Ri,toBuffer:Xe}=Ot(),de=Symbol("kByteLength"),sc=Buffer.alloc(4),Ln=8*1024,Ze,mt=Ln,pe=0,ic=1,oc=2,Pr=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=pe,this.onerror=nc,this[tc]=void 0}static frame(e,i){let a,x=!1,f=2,l=!1;i.mask&&(a=i.maskBuffer||sc,i.generateMask?i.generateMask(a):(mt===Ln&&(Ze===void 0&&(Ze=Buffer.alloc(Ln)),Qx(Ze,0,Ln),mt=0),a[0]=Ze[mt++],a[1]=Ze[mt++],a[2]=Ze[mt++],a[3]=Ze[mt++]),l=(a[0]|a[1]|a[2]|a[3])===0,f=6);let h;typeof e=="string"?(!i.mask||l)&&i[de]!==void 0?h=i[de]:(e=Buffer.from(e),h=e.length):(h=e.length,x=i.mask&&i.readOnly&&!l);let m=h;h>=65536?(f+=8,m=127):h>125&&(f+=2,m=126);let _=Buffer.allocUnsafe(x?h+f:f);return _[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(_[0]|=64),_[1]=m,m===126?_.writeUInt16BE(h,2):m===127&&(_[2]=_[3]=0,_.writeUIntBE(h,4,6)),i.mask?(_[1]|=128,_[f-4]=a[0],_[f-3]=a[1],_[f-2]=a[2],_[f-1]=a[3],l?[_,e]:x?(Ri(e,a,_,f,h),[_]):(Ri(e,a,e,0,h),[_,e])):[_,e]}close(e,i,a,x){let f;if(e===void 0)f=ec;else{if(typeof e!="number"||!rc(e))throw new TypeError("First argument must be a valid error code number");if(i===void 0||!i.length)f=Buffer.allocUnsafe(2),f.writeUInt16BE(e,0);else{let h=Buffer.byteLength(i);if(h>123)throw new RangeError("The message must not be greater than 123 bytes");f=Buffer.allocUnsafe(2+h),f.writeUInt16BE(e,0),typeof i=="string"?f.write(i,2):f.set(i,2)}}let l={[de]:f.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==pe?this.enqueue([this.dispatch,f,!1,l,x]):this.sendFrame(r.frame(f,l),x)}ping(e,i,a){let x,f;if(typeof e=="string"?(x=Buffer.byteLength(e),f=!1):pt(e)?(x=e.size,f=!1):(e=Xe(e),x=e.length,f=Xe.readOnly),x>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[de]:x,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:f,rsv1:!1};pt(e)?this._state!==pe?this.enqueue([this.getBlobData,e,!1,l,a]):this.getBlobData(e,!1,l,a):this._state!==pe?this.enqueue([this.dispatch,e,!1,l,a]):this.sendFrame(r.frame(e,l),a)}pong(e,i,a){let x,f;if(typeof e=="string"?(x=Buffer.byteLength(e),f=!1):pt(e)?(x=e.size,f=!1):(e=Xe(e),x=e.length,f=Xe.readOnly),x>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[de]:x,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:f,rsv1:!1};pt(e)?this._state!==pe?this.enqueue([this.getBlobData,e,!1,l,a]):this.getBlobData(e,!1,l,a):this._state!==pe?this.enqueue([this.dispatch,e,!1,l,a]):this.sendFrame(r.frame(e,l),a)}send(e,i,a){let x=this._extensions[Ni.extensionName],f=i.binary?2:1,l=i.compress,h,m;typeof e=="string"?(h=Buffer.byteLength(e),m=!1):pt(e)?(h=e.size,m=!1):(e=Xe(e),h=e.length,m=Xe.readOnly),this._firstFragment?(this._firstFragment=!1,l&&x&&x.params[x._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=h>=x._threshold),this._compress=l):(l=!1,f=0),i.fin&&(this._firstFragment=!0);let _={[de]:h,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:f,readOnly:m,rsv1:l};pt(e)?this._state!==pe?this.enqueue([this.getBlobData,e,this._compress,_,a]):this.getBlobData(e,this._compress,_,a):this._state!==pe?this.enqueue([this.dispatch,e,this._compress,_,a]):this.dispatch(e,this._compress,_,a)}getBlobData(e,i,a,x){this._bufferedBytes+=a[de],this._state=oc,e.arrayBuffer().then(f=>{if(this._socket.destroyed){let h=new Error("The socket was closed while the blob was being read");process.nextTick(Tr,this,h,x);return}this._bufferedBytes-=a[de];let l=Xe(f);i?this.dispatch(l,i,a,x):(this._state=pe,this.sendFrame(r.frame(l,a),x),this.dequeue())}).catch(f=>{process.nextTick(ac,this,f,x)})}dispatch(e,i,a,x){if(!i){this.sendFrame(r.frame(e,a),x);return}let f=this._extensions[Ni.extensionName];this._bufferedBytes+=a[de],this._state=ic,f.compress(e,a.fin,(l,h)=>{if(this._socket.destroyed){let m=new Error("The socket was closed while data was being compressed");Tr(this,m,x);return}this._bufferedBytes-=a[de],this._state=pe,a.readOnly=!1,this.sendFrame(r.frame(h,a),x),this.dequeue()})}dequeue(){for(;this._state===pe&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][de],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][de],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)}};Oi.exports=Pr;function Tr(r,e,i){typeof i=="function"&&i(e);for(let a=0;a<r._queue.length;a++){let x=r._queue[a],f=x[x.length-1];typeof f=="function"&&f(e)}}function ac(r,e,i){Tr(r,e,i),r.onerror(e)}});var ji=ie((Pl,Hi)=>{"use strict";var{kForOnEventAttribute:zt,kListener:Nr}=Ne(),Bi=Symbol("kCode"),zi=Symbol("kData"),Mi=Symbol("kError"),qi=Symbol("kMessage"),Ui=Symbol("kReason"),wt=Symbol("kTarget"),Fi=Symbol("kType"),Ki=Symbol("kWasClean"),Oe=class{constructor(e){this[wt]=null,this[Fi]=e}get target(){return this[wt]}get type(){return this[Fi]}};Object.defineProperty(Oe.prototype,"target",{enumerable:!0});Object.defineProperty(Oe.prototype,"type",{enumerable:!0});var $e=class extends Oe{constructor(e,i={}){super(e),this[Bi]=i.code===void 0?0:i.code,this[Ui]=i.reason===void 0?"":i.reason,this[Ki]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[Bi]}get reason(){return this[Ui]}get wasClean(){return this[Ki]}};Object.defineProperty($e.prototype,"code",{enumerable:!0});Object.defineProperty($e.prototype,"reason",{enumerable:!0});Object.defineProperty($e.prototype,"wasClean",{enumerable:!0});var _t=class extends Oe{constructor(e,i={}){super(e),this[Mi]=i.error===void 0?null:i.error,this[qi]=i.message===void 0?"":i.message}get error(){return this[Mi]}get message(){return this[qi]}};Object.defineProperty(_t.prototype,"error",{enumerable:!0});Object.defineProperty(_t.prototype,"message",{enumerable:!0});var Mt=class extends Oe{constructor(e,i={}){super(e),this[zi]=i.data===void 0?null:i.data}get data(){return this[zi]}};Object.defineProperty(Mt.prototype,"data",{enumerable:!0});var xc={addEventListener(r,e,i={}){for(let x of this.listeners(r))if(!i[zt]&&x[Nr]===e&&!x[zt])return;let a;if(r==="message")a=function(f,l){let h=new Mt("message",{data:l?f:f.toString()});h[wt]=this,Nn(e,this,h)};else if(r==="close")a=function(f,l){let h=new $e("close",{code:f,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});h[wt]=this,Nn(e,this,h)};else if(r==="error")a=function(f){let l=new _t("error",{error:f,message:f.message});l[wt]=this,Nn(e,this,l)};else if(r==="open")a=function(){let f=new Oe("open");f[wt]=this,Nn(e,this,f)};else return;a[zt]=!!i[zt],a[Nr]=e,i.once?this.once(r,a):this.on(r,a)},removeEventListener(r,e){for(let i of this.listeners(r))if(i[Nr]===e&&!i[zt]){this.removeListener(r,i);break}}};Hi.exports={CloseEvent:$e,ErrorEvent:_t,Event:Oe,EventTarget:xc,MessageEvent:Mt};function Nn(r,e,i){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,i):r.call(e,i)}});var Rn=ie((Tl,Gi)=>{"use strict";var{tokenChars:qt}=gt();function Ee(r,e,i){r[e]===void 0?r[e]=[i]:r[e].push(i)}function cc(r){let e=Object.create(null),i=Object.create(null),a=!1,x=!1,f=!1,l,h,m=-1,_=-1,b=-1,w=0;for(;w<r.length;w++)if(_=r.charCodeAt(w),l===void 0)if(b===-1&&qt[_]===1)m===-1&&(m=w);else if(w!==0&&(_===32||_===9))b===-1&&m!==-1&&(b=w);else if(_===59||_===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${w}`);b===-1&&(b=w);let k=r.slice(m,b);_===44?(Ee(e,k,i),i=Object.create(null)):l=k,m=b=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(h===void 0)if(b===-1&&qt[_]===1)m===-1&&(m=w);else if(_===32||_===9)b===-1&&m!==-1&&(b=w);else if(_===59||_===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${w}`);b===-1&&(b=w),Ee(i,r.slice(m,b),!0),_===44&&(Ee(e,l,i),i=Object.create(null),l=void 0),m=b=-1}else if(_===61&&m!==-1&&b===-1)h=r.slice(m,w),m=b=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(x){if(qt[_]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);m===-1?m=w:a||(a=!0),x=!1}else if(f)if(qt[_]===1)m===-1&&(m=w);else if(_===34&&m!==-1)f=!1,b=w;else if(_===92)x=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(_===34&&r.charCodeAt(w-1)===61)f=!0;else if(b===-1&&qt[_]===1)m===-1&&(m=w);else if(m!==-1&&(_===32||_===9))b===-1&&(b=w);else if(_===59||_===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${w}`);b===-1&&(b=w);let k=r.slice(m,b);a&&(k=k.replace(/\\/g,""),a=!1),Ee(i,h,k),_===44&&(Ee(e,l,i),i=Object.create(null),l=void 0),h=void 0,m=b=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(m===-1||f||_===32||_===9)throw new SyntaxError("Unexpected end of input");b===-1&&(b=w);let C=r.slice(m,b);return l===void 0?Ee(e,C,i):(h===void 0?Ee(i,C,!0):a?Ee(i,h,C.replace(/\\/g,"")):Ee(i,h,C),Ee(e,l,i)),e}function fc(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(x=>{let f=a[x];return Array.isArray(f)||(f=[f]),f.map(l=>l===!0?x:`${x}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Gi.exports={format:fc,parse:cc}});var Mn=ie((Rl,ro)=>{"use strict";var uc=J("events"),dc=J("https"),lc=J("http"),Vi=J("net"),hc=J("tls"),{randomBytes:gc,createHash:pc}=J("crypto"),{Duplex:Ll,Readable:Nl}=J("stream"),{URL:Rr}=J("url"),je=ht(),mc=Ir(),wc=Lr(),{isBlob:_c}=gt(),{BINARY_TYPES:Wi,CLOSE_TIMEOUT:yc,EMPTY_BUFFER:On,GUID:bc,kForOnEventAttribute:Or,kListener:vc,kStatusCode:Sc,kWebSocket:Z,NOOP:Yi}=Ne(),{EventTarget:{addEventListener:Cc,removeEventListener:Ec}}=ji(),{format:Ac,parse:Dc}=Rn(),{toBuffer:kc}=Ot(),Xi=Symbol("kAborted"),Br=[8,13],Be=["CONNECTING","OPEN","CLOSING","CLOSED"],Ic=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,U=class r extends uc{constructor(e,i,a){super(),this._binaryType=Wi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=On,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]),Zi(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Wi.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 x=new mc({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),f=new wc(e,this._extensions,a.generateMask);this._receiver=x,this._sender=f,this._socket=e,x[Z]=this,f[Z]=this,e[Z]=this,x.on("conclude",Lc),x.on("drain",Nc),x.on("error",Rc),x.on("message",Oc),x.on("ping",Bc),x.on("pong",zc),f.onerror=Mc,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",eo),e.on("data",zn),e.on("end",to),e.on("error",no),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[je.extensionName]&&this._extensions[je.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){xe(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())}),Qi(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){zr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||On,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){zr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||On,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){zr(this,e,a);return}let x={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[je.extensionName]||(x.compress=!1),this._sender.send(e||On,x,a)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(U,"CONNECTING",{enumerable:!0,value:Be.indexOf("CONNECTING")});Object.defineProperty(U.prototype,"CONNECTING",{enumerable:!0,value:Be.indexOf("CONNECTING")});Object.defineProperty(U,"OPEN",{enumerable:!0,value:Be.indexOf("OPEN")});Object.defineProperty(U.prototype,"OPEN",{enumerable:!0,value:Be.indexOf("OPEN")});Object.defineProperty(U,"CLOSING",{enumerable:!0,value:Be.indexOf("CLOSING")});Object.defineProperty(U.prototype,"CLOSING",{enumerable:!0,value:Be.indexOf("CLOSING")});Object.defineProperty(U,"CLOSED",{enumerable:!0,value:Be.indexOf("CLOSED")});Object.defineProperty(U.prototype,"CLOSED",{enumerable:!0,value:Be.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(U.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(U.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Or])return e[vc];return null},set(e){for(let i of this.listeners(r))if(i[Or]){this.removeListener(r,i);break}typeof e=="function"&&this.addEventListener(r,e,{[Or]:!0})}})});U.prototype.addEventListener=Cc;U.prototype.removeEventListener=Ec;ro.exports=U;function Zi(r,e,i,a){let x={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:yc,protocolVersion:Br[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=x.autoPong,r._closeTimeout=x.closeTimeout,!Br.includes(x.protocolVersion))throw new RangeError(`Unsupported protocol version: ${x.protocolVersion} (supported versions: ${Br.join(", ")})`);let f;if(e instanceof Rr)f=e;else try{f=new Rr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}f.protocol==="http:"?f.protocol="ws:":f.protocol==="https:"&&(f.protocol="wss:"),r._url=f.href;let l=f.protocol==="wss:",h=f.protocol==="ws+unix:",m;if(f.protocol!=="ws:"&&!l&&!h?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:h&&!f.pathname?m="The URL's pathname is empty":f.hash&&(m="The URL contains a fragment identifier"),m){let L=new SyntaxError(m);if(r._redirects===0)throw L;Bn(r,L);return}let _=l?443:80,b=gc(16).toString("base64"),w=l?dc.request:lc.request,C=new Set,k;if(x.createConnection=x.createConnection||(l?Tc:Pc),x.defaultPort=x.defaultPort||_,x.port=f.port||_,x.host=f.hostname.startsWith("[")?f.hostname.slice(1,-1):f.hostname,x.headers={...x.headers,"Sec-WebSocket-Version":x.protocolVersion,"Sec-WebSocket-Key":b,Connection:"Upgrade",Upgrade:"websocket"},x.path=f.pathname+f.search,x.timeout=x.handshakeTimeout,x.perMessageDeflate&&(k=new je({...x.perMessageDeflate,isServer:!1,maxPayload:x.maxPayload}),x.headers["Sec-WebSocket-Extensions"]=Ac({[je.extensionName]:k.offer()})),i.length){for(let L of i){if(typeof L!="string"||!Ic.test(L)||C.has(L))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(L)}x.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(x.origin&&(x.protocolVersion<13?x.headers["Sec-WebSocket-Origin"]=x.origin:x.headers.Origin=x.origin),(f.username||f.password)&&(x.auth=`${f.username}:${f.password}`),h){let L=x.path.split(":");x.socketPath=L[0],x.path=L[1]}let T;if(x.followRedirects){if(r._redirects===0){r._originalIpc=h,r._originalSecure=l,r._originalHostOrSocketPath=h?x.socketPath:f.host;let L=a&&a.headers;if(a={...a,headers:{}},L)for(let[F,Q]of Object.entries(L))a.headers[F.toLowerCase()]=Q}else if(r.listenerCount("redirect")===0){let L=h?r._originalIpc?x.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:f.host===r._originalHostOrSocketPath;(!L||r._originalSecure&&!l)&&(delete x.headers.authorization,delete x.headers.cookie,L||delete x.headers.host,x.auth=void 0)}x.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(x.auth).toString("base64")),T=r._req=w(x),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=w(x);x.timeout&&T.on("timeout",()=>{xe(r,T,"Opening handshake has timed out")}),T.on("error",L=>{T===null||T[Xi]||(T=r._req=null,Bn(r,L))}),T.on("response",L=>{let F=L.headers.location,Q=L.statusCode;if(F&&x.followRedirects&&Q>=300&&Q<400){if(++r._redirects>x.maxRedirects){xe(r,T,"Maximum redirects exceeded");return}T.abort();let ne;try{ne=new Rr(F,e)}catch{let I=new SyntaxError(`Invalid URL: ${F}`);Bn(r,I);return}Zi(r,ne,i,a)}else r.emit("unexpected-response",T,L)||xe(r,T,`Unexpected server response: ${L.statusCode}`)}),T.on("upgrade",(L,F,Q)=>{if(r.emit("upgrade",L),r.readyState!==U.CONNECTING)return;T=r._req=null;let ne=L.headers.upgrade;if(ne===void 0||ne.toLowerCase()!=="websocket"){xe(r,F,"Invalid Upgrade header");return}let Ae=pc("sha1").update(b+bc).digest("base64");if(L.headers["sec-websocket-accept"]!==Ae){xe(r,F,"Invalid Sec-WebSocket-Accept header");return}let I=L.headers["sec-websocket-protocol"],M;if(I!==void 0?C.size?C.has(I)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":C.size&&(M="Server sent no subprotocol"),M){xe(r,F,M);return}I&&(r._protocol=I);let Y=L.headers["sec-websocket-extensions"];if(Y!==void 0){if(!k){xe(r,F,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let me;try{me=Dc(Y)}catch{xe(r,F,"Invalid Sec-WebSocket-Extensions header");return}let De=Object.keys(me);if(De.length!==1||De[0]!==je.extensionName){xe(r,F,"Server indicated an extension that was not requested");return}try{k.accept(me[je.extensionName])}catch{xe(r,F,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[je.extensionName]=k}r.setSocket(F,Q,{allowSynchronousEvents:x.allowSynchronousEvents,generateMask:x.generateMask,maxPayload:x.maxPayload,skipUTF8Validation:x.skipUTF8Validation})}),x.finishRequest?x.finishRequest(T,r):T.end()}function Bn(r,e){r._readyState=U.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Pc(r){return r.path=r.socketPath,Vi.connect(r)}function Tc(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Vi.isIP(r.host)?"":r.host),hc.connect(r)}function xe(r,e,i){r._readyState=U.CLOSING;let a=new Error(i);Error.captureStackTrace(a,xe),e.setHeader?(e[Xi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Bn,r,a)):(e.destroy(a),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function zr(r,e,i){if(e){let a=_c(e)?e.size:kc(e).length;r._socket?r._sender._bufferedBytes+=a:r._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${r.readyState} (${Be[r.readyState]})`);process.nextTick(i,a)}}function Lc(r,e){let i=this[Z];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=r,i._socket[Z]!==void 0&&(i._socket.removeListener("data",zn),process.nextTick($i,i._socket),r===1005?i.close():i.close(r,e))}function Nc(){let r=this[Z];r.isPaused||r._socket.resume()}function Rc(r){let e=this[Z];e._socket[Z]!==void 0&&(e._socket.removeListener("data",zn),process.nextTick($i,e._socket),e.close(r[Sc])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Ji(){this[Z].emitClose()}function Oc(r,e){this[Z].emit("message",r,e)}function Bc(r){let e=this[Z];e._autoPong&&e.pong(r,!this._isServer,Yi),e.emit("ping",r)}function zc(r){this[Z].emit("pong",r)}function $i(r){r.resume()}function Mc(r){let e=this[Z];e.readyState!==U.CLOSED&&(e.readyState===U.OPEN&&(e._readyState=U.CLOSING,Qi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Qi(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function eo(){let r=this[Z];if(this.removeListener("close",eo),this.removeListener("data",zn),this.removeListener("end",to),r._readyState=U.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[Z]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Ji),r._receiver.on("finish",Ji))}function zn(r){this[Z]._receiver.write(r)||this.pause()}function to(){let r=this[Z];r._readyState=U.CLOSING,r._receiver.end(),this.end()}function no(){let r=this[Z];this.removeListener("error",no),this.on("error",Yi),r&&(r._readyState=U.CLOSING,this.destroy())}});var ao=ie((Bl,oo)=>{"use strict";var Ol=Mn(),{Duplex:qc}=J("stream");function so(r){r.emit("close")}function Uc(){!this.destroyed&&this._writableState.finished&&this.destroy()}function io(r){this.removeListener("error",io),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Fc(r,e){let i=!0,a=new qc({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(f,l){let h=!l&&a._readableState.objectMode?f.toString():f;a.push(h)||r.pause()}),r.once("error",function(f){a.destroyed||(i=!1,a.destroy(f))}),r.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(x,f){if(r.readyState===r.CLOSED){f(x),process.nextTick(so,a);return}let l=!1;r.once("error",function(m){l=!0,f(m)}),r.once("close",function(){l||f(x),process.nextTick(so,a)}),i&&r.terminate()},a._final=function(x){if(r.readyState===r.CONNECTING){r.once("open",function(){a._final(x)});return}r._socket!==null&&(r._socket._writableState.finished?(x(),a._readableState.endEmitted&&a.destroy()):(r._socket.once("finish",function(){x()}),r.close()))},a._read=function(){r.isPaused&&r.resume()},a._write=function(x,f,l){if(r.readyState===r.CONNECTING){r.once("open",function(){a._write(x,f,l)});return}r.send(x,l)},a.on("end",Uc),a.on("error",io),a}oo.exports=Fc});var Mr=ie((zl,xo)=>{"use strict";var{tokenChars:Kc}=gt();function Hc(r){let e=new Set,i=-1,a=-1,x=0;for(x;x<r.length;x++){let l=r.charCodeAt(x);if(a===-1&&Kc[l]===1)i===-1&&(i=x);else if(x!==0&&(l===32||l===9))a===-1&&i!==-1&&(a=x);else if(l===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${x}`);a===-1&&(a=x);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 ${x}`)}if(i===-1||a!==-1)throw new SyntaxError("Unexpected end of input");let f=r.slice(i,x);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);return e.add(f),e}xo.exports={parse:Hc}});var po=ie((ql,go)=>{"use strict";var jc=J("events"),qn=J("http"),{Duplex:Ml}=J("stream"),{createHash:Gc}=J("crypto"),co=Rn(),Qe=ht(),Wc=Mr(),Jc=Mn(),{CLOSE_TIMEOUT:Vc,GUID:Yc,kWebSocket:Xc}=Ne(),Zc=/^[+/0-9A-Za-z]{22}==$/,fo=0,uo=1,ho=2,qr=class extends jc{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Vc,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Jc,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=qn.createServer((a,x)=>{let f=qn.STATUS_CODES[426];x.writeHead(426,{"Content-Length":f.length,"Content-Type":"text/plain"}),x.end(f)}),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=$c(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(x,f,l)=>{this.handleUpgrade(x,f,l,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=fo}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===ho){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Ut,this);return}if(e&&this.once("close",e),this._state!==uo)if(this._state=uo,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(Ut,this):process.nextTick(Ut,this);else{let i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{Ut(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,x){i.on("error",lo);let f=e.headers["sec-websocket-key"],l=e.headers.upgrade,h=+e.headers["sec-websocket-version"];if(e.method!=="GET"){et(this,e,i,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){et(this,e,i,400,"Invalid Upgrade header");return}if(f===void 0||!Zc.test(f)){et(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(h!==13&&h!==8){et(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ft(i,400);return}let m=e.headers["sec-websocket-protocol"],_=new Set;if(m!==void 0)try{_=Wc.parse(m)}catch{et(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let b=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&b!==void 0){let C=new Qe({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let k=co.parse(b);k[Qe.extensionName]&&(C.accept(k[Qe.extensionName]),w[Qe.extensionName]=C)}catch{et(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${h===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(k,T,L,F)=>{if(!k)return Ft(i,T||401,L,F);this.completeUpgrade(w,f,_,e,i,a,x)});return}if(!this.options.verifyClient(C))return Ft(i,401)}this.completeUpgrade(w,f,_,e,i,a,x)}completeUpgrade(e,i,a,x,f,l,h){if(!f.readable||!f.writable)return f.destroy();if(f[Xc])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fo)return Ft(f,503);let _=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gc("sha1").update(i+Yc).digest("base64")}`],b=new this.options.WebSocket(null,void 0,this.options);if(a.size){let w=this.options.handleProtocols?this.options.handleProtocols(a,x):a.values().next().value;w&&(_.push(`Sec-WebSocket-Protocol: ${w}`),b._protocol=w)}if(e[Qe.extensionName]){let w=e[Qe.extensionName].params,C=co.format({[Qe.extensionName]:[w]});_.push(`Sec-WebSocket-Extensions: ${C}`),b._extensions=e}this.emit("headers",_,x),f.write(_.concat(`\r
|
|
8
|
+
var $o=Object.create;var xr=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var qo=Object.getOwnPropertyNames;var Go=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty;var P=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var j=(r,e)=>()=>(r&&(e=r(r=0)),e);var B=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ir=(r,e)=>{for(var t in e)xr(r,t,{get:e[t],enumerable:!0})},Wo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qo(e))!Ho.call(r,s)&&s!==t&&xr(r,s,{get:()=>e[s],enumerable:!(n=zo(e,s))||n.enumerable});return r};var le=(r,e,t)=>(t=r!=null?$o(Go(r)):{},Wo(e||!r||!r.__esModule?xr(t,"default",{value:r,enumerable:!0}):t,r));import{chmod as jo,mkdir as Jo,readFile as Vo,rename as Wn,writeFile as jn}from"node:fs/promises";import{dirname as Qo}from"node:path";async function yt(r){try{let e=await Vo(r,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function St(r,e,t){await Jo(Qo(r),{recursive:!0});let n=`${JSON.stringify(e,null,2)}
|
|
9
|
+
`,s=`${r}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{t?.mode!==void 0?await jn(s,n,{encoding:"utf8",mode:t.mode}):await jn(s,n,"utf8"),await Wn(s,r),t?.mode!==void 0&&await jo(r,t.mode)}catch(i){await Wn(s,s).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(s,{force:!0}).catch(()=>{}),i}}var Tr=j(()=>{"use strict"});function Qn(r){return vt[Jn]<=vt[r]}function Rr(r){Vn={...r}}function Et(r,e,t,n){if(vt[r]<vt[Jn])return;let s=JSON.stringify({ts:new Date().toISOString(),level:r,module:e,msg:t,...Vn,...n});r==="error"||r==="warn"?Xo.write(`${s}
|
|
10
|
+
`):Ko.write(`${s}
|
|
11
|
+
`)}function w(r){return{debug:(e,t)=>Et("debug",r,e,t),info:(e,t)=>Et("info",r,e,t),warn:(e,t)=>Et("warn",r,e,t),error:(e,t)=>Et("error",r,e,t),child:e=>w(`${r}.${e}`)}}var vt,Jn,Ko,Xo,Vn,k=j(()=>{"use strict";vt={debug:10,info:20,warn:30,error:40},Jn=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),Ko=process.stdout,Xo=process.stderr,Vn={}});import{homedir as Yo}from"node:os";import{join as N}from"node:path";function x(r){let e=r??Yo(),t=N(e,".coze"),n=N(t,"bridge"),s=N(n,"lib");return{cozeRoot:t,bridgeRoot:n,libDir:s,libEntry:N(s,"index.js"),pidFile:N(n,"bridge.pid"),portFile:N(n,"bridge.port"),tokenFile:N(n,"bridge.token"),logFile:N(n,"bridge.log"),installLock:N(n,"install.lock"),configFile:N(n,"config.json"),agentsRoot:N(t,"agents")}}function ne(r,e=x()){let t=N(e.agentsRoot,r);return{root:t,config:N(t,"config.json"),workspace:N(t,"workspace"),logs:N(t,"logs")}}var F=j(()=>{"use strict"});var It={};Ir(It,{AGENT_CONFIG_FILE_MODE:()=>kt,enforceAgentConfigMode:()=>ta,loadAgentConfig:()=>U,persistAgentSessions:()=>Pr,persistAgentSkills:()=>xt,saveAgentConfig:()=>J});import{chmod as Zo,stat as ea}from"node:fs/promises";function U(r,e){return yt(ne(r,e).config)}function J(r,e){return St(ne(r.agentId,e).config,r,{mode:kt})}async function ta(r,e){if(process.platform==="win32")return;let t=ne(r,e).config;try{let n=await ea(t);if(!n.isFile())return;let s=n.mode&511;s!==kt&&(await Zo(t,kt),Kn.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(n){if(n.code==="ENOENT")return;Kn.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(n)})}}async function Pr(r,e,t){let n=await U(r,t);n&&(n.sessions=Object.fromEntries(e),await J(n,t))}async function xt(r,e,t){let n=await U(r,t);n&&(n.skills=e,await J(n,t))}var Kn,kt,ue=j(()=>{"use strict";Tr();k();F();Kn=w("agent-config"),kt=384});function Sc(){return Ds||(Ds=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ec(){return Ls||(Ls=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function vc(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",o)},i=()=>{t(q(r.result)),s()},o=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Ms.set(t,r)}).catch(()=>{}),Lr.set(e,r),e}function kc(r){if(br.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",o),r.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",o),r.addEventListener("abort",o)});br.set(r,e)}function Fs(r){Dr=r(Dr)}function xc(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(it(this),e,...t);return Bs.set(n,e.sort?e.sort():[e]),q(n)}:Ec().includes(r)?function(...e){return r.apply(it(this),e),q(Ms.get(this))}:function(...e){return q(r.apply(it(this),e))}}function Ic(r){return typeof r=="function"?xc(r):(r instanceof IDBTransaction&&kc(r),yc(r,Sc())?new Proxy(r,Dr):r)}function q(r){if(r instanceof IDBRequest)return vc(r);if(Nr.has(r))return Nr.get(r);let e=Ic(r);return e!==r&&(Nr.set(r,e),Lr.set(e,r)),e}var yc,Ds,Ls,Ms,br,Bs,Nr,Lr,Dr,it,Mr=j(()=>{yc=(r,e)=>e.some(t=>r instanceof t);Ms=new WeakMap,br=new WeakMap,Bs=new WeakMap,Nr=new WeakMap,Lr=new WeakMap;Dr={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return br.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Bs.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return q(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};it=r=>Lr.get(r)});var $s={};Ir($s,{deleteDB:()=>Rc,openDB:()=>Tc,unwrap:()=>it,wrap:()=>q});function Tc(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let o=indexedDB.open(r,e),a=q(o);return n&&o.addEventListener("upgradeneeded",c=>{n(q(o.result),c.oldVersion,c.newVersion,q(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function Rc(r,{blocked:e}={}){let t=indexedDB.deleteDatabase(r);return e&&t.addEventListener("blocked",()=>e()),q(t).then(()=>{})}function Us(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Br.get(e))return Br.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=Ac.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||Pc.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),d=c.store;return n&&(d=d.index(a.shift())),(await Promise.all([d[t](...a),s&&c.done]))[0]};return Br.set(e,i),i}var Pc,Ac,Br,zs=j(()=>{Mr();Mr();Pc=["get","getKey","getAll","getAllKeys","count"],Ac=["put","add","delete","clear"],Br=new Map;Fs(r=>({...r,get:(e,t,n)=>Us(e,t)||r.get(e,t,n),has:(e,t)=>!!Us(e,t)||r.has(e,t)}))});var oe=B((Rg,hi)=>{"use strict";var ui=["nodebuffer","arraybuffer","fragments"],fi=typeof Blob<"u";fi&&ui.push("blob");hi.exports={BINARY_TYPES:ui,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:fi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ut=B((Pg,Xt)=>{"use strict";var{EMPTY_BUFFER:Nd}=oe(),an=Buffer[Symbol.species];function bd(r,e){if(r.length===0)return Nd;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new an(t.buffer,t.byteOffset,n):t}function gi(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function pi(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Dd(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function cn(r){if(cn.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new an(r):ArrayBuffer.isView(r)?e=new an(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),cn.readOnly=!1),e}Xt.exports={concat:bd,mask:gi,toArrayBuffer:Dd,toBuffer:cn,unmask:pi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=P("bufferutil");Xt.exports.mask=function(e,t,n,s,i){i<48?gi(e,t,n,s,i):r.mask(e,t,n,s,i)},Xt.exports.unmask=function(e,t){e.length<32?pi(e,t):r.unmask(e,t)}}catch{}});var wi=B((Ag,_i)=>{"use strict";var mi=Symbol("kDone"),dn=Symbol("kRun"),ln=class{constructor(e){this[mi]=()=>{this.pending--,this[dn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[dn]()}[dn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[mi])}}};_i.exports=ln});var Ge=B((Cg,vi)=>{"use strict";var ft=P("zlib"),yi=ut(),Ld=wi(),{kStatusCode:Si}=oe(),Md=Buffer[Symbol.species],Bd=Buffer.from([0,0,255,255]),Zt=Symbol("permessage-deflate"),ae=Symbol("total-length"),ze=Symbol("callback"),me=Symbol("buffers"),qe=Symbol("error"),Yt,un=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,!Yt){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Yt=new Ld(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[ze];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,n=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(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}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(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="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 "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Yt.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Yt.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ft.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zt]=this,this._inflate[ae]=0,this._inflate[me]=[],this._inflate.on("error",Ud),this._inflate.on("data",Ei)}this._inflate[ze]=n,this._inflate.write(e),t&&this._inflate.write(Bd),this._inflate.flush(()=>{let i=this._inflate[qe];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=yi.concat(this._inflate[me],this._inflate[ae]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ae]=0,this._inflate[me]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ft.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[me]=[],this._deflate.on("data",Fd)}this._deflate[ze]=n,this._deflate.write(e),this._deflate.flush(ft.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=yi.concat(this._deflate[me],this._deflate[ae]);t&&(i=new Md(i.buffer,i.byteOffset,i.length-4)),this._deflate[ze]=null,this._deflate[ae]=0,this._deflate[me]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};vi.exports=un;function Fd(r){this[me].push(r),this[ae]+=r.length}function Ei(r){if(this[ae]+=r.length,this[Zt]._maxPayload<1||this[ae]<=this[Zt]._maxPayload){this[me].push(r);return}this[qe]=new RangeError("Max payload size exceeded"),this[qe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[qe][Si]=1009,this.removeListener("data",Ei),this.reset()}function Ud(r){if(this[Zt]._inflate=null,this[qe]){this[ze](this[qe]);return}r[Si]=1007,this[ze](r)}});var He=B((Og,er)=>{"use strict";var{isUtf8:ki}=P("buffer"),{hasBlob:$d}=oe(),zd=[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 qd(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function fn(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Gd(r){return $d&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}er.exports={isBlob:Gd,isValidStatusCode:qd,isValidUTF8:fn,tokenChars:zd};if(ki)er.exports.isValidUTF8=function(r){return r.length<24?fn(r):ki(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=P("utf-8-validate");er.exports.isValidUTF8=function(e){return e.length<32?fn(e):r(e)}}catch{}});var _n=B((Ng,Ci)=>{"use strict";var{Writable:Hd}=P("stream"),xi=Ge(),{BINARY_TYPES:Wd,EMPTY_BUFFER:Ii,kStatusCode:jd,kWebSocket:Jd}=oe(),{concat:hn,toArrayBuffer:Vd,unmask:Qd}=ut(),{isValidStatusCode:Kd,isValidUTF8:Ti}=He(),tr=Buffer[Symbol.species],H=0,Ri=1,Pi=2,Ai=3,gn=4,pn=5,rr=6,mn=class extends Hd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Jd]=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=H}_write(e,t,n){if(this._opcode===8&&this._state==H)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new tr(n.buffer,n.byteOffset+e,n.length-e),new tr(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new tr(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case H:this.getInfo(e);break;case Ri:this.getPayloadLength16(e);break;case Pi:this.getPayloadLength64(e);break;case Ai:this.getMask();break;case gn:this.getData(e);break;case pn:case rr: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 n=(t[0]&64)===64;if(n&&!this._extensions[xi.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(n){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=n}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(n){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=Ri:this._payloadLength===127?this._state=Pi: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),n=t.readUInt32BE(0);if(n>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=n*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=Ai:this._state=gn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=gn}getData(e){let t=Ii;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&&Qd(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=pn,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[xi.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===H&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=H;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=hn(n,t):this._binaryType==="arraybuffer"?s=Vd(hn(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=H):(this._state=rr,setImmediate(()=>{this.emit("message",s,!0),this._state=H,this.startLoop(e)}))}else{let s=hn(n,t);if(!this._skipUTF8Validation&&!Ti(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===pn||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=H):(this._state=rr,setImmediate(()=>{this.emit("message",s,!1),this._state=H,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ii),this.end();else{let n=e.readUInt16BE(0);if(!Kd(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new tr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ti(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",n,s),this.end()}this._state=H;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=H):(this._state=rr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=H,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[jd]=s,o}};Ci.exports=mn});var Sn=B((Dg,bi)=>{"use strict";var{Duplex:bg}=P("stream"),{randomFillSync:Xd}=P("crypto"),Oi=Ge(),{EMPTY_BUFFER:Yd,kWebSocket:Zd,NOOP:el}=oe(),{isBlob:We,isValidStatusCode:tl}=He(),{mask:Ni,toBuffer:Te}=ut(),W=Symbol("kByteLength"),rl=Buffer.alloc(4),nr=8*1024,Re,je=nr,Q=0,nl=1,sl=2,wn=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Q,this.onerror=el,this[Zd]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||rl,t.generateMask?t.generateMask(n):(je===nr&&(Re===void 0&&(Re=Buffer.alloc(nr)),Xd(Re,0,nr),je=0),n[0]=Re[je++],n[1]=Re[je++],n[2]=Re[je++],n[3]=Re[je++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[W]!==void 0?a=t[W]:(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]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],o?[d,e]:s?(Ni(e,n,d,i,a),[d]):(Ni(e,n,e,0,a),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=Yd;else{if(typeof e!="number"||!tl(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={[W]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Q?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):We(e)?(s=e.size,i=!1):(e=Te(e),s=e.length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[W]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Q?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):We(e)?(s=e.size,i=!1):(e=Te(e),s=e.length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[W]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Q?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Oi.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):We(e)?(a=e.size,c=!1):(e=Te(e),a=e.length,c=Te.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={[W]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==Q?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[W],this._state=sl,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(yn,this,a,s);return}this._bufferedBytes-=n[W];let o=Te(i);t?this.dispatch(o,t,n,s):(this._state=Q,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(il,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Oi.extensionName];this._bufferedBytes+=n[W],this._state=nl,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");yn(this,c,s);return}this._bufferedBytes-=n[W],this._state=Q,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Q&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][W],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][W],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)}};bi.exports=wn;function yn(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function il(r,e,t){yn(r,e,t),r.onerror(e)}});var qi=B((Lg,zi)=>{"use strict";var{kForOnEventAttribute:ht,kListener:En}=oe(),Di=Symbol("kCode"),Li=Symbol("kData"),Mi=Symbol("kError"),Bi=Symbol("kMessage"),Fi=Symbol("kReason"),Je=Symbol("kTarget"),Ui=Symbol("kType"),$i=Symbol("kWasClean"),ce=class{constructor(e){this[Je]=null,this[Ui]=e}get target(){return this[Je]}get type(){return this[Ui]}};Object.defineProperty(ce.prototype,"target",{enumerable:!0});Object.defineProperty(ce.prototype,"type",{enumerable:!0});var Pe=class extends ce{constructor(e,t={}){super(e),this[Di]=t.code===void 0?0:t.code,this[Fi]=t.reason===void 0?"":t.reason,this[$i]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Di]}get reason(){return this[Fi]}get wasClean(){return this[$i]}};Object.defineProperty(Pe.prototype,"code",{enumerable:!0});Object.defineProperty(Pe.prototype,"reason",{enumerable:!0});Object.defineProperty(Pe.prototype,"wasClean",{enumerable:!0});var Ve=class extends ce{constructor(e,t={}){super(e),this[Mi]=t.error===void 0?null:t.error,this[Bi]=t.message===void 0?"":t.message}get error(){return this[Mi]}get message(){return this[Bi]}};Object.defineProperty(Ve.prototype,"error",{enumerable:!0});Object.defineProperty(Ve.prototype,"message",{enumerable:!0});var gt=class extends ce{constructor(e,t={}){super(e),this[Li]=t.data===void 0?null:t.data}get data(){return this[Li]}};Object.defineProperty(gt.prototype,"data",{enumerable:!0});var ol={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ht]&&s[En]===e&&!s[ht])return;let n;if(r==="message")n=function(i,o){let a=new gt("message",{data:o?i:i.toString()});a[Je]=this,sr(e,this,a)};else if(r==="close")n=function(i,o){let a=new Pe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Je]=this,sr(e,this,a)};else if(r==="error")n=function(i){let o=new Ve("error",{error:i,message:i.message});o[Je]=this,sr(e,this,o)};else if(r==="open")n=function(){let i=new ce("open");i[Je]=this,sr(e,this,i)};else return;n[ht]=!!t[ht],n[En]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[En]===e&&!t[ht]){this.removeListener(r,t);break}}};zi.exports={CloseEvent:Pe,ErrorEvent:Ve,Event:ce,EventTarget:ol,MessageEvent:gt};function sr(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ir=B((Mg,Gi)=>{"use strict";var{tokenChars:pt}=He();function Z(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function al(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<r.length;u++)if(d=r.charCodeAt(u),o===void 0)if(l===-1&&pt[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 m=r.slice(c,l);d===44?(Z(e,m,t),t=Object.create(null)):o=m,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&pt[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),Z(t,r.slice(c,l),!0),d===44&&(Z(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=r.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(pt[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:n||(n=!0),s=!1}else if(i)if(pt[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&&r.charCodeAt(u-1)===61)i=!0;else if(l===-1&&pt[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 m=r.slice(c,l);n&&(m=m.replace(/\\/g,""),n=!1),Z(t,a,m),d===44&&(Z(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=r.slice(c,l);return o===void 0?Z(e,f,t):(a===void 0?Z(t,f,!0):n?Z(t,a,f.replace(/\\/g,"")):Z(t,a,f),Z(e,o,t)),e}function cl(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Gi.exports={format:cl,parse:al}});var dr=B((Ug,to)=>{"use strict";var dl=P("events"),ll=P("https"),ul=P("http"),ji=P("net"),fl=P("tls"),{randomBytes:hl,createHash:gl}=P("crypto"),{Duplex:Bg,Readable:Fg}=P("stream"),{URL:vn}=P("url"),_e=Ge(),pl=_n(),ml=Sn(),{isBlob:_l}=He(),{BINARY_TYPES:Hi,CLOSE_TIMEOUT:wl,EMPTY_BUFFER:or,GUID:yl,kForOnEventAttribute:kn,kListener:Sl,kStatusCode:El,kWebSocket:A,NOOP:Ji}=oe(),{EventTarget:{addEventListener:vl,removeEventListener:kl}}=qi(),{format:xl,parse:Il}=ir(),{toBuffer:Tl}=ut(),Vi=Symbol("kAborted"),xn=[8,13],de=["CONNECTING","OPEN","CLOSING","CLOSED"],Rl=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,v=class r extends dl{constructor(e,t,n){super(),this._binaryType=Hi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=or,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,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Qi(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hi.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,n){let s=new pl({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new ml(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",Cl),s.on("drain",Ol),s.on("error",Nl),s.on("message",bl),s.on("ping",Dl),s.on("pong",Ll),i.onerror=Ml,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yi),e.on("data",cr),e.on("end",Zi),e.on("error",eo),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[_e.extensionName]&&this._extensions[_e.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){z(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,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Xi(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||or,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||or,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[_e.extensionName]||(s.compress=!1),this._sender.send(e||or,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(v,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(v.prototype,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(v,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(v.prototype,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(v,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(v.prototype,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(v,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});Object.defineProperty(v.prototype,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(v.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(v.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[kn])return e[Sl];return null},set(e){for(let t of this.listeners(r))if(t[kn]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[kn]:!0})}})});v.prototype.addEventListener=vl;v.prototype.removeEventListener=kl;to.exports=v;function Qi(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wl,protocolVersion:xn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,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=s.autoPong,r._closeTimeout=s.closeTimeout,!xn.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${xn.join(", ")})`);let i;if(e instanceof vn)i=e;else try{i=new vn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._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(r._redirects===0)throw _;ar(r,_);return}let d=o?443:80,l=hl(16).toString("base64"),u=o?ll.request:ul.request,f=new Set,m;if(s.createConnection=s.createConnection||(o?Al:Pl),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&&(m=new _e({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=xl({[_e.extensionName]:m.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!Rl.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 p;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let _=n&&n.headers;if(n={...n,headers:{}},_)for(let[S,O]of Object.entries(_))n.headers[S.toLowerCase()]=O}else if(r.listenerCount("redirect")===0){let _=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!_||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,_||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=r._req=u(s),r._redirects&&r.emit("redirect",r.url,p)}else p=r._req=u(s);s.timeout&&p.on("timeout",()=>{z(r,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[Vi]||(p=r._req=null,ar(r,_))}),p.on("response",_=>{let S=_.headers.location,O=_.statusCode;if(S&&s.followRedirects&&O>=300&&O<400){if(++r._redirects>s.maxRedirects){z(r,p,"Maximum redirects exceeded");return}p.abort();let ee;try{ee=new vn(S,e)}catch{let L=new SyntaxError(`Invalid URL: ${S}`);ar(r,L);return}Qi(r,ee,t,n)}else r.emit("unexpected-response",p,_)||z(r,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,O)=>{if(r.emit("upgrade",_),r.readyState!==v.CONNECTING)return;p=r._req=null;let ee=_.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){z(r,S,"Invalid Upgrade header");return}let te=gl("sha1").update(l+yl).digest("base64");if(_.headers["sec-websocket-accept"]!==te){z(r,S,"Invalid Sec-WebSocket-Accept header");return}let L=_.headers["sec-websocket-protocol"],g;if(L!==void 0?f.size?f.has(L)||(g="Server sent an invalid subprotocol"):g="Server sent a subprotocol but none was requested":f.size&&(g="Server sent no subprotocol"),g){z(r,S,g);return}L&&(r._protocol=L);let E=_.headers["sec-websocket-extensions"];if(E!==void 0){if(!m){z(r,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=Il(E)}catch{z(r,S,"Invalid Sec-WebSocket-Extensions header");return}let re=Object.keys(T);if(re.length!==1||re[0]!==_e.extensionName){z(r,S,"Server indicated an extension that was not requested");return}try{m.accept(T[_e.extensionName])}catch{z(r,S,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[_e.extensionName]=m}r.setSocket(S,O,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,r):p.end()}function ar(r,e){r._readyState=v.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Pl(r){return r.path=r.socketPath,ji.connect(r)}function Al(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ji.isIP(r.host)?"":r.host),fl.connect(r)}function z(r,e,t){r._readyState=v.CLOSING;let n=new Error(t);Error.captureStackTrace(n,z),e.setHeader?(e[Vi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ar,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function In(r,e,t){if(e){let n=_l(e)?e.size:Tl(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${de[r.readyState]})`);process.nextTick(t,n)}}function Cl(r,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[A]!==void 0&&(t._socket.removeListener("data",cr),process.nextTick(Ki,t._socket),r===1005?t.close():t.close(r,e))}function Ol(){let r=this[A];r.isPaused||r._socket.resume()}function Nl(r){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",cr),process.nextTick(Ki,e._socket),e.close(r[El])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Wi(){this[A].emitClose()}function bl(r,e){this[A].emit("message",r,e)}function Dl(r){let e=this[A];e._autoPong&&e.pong(r,!this._isServer,Ji),e.emit("ping",r)}function Ll(r){this[A].emit("pong",r)}function Ki(r){r.resume()}function Ml(r){let e=this[A];e.readyState!==v.CLOSED&&(e.readyState===v.OPEN&&(e._readyState=v.CLOSING,Xi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Xi(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Yi(){let r=this[A];if(this.removeListener("close",Yi),this.removeListener("data",cr),this.removeListener("end",Zi),r._readyState=v.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[A]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Wi),r._receiver.on("finish",Wi))}function cr(r){this[A]._receiver.write(r)||this.pause()}function Zi(){let r=this[A];r._readyState=v.CLOSING,r._receiver.end(),this.end()}function eo(){let r=this[A];this.removeListener("error",eo),this.on("error",Ji),r&&(r._readyState=v.CLOSING,this.destroy())}});var io=B((zg,so)=>{"use strict";var $g=dr(),{Duplex:Bl}=P("stream");function ro(r){r.emit("close")}function Fl(){!this.destroyed&&this._writableState.finished&&this.destroy()}function no(r){this.removeListener("error",no),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Ul(r,e){let t=!0,n=new Bl({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(ro,n);return}let o=!1;r.once("error",function(c){o=!0,i(c)}),r.once("close",function(){o||i(s),process.nextTick(ro,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Fl),n.on("error",no),n}so.exports=Ul});var Tn=B((qg,oo)=>{"use strict";var{tokenChars:$l}=He();function zl(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&$l[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}oo.exports={parse:zl}});var go=B((Hg,ho)=>{"use strict";var ql=P("events"),lr=P("http"),{Duplex:Gg}=P("stream"),{createHash:Gl}=P("crypto"),ao=ir(),Ae=Ge(),Hl=Tn(),Wl=dr(),{CLOSE_TIMEOUT:jl,GUID:Jl,kWebSocket:Vl}=oe(),Ql=/^[+/0-9A-Za-z]{22}==$/,co=0,lo=1,fo=2,Rn=class extends ql{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jl,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wl,...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=lr.createServer((n,s)=>{let i=lr.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 n=this.emit.bind(this,"connection");this._removeListeners=Kl(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=co}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===fo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(mt,this);return}if(e&&this.once("close",e),this._state!==lo)if(this._state=lo,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(mt,this):process.nextTick(mt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{mt(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,n,s){t.on("error",uo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ce(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ce(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ql.test(i)){Ce(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ce(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){_t(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Hl.parse(c)}catch{Ce(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 Ae({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=ao.parse(l);m[Ae.extensionName]&&(f.accept(m[Ae.extensionName]),u[Ae.extensionName]=f)}catch{Ce(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,(m,p,_,S)=>{if(!m)return _t(t,p||401,_,S);this.completeUpgrade(u,i,d,e,t,n,s)});return}if(!this.options.verifyClient(f))return _t(t,401)}this.completeUpgrade(u,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Vl])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>co)return _t(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gl("sha1").update(t+Jl).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ae.extensionName]){let u=e[Ae.extensionName].params,f=ao.format({[Ae.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",uo),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(mt,this)})),a(l,s)}};ho.exports=Rn;function Kl(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let n of Object.keys(e))r.removeListener(n,e[n])}}function mt(r){r._state=fo,r.emit("close")}function uo(){this.destroy()}function _t(r,e,t,n){t=t||lr.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...n},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${lr.STATUS_CODES[e]}\r
|
|
14
|
+
`+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
|
|
15
15
|
`)+`\r
|
|
16
16
|
\r
|
|
17
|
-
`+
|
|
17
|
+
`+t)}function Ce(r,e,t,n,s,i){if(r.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ce),r.emit("wsClientError",o,t,e)}else _t(t,n,s,i)}});import{spawn as _u}from"node:child_process";import{existsSync as wu,openSync as yu}from"node:fs";import{mkdir as Su}from"node:fs/promises";import{dirname as Eu}from"node:path";import{fileURLToPath as vu}from"node:url";function Cn(r=x()){return wu(r.libEntry)?r.libEntry:vu(new URL("../index.ts",import.meta.url))}async function To(r={}){let e=r.paths??x(),t=r.entryOverride??Cn(e);await Su(Eu(e.logFile),{recursive:!0});let n=yu(e.logFile,"a"),i=t.endsWith(".ts")?["--import","tsx/esm",t,"--daemon"]:[t,"--daemon"],o=_u(process.execPath,i,{detached:!0,stdio:["ignore",n,n],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return ku.info("daemon spawned",{pid:o.pid,entry:t}),{pid:o.pid,entry:t}}var ku,On=j(()=>{"use strict";k();F();ku=w("spawn-daemon")});import{spawn as Ou}from"node:child_process";import{mkdir as Nu,unlink as bu,writeFile as Du}from"node:fs/promises";import{dirname as Lu,join as Mu}from"node:path";function mr(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Oo(r,e){return new Promise((t,n)=>{let s=Ou(r,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",n),s.on("close",o=>{o===0?t():n(new Error(`${r} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var pr,Dn,Ln,No=j(()=>{"use strict";k();pr=w("supervisor.launchd"),Dn="ai.coze.bridge",Ln={platform:"darwin",renderConfig(r){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>${Dn}</string>
|
|
23
23
|
<key>ProgramArguments</key>
|
|
24
24
|
<array>
|
|
25
|
-
<string>${
|
|
26
|
-
<string>${
|
|
25
|
+
<string>${mr(r.nodeBin)}</string>
|
|
26
|
+
<string>${mr(r.entry)}</string>
|
|
27
27
|
<string>--daemon</string>
|
|
28
28
|
</array>
|
|
29
29
|
<key>RunAtLoad</key>
|
|
@@ -33,12 +33,12 @@ var H0=Object.create;var fr=Object.defineProperty;var j0=Object.getOwnPropertyDe
|
|
|
33
33
|
<key>ThrottleInterval</key>
|
|
34
34
|
<integer>10</integer>
|
|
35
35
|
<key>StandardOutPath</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${mr(r.logFile)}</string>
|
|
37
37
|
<key>StandardErrorPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${mr(r.logFile)}</string>
|
|
39
39
|
</dict>
|
|
40
40
|
</plist>
|
|
41
|
-
`},configPath(r){return
|
|
41
|
+
`},configPath(r){return Mu(r.homeDir,"Library","LaunchAgents",`${Dn}.plist`)},async install(r){let e=this.configPath(r);await Nu(Lu(e),{recursive:!0}),await Du(e,this.renderConfig(r),"utf8"),pr.info("plist written",{plistPath:e}),await Oo("launchctl",["load","-w",e]),pr.info("launchd job loaded",{label:Dn})},async uninstall(r){let e=this.configPath(r);await Oo("launchctl",["unload","-w",e]).catch(t=>pr.warn("launchctl unload failed (ignored)",{err:String(t)})),await bu(e).catch(t=>{if(t.code!=="ENOENT")throw t}),pr.info("launchd job removed",{plistPath:e})}}});import{spawn as Bu}from"node:child_process";import{mkdir as Fu,unlink as Uu,writeFile as $u}from"node:fs/promises";import{dirname as zu,join as qu}from"node:path";function yr(r,e){return new Promise((t,n)=>{let s=Bu(r,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",n),s.on("close",o=>{o===0?t():n(new Error(`${r} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var _r,wr,Mn,bo=j(()=>{"use strict";k();_r=w("supervisor.systemd"),wr="coze-bridge.service",Mn={platform:"linux",renderConfig(r){return`[Unit]
|
|
42
42
|
Description=Coze Bridge daemon
|
|
43
43
|
After=network.target
|
|
44
44
|
|
|
@@ -52,7 +52,7 @@ StandardError=append:${r.logFile}
|
|
|
52
52
|
|
|
53
53
|
[Install]
|
|
54
54
|
WantedBy=default.target
|
|
55
|
-
`},configPath(r){return
|
|
55
|
+
`},configPath(r){return qu(r.homeDir,".config","systemd","user",wr)},async install(r){let e=this.configPath(r);await Fu(zu(e),{recursive:!0}),await $u(e,this.renderConfig(r),"utf8"),_r.info("systemd unit written",{unitPath:e}),await yr("systemctl",["--user","daemon-reload"]),await yr("systemctl",["--user","enable","--now",wr]),_r.info("systemd unit enabled",{unitName:wr})},async uninstall(r){let e=this.configPath(r);await yr("systemctl",["--user","disable","--now",wr]).catch(t=>_r.warn("systemctl disable failed (ignored)",{err:String(t)})),await Uu(e).catch(t=>{if(t.code!=="ENOENT")throw t}),await yr("systemctl",["--user","daemon-reload"]).catch(()=>{}),_r.info("systemd unit removed",{unitPath:e})}}});import{spawn as Gu}from"node:child_process";import{join as Hu}from"node:path";function Do(r,e){return new Promise((t,n)=>{let s=Gu(r,e,{stdio:["ignore","pipe","pipe"],shell:!1}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",n),s.on("close",o=>{o===0?t():n(new Error(`${r} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Bn,Sr,Fn,Lo=j(()=>{"use strict";k();Bn=w("supervisor.taskscheduler"),Sr="CozeBridge",Fn={platform:"win32",renderConfig(r){return`<?xml version="1.0" encoding="UTF-16"?>
|
|
56
56
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
57
57
|
<RegistrationInfo>
|
|
58
58
|
<Description>Coze Bridge daemon</Description>
|
|
@@ -76,20 +76,21 @@ WantedBy=default.target
|
|
|
76
76
|
</Exec>
|
|
77
77
|
</Actions>
|
|
78
78
|
</Task>
|
|
79
|
-
`},configPath(r){return
|
|
79
|
+
`},configPath(r){return Hu(r.homeDir,".coze","bridge","task.xml")},async install(r){let e=`"${r.nodeBin}" "${r.entry}" --daemon`;await Do("schtasks",["/Create","/SC","ONLOGON","/TN",Sr,"/TR",e,"/RU",r.userName,"/F"]),Bn.info("task scheduler entry created",{task:Sr})},async uninstall(r){await Do("schtasks",["/Delete","/TN",Sr,"/F"]).catch(e=>Bn.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Bn.info("task scheduler entry removed",{task:Sr})}}});var Un={};Ir(Un,{buildContext:()=>Vu,getSupervisor:()=>Ju,launchdSupervisor:()=>Ln,systemdSupervisor:()=>Mn,taskSchedulerSupervisor:()=>Fn});import{homedir as Wu,userInfo as ju}from"node:os";function Ju(r=process.platform){switch(r){case"darwin":return Ln;case"linux":return Mn;case"win32":return Fn;default:throw new Error(`unsupported platform for OS supervisor: ${r}`)}}function Vu(){let r=x();return{nodeBin:process.execPath,entry:Cn(r),logFile:r.logFile,homeDir:Wu(),userName:ju().username}}var $n=j(()=>{"use strict";F();On();No();bo();Lo()});ue();k();import{readdir as aa}from"node:fs/promises";import{mkdir as ra,writeFile as na}from"node:fs/promises";import{join as sa}from"node:path";var ia={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function be(r,e,t,n){await ra(r,{recursive:!0});let s=ia[e],i=sa(r,s),o=oa(e,t,n);return await na(i,o,"utf8"),i}function oa(r,e,t){let n=`# Coze Agent: ${e}
|
|
80
80
|
|
|
81
81
|
> framework: \`${r}\`
|
|
82
82
|
|
|
83
|
-
`,
|
|
84
|
-
`)?
|
|
83
|
+
`,s=t?.trim()?t.endsWith(`
|
|
84
|
+
`)?t:`${t}
|
|
85
85
|
`:`_No instructions provided._
|
|
86
|
-
`;return`${
|
|
86
|
+
`;return`${n}---
|
|
87
87
|
|
|
88
|
-
${x}`}var ve=R("agent-detail-sync"),$t=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await fa(i)}catch(x){ve.info("agents dir not found, skip detail sync",{root:i,err:String(x)});return}ve.info("starting detail sync",{reason:e,count:a.length});for(let x of a)try{await this.syncOne(x)}catch(f){ve.warn("detail sync failed for agent, skipping",{agentId:x,err:String(f)})}ve.info("detail sync done",{reason:e})}async syncOne(e){let i=await ae(e,this.opts.paths);if(!i){ve.info("detail sync: agent config missing, skip",{agentId:e});return}let a;try{a=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(l){ve.warn("detail RPC failed, using local data",{agentId:e,err:String(l)});return}if(a.agentId&&a.agentId!==e){ve.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:a.agentId});return}let x=!1,f=!1;if(a.agentName&&a.agentName!==i.agentName&&(i.agentName=a.agentName,x=!0),a.description!==void 0&&a.description!==i.description&&(i.description=a.description,x=!0),a.cozeIdentity&&a.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=a.cozeIdentity,x=!0,f=!0),a.deployType&&ve.info("detail.deployType",{agentId:e,deployType:a.deployType}),!x){ve.debug("detail sync: no diff",{agentId:e});return}await ge(i,this.opts.paths),ve.info("detail sync: config updated",{agentId:e,identityChanged:f,agentName:i.agentName}),f&&(await at(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ue();import{spawn as zs}from"node:child_process";import{lstat as hr,mkdir as ua,readFile as Ms,readdir as da,rm as la,stat as ha,writeFile as ga}from"node:fs/promises";import{join as Le,normalize as pa,relative as qs,resolve as ma,sep as Us}from"node:path";function Dt(r){return r?.cozeDeployType==="cloud"?"cloud":"local"}function Is(r){let{_meta:e,...i}=r;return{stripped:i,meta:e}}function xt(r){if(!r?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return r.cozeAgentId}var E=class extends Error{code;retriable;cause;constructor(e,i,a){super(i),this.name="BridgeError",this.code=e,this.retriable=a?.retriable??!1,a?.cause!==void 0&&(this.cause=a.cause)}};K();oe();function Ve(r,e){if(Dt(r)!=="cloud")throw new E("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Qt(r){return r.replace(/[^A-Za-z0-9._-]+/g,"-")}var Ps="https://llm-gateway.coze.cn",ct="auto";function Ts(r){return{model:r.model??ct,...r.modelToken?{modelToken:r.modelToken}:{}}}function Ls(r){return!r||r===ct}function Ns(r){let e={};return r.modelToken&&(e.ANTHROPIC_BASE_URL=Ps,e.ANTHROPIC_AUTH_TOKEN=r.modelToken),Ls(r.model)||(e.ANTHROPIC_MODEL=r.model),e}function Rs(r){let e=[];return Ls(r.model)||e.push("-c",`model="${r.model}"`),r.modelToken&&(e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Ps}/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 Os(r){return r.modelToken?{OPENAI_API_KEY:r.modelToken}:{}}var fe=R("agent-handlers"),Bs=5*1024*1024,wa=1,_a=6,ya=new Set(["node_modules",".git",".coze","dist","build",".next"]),tn=class{constructor(e){this.opts=e}opts;async listSkills(e){Ve(e._meta,"_agent/listSkills");let i=xt(e._meta),a=await this.loadAgentCfg(i),x=a?.workspace??Te(i).workspace,f=a?.skills??[],l=[];for(let h of f){let m=Le(x,h.relPath,"SKILL.md");await ha(m).then(b=>b.isFile()).catch(()=>!1)&&l.push({skillId:h.skillId,skillName:h.skillName,downloadUrl:h.downloadUrl??"",...h.description?{description:h.description}:{},...h.version?{version:h.version}:{}})}return{skills:l}}async addSkills(e){Ve(e._meta,"_agent/addSkills");let i=xt(e._meta),a=await this.requireAgentCfg(i),x=e.skills??[],f=[...a.skills??[]],l=new Map(f.map((m,_)=>[m.skillId,_])),h=[];for(let m of x){if(!m.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let _=ba(m.skillName),b=va(a.framework),w=Le(b,_),C=Le(a.workspace,w);await ua(C,{recursive:!0});let k=await Ea(m.downloadUrl);Da(k)?await ka(k,C):await ga(Le(C,"SKILL.md"),k.toString("utf8"),"utf8");let T={skillId:m.skillId,skillName:m.skillName,relPath:w,installedAt:Date.now(),...m.description?{description:m.description}:{},...m.version?{version:m.version}:{},...m.downloadUrl?{downloadUrl:m.downloadUrl}:{}},L=l.get(m.skillId);L!==void 0?f[L]=T:(l.set(m.skillId,f.length),f.push(T)),h.push(m),fe.info("skill installed",{agentId:i,skillId:m.skillId,skillName:m.skillName,relPath:w})}return await Xt(i,f),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:h}}async removeSkills(e){Ve(e._meta,"_agent/removeSkills");let i=xt(e._meta),a=await this.requireAgentCfg(i),x=new Set(e.skillIds??[]),f=a.skills??[],l=[];for(let h of f){if(!x.has(h.skillId)){l.push(h);continue}let m=Le(a.workspace,h.relPath);await la(m,{recursive:!0,force:!0}),fe.info("skill removed",{agentId:i,skillId:h.skillId,relPath:h.relPath})}return await Xt(i,l),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[x,f]of a.sessions)if(!(!f.downstream||!f.acpSessionId)){f.loadingSession=!0;try{await f.downstream.sessionLoad({sessionId:f.acpSessionId,cwd:a.workspace}),fe.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:x,acpId:f.acpSessionId})}catch(l){fe.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:x,acpId:f.acpSessionId,err:String(l)})}finally{f.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return fe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await ae(i);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(fe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await ge(a),await at(a.workspace,a.framework,i,e.cozeIdentity),fe.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 ae(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await ge(a),fe.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}):(fe.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Ve(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:ct,a=await ae(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await ge(a),fe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let x=this.opts.agents.get(e.agentId);return x?(await x.msgQueue.enqueue(async()=>{x.model=i,await x.killAllRuntimes(`switchModel: ${i}`)}),fe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:i}),{ok:!0}):(fe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0})}async getFileTree(e){Ve(e._meta,"_agent/getFileTree");let i=e._meta,a=xt(i),x=await this.resolveWorkspace(a),f=e.filePath??"",l=this.safeJoin(x,f),h=await hr(l).catch(()=>null);if(!h)throw new E("IPC_BAD_REQUEST",`path not found: ${f}`);if(h.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${f}`);let m=Pa(e.depth);return h.isDirectory()?{tree:await Fs(x,l,f,m)}:{tree:[{name:Ta(f),path:Ks(f||"."),isDir:!1,size:h.size,modifiedAt:Math.floor(h.mtimeMs)}]}}async getFileContent(e){Ve(e._meta,"_agent/getFileContent");let i=xt(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new E("IPC_BAD_REQUEST","filePath required");let x=this.safeJoin(a,e.filePath),f=await hr(x).catch(()=>null);if(!f||!f.isFile())throw new E("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(f.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(f.size>Bs)throw new E("IPC_BAD_REQUEST",`file too large: ${f.size} bytes (max ${Bs})`);let l=await Ms(x);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:f.size}:{content:l.toString("utf8"),encoding:"utf-8",size:f.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await ae(e).catch(()=>null))?.workspace??Te(e).workspace}safeJoin(e,i){let a=ma(e,i||"."),x=qs(e,a);if(x.startsWith("..")||x===".."||x.startsWith(`..${Us}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return ae(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 ba(r){let e=Qt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new E("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function va(r){return r==="claude-code"?Le(".claude","skills"):Le(".agents","skills")}var Sa=3e4,Ca=50*1024*1024,nn=3e4;async function Ea(r){if(!r)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);en(e);let i=Aa(r);return en(i.length),i}if(r.startsWith("file:")){let e=new URL(r).pathname,i=await Ms(e);return en(i.length),i}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),Sa);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 x=await a.arrayBuffer();return en(x.byteLength),Buffer.from(x)}finally{clearTimeout(i)}}throw new E("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function en(r){if(r>Ca)throw new E("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function Aa(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 Da(r){return r.length>=2&&r[0]===31&&r[1]===139}async function ka(r,e){await Ia(r),await new Promise((i,a)=>{let x=zs("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),f="";x.stderr?.on("data",h=>{f+=String(h)});let l=setTimeout(()=>{x.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar extract timeout (${nn}ms)`))},nn);x.on("error",h=>{clearTimeout(l),a(new E("IPC_BAD_REQUEST",`tar spawn failed: ${h.message}`,{cause:h}))}),x.on("exit",h=>{clearTimeout(l),h===0?i():a(new E("IPC_BAD_REQUEST",`tar exit ${h}${f?`: ${f.trim().slice(0,200)}`:""}`))}),x.stdin?.end(r)})}async function Ia(r){let e=await new Promise((i,a)=>{let x=zs("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),f="",l="";x.stdout?.on("data",m=>{f+=String(m)}),x.stderr?.on("data",m=>{l+=String(m)});let h=setTimeout(()=>{x.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar list timeout (${nn}ms)`))},nn);x.on("error",m=>{clearTimeout(h),a(new E("IPC_BAD_REQUEST",`tar list spawn failed: ${m.message}`))}),x.on("exit",m=>{clearTimeout(h),m===0?i(f):a(new E("IPC_BAD_REQUEST",`tar list exit ${m}${l?`: ${l.trim().slice(0,200)}`:""}`))}),x.stdin?.end(r)});for(let i of e.split(`
|
|
89
|
-
`)
|
|
90
|
-
`}
|
|
91
|
-
`);this.buffer=i.pop()??"";let a=[];for(let x of i){let f=x.replace(/\r$/,"").trim();if(f)try{a.push(JSON.parse(f))}catch(l){this.onError?.({line:f,error:l})}}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 Vs={"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","session/request_permission":"session.requestPermission",initialize:"initialize"},od=Object.fromEntries(Object.entries(Vs).map(([r,e])=>[e,r])),Oa={"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"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},ut=class{seq=0;next(e,i){this.seq+=1;let a=Vs[e]??Ba(e),x=Oa[a]??[],f=[a,String(this.seq)];if(x.length>0){let l=x.map(m=>Js(i?.[m]??"")),h=za(l).join(":");h&&f.push(h)}else i&&Object.values(i).some(l=>l)&&f.push(Object.values(i).filter(Boolean).map(l=>Js(String(l))).join(":"));return f.join("_")}reset(){this.seq=0}};function Ba(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Js(r){return r.replace(/[:_\s]+/g,"-")}function za(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}K();var qa=3e4;function Ys(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var Fe=class{constructor(e){this.opts=e;this.log=R(`downstream.${this.constructor.name}`),this.decoder=new cn({onError:i=>this.log.warn("decode line failed",{line:i.line})})}opts;child;decoder;pending=new Map;idAllocator=new ut;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;sanitizeEnv(e){return e}async start(){if(this.child)throw new E("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=Ma(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 x of this.decoder.push(a))this.dispatch(x)}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{this.log.debug("stderr",{text:a.trimEnd()})}),i.on("exit",(a,x)=>{this.stopped=!0,this.failAllPending(new E("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${x})`));for(let f of this.exitHandlers)f(a,x)}),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(f=>i.once("exit",()=>f()));Ys(i.pid,"SIGTERM");let x=setTimeout(()=>{i.killed||Ys(i.pid,"SIGKILL")},5e3);try{await a}finally{clearTimeout(x)}}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(sn("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(Ye(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=qa){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let x=this.idAllocator.next(e),f=It(x,e,i),l=a>0&&Number.isFinite(a);return new Promise((h,m)=>{let _=l?setTimeout(()=>{this.pending.delete(x),m(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(x,{resolve:h,reject:m,timer:_,method:e});try{this.writeFrame(f)}catch(b){_&&clearTimeout(_),this.pending.delete(x),m(b)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new E("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Ws(e))}dispatch(e){if(an(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?i.reject(Gs(e.error)):i.resolve(e.result);return}if(js(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(Hs(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(Ye(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(Ye(e.id,xn(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var Ua="@agentclientprotocol/claude-agent-acp@latest";function Fa(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 fn=class extends Fe{framework="claude-code";constructor(e){let i=e.command??"npx",a=e.args??["-y",Ua],x={command:i,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(x)}sanitizeEnv(e){return Fa(e)}};import{mkdtempSync as Ka,rmSync as Ha}from"node:fs";import{tmpdir as ja}from"node:os";import{join as Ga}from"node:path";var Wa="@zed-industries/codex-acp@latest",un=class extends Fe{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=e.command??"npx",a=e.args??["-y",Wa],x=e.extraArgs?[...a,...e.extraArgs]:a,f=e.isolateCodexHome?Ka(Ga(ja(),"coze-bridge-codex-home-")):void 0,l=f?{...e.env??{},CODEX_HOME:f}:e.env,h={command:i,args:x,cwd:e.cwd,...l?{env:l}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=f}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{Ha(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};import{spawn as Xs}from"node:child_process";K();var dn=class extends Fe{framework="openclaw";registerLog;profile;agentId;sessionName;registered=!1;constructor(e){let i=e.profile??"coze",a=e.sessionName??"default",x=["--profile",i,"acp","--session",`agent:${e.agentId}:${a}`],f={command:e.command,args:x,cwd:e.cwd,...e.env?{env:e.env}:{}};super(f),this.profile=i,this.agentId=e.agentId,this.sessionName=a,this.registerLog=R("downstream.openclaw.register")}async start(){await this.registerAgent().catch(e=>{this.registerLog.warn("openclaw agents add failed (will continue to acp anyway)",{agentId:this.agentId,err:String(e)})}),await super.start()}registerAgent(){return new Promise((e,i)=>{let a=Xs(this.opts.command,["--profile",this.profile,"agents","add",this.agentId,"--workspace",this.opts.cwd,"--non-interactive"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),x="";a.stderr?.on("data",f=>{x+=f.toString("utf8")}),a.on("error",i),a.on("close",f=>{f===0?(this.registered=!0,this.registerLog.info("agent registered",{agentId:this.agentId,profile:this.profile}),e()):i(new E("AGENT_SPAWN_FAILED",`openclaw agents add ${this.agentId} exited ${f}: ${x.trim()}`))})})}async cleanup(e){this.registered&&await new Promise(i=>{let a=Xs(this.opts.command,["--profile",this.profile,"agents","delete",this.agentId,"--force"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),x="";a.stderr?.on("data",f=>{x+=f.toString("utf8")}),a.on("error",f=>{this.registerLog.warn("openclaw agents delete failed (best-effort)",{agentId:this.agentId,err:String(f)}),i()}),a.on("close",f=>{f===0?this.registerLog.info("agent unregistered",{agentId:this.agentId}):this.registerLog.warn("openclaw agents delete non-zero exit",{agentId:this.agentId,code:f,stderr:x.trim()}),this.registered=!1,i()})})}get acpSessionName(){return this.sessionName}};K();oe();var ln=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 hn=class{agentId;framework;workspace;deployType;msgQueue;sessions=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",this.msgQueue=new ln}async dispose(e){this.status="stopped",this.msgQueue.dispose(new Error(`AgentSession disposed${e?`: ${e}`:""}`)),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let i=[];for(let[,a]of this.sessions)Pt(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Pt(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}var Ke=R("agent-manager"),Va=(r,e,i,a,x,f)=>{switch(r){case"claude-code":{let l=x?Ns(x):void 0;return new fn({cwd:i,...l&&Object.keys(l).length>0?{env:l}:{}})}case"codex":{let l=x?Rs(x):[],h=x?Os(x):void 0,m=!!x;return new un({cwd:i,...l.length>0?{extraArgs:l}:{},...h&&Object.keys(h).length>0?{env:h}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new dn({command:e,cwd:i,agentId:a,...f?{sessionName:Qt(f)}:{}})}};function Ya(r){return r==="claude-code"||r==="codex"}var Xa={path:"",version:"cloud-deployed"},Za={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},$a=2e4,gn=class{paths;config;registry;factory;createTimeoutMs;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Va,this.createTimeoutMs=e.createTimeoutMs??$a}async createAgent(e){if(!e.agentId)throw new E("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new E("IPC_BAD_REQUEST","framework required");let i=Dt(e._meta)==="cloud";if(i&&e.framework==="openclaw")return Ke.info("cloud-deployed openclaw, ack without local spawn",{agentId:e.agentId,framework:e.framework}),{ok:!0,agentId:e.agentId,framework:e.framework};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")Ke.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(w=>Ke.warn("dispose stale agent failed (ignored)",{err:String(w)})),this.registry.unregister(e.agentId);else return Ke.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`);let x=Te(e.agentId,this.paths),f=e.workspace??x.workspace,l=Dt(e._meta),h=new AbortController,m=setTimeout(()=>h.abort(new E("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),_,b=!1;try{let w=()=>{if(h.signal.aborted)throw h.signal.reason instanceof Error?h.signal.reason:new E("AGENT_TIMEOUT","_agent/create aborted")};await gr(x.root,{recursive:!0}),await gr(f,{recursive:!0}),await gr(x.logs,{recursive:!0}),w(),await at(f,e.framework,e.agentId,e.cozeIdentity),w();let C=await ae(e.agentId,this.paths).catch(()=>null),k=Ts({model:e.model??C?.model});if(_=new hn({agentId:e.agentId,framework:e.framework,workspace:f,model:k.model??ct,deployType:l}),_.status="ok",C?.sessions){for(let[F,Q]of Object.entries(C.sessions))_.sessions.set(F,{acpSessionId:Q.acpSessionId,modelToken:Q.modelToken,tokenGeneratedAt:Q.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1});let L=Object.keys(C.sessions).length;L>0&&Ke.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:L})}this.registry.register(_),b=!0;let T={agentId:e.agentId,framework:e.framework,workspace:f,cozeIdentity:e.cozeIdentity,createdAt:C?.createdAt??Date.now(),sessions:C?.sessions??{},model:k.model};return l==="cloud"&&(T.deployType="cloud"),C?.skills&&(T.skills=C.skills),C?.agentName&&(T.agentName=C.agentName),C?.description&&(T.description=C.description),await ge(T,this.paths),Ke.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:l}),{ok:!0,agentId:e.agentId,workspace:f,framework:e.framework}}catch(w){throw Ke.error("agent create failed, rolling back",{agentId:e.agentId,err:String(w)}),b&&_&&(await _.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ja(x.root,{recursive:!0,force:!0}).catch(C=>Ke.warn("rm agent dir failed (ignored)",{err:String(C)})),w instanceof E?w:new E("AGENT_SPAWN_FAILED",String(w),{cause:w})}finally{clearTimeout(m)}}async spawnSessionDownstream(e,i,a){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Ya(e.framework))f=Xa;else throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let l=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,h=this.factory(e.framework,f.path,e.workspace,e.agentId,l,a);try{return await h.start(),await h.initialize(Za),h}catch(m){throw await h.stop("spawnSessionDownstream failed").catch(()=>{}),m instanceof E?m:new E("AGENT_SPAWN_FAILED",m instanceof Error?m.message:String(m),{cause:m})}}};K();import{spawn as Qa}from"node:child_process";import{constants as Zs,access as ex}from"node:fs/promises";import{delimiter as tx,join as nx}from"node:path";var rx=R("framework-detector"),$s={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sx=[".exe",".cmd",".bat",".ps1"],Tt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Qa,access:e.access??ex}}async detect(e){let i=$s[e],a=await this.which(i);if(!a)return rx.debug("framework binary not found",{framework:e,bin:i}),null;let x=await this.probeVersion(a);return{path:a,version:x}}async detectAll(){let e=await Promise.all(Object.keys($s).map(async a=>[a,await this.detect(a)])),i={};for(let[a,x]of e)x&&(i[a]=x);return i}async which(e){let i=this.env.pathEnv.split(tx).filter(Boolean),a=this.env.platform==="win32"?["",...sx]:[""];for(let x of i)for(let f of a){let l=nx(x,e+f);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?Zs.F_OK:Zs.X_OK;return await this.env.access(e,i),!0}catch{return!1}}async probeVersion(e){return new Promise(i=>{let a="",x=!1,f,l=h=>{x||(x=!0,f&&clearTimeout(f),i(h.trim()||"unknown"))};try{let h=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});f=setTimeout(()=>{h.kill("SIGKILL"),l("unknown")},5e3),h.stdout?.on("data",m=>{a+=m.toString("utf8")}),h.on("error",()=>l("unknown")),h.on("close",()=>{let m=ox(a).split(/\r?\n/)[0]??"";l(m)})}catch{l("unknown")}})}},ix=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function ox(r){return r.replace(ix,"")}ur();oe();var ax=10*6e4;function Qs(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ax:e}function pn(r){return Gt(r??H().configFile)}function Lt(r,e){return Wt(e??H().configFile,r)}import{randomBytes as xx}from"node:crypto";Ue();var ei={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",DELETE:"_agent/delete"};K();var W=R("core"),cx=3e4,fx=3e4,mn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new ut;pendingUpstream=new Map;pendingBridge=new Map;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,i){this.extensions[e]=i}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.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),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){W.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)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,i,a){let x=a.downstream;x&&(x.onUpdate(f=>{a.loadingSession||this.forwardUpdate(e,f)}),x.onAgentRequest(f=>{this.handleAgentRequest(e,x,f)}),x.onExit((f,l)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:f,signal:l}),Pt(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(an(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;try{if(e.method.startsWith("_agent/")){let a=this.extensions[e.method];if(!a){i!==null?await this.sendError(i,G.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let x=await a(e,this);i!==null&&await this.upstream.send(ft(i,x));return}if(e.method.startsWith("session/")){let a=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(ft(i,a));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,G.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(a){W.error("handleFrame failed",{method:e.method,err:String(a)}),i!==null&&await this.upstream.send(Ye(i,xn(a)))}}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 x=this.agents.get(a);if(!x)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}`);if(e.method==="session/cancel")return this.dispatchSessionCall(x,e.method,i);let f=Date.now(),l=!1;try{let h=await x.msgQueue.enqueue(()=>this.dispatchSessionCall(x,e.method,i));return l=!0,h}finally{W.info("session call done",{agentId:x.agentId,method:e.method,durationMs:Date.now()-f,ok:l})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:x}=Is(a);switch(i){case"session/new":{let f=ux();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:f}),{sessionId:f}}case"session/load":{let f=x;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:f.sessionId}),{}}case"session/prompt":{let f=x,l=f.sessionId;if(!l)throw new E("IPC_BAD_REQUEST","session/prompt: missing sessionId");let h=await this.ensureRuntime(e,l);if(await this.ensureDownstream(e,l,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 _=await h.downstream.sessionPrompt({...f,sessionId:h.acpSessionId});return h.lastActiveAt=Date.now(),_}finally{e.activeTriggers.delete(h.acpSessionId),h.downstream?.isAlive()&&this.armIdleTimer(e,l,h)}}case"session/cancel":{let l=x.sessionId;if(!l)throw new E("IPC_BAD_REQUEST","session/cancel: missing sessionId");let h=e.sessions.get(l);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 f={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1};return e.sessions.set(i,f),await this.persistSessionMapping(e),f}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let x=await this.sendRequest(ei.GEN_MODEL_TOKEN,a,fx);if(!x?.modelToken)throw new E("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return x.modelToken}catch(x){throw x instanceof E&&x.code==="MODEL_TOKEN_GEN_FAILED"?x:new E("MODEL_TOKEN_GEN_FAILED",x instanceof Error?x.message:String(x),{cause:x})}}async ensureDownstream(e,i,a){if(Pt(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new E("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let x=await this.sessionSpawner(e,a.modelToken,i);if(a.downstream=x,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await x.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(f){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(f)}),a.acpSessionId=void 0;let l=await x.sessionNew({cwd:e.workspace});a.acpSessionId=l.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let f=await x.sessionNew({cwd:e.workspace});a.acpSessionId=f.sessionId,await this.persistSessionMapping(e)}}armIdleTimer(e,i,a){Pt(a),a.idleTimer=setTimeout(()=>{W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:i});let x=a.downstream;a.downstream=void 0,a.idleTimer=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId),x&&x.stop("idle timeout").catch(f=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(f)}))},this.sessionIdleTimeoutMs),a.idleTimer.unref?.()}forwardUpdate(e,i){let a=i.sessionId,x=this.reverseSessionId(e,a);if(!x){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let f={cozeAgentId:e.agentId},l=e.activeTriggers.get(a);l&&(f.cozeTriggerMsgId=l),this.upstream.send(sn("session/update",{...i,sessionId:x,_meta:f})).catch(h=>W.warn("forward update failed",{agentId:e.agentId,err:String(h)}))}handleAgentRequest(e,i,a){if(a.method==="session/request_permission"){this.forwardPermissionRequest(e,i,a);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:a.method}),i.respondAgentRequestError(a.id,{code:G.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}forwardPermissionRequest(e,i,a){let x=this.upstreamIds.next("session/request_permission"),f=a.params??{},h=f.sessionId,m=h?e.activeTriggers.get(h):void 0,_={cozeAgentId:e.agentId};m&&(_.cozeTriggerMsgId=m);let b=h?this.reverseSessionId(e,h):void 0,w={...f,...b?{sessionId:b}:{},_meta:_};this.pendingUpstream.set(x,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),this.upstream.send(It(x,"session/request_permission",w)).catch(C=>{this.pendingUpstream.delete(x),W.error("forward permission request failed",{agentId:e.agentId,err:String(C)}),i.respondAgentRequestError(a.id,{code:G.INTERNAL_ERROR,message:`upstream send failed: ${String(C)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let i=this.pendingUpstream.get(e.id);if(i){this.pendingUpstream.delete(e.id),e.error?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 on(e.error)):a.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=cx){let x=this.upstreamIds.next(e);return new Promise((f,l)=>{let h=setTimeout(()=>{this.pendingBridge.delete(x),l(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(x,{method:e,resolve:f,reject:l,timer:h}),this.upstream.send(It(x,e,i)).catch(m=>{let _=this.pendingBridge.get(x);_&&(clearTimeout(_.timer),this.pendingBridge.delete(x)),l(m)})})}async persistSessionMapping(e){if(this.paths)try{let i=new Map;for(let[a,x]of e.sessions){let f={modelToken:x.modelToken,tokenGeneratedAt:x.tokenGeneratedAt};x.acpSessionId&&(f.acpSessionId=x.acpSessionId),i.set(a,f)}await lr(e.agentId,i,this.paths)}catch(i){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(i)})}}reverseSessionId(e,i){for(let[a,x]of e.sessions.entries())if(x.acpSessionId===i)return a}sendError(e,i,a){return this.upstream.send(Ye(e,{code:i,message:a}))}};function ux(){return xx(16).toString("hex")}K();oe();import{randomBytes as dx}from"node:crypto";import{chmod as lx,mkdir as hx,writeFile as ti}from"node:fs/promises";import{createServer as gx}from"node:http";import{dirname as px}from"node:path";var mx=1e6,pr=R("ipc"),wn=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??H()}async start(){this.token=dx(32).toString("hex");let e=gx((a,x)=>{this.dispatch(a,x)});this.server=e,await new Promise((a,x)=>{e.once("error",x),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(),pr.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(x=>x?a(x):i())}),this.server=null)}async persistAuthFiles(){await hx(px(this.paths.portFile),{recursive:!0}),await ti(this.paths.portFile,String(this.port),"utf8"),await ti(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await lx(this.paths.tokenFile,384)}catch(e){pr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Nt(i,401,{error:"unauthorized"});return}let x=`${e.method} ${(e.url??"").split("?")[0]}`,f=this.routes.get(x);if(!f){Nt(i,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await _x(e)}catch(h){Nt(i,400,{error:"invalid json",detail:String(h)});return}try{let h=await f.handler(l,e);Nt(i,200,h??{ok:!0})}catch(h){pr.error("IPC handler failed",{key:x,err:String(h)}),Nt(i,500,{error:h instanceof Error?h.message:String(h)})}}};function Nt(r,e,i){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(i))}async function _x(r){let e=[],i=0;for await(let x of r){let f=x;if(i+=f.length,i>mx)throw new Error("body too large");e.push(f)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var ko=Pe(di(),1);var Qc=Pe(ao(),1),ef=Pe(Rn(),1),tf=Pe(ht(),1),nf=Pe(Ir(),1),rf=Pe(Lr(),1),sf=Pe(Mr(),1),mo=Pe(Mn(),1),of=Pe(po(),1);var wo=mo.default;K();var Un="1008033",_o="1289";var yo="pbbp2",bo="https://www.coze.cn",vo="/api/coze_claw/resource/get_frontier_key",af="https://www.coze.cn",xf="wss://frontier.coze.cn";function So(r){return r??process.env.COZE_BRIDGE_HANDSHAKE_URL??af}function Co(r){return r??process.env.COZE_BRIDGE_FRONTIER_URL??xf}function Fn(r){let e={},i=r?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,a=r?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return i&&(e["x-tt-env"]=i),a&&(e["x-use-ppe"]=a),e}var te=R("upstream.frontier"),Ao="application/json",Do="none",Kn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){te.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:bo,...Fn(this.opts.ppeOverride)};class i extends wo{constructor(h){super(h,yo,{headers:e})}send(h,...m){if(Ds("debug"))try{let _;typeof h=="string"?_=Buffer.from(h,"utf8"):h instanceof Buffer?_=h:h instanceof ArrayBuffer?_=new Uint8Array(h):ArrayBuffer.isView(h)?_=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):_=new Uint8Array(0);let b=Buffer.from(_.slice(0,128)).toString("hex");te.debug("WS raw frame out",{bytes:_.byteLength,headHex:b})}catch(_){te.warn("WS raw frame dump failed",{err:String(_)})}super.send(h,...m)}}let a=Co(this.opts.urlOverride),x={url:a,ws:i,fpID:_o,aID:Un,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Ao,force:!0},payloadEncoding:{encoding:Do,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},f=new ko.FWS(x);f.onopen=()=>{this.opened=!0,this.openCount+=1;let l=this.openCount===1;te.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:l,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:l})).catch(h=>te.warn("onConnect handler threw (ignored)",{err:String(h)}))},f.onclose=l=>{this.opened=!1,te.info("frontier closed",{code:l.code,reason:l.reason,willReconnect:l.willReconnect})},f.onerror=l=>{te.warn("frontier error",{code:l.code,msg:l.message})},f.onmessage=l=>this.handleMessage(l),this.fws=f,await f.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){te.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),x=e;te.info("frontier frame out",{method:x.method,jsonrpcId:x.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:Ao,payloadEncoding:Do})}catch(f){throw new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(f)}`,{cause:f})}}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){te.debug("drop non-adapter frontier frame",{service:i});return}let a=uf(e);if(!a){te.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){te.debug("frame received but no onFrame handler",{size:a.length});return}let x;try{x=JSON.parse(a)}catch(f){te.warn("frontier message JSON parse failed",{err:String(f),head:a.slice(0,80)});return}te.info("frontier frame in",{logid:ff(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:x.id}),Promise.resolve(this.handler(x)).catch(f=>te.warn("frontier frame handler threw",{err:String(f)}))}};function ff(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function uf(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}}K();function Po(r){return r?r.startsWith("boe_")?{ttEnv:r}:{ttEnv:r,usePpe:"1"}:{}}var Io=R("handshake");async function To(r){let e=So(r.endpoint),i=r.timeoutMs??1e4,a=`${df(e)}${vo}?aid=${encodeURIComponent(Un)}`,x={Authorization:`Bearer ${r.privatecode}`,Accept:"application/json",...Fn(r.ppeOverride)},f=new AbortController,l=setTimeout(()=>f.abort(),i);Io.info("frontier key handshake",{base:e});try{let h=await fetch(a,{method:"GET",headers:x,signal:f.signal}),m=h.headers.get("x-tt-logid")??"",_=h.headers.get("x-tt-trace-id")??"";if(!h.ok){let k=await h.text().catch(()=>"");throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${h.status} logid=${m}: ${k.slice(0,200)}`)}let b=await h.json();if(b.code!==void 0&&b.code!==0)throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${b.code} msg=${b.msg??"-"} logid=${m}`);let w=b.data?.access_key,C=b.data?.device_id;if(!w||!C)throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${m}: ${JSON.stringify(b)}`);return Io.info("handshake ok",{remoteDeviceId:C,logid:m,traceId:_}),{accessKey:w,deviceId:C}}catch(h){throw h instanceof E?h:h.name==="AbortError"?new E("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${i}ms)`):new E("UPSTREAM_HANDSHAKE_FAILED",String(h),{cause:h})}finally{clearTimeout(l)}}function df(r){return r.endsWith("/")?r.slice(0,-1):r}K();var Ur=R("upstream.switchable"),Hn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;Ur.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(x){throw Ur.error("swap target start failed, reverting",{err:String(x)}),this.inner=a,x}await a.stop(i??"swapped").catch(x=>Ur.warn("previous upstream stop threw (ignored)",{err:String(x)}))}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 Fr=R("upstream"),Kt=class{handler=null;async start(){Fr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Fr.info("NoopUpstream stopped",{reason:e})}async send(e){Fr.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();oe();K();oe();import{execSync as lf}from"node:child_process";import{readFileSync as Lo,unlinkSync as hf}from"node:fs";import{mkdir as gf,readFile as No,unlink as Ro,writeFile as pf}from"node:fs/promises";import{dirname as mf}from"node:path";var wf=R("single-instance"),jn=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??H().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&&(wf.warn("removing stale pid file",{stalePid:e}),await Ro(this.pidFile).catch(()=>{})),await gf(mf(this.pidFile),{recursive:!0}),await pf(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await No(this.pidFile,"utf8")).trim()===String(process.pid)&&await Ro(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await No(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=Lo(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=lf(`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{Lo(this.pidFile,"utf8").trim()===String(process.pid)&&hf(this.pidFile)}catch{}})}};var z=R("daemon"),_f="coze-bridge-daemon";async function zo(){let r=new jn({processTitle:_f}),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??{};dr({pid:process.pid}),z.info(i?"loaded bridge config":"initialized bridge config");try{let I=new Tt;a.frameworksCache=await I.detectAll(),z.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(I){z.warn("framework detection failed",{err:String(I)})}await Lt(a);let x=new Hn(new Kt),f=H(),l=null,h=new mn({upstream:x,paths:f,bridgeConfig:a,sessionSpawner:async(I,M,Y)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(I,M,Y)}});await bf(f,h);let m=new gn({paths:f,config:a,registry:h});l=m;let _,b,w=null,C=null;h.registerExtension("_agent/create",async I=>m.createAgent(I.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let k=new tn({agents:h.agents,disposeAndMarkDisconnected:async(I,M)=>{let Y=h.agents.get(I);Y&&(await Y.dispose(`disconnect: ${M}`).catch(me=>z.warn("dispose during disconnect failed (ignored)",{agentId:I,err:String(me)})),Y.status="disconnected",h.unregister(I)),h.disconnectedAgents.add(I)}});h.registerExtension("_agent/listSkills",I=>k.listSkills(I.params)),h.registerExtension("_agent/addSkills",I=>k.addSkills(I.params)),h.registerExtension("_agent/removeSkills",I=>k.removeSkills(I.params)),h.registerExtension("_agent/getFileTree",I=>k.getFileTree(I.params)),h.registerExtension("_agent/getFileContent",I=>k.getFileContent(I.params)),h.registerExtension("_agent/update",I=>k.updateAgent(I.params)),h.registerExtension("_agent/disconnect",I=>k.disconnectAgent(I.params)),h.registerExtension("_agent/switchModel",I=>k.switchModel(I.params));let T=new $t({paths:f,handlers:k,sendDetail:I=>h.sendRequest("_agent/detail",I)});x.onConnect(({initial:I})=>{z.info("frontier upstream connected, triggering detail sync",{initial:I}),T.syncAll(I?"initial-connect":"reconnect").catch(M=>z.warn("detail sync top-level error (ignored)",{err:String(M)}))});let L=new wn({paths:f,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...h.agents.keys()],deviceId:w??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async I=>{let M=I,Y=M?.privatecode,me=M?.pairing_code;if(!Y||!me)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let De=Po(M.env),we=M.handshake_url,le=M.frontier_url,We=yf(M.env,we,le),Ht=!!_&&_!==Y,jt=b!==void 0&&b!==We,_e=Ht||jt;if(_e){z.warn("pair config switched, resetting agents",{pcChanged:Ht,envChanged:jt,previousPc:_?Oo(_):"",nextPc:Oo(Y),previousEnvKey:b??"",nextEnvKey:We});for(let be of[...h.agents.values()])await be.dispose("pair config switch").catch(()=>{}),h.agents.delete(be.agentId);await x.swap(new Kt,"pair switch").catch(()=>{})}let ye=await To({privatecode:Y,...we?{endpoint:we}:{},ppeOverride:De});w=ye.deviceId,dr({deviceId:w,pid:process.pid});let $n=new Kn({handshake:ye,privatecode:Y,...le?{urlOverride:le}:{},ppeOverride:De});await x.swap($n,"pair");let re=Object.keys(a.frameworksCache??{});try{let be=await h.sendRequest("_agent/pair",{pairCode:me,patToken:Y,frameworks:re,_meta:{cozeDeviceId:w}});z.info("_agent/pair ok",{pairResult:be}),_=Y,b=We,C||(C=new rn({core:h,getDeviceId:()=>w??""})),C.start(),_e&&Bo(f,m).catch(q=>z.warn("post-pair-switch auto-revive error (ignored)",{err:String(q)}));let X;return M.agent_id&&(X=await vf(M.agent_id,f,m,q=>h.sendRequest("_agent/detail",q)).catch(q=>(z.error("--agent-id ensureAgent failed",{agentId:M.agent_id,err:String(q)}),{ok:!1,agentId:M.agent_id??"",note:String(q)}))),{ok:!0,note:"paired with cloud",...X?{agent:X}:{}}}catch(be){return z.error("_agent/pair failed",{err:String(be)}),{ok:!1,note:`pair failed: ${String(be)}`}}}},{method:"POST",path:"/_agent/create",handler:async I=>{let M=I;return{ok:!0,result:await m.createAgent(M)}}},{method:"POST",path:"/refresh",handler:async()=>{z.info("IPC /refresh: re-detecting frameworks");let I=new Tt;return a.frameworksCache=await I.detectAll(),await Lt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(z.info("IPC /shutdown received"),setImmediate(()=>{Ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:F,token:Q}=await L.start();await h.start(),Bo(f,m).catch(I=>z.warn("auto-revive top-level error (ignored)",{err:String(I)}));let ne=null,Ae={port:F,token:Q,core:h,ipc:L,shutdown(I){return ne||(z.info("daemon shutdown",{reason:I}),ne=(async()=>{C?.stop(),await h.stop(I),await L.stop(),await r.release()})(),ne)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{Ae.shutdown(I).then(()=>process.exit(0))});return z.info("daemon ready",{port:F,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),Ae}function Oo(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function yf(r,e,i){return`${r??""}|${e??""}|${i??""}`}async function bf(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.agentsRoot)}catch{return}let{loadAgentConfig:x,enforceAgentConfigMode:f}=await Promise.resolve().then(()=>(Ue(),Zt));for(let l of a){await f(l,r).catch(h=>z.warn("enforceAgentConfigMode failed (ignored)",{agentId:l,err:String(h)}));try{let h=await x(l,r);h?.disconnectedAt&&(e.disconnectedAgents.add(l),z.info("agent marked disconnected on startup",{agentId:l,disconnectedAt:h.disconnectedAt,reason:h.disconnectReason??""}))}catch(h){z.warn("failed to load agent config on startup, skipping",{agentId:l,err:String(h)})}}}async function vf(r,e,i,a){let{loadAgentConfig:x}=await Promise.resolve().then(()=>(Ue(),Zt)),f=await x(r,e);if(f){z.info("--agent-id: local config found, reconnecting",{agentId:r,framework:f.framework,hadDisconnect:!!f.disconnectedAt});let _={agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{}};return await i.createAgent(_),{ok:!0,agentId:r,note:f.disconnectedAt?"revived from local config":"connected from local config"}}z.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let l=await a({_meta:{cozeAgentId:r}});if(!l.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:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...l.deployType?{_meta:{cozeDeployType:l.deployType}}:{}};await i.createAgent(h);let m=l.deployType==="cloud"&&l.framework==="openclaw";return{ok:!0,agentId:r,note:m?"cloud agent acknowledged":"created from cloud detail"}}async function Bo(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:x}=await Promise.resolve().then(()=>(Ue(),Zt));z.info("auto-revive: scanning local agents on startup",{count:a.length});let f=0,l=0;for(let h of a){let m;try{m=await x(h,r)}catch(_){z.warn("auto-revive: load config failed (skipping)",{agentId:h,err:String(_)}),l+=1;continue}if(!m){l+=1;continue}if(m.disconnectedAt){z.info("auto-revive: skip disconnected agent",{agentId:h,disconnectedAt:m.disconnectedAt}),l+=1;continue}try{z.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}}:{}}),f+=1}catch(_){z.warn("auto-revive: createAgent failed (skipping)",{agentId:h,framework:m.framework,err:String(_)}),l+=1}}return z.info("auto-revive: done",{revived:f,skipped:l,total:a.length}),{revived:f,skipped:l,total:a.length}}Hr();oe();import{readFile as qo}from"node:fs/promises";var Ge=class{paths;constructor(e){this.paths=e??H()}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:Tf(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([qo(this.paths.portFile,"utf8"),qo(this.paths.tokenFile,"utf8")]),a=Number.parseInt(e.trim(),10),x=i.trim();return!Number.isFinite(a)||a<=0||!x?null:{port:a,token:x}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,i){let a=i.body!==void 0,x={Authorization:`Bearer ${e.token}`};a&&(x["content-type"]="application/json");let f=new AbortController,l=setTimeout(()=>f.abort(),i.timeoutMs??5e3);try{let h=await fetch(`http://127.0.0.1:${e.port}${i.path}`,{method:i.method,headers:x,body:a?JSON.stringify(i.body):void 0,signal:f.signal}),m=await h.text();return{status:h.status,body:Pf(m)}}finally{clearTimeout(l)}}};function Pf(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Tf(r){return r instanceof Error?r.message:String(r)}K();oe();import{copyFile as Uo,mkdir as Lf,readFile as jr,writeFile as Nf}from"node:fs/promises";import{dirname as Rf,resolve as Gr,sep as Gn}from"node:path";import{fileURLToPath as Of}from"node:url";K();oe();var Fo=R("dist-install");function Bf(r){let e=Of(r),i=Rf(e),a=`${Gn}src${Gn}`;if(i.includes(a)||i.endsWith(`${Gn}src${Gn}cli`))return null;let x=Gr(i,"index.js"),f=Gr(i,"..","package.json");return{dist:x,pkgJson:f}}async function Ko(r={}){let e=r.paths??H(),i=Bf(import.meta.url),a=r.sourceDist??i?.dist,x=r.sourcePackageJson??i?.pkgJson;if(!a||!x)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let f;try{f=JSON.parse(await jr(x,"utf8")).version??"unknown"}catch(w){return Fo.warn("cannot read source package.json,skip dist install",{err:String(w)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(w)}`}}let l=await pn(e.configFile)??{},h=l.libVersion;if(h===f)try{return await jr(e.libEntry),{kind:"already-current",libVersion:f}}catch{}await Lf(e.libDir,{recursive:!0}),await Uo(a,e.libEntry),await Uo(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let m=Gr(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
|
|
92
|
-
`;return await jr(m,"utf8").catch(()=>null)!==_&&await Nf(m,_),l.libVersion=f,await Lt(l,e.configFile),Fo.info("dist installed",{libEntry:e.libEntry,fromVersion:h,toVersion:f}),h?{kind:"version-changed",fromVersion:h,toVersion:f,libEntry:e.libEntry}:{kind:"first-install",libVersion:f,libEntry:e.libEntry}}var tu=R("cli");function yt(r,e){let i=[],a;for(let x=0;x<r.length;x++){let f=r[x];if(f===e){a=r[x+1],x+=1;continue}if(f.startsWith(`${e}=`)){a=f.slice(e.length+1);continue}i.push(f)}return{value:a,rest:i}}function nu(r){let e=r.slice(2);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 i=e,{value:a,rest:x}=yt(i,"--pat-token");i=x;let{value:f,rest:l}=yt(i,"--pair-code");i=l;let{value:h,rest:m}=yt(i,"--env");i=m;let{value:_,rest:b}=yt(i,"--handshake-url");i=b;let{value:w,rest:C}=yt(i,"--frontier-url");i=C;let{value:k}=yt(i,"--agent-id");if(!a||!f)return{mode:"help"};let T={mode:"pair",privatecode:a,pairingCode:f};return h&&(T.env=h),_&&(T.handshakeUrl=_),w&&(T.frontierUrl=w),k&&(T.agentId=k),T}var ru=`
|
|
88
|
+
${s}`}var K=w("agent-detail-sync"),Tt=class{constructor(e){this.opts=e}opts;async syncAll(e){let t=this.opts.paths.agentsRoot,n;try{n=await aa(t)}catch(s){K.info("agents dir not found, skip detail sync",{root:t,err:String(s)});return}K.info("starting detail sync",{reason:e,count:n.length});for(let s of n)try{await this.syncOne(s)}catch(i){K.warn("detail sync failed for agent, skipping",{agentId:s,err:String(i)})}K.info("detail sync done",{reason:e})}async syncOne(e){let t=await U(e,this.opts.paths);if(!t){K.info("detail sync: agent config missing, skip",{agentId:e});return}let n;try{n=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(o){K.warn("detail RPC failed, using local data",{agentId:e,err:String(o)});return}if(n.agentId&&n.agentId!==e){K.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:n.agentId});return}let s=!1,i=!1;if(n.agentName&&n.agentName!==t.agentName&&(t.agentName=n.agentName,s=!0),n.description!==void 0&&n.description!==t.description&&(t.description=n.description,s=!0),n.cozeIdentity&&n.cozeIdentity!==t.cozeIdentity&&(t.cozeIdentity=n.cozeIdentity,s=!0,i=!0),n.deployType&&K.info("detail.deployType",{agentId:e,deployType:n.deployType}),!s){K.debug("detail sync: no diff",{agentId:e});return}await J(t,this.opts.paths),K.info("detail sync: config updated",{agentId:e,identityChanged:i,agentName:t.agentName}),i&&(await be(t.workspace,t.framework,e,t.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};ue();import{spawn as ms}from"node:child_process";import{lstat as Ar,mkdir as ua,readFile as _s,readdir as fa,rm as ha,stat as ga,writeFile as pa}from"node:fs/promises";import{join as ie,normalize as ma,relative as ws,resolve as _a,sep as ys}from"node:path";var X={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 Xe(r){return r?.cozeDeployType==="cloud"?"cloud":"local"}function Xn(r){let{_meta:e,...t}=r;return{stripped:t,meta:e}}function De(r){if(!r?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return r.cozeAgentId}var h=class extends Error{code;retriable;cause;constructor(e,t,n){super(t),this.name="BridgeError",this.code=e,this.retriable=n?.retriable??!1,n?.cause!==void 0&&(this.cause=n.cause)}};k();F();function se(r,e){if(Xe(r)!=="cloud")throw new h("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Rt(r){return r.replace(/[^A-Za-z0-9._-]+/g,"-")}k();var Pt="1008033",Yn="1289";var Zn="pbbp2",es="https://www.coze.cn",ts="/api/coze_claw/resource/get_frontier_key",ca="https://www.coze.cn",da="wss://frontier.coze.cn";function rs(r){return r??process.env.COZE_BRIDGE_HANDSHAKE_URL??ca}function ns(r){return r??process.env.COZE_BRIDGE_FRONTIER_URL??da}function At(r){let e={},t=r?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,n=r?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return t&&(e["x-tt-env"]=t),n&&(e["x-use-ppe"]=n),e}function Ct(r){return r?r.startsWith("boe_")?{ttEnv:r}:{ttEnv:r,usePpe:"1"}:{}}var ss=w("handshake");async function is(r){let e=rs(r.endpoint),t=r.timeoutMs??1e4,n=`${la(e)}${ts}?aid=${encodeURIComponent(Pt)}`,s={Authorization:`Bearer ${r.privatecode}`,Accept:"application/json",...At(r.ppeOverride)},i=new AbortController,o=setTimeout(()=>i.abort(),t);ss.info("frontier key handshake",{base:e});try{let a=await fetch(n,{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 m=await a.text().catch(()=>"");throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${m.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 ss.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 la(r){return r.endsWith("/")?r.slice(0,-1):r}var os="https://llm-gateway.coze.cn",Le="auto";function as(r){return{model:r.model??Le,...r.modelToken?{modelToken:r.modelToken}:{}}}function cs(r){return!r||r===Le}function ds(r){let e={};return r.modelToken&&(e.ANTHROPIC_BASE_URL=os,e.ANTHROPIC_AUTH_TOKEN=r.modelToken),cs(r.model)||(e.ANTHROPIC_MODEL=r.model),e}function ls(r){let e=[];return cs(r.model)||e.push("-c",`model="${r.model}"`),r.modelToken&&(e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${os}/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 us(r){return r.modelToken?{OPENAI_API_KEY:r.modelToken}:{}}function fs(r){let{ttEnv:e,usePpe:t}=Ct(r),n={};return e&&(n["x-tt-env"]=e),t&&(n["x-use-ppe"]=t),n}function hs(r,e){if(!r.modelToken)return{};let t=fs(e);return Object.keys(t).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(t).map(([s,i])=>`${s}:${i}`).join(`
|
|
89
|
+
`)}}function gs(r,e){if(!r.modelToken)return[];let t=fs(e),n=[];for(let[s,i]of Object.entries(t))n.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return n}var M=w("agent-handlers"),ps=5*1024*1024,wa=1,ya=6,Sa=new Set(["node_modules",".git",".coze","dist","build",".next"]),Nt=class{constructor(e){this.opts=e}opts;async listSkills(e){se(e._meta,"_agent/listSkills");let t=De(e._meta),n=await this.loadAgentCfg(t),s=n?.workspace??ne(t).workspace,i=n?.skills??[],o=[];for(let a of i){let c=ie(s,a.relPath,"SKILL.md");await ga(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){se(e._meta,"_agent/addSkills");let t=De(e._meta),n=await this.requireAgentCfg(t),s=e.skills??[],i=[...n.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=Ea(c.skillName),l=va(n.framework),u=ie(l,d),f=ie(n.workspace,u);await ua(f,{recursive:!0});let m=await Ia(c.downloadUrl);Ra(m)?await Pa(m,f):await pa(ie(f,"SKILL.md"),m.toString("utf8"),"utf8");let p={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[_]=p:(o.set(c.skillId,i.length),i.push(p)),a.push(c),M.info("skill installed",{agentId:t,skillId:c.skillId,skillName:c.skillName,relPath:u})}return await xt(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){se(e._meta,"_agent/removeSkills");let t=De(e._meta),n=await this.requireAgentCfg(t),s=new Set(e.skillIds??[]),i=n.skills??[],o=[];for(let a of i){if(!s.has(a.skillId)){o.push(a);continue}let c=ie(n.workspace,a.relPath);await ha(c,{recursive:!0,force:!0}),M.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await xt(t,o),await this.reloadAgentSessions(t,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,t){return this.reloadAgentSessions(e,t)}async reloadAgentSessions(e,t){let n=this.opts.agents.get(e);if(n&&n.framework!=="codex"){for(let[s,i]of n.sessions)if(!(!i.downstream||!i.acpSessionId)){i.loadingSession=!0;try{await i.downstream.sessionLoad({sessionId:i.acpSessionId,cwd:n.workspace}),M.info("session reloaded",{reason:t,agentId:e,framework:n.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){M.warn("session reload failed",{reason:t,agentId:e,framework:n.framework,cloudId:s,acpId:i.acpSessionId,err:String(o)})}finally{i.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return M.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,n=await U(t);if(!n)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return n.cozeIdentity===e.cozeIdentity?(M.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(n.cozeIdentity=e.cozeIdentity,await J(n),await be(n.workspace,n.framework,t,e.cozeIdentity),M.info("_agent/update: cozeIdentity rewritten",{agentId:t,framework:n.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 n=await U(t);return n?(n.disconnectedAt=Date.now(),n.disconnectReason=e.reason??"",await J(n),M.info("agent disconnected",{agentId:t,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(t,e.reason??"disconnect"),{ok:!0}):(M.warn("_agent/disconnect: agent not found, ignoring",{agentId:t}),{ok:!0})}async switchModel(e){if(se(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:Le,n=await U(e.agentId);if(!n)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);n.model=t,await J(n),M.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);return s?(await s.msgQueue.enqueue(async()=>{s.model=t,await s.killAllRuntimes(`switchModel: ${t}`)}),M.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:t}),{ok:!0}):(M.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0})}async resetAgent(e){if(se(e._meta,X.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${X.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,X.RESET,e.reason),{ok:!0}}async repairAgent(e){if(se(e._meta,X.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${X.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${X.REPAIR} only allowed for openclaw, got ${t.framework}`);return await this.runDetailSync(e.agentId,X.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,n){if(!this.opts.detailSyncer){M.warn("detailSyncer not wired, skipping sync",{method:t,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){M.warn("detail sync failed (ignored)",{method:t,agentId:e,reason:n,err:String(s)})}}async getFileTree(e){se(e._meta,"_agent/getFileTree");let t=e._meta,n=De(t),s=await this.resolveWorkspace(n),i=e.filePath??"",o=this.safeJoin(s,i),a=await Ar(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=Ca(e.depth);return a.isDirectory()?{tree:await Ss(s,o,i,c)}:{tree:[{name:Oa(i),path:Es(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){se(e._meta,"_agent/getFileContent");let t=De(e._meta),n=await this.resolveWorkspace(t);if(!e.filePath)throw new h("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(n,e.filePath),i=await Ar(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>ps)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${ps})`);let o=await _s(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 U(e).catch(()=>null))?.workspace??ne(e).workspace}safeJoin(e,t){let n=_a(e,t||"."),s=ws(e,n);if(s.startsWith("..")||s===".."||s.startsWith(`..${ys}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return n}loadAgentCfg(e){return U(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 Ea(r){let e=Rt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function va(r){return r==="claude-code"?ie(".claude","skills"):ie(".agents","skills")}var ka=3e4,xa=50*1024*1024,bt=3e4;async function Ia(r){if(!r)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);Ot(e);let t=Ta(r);return Ot(t.length),t}if(r.startsWith("file:")){let e=new URL(r).pathname,t=await _s(e);return Ot(t.length),t}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),ka);try{let n=await fetch(r,{signal:e.signal});if(!n.ok)throw new h("IPC_BAD_REQUEST",`fetch skill failed HTTP ${n.status} ${r}`);let s=await n.arrayBuffer();return Ot(s.byteLength),Buffer.from(s)}finally{clearTimeout(t)}}throw new h("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function Ot(r){if(r>xa)throw new h("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function Ta(r){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(r);if(!e)throw new h("IPC_BAD_REQUEST","bad data URL");let t=!!e[2],n=e[3]??"";return t?Buffer.from(n,"base64"):Buffer.from(decodeURIComponent(n),"utf8")}function Ra(r){return r.length>=2&&r[0]===31&&r[1]===139}async function Pa(r,e){await Aa(r),await new Promise((t,n)=>{let s=ms("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"),n(new h("IPC_BAD_REQUEST",`tar extract timeout (${bt}ms)`))},bt);s.on("error",a=>{clearTimeout(o),n(new h("IPC_BAD_REQUEST",`tar spawn failed: ${a.message}`,{cause:a}))}),s.on("exit",a=>{clearTimeout(o),a===0?t():n(new h("IPC_BAD_REQUEST",`tar exit ${a}${i?`: ${i.trim().slice(0,200)}`:""}`))}),s.stdin?.end(r)})}async function Aa(r){let e=await new Promise((t,n)=>{let s=ms("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"),n(new h("IPC_BAD_REQUEST",`tar list timeout (${bt}ms)`))},bt);s.on("error",c=>{clearTimeout(a),n(new h("IPC_BAD_REQUEST",`tar list spawn failed: ${c.message}`))}),s.on("exit",c=>{clearTimeout(a),c===0?t(i):n(new h("IPC_BAD_REQUEST",`tar list exit ${c}${o?`: ${o.trim().slice(0,200)}`:""}`))}),s.stdin?.end(r)});for(let t of e.split(`
|
|
90
|
+
`)){let n=t.trim();if(!n)continue;let s=n.charCodeAt(0);if(s!==45&&s!==100)throw new h("IPC_BAD_REQUEST",`tar entry kind '${n[0]}' not allowed (symlink/hardlink/special): ${n.slice(0,100)}`);let o=(n.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 Ss(r,e,t,n){if(n<=0)return[];let s;try{s=await fa(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(Sa.has(o.name)||o.isSymbolicLink())continue;let a=ie(e,o.name),c=ma(ie(t,o.name)),d=null;try{d=await Ar(a)}catch{continue}if(d.isSymbolicLink())continue;let l={name:o.name,path:Es(ws(r,a)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&n>1&&(l.children=await Ss(r,a,c,n-1)),i.push(l)}return i.sort((o,a)=>o.isDir!==a.isDir?o.isDir?-1:1:o.name.localeCompare(a.name)),i}function Ca(r){return!r||r<=0?wa:Math.min(r,ya)}function Oa(r){if(!r||r==="."||r==="/")return".";let e=r.split(/[/\\]/);return e[e.length-1]||"."}function Es(r){return r.split(ys).join("/")}k();var Ye=w("agent-health-reporter"),Na=1e4,Dt=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Na}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()}),Ye.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ye.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ye.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Ye.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=ba(s);i&&t.push({agentId:s.agentId,status:i})}if(t.length===0)return;let n={agents:t,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",n)}catch(s){Ye.warn("heartbeat batch send failed",{count:t.length,err:String(s)})}}finally{this.inFlight=!1}}};function ba(r){return r.status==="error"?"error":r.activeTriggers.size>0?"busy":r.status==="ok"?"online":null}ue();import{mkdir as Cr,rm as Ja}from"node:fs/promises";import{spawn as Fa}from"node:child_process";function Ze(r,e,t){return t===void 0?{jsonrpc:"2.0",id:r,method:e}:{jsonrpc:"2.0",id:r,method:e,params:t}}function Lt(r,e){return e===void 0?{jsonrpc:"2.0",method:r}:{jsonrpc:"2.0",method:r,params:e}}function Me(r,e){return{jsonrpc:"2.0",id:r,result:e}}function Se(r,e){return{jsonrpc:"2.0",id:r,error:e}}var Mt=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 vs(r){return"method"in r&&"id"in r&&r.id!==void 0}function ks(r){return"method"in r&&!("id"in r)}function Bt(r){return!("method"in r)&&"id"in r}var Da={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 Ft(r){return r instanceof h?{code:Da[r.code]??R.INTERNAL_ERROR,message:r.message,data:{bridgeCode:r.code,retriable:r.retriable}}:{code:R.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)}}function xs(r){let e=r.data,t=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new h(t,r.message,{retriable:e?.retriable??!1,cause:r.data})}function Is(r){return`${JSON.stringify(r)}
|
|
91
|
+
`}var Ut=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(`
|
|
92
|
+
`);this.buffer=t.pop()??"";let n=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{n.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return n}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 Rs={"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"},dh=Object.fromEntries(Object.entries(Rs).map(([r,e])=>[e,r])),La={"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:[]},Be=class{seq=0;next(e,t){this.seq+=1;let n=Rs[e]??Ma(e),s=La[n]??[],i=[n,String(this.seq)];if(s.length>0){let o=s.map(c=>Ts(t?.[c]??"")),a=Ba(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>Ts(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function Ma(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Ts(r){return r.replace(/[:_\s]+/g,"-")}function Ba(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}k();var Ua=3e4;function Ps(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var fe=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Ut({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Be;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;sanitizeEnv(e){return e}async start(){if(this.child)throw new h("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",t=Fa(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",n=>{for(let s of this.decoder.push(n))this.dispatch(s)}),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",n=>{this.log.debug("stderr",{text:n.trimEnd()})}),t.on("exit",(n,s)=>{this.stopped=!0,this.failAllPending(new h("AGENT_PROTOCOL_ERROR",`agent exited (${n}/${s})`));for(let i of this.exitHandlers)i(n,s)}),t.on("error",n=>{this.log.error("child error",{err:String(n)}),this.failAllPending(new h("AGENT_SPAWN_FAILED",String(n),{cause:n}))}),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,n=new Promise(i=>t.once("exit",()=>i()));Ps(t.pid,"SIGTERM");let s=setTimeout(()=>{t.killed||Ps(t.pid,"SIGKILL")},5e3);try{await n}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(Lt("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(Me(e,t))}catch(n){this.log.warn("respondAgentRequest write failed",{id:e,err:String(n)})}}respondAgentRequestError(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Se(e,t))}catch(n){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(n)})}}onExit(e){this.exitHandlers.push(e)}call(e,t,n=Ua){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=Ze(s,e,t),o=n>0&&Number.isFinite(n);return new Promise((a,c)=>{let d=o?setTimeout(()=>{this.pending.delete(s),c(new h("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n):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(Is(e))}dispatch(e){if(Bt(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?t.reject(xs(e.error)):t.resolve(e.result);return}if(ks(e)){if(e.method==="session/update")for(let t of this.updateHandlers)Promise.resolve(t(e.params)).catch(n=>this.log.warn("update handler failed",{err:String(n)}));else this.log.debug("unknown notification",{method:e.method});return}if(vs(e)){let t=e;this.handleAgentRequest(t).catch(n=>this.log.error("agent request handler failed",{method:t.method,err:String(n)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Se(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let t of this.agentRequestHandlers)try{await t(e)}catch(n){this.log.error("agentRequestHandler threw",{method:e.method,err:String(n)});try{this.writeFrame(Se(e.id,Ft(n)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var $a="@agentclientprotocol/claude-agent-acp@latest";function za(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&(t.startsWith("CLAUDE")||t==="AI_AGENT"||t==="BAGGAGE"||(e[t]=n));return e}var $t=class extends fe{framework="claude-code";constructor(e){let t=e.command??"npx",n=e.args??["-y",$a],s={command:t,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return za(e)}};import{mkdtempSync as qa,rmSync as Ga}from"node:fs";import{tmpdir as Ha}from"node:os";import{join as Wa}from"node:path";var ja="@zed-industries/codex-acp@latest",zt=class extends fe{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=e.command??"npx",n=e.args??["-y",ja],s=e.extraArgs?[...n,...e.extraArgs]:n,i=e.isolateCodexHome?qa(Wa(Ha(),"coze-bridge-codex-home-")):void 0,o=i?{...e.env??{},CODEX_HOME:i}:e.env,a={command:t,args:s,cwd:e.cwd,...o?{env:o}:{}};super(a),this.authMethodId=e.authMethodId,this.codexHomeDir=i}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{Ga(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};import{spawn as As}from"node:child_process";k();var qt=class extends fe{framework="openclaw";registerLog;profile;agentId;sessionName;registered=!1;constructor(e){let t=e.profile??"coze",n=e.sessionName??"default",s=["--profile",t,"acp","--session",`agent:${e.agentId}:${n}`],i={command:e.command,args:s,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i),this.profile=t,this.agentId=e.agentId,this.sessionName=n,this.registerLog=w("downstream.openclaw.register")}async start(){await this.registerAgent().catch(e=>{this.registerLog.warn("openclaw agents add failed (will continue to acp anyway)",{agentId:this.agentId,err:String(e)})}),await super.start()}registerAgent(){return new Promise((e,t)=>{let n=As(this.opts.command,["--profile",this.profile,"agents","add",this.agentId,"--workspace",this.opts.cwd,"--non-interactive"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),s="";n.stderr?.on("data",i=>{s+=i.toString("utf8")}),n.on("error",t),n.on("close",i=>{i===0?(this.registered=!0,this.registerLog.info("agent registered",{agentId:this.agentId,profile:this.profile}),e()):t(new h("AGENT_SPAWN_FAILED",`openclaw agents add ${this.agentId} exited ${i}: ${s.trim()}`))})})}async cleanup(e){this.registered&&await new Promise(t=>{let n=As(this.opts.command,["--profile",this.profile,"agents","delete",this.agentId,"--force"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),s="";n.stderr?.on("data",i=>{s+=i.toString("utf8")}),n.on("error",i=>{this.registerLog.warn("openclaw agents delete failed (best-effort)",{agentId:this.agentId,err:String(i)}),t()}),n.on("close",i=>{i===0?this.registerLog.info("agent unregistered",{agentId:this.agentId}):this.registerLog.warn("openclaw agents delete non-zero exit",{agentId:this.agentId,code:i,stderr:s.trim()}),this.registered=!1,t()})})}get acpSessionName(){return this.sessionName}};k();F();var Gt=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,n)=>{this.slots.push({task:e,resolve:t,reject:n}),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 Ht=class{agentId;framework;workspace;deployType;msgQueue;sessions=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",this.msgQueue=new Gt}async dispose(e){this.status="stopped",this.msgQueue.dispose(new Error(`AgentSession disposed${e?`: ${e}`:""}`)),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let t=[];for(let[,n]of this.sessions)et(n),n.downstream&&(t.push(n.downstream.stop(e).catch(()=>{})),n.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function et(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}var he=w("agent-manager"),Va=(r,e,t,n,s,i,o)=>{switch(r){case"claude-code":{let a=s?{...ds(s),...hs(s,o)}:void 0;return new $t({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...ls(s),...gs(s,o)]:[],c=s?us(s):void 0,d=!!s;return new zt({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 qt({command:e,cwd:t,agentId:n,...i?{sessionName:Rt(i)}:{}})}};function Qa(r){return r==="claude-code"||r==="codex"}var Ka={path:"",version:"cloud-deployed"},Xa={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ya=2e4,Wt=class{paths;config;registry;factory;createTimeoutMs;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Va,this.createTimeoutMs=e.createTimeoutMs??Ya}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=Xe(e._meta)==="cloud";if(t&&e.framework==="openclaw")return he.info("cloud-deployed openclaw, ack without local spawn",{agentId:e.agentId,framework:e.framework}),{ok:!0,agentId:e.agentId,framework:e.framework};this.registry.reviveIfDisconnected?.(e.agentId);let n=this.registry.get(e.agentId);if(n){if(n.framework!==e.framework)throw new h("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${n.framework})`);if(n.status==="error")he.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await n.dispose("rebuild after error").catch(u=>he.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else return he.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:n.agentId,workspace:n.workspace,framework:n.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`);let s=ne(e.agentId,this.paths),i=e.workspace??s.workspace,o=Xe(e._meta),a=new AbortController,c=setTimeout(()=>a.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),d,l=!1;try{let u=()=>{if(a.signal.aborted)throw a.signal.reason instanceof Error?a.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await Cr(s.root,{recursive:!0}),await Cr(i,{recursive:!0}),await Cr(s.logs,{recursive:!0}),u(),await be(i,e.framework,e.agentId,e.cozeIdentity),u();let f=await U(e.agentId,this.paths).catch(()=>null),m=as({model:e.model??f?.model});if(d=new Ht({agentId:e.agentId,framework:e.framework,workspace:i,model:m.model??Le,deployType:o}),d.status="ok",f?.sessions){for(let[S,O]of Object.entries(f.sessions))d.sessions.set(S,{acpSessionId:O.acpSessionId,modelToken:O.modelToken,tokenGeneratedAt:O.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let _=Object.keys(f.sessions).length;_>0&&he.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:_})}this.registry.register(d),l=!0;let p={agentId:e.agentId,framework:e.framework,workspace:i,cozeIdentity:e.cozeIdentity,createdAt:f?.createdAt??Date.now(),sessions:f?.sessions??{},model:m.model};return o==="cloud"&&(p.deployType="cloud"),f?.skills&&(p.skills=f.skills),f?.agentName&&(p.agentName=f.agentName),f?.description&&(p.description=f.description),await J(p,this.paths),he.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:o}),{ok:!0,agentId:e.agentId,workspace:i,framework:e.framework}}catch(u){throw he.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),l&&d&&(await d.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ja(s.root,{recursive:!0,force:!0}).catch(f=>he.warn("rm agent dir failed (ignored)",{err:String(f)})),u instanceof h?u:new h("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(c)}}async spawnSessionDownstream(e,t,n,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&Qa(e.framework))o=Ka;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=this.factory(e.framework,o.path,e.workspace,e.agentId,a,n,s);try{return await c.start(),await c.initialize(Xa),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})}}};k();import{spawn as Za}from"node:child_process";import{constants as Cs,access as ec}from"node:fs/promises";import{delimiter as tc,join as rc}from"node:path";var nc=w("framework-detector"),Os={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sc=[".exe",".cmd",".bat",".ps1"],rt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Za,access:e.access??ec}}async detect(e){let t=Os[e],n=await this.which(t);if(!n)return nc.debug("framework binary not found",{framework:e,bin:t}),null;let s=await this.probeVersion(n);return{path:n,version:s}}async detectAll(){let e=await Promise.all(Object.keys(Os).map(async n=>[n,await this.detect(n)])),t={};for(let[n,s]of e)s&&(t[n]=s);return t}async which(e){let t=this.env.pathEnv.split(tc).filter(Boolean),n=this.env.platform==="win32"?["",...sc]:[""];for(let s of t)for(let i of n){let o=rc(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?Cs.F_OK:Cs.X_OK;return await this.env.access(e,t),!0}catch{return!1}}async probeVersion(e){return new Promise(t=>{let n="",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=>{n+=c.toString("utf8")}),a.on("error",()=>o("unknown")),a.on("close",()=>{let c=oc(n).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},ic=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function oc(r){return r.replace(ic,"")}Tr();F();var ac=10*6e4;function Ns(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ac:e}function jt(r){return yt(r??x().configFile)}function nt(r,e){return St(e??x().configFile,r)}import{randomBytes as cc}from"node:crypto";ue();k();var I=w("core"),dc=3e4,lc=3e4,Jt=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Be;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=Ns(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(),I.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){I.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),I.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(n){I.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(n)})}}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)&&I.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,t,n){let s=n.downstream;s&&(s.onUpdate(i=>{n.loadingSession||this.forwardUpdate(e,i)}),s.onAgentRequest(i=>{this.handleAgentRequest(e,s,i)}),s.onExit((i,o)=>{I.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),et(n),n.downstream=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId)}))}async handleFrame(e){if(Bt(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,n=e.params?._meta?.cozeEnv;n&&(this.currentCozeEnv=n);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}`):I.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Me(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Me(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Me(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):I.warn("drop unknown notification",{method:e.method})}catch(s){I.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(Se(t,Ft(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,n=t._meta?.cozeAgentId;if(!n)throw new h("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(n);if(!s)throw this.disconnectedAgents.has(n)?new h("AGENT_DISCONNECTED",`agent ${n} has been disconnected; cloud must _agent/create to revive`):new h("AGENT_NOT_FOUND",`agent not found: ${n}`);if(e.method==="session/cancel")return this.dispatchSessionCall(s,e.method,t);let i=Date.now(),o=!1;try{let a=await s.msgQueue.enqueue(()=>this.dispatchSessionCall(s,e.method,t));return o=!0,a}finally{I.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-i,ok:o})}}async dispatchSessionCall(e,t,n){e.lastActiveAt=Date.now();let{stripped:s}=Xn(n);switch(t){case"session/new":{let i=uc();return I.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return I.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=n._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 n=e.sessions.get(t);if(n)return n;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 n={sessionId:t,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(X.GEN_MODEL_TOKEN,n,lc);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,n){if(et(n),n.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,n.modelToken,t,this.currentCozeEnv);if(n.downstream=s,this.attachRuntimeHooks(e,t,n),n.acpSessionId){n.loadingSession=!0;try{await s.sessionLoad({sessionId:n.acpSessionId,cwd:e.workspace}),I.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:n.acpSessionId})}catch(i){I.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:t,acpId:n.acpSessionId,err:String(i)}),n.acpSessionId=void 0;let o=await s.sessionNew({cwd:e.workspace});n.acpSessionId=o.sessionId,await this.persistSessionMapping(e)}finally{n.loadingSession=!1}}else{let i=await s.sessionNew({cwd:e.workspace});n.acpSessionId=i.sessionId,await this.persistSessionMapping(e)}}armIdleTimer(e,t,n){et(n),n.idleTimer=setTimeout(()=>{I.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:t});let s=n.downstream;n.downstream=void 0,n.idleTimer=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),s&&s.stop("idle timeout").catch(i=>I.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:t,err:String(i)}))},this.sessionIdleTimeoutMs),n.idleTimer.unref?.()}forwardUpdate(e,t){let n=t.sessionId,s=this.reverseSessionId(e,n);if(!s){I.debug("drop update for unknown session",{agentId:e.agentId,acpId:n});return}let i=e.sessions.get(s);if(!i){I.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++i.replySeq},a=e.activeTriggers.get(n);a&&(o.cozeTriggerMsgId=a),this.upstream.send(Lt("session/update",{...t,sessionId:s,_meta:o})).catch(c=>I.warn("forward update failed",{agentId:e.agentId,err:String(c)}))}handleAgentRequest(e,t,n){if(n.method==="session/request_permission"){this.forwardPermissionRequest(e,t,n);return}I.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:n.method}),t.respondAgentRequestError(n.id,{code:R.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${n.method}`})}forwardPermissionRequest(e,t,n){let s=this.upstreamIds.next("session/request_permission"),i=n.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:n.id,agentId:e.agentId,downstream:t,method:n.method}),this.upstream.send(Ze(s,"session/request_permission",u)).catch(f=>{this.pendingUpstream.delete(s),I.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),t.respondAgentRequestError(n.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 n=this.pendingBridge.get(e.id);if(n){this.pendingBridge.delete(e.id),clearTimeout(n.timer),e.error?n.reject(new Mt(e.error)):n.resolve(e.result);return}I.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,n=dc){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 ${n}ms`))},n);this.pendingBridge.set(s,{method:e,resolve:i,reject:o,timer:a}),this.upstream.send(Ze(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[n,s]of e.sessions){let i={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(i.acpSessionId=s.acpSessionId),t.set(n,i)}await Pr(e.agentId,t,this.paths)}catch(t){I.warn("persist session mapping failed",{agentId:e.agentId,err:String(t)})}}reverseSessionId(e,t){for(let[n,s]of e.sessions.entries())if(s.acpSessionId===t)return n}sendError(e,t,n){return this.upstream.send(Se(e,{code:t,message:n}))}};function uc(){return cc(16).toString("hex")}k();F();import{randomBytes as fc}from"node:crypto";import{chmod as hc,mkdir as gc,writeFile as bs}from"node:fs/promises";import{createServer as pc}from"node:http";import{dirname as mc}from"node:path";var _c=1e6,Or=w("ipc"),Vt=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??x()}async start(){this.token=fc(32).toString("hex");let e=pc((n,s)=>{this.dispatch(n,s)});this.server=e,await new Promise((n,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>n())});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(),Or.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((t,n)=>{e.close(s=>s?n(s):t())}),this.server=null)}async persistAuthFiles(){await gc(mc(this.paths.portFile),{recursive:!0}),await bs(this.paths.portFile,String(this.port),"utf8"),await bs(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await hc(this.paths.tokenFile,384)}catch(e){Or.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){st(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){st(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await wc(e)}catch(a){st(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);st(t,200,a??{ok:!0})}catch(a){Or.error("IPC handler failed",{key:s,err:String(a)}),st(t,500,{error:a instanceof Error?a.message:String(a)})}}};function st(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(t))}async function wc(r){let e=[],t=0;for await(let s of r){let i=s;if(t+=i.length,t>_c)throw new Error("body too large");e.push(i)}let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):null}var qs="";function Cc(r=""){let t=`${Date.now()}`,n=qs||(qs=Dc(r)),s=Math.random().toString(16).slice(-6);return"02"+t+n+s}function Oc(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Nc(r){return(Array(8).join("0")+parseInt(r,10).toString(2)).slice(-8)}function Gs(r){return(Array(4).join("0")+parseInt(r,2).toString(16)).slice(-4)}function bc(r){let e=r.split(/\./).map(s=>Nc(s)),t=[];return t[0]=Gs(e[0]+e[1]),t[1]=Gs(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function Dc(r){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(r),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(r);return e?bc(r):t?Lc(r):"00000000000000000000000000000000"}function Lc(r){let e="",t=[],n=0,s=0,i=!0,o="0000";if(r.indexOf("::")>-1){let a=r.split("::");for(let d=0;d<a.length;d++){let l=a[d];if(l.indexOf(":")>0){let u=l.split(":");i&&(n=u.length),s+=u.length;for(let f=0;f<u.length;f++)if(u[f].length!==4){let p=o.substring(0,4-u[f].length).concat(u[f]);t.push(p)}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&&(n+=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===n&&(e=e.concat(c)),e=e.concat(t[d]);return e}{let a=r.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 Mc(r,e){let t=r.key;t!==void 0&&(C(e,10),ke(e,t));let n=r.value;n!==void 0&&(C(e,18),ke(e,n))}function Bc(r){let e={};e:for(;!ni(r);){let t=b(r);switch(t>>>3){case 0:break e;case 1:e.key=ve(r,b(r));break;case 2:e.value=ve(r,b(r));break;default:ei(r,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 Zs(r){let e=ri();return Fc(r,e),Hc(e)}function Fc(r,e){let t=r.SeqID;t!==void 0&&(C(e,8),ot(e,t));let n=r.LogID;n!==void 0&&(C(e,16),ot(e,n));let s=r.service;s!==void 0&&(C(e,24),ot(e,Fr(s)));let i=r.method;i!==void 0&&(C(e,32),ot(e,Fr(i)));let o=r.headers;if(o!==void 0)for(let p of o){C(e,42);let _=ri();Mc(p,_),C(e,_.limit),Jc(e,_),qc(_)}let a=r.payloadEncoding;a!==void 0&&(C(e,50),ke(e,a));let c=r.payloadType;c!==void 0&&(C(e,58),ke(e,c));let d=r.payload;d!==void 0&&(C(e,66),C(e,d.length),jc(e,d));let l=r.LogIDNew;l!==void 0&&(C(e,74),ke(e,l));let u=r.serverTiming;u!==void 0&&(C(e,82),ke(e,u));let f=r.msgID;f!==void 0&&(C(e,90),ke(e,f));let m=r.frameType;m!==void 0&&(C(e,96),ot(e,Fr(m)))}function Uc(r){return $c(Gc(r))}function $c(r){let e={};e:for(;!ni(r);){let t=b(r);switch(t>>>3){case 0:break e;case 1:e.SeqID=Ws(r,!0);break;case 2:e.LogID=Ws(r,!0);break;case 3:e.service=b(r);break;case 4:e.method=b(r);break;case 5:{let n=zc(r);(e.headers||(e.headers=[])).push(Bc(r)),r.limit=n;break}case 6:e.payloadEncoding=ve(r,b(r));break;case 7:e.payloadType=ve(r,b(r));break;case 8:e.payload=Wc(r,b(r));break;case 9:e.LogIDNew=ve(r,b(r));break;case 10:e.serverTiming=ve(r,b(r));break;case 11:e.msgID=ve(r,b(r));break;case 12:e.frameType=b(r);break;default:ei(r,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 zc(r){let e=b(r),t=r.limit;return r.limit=r.offset+e,t}function ei(r,e){switch(e){case 0:for(;128&G(r););break;case 2:Ur(r,b(r));break;case 5:Ur(r,4);break;case 1:Ur(r,8);break;default:throw new Error("Unimplemented type: "+e)}}function Fr(r){return r|=0,{low:r,high:r>>31,unsigned:r>=0}}var ti=[];function ri(){let r=ti.pop();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function qc(r){ti.push(r)}function Gc(r){return{bytes:r,offset:0,limit:r.length}}function Hc(r){let e=r.bytes,t=r.limit;return e.length===t?e:e.subarray(0,t)}function Ur(r,e){if(r.offset+e>r.limit)throw new Error("Skip past limit");r.offset+=e}function ni(r){return r.offset>=r.limit}function dt(r,e){let t=r.bytes,n=r.offset,s=r.limit,i=n+e;if(i>t.length){let o=new Uint8Array(2*i);o.set(t),r.bytes=o}return r.offset=i,i>s&&(r.limit=i),n}function nn(r,e){let t=r.offset;if(t+e>r.limit)throw new Error("Read past limit");return r.offset+=e,t}function Wc(r,e){let t=nn(r,e);return r.bytes.subarray(t,t+e)}function jc(r,e){let t=dt(r,e.length);r.bytes.set(e,t)}function ve(r,e){let t=nn(r,e),n=String.fromCharCode,s=r.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],d,l,u,f;(128&c)===0?o+=n(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+=n(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+=n(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+=n((f>>10)+55296,(1023&f)+56320),a+=3))):o+=i}return o}function ke(r,e){let t=e.length,n=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),n+=a<128?1:a<2048?2:a<65536?3:4}C(r,n);let s=dt(r,n),i=r.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 Jc(r,e){let t=dt(r,e.limit),n=r.bytes,s=e.bytes;for(let i=0,o=e.limit;i<o;i++)n[i+t]=s[i]}function G(r){return r.bytes[nn(r,1)]}function Hs(r,e){let t=dt(r,1);r.bytes[t]=e}function b(r){let e=0,t=0,n;do n=G(r),e<32&&(t|=(127&n)<<e),e+=7;while(128&n);return t}function C(r,e){for(e>>>=0;e>=128;)Hs(r,127&e|128),e>>>=7;Hs(r,e)}function Ws(r,e){let t=0,n=0,s=0,i;return i=G(r),t=127&i,128&i&&(i=G(r),t|=(127&i)<<7,128&i&&(i=G(r),t|=(127&i)<<14,128&i&&(i=G(r),t|=(127&i)<<21,128&i&&(i=G(r),n=127&i,128&i&&(i=G(r),n|=(127&i)<<7,128&i&&(i=G(r),n|=(127&i)<<14,128&i&&(i=G(r),n|=(127&i)<<21,128&i&&(i=G(r),s=127&i,128&i&&(i=G(r),s|=(127&i)<<7))))))))),{low:t|n<<28,high:n>>>4|s<<24,unsigned:e}}function ot(r,e){let t=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,s=e.high>>>24,i=s===0?n===0?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:s<128?9:10,o=dt(r,i),a=r.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?n>>>21|128:n>>>21&127;case 7:a[o+6]=i!==7?n>>>14|128:n>>>14&127;case 6:a[o+5]=i!==6?n>>>7|128:n>>>7&127;case 5:a[o+4]=i!==5?128|n:127&n;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 Vc(r){return Uc(r)}function js(r){return Zs(r)}var Js=65536,Qc="\0\0\0\0\0\0\0\0",Fe=Js*Js,si=Fe*Fe,Vs=si/2,ge=String.prototype.charCodeAt,$=class r{constructor(e,t,n){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!n}static isLong(e){return e&&e.isLong===!0}static fromBits(e,t,n){return new r(e,t,n)}static fromBytes(e,t,n){return n?r.fromBytesLE(e,t):r.fromBytesBE(e,t)}static fromBytesLE(e,t){return new r(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 r(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===Qc?Qs:new r((ge.call(e,0)|ge.call(e,1)<<8|ge.call(e,2)<<16|ge.call(e,3)<<24)>>>0,(ge.call(e,4)|ge.call(e,5)<<8|ge.call(e,6)<<16|ge.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?Kc:Qs;if(t){if(e>=si)return Yc}else{if(e<=-Vs)return Zc;if(e+1>=Vs)return Xc}return r.fromBits(e%Fe|0,e/Fe|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*Fe+(this.low>>>0):this.high*Fe+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){r.isLong(e)||(e=r.fromNumber(e));let t=this.high>>>16,n=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,m=0;return m+=i+d,f+=m>>>16,m&=65535,f+=s+c,u+=f>>>16,f&=65535,u+=n+a,l+=u>>>16,u&=65535,l+=t+o,l&=65535,r.fromBits(f<<16|m,l<<16|u,this.unsigned)}equals(e){return r.isLong(e)||(e=r.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?r.fromBits(0,0,this.unsigned):this.low===-1?r.fromBits(0,this.high+1,this.unsigned):r.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]}},Qs=new $(0,0,!1),Kc=new $(0,0,!0),Xc=$.fromBits(-1,2147483647,!1),Yc=$.fromBits(-1,-1,!0),Zc=$.fromBits(0,-2147483648,!1),Ee=(function(r){return r[r.NATIVE_ERROR=5001]="NATIVE_ERROR",r[r.CONNECTING_ERROR=5002]="CONNECTING_ERROR",r[r.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",r[r.MESSAGE_ERROR=5004]="MESSAGE_ERROR",r[r.OPEN_ERROR=5005]="OPEN_ERROR",r})({}),xe=class{constructor(e){this.type=e,this.target=null}},zr=class extends xe{constructor(e,t){super(e),this.message=t&&t.message||null}},qr=class extends xe{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}},Gr=class extends xe{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}},Hr=class extends xe{constructor(e,t){super(e),this.data=t&&t.data||null}},Wr=class extends Hr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},jr=class extends xe{constructor(e,t){super(e),this.data=t&&t.data||null}};function V(r,{message:e,code:t,error:n}){return new qr(r,{message:e,code:t,error:n})}function Y(r,{code:e,reason:t,wasClean:n,willReconnect:s}){return new Gr(r,{code:e,reason:t,wasClean:n,willReconnect:s})}function ed(r,{data:e,message:t}){return new Wr(r,{data:e,message:t})}function td(r,{data:e}){return new jr(r,{data:e})}function Ks(r,{message:e}){return new zr(r,{message:e})}var Qt=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()}},$e=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Ie=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",lt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",at=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",rd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,ct=class{constructor(){this._listeners={}}emit(e,...t){let n=this._listeners[e];if(n)n.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 n=this._listeners[e];if(n)for(let s=0;s<n.length;)n[s].fn===t?n.splice(s,1):++s}return this}on(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this}},Jr=class extends ct{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,t,n){super(),this._socket=null,lt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Ie&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let t=V("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let n=Y("close",{reason:this._formatErrorMessage(e)});this.emit("close",n)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",td("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",Y("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",ed("message",{...e}))}),this._socket.onError(e=>{this.emit("error",V("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:n=>{this.emit("error",V("error",{message:this._formatErrorMessage(n)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",V("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 nd(r,e){if(e)return new e(r.url,r.protocol);if(lt||Ie)return new Jr(r.url,r.protocol,r.headers);if(($e||at)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(r.url,r.protocols)}function sd(r){return!!(r||lt&&wx.connectSocket||Ie&&tt.connectSocket||($e||at)&&typeof WebSocket<"u"&&WebSocket)}function Xs(r,e,t){let n=-1;async function s(i){return i<=n?Promise.reject(new Error("next() called multiple times in process")):(n=i,i===t.length?Promise.resolve():t[i].bind(r)(e,s.bind(null,i+1)))}s(0)}function ii(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(64512&t)===55296&&(64512&r.charCodeAt(n+1))===56320?(++n,e+=4):e+=3;return e}function oi(r,e,t){if(t-e<1)return"";let n="";for(let s=e;s<t;){let i=r[s++];if(i<=127)n+=String.fromCharCode(i);else if(i>=192&&i<224)n+=String.fromCharCode((31&i)<<6|63&r[s++]);else if(i>=224&&i<240)n+=String.fromCharCode((15&i)<<12|(63&r[s++])<<6|63&r[s++]);else if(i>=240){let o=((7&i)<<18|(63&r[s++])<<12|(63&r[s++])<<6|63&r[s++])-65536;n+=String.fromCharCode(55296+(o>>10)),n+=String.fromCharCode(56320+(1023&o))}}return n}function Vr(r,e,t){let n=t,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=63&s|128):(64512&s)===55296&&(64512&(i=r.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-n}async function ai(r){if(typeof r=="string"){let e=new Uint8Array(ii(r));return Vr(r,e,0),e}return r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function id(r){try{return typeof r!="string"&&(r instanceof ArrayBuffer||r.buffer&&r.buffer instanceof ArrayBuffer)||typeof r!="string"?"":(JSON.parse(r),"application/json")}catch{return typeof r=="string"?"text/plain;charset=utf-8":""}}var od=(r,e)=>{switch(r){case"boe":case"ppe":return{[`x-use-${r}`]:1,"x-tt-env":e};default:return{}}},Qr=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 ad(r){return new Promise(e=>{if(!$e)return e("unknown reason");try{let t=document.createElement("script");window.frontierJSONP=n=>{document.body.removeChild(t),window.frontierJSONP=void 0,e(n&&n.msg||"unknown reason")},t.type="text/javascript",t.src=r.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(t)}catch{document.body.removeChild(t)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function pe(r,e,t){return!!r?.find(n=>n.key===e&&n.value===t)}function Ue(r,e){return r?.find(t=>t.key===e)?.value}var $r=null;async function cd(){return $r||($r=Promise.resolve().then(()=>(zs(),$s))),$r}var Kr=class extends ct{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:n}=await cd();this._qosDB=await n(`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}}},Xr=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 n=this._qosDB.getItem(this._prefix),s=JSON.parse(n||"{}");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),n=JSON.parse(t||"{}");return n[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(n))}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}},Yr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Ie?tt:lt?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 n=this._qosDB.getStorageSync(this._prefix),s=JSON.parse(n||"{}");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),n=JSON.parse(t||"{}");return n[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(n))}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 ci(r,e){if(Ie||Ie)return new Yr(r,e);if(($e||at)&&typeof indexedDB<"u")return new Kr(r,e);if(($e||at)&&typeof localStorage<"u")return new Xr(r,e);throw new Error("init QoSDB failed")}var Zr=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=ci("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:n})=>n<Date.now()).forEach(n=>{this._qosDB?.del(n.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 sn(r){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=pe(r.message.headers,"x_frontier_qos","2"),n=t&&pe(r.message.headers,"x_frontier_qos_ack","1"),s=t&&pe(r.message.headers,"x_frontier_is_ack","1"),i=s?Ue(r.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:n,isAckCleanupMessage:s,ackMsgIds:i}}async function di(){return this._QoSManager||(this._QoSManager=new Zr),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function dd(r,e){let{enableAutoAck:t}=this._options,n=pe(r.message.headers,"need_ack","1"),s=pe(r.message.headers,"is_ack","1"),i=sn.call(this,r);if(t&&n){let{SeqID:o,LogID:a,service:c,LogIDNew:d,method:l}=r.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(r),e()}async function ld(r,e){this._debug("received",r.message),e()}async function ud(r,e){let t=Vc(await ai(r.data));try{if(t.payload instanceof Uint8Array){let n=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=n.force?n.encoding:s||n.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=oi(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(n){t.textPayload="",console.log(n)}r.message=t,e()}function fd(r,e,t){let n=t||8192,s=n>>>1,i=null,o=n;return function(a){if(a<1||a>s)return r(a);o+a>n&&(i=r(n),o=0);let c=e.call(i,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var hd=4294967295;function gd(r,e,t){if(t>hd)throw new Error("integer too large");let n=3;for(;n>=0;){let s=255&t;tn(s,r,e+n),t>>>=8,n--}return e+4}function pd(r,e){let t=0,n=e,s=e+4;for(;n<s;){let{value:i,offset:o}=en(r,n);n=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function md(r,e,t){return r?r.length<40?Vr(r,e,t)+t:e.utf8Write?e.utf8Write(r,t)+t:e.write?e.write(r,t)+t:Vr(r,e,t)+t:t}function _d(r,e){let t=new $(r[e+4]<<24|r[e+5]<<16|r[e+6]<<8|r[e+7],r[e+0]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3],!0);return e+=8,{value:t,offset:e+8}}function wd(r,e,t){let n=r.low,s=r.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]=n>>>24,e[t+5]=n>>>16&255,e[t+6]=n>>>8&255,e[t+7]=255&n,t+=8,t}function en(r,e){return r.readUInt8?{value:r.readUInt8(e),offset:e+1}:{value:255&r[e],offset:e+1}}function tn(r,e,t){return e.writeUint8?e.writeUint8(r,t):e[t]=255&r,t+1}var yd=function(r){return new Uint8Array(r)},Sd=typeof Buffer<"u"?Buffer.allocUnsafe:fd(yd,Uint8Array.prototype.subarray),Ed=16,on=32;function vd(r){let e=0,t={};for(let n=0;n<r.length;n++)t[r[n].cursor_name]=ii(r[n].cursor_name),e+=14+t[r[n].cursor_name];return[e,t]}function Ys(r,e,t){let[n,s]=vd(r),i=Sd(n),o=0;return r.forEach(a=>{console.log("cursor.service",a,a.service),o=tn(0,i,o),console.log("header",o),o=gd(i,o,a.service||0),console.log("service",o),o=tn(s[a.cursor_name],i,o),console.log("service-name",o),o=md(a.cursor_name,i,o),console.log("name",o),o=wd($.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:on,headers:[{key:"cursor_file_name",value:t}],payload:i}}function kd(r){let e=0,t=[];for(;e<r.byteLength;){let{offset:n}=en(r,e);e=n;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=pd(r,e);s.service=i,e=o;let{value:a,offset:c}=en(r,e);e=c,s.cursor_name=oi(r,e,e+a),e+=a;let{value:d,offset:l}=_d(r,e);s.cursor=d.toNumber(),e=l,t.push(s)}return t}function xd(){return{frameType:on,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var rn=class{constructor(e,t,n){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=n,this._qosDB=ci(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?Ys(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Ys(t,0,this._cursorFileName):xd()}}async set(e,t,n){return console.log("setdb",e,t,n),this._qosDB.set({cursor_name:e,cursor:t,service:n})}async setCursors(e){let t=kd(e);for(let n of t)console.log("setcursor",t),await this._qosDB.set(n)}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}},Id="__x_msg_qos__";async function li(r){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:n}=this._options,s=r||Id;try{return this._cursorManager?r&&this._cursorManager.updateCursorFileName(r):this._cursorManager=new rn(`${t}_${e}_${s}`,s,n),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function Td(r,e){let t=pe(r.message.headers,"code","-1"),n=pe(r.message.headers,"is_ack","1"),s=Ue(r.message.headers,"x_frontier_msgid"),i=Number(Ue(r.message.headers,"x_frontier_ttl"))||0,o=sn.call(this,r),a=pe(r.message.headers,"x-msg-qos","2"),c=Ue(r.message.headers,"x-msg-cursor_name"),d=Number(Ue(r.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let l=o.isQoSMessage?await di.call(this):null;if(r.message.service>0&&n&&!t||r.message.service>0){if(s&&o.isQoSMessage&&l)return await l.get(s)||(this._dispatchMessageEvent(r),await l.set(s,Date.now()+i)),e();if(a){let u=await li.call(this);if(!u)return this._dispatchMessageEvent(r),e();let f=await u.get(c)??-1;if(f<d)this._dispatchMessageEvent(r),u.set(c,d,r.message.service);else throw new Error(`recevied message cursor ${d} larger than local cursor ${f}`);return e()}return this._dispatchMessageEvent(r),e()}}async function Rd(r,e){let t=sn.call(this,r);if(!t.isQoSMessage)return e();let n=await di.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await n.del(s);e()}async function Pd(r,e){let t=r.message.frameType===Ed,n=r.message.frameType===on;if(!t&&!n)return e();let s=Ue(r.message.headers,"cursor_file_name");if(!s)return e();let i=await li.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:$.fromNumber(this._seqId++),LogID:$.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Zs(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(n){let o=r.message.payload;o&&i.setCursors(o)}}var Ad=async function(r,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},Cd=async function(r,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},Od=async function(r,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(r),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n} success`),e()},Kt=class extends ct{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=$e,this._isNode=rd,this._isMiniTT=Ie,this._isMiniWX=lt,this._isWorker=at,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{Xs(this,i,[Ad,Od,Cd])}catch(o){let a=V("error",{message:o.message,code:Ee.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{Xs(this,i,[ud,dd,Rd,Pd,Td,ld])}catch(c){let d=V("error",{message:c.message,code:Ee.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(V("error",{message:c,code:Ee.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(V("error",{message:i.message,code:Ee.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(Y("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(Y("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 ad(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(Y("close",{code:i.code,reason:c}));let d=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(V("error",{message:d,code:Ee.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(Y("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:Oc,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:n}=e,s=Array.isArray(t)?t:typeof t=="string"?[t]:[];if(!s||s.length===0)throw new Error("please provide valid url");if(!sd(n))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Qt(s,this._options.maxRetries),this._pingLossCounter=new Qr(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=Ks("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:n,bddID:s,ttwID:i,accessKey:o,aID:a,customParams:c={},enableAutoAck:d,enableQoS:l,QoSLevel:u,env:f}=this._options,m,p,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(m=location&&location.protocol=="https:"?"wss://":"ws://",p=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${m}${p}`):(m="wss://",p=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(p)?p:`${m}${p}`);let S=s?"bd_did":i?"ttwid":"device_id",O=s||i||n;if(!O||!S)throw new Error("please provide bddID, deviceID or ttwID");let ee=typeof c=="function"?await c():c,te=f?od(f.xUseEnv,f.xTTEnv):{},L=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[S]:O,xsack:d?1:0,xaack:d?1:0,xsqos:l?1:0,qos_level:l?u:void 0,qos_sdk_version:2,...te},ee),g=Object.keys(L).reduce((E,T)=>L[T]!==void 0?`${E}${E?"&":"?"}${T}=${L[T]}`:E,"");return`${_}/ws/v2${g}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:t}=this._options;if(e){let s=this._endpointManager?.getCurrentEndpoint(),i=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(i){let a=`connect ${s} timeout, max retries reached, will use backup endpoint ${i} to retry`,c=V("error",{message:a,code:Ee.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(V("error",{message:a,code:Ee.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=Ks("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(s)}let n=this._endpointManager?.getCurrentEndpointTriesCount()||0;n>1&&await this._wait(n-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=nd({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:n,reconnectIntervalGrowFactor:s}=this._options,i=t*Math.pow(s,e-1);return i>n?n: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="",n=!1){this._ws&&this._destroyWebSocket(e,t,n)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let t=js(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="",n=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,n&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let i=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(Y("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(Y("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(Y("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(Y("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,n)=>(t+=n&&n.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 n=await ai(e),s=id(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?Cc(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let f={SeqID:$.fromNumber(this._seqId++),LogID:$.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:n,LogIDNew:u},m=js(f);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(m),this._debug("sent",f)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(m),this._debug("enqueue",f)):(this._messageQueue.shift(),this._messageQueue.push(m)),{seqID:this._seqId,logID:a,logIDNew:u}}async reconnect(e){let{url:t}=e||{},n=Array.isArray(t)?t:typeof t=="string"?[t]:[];e&&Object.assign(this._options,e),n&&n.length?this._endpointManager=new Qt(n,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 n=()=>{e("success"),this.off("ping_once_success",n),this.off("ping_once_timeout",s)},s=()=>{t("timeout"),this.off("ping_once_success",n),this.off("ping_once_timeout",s)};this.on("ping_once_success",n),this.on("ping_once_timeout",s),this._ping()})}};var Xl=le(io(),1),Yl=le(ir(),1),Zl=le(Ge(),1),eu=le(_n(),1),tu=le(Sn(),1),ru=le(Tn(),1),po=le(dr(),1),nu=le(go(),1);var mo=po.default;k();var D=w("upstream.frontier"),wo="application/json",yo="none",ur=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){D.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:es,...At(this.opts.ppeOverride)};class t extends mo{constructor(a){super(a,Zn,{headers:e})}send(a,...c){if(Qn("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");D.debug("WS raw frame out",{bytes:d.byteLength,headHex:l})}catch(d){D.warn("WS raw frame dump failed",{err:String(d)})}super.send(a,...c)}}let n=ns(this.opts.urlOverride),s={url:n,ws:t,fpID:Yn,aID:Pt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:wo,force:!0},payloadEncoding:{encoding:yo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new Kt(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;D.info("frontier opened",{url:n,remoteDeviceId:this.opts.handshake.deviceId,initial:o,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:o})).catch(a=>D.warn("onConnect handler threw (ignored)",{err:String(a)}))},i.onclose=o=>{this.opened=!1,D.info("frontier closed",{code:o.code,reason:o.reason,willReconnect:o.willReconnect})},i.onerror=o=>{D.warn("frontier error",{code:o.code,msg:o.message})},i.onmessage=o=>this.handleMessage(o),this.fws=i,await i.connect()}async stop(e){let t=this.fws;if(t){this.fws=null,this.opened=!1;try{t.close(1e3,e??"bridge shutdown")}catch(n){D.warn("frontier close threw (ignored)",{err:String(n)})}}}async send(e){let t=this.fws;if(!t)throw new h("UPSTREAM_DISCONNECTED","frontier upstream not started");let n=JSON.stringify(e),s=e;D.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:n.length});try{await t.send(n,{service:33555712,method:1,payloadType:wo,payloadEncoding:yo})}catch(i){throw new h("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(i)}`,{cause:i})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let t=e.message?.service;if(t!==33555712){D.debug("drop non-adapter frontier frame",{service:t});return}let n=ou(e);if(!n){D.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){D.debug("frame received but no onFrame handler",{size:n.length});return}let s;try{s=JSON.parse(n)}catch(i){D.warn("frontier message JSON parse failed",{err:String(i),head:n.slice(0,80)});return}D.info("frontier frame in",{logid:iu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id}),Promise.resolve(this.handler(s)).catch(i=>D.warn("frontier frame handler threw",{err:String(i)}))}};function iu(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function ou(r){let e=r.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 Pn=w("upstream.switchable"),fr=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;Pn.info("swap upstream",{reason:t});let n=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 Pn.error("swap target start failed, reverting",{err:String(s)}),this.inner=n,s}await n.stop(t??"swapped").catch(s=>Pn.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 An=w("upstream"),wt=class{handler=null;async start(){An.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){An.info("NoopUpstream stopped",{reason:e})}async send(e){An.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();F();k();F();import{execSync as au}from"node:child_process";import{readFileSync as So,unlinkSync as cu}from"node:fs";import{mkdir as du,readFile as Eo,unlink as vo,writeFile as lu}from"node:fs/promises";import{dirname as uu}from"node:path";var fu=w("single-instance"),hr=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??x().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&&(fu.warn("removing stale pid file",{stalePid:e}),await vo(this.pidFile).catch(()=>{})),await du(uu(this.pidFile),{recursive:!0}),await lu(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Eo(this.pidFile,"utf8")).trim()===String(process.pid)&&await vo(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Eo(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=So(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=au(`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{So(this.pidFile,"utf8").trim()===String(process.pid)&&cu(this.pidFile)}catch{}})}};var y=w("daemon"),hu="coze-bridge-daemon";async function Io(){let r=new hr({processTitle:hu}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await jt(),n=t??{};Rr({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let g=new rt;n.frameworksCache=await g.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(n.frameworksCache)})}catch(g){y.warn("framework detection failed",{err:String(g)})}await nt(n);let s=new fr(new wt),i=x(),o=null,a=new Jt({upstream:s,paths:i,bridgeConfig:n,sessionSpawner:async(g,E,T,re)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(g,E,T,re)}});await pu(i,a);let c=new Wt({paths:i,config:n,registry:a});o=c;let d,l,u=null,f=null;a.registerExtension("_agent/create",async g=>c.createAgent(g.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let m={},p=new Nt({agents:a.agents,disposeAndMarkDisconnected:async(g,E)=>{let T=a.agents.get(g);T&&(await T.dispose(`disconnect: ${E}`).catch(re=>y.warn("dispose during disconnect failed (ignored)",{agentId:g,err:String(re)})),T.status="disconnected",a.unregister(g)),a.disconnectedAgents.add(g)},detailSyncer:async g=>{if(!m.ref)throw new Error("agent-detail-sync not initialized yet");await m.ref.syncOne(g)}});a.registerExtension("_agent/listSkills",g=>p.listSkills(g.params)),a.registerExtension("_agent/addSkills",g=>p.addSkills(g.params)),a.registerExtension("_agent/removeSkills",g=>p.removeSkills(g.params)),a.registerExtension("_agent/getFileTree",g=>p.getFileTree(g.params)),a.registerExtension("_agent/getFileContent",g=>p.getFileContent(g.params)),a.registerExtension("_agent/update",g=>p.updateAgent(g.params)),a.registerExtension("_agent/disconnect",g=>p.disconnectAgent(g.params)),a.registerExtension("_agent/switchModel",g=>p.switchModel(g.params)),a.registerExtension("_agent/reset",g=>p.resetAgent(g.params)),a.registerExtension("_agent/repair",g=>p.repairAgent(g.params));let _=new Tt({paths:i,handlers:p,sendDetail:g=>a.sendRequest("_agent/detail",g)});m.ref=_,s.onConnect(({initial:g})=>{y.info("frontier upstream connected, triggering detail sync",{initial:g}),_.syncAll(g?"initial-connect":"reconnect").catch(E=>y.warn("detail sync top-level error (ignored)",{err:String(E)}))});let S=new Vt({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:u??"",frameworksCache:n.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async g=>{let E=g,T=E?.privatecode,re=E?.pairing_code;if(!T||!re)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Oe=Ct(E.env),Ke=E.handshake_url,Er=E.frontier_url,vr=gu(E.env,Ke,Er),zn=!!d&&d!==T,qn=l!==void 0&&l!==vr,Gn=zn||qn;if(Gn){y.warn("pair config switched, resetting agents",{pcChanged:zn,envChanged:qn,previousPc:d?ko(d):"",nextPc:ko(T),previousEnvKey:l??"",nextEnvKey:vr});for(let ye of[...a.agents.values()])await ye.dispose("pair config switch").catch(()=>{}),a.agents.delete(ye.agentId);await s.swap(new wt,"pair switch").catch(()=>{})}let Hn=await is({privatecode:T,...Ke?{endpoint:Ke}:{},ppeOverride:Oe});u=Hn.deviceId,Rr({deviceId:u,pid:process.pid});let Fo=new ur({handshake:Hn,privatecode:T,...Er?{urlOverride:Er}:{},ppeOverride:Oe});await s.swap(Fo,"pair");let Uo=Object.keys(n.frameworksCache??{});try{let ye=await a.sendRequest("_agent/pair",{pairCode:re,patToken:T,frameworks:Uo,_meta:{cozeDeviceId:u}});y.info("_agent/pair ok",{pairResult:ye}),d=T,l=vr,f||(f=new Dt({core:a,getDeviceId:()=>u??""})),f.start(),Gn&&xo(i,c).catch(Ne=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let kr;return E.agent_id&&(kr=await mu(E.agent_id,i,c,Ne=>a.sendRequest("_agent/detail",Ne)).catch(Ne=>(y.error("--agent-id ensureAgent failed",{agentId:E.agent_id,err:String(Ne)}),{ok:!1,agentId:E.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...kr?{agent:kr}:{}}}catch(ye){return y.error("_agent/pair failed",{err:String(ye)}),{ok:!1,note:`pair failed: ${String(ye)}`}}}},{method:"POST",path:"/_agent/create",handler:async g=>{let E=g;return{ok:!0,result:await c.createAgent(E)}}},{method:"POST",path:"/refresh",handler:async()=>{y.info("IPC /refresh: re-detecting frameworks");let g=new rt;return n.frameworksCache=await g.detectAll(),await nt(n),{ok:!0,frameworks:n.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{L.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:O,token:ee}=await S.start();await a.start(),xo(i,c).catch(g=>y.warn("auto-revive top-level error (ignored)",{err:String(g)}));let te=null,L={port:O,token:ee,core:a,ipc:S,shutdown(g){return te||(y.info("daemon shutdown",{reason:g}),te=(async()=>{f?.stop(),await a.stop(g),await S.stop(),await r.release()})(),te)}};for(let g of["SIGTERM","SIGINT"])process.on(g,()=>{L.shutdown(g).then(()=>process.exit(0))});return y.info("daemon ready",{port:O,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(n.frameworksCache??{}),libVersion:n.libVersion??"dev"}),L}function ko(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function gu(r,e,t){return`${r??""}|${e??""}|${t??""}`}async function pu(r,e){let{readdir:t}=await import("node:fs/promises"),n;try{n=await t(r.agentsRoot)}catch{return}let{loadAgentConfig:s,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(ue(),It));for(let o of n){await i(o,r).catch(a=>y.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await s(o,r);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 mu(r,e,t,n){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ue(),It)),i=await s(r,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:r,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:r,note:i.disconnectedAt?"revived from local config":"connected from local config"}}y.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let o=await n({_meta:{cozeAgentId:r}});if(!o.framework)throw new h("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 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:r,note:c?"cloud agent acknowledged":"created from cloud detail"}}async function xo(r,e){let{readdir:t}=await import("node:fs/promises"),n;try{n=await t(r.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(n.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ue(),It));y.info("auto-revive: scanning local agents on startup",{count:n.length});let i=0,o=0;for(let a of n){let c;try{c=await s(a,r)}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:n.length}),{revived:i,skipped:o,total:n.length}}On();F();import{readFile as Ro}from"node:fs/promises";var we=class{paths;constructor(e){this.paths=e??x()}async probe(e=1e3){let t=await this.readAuth();if(!t)return{kind:"not-running"};try{let n=await this.fetch(t,{method:"GET",path:"/status",timeoutMs:e});return n.status===200?{kind:"connected",...t}:{kind:"stale",reason:`unexpected status ${n.status}`}}catch(n){return{kind:"stale",reason:Iu(n)}}}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([Ro(this.paths.portFile,"utf8"),Ro(this.paths.tokenFile,"utf8")]),n=Number.parseInt(e.trim(),10),s=t.trim();return!Number.isFinite(n)||n<=0||!s?null:{port:n,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,t){let n=t.body!==void 0,s={Authorization:`Bearer ${e.token}`};n&&(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:n?JSON.stringify(t.body):void 0,signal:i.signal}),c=await a.text();return{status:a.status,body:xu(c)}}finally{clearTimeout(o)}}};function xu(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Iu(r){return r instanceof Error?r.message:String(r)}k();F();import{copyFile as Po,mkdir as Tu,readFile as Nn,writeFile as Ru}from"node:fs/promises";import{dirname as Pu,resolve as bn,sep as gr}from"node:path";import{fileURLToPath as Au}from"node:url";k();F();var Ao=w("dist-install");function Cu(r){let e=Au(r),t=Pu(e),n=`${gr}src${gr}`;if(t.includes(n)||t.endsWith(`${gr}src${gr}cli`))return null;let s=bn(t,"index.js"),i=bn(t,"..","package.json");return{dist:s,pkgJson:i}}async function Co(r={}){let e=r.paths??x(),t=Cu(import.meta.url),n=r.sourceDist??t?.dist,s=r.sourcePackageJson??t?.pkgJson;if(!n||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let i;try{i=JSON.parse(await Nn(s,"utf8")).version??"unknown"}catch(u){return Ao.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 jt(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Nn(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await Tu(e.libDir,{recursive:!0}),await Po(n,e.libEntry),await Po(`${n}.map`,`${e.libEntry}.map`).catch(()=>{});let c=bn(e.libDir,"package.json"),d=`${JSON.stringify({type:"module"},null,2)}
|
|
93
|
+
`;return await Nn(c,"utf8").catch(()=>null)!==d&&await Ru(c,d),o.libVersion=i,await nt(o,e.configFile),Ao.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 Qu=w("cli");function Qe(r,e){let t=[],n;for(let s=0;s<r.length;s++){let i=r[s];if(i===e){n=r[s+1],s+=1;continue}if(i.startsWith(`${e}=`)){n=i.slice(e.length+1);continue}t.push(i)}return{value:n,rest:t}}function Ku(r){let e=r.slice(2);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:n,rest:s}=Qe(t,"--pat-token");t=s;let{value:i,rest:o}=Qe(t,"--pair-code");t=o;let{value:a,rest:c}=Qe(t,"--env");t=c;let{value:d,rest:l}=Qe(t,"--handshake-url");t=l;let{value:u,rest:f}=Qe(t,"--frontier-url");t=f;let{value:m}=Qe(t,"--agent-id");if(!n||!i)return{mode:"help"};let p={mode:"pair",privatecode:n,pairingCode:i};return a&&(p.env=a),d&&(p.handshakeUrl=d),u&&(p.frontierUrl=u),m&&(p.agentId=m),p}var Xu=`
|
|
93
94
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
94
95
|
|
|
95
96
|
Usage:
|
|
@@ -116,35 +117,35 @@ Auto-connect agent (optional):
|
|
|
116
117
|
|
|
117
118
|
Internal:
|
|
118
119
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
119
|
-
`.trimStart();async function
|
|
120
|
-
`),1;if(
|
|
121
|
-
`),1;let
|
|
122
|
-
${JSON.stringify(
|
|
123
|
-
`),0}async function
|
|
124
|
-
`),0;if(
|
|
125
|
-
`),0;try{return await
|
|
126
|
-
`),0}catch(
|
|
127
|
-
`),1}}async function
|
|
128
|
-
`),1;try{let
|
|
129
|
-
${JSON.stringify(
|
|
130
|
-
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(
|
|
131
|
-
`),1)}catch(
|
|
132
|
-
`),1}}async function
|
|
133
|
-
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(
|
|
134
|
-
`)}await new Promise(
|
|
135
|
-
`)}catch(
|
|
136
|
-
`)}let
|
|
137
|
-
`)}catch(
|
|
120
|
+
`.trimStart();async function Mo(r=process.argv,e={}){let t=Ku(r);switch(t.mode){case"help":return process.stdout.write(Xu),0;case"daemon":{try{await Io()}catch(n){return Qu.error("daemon start failed",{err:String(n)}),1}return new Promise(()=>{})}case"status":return Yu(e);case"stop":return Zu(e);case"refresh":return ef(e);case"uninstall":return tf(e);case"install-service":return rf();case"pair":{let n={};return t.env&&(n.env=t.env),t.handshakeUrl&&(n.handshakeUrl=t.handshakeUrl),t.frontierUrl&&(n.frontierUrl=t.frontierUrl),nf(t.privatecode,t.pairingCode,e,n,t.agentId)}}}async function Bo(r){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(r.pidFile).catch(()=>{}),e(r.portFile).catch(()=>{}),e(r.tokenFile).catch(()=>{})])}async function Yu(r){let e=r.paths??x(),t=new we(e),n=await t.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
121
|
+
`),1;if(n.kind==="stale")return await Bo(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
122
|
+
`),1;let s=await t.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
123
|
+
${JSON.stringify(s.body,null,2)}
|
|
124
|
+
`),0}async function Zu(r){let e=r.paths??x(),t=new we(e),n=await t.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
125
|
+
`),0;if(n.kind==="stale")return await Bo(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
126
|
+
`),0;try{return await t.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
127
|
+
`),0}catch(s){return process.stdout.write(`coze-bridge: stop failed: ${String(s)}
|
|
128
|
+
`),1}}async function ef(r){let e=new we(r.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
129
|
+
`),1;try{let n=await e.request({method:"POST",path:"/refresh"});return n.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
130
|
+
${JSON.stringify(n.body,null,2)}
|
|
131
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(n.body)}
|
|
132
|
+
`),1)}catch(n){return process.stderr.write(`coze-bridge: refresh failed: ${String(n)}
|
|
133
|
+
`),1}}async function tf(r){let e=new we(r.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
134
|
+
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(i){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(i)}
|
|
135
|
+
`)}await new Promise(i=>setTimeout(i,500))}if(!r.skipSupervisor)try{let{getSupervisor:i,buildContext:o}=await Promise.resolve().then(()=>($n(),Un)),a=i();await a.uninstall(o()),process.stdout.write(`coze-bridge: ${a.platform} supervisor unregistered
|
|
136
|
+
`)}catch(i){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(i)}
|
|
137
|
+
`)}let n=r.paths??x(),{rm:s}=await import("node:fs/promises");try{await s(n.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${n.cozeRoot}
|
|
138
|
+
`)}catch(i){return process.stderr.write(`coze-bridge: remove failed: ${String(i)}
|
|
138
139
|
`),1}return process.stdout.write(`coze-bridge: uninstalled
|
|
139
|
-
`),0}async function
|
|
140
|
-
`),await
|
|
140
|
+
`),0}async function rf(){try{let{getSupervisor:r,buildContext:e}=await Promise.resolve().then(()=>($n(),Un)),t=r(),n=e();return process.stdout.write(`coze-bridge: installing ${t.platform} supervisor...
|
|
141
|
+
`),await t.install(n),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
141
142
|
`),0}catch(r){return process.stderr.write(`coze-bridge: --install-service failed: ${String(r)}
|
|
142
|
-
`),1}}async function
|
|
143
|
-
`),(await
|
|
144
|
-
`)}let
|
|
145
|
-
`),await
|
|
146
|
-
`),1;let
|
|
147
|
-
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
148
|
-
`),1)}catch(
|
|
149
|
-
`),1}}async function
|
|
143
|
+
`),1}}async function nf(r,e,t,n={},s){let i=new we(t.paths),o=t.spawnDaemon??To;if(!t.skipDistInstall){let d=await Co({paths:t.paths});d.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${d.fromVersion} \u2192 ${d.toVersion}
|
|
144
|
+
`),(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}
|
|
145
|
+
`)}let a=await i.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
146
|
+
`),await o({paths:t.paths}),a=await sf(i,t.waitTimeoutMs??1e4,t.sleep??of),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
|
|
147
|
+
`),1;let c={privatecode:r,pairing_code:e};n.env&&(c.env=n.env),n.handshakeUrl&&(c.handshake_url=n.handshakeUrl),n.frontierUrl&&(c.frontier_url=n.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"})
|
|
148
|
+
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(d.body)}
|
|
149
|
+
`),1)}catch(d){return process.stderr.write(`coze-bridge: pair failed: ${String(d)}
|
|
150
|
+
`),1}}async function sf(r,e,t){let n=Date.now()+e;for(;Date.now()<n;){let s=await r.probe(500);if(s.kind==="connected")return s;await t(200)}return r.probe(500)}function of(r){return new Promise(e=>setTimeout(e,r))}Mo(process.argv).then(r=>process.exit(r),r=>{process.stderr.write(`fatal: ${r instanceof Error?r.stack??r.message:String(r)}
|
|
150
151
|
`),process.exit(1)});
|