coze-bridge 0.1.13 → 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.
Files changed (2) hide show
  1. package/dist/index.js +53 -52
  2. 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 Ua=Object.create;var cr=Object.defineProperty;var Ka=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Ga=Object.getPrototypeOf,ja=Object.prototype.hasOwnProperty;var Y=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Ie=(r,e)=>()=>(r&&(e=r(r=0)),e);var se=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),bs=(r,e)=>{for(var i in e)cr(r,i,{get:e[i],enumerable:!0})},Wa=(r,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let x of Ha(e))!ja.call(r,x)&&x!==i&&cr(r,x,{get:()=>e[x],enumerable:!(a=Ka(e,x))||a.enumerable});return r};var De=(r,e,i)=>(i=r!=null?Ua(Ga(r)):{},Wa(e||!r||!r.__esModule?cr(i,"default",{value:r,enumerable:!0}):i,r));import{chmod as Ja,mkdir as Va,readFile as Ya,rename as vs,writeFile as Ss}from"node:fs/promises";import{dirname as $a}from"node:path";async function Ht(r){try{let e=await Ya(r,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Gt(r,e,i){await Va($a(r),{recursive:!0});let a=`${JSON.stringify(e,null,2)}
9
- `,x=`${r}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{i?.mode!==void 0?await Ss(x,a,{encoding:"utf8",mode:i.mode}):await Ss(x,a,"utf8"),await vs(x,r),i?.mode!==void 0&&await Ja(r,i.mode)}catch(u){await vs(x,x).catch(()=>{});let{rm:d}=await import("node:fs/promises");throw await d(x,{force:!0}).catch(()=>{}),u}}var xr=Ie(()=>{"use strict"});function As(r){return Wt[Es]<=Wt[r]}function ur(r){Cs={...r}}function jt(r,e,i,a){if(Wt[r]<Wt[Es])return;let x=JSON.stringify({ts:new Date().toISOString(),level:r,module:e,msg:i,...Cs,...a});r==="error"||r==="warn"?Xa.write(`${x}
10
- `):Qa.write(`${x}
11
- `)}function N(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=>N(`${r}.${e}`)}}var Wt,Es,Qa,Xa,Cs,K=Ie(()=>{"use strict";Wt={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"})(),Qa=process.stdout,Xa=process.stderr,Cs={}});import{homedir as Za}from"node:os";import{join as te}from"node:path";function H(r){let e=r??Za(),i=te(e,".coze"),a=te(i,"bridge"),x=te(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:x,libEntry:te(x,"index.js"),pidFile:te(a,"bridge.pid"),portFile:te(a,"bridge.port"),tokenFile:te(a,"bridge.token"),logFile:te(a,"bridge.log"),installLock:te(a,"install.lock"),configFile:te(a,"config.json"),agentsRoot:te(i,"agents")}}function Te(r,e=H()){let i=te(e.agentsRoot,r);return{root:i,config:te(i,"config.json"),workspace:te(i,"workspace"),logs:te(i,"logs")}}var ae=Ie(()=>{"use strict"});var Yt={};bs(Yt,{AGENT_CONFIG_FILE_MODE:()=>Jt,enforceAgentConfigMode:()=>n0,loadAgentConfig:()=>ce,persistAgentSessions:()=>fr,persistAgentSkills:()=>Vt,saveAgentConfig:()=>me});import{chmod as e0,stat as t0}from"node:fs/promises";function ce(r,e){return Ht(Te(r,e).config)}function me(r,e){return Gt(Te(r.agentId,e).config,r,{mode:Jt})}async function n0(r,e){if(process.platform==="win32")return;let i=Te(r,e).config;try{let a=await t0(i);if(!a.isFile())return;let x=a.mode&511;x!==Jt&&(await e0(i,Jt),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 fr(r,e,i){let a=await ce(r,i);a&&(a.sessions=Object.fromEntries(e),await me(a,i))}async function Vt(r,e,i){let a=await ce(r,i);a&&(a.skills=e,await me(a,i))}var ks,Jt,Ue=Ie(()=>{"use strict";xr();K();ae();ks=N("agent-config"),Jt=384});var ui=se(Q=>{"use strict";var S=P;(function(r,e){let i=P,a=r();for(;;)try{if(parseInt(i(1052))/1+parseInt(i(839))/2+parseInt(i(1598))/3+-parseInt(i(538))/4+-parseInt(i(1755))/5*(parseInt(i(1781))/6)+-parseInt(i(734))/7+parseInt(i(1360))/8*(parseInt(i(1292))/9)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Sn,778249);var mc=Object[S(1588)+"operty"],wc=Object[S(1318)+"opertyNames"],ii=(r,e)=>function(){return r&&(e=(0,r[{OyzEe:function(u,d){return u(d)}}[S(1628)](wc,r)[0]])(r=0)),e},_c=(r,e)=>{let i={cdVaZ:function(x,u,d,h){return x(u,d,h)}};for(var a in e)i.cdVaZ(mc,r,a,{get:e[a],enumerable:!0})};function yc(){return ei||(ei=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bc(){let r=S;return ti||(ti=[IDBCursor[r(1268)+"e"].advance,IDBCursor[r(1268)+"e"][r(1104)],IDBCursor[r(1268)+"e"][r(1104)+r(497)+"ey"]])}function vc(r){let e=S,i={bwUDx:"success",hofvv:"error",cbpxP:function(x,u){return x(u)},EPtSg:function(x){return x()},UiMKb:function(x,u){return x instanceof u}},a=new Promise((x,u)=>{let d=P,h={aFCWh:function(_){return i[P(1876)](_)}},m=()=>{let _=P;r[_(938)+_(1425)+_(733)](i[_(999)],w),r[_(938)+_(1425)+"ner"](i[_(940)],b)},w=()=>{let _=P;i[_(1769)](x,Ce(r[_(1456)])),m()},b=()=>{let _=P;u(r[_(533)]),h[_(783)](m)};r[d(1149)+"Listener"](i[d(999)],w),r["addEvent"+d(1538)](i[d(940)],b)});return a[e(568)](x=>{let u=e;i[u(1280)](x,IDBCursor)&&pr[u(510)](x,r)})[e(1163)](()=>{}),bn.set(a,r),a}function Sc(r){let e=S,i={szFWk:e(1016),tEmio:"error",mjvQQ:e(1379),rrkiu:function(x,u){return x>u},rQYag:function(x,u){return x===u},SAgiY:e(408),jpgxj:function(x){return x()},xHFEH:function(x,u){return x(u)},kTSQu:e(516)+"or"};if(yn[e(1270)](r))return;let a=new Promise((x,u)=>{let d=e,h={yIIXm:function(_,C){return i.rrkiu(_,C)},fjRVN:function(_,C){return i[P(1535)](_,C)},nFMRx:i[d(1184)],Kehvq:function(_){return i[d(1710)](_)},EeUNy:function(_,C){return i[d(1707)](_,C)},cqdsJ:i[d(1233)]},m=()=>{let _=d;r[_(938)+"entListe"+_(733)](i[_(1446)],w),r["removeEventListe"+_(733)](i.tEmio,b),r["removeEventListe"+_(733)](i[_(1075)],b)},w=()=>{let _=d,C={KpeWr:function(L,I){return h[P(707)](L,I)}};if(h[_(1024)](h[_(1009)],"wtynF"))h[_(1166)](x),m();else return this[_(1062)+"ndex"]==this[_(1217)+"s"].length?!0:C.KpeWr(this[_(1489)+"ndpointT"+_(1338)+"t"],this[_(1770)+"es"])},b=()=>{let _=d;h[_(1589)](u,r[_(533)]||new DOMException(h[_(625)],"AbortError")),m()};r[d(1149)+"Listener"](i[d(1446)],w),r[d(1149)+d(1538)](i[d(623)],b),r[d(1149)+d(1538)](i[d(1075)],b)});yn[e(510)](r,a)}function Ec(r){vn={EEzQH:function(i,a){return i(a)}}.EEzQH(r,vn)}function Cc(r){let e=S,i={JJSeL:function(a,x){return a(x)},gcmNU:function(a,x){return a(x)},KPhwu:function(a,x){return a>x},HRLhA:function(a,x){return a+x},yNmxV:e(778)+e(523),WMbCv:function(a,x){return a(x)},JGSEm:function(a,x){return a===x},CqRnn:function(a,x){return a in x},mbwpd:function(a){return a()},FXYgv:e(1746)};if(i[e(638)](r,IDBDatabase[e(1268)+"e"][e(660)+"ion"])&&!i.CqRnn("objectSt"+e(541),IDBTransaction[e(1268)+"e"]))return function(a,...x){let u=e,d=r[u(1236)](i.JJSeL(Tt,this),a,...x);return gr[u(510)](d,a.sort?a[u(1169)]():[a]),i[u(468)](Ce,d)};if(i[e(572)](bc).includes(r))if(i.JGSEm(i.FXYgv,e(1406))){let a=_0x4a22df[e(646)];if(i[e(418)](i[e(1802)](a,_0x2e770d),_0x2b3adb[e(1199)]))throw new _0x4fa9b5(i[e(1115)]);return _0x12f499.offset+=_0x51c418,a}else return function(...a){let x=e;return r[x(1203)](Tt(this),a),Ce(pr[x(1528)](this))};return function(...a){let x=e;return Ce(r[x(1203)](i[x(787)](Tt,this),a))}}function Ac(r){let e=S,i={OWoPe:e(1368),FlgFu:function(a,x){return a(x)},knZHw:function(a,x){return a instanceof x},QZexg:function(a,x){return a(x)},OKxUM:function(a,x,u){return a(x,u)},VuAbz:function(a){return a()}};return typeof r===i[e(1819)]?i.FlgFu(Cc,r):(i[e(675)](r,IDBTransaction)&&i[e(1245)](Sc,r),i[e(685)](oi,r,i.VuAbz(yc))?new Proxy(r,vn):r)}function Ce(r){let e=S,i={eJePC:function(x,u){return x(u)},cXvIi:function(x,u){return x!==u}};if(r instanceof IDBRequest)return i[e(1451)](vc,r);if(wn[e(1270)](r))return wn.get(r);let a=i[e(1451)](Ac,r);return i.cXvIi(a,r)&&(wn[e(510)](r,a),bn[e(510)](a,r)),a}function P(r,e){r=r-386;let i=Sn(),a=i[r];if(P.OpPqTh===void 0){var x=function(m){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",b="",_="";for(let C=0,L,I,R=0;I=m.charAt(R++);~I&&(L=C%4?L*64+I:I,C++%4)?b+=String.fromCharCode(255&L>>(-2*C&6)):0)I=w.indexOf(I);for(let C=0,L=b.length;C<L;C++)_+="%"+("00"+b.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(_)};P.KaQcMq=x,P.FNDdER={},P.OpPqTh=!0}let u=i[0],d=r+u,h=P.FNDdER[d];return h?a=h:(a=P.KaQcMq(a),P.FNDdER[d]=a),a}var oi,ei,ti,pr,yn,gr,wn,bn,vn,Tt,ni=ii({"node_modules/idb/build/wrap-idb-value.js"(){let r=S,e={MIZEd:function(i,a){return i instanceof a},IdRBs:function(i,a){return i!==a},bGama:r(1556),LEvSR:r(648),uaOxB:r(1145),HMWQs:function(i,a){return i===a},PuHyT:r(1603)+r(541),zbten:r(838),JCEmt:function(i,a){return i(a)},oMatY:function(i,a){return i===a},uaSCS:"YRfjM",JiYZq:function(i,a){return i instanceof a},WpwUH:function(i,a){return i===a}};oi=(i,a)=>a.some(x=>i instanceof x),pr=new WeakMap,yn=new WeakMap,gr=new WeakMap,wn=new WeakMap,bn=new WeakMap,vn={get(i,a,x){let u=r;if(e.MIZEd(i,IDBTransaction))if(e[u(1095)](e.bGama,e[u(1416)])){if(a===e.uaOxB)return yn[u(1528)](i);if(e.HMWQs(a,e[u(1112)]))return i[u(1603)+u(541)]||gr[u(1528)](i);if(a===e[u(780)])return x[u(1603)+u(541)][1]?void 0:x[u(1603)+u(528)](x[u(1603)+"oreNames"][0])}else _0x4146f8[u(1030)](_0x4acadd);return e[u(1023)](Ce,i[a])},set(i,a,x){return i[a]=x,!0},has(i,a){let x=r;return e[x(754)](e.uaSCS,e[x(469)])?e[x(532)](i,IDBTransaction)&&(e[x(754)](a,e[x(947)])||e[x(1806)](a,e[x(780)]))?!0:a in i:_0x2c7ebe}},Tt=i=>bn[r(1528)](i)}}),ai={};_c(ai,{deleteDB:()=>Pc,openDB:()=>kc,unwrap:()=>Tt,wrap:()=>Ce});function kc(r,e,{blocked:i,upgrade:a,blocking:x,terminated:u}={}){let d=S,h={FYzFt:function(b,_,C,L,I){return b(_,C,L,I)},AqYdB:function(b,_){return b(_)},ctnZf:function(b,_){return b(_)},sCeca:function(b,_){return b||_},vvezs:d(1547)+"hange",aLhgE:d(1822),RAWKX:d(1089)+d(1772),qWRts:"blocked"},m=indexedDB[d(1875)](r,e),w=h[d(1014)](Ce,m);if(a)if(d(1822)===h[d(1817)])m["addEvent"+d(1538)](h.RAWKX,b=>{let _=d;h[_(1594)](a,h[_(628)](Ce,m[_(1456)]),b[_(1180)+"on"],b[_(1823)+"on"],h[_(1014)](Ce,m["transact"+_(474)]))});else{let b=this._qosDB[d(1505)+d(848)+"nc"](this[d(1353)]),_=_0x51b547[d(1525)](h.sCeca(b,"{}"));return _0x561aab[d(1035)](_)}return i&&m[d(1149)+"Listener"](h[d(1469)],()=>i()),w[d(568)](b=>{let _=d;u&&b[_(1149)+_(1538)]("close",()=>u()),x&&b[_(1149)+"Listener"](h[_(1886)],()=>x())}).catch(()=>{}),w}function Pc(r,{blocked:e}={}){let i=S,a={swFbl:i(1078),SNKwm:function(u,d){return u(d)}},x=indexedDB[i(544)+i(1777)](r);return e&&x[i(1149)+"Listener"](a[i(865)],()=>e()),a[i(450)](Ce,x)[i(568)](()=>{})}function ri(r,e){let i=S,a={bORpm:i(1605),sbknl:i(551),rswbi:function(m,w){return m!==w},apMmI:function(m,w){return m in w}};if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e===a[i(937)]))return;if(_n[i(1528)](e))return _n[i(1528)](e);let x=e[i(1493)](/FromIndex$/,""),u=a[i(1609)](e,x),d=xi.includes(x);if(!a[i(781)](x,(u?IDBIndex:IDBObjectStore).prototype)||!(d||ci[i(1386)](x)))return;let h=async function(m,...w){let b=i,_=this[b(660)+"ion"](m,d?b(878)+"e":a[b(1357)]),C=_[b(838)];return u&&(C=C[b(455)](w[b(678)]())),(await Promise.all([C[x](...w),d&&_[b(1145)]]))[0]};return _n[i(510)](e,h),h}var ci,xi,_n,Ic=ii({"node_modules/idb/build/index.js"(){let r=S,e={hswFy:function(x){return x()},qgdzi:r(1581)+"ys",KWyBJ:r(1248),wUpwo:r(972),MmGSZ:r(1799),ZNCVx:function(x,u){return x(u)}},i=(r(1752)+"0|5")[r(862)]("|"),a=0;for(;;){switch(i[a++]){case"0":_n=new Map;continue;case"1":e[r(1610)](ni);continue;case"2":ci=[r(1528),"getKey","getAll",e[r(1563)],r(429)];continue;case"3":e[r(1610)](ni);continue;case"4":xi=[r(1006),e[r(1855)],e.wUpwo,e[r(994)]];continue;case"5":e[r(1512)](Ec,x=>({...x,get:(u,d,h)=>ri(u,d)||x[r(1528)](u,d,h),has:(u,d)=>!!ri(u,d)||x[r(1270)](u,d)}));continue}break}}}),Dc={idb:function(r){let e=S;r[e(1887)]=Promise[e(1061)]()[e(568)](()=>(Ic(),ai))[e(568)](function(i){return i})}},si={};function Ee(r){let e=S,i={XgrFo:e(681)+"0",WkxOJ:function(h,m){return h!==m}},a=i[e(1327)][e(862)]("|"),x=0;for(;;){switch(a[x++]){case"0":return d[e(1887)];case"1":var u=si[r];continue;case"2":var d=si[r]={exports:{}};continue;case"3":Dc[r](d,d[e(1887)],Ee);continue;case"4":if(i[e(801)](void 0,u))return u[e(1887)];continue}break}}function Sn(){let r=["y2XQvuO","u0LbCNK","uLHIAhm","r091q1O","rvjst1i","y2jWEfa","Bwf4uMv0CMK","AMDcvxq","zwvKzwq","AMTABNi","yMfSrxzLBNq","AM9PBG","ihzHBgLKigq","DgfIyxnL","BeviDee","zgf0yq","ruDcCM4","mJrfzxPetxG","rNjVBNrPzxi","qw5UD2W","BfHWu2C","x2nYzwf0zvm","q09otKvdveK","Bwf4tg9ZC0m","CMvWBgfJzui","suvRAuS","sLzvwLC","nNWXFdb8nW","tMjpvLi","yxjdqNa","z0nWzfG","x19LC01Vzhu","ze9NAe0","BNHgEgS","zw1VvuO","y2XLyxi","zLbkDNO","AKPVB20","sfjmAee","zw5JB2rPBMC","u1nIDhi","DxrMofDYAxq","v3b3vuG","C2vrAxu","Bu5rC2G","BezSDxnO","sKDlsvG","BfrqEM8","ywPjzeC","yLP6vMK","r3nOtM4","zvfKvxy","DxnLCKLW","yuXOz0u","zxq9DxrMltG","t1DVugu","A2vmq24","CLzHBhvLCW","CgPKCK0","BMv3vMvYC2K","q0D0uNa","Bwv0Ag9K","wLrtqNi","AwPmvuu","CMvZzxrfBMq","yxrHlcbKyxq","CvjUENK","q0Xpu0LorW","sfLIuvy","B3bLBKrc","Du5sD3e","EhfWvvu","sMD3zgK","yw5Hz2vY","x3jLBw92zvC","BML0AwfSAxO","v0DXz2e","AxmGDw5Kzwy","ruTMC0q","BgvUz3rO","CuvMAui","AgLNAa","BhnhD2m","v3vZu0S","uNLUCLC","yuH1uuG","u3LSBxq","yM9L","CMvKDwnL","ywnRtxnNswq","y25Hz3u","s1D5qKO","DKL3uvq","sLzkA0q","Cg9W","y29UC3rYDwm","yu9YreK","y3nWBMO","y2zHCuK","AxnFywnR","A0LuBei","r3Hszuq","B2nRzxq","x3bPBMDqB24","qNHkCKW","ALncDwq","x29UugfNzu4","x29WDgLVBNm","DeLUDgvYy2u","B3PnAg8","zMrKueS","B3bLBG","rvb0u2C","DvjAq2i","qNz0BLe","yxvks28","zK1PDgu","wfzrCLG","y3jLyxrLq2W","zxf1ywXZ","ExzuEhm","Dgntww8","DNzLENm","zxHWB3j0CW","x3bHDgHlzxK","zMLUza","C3rquLy","y3jLyxrLuMu","D1Hvv04","AxnszwfKEq","Dg9Y","CLzLD0m","CMfTzq","vvP1s3O","ywWGy3vYC28","DhDVu1m","BwvKAwf0zwW","zevgvMW","rNPfA1m","z1rPBwvVDxq","CYbPBNn0yw4","BMrLEa","vxjkAg0","rxnUswG","yvPYv08","vKHZyxm","ywDLu2HVDW","sKLxrvi","tufyx1jfvfi","x2HHBMrSzu8","Aw5KzxHpzG","x3jLywr5q2W","Dw5KzwzPBMu","yuPXBgW","v2X6BKm","zK5Kz3u","CNnVCL9Uyw0","y1fSz3m","DMfSDwu","yNLL","uuzVswy","D3r5BKy","zxjFBxnNAwq","rLDt","CgjICdi","ww9PCva","DefwALm","zMPuDuy","z0PNAgi","DgTzEwS","x3nLBMrby2S","s1bOD3u","q2fgvwS","EvzcqMO","Dgv4DfbHEwW","AxnAzxjV","yxnKve4","CMvUDevUzha","wxzOqLC","Ahr0Ca","Bg9Nsurhzw4","zcWGDw5RBM8","y291BNq","ANPWEMS","quzhqMm","yMrFzgLK","DuHvEem","AvvTuwm","suz6D2m","B25pCgvU","uxjvt3e","C3rYAw5NAwy","DcbVzIbYyw4","y1PHqu4","CxvYvKS","uuHsEee","DKnTug0","x3DZ","Aw5L","t29TzMG","B25ozxr3B3i","x2rPC2nVBM4","v3LYtwq","u05lD20","Eu9eDeO","zgTAALy","yw5Nzq","D1LNANC","Aw5KzxG","BxHnBM4","z2HrB1e","A0f3B2u","v0vIqum","zw5XDwv1zq","qw1VDw50","u0TjAu0","B25LCNjVCG","uu9Otfe","icSG","CNfivg0","AuzAuw0","z2nTtLu","Dwftq1m","wevzy1K","ywrKt25L","yMfuEwK","s1fWu2e","Aw9U","zwPJAKK","wKXwCwu","ug9jsgy","y3r4","t1HsweK","zw5HyMXLqxu","Bhj4AMG","zNjHBwvuExa","ChvZAa","BMDLza","DvjlChu","CYbWyxjHBxm","vgLsse8","yxbWBgLJyxq","z2v0qwXS","wuvcqwC","x2HHBMrSzva","tNnpuhm","CgLUz1rPBwu","tgz0BLu","ywrKq291BNq","rgDPANG","uhjPBwfYEuS","ugTrr3u","AvnuwwC","rfjIwem","B3rvtg0","uKrfBeO","zfbPBwq","z2v0sxrLBq","q3vZDg9Trxi","Aw9Ul2PZB24","ywDLsgLKzq","yMDuChO","wgHvzu8","C2v0","whPJCMK","z3LhteS","zKfrBvm","C2jkENK","wfDRwum","qwjVCNrfCNi","B3bLBIa","uNPcs2u","tKHAC1a","yMLUyxj5","DhjPBq","s2nsD3a","DcbSAw1PDa","BwnMzNq","CMvTB3zLq2G","DgrTC2S","uxfLDuW","B3jL","uKXTCe4","r3Lkq0e","ALLjvK4","sMLzwNe","zxjYB3i","qxzVEwu","BM9Uzv9UB24","Dev2zw50","q0LtzMK","mJy5odqYohLyDK5JrW","AefsqM0","C3rHCNq","B3jLtMfTzxm","EK1QyuC","qw1iuMq","zgvSzxrLrge","y2XVC2uSihC","CxziBgW","ruPire8","DuHuuwS","tMfTzq","yvLQBhK","C3rYAw5N","CNbmCKG","yw5tveC","Dg9cExrLC0W","nxW0Fdf8nNW","Ec11C2uT","vNPosw4","DvjjDfC","yw51Ce1LC3m","DuLhB0G","CxDrCxu","wvf0qwm","svbyqxG","CxLrC1y","sef1vwW","s1f3EKS","tKfrEKu","DgHLBG","zM9Yy2u","x3nVy2TLDa","ihn1y2nLC3m","Bwj3Cgq","CuTsAwe","ANLwvui","ChLlr0q","sw1XBgC","u2DIB2q","Cvbmq0O","qwTpuei","DMLJzuLeig8","rgX5qKm","zNrHAw8","s1LfAve","DunlrLe","Aw5KzxGGB3u","zgvS","CKXeDxK","CgLUz0XVC3m","AK1yEwC","AxnrB1nnzxm","Bxrkq2i","BMCGDxjSoIa","ELbsC2C","tunpCvO","Cxjpuhq","y3jLyxrLrwW","y2HHCKnVzgu","sNPsue0","y2vZC0HHBMq","zMXVB3i","C2TPExG","B25tDgfYDfi","Aw9UvgLTzw8","ENvTz2m","rMjxywC","x2DLDeLUDgu","uNf6C0W","tMHjAfK","rLLvwuq","y3jLyxrLtwu","Cg5Xyvq","q2zJzwG","zujZruO","BwfUDwfSihi","Aw5N","CgfNzxnOB3C","AMvmyxK","t3bLBKv2zw4","yvDwz1e","C3rLBMvYCW","z05yBeG","shPft20","DevTAw8","yw1Lu3bHy2u","y3fKC0O","C3bSAwnL","B3nLrxzLBNq","qxfzzei","Dg9hzw5LCMe","r1HWyKy","uejpAwS","zv90Aw1LB3u","Dezcs2e","z3jQv2S","D2P0BM8","rLzcs0u","zNjVBunOyxi","sKDtrw0","B25SAw5L","Bxfntvy","vKPsA3q","vvjhsNa","DgvmB2Djre4","Efn4rxO","q291BNq","B2zMC2v0","BgLUzq","DMnfCu0","DMTgAeO","wvHRugi","yNzxEM4","zNjVBu51Bwi","s21LtLO","BMrWB2LUDfq","CMLVCKu","wNzkDfm","Ee16seu","Dg9VigXHCMC","AxnbCNjHEq","DhjHBNnHy3q","sNHoqxu","BMvLzf9Hy2S","ENreCvm","y0rmze8","C2DNvLa","vxPwrK0","o2nOyxjZzxq","B0LZqLq","BgvY","EhDWwvq","B2fK","Dg9mB3DLCKm","x2LZtwLUAvC","zLnTrg0","A25AshC","CM92AwrLihC","zxmGCMvHy2G","C2HPzNq","x3fVC0rc","EwrVu28","mxW0Fdj8m3W","EgLhB2i","CgXOweK","BxzrEey","t0T4vu0","zgrjrcWGzgu","tw96BM0","tg9JAW","mdaWma","aaaaaaaaaaa","C2vYDMvYvgK","vMX0ELm","vuLZANi","Cgf5Bg9Hzeu","s01kv1a","zKvesgq","A0DPzwq","s29wrMe","r3jmr2S","CM1nsgi","rMvTqvK","tefhrMK","AgfTzLC","zKP2zvK","DM9XBw4","yxrLq291BNq","EuLjwg0","yxKSihrYEsa","ue9Sq1q","CNnVCKzPBgu","AefJA01LC3m","quXwB1K","BeXiCxa","DgHHBIbSB2m","Ef9MCM9UDgK","rLjptLrjrvi","yxfoD1e","wgrQEM4","Bwf4twvZC2e","v1DRywe","D2vI","DuDNA1G","s2rNDK0","sMPwCg8","BwfW","C21cAhC","De9KALK","yM5ZEwi","x0vysvnu","ALDHseO","ChjVDg9JB2W","y2rmChy","BMvY","ota4ntG3neThzgzUAW","y0fLy28","A2v5","CLjotKC","C2nYAxb0","BxDxwhq","EuTrA0u","DNfxsvO","t2LWDxq","swrQB2G","sg9ZDwm","uLbszLm","zw5fDMvUDa","BM5Ly3q","DxjS","y2HnyxHuCMK","BuLQt0y","tg9UC3G","yLfMDgO","sLnAv2u","B01HDfK","zw50zwqGDhK","BxnN","r2P4sNG","AeziExK","CKHhAgK","DMvY","q1vxq3i","wxP5Dhq","vgLTzw91Da","Dhr3Awq","B2PxwKO","DLDPvhG","y3nzAe8","x2LUAxrqCM8","ywnRDxbfBMq","tfzfBgG","BgLZDgvUtMu","q09oveLovuu","Dhjjvxy","mdaWmdaWmda","C3bLufG","nNWZFdr8mG","C2vYDMLJzs0","uMvHzcbWyxm","BMnLq2XVC2u","EMj0zw4","yxbnBuK","CKfOwKy","yuzdv2G","igzHAwWSig0","u3rYyxrLz3K","v2vIu29JA2u","v01Iq3y","tfbYv3K","C0jf","x2zVCM1HDeu","uNvbuvu","seDuELK","ALv6uMu","Bfb4zfO","CMv0CNLdB3u","zLDvBuK","uMvJB25Uzwm","uLnRqMu","x3DZsw5ZDge","v0T4zhy","v2T4t0O","x2LZtwLUAvq","x2XPC3rLBMu","tgHYuNi","t2TOthK","zw1PDa","rM1qDfO","shzsBMK","DxDwt3i","B1vOyuC","u2HHCMvKv28","vfDcvMG","CMXRC00","z2vrDwv1zuW","ugrtqLq","t1LNrvO","y2vXD0y","ihbYB3rVy28","sK1dCfa","sKHrEui","Bg93","rKrvrwe","B25TzxnZywC","x2DLBMvYyxq","C2vUzf9Hy2S","AwXLtMfTzq","wLD4swm","C1jHww8","x2fKzfDZtgK","ywzL","B2zM","DMTWwwq","AgfZt3DUuhi","tg9Nsuq","vMPbzKi","rfjNtKy","z1HQs3y","C3rVCMu","mJGXmty1ngnICgzwDW","Bfr1BeK","svf6DKy","C3jJ","sMPfsw4","CMrvqLm","CfncCMq","Dg9tDhjPBMC","A2fgyKK","z2vjBMzVu3K","shrxCuy","D2fZq2XLyw4","sNfJAue","s0HIqwK","yKfmwKW","D25Rqve","EwfmsLu","EsbJBg9Zzwq","zwnVBM5Ly3q","qKXAAMO","Aw47y2HHCNm","Ew9ZAMi","B3zpBeC","C3bSAxq","EfPryuy","Dxrjza","C3DgyMW","Efrurw52","Be1ozfy","t0vwwLe","t2jQzwn0","rLvpC08","zxH0zw5ZAw8","zw5HyMXLvhi","thfjzfy","x2jPBMfYEvq","AMftCLC","y29SBM8","x2rPC3bHDgm","CMvHzhDYAxq","sNDoCNC","q3vZDg9Tq2W","q29Kzq","CLDMAMG","rxzLBNq","AwXK","sw1gCK8","Axnby2TdBgu","mhWYFdn8mxW","AxnmB25N","B2LUDfjLywm","Chvitum","B25szwnLAxy","Bwu6ia","Dw5ZAwDUzwq","Cgu6ia","tuntCKq","mhWZFdi","zKT2sKG","rxvzt2K","t21urge","suPTzeC","y1rxv00","tfrMwum","CxLJv3q","A2PVAgi","CvPRBwm","sg1itKC","yvDevMC","x2LZsw5PDa","BNruCMLLC0m","uwvSEM0","BKj2sgW","BMCGB3iGyw4","vujZD3a","t3f5tuC","t1nKEey","AgPMvgW","BNrLCG","r05JB3i","uvbZswS","C3HVu1K","x2n1CNnVCK0","AKfzEe0","uMzwzgS","tLvfr2K","AevYCM9Yrxy","zMvY","t0P6DxG","Agzwru8","D01Hzha","uu5hDg4","Cwjczhi","yxnJCMLWDa","quvzBfG","AgvHzgvYCW","quD1y0e","BNzpB0u","C2jRBMW","CMvTB3zLrxy","x3bPBMDmB3m","Ag9MDNy","t2nXyNu","u3DxsKq","B2fIy0C","B25fCNjVCG","vu5NBxq","q0Xpu0ve","DwfpEei","s1bvDg8","CMvZzxrdB3u","tNjVwgm","wwPLywG","Cg93","yMLUza","x29Ut3bLBG","A1n0yxr1C0m","ALfpuhm","EwPrEw0","B3jpBMXPBMu","vgfN","zw1Pyw8","BKXvrLG","CKHIz2i","qMnfCfe","wMjZvKe","zu9sDgu","vgXfCM0","vLvAvNu","DufNqwi","AKzzBMC","vwLxqu4","Cg56AuG","zgvSzxrL","Bhm6ia","uMrzvKu","q2vvDM0","zMPrvhO","AMvJDfn0B3i","yxPdwwq","x2TLEvbHDgG","uunctgO","tKDFrvjst1i","AeH3DMu","B25tDg9Wsw0","y0nvrwu","ufvvwM8","yNL0zuXLBMC","EvjLy29UBMu","r2HQAhO","yw1L","zxrxB3jRq2G","zLrQAuC","mhW0Fdn8mNW","BePoshi","tw1hu1O","y29UBMvJDca","Aw5PDcbrB1m","thLtEhq","u3Hpy0C","yNDvrhG","DejIANC","tMfjBvu","z29PBMCGyxC","B3nZy2S","DxDir2y","id4G","Chv0","mNWWFdf8nxW","CNzHBfzHBhu","BKznuNG","AgvHzgvY","Ce5fsMS","CMfUzg9T","uLjpuG","y3rUwMy","y2uGBM90igK","y29TCgXLDgu","u3Ddr2y","uu5QqwO","v3bkzKC","zK1zAe8","x2nSzwfYvgK","CIb0DhDjra","sKnfBxq","zMPsvK4","ENHPuNC","thfJDKy","B3bbA1C","twvZC2fNzuu","rNDIBhO","Bg9N","pxv0zI04","vgvntxO","u2vXsuq","q3Pvrem","DMfSDwvZ","z2u6ia","zgLNDNy","s0r5B20","ihrVihjLDhi","x2nSzwfYugK","t09rB3q","yxnL","x2rYB3bhBg8","AMzNDfa","sufoBxa","BLb4BMG","u0PgBLC","t1bsywS","DhjPzxmGCMu","zLvVsxy","x21LC3nHz2u","mteYmZC1oxveq01UBW","zNDZxZeUmc4","CgfNzwHPzgu","zgzwyLC","yxGGCMv0CMK","ywnRpwzYB24","vMzoBu0","rxjYB3jdB2q","EvbvzM4","CMvZB2X2zq","y3vYCMvUDeK","DLzWDvK","DxLVB28","sxjqtfe","ywDL","BNvTyMvY","quXm","Eu1cyue","vhb6AKG","BeDnyK8","vMrYzvu","y0jbDhm","rwHLBe0","BwP2uve","CMvJzxzPzwq","uxvLDwu","yMXVy2TLza","BwLZzq","zcWG","CffvsgW","swHmshe","Dg9cExrLCW","DLLWtgm","wxLTrMG","BgLUzw5V","uKzHtu8","s3PitKm","DxbNCMfKzw4","AunUEuq","C0HmDuS","vxbKyxrLq28","rxbXseC","vuD1se0","swrsqNm","BNfJAfm","rgXXAw0","BKPODhO","zuzAq04","s2vJCKO","suDQCve","zKrSsve","x29UtwvZC2e","y29UDgLUDwu","D24GCMvHC28","DLPhwLq","y3vYDMfSDwu","y2rbEKi","y29UBMvJDeu","AgnryvO","shf6tha","uhviEvq","zen1shK","ExbL","Eu5TEfy","yMDdAgC","Efvsr0C","zcbLCNjVCI4","Cuzjq0e","zw5HyMXLuw8","qMXMrxe","jMPZy2fSBgi","tuvtu0fhrv8","CKThtfC","C3vIC3rYAw4","t1Pku08","C2fNzq","CgLUz09Uy2u","ignVzgu6ia","DgfYz2v0","rxLcs1u","AKzUrvC","B3nLza","A2LHCfe","AgvKtwf4uMu","D3m6lY8","t1bftL9fuLi","Dg5ssxa","Eez5D2e","swvsv1m","Aw50zwDLCIa","B3vUDa","s1PwrLC","zMzMzG","zg9Uzq","ywXSB2nvBNm","txfWs3G","zePTrMm","ywrKrxzLBNq","C0nYsgK","yNvMzMvYzwq","yMfdvfK","rxLytLy","x2n1CNnVCK4","yKT2zKG","DffovuG","s1f4rKS","BwvZC2fNzv8","txfnv28","B3feuK0","weT6ze0","tfbJs0m","y2f0y2G","suDjC2G","CNnzs3i","s2vODNe","wwH6y2q","x29UvgLTzw8","C29YDa","zM9YrwfJAa","D3jPDgvvAw4","s05bu0S","zuDmBe8","CMvZzxruCMK","whnHuvy","BuDetwW","ywXmv2S","CNzHBa","y3jLyxrLt3a","B2XKvMvYC2K","BMrWB2LUDca","rKLmrv9ot1q","BMnVzgLUzW","u0fNAvK","CgvYC2LZDgu","zgvJB2rLzey","tuDYCuW","wKT3y2q","v2PhB3i","BMDuAw1LCG","DMjWuwK","zfDVCMTLCKC","CNjVCK1LC3m","r0nwBNG","s0XHyve","uw1wCuW","s3v5yKK","yxzlt3u","BgLTAxq","BNrbBMrvCgq","sxzYse4","sfPdtxi","yxbWBhK","y3vYC29Yx2y","qNrquK8","r25NBgC","A1H3rxe","uNPku3O","CfPqt2y","BNrfBMrWB2K","D3vRueC","tefvuw4","suvtx0vsuK8","vLrizha","y2HnyxHdB3u","uffnsxi","zw5KCg9PBNq","rNbzwfK","x194x21Zz18","y29UBMvJDgK","y0nJAg0","zw50","uMHxq1O","yxv0B21HDgK","x25HDMLNyxq","nhWZ","y29UBMvJDfm","B25nzxnZywC","CwzTuwO","yNL0zu9MzNm","C2vYDMLJzq","zxjFCw9Z","A1rtuxu","tKTHD2e","ruHPA1a","y2fSBa","sLfUAvG","CgLUz19VBMm","A25stvq","rK9NrNa","ign1CNnVCIa","u2fqrLi","yw5ZzM9YBvq","D3jPDgu","uvPLEgC","x2LUDgvYDMe","tw9KDwXL","ywrK","zNrvzNy","t2L0wge","vKvdBNu","qMTovw0","uxPmwgS","x2nVBM5Ly3q","u1rcue0","DgLTzw91DcW","Ec1TC2CTy3u","C2v0q3vYC28","t2Tpy2i","twLZC2LUzYa","qNjPzgDL","rvvPEgi","zu9Ks3O","v1bYELq","ywnRx2LK","tMHZrvm","zgLZCgf0y2G","ChjVDg90Exa","zw5JB2rLrNi","AgfZ","Ae1LC3nHz2u","BfPKCLm","txnctNK","wLDrthi","DgzJvu4","ig1LC3nHz2u","q2HnAvu","sMPqBLq","sKHyrLm","vwLns2i","uevsCuS","y29Uy2f0","wuXnvhi","zuLJz3O","BNrSqM8","BKnKqMy","CM9YrxzLBNq","C2v0u3rVCMe","AwXLx25HBwu","tKTPzhq","B1j2BMe","oxvHCg1qsq","EwLOB3a","DhvZDem","BxngEfG","Aw1LCYbPBIa","zwn0","CvnMzfK","qMrQDM8","Cw1zCNG","t0PMtNa","CKPZzvK","Axz4EuS","zhzbB0C","m3W4Fdb8n3W","zgHiA0O","A3bAALa","x2LZqNjVD3m","zu9PCNC","twrmBgC","vurzuLa","Dg9oDw1Izxi","z2v0q3vYC28","y2XVC2u","AvD5uvK","EfngB04","zvDnCwG","z2v0t3DUuhi","reiGzMfPBgu","rLLeBui","wwH4zeS","sevhqLa","shH0twu","CuXbD3G","zxDTBvC","ChLwAMe","wgDYrM8","CeHiC1a","EgTPEeG","ug9At0e","vLb6EuK","y29UDgv4Da","vwTNCg0","BwLUAvbYB2C","vgvhy1C","qwTkt08","DfDAA1C","CMLLC0nVDw4","tun0t0e","whbhChC","DNr2Deq","BgvSyMO","C0Xf","BwvY","BwvZC2fNztO","x2rLC3rYB3K","BxjrtvO","x3vYBa","sfLVqKe","y2HLy2Tszwe","D3LeBKG","x29UrxjYB3i","x3bYzwzPEa","uKfmqva","x2LUAxq","B2zMBgLUzq","yK9sCg0","D2LSBfjLy28","q0LqBwe","mtaYodi0oe10zhvwua","zgnQBKy","CNnVCL92ywW","rLjSvue","yw1LoIa","lcbxzwjtB2m","DMTxDNq","BxnNsuq","zNvUy3rPB24","zufJAW","Dw50","tePvqNi","z2v0q3vYCMu","B3LPBNq","sLPKCgm","B3bLCNr5","Cg9PBNrbBMq","v0DWtwW","zMDSuhy","ywjVCNq","x2LZv29YA2u","uK5Hz2O","wLDMAeG","AwDHDg9Yt24","EKX1r1i","CM92AwrLige","Aw5JBhvKzxm","x3jLy29UBMu","ywr2yw5Jzq","EfvZzuvUDG","wuPutKK","r2XvDeK","zNjVBuj5Dgu","rgvKAwnHDgu","wujOAvO","Dwr0y2W","CMvHzhLtDge","yvnWz1u","DgLTzw91Da","BwvZC2fNzq","wMLdEee","q1v1yKe","BgrlEwy","l3DZl3yY","ywHbDgu","r2XpEKm","zNDftLC","vw5Oyw5KBgu","ENbss24","C0nVDw50zxi","yNzwyMi","uKHOwhm","vfjLB1O","x3bPBMC","D1nwuuG","wgrlBgK","tev2u1i","z2vtEw5J","x21PBMLoyxy","DMfS","zw1LBNq","vgnfzxq","x2LUAxrhBg8","zNjVBuHHC2G","x2rLyNvN","zw50tgLZDgu","AxPOsLq","ywXty29Wzq","rhD2B2W","tMDWAgG","uwjkrui","uM9syu8","t3jAs3O","DhLWzq","AeL0rhu","u0nAC0i","CMvXDwLYzwq","y3vYC29Yx24","zxjYtxnN","zLP3EhC","wvvXExC","uMfwBKi","wurRuhu","uMTktxe","rg9Lz3y","yMfXAgO","C3Pgv2S","BM93","Ahr0Chm6","s05Qy3G","DeLAv2W","zuPLuem","ywXSzwqGBxu","DeDhBuO","zMzLCG","t292BvG","CMvZDwX0","yM9KEq","Ae9Wzw5fDMu","y3jLyxrLt2i","zg5uq04","ALr0CKS","Auv5wNO","zuX4C1y","yNL0zxm","v2LUzg93","DLnpCeC","DKDRAfC","y3vYC29YlNm","CvDsDhm","C0XPC3rLBMu","vhHgreS","x2rItMfTzq","tg9NsurozxC","C2DPza","y3vZDg9Tshq","yufRqMW","Awr6CxK","zMzmAw5L","qMTgvgq","A2v5CW","ihjLy29UBMu","yMfJA3vWigu","shrzwhK","y2XLyxjtDg8","Cgf5Bg9Hza","zxj2AwnL","ywXPzcb1CMW","zfDTtMi","y3vYCMvUDeu","x3nLCuLK","AgL0zeS","yxKSig5LDhC","CMvWBgfJzq","q2Pms0u","wvLhwfq","ihrPBwvZ","C2v0zgi","yxHqqK8","yxbWzw5Kq2G","BMvJDa","B3jRig9MzMW","zMLSDgvY","C3nHz2vfDMu","y1fRyuW","z2v0u3rVCMe","ihrYEsbYzwm","y0PyC3a","C1nOr2u","zv9ZDwnJzxm","x2HHBMrSzvi","BIWGAg9ZDg4","wK5dvNG","s3vns2u","C0TgD3m","r0zerMO","rMHArfe","CMvHC29U","Dw5RBM93BIa","yMzbELy","yuPRu3m","uNbpuue","DMvUDa","AenSB3nLrxy","sxHbyMm","CgfYC2u","m3WYFdr8mxW","ANHvtui","z2v0","BwLUzW","CMvJB25Uzwm","rvvztvy","rg1kBhm","B2nRzxrgywK","BfjvEe4","CLfzywC","B2nRzxrtDwm","vgrzr0W","tgLZDgvUzxi","CMTLCKDSB2i","x3bYB3rVy28","qwLQA3q","Cw1Lv1C","BM5hAue","zgLZywjSzue","ywnOzwq","BMfTzq","DMvYC2LVBMm","yNvMzMvY","CgXLyxnLiha","B25mAw5L","zu5cD2G","C3HUDva","y1rNs08","t1bftG","AgfUz2u","yKTbqMW","x2n1CNnVCKy","q29UzMLN","rvjrww4","rKDkwxu","sfjcwKu","v25zC3i","CwDKEMK","zwTiAKy","Bg9IywXty28","DKjYBwm","v05QBxG","sK1nvKm","zxjFDhrS","u1HPveq","y1b5t3i","qMXxqxq","Dhj1y3rVCIa","uwfMvvm","CMT0vvK","DhDVCMTdAge","zxflELu","wwLIwfe","t3ftEwm","y2HLy2TdDxi","z2v0qwXSs2u","Cg9PBNrdB24","s0zdCfa","ExrKuuS","ChrVCG","D2r0s1a","yLLtzhy","zgvMAw5Luhi","rwvvtNK","yMLUyxj5vhK","yw1QrNq","wwzPwvG","z2vY","rLL6rNq","CxbHru4","vfvpAxq","sgfOzKe","mZm5otC0n3LmzhnRvW","ywDLrxzLBNq","AvDvvM8","shPSzvq","txDNtgC","B2jQzwn0u3q","DxrVuMvJB24","CMvHzg9UBhK","ru1qwwK","BLfYD00","tMHVExq","CNn3yMK","Ahn3rNK","C2vUza","x1fVu01HBMe","x29Uq2XVC2u","EwXjvfq","uu9LsNy","tMTSCuq","zNjVBNrPzxi","r1HIr0i","wu9Nug4","tKfusvzfx0u","y3ruAw1LB3u","x0rctMfTzq","rgHts2W","wMvRqNe","rM1HyMe","C3vIyxjYyxK","vKXez2y","t3L6rwu","zgv2AwnLx2K","mNW1Fdn8nhW","s2v6twS","mxWZ","tvHwA3K","sK1Pru4","DK9mEeq","wgPRyKm","zMX1C2HfEha","Avb6shO","sLnptLa","C2v0sxrLBq","ChD5wNm","BvntvfK","r2HsA2K","tLDVA1u","zNjVBujPDhm","mxWYFdr8nNW","EuzsreK","qwHAD3a","CLzbDgq","igfYCMf5yNu","uxDLsMq","DhrUvwO","qwXWAKO","tLPKwNC","zu9xENa","qNr6y0u","r3fKDKG","s1HxBMy","wKPXvum","AhH5rMG","yNDXy2u","v1vxwKW","BhrPCgXLihq","zMLSzw5HBwu","Dgv4Dc9Qyxy","v3nNCxq","rfbNvfO","uuDLu2S","qxnmv3K","uNLNseS","CgLUz0LUDgu","t0Xbs04","v1LNEwG","EwPxzfy","vMLSzha","De1HBMfNzxi","y2H6q0C","Dgj5C0K","ihrPBwvVDxq","sg9PAgW","A25rB04","quD2sKK","DeLK","txjztLG","Cgf5Bg9Hzfq","rujsswW","mxWWFdr8m3W","ze1ZrhO","rKXfuuK","ChbL","n3W1Fdb8mxW","uwP2u3e","CeTIzuG","vhrKsKC","v0LLAwG","vw1NAfu","C0v2sKe","tNzxAwS","y3r4rgG","CKPjCvC","u2LwEwC","DgvZDa","zwrPyxrLBhK","y2XVC2veqG","wenJvw8","CMfTugfYyw0","EeHgruG","B1z5Chm","u2zjv0u","ANbNEgO","vhLKENC","yxv0BW","BfrPBwvVDxq","BKXPBMu","zhP3uLO","DhnRrhG","y3vYC29Y","wMnTqwq","Cw9Zx18","EKjVCva","BMCGzMfPBgu","B25JBg9Zzq","yLDvAum","DNPvrhy","B25VCgvU","y29Kzq","C2XPy2u","sgLrEwq","sKXLyMS","Dg9iyxnO","zNfwq3O","y3jLyxrLrxi","A2v0ignVBNm","DvbNDxG","DwnACeG","rfDzCLu","lcbTyxGGCMu","yxnZAwDU","CwzcCMu","AxjLza","x2vUzhbVAw4","z0vMAwu","zvvYBa","CNHSrKu","wNbjz3y","uNDusvO","zxjYtM8","BeHHBMrSzxi","sgPUDhK","sNzTuhy","wMTWAMG","m3WXFdj8nhW","Dg9cExrLC0i","DxbKyxrLq3u","mtmWmdy2mffIChPtqq","igzPzwXKoIa","y09Wzw4","Aw5Lza","zMLN","zxjHDg9Y","zNrJuwG","AxnrB1nby2S","DNHPqKG"];return Sn=function(){return r},Sn()}Ee.d=(r,e)=>{let i=P;for(var a in e)Ee.o(e,a)&&!Ee.o(r,a)&&Object[i(1588)+i(1375)](r,a,{enumerable:!0,get:e[a]})},(()=>{let r=S;Ee.o=(e,i)=>Object.prototype[r(833)+r(1375)][r(1236)](e,i)})(),(()=>{let r=S,e={uyooo:function(i,a){return i!=a},iTeAu:r(399)+"d",gyGLK:"Module"};Ee.r=i=>{let a=r;e[a(1064)](e.iTeAu,typeof Symbol)&&Symbol[a(846)+a(959)]&&Object[a(1588)+a(1375)](i,Symbol["toString"+a(959)],{value:e[a(512)]}),Object[a(1588)+a(1375)](i,"__esModule",{value:!0})}})();var $={};(()=>{let r=S,e={LhrRr:function(s,t){return s+t},SJFnW:function(s,t){return s*t},VPzyI:function(s,t){return s+t},JzRPM:function(s,t){return s(t)},rAhZF:function(s,t,n){return s(t,n)},uRKpu:function(s,t){return s(t)},zPRsg:function(s,t,n){return s(t,n)},QzLXk:function(s,t){return s(t)},QOhLQ:function(s,t){return s+t},NKidt:r(689),uRItW:function(s,t){return s!==t},XVQrX:r(1583),YymFh:r(903),RzBKe:function(s,t){return s>t},ozMho:function(s,t){return s<t},ftaio:function(s,t){return s-t},zpgTv:r(564),OLAKN:function(s,t){return s-t},cCchm:function(s,t){return s===t},HGTzY:function(s,t){return s<t},oIsBT:function(s,t){return s|t},qpaEN:function(s,t){return s<<t},axPBO:function(s,t){return s<<t},fAQmS:function(s,t){return s&t},stPRV:function(s,t,n){return s(t,n)},aHuQH:function(s,t){return s>>t},avKOu:function(s,t){return s===t},nvOoE:r(1382),xiGob:"ysKVA",trIUv:function(s,t,n){return s(t,n)},nnGiA:function(s,t,n){return s(t,n)},QbJEB:function(s,t){return s===t},zBoqP:r(1667),vSOpG:r(1302),lXpSg:function(s,t){return s>>>t},mvQxF:function(s,t,n){return s(t,n)},ZWxIc:function(s,t,n){return s(t,n)},Oomfh:function(s,t){return s===t},GQoPJ:r(1260)+r(1436)+r(1756)+r(736),anSTG:function(s){return s()},YXkPb:function(s,t){return s(t)},vqWIZ:function(s,t){return s>>>t},cQkaL:function(s,t){return s&t},BvtnQ:function(s,t){return s>>>t},EuYOi:r(545)+"s alread"+r(856),cCUEe:function(s,t){return s===t},HEGBP:r(1160),RNagj:function(s,t){return s!==t},RpyOS:"mwltf",UDYRP:r(1559),PJPeZ:function(s,t,n){return s(t,n)},riorE:function(s,t){return s!==t},lelbj:function(s,t,n){return s(t,n)},eBsEJ:function(s,t,n){return s(t,n)},eqKzU:function(s,t){return s(t)},tustC:function(s,t,n){return s(t,n)},SXiTD:function(s,t,n){return s(t,n)},tbysI:r(542),TxFDK:function(s,t,n){return s(t,n)},KNjcx:function(s,t,n){return s(t,n)},IeRWS:function(s,t,n){return s(t,n)},cAeco:r(1444),MuKdv:r(757),skiyx:function(s,t,n){return s(t,n)},UGuHM:function(s,t){return s!==t},kjohb:function(s,t,n){return s(t,n)},WlznC:function(s,t,n){return s(t,n)},hitdK:function(s,t,n){return s(t,n)},JVJkD:function(s,t,n){return s(t,n)},CUubA:function(s,t,n){return s(t,n)},mIjOF:function(s,t,n){return s(t,n)},KoVFa:function(s,t){return s>>>t},OPRak:function(s,t,n){return s(t,n)},vZGZT:function(s,t){return s(t)},sbJzy:function(s,t,n){return s(t,n)},LySxt:function(s,t,n){return s(t,n)},HZCMr:function(s,t){return s(t)},GwXQm:function(s,t,n){return s(t,n)},JjPnT:function(s,t){return s(t)},CUWCr:function(s,t,n){return s(t,n)},OZJSO:function(s,t){return s===t},uGgkX:r(1260)+r(1436)+" field: "+r(1033),LPrWy:r(1260)+r(1436)+r(1756)+r(834),KcRwp:r(1260)+r(1436)+r(1756)+"service",UpIcY:r(1260)+r(1436)+r(1756)+r(1825),QweJd:"close",CeKOF:r(496),nxFxk:function(s,t){return s+t},RzJSz:function(s,t){return s&t},ChMiU:function(s,t){return s(t)},iFZQm:function(s,t,n){return s(t,n)},Sgbod:function(s,t,n){return s(t,n)},qSfdY:"Unimplem"+r(755)+r(894),bYSdv:function(s,t){return s>=t},tdmsk:function(s,t){return s>=t},IGjqQ:function(s,t,n,o){return s(t,n,o)},JGKIX:function(s,t){return s+t},udtcl:function(s,t){return s!==t},oUhaG:r(1815),xqpUU:r(702),rdUBS:function(s,t){return s===t},cljUJ:function(s,t){return s+t},bwqce:function(s,t){return s>=t},lTulI:function(s,t){return s<t},rKGLW:function(s,t){return s|t},oabcG:function(s,t){return s&t},UIsjr:function(s,t){return s>=t},Dwvol:function(s,t){return s>>t},dkZjV:function(s,t){return s===t},kAwoe:r(442),JMMVC:function(s,t){return s>t},JLebk:function(s,t){return s>t},mtJCb:"Read past limit",baCTY:function(s,t,n){return s(t,n)},mSSTY:function(s,t){return s+t},LTfYC:function(s,t,n){return s(t,n)},yKQkE:function(s,t){return s&t},Qelzm:function(s,t){return s+t},ceqwF:function(s,t){return s&t},EGBrn:function(s,t){return s==t},WEbAC:function(s,t){return s+t},eOirw:function(s,t){return s+t},TlErm:function(s,t){return s+t},AFGBc:function(s,t){return s!==t},DRgNF:function(s,t){return s|t},RHhXs:function(s,t){return s<<t},SiVyg:function(s,t){return s|t},JMCpP:function(s,t){return s&t},bKvfH:function(s,t){return s&t},NhsES:function(s,t){return s&t},OitXa:function(s,t){return s<=t},tnRIp:function(s,t){return s&t},MCtOA:function(s,t){return s+t},AGvJI:function(s,t){return s+t},QNjAj:function(s,t){return s+t},QrUOq:function(s,t){return s!==t},LqcvF:function(s,t){return s<<t},sCrHi:function(s,t){return s<<t},qurVK:function(s,t){return s&t},uIGoH:function(s,t){return s>=t},Ivgth:function(s,t){return s+t},bgChg:function(s,t){return s-t},dfVbW:function(s,t){return s+t},rLDuy:function(s,t){return s<t},TpzjH:function(s,t){return s>=t},xSewm:function(s,t){return s<=t},yosjb:function(s,t){return s<t},hGbFg:function(s,t){return s+t},NZdZw:function(s,t){return s<t},JwNrw:function(s,t){return s|t},tBbjw:function(s,t){return s&t},PoZOA:function(s,t){return s<t},JHXFS:function(s,t){return s&t},azCYd:function(s,t){return s|t},OvgOA:function(s,t){return s>>t},oyint:function(s,t){return s&t},zxiRw:function(s,t){return s&t},qmeWW:function(s,t){return s>>t},YJTNI:function(s,t){return s&t},JSZWe:function(s,t){return s>>>t},TUOit:function(s,t){return s&t},FemAY:function(s,t){return s>>>t},vOLxD:r(619),yMBaA:function(s,t){return s<t},VzNIn:function(s,t){return s+t},Ocqbu:r(825),xSFoN:r(1263),EUixb:r(631),iaJts:function(s,t,n){return s(t,n)},iWUVo:function(s,t){return s<<t},rktUY:function(s,t){return s&t},Hjnty:function(s,t){return s&t},MdLlg:function(s,t){return s&t},RhWCZ:r(1016),uRZCb:r(533),Hoihl:function(s){return s()},WWkaa:r(516)+"or",rRNNG:function(s,t){return s&t},dvAoG:function(s,t){return s&t},hfVEO:function(s,t){return s<<t},jaSrW:function(s,t){return s&t},IxUTz:function(s,t){return s&t},dJmFc:function(s,t){return s&t},JMiEN:function(s,t){return s<<t},OJfNp:function(s,t){return s&t},alLWk:function(s,t){return s&t},pQUHl:function(s,t){return s<<t},FmPtZ:function(s,t){return s&t},wnkAQ:function(s,t){return s&t},dzwRZ:function(s,t){return s|t},yPUfn:function(s,t){return s>>>t},RuAQU:function(s,t){return s>>>t},plhXI:function(s,t){return s|t},BlWAt:function(s,t){return s>>>t},iSTYg:function(s,t){return s<t},AVFzs:function(s,t){return s<t},cZaAN:function(s,t,n){return s(t,n)},Hosuc:function(s,t){return s&t},eORte:function(s,t){return s+t},HvRni:function(s,t){return s|t},hARBm:function(s,t){return s>>>t},LPcKC:function(s,t){return s+t},GqdvH:function(s,t){return s!==t},ZvJtS:function(s,t){return s|t},iCnyD:function(s,t){return s&t},bgTpz:function(s,t){return s>>>t},NsOPs:function(s,t){return s>>>t},uCKFQ:function(s,t){return s+t},cDLdO:function(s,t){return s!==t},aJqll:function(s,t){return s+t},lGMbO:function(s,t){return s>>>t},iWyQY:function(s,t){return s!==t},LqIdV:function(s,t){return s|t},TcEet:function(s,t){return s>>>t},uPgux:function(s,t){return s&t},KQwzK:function(s,t){return s>>>t},HEJUR:function(s,t){return s&t},YfJKs:function(s,t){return s|t},HzleT:function(s,t){return s&t},PERqK:"RNGjT",digvv:r(466),FhZDQ:function(s,t,n,o,c){return s(t,n,o,c)},RSkBe:function(s,t){return s(t)},bZzVi:function(s,t){return s!==t},xwpYT:r(1689),lJNHr:"QyQDm",AFxaG:function(s,t){return s|t},wukPG:function(s,t){return s<<t},YUqyw:function(s,t){return s<<t},Lonsx:function(s,t){return s|t},fqVCz:function(s,t){return s<<t},gNXlH:function(s,t){return s===t},RPRfS:function(s,t){return s|t},yaerY:function(s,t){return s<<t},WUWZL:function(s,t){return s<<t},lPxdZ:function(s,t){return s<<t},bWUiC:function(s,t){return s>>>t},HuHjX:function(s,t){return s|t},YDkPu:function(s,t){return s|t},qfBre:function(s,t){return s|t},otULm:function(s,t){return s>>>t},MsBNy:function(s,t){return s&t},vCmPm:function(s,t){return s&t},HjOEK:function(s,t){return s>>>t},fWUmI:function(s,t){return s<=t},sRaYo:function(s,t){return s>=t},tWZkW:function(s,t){return s|t},WKxdv:function(s,t){return s%t},OqyMG:function(s,t){return s|t},aWDVg:function(s,t){return s/t},eFZCN:function(s,t){return s!==t},YYGXT:function(s,t){return s>>>t},iUmQc:function(s,t){return s*t},gMdaj:function(s,t){return s(t)},oVyps:"ROGrF",kaFbI:r(1616),NUEGi:function(s,t){return s===t},WjGor:function(s,t){return s&t},Zkpjh:function(s,t){return s>>>t},ZVplU:function(s,t){return s&t},Idjoh:function(s,t){return s>>>t},pNEJk:function(s,t){return s+t},ksOQA:function(s,t){return s>>>t},Avoye:function(s,t){return s+t},hcQaZ:function(s,t){return s>>>t},idzqy:function(s,t){return s+t},lTPzo:function(s,t){return s|t},Sylmt:function(s,t){return s!==t},pZPOf:function(s,t){return s===t},bnsyb:function(s,t){return s>>>t},xJvZG:function(s,t){return s===t},ZNDUj:function(s,t){return s===t},kiapQ:function(s,t){return s+t},knRMT:function(s,t){return s>>>t},ZLVqe:function(s,t){return s&t},nBvHl:function(s,t){return s>>>t},JQniX:function(s,t){return s>>>t},VfNmM:function(s,t){return s&t},sEvJA:function(s,t){return s&t},XjkbC:function(s,t){return s&t},xGioe:function(s,t){return s&t},vkpYd:r(1007)+r(1226),WusSK:r(1786)+r(981),RXbhs:r(395)+r(1213)+"R",aSpgU:r(1620)+r(1013),HRBZE:r(1137)+"OR",XEYcY:r(1123)+"ERROR",cfaqI:r(555)+r(896),wYgjw:"4|2|3|1|0",Ngphh:function(s,t){return s>t},pwyZs:r(1901),HYbQV:function(s,t,n){return s(t,n)},tfcUN:function(s,t){return s!==t},KNASK:r(1460),keLCn:r(462),yjQym:function(s,t){return s===t},UZuKz:function(s,t){return s-t},aYjly:function(s,t){return s===t},QqeuL:function(s,t){return s instanceof t},mGDMl:r(1407)+r(1118),XKzdM:function(s,t){return s+t},FDUEa:r(1439),rsBWX:function(s,t){return s===t},dPimd:r(1206),jMXyg:r(1800),NAQzE:"DaPvT",mqMMV:"message",YBhiZ:function(s,t,n){return s(t,n)},KuybI:function(s,t,n){return s(t,n)},qLAwx:function(s,t,n){return s(t,n)},rsyIF:function(s,t,n){return s(t,n)},dOghM:"geVgS",hItDu:r(1627),SCZsB:function(s,t){return s||t},ttnUj:function(s,t){return s||t},HqzLp:r(1526)+"0",wXUWN:function(s,t){return s||t},lsGwc:function(s,t){return s!=t},CISfi:"undefined",yVBBj:function(s,t){return s<=t},Scxza:"next() c"+r(1452)+r(1663)+r(1296)+"process",IJmdG:function(s,t){return s===t},NKawa:function(s,t){return s+t},aOrDI:function(s,t){return s<t},Annwl:function(s,t){return s===t},OXRXI:function(s,t){return s<t},OkhLy:function(s,t){return s-t},glwqU:function(s,t){return s<=t},GXbGB:function(s,t){return s>=t},msFxX:function(s,t){return s<t},uNRwq:function(s,t){return s|t},uwHGf:function(s,t){return s<<t},lEHtA:function(s,t){return s|t},tQNUH:function(s,t){return s&t},asdTN:function(s,t){return s|t},iEyZz:function(s,t){return s<<t},cdAzB:function(s,t){return s<<t},adpaz:function(s,t){return s&t},lMNdV:function(s,t){return s+t},csYhO:function(s,t){return s+t},DhSKl:function(s,t){return s&t},wSVQH:r(551),lRUxN:function(s,t){return s(t)},Nneem:function(s,t){return s!==t},ekHjF:function(s,t){return s<t},ZmDaV:function(s,t){return s|t},vkWvt:function(s,t){return s===t},cTgKO:function(s,t){return s&t},GpaEk:"4|2|5|0|"+r(1632),RAzuB:function(s,t){return s|t},hxyFh:function(s,t){return s>>t},XydME:function(s,t){return s&t},FGJYu:function(s,t){return s+t},VdreU:function(s,t){return s|t},EsnIh:function(s,t){return s&t},Xzcri:function(s,t){return s instanceof t},jgBUt:function(s,t){return s instanceof t},OaLAW:function(s,t){return s!=t},fTjiG:function(s,t){return s==t},mcfft:"text/pla"+r(859)+r(1818),fjQTz:r(1851),gJghb:r(1247),nqchS:"__esModule",ydoSo:function(s,t){return s===t},NGYFc:r(905),OJzux:function(s,t){return s<t},ZbsVA:function(s,t){return s+t},jxUMB:function(s,t){return s(t)},opAkW:r(1518)+"reason",TiRHO:r(639),fMYhO:r(1054),GOuCZ:r(738),bOLnI:r(1665)+"ascript",QafUS:"&jscallback=frontierJSONP",YfiYX:"TWBVh",KXWnf:r(1029),IANmp:r(1735),nnhZr:r(1463),RkJMq:r(717),vbpQi:r(726),HYoBA:function(s){return s()},twoSS:function(s,t){return s===t},baTyi:r(1488),gXjKv:function(s,t){return s===t},JxNAu:r(449),OOQot:r(697),WnYsr:function(s,t){return s===t},AkOPB:function(s,t){return s in t},ctxDh:r(1865),PUUZo:function(s,t){return s===t},ajIdG:r(1567),DRbXC:function(s,t){return s||t},jJoom:function(s,t){return s||t},RaVnB:"4|2|1|0|3",OYgEZ:function(s,t){return s!==t},yaLJU:function(s,t){return s||t},sHLuK:function(s,t){return s||t},IxAbc:function(s,t){return s(t)},FpYXY:function(s,t){return s!==t},LftnU:r(612),MgTPf:function(s,t){return s||t},OkOcb:"ymSim",wMadp:"xwCcR",XdKli:function(s,t){return s||t},KuMKe:r(996)+r(1319)+"d",WPrzT:function(s,t){return s*t},ALVoY:function(s,t){return s!==t},PdSBT:r(1467),JHYGo:function(s,t,n){return s(t,n)},JjVpo:"qos",nPzWu:r(1158)+"id",Moznm:"OmTDa",EhelM:function(s,t){return s(t)},IPXAx:r(885),izhJT:r(1201),ZTSBr:function(s,t){return s(t)},FUOsO:r(715)+r(1232),grjWk:r(715)+"er_qos_ack",jRnqY:"x_frontier_is_ack",HbOOs:"x_frontier_ack_m"+r(1474),cQlgs:function(s,t,n,o){return s(t,n,o)},ewmmW:"is_ack",GhRki:function(s,t){return s&&t},CIPma:r(1265),emwGa:"ack_code",ftUfv:function(s){return s()},ZcmAd:function(s,t){return s(t)},jxwqa:r(1728),DlyBC:r(752),Oiput:"application/json",VTHdp:"application/json"+r(667)+r(1031),rlksM:r(535)+"e",cJXsp:r(520),YOgPn:function(s,t){return s(t)},jWaHJ:function(s,t){return s+t},EOPUq:function(s,t){return s|t},CGtRp:r(1724),SElGD:r(630),RynrW:function(s,t){return s>>>t},fKvJH:function(s,t){return s(t)},GyJCA:function(s,t){return s+t},AlpjJ:function(s,t){return s+t},tAVjS:function(s,t){return s+t},VHsas:r(465),JqciA:r(1005),yJVhE:function(s,t){return s+t},BkFTd:r(531),DZGxx:function(s,t){return s>>>t},ghQoQ:r(992)+"1",hHwve:function(s,t){return s+t},domhM:function(s,t){return s+t},qRnzy:function(s,t){return s+t},MoGHH:function(s,t){return s<t},jFYng:function(s,t){return s|t},EJHDO:function(s,t){return s+t},YoiqP:function(s,t){return s+t},wjtno:function(s,t){return s+t},xoUPL:function(s,t){return s<<t},ovOlG:function(s,t){return s+t},RoRaO:function(s,t){return s+t},rHGhi:function(s,t){return s+t},SyTdW:function(s,t){return s>>>t},qYYVI:function(s,t){return s&t},OSdxF:function(s,t){return s>>>t},seQiu:function(s,t){return s+t},ELuwT:function(s,t){return s&t},tkYyk:function(s,t){return s>>>t},lAVmG:function(s,t){return s+t},KQpSa:function(s,t){return s&t},YhxdK:function(s,t){return s>>>t},TeGcW:r(1363),pnziH:function(s,t){return s+t},dbNHp:function(s,t){return s+t},Aijkt:function(s,t){return s&t},LsWgr:function(s,t){return s>>>t},ZKwcd:function(s,t){return s&t},sKFws:function(s,t){return s&t},OYrls:function(s,t){return s|t},CZpya:function(s,t){return s>>>t},qEfiB:function(s,t){return s<t},MCSrD:function(s,t){return s|t},puHMC:function(s,t){return s!==t},pyVja:function(s,t,n,o){return s(t,n,o)},fDlIQ:function(s,t){return s===t},emoUJ:"xAfRD",QjvSq:"BRTTL",cyyND:function(s,t){return s(t)},MXVky:r(1305)+r(1646)+"10|5|9",PQMIr:r(1010),SxOcG:"service",aAkBl:r(1468)+r(1486),KMJWP:function(s,t,n,o){return s(t,n,o)},JHQyB:function(s,t,n,o){return s(t,n,o)},kvcDj:r(1107),rsYKr:r(1705),EyXNV:r(1204)+r(1289),JVUZW:"success",jFnEW:r(1238)+r(632)+"t",NvWik:function(s,t){return s<t},KZVFW:r(696),OrZKz:function(s,t){return s+t},QYRLx:r(1182)+r(729),WMasM:"cursor_name",rpLrH:function(s,t){return s(t)},qbBdr:"ping_onc"+r(1509)+"s",EKfsD:r(951),AmHRd:"vgmmj",FVBKE:"allCurso"+r(1821),RdYVE:r(1068),KzHNC:"INSTANT",vYpLc:r(772),IEkiK:r(1497),baqhj:function(s,t){return s(t)},DWYrU:"setcursor",xRyJa:function(s,t){return s>=t},WGpMl:function(s,t){return s===t},UrJhm:function(s,t){return s===t},fJveY:r(391),JIWER:r(565),UNgmt:r(573),qPLCJ:function(s,t){return s||t},Wsgqt:r(674),ojWZJ:r(845),cBAts:r(843),mwWXt:r(1687)+"2",cPyOr:"yoFVf",SaPFR:r(1019),nCdBf:function(s,t,n,o){return s(t,n,o)},ZpIgv:r(1726),mxMnn:function(s,t,n){return s(t,n)},ossck:r(715)+r(409),zLuGR:r(715)+r(1569),qfmQj:"x-msg-qos",OovmX:function(s,t,n){return s(t,n)},bALZL:r(1257)+r(1362)+"ue",Ghjhz:function(s){return s()},arCBp:function(s){return s()},mDsYa:function(s){return s()},HahfA:r(1356),vWiTx:r(616),hFHyy:function(s,t){return s===t},NhIhY:r(1272),rVewC:r(1750),EHikP:function(s,t){return s===t},EUYMV:function(s,t){return s===t},NHZsP:function(s){return s()},voqmn:function(s){return s()},RfVdk:function(s){return s()},hamfW:function(s,t){return s===t},pHHsP:function(s,t,n){return s(t,n)},ZiCxA:function(s,t,n,o){return s(t,n,o)},RLmpN:function(s,t,n){return s(t,n)},eWMqh:"always",tVaAR:function(s,t){return s===t},spePX:function(s,t,n){return s(t,n)},fMite:function(s,t){return s|t},KLaaQ:function(s,t){return s>>t},Hqhgm:function(s,t){return s>>t},tIZWl:function(s,t){return s&t},amjFt:r(1157),DmJls:function(s,t,n){return s(t,n)},eOWzp:"arraybuf"+r(926),QKoLZ:"auto",ShQCX:r(1549)+r(676)+r(486)+r(1365)+r(1733)+r(1573)+r(1841)+r(1758),yjWdV:r(1530)+"t",wVPRn:function(s,t){return s===t},bfAzV:"lZPSf",PUEmD:r(1520),Ukgpm:function(s,t){return s!==t},BtPRO:function(s,t){return s!==t},PoIHf:r(1804),dCuHy:function(s,t){return s==t},EyBKU:r(1448),LVElh:"wss://",PkQGu:r(1136),tnucL:r(764),yFRDI:r(1629)+"d",jUzRe:function(s,t){return s||t},NGFiD:"please provide b"+r(686)+r(580)+r(1022),Jgwdi:"function",PXQmB:r(721),tcVxy:r(1053)+"0",jTtrK:function(s,t,n){return s(t,n)},qwQqu:r(540),cnagu:function(s,t,n){return s(t,n)},yihop:function(s,t){return s(t)},oAhWv:r(716)+">",OqSyc:function(s,t){return s*t},LCvVA:function(s,t){return s-t},POlCT:function(s,t){return s>t},xMzHE:function(s,t,n){return s(t,n)},GrLGk:function(s,t){return s!==t},VJRkt:function(s,t,n){return s(t,n)},fddPK:r(1002)+r(708)+r(1530)+"ting ser"+r(760),YgyaE:function(s,t){return s===t},lLHqp:r(961),iPzHz:r(1256)+r(1506)+"onnecting",KezMk:"open",XJQQU:function(s,t){return s!==t},Fofiv:r(1082),YLMTr:r(607),VltzS:function(s,t,n){return s(t,n)},zpRKn:function(s,t){return s===t},QCBLj:r(1869),MCOqZ:function(s,t,n){return s(t,n)},eNBwh:r(1002)+r(1492)+r(1501)+r(445),SJnwz:"ack",DUfaG:function(s,t){return s===t},fUoIv:function(s,t){return s(t)},Dlqim:r(426),tskDx:r(1065),URGJp:r(644),PjPcd:function(s,t){return s==t},bvVbb:r(1549)+r(1385)+r(1776)+r(1829)+"a must be a stri"+r(912)+r(1650)+r(1454),uHTQk:r(1067),OEVZQ:function(s,t){return s instanceof t},MwgLg:function(s,t){return s instanceof t},xmVXT:r(1549)+"rovide a valid service",vIwQT:function(s,t){return s instanceof t},CaFUk:function(s,t){return s instanceof t},cTWWM:function(s,t){return s(t)},UBswp:"sent",Yhzcd:function(s,t){return s!==t},KdgvM:"rTnCp",ftcQh:r(460),nZAih:function(s,t){return s||t},AEYlX:function(s,t){return s==t},QPsIk:function(s,t){return s!==t},vVpuY:r(614)+r(857)+r(615),PyANF:r(887)+"4",ztDqS:r(1354),FYDmB:"timeout",EBRIl:function(s,t,n){return s(t,n)},KDyom:r(1378),HmHNG:r(690),szihn:function(s,t){return s*t},NWokU:function(s,t){return s!=t},ZoNCt:function(s,t){return s===t},kITlB:r(1465),rHbgb:function(s,t){return s!=t},BcEpQ:function(s,t){return s!=t},SwWJD:function(s,t){return s!=t},ZWQLr:r(869),RPRaO:r(1393)+r(1192)+r(1565)+"pe",kpZjP:function(s,t){return s!=t},XsaQV:function(s,t){return s==t},tOdjY:function(s,t){return s!=t},XhUeO:"ServiceWorkerGlobalScope",AhZwp:function(s,t){return s!=t},qjKKt:r(1219)+r(1719)};Ee.r($),Ee.d($,{FWS:()=>Ma,CustomErrorEvent:()=>rs,createCloseEvent:()=>pe,ReconnectEvent:()=>ns,createErrorEvent:()=>ue,decodedFrame:()=>Qr,createOpenEvent:()=>xs,CustomCloseEvent:()=>ss,createReconnectEvent:()=>Qn,FrontierMessageEvent:()=>os,encodeFrame:()=>$n,createMessageEvent:()=>cs,OpenEvent:()=>as,ErrorCode:()=>Fe,Event:()=>rt,MessageEvent:()=>is});let i="";function a(s=""){let t=r,n="02",o=""+Date.now(),c=i||(i=m(s)),f=Math[t(1012)]()[t(846)](16)[t(1727)](-6);return e[t(804)](n+o+c,f)}function x(){let s=r;return e[s(804)](1e4*Date[s(1447)](),Math[s(600)](e[s(1047)](1e4,Math[s(1012)]())))}function u(s){let t=r;return e[t(1331)](e[t(598)](Array,8)[t(1775)]("0"),e.rAhZF(parseInt,s,10)[t(846)](2))[t(1727)](-8)}function d(s){let t=r;return e[t(1331)](e[t(485)](Array,4)[t(1775)]("0"),e[t(593)](parseInt,s,2)[t(846)](16))[t(1727)](-4)}function h(s){let t=r,n=s[t(862)](/\./)[t(725)](f=>u(f)),o=[];return o[0]=e[t(1253)](d,e[t(464)](n[0],n[1])),o[1]=e[t(1253)](d,e[t(464)](n[2],n[3])),[e[t(1290)],e[t(1290)],e[t(1290)],e[t(1290)],"0000",t(1144),o[0],o[1]][t(1775)]("")}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}/.test(s),o=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(s);return n?h(s):o?e.JzRPM(w,s):t(774)+t(774)+t(774)+t(774)}function w(s){let t=r;if(e.uRItW(e[t(1881)],e[t(1085)])){let n="",o=[],c=0,f=0,g=!0,p=e[t(1290)];if(e[t(518)](s.indexOf("::"),-1)){let l=s[t(862)]("::");for(let k=0;k<l.length;k++){let v=l[k];if(v[t(397)](":")>0){let A=v[t(862)](":");g&&(c=A[t(1843)]),f+=A[t(1843)];for(let T=0;e[t(1873)](T,A[t(1843)]);T++)if(A[T][t(1843)]!==4){let G=p[t(1125)+"g"](0,e.ftaio(4,A[T].length)),M=G[t(1282)](A[T]);o[t(483)](M)}else o.push(A[T]);g=!1}else{if(e.uRItW(4,v[t(1843)]))if(e[t(558)](e.zpgTv,"YHmso")){let A=p[t(1125)+"g"](0,e[t(1672)](4,v[t(1843)])),T=A[t(1282)](v);o.push(T)}else{let{type:A}=_0x4215b0;this[t(806)](A,_0xb3633e)}else o.push(v);g&&(c+=1),f+=1,g=!1}}let y="";for(let k=0;e[t(1873)](k,e[t(582)](8,f));k++)y=y[t(1282)](p);for(let k=0;e.ozMho(k,o[t(1843)]);k++)e[t(1221)](k,c)&&(n=n.concat(y)),n=n[t(1282)](o[k]);return n}{let l=s[t(862)](":");for(let y=0;e[t(792)](y,l[t(1843)]);y++){let k=l[y];if(e[t(558)](4,l[y].length)){let v=p[t(1125)+"g"](0,e[t(582)](4,l[y][t(1843)])),A=v[t(1282)](k);n=n[t(1282)](A)}else n=n[t(1282)](k)}return n}}else this[t(570)]&&this._socket[t(1314)]({code:_0x31da35,reason:_0x39a77f})}function b(s,t){let n=r;if(e[n(1198)](e[n(936)],e[n(682)]))_0x417983=e.oIsBT(e[n(668)](e[n(668)](e[n(1595)](7&_0xf7825c,18),e.axPBO(e[n(513)](63,_0x934929),12)),e[n(513)](63,_0xd67c70)<<6),e[n(513)](63,_0x39fe21)),e.ozMho(_0x14b0d0,65536)||e[n(518)](_0x4c76c0,1114111)?_0x1ad72b+=_0x49669b:(_0x10f74e-=65536,_0x192e16+=e[n(1890)](_0x21fa86,e[n(464)](e[n(1849)](_0x21b3ed,10),55296),e[n(804)](1023&_0xbbe878,56320)),_0x3ae52c+=3);else{let o=s[n(736)];e[n(558)](void 0,o)&&(e[n(773)](J,t,10),e.zPRsg(be,t,o));let c=s[n(405)];e[n(558)](void 0,c)&&(e[n(782)](J,t,18),e[n(1543)](be,t,c))}}function _(s){let t=r;if(e[t(1430)](e[t(1720)],e[t(1466)]))this[t(444)]&&this[t(444)][t(1611)](_0x509cca),this[t(1051)+t(1077)][_0x514e4f]=null;else{let n={};e:for(;!ke(s);){let o=U(s);switch(e[t(1784)](o,3)){case 0:break e;case 1:n[t(736)]=ye(s,e[t(598)](U,s));break;case 2:n[t(405)]=e.mvQxF(ye,s,e[t(485)](U,s));break;default:e.ZWxIc(ee,s,e.fAQmS(7,o))}}if(e[t(446)](void 0,n.key))throw new Error(e.GQoPJ);if(e[t(1430)](void 0,n[t(405)]))throw new Error(t(1260)+t(1436)+t(1756)+t(405));return n}}function C(s){let t=r,n=e[t(553)](oe);return L(s,n),e.YXkPb(V,n)}function L(s,t){let n=r;if(e[n(984)](e[n(1322)],e[n(1322)])){let o=s[n(1033)];e[n(1381)](void 0,o)&&(e[n(827)](J,t,8),bt(t,o));let c=s[n(834)];if(e[n(1381)](void 0,c))if(e[n(558)](e.RpyOS,e[n(1311)]))J(t,16),e[n(684)](bt,t,c);else{let M=this[n(1845)],X=this[n(821)];return[e[n(513)](255,X),e[n(513)](e[n(1784)](X,8),255),e.fAQmS(e[n(1784)](X,16),255),e[n(741)](X,24),255&M,e[n(1504)](e[n(1878)](M,8),255),e[n(513)](e[n(1878)](M,16),255),M>>>24]}let f=s[n(1231)];e[n(558)](void 0,f)&&(e[n(593)](J,t,24),e.PJPeZ(bt,t,le(f)));let g=s[n(1825)];g!==void 0&&(J(t,32),bt(t,le(g)));let p=s[n(934)];if(e.riorE(void 0,p))for(let M of p){e[n(1342)](J,t,42);let X=oe();b(M,X),e[n(593)](J,t,X.limit),e.eBsEJ(Ut,t,X),e[n(1577)](D,X)}let l=s[n(694)+n(1183)];e.RNagj(void 0,l)&&(e.tustC(J,t,50),be(t,l));let y=s["payloadT"+n(1114)];e[n(655)](void 0,y)&&(e.SXiTD(J,t,58),be(t,y));let k=s[n(1485)];if(k!==void 0)if(e[n(1221)](e[n(1678)],e[n(1678)]))e[n(1471)](J,t,66),e.KNjcx(J,t,k[n(1843)]),e[n(1140)](qt,t,k);else{let M=(n(1630)+n(1791))[n(862)]("|"),X=0;for(;;){switch(M[X++]){case"0":if(e[n(1198)](this._ws.readyState,this[n(946)])||this._ws[n(1396)+"te"]===this[n(1831)])return void this[n(1424)](e[n(898)]);continue;case"1":if(!this[n(444)])return void this[n(1424)](n(545)+n(387)+n(1015)+n(1839)+"ed");continue;case"2":this[n(398)+n(1133)]=!0;continue;case"3":this["_clearPi"+n(1190)]();continue;case"4":this["_dropGlo"+n(1774)+"Listener"]();continue;case"5":this[n(1021)+n(1344)]();continue;case"6":this[n(1612)+n(1593)]?.[n(1704)]();continue;case"7":this[n(1346)+n(786)+"t"](_0x13896d,_0x4ffc78);continue}break}}let v=s[n(1473)];if(e[n(558)](void 0,v))if(e[n(735)]!==e.MuKdv)e[n(1342)](J,t,74),e[n(601)](be,t,v);else return this._ws?this[n(444)][n(731)]:"";let A=s.serverTiming;e[n(1094)](void 0,A)&&(e[n(904)](J,t,82),e[n(401)](be,t,A));let T=s[n(1367)];e[n(1094)](void 0,T)&&(e[n(1491)](J,t,90),e[n(1857)](be,t,T));let G=s[n(482)+"e"];e.uRItW(void 0,G)&&(e[n(1401)](J,t,96),e[n(750)](bt,t,e[n(598)](le,G)))}else this[n(1787)+"ount"]=_0x3c3caa,this[n(429)]=0}function I(s){return R(q(s))}function R(s){let t=r,n={};e:for(;!ke(s);){let o=e[t(1253)](U,s);switch(e[t(698)](o,3)){case 0:break e;case 1:n[t(1033)]=e[t(1048)](Pe,s,!0);break;case 2:n[t(834)]=Pe(s,!0);break;case 3:n.service=e[t(1253)](U,s);break;case 4:n[t(1825)]=e[t(1253)](U,s);break;case 5:{let c=e[t(1106)](z,s);(n[t(934)]||(n[t(934)]=[]))[t(483)](e[t(598)](_,s)),s[t(1199)]=c;break}case 6:n.payloadEncoding=e[t(514)](ye,s,e[t(485)](U,s));break;case 7:n.payloadType=e[t(997)](ye,s,e[t(485)](U,s));break;case 8:n[t(1485)]=yt(s,e[t(1202)](U,s));break;case 9:n[t(1473)]=ye(s,e[t(650)](U,s));break;case 10:n[t(691)+t(1529)]=e.GwXQm(ye,s,e[t(485)](U,s));break;case 11:n[t(1367)]=e[t(514)](ye,s,U(s));break;case 12:n[t(482)+"e"]=e[t(1278)](U,s);break;default:e[t(761)](ee,s,e[t(1504)](7,o))}}if(e[t(1126)](void 0,n[t(1033)]))throw new Error(e[t(722)]);if(e[t(1430)](void 0,n[t(834)]))throw new Error(e[t(788)]);if(n[t(1231)]===void 0)throw new Error(e[t(522)]);if(e.avKOu(void 0,n[t(1825)]))throw new Error(e.UpIcY);return n}function z(s){let t=r,n={QOeJv:function(o,c,f){return o(c,f)},AsLWy:t(533),chzCG:e[t(1651)]};if(e.CeKOF===t(496)){let o=e[t(485)](U,s),c=s[t(1199)];return s[t(1199)]=e[t(1797)](s[t(646)],o),c}else _0x5f5c76[t(1061)]()[t(568)](()=>{let o=t,c=n[o(1615)](_0x2f0dca,n[o(1669)],{message:this[o(790)+"rrorMessage"](_0x220be7)});this[o(806)](n[o(1669)],c);let f=n.QOeJv(_0x1409be,n.chzCG,{reason:this[o(790)+"rrorMessage"](_0x758619)});this[o(806)](n[o(1677)],f)})}function ee(s,t){let n=r;switch(t){case 0:for(;e[n(1208)](128,re(s)););break;case 2:e[n(1449)](he,s,e[n(1277)](U,s));break;case 5:e[n(467)](he,s,4);break;case 1:e[n(577)](he,s,8);break;default:throw new Error(e[n(464)](e[n(1298)],t))}}function le(s){return s|=0,{low:s,high:s>>31,unsigned:e.bYSdv(s,0)}}let _e=[];function oe(){let s=r,t=_e[s(1858)]();return t?(t[s(646)]=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(s){_e.push(s)}function q(s){return{bytes:s,offset:0,limit:s[r(1843)]}}function V(s){let t=r,n={YvhBW:function(o,c){return e[P(526)](o,c)},SIAry:function(o,c,f,g){return e.IGjqQ(o,c,f,g)},ynmWj:function(o,c){return e[P(1331)](o,c)},nQBQU:function(o,c){return e[P(1810)](o,c)}};if(e[t(1395)](e[t(810)],e[t(1835)])){let o=s.bytes,c=s[t(1199)];return e[t(844)](o[t(1843)],c)?o:o[t(1626)](0,c)}else{if(_0x38b849>_0x369e57)throw new _0x20a960(t(1141)+t(658)+"e");let o=3;for(;n[t(425)](o,0);){let c=255&_0x308b55;n[t(1765)](_0x4f73bf,c,_0x1379ca,n.ynmWj(_0x1a48d8,o)),_0x3dcf03>>>=8,o--}return n.nQBQU(_0x3eceeb,4)}}function he(s,t){let n=r;if(e.cljUJ(s.offset,t)>s[n(1199)])throw new Error("Skip pas"+n(523));s[n(646)]+=t}function ke(s){let t=r;return e.bwqce(s[t(646)],s[t(1199)])}function ge(s,t){let n=r,o={BkNUm:function(c,f){return c<=f},KPUto:function(c,f){return e.bYSdv(c,f)},yXLvH:function(c,f){return e[P(840)](c,f)},ZJqUC:function(c,f){return e[P(1124)](c,f)},HtWqF:function(c,f){return c<<f},kOqAd:function(c,f){return c&f},bmATN:function(c,f){return c&f},ejcjI:function(c,f){return e[P(943)](c,f)},GCVnx:function(c,f){return e[P(1504)](c,f)},BtzcE:function(c,f){return e[P(693)](c,f)},ldKyf:function(c,f){return e[P(1672)](c,f)},KYEiQ:function(c,f){return c|f},emiao:function(c,f){return e[P(1208)](c,f)},yODtJ:function(c,f){return c&f},vBrmc:function(c,f){return c&f},HxtMe:function(c,f){return e[P(1810)](c,f)},jfgtP:function(c,f){return e.Dwvol(c,f)},TtdJG:function(c,f){return e[P(1810)](c,f)}};if(e[n(452)](e[n(458)],e[n(458)])){let c=s.bytes,f=s[n(646)],g=s[n(1199)],p=e.VPzyI(f,t);if(e.RzBKe(p,c[n(1843)])){let l=new Uint8Array(e.SJFnW(2,p));l[n(510)](c),s[n(1464)]=l}return s[n(646)]=p,e.JMMVC(p,g)&&(s.limit=p),f}else{let c=_0x2695e1[_0x2c8e6a++];if(o[n(1252)](c,127))_0x286180+=_0x16c64e["fromChar"+n(881)](c);else if(o[n(948)](c,192)&&o.yXLvH(c,224))_0x16f554+=_0x1a7661["fromChar"+n(881)](o[n(1659)](o[n(849)](o.kOqAd(31,c),6),o.bmATN(63,_0x4f9d5c[_0x599ee7++])));else if(c>=224&&c<240)_0x34211b+=_0x3bb547.fromCharCode(o.ZJqUC(o[n(1659)](o[n(849)](o[n(475)](15,c),12),o.HtWqF(o[n(1194)](63,_0x21df5d[_0x49de96++]),6)),63&_0x4da420[_0x4bf492++]));else if(o[n(1656)](c,240)){let f=o[n(1402)](o[n(583)](o[n(583)](o.HtWqF(o.emiao(7,c),18)|o[n(451)](63,_0x30050c[_0x279631++])<<12,o[n(849)](o[n(1566)](63,_0x260b04[_0x530ab1++]),6)),o[n(960)](63,_0x3aaa53[_0x47f70d++])),65536);_0x1e64f1+=_0xd9d745.fromCharCode(o[n(1323)](55296,o[n(1044)](f,10))),_0x4073ba+=_0x4f412b[n(637)+n(881)](o[n(1694)](56320,1023&f))}}}function Je(s,t){let n=r,o=s[n(646)];if(e[n(1729)](e[n(1764)](o,t),s.limit))throw new Error(e[n(591)]);return s[n(646)]+=t,o}function yt(s,t){let n=r,o=e[n(1152)](Je,s,t);return s.bytes[n(1626)](o,e[n(1642)](o,t))}function qt(s,t){let n=r,o=ge(s,t[n(1843)]);s[n(1464)][n(510)](t,o)}function ye(s,t){let n=r,o=e[n(902)](Je,s,t),c=String.fromCharCode,f=s[n(1464)],g="\uFFFD",p="";for(let l=0;l<t;l++){let y=f[l+o],k,v,A,T;e[n(740)](128,y)===0?p+=c(y):e[n(943)](224,y)===192?e[n(1661)](e[n(910)](l,1),t)?p+=g:(k=f[e[n(1764)](l+o,1)],e[n(655)](e.RzJSz(192,k),128)?p+=g:(T=e[n(1124)](e[n(1498)](31&y,6),e[n(817)](63,k)),e.lTulI(T,128)?p+=g:(p+=e[n(485)](c,T),l++))):e[n(1780)](e[n(1208)](240,y),224)?e[n(459)](l,2)>=t?p+=g:(k=f[e[n(1309)](e.cljUJ(l,o),1)],v=f[e[n(966)](l+o,2)],e[n(431)](e[n(817)](e[n(836)](k,e[n(1411)](v,8)),49344),32896)?p+=g:(T=e.SiVyg(e[n(819)](15,y)<<12|e.RHhXs(e[n(1155)](63,k),6),e[n(1266)](63,v)),e[n(840)](T,2048)||T>=55296&&e[n(1250)](T,57343)?p+=g:(p+=e[n(650)](c,T),l+=2))):e.EGBrn(e[n(1138)](248,y),240)?e[n(1339)](l,3)>=t?p+=g:(k=f[e[n(1682)](l,o)+1],v=f[e.QNjAj(e[n(804)](l,o),2)],A=f[l+o+3],e[n(437)](e.RzJSz(e[n(836)](k|e.qpaEN(v,8),A<<16),12632256),8421504)?p+=g:(T=e[n(1701)](e[n(1026)](7&y,18),e[n(1150)](e[n(1155)](63,k),12))|e[n(1498)](e[n(441)](63,v),6)|63&A,e[n(840)](T,65536)||e.JMMVC(T,1114111)?p+=g:(T-=65536,p+=c((T>>10)+55296,(1023&T)+56320),l+=3))):p+=g}return p}function be(s,t){let n=r,o=t[n(1843)],c=0;for(let p=0;p<o;p++){let l=t[n(597)+"At"](p);e[n(560)](l,55296)&&l<=56319&&e.Ivgth(p,1)<o&&(l=e[n(1116)](e[n(1055)](l<<10,t[n(597)+"At"](++p)),56613888)),c+=e.lTulI(l,128)?1:e[n(587)](l,2048)?2:l<65536?3:4}e.LTfYC(J,s,c);let f=e.OPRak(ge,s,c),g=s[n(1464)];for(let p=0;p<o;p++){let l=t[n(597)+"At"](p);e[n(1070)](l,55296)&&e.xSewm(l,56319)&&e[n(860)](e[n(1682)](p,1),o)&&(l=e[n(1672)](e.hGbFg(e[n(1595)](l,10),t.charCodeAt(++p)),56613888)),l<128?g[f++]=l:(e.NZdZw(l,2048)?g[f++]=e[n(879)](e[n(1e3)](e[n(1849)](l,6),31),192):(e[n(1330)](l,65536)?g[f++]=e[n(1279)](e[n(1428)](l,12),15)|224:(g[f++]=e[n(978)](e.OvgOA(l,18)&7,240),g[f++]=e[n(668)](e[n(1373)](l>>12,63),128)),g[f++]=e[n(1701)](e[n(1025)](e.qmeWW(l,6),63),128)),g[f++]=e[n(879)](e[n(1390)](63,l),128))}}function Ut(s,t){let n=r,o={sShGe:function(c,f){return e.JSZWe(c,f)},rVAtd:function(c,f){return e[P(943)](c,f)},rmMHb:function(c,f){return e[P(1504)](c,f)},lrxjh:function(c,f){return e[P(1596)](c,f)},cspnj:function(c,f){return e[P(701)](c,f)}};if(e[n(1635)]!==e[n(1635)]){let c=this[n(1845)],f=this[n(821)];return[o[n(1508)](c,24),o[n(1649)](o[n(1508)](c,16),255),o[n(1649)](o[n(1508)](c,8),255),o[n(700)](255,c),f>>>24,o[n(481)](o[n(1508)](f,16),255),o[n(481)](o[n(1861)](f,8),255),o[n(1649)](255,f)]}else{let c=e[n(1140)](ge,s,t[n(1199)]),f=s.bytes,g=t[n(1464)];for(let p=0,l=t.limit;e[n(1069)](p,l);p++)f[e[n(557)](p,c)]=g[p]}}function re(s){let t=r;if(e[t(1316)]!==e[t(1262)])return s[t(1464)][e.iaJts(Je,s,1)];this[t(444)]&&this._ws[t(1611)](_0x4556f8),this[t(1424)](e[t(941)],_0x6dbf25)}function Kt(s,t){let n=r,o=e[n(1294)](ge,s,1);s.bytes[o]=t}function U(s){let t=r,n=0,o=0,c;do c=re(s),e.yMBaA(n,32)&&(o|=e[t(1600)](e.rktUY(127,c),n)),n+=7;while(e[t(1749)](128,c));return o}function J(s,t){let n=r;for(t>>>=0;e.bYSdv(t,128);)e[n(514)](Kt,s,e.SiVyg(e[n(1310)](127,t),128)),t>>>=7;Kt(s,t)}function Pe(s,t){let n=r,o={RupMG:e[n(1223)],KHbAi:e[n(1877)],uVwPf:function(l){return e[n(1680)](l)},EpqHG:e[n(720)],WioSy:function(l){return l()},nPxnh:n(1379)},c=0,f=0,g=0,p;if(p=e[n(1253)](re,s),c=127&p,e.rRNNG(128,p)&&(p=re(s),c|=e[n(1498)](e[n(1304)](127,p),7),e[n(737)](128,p)&&(p=re(s),c|=e[n(928)](e[n(1266)](127,p),14),e[n(1749)](128,p)&&(p=re(s),c|=e[n(875)](127,p)<<21,e[n(819)](128,p)))))if(e.rdUBS("IGIsh",n(1164)))p=e[n(1253)](re,s),f=e.IxUTz(127,p),e[n(1148)](128,p)&&(p=re(s),f|=e[n(1634)](e[n(1301)](127,p),7),e[n(1279)](128,p)&&(p=e[n(650)](re,s),f|=e[n(1177)](127,p)<<14,e[n(1504)](128,p)&&(p=re(s),f|=e.pQUHl(e[n(1304)](127,p),21),128&p&&(p=e.JjPnT(re,s),g=e[n(807)](127,p),e[n(854)](128,p)&&(p=e[n(1277)](re,s),g|=e[n(1595)](127&p,7))))));else{let l=()=>{let v=n;_0x518a0f["removeEventListe"+v(733)](XFyLAB.RupMG,y),_0x1d2bdf[v(938)+v(1425)+v(733)](XFyLAB.KHbAi,k),_0x3e182c[v(938)+v(1425)+v(733)]("abort",k)},y=()=>{XFyLAB.uVwPf(_0x366d18),l()},k=()=>{let v=n;_0x511d44(_0x239afa[v(533)]||new _0x51ff55(XFyLAB.EpqHG,XFyLAB[v(1093)])),XFyLAB.WioSy(l)};_0x2a07e2[n(1149)+"Listener"](XFyLAB.RupMG,y),_0x1dc4cc[n(1149)+n(1538)](XFyLAB[n(852)],k),_0xef1562[n(1149)+n(1538)](XFyLAB[n(1046)],k)}return{low:e.rKGLW(c,f<<28),high:e[n(1715)](e[n(1060)](f,4),e[n(1634)](g,24)),unsigned:t}}function bt(s,t){let n=r,o=e[n(791)](t.low,0),c=e[n(683)](e[n(791)](t[n(821)],28),t[n(1845)]<<4)>>>0,f=e[n(1572)](t.high,24),g=e.cCchm(0,f)?c===0?e.yMBaA(o,16384)?e.NZdZw(o,128)?1:2:e[n(499)](o,2097152)?3:4:e.AVFzs(c,16384)?e.lTulI(c,128)?5:6:e[n(1654)](c,2097152)?7:8:f<128?9:10,p=e[n(440)](ge,s,g),l=s[n(1464)];switch(g){case 10:l[e.WEbAC(p,9)]=e[n(744)](f>>>7,1);case 9:l[e[n(965)](p,8)]=e[n(1381)](9,g)?128|f:e[n(740)](127,f);case 8:l[e[n(1339)](p,7)]=e[n(437)](8,g)?e[n(808)](e[n(539)](c,21),128):e[n(854)](e[n(1060)](c,21),127);case 7:l[e[n(1162)](p,6)]=e.GqdvH(7,g)?e[n(656)](e.RuAQU(c,14),128):e[n(1090)](e[n(508)](c,14),127);case 6:l[p+5]=e.riorE(6,g)?e[n(492)](c,7)|128:e.TUOit(c>>>7,127);case 5:l[e[n(584)](p,4)]=e[n(664)](5,g)?e[n(808)](128,c):e[n(1575)](127,c);case 4:l[e[n(1339)](p,3)]=e[n(431)](4,g)?e[n(1124)](o>>>21,128):e[n(807)](e[n(698)](o,21),127);case 3:l[e[n(400)](p,2)]=e.riorE(3,g)?e.lGMbO(o,14)|128:o>>>14&127;case 2:l[p+1]=e[n(1315)](2,g)?e[n(873)](e.TcEet(o,7),128):e[n(1734)](e[n(566)](o,7),127);case 1:l[p]=g!==1?e[n(836)](128,o):e.HEJUR(127,o)}}function Qr(s){return I(s)}function $n(s){return e.ChMiU(C,s)}let Xr=65536,Vo=e[r(906)],nt=e.szihn(Xr,Xr),Zr=nt*nt,es=e[r(907)](Zr,2),ze=String[r(1268)+"e"][r(597)+"At"];class O{constructor(t,n,o){let c=r;this[c(888)]=!0,this[c(821)]=0|t,this[c(1845)]=e[c(1701)](0,n),this[c(893)]=!!o}static isLong(t){return t&&t.isLong===!0}static[r(1645)](t,n,o){let c=r;if(e[c(1281)]!==e[c(1037)])return new O(t,n,o);_0x164df7[_0x131ef7++]=e.dzwRZ(e[c(1542)](_0x55bfe9,6),192),_0x193dcb[_0xf90bd7++]=e.YfJKs(e[c(1601)](63,_0x33b172),128)}static[r(1392)+"s"](t,n,o){let c=r;if(e[c(1813)](e[c(670)],e[c(993)]))return o?O[c(1392)+c(1343)](t,n):O[c(1392)+c(789)](t,n);VTKkRk[c(1516)](_0x394b6b,VTKkRk[c(798)](_0x1e73a0,_0x54a1f0[c(1456)]),_0xf11f7e[c(1180)+"on"],_0x2f882a[c(1823)+"on"],_0x55544a(_0x3da622[c(660)+c(474)]))}static[r(1392)+"sLE"](t,n){let o=r;return new O(e.AFxaG(t[0]|e.LqcvF(t[1],8),e[o(1600)](t[2],16))|e[o(1150)](t[3],24),e.DRgNF(t[4]|t[5]<<8,t[6]<<16)|e[o(1211)](t[7],24),n)}static[r(1392)+r(789)](t,n){let o=r;return new O(e[o(656)](e[o(668)](t[4]<<24,e[o(1634)](t[5],16))|e[o(1440)](t[6],8),t[7]),e.LqIdV(e[o(751)](e[o(873)](e[o(1150)](t[0],24),e[o(1731)](t[1],16)),t[2]<<8),t[3]),n)}static[r(1423)](t){let n=r;return e[n(621)](t,Vo)?ts:new O(e[n(668)](e[n(745)](ze[n(1236)](t,0)|e.yaerY(ze.call(t,1),8),e.WUWZL(ze.call(t,2),16)),e.lPxdZ(ze[n(1236)](t,3),24))>>>0,e.bWUiC(e.HuHjX(e.YDkPu(e[n(1739)](ze.call(t,4),ze[n(1236)](t,5)<<8),e[n(1662)](ze.call(t,6),16)),ze[n(1236)](t,7)<<24),0),!0)}[r(1730)](){let t=r;return String[t(637)+"Code"](e[t(1301)](255,this[t(821)]),e.HEJUR(e[t(791)](this[t(821)],8),255),e[t(1177)](e[t(501)](this.low,16),255),this[t(821)]>>>24,e[t(1273)](255,this[t(1845)]),e[t(443)](e[t(1071)](this[t(1845)],8),255),e.hARBm(this.high,16)&255,e.HjOEK(this[t(1845)],24))}static fromNumber(t,n=!0){let o=r;if(e[o(1202)](isNaN,t))return n?Yo:ts;if(n){if(e[o(560)](t,Zr))return Qo}else{if(e[o(796)](t,-es))return Xo;if(e[o(828)](t+1,es))return $o}return O[o(1645)](e[o(1337)](e[o(800)](t,nt),0),e[o(914)](e.aWDVg(t,nt),0),n)}[r(1312)](){let t=r;if(e[t(1099)]("FbWag",t(605)))this[t(806)](t(1314),_0x28ae7f),this[t(1722)]&&this[t(1722)](_0x453985);else return this[t(893)]?e.YYGXT(this[t(1845)],0)*nt+e[t(753)](this[t(821)],0):e[t(434)](this[t(1845)],nt)+e[t(1495)](this[t(821)],0)}[r(422)](){let t=r;if(e[t(1708)]!==e[t(847)])return e[t(924)](0,this[t(1845)])&&e.avKOu(0,this[t(821)]);VTKkRk[t(1106)](_0x51da65,VTKkRk.gMdaj(_0x152813,_0x1e094d[t(1456)])),VTKkRk[t(1680)](_0x1cc1a3)}add(t){let n=r;O[n(888)](t)||(t=O[n(652)+"er"](t));let o=this[n(1845)]>>>16,c=e[n(1189)](65535,this[n(1845)]),f=this[n(821)]>>>16,g=65535&this[n(821)],p=e[n(1751)](t.high,16),l=e.ZVplU(65535,t[n(1845)]),y=e[n(743)](t[n(821)],16),k=65535&t[n(821)],v=0,A=0,T=0,G=0;return G+=e[n(1011)](g,k),T+=e.ksOQA(G,16),G&=65535,T+=f+y,A+=e[n(1723)](T,16),T&=65535,A+=e[n(534)](c,l),v+=e[n(1110)](A,16),A&=65535,v+=e[n(1477)](o,p),v&=65535,O[n(1645)](e[n(1811)](T<<16,G),e[n(808)](v<<16,A),this[n(893)])}[r(1883)](t){let n=r;return O.isLong(t)||(t=O.fromNumber(t)),e[n(1850)](this[n(893)],t.unsigned)&&e[n(924)](this[n(1845)]>>>31,1)&&e[n(1209)](e[n(728)](t[n(1845)],31),1)?!1:this[n(1845)]===t[n(1845)]&&e.xJvZG(this[n(821)],t.low)}[r(471)](){let t=r;return this[t(821)]===-1&&this.high===-1?O[t(1645)](0,0,this[t(893)]):e.ZNDUj(-1,this[t(821)])?O[t(1645)](0,e[t(1134)](this[t(1845)],1),this.unsigned):O.fromBits(e[t(1810)](this.low,1),this.high,this[t(893)])}[r(1083)](t){let n=r;return t?this[n(554)+"E"]():this[n(1753)+"E"]()}[r(554)+"E"](){let t=r,n=this.high,o=this.low;return[e.RzJSz(255,o),e[t(875)](o>>>8,255),e[t(1208)](e[t(1421)](o,16),255),e[t(1239)](o,24),e[t(476)](255,n),e.MdLlg(n>>>8,255),e[t(1390)](e[t(911)](n,16),255),e[t(1784)](n,24)]}toBytesBE(){let t=r,n=this.high,o=this.low;return[n>>>24,e[t(1237)](n,16)&255,e[t(1058)](e[t(508)](n,8),255),255&n,o>>>24,e[t(1697)](e[t(911)](o,16),255),e[t(1636)](e[t(1878)](o,8),255),e.xGioe(255,o)]}}let ts=new O(0,0,!1),Yo=new O(0,0,!0),$o=O.fromBits(-1,2147483647,!1),Qo=O[r(1645)](-1,-1,!0),Xo=O[r(1645)](0,-2147483648,!1);var Fe=(function(s){let t=r,n=e[t(832)][t(862)]("|"),o=0;for(;;){switch(n[o++]){case"0":s[s[e[t(1847)]]=5002]=t(1786)+t(981);continue;case"1":s[s[e[t(1766)]]=5003]=e[t(1766)];continue;case"2":s[s[e[t(1397)]]=5001]=e[t(1397)];continue;case"3":return s;case"4":s[s[e[t(1561)]]=5005]=e[t(1561)];continue;case"5":s[s[e.XEYcY]=5004]=e[t(470)];continue}break}})({});class rt{constructor(t){let n=r;this[n(1433)]=t,this[n(1130)]=null}}class ns extends rt{constructor(t,n){let o=r;super(t),this[o(1399)]=n&&n.message||null}}class rs extends rt{constructor(t,n){let o=r,c=e[o(1862)][o(862)]("|"),f=0;for(;;){switch(c[f++]){case"0":this[o(1086)]=n&&n[o(1086)]||0;continue;case"1":this[o(876)]=n&&n[o(876)]||0;continue;case"2":this[o(1726)]=n&&n.code||5001;continue;case"3":this[o(1399)]=n&&n[o(1399)]||"";continue;case"4":this[o(533)]=n&&n[o(533)]||null;continue;case"5":super(t);continue;case"6":this.filename=n&&n[o(1664)]||"";continue}break}}}class ss extends rt{constructor(t,n){let o=r,c=e[o(454)][o(862)]("|"),f=0;for(;;){switch(c[f++]){case"0":this[o(1358)+o(747)]=n&&n[o(1358)+o(747)]||!1;continue;case"1":this[o(850)]=n&&n[o(850)]||!1;continue;case"2":this.code=n&&n[o(1726)]||0;continue;case"3":this[o(1517)]=n&&n[o(1517)]||"";continue;case"4":super(t);continue}break}}}class is extends rt{constructor(t,n){let o=r;super(t),this[o(1779)]=n&&n[o(1779)]||null}}class os extends is{constructor(t,n){let o=r;super(t),this.data=n&&n[o(1779)]||null,this[o(1399)]=n&&n[o(1399)]||null}}class as extends rt{constructor(t,n){let o=r;if(e.eFZCN("aFpBJ",e[o(1641)]))super(t),this[o(1779)]=n&&n[o(1779)]||null;else{let{initReconnectInterval:c,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this._options,p=e[o(434)](c,_0x2eec90.pow(g,e[o(1672)](_0xdeac8a,1)));return e.Ngphh(p,f)?f:p}}}function ue(s,{message:t,code:n,error:o}){return new rs(s,{message:t,code:n,error:o})}function pe(s,{code:t,reason:n,wasClean:o,willReconnect:c}){return new ss(s,{code:t,reason:n,wasClean:o,willReconnect:c})}function cs(s,{data:t,message:n}){return new os(s,{data:t,message:n})}function xs(s,{data:t}){return new as(s,{data:t})}function Qn(s,{message:t}){return new ns(s,{message:t})}class us{constructor(t,n){let o=r,c={QNGtn:"error",xFywa:function(f,g,p){return e[P(1832)](f,g,p)},rWfjh:function(f,g){return f+g}};if(e[o(1275)](e.KNASK,e[o(1172)])){let f=_0x44145f[o(1548)][o(1727)](_0x42283c[o(1230)+"et"],c[o(882)](_0x2c3a69[o(986)+"th"],_0x18091a[o(1230)+"et"]));this[o(570)]&&this[o(570)][o(1611)]({data:f,fail:g=>{let p=o;this[p(806)](c[p(930)],c[p(1139)](_0x1b48db,p(533),{message:this[p(790)+"rrorMess"+p(1066)](g)}))}})}else this[o(1217)+"s"]=t,this[o(1770)+"es"]=n,this[o(1062)+o(388)]=0,this[o(1489)+o(654)+o(1338)+"t"]=0}[r(1828)+"pointCon"+r(1759)](){let t=r;e[t(1820)]!==t(653)?(this[t(1062)+t(388)]=0,this[t(1489)+"ndpointT"+t(1338)+"t"]=0):(_0x56a081(_0xe96a13,90),e.CUWCr(_0x3018fb,_0x398e3d,_0x42a89f))}[r(1174)+"es"](){let t=r;this[t(1489)+"ndpointT"+t(1338)+"t"]=0}getCurrentEndpoint(){let t=r;return this[t(1217)+"s"][this["currentI"+t(388)]]}["getCurre"+r(1210)+"ntTriesCount"](){let t=r;return this[t(1489)+t(654)+t(1338)+"t"]}[r(1350)+r(749)+"es"](){let t=r;return!!(e[t(1661)](this[t(1062)+"ndex"],this.endpoints[t(1843)])||e[t(957)](this["currentI"+t(388)],e[t(1897)](this[t(1217)+"s"][t(1843)],1))&&this[t(1489)+t(654)+t(1338)+"t"]===this[t(1770)+"es"])}[r(1580)+r(424)+r(889)+r(1135)+"tries"](){let t=r;return this["currentI"+t(388)]==this[t(1217)+"s"][t(1843)]?!0:e[t(1729)](this[t(1489)+"ndpointT"+t(1338)+"t"],this[t(1770)+"es"])}[r(1788)+r(769)+r(1376)+r(1092)+r(1370)](){let t=r;return this[t(1489)+t(654)+"riesCount"]=1,this[t(1062)+t(388)]++,this[t(1217)+"s"][this[t(1062)+t(388)]]}["getCurre"+r(1210)+r(1200)+r(706)](){let t=r;return this[t(1489)+t(654)+t(1338)+"t"]++,this.getCurrentEndpoint()}}let st=(e[r(1644)]("undefined",typeof globalThis)&&e.ZoNCt(e.kITlB,globalThis[r(1859)+r(1894)].name)||e[r(962)](e[r(537)],typeof window)&&e.UrJhm(e[r(1864)],window["construc"+r(1894)].name))&&e[r(963)](e.CISfi,typeof document),Ve=e[r(942)](e.CISfi,typeof globalThis)&&(e[r(1408)](e[r(1274)],globalThis[r(1859)+r(1894)][r(1546)])||e[r(1899)](e.RPRaO,globalThis[r(1859)+"tor"][r(1546)]))&&e[r(537)]!=typeof tt,vt=(e[r(1307)](r(399)+"d",typeof globalThis)&&e[r(1274)]===globalThis[r(1859)+r(1894)][r(1546)]||e[r(1175)](e[r(537)],typeof globalThis)||e[r(1644)](e[r(537)],typeof globalThis)&&!!globalThis["WeixinJS"+r(1261)])&&e[r(727)](r(399)+"d",typeof wx),St=e.BcEpQ(r(399)+"d",typeof globalThis)&&(e.OZJSO(e.RPRaO,globalThis[r(1859)+r(1894)].name)||r(811)+r(1539)+r(1427)===globalThis[r(1859)+r(1894)][r(1546)]||e[r(509)]===globalThis[r(1859)+"tor"][r(1546)])&&e[r(537)]!=typeof self,Zo=e[r(1846)](e[r(537)],typeof globalThis)&&e.hFHyy(e[r(1274)],globalThis[r(1859)+r(1894)].name)&&r(399)+"d"!=typeof global&&e[r(1274)]===global[r(1859)+r(1894)][r(1546)]&&e.CISfi!=typeof process&&!!process.version;class Xn{constructor(){let t=r;this[t(803)+"rs"]={}}emit(t,...n){let o=r,c=this[o(803)+"rs"][t];if(c)c[o(1727)]()[o(1170)](f=>f.fn.apply(f[o(478)],n));else if(e[o(550)](e.uRZCb,t)&&!this[o(463)]){let f=n[o(1843)]&&n[0];if(e[o(527)](f,Error))throw f;let g=new Error(e[o(1176)]+(f?e[o(1161)](e[o(1764)](" (",f[o(1399)]),")"):""));throw g[o(1332)]=f,f}return this}[r(831)](t,n){let o=r,c={ntlBo:function(f,g,p){return e.stPRV(f,g,p)}};if(o(1306)!==e[o(822)]){if(e.rsBWX(void 0,t))this._listeners={};else if(e[o(1221)](void 0,n))this._listeners[t]=null;else if(e[o(550)](e[o(503)],o(1032))){let f="connect "+_0xc6b42a+(o(784)+o(1056)+o(677)+"ed");this[o(877)+o(925)+o(1222)](c[o(1285)](_0x31b941,o(533),{message:f,code:_0x2ef8e4[o(395)+"IES_ERROR"],error:_0xb89cea}));return}else{let f=this[o(803)+"rs"][t];if(f)for(let g=0;e[o(792)](g,f[o(1843)]);)e[o(621)](f[g].fn,n)?f[o(626)](g,1):++g}return this}else{let f=e[o(1570)](_0x191283,_0x3b4ca2,_0x44dde2.length);_0x218b0a[o(1464)][o(510)](_0x4f973d,f)}}on(t,n,o){let c=r;return(this[c(803)+"rs"][t]||(this._listeners[t]=[]))[c(483)]({fn:n,ctx:o||this}),this}}class ea extends Xn{[r(790)+r(1193)+r(1066)](t){let n=r;return t[n(1438)]||t.errNo?(n(1345)+" "+(t[n(1438)]||"")+n(1129)+(t[n(1747)]||""))[n(521)]():JSON[n(438)+"y"](t)}constructor(t,n,o){let c=r;super(),this[c(570)]=null,vt&&wx["connectS"+c(1866)]&&(this[c(570)]=wx[c(1227)+"ocket"]({url:t,protocols:n,header:o,fail:this["_createS"+c(1533)+c(1748)][c(953)](this),success:this[c(1785)+c(1536)+c(599)+"ler"][c(953)](this)})),Ve&&tt[c(1227)+c(1866)]&&(this._socket=tt["connectS"+c(1866)]({url:t,protocols:n,header:o,fail:this["_createS"+c(1533)+"lHandler"][c(953)](this),success:this[c(1785)+c(1536)+c(599)+c(669)].bind(this)}))}[r(1785)+"ocketSuccessHand"+r(669)](){let t=r;Promise[t(1061)]()[t(568)](()=>{this[t(829)+"steners"]()})}[r(1785)+"ocketFai"+r(1748)](t){let n=r;if(e[n(1850)](e[n(589)],e[n(567)]))Promise.resolve()[n(568)](()=>{let o=n,c=ue(e[o(1877)],{message:this["_formatE"+o(1193)+o(1066)](t)});this[o(806)](e[o(1877)],c);let f=e[o(1048)](pe,e.QweJd,{reason:this[o(790)+o(1193)+o(1066)](t)});this.emit(e[o(1651)],f)});else return e.uIGoH(_0x201b21[n(646)],_0x1ce6de[n(1199)])}["_addWsLi"+r(620)](){let t=r,n={dcjnF:t(1875),mNQsh:e[t(640)],GlOzC:function(o,c,f){return e[t(1394)](o,c,f)},vxiBH:e[t(1877)],lEmmA:function(o,c,f){return o(c,f)}};this[t(570)][t(436)](o=>{let c=t;this[c(806)](n.dcjnF,xs(n[c(1361)],{...o,data:o[c(1438)]||""}))}),this[t(570)].onClose(o=>{let c=t;this.emit("close",e.OPRak(pe,c(1314),{...o}))}),this[t(570)][t(1228)+"e"](o=>{let c=t;this[c(806)](n[c(1808)],n[c(1405)](cs,n[c(1808)],{...o}))}),this[t(570)][t(944)](o=>{let c=t;this.emit(n[c(1763)],n.lEmmA(ue,n[c(1763)],{...o,message:o[c(1438)]||""}))})}[r(1611)](t){let n=r,o={AGucA:e.uRZCb,aOGtp:function(c,f,g){return e[P(1324)](c,f,g)}};if(t instanceof Uint8Array){let c=t.buffer.slice(t[n(1230)+"et"],e[n(1309)](t.byteLength,t[n(1230)+"et"]));this[n(570)]&&this[n(570)][n(1611)]({data:c,fail:f=>{let g=n;this.emit(e[g(1877)],e.KuybI(ue,e[g(1877)],{message:this[g(790)+g(1193)+g(1066)](f)}))}})}else this[n(570)]&&this[n(570)][n(1611)]({data:t,fail:c=>{let f=n;this[f(806)](o[f(935)],o.aOGtp(ue,f(533),{message:this[f(790)+f(1193)+f(1066)](c)}))}})}close(t,n){let o=r;this._socket&&this[o(570)].close({code:t,reason:n})}[r(1149)+r(1538)](t,n){this.on(t,n)}[r(938)+r(1425)+"ner"](t,n){this.off(t,n)}get[r(1396)+"te"](){let t=r;return this[t(570)][t(1396)+"te"]}get[r(1590)+"pe"](){let t=r;return this._socket[t(1590)+"pe"]}set[r(1590)+"pe"](t){}get[r(748)](){let t=r;if(e[t(1657)](e[t(1796)],e[t(1796)]))_0x425871(_0x38129a,66),e.rsyIF(_0x5b3cec,_0x5c74db,_0x5c3f6a[t(1843)]),_0x2b479b(_0x5697ef,_0x1490b6);else return this[t(570)][t(748)]}get[r(731)](){return this[r(570)].protocol}get[r(871)+"ns"](){let t=r;return e.dkZjV(e[t(1434)],"VLDgf")?this[t(570)][t(871)+"ns"]:!!this[t(679)]}get[r(1151)+r(461)](){return 0}}function ta(s,t){let n=r;if(t)return new t(s[n(748)],s[n(731)]);if(e[n(1435)](vt,Ve))return new ea(s[n(748)],s.protocol,s.headers);if(e[n(1652)](st,St)&&n(399)+"d"!=typeof WebSocket&&WebSocket)return new WebSocket(s[n(748)],s.protocols)}function na(s){let t=r,n=e[t(1111)][t(862)]("|"),o=0;for(;;){switch(n[o++]){case"0":return!1;case"1":if(e[t(1892)](st,St)&&e.lsGwc(e[t(537)],typeof WebSocket)&&WebSocket)return!0;continue;case"2":if(vt&&wx[t(1227)+t(1866)])return!0;continue;case"3":if(s)return!0;continue;case"4":if(Ve&&tt[t(1227)+t(1866)])return!0;continue}break}}function fs(s,t,n){let o=-1;async function c(f){let g=P;return e[g(420)](f,o)?Promise.reject(new Error(e.Scxza)):(o=f,e.IJmdG(f,n.length)?Promise[g(1061)]():n[f].bind(s)(t,c.bind(null,e[g(1234)](f,1))))}c(0)}function ds(s){let t=r,n=0,o=0;for(let c=0;e[t(1860)](c,s[t(1843)]);++c)o=s[t(597)+"At"](c),e[t(1069)](o,128)?n+=1:e[t(499)](o,2048)?n+=2:e[t(476)](64512,o)===55296&&e[t(1783)](e[t(1155)](64512,s.charCodeAt(e[t(1309)](c,1))),56320)?(++c,n+=4):n+=3;return n}function ls(s,t,n){let o=r;if(e[o(479)](e[o(805)](n,t),1))return"";let c="";for(let f=t;e[o(479)](f,n);){let g=s[f++];if(e.glwqU(g,127))c+=String[o(637)+o(881)](g);else if(e[o(1618)](g,192)&&e[o(1295)](g,224))c+=String[o(637)+o(881)](e[o(1834)](e[o(1004)](31&g,6),63&s[f++]));else if(e[o(693)](g,224)&&g<240)c+=String[o(637)+"Code"](e[o(1442)](e[o(1778)](e.lPxdZ(e[o(1156)](15,g),12),e[o(1304)](63,s[f++])<<6),63&s[f++]));else if(e[o(1587)](g,240)){let p=e.asdTN(e[o(1811)](e[o(1081)](7&g,18)|e[o(1462)](e[o(1301)](63,s[f++]),12),e.cdAzB(63&s[f++],6)),e.adpaz(63,s[f++]))-65536;c+=String[o(637)+o(881)](e[o(867)](55296,e[o(1428)](p,10))),c+=String["fromChar"+o(881)](e[o(767)](56320,e[o(1623)](1023,p)))}}return c}function Zn(s,t,n){let o=r,c={LAUQn:function(f,g){return e[P(1780)](f,g)},IFzwc:e[o(1414)],wdtKP:function(f,g){return e[o(1534)](f,g)},kspSH:function(f,g,p,l){return e[o(1101)](f,g,p,l)}};if(e.Nneem(o(1255),"abery")){let f=n,g,p;for(let l=0;l<s[o(1843)];++l)if(g=s[o(597)+"At"](l),e[o(1564)](g,128))t[n++]=g;else if(e.AVFzs(g,2048))t[n++]=e.ZmDaV(g>>6,192),t[n++]=e[o(1636)](63,g)|128;else if(e[o(1138)](64512,g)===55296&&e[o(1366)](e[o(1553)](64512,p=s[o(597)+"At"](l+1)),56320)){let y=e.GpaEk[o(862)]("|"),k=0;for(;;){switch(y[k++]){case"0":t[n++]=e.RAzuB(e[o(1542)](g,12)&63,128);continue;case"1":t[n++]=e[o(1715)](e.adpaz(e[o(1660)](g,6),63),128);continue;case"2":++l;continue;case"3":t[n++]=e.XydME(63,g)|128;continue;case"4":g=e[o(1560)](e[o(1134)](65536,e[o(1634)](1023&g,10)),1023&p);continue;case"5":t[n++]=e[o(1660)](g,18)|240;continue}break}}else t[n++]=g>>12|224,t[n++]=e[o(683)](e[o(1156)](g>>6,63),128),t[n++]=e[o(1072)](e[o(390)](63,g),128);return n-f}else{if(c[o(1212)](c[o(435)],typeof _0x28b12c)){let f=new _0x5cba6e(c[o(1586)](_0xdb88d2,_0x209d1d));return c.kspSH(_0x10da37,_0x3f1386,f,0),f}return _0x4e0813 instanceof _0x44d21a?new _0x1598ec(_0x543636):new _0x3cf503(_0xbdcf20[o(1548)],_0x3b4d94[o(1230)+"et"],_0x3868db.byteLength)}}async function hs(s){let t=r;if(e[t(1414)]==typeof s){let n=new Uint8Array(e.RSkBe(ds,s));return Zn(s,n,0),n}return e[t(511)](s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s[t(1548)],s[t(1230)+"et"],s[t(986)+"th"])}function ra(s){let t=r;try{return e[t(1414)]!=typeof s&&(e[t(511)](s,ArrayBuffer)||s.buffer&&e.jgBUt(s.buffer,ArrayBuffer))||e.OaLAW(e[t(1414)],typeof s)?"":(JSON[t(1525)](s),t(488)+t(506))}catch{return e[t(991)](e[t(1414)],typeof s)?e[t(524)]:""}}let sa=(s,t)=>{let n=r;switch(s){case e[n(976)]:case n(1690):return{[n(556)+s]:1,"x-tt-env":t};default:return{}}};class ia{constructor(t){let n=r;this[n(1787)+n(1142)]=t,this.count=0}[r(495)](){let t=r;e[t(680)](t(905),e.NGYFc)?this.count++:(VTKkRk[t(537)]!=typeof _0x466e&&_0x42759a[t(846)+"Tag"]&&_0x352fc0["definePr"+t(1375)](_0x19373c,_0x9d49d9[t(846)+t(959)],{value:VTKkRk[t(415)]}),_0xe4ca35.defineProperty(_0x4c13d8,VTKkRk[t(1096)],{value:!0}))}[r(1350)+"chMaxCount"](){let t=r;return this.count>=this["maxLossC"+t(1142)]}[r(949)+r(917)](t=0){let n=r;this[n(1787)+"ount"]=t,this[n(429)]=0}}async function oa(s){let t=r,n={JMmjO:function(o,c){return e[P(1250)](o,c)},YEBAg:function(o,c){return e[P(927)](o,c)},uHUxC:function(o,c){return e[P(964)](o,c)},JCfgh:function(o,c){return o-c},MbdVt:function(o,c){return o<<c},Fmaba:function(o,c){return e[P(927)](o,c)},HzEOm:function(o,c){return e.jxUMB(o,c)},qrOPt:e[t(1027)],Nhoyt:e[t(487)],cYxiT:e[t(1020)],MrYNX:function(o,c){return o&c},bvWzn:function(o,c){return e[t(1099)](o,c)},sxnuP:t(611),Vildp:t(1494),lWeJu:e[t(1767)],BxJrL:e.bOLnI,Tydzw:e[t(1574)],zumgc:function(o,c){return o===c},hjfTl:e[t(1592)],oRvna:e[t(1658)],yvTxs:e[t(1045)],rxlFE:e.nnhZr};return new Promise(o=>{let c=t,f={RFaMO:function(g,p){return n[P(622)](g,p)},MbFJp:n[c(595)],VECnu:n[c(1608)],WVJNN:n.cYxiT,fmhYS:"pageshow",Lught:function(g,p){return n[c(1684)](g,p)},VUZVu:function(g,p){return n[c(433)](g,p)}};if(n.bvWzn(n[c(1552)],n[c(1675)])){if(!st)return o(n[c(595)]);try{let g=document.createElement(n.lWeJu);window["frontier"+c(1639)]=p=>{let l=c;document[l(1457)][l(525)+"ild"](g),window[l(1617)+"JSONP"]=void 0,f[l(1087)](o,p&&p[l(756)]||f.MbFJp)},g.type=n[c(1868)],g[c(842)]=n[c(433)](s[c(1493)](/^ws/,"http"),n[c(1711)]);try{n[c(604)](n[c(916)],c(812))?document.body[c(1499)+c(884)](g):(this[c(1308)+"er"]&&_0x42bab4["removeEv"+c(1425)+"ner"](f[c(1251)],this[c(396)+c(1714)]),this[c(1308)+"er"]&&_0x26acf5[c(938)+"entListe"+c(733)](c(1356),this[c(396)+c(1478)]),this[c(1308)+"er"]&&_0x1583be[c(938)+c(1425)+c(733)](f.WVJNN,this[c(491)+c(507)]),this._isBrowser&&_0x260dbb["removeEventListe"+c(733)](f.fmhYS,this[c(491)+c(393)]))}catch{if(n[c(651)]("casDc",n[c(1291)]))document[c(1457)][c(525)+c(884)](g);else try{return!!this[c(679)]}catch(p){return _0xe85e82[c(1030)](p),!1}}}catch{if(n.bvWzn(n[c(1884)],n[c(1744)]))window[c(1617)+"JSONP"]=void 0,n[c(622)](o,c(1518)+c(1517));else{let g=_0x3eff87.charCodeAt(_0x4851f4);g>=55296&&bzaUbV.JMmjO(g,56319)&&bzaUbV[c(490)](bzaUbV.uHUxC(_0x37c9b5,1),_0x3ad501)&&(g=bzaUbV.JCfgh(bzaUbV[c(433)](bzaUbV.MbdVt(g,10),_0x574c87[c(597)+"At"](++_0x37c842)),56613888)),_0x4f014b+=bzaUbV[c(1625)](g,128)?1:bzaUbV[c(490)](g,2048)?2:g<65536?3:4}}}else return _0x1b62fb[c(1171)+"t8"]?_0x14930e[c(1171)+"t8"](_0x3b33c4,_0x2970fb):_0x20ce65[_0x2a2dfd]=f.Lught(255,_0x4d8d34),f[c(967)](_0x310947,1)})}function qe(s,t,n){let o=r,c={jAYxM:function(f,g,p){return e[P(1543)](f,g,p)},xbQpc:e.QweJd};if(e[o(900)](e[o(1443)],e[o(1191)])){let f=this[o(1741)+o(1676)]?.[o(1372)+o(1210)+"nt"]();this[o(877)+o(1523)+o(1222)](c[o(922)](_0x1fad0b,c.xbQpc,{code:_0x3076ec.code,reason:o(1220)+o(1721)+o(428)+o(1105)+"n, hostname: "+f})),this[o(1741)+"tManager"]?.[o(1828)+o(1582)+"fig"](),this[o(939)+o(1409)]?.[o(949)+o(917)]();return}else return!!s?.[o(1889)](f=>f[o(736)]===t&&f[o(405)]===n)}function it(s,t){let n=r;return s?.find(o=>o[n(736)]===t)?.[n(405)]}let er=null;async function aa(){let s=r;return er||(er=Promise[s(1061)]()[s(568)](Ee[s(953)](Ee,"idb"))),er}class ca extends Xn{constructor(t,n){let o=r;super(),this[o(1472)]=t,this[o(979)]=n,this[o(679)]=void 0,this._initPromise=null}async[r(1833)](){await this[r(1355)]()}async[r(1355)](){let t=r,n={FYUYD:function(o){return e[P(1349)](o)},xURGG:function(o,c,f,g){return o(c,f,g)}};if(!this[t(679)]){if(this[t(768)+t(1079)])return this["_initPro"+t(1079)];try{let o=this[t(1472)],c=this._keyPath;this[t(768)+t(1079)]=(async()=>{let f=t,{openDB:g}=await n[f(609)](aa);this[f(679)]=await n[f(1117)](g,f(1617)+"_"+o,1,{upgrade(p){let l=f;p[l(1459)+l(977)+"e"](o,{keyPath:c})}})})(),await this["_initPro"+t(1079)]}catch(o){console[t(1030)](o)}finally{this[t(768)+t(1079)]=null}}}async[r(1528)](t){let n=r;try{return await this[n(1355)](),this[n(679)]?.[n(1528)](this[n(1472)],t)}catch(o){console[n(1030)](o)}}async set(t,n){let o=r;return await this[o(1355)](),this[o(679)]?.[o(1006)](this[o(1472)],t)}async[r(586)](t){let n=r;if(e[n(1899)](e[n(472)],e[n(472)]))try{return await this[n(1355)](),this[n(679)]?.[n(972)](this[n(1472)],t)}catch(o){console[n(1030)](o)}else return null}async[r(1799)](){let t=r;try{return await this._init(),this[t(679)]?.[t(1799)](this[t(1472)])}catch(n){console[t(1030)](n)}}async[r(1480)](){let t=r;return e[t(837)](e[t(661)],e[t(1041)])?this[t(570)].protocol:(await this[t(1355)](),this[t(679)]?.[t(1581)+"ys"](this[t(1472)]))}async[r(489)](){let t=r;return await this[t(1355)](),this[t(679)]?.[t(489)](this[t(1472)])}async closeDB(){let t=r,n={BLZjj:function(o,c){return o instanceof c},tJLYg:function(o,c){return e.WnYsr(o,c)},GlUtI:function(o,c){return e[P(579)](o,c)}};try{this._qosDB?.[t(1314)](),this[t(679)]=void 0}catch(o){if(e[t(1699)]!==e.ctxDh)return yALsff[t(858)](_0x4f0739,_0x59bb7c)&&(yALsff.tJLYg(_0x81aeb5,"done")||_0x5d6265===t(838))?!0:yALsff[t(1391)](_0x35b38a,_0x2f74e8);console[t(1030)](o)}}get isReady(){let t=r;try{return e[t(985)](e[t(1812)],e[t(1812)])?!!this[t(679)]:this[t(444)]?this[t(444)][t(1590)+"pe"]:this[t(874)+t(1114)]}catch(n){return console.log(n),!1}}}class xa{constructor(t,n){let o=r;this._DBName=t,this[o(1888)]=n,this[o(679)]=localStorage}async[r(1833)](){}get[r(1353)](){let t=r;return t(1617)+"_"+this[t(1622)]}async[r(1528)](t){let n=r,o=this[n(679)][n(504)](this[n(1353)]);return JSON[n(1525)](o||"{}")[t]}async[r(510)](t,n){let o=r,c=this[o(679)][o(504)](this._prefix),f=JSON[o(1525)](e[o(1435)](c,"{}"));return f[n||t[this[o(1888)]]]=t,this[o(679)][o(1640)](this[o(1353)],JSON[o(438)+"y"](f)),n||t[this[o(1888)]]}async del(t){let n=r,o=this[n(679)][n(504)](this[n(1353)]),c=JSON[n(1525)](e[n(500)](o,"{}"));return c[t]=void 0,this[n(679)].setItem(this[n(1353)],JSON.stringify(c))}async[r(1799)](){return this[r(679)].clear()}async[r(1480)](){let t=r,n=this[t(679)].getItem(this[t(1353)]),o=JSON[t(1525)](e.jJoom(n,"{}"));return Object.keys(o)}async[r(489)](){let t=r,n=this._qosDB.getItem(this[t(1353)]),o=JSON[t(1525)](e[t(1801)](n,"{}"));return Object.values(o)}[r(1704)](){return Promise[r(1061)]()}get[r(1893)](){return!!this[r(679)]}}class ua{constructor(t,n){let o=r;this._DBName=t,this[o(1888)]=n,this[o(679)]=Ve?tt:vt?wx:null}async[r(1833)](){}get[r(1353)](){return"frontier_"+this[r(1622)]}async[r(1528)](t){let n=r,o={pyKGD:e[n(1441)],GshNn:e[n(640)],RygHK:e[n(1651)],rneQD:n(533)};if(e[n(816)]("qznDB",n(1688))){let c=this[n(679)][n(1505)+"geSync"](this._prefix);return JSON[n(1525)](e.yaLJU(c,"{}"))[t]}else{let c=o[n(575)].split("|"),f=0;for(;;){switch(c[f++]){case"0":this._ws[n(938)+n(1425)+n(733)](o[n(1814)],this._onMessage);continue;case"1":this[n(444)][n(938)+n(1425)+n(733)](o[n(1670)],this[n(1613)]);continue;case"2":this[n(444)]["removeEv"+n(1425)+n(733)](n(1875),this[n(954)]);continue;case"3":this[n(444)][n(938)+n(1425)+n(733)](o.rneQD,this[n(1352)]);continue;case"4":if(!this[n(444)])return;continue}break}}}async[r(510)](t,n){let o=r,c=this[o(679)]["getStora"+o(1417)](this[o(1353)]),f=JSON[o(1525)](e[o(500)](c,"{}"));return f[n||t[this._pathKey]]=t,this[o(679)][o(1288)+o(1417)](this[o(1353)],JSON[o(438)+"y"](f)),n||t[this._pathKey]}async del(t){let n=r,o=this[n(679)][n(1505)+n(1417)](this._prefix),c=JSON.parse(e[n(1091)](o,"{}"));return c[t]=void 0,this._qosDB[n(1288)+"geSync"](this[n(1353)],JSON[n(438)+"y"](c))}async[r(1799)](){let t=r;if(e.FpYXY(e[t(494)],e[t(494)]))_0x51df41[t(1617)+t(1639)]=void 0,e[t(1524)](_0x48b90a,t(1518)+t(1517));else return this[t(679)][t(1484)+"rageSync"]()}async[r(1480)](){let t=r,n=this[t(679)][t(1505)+t(848)+"nc"](this._prefix),o=JSON[t(1525)](e[t(855)](n,"{}"));return Object[t(1480)](o)}async getAll(){let t=r,n=this[t(679)][t(1505)+t(848)+"nc"](this[t(1353)]),o=JSON[t(1525)](e.MgTPf(n,"{}"));return Object[t(1035)](o)}[r(1704)](){let t=r,n={MGrqL:function(o){return o()}};if(e[t(1850)](e[t(1259)],e[t(929)]))return Promise.resolve();{let o=this[t(1741)+t(1676)]?.[t(1372)+t(1210)+"nt"]();this[t(1424)](t(517)+o),n[t(1187)](_0x58dc78)}}get[r(1893)](){return!!this[r(679)]}}function gs(s,t){let n=r;if(Ve||Ve)return new ua(s,t);if(e[n(1415)](st,St)&&e[n(1846)](e[n(537)],typeof indexedDB))return new ca(s,t);if((st||St)&&n(399)+"d"!=typeof localStorage)return new xa(s,t);throw new Error(e[n(1513)])}class fa{constructor(){let t=r;if(e[t(712)](e[t(815)],t(1467))){let n=new _0x5f47d5(e[t(1264)](2,_0x52e70a));n[t(510)](_0x585fad),_0xee6fb6[t(1464)]=n}else this["_interva"+t(1713)+"Id"]=null,this[t(1246)+"l"]=36e5,this[t(679)]=e.JHYGo(gs,e[t(724)],e.nPzWu)}async _intervalFlush(){let t=r,n={MqMWo:t(1399),fjTuF:function(o,c){return e[t(712)](o,c)},ivxyK:t(1147),MJahr:"jOWzd"};e[t(1275)](e[t(687)],t(899))?(this.emit(n[t(1159)],_0x5db4c8),this[t(823)+"e"]&&this.onmessage(_0x404c6b)):(e[t(1074)](clearInterval,this[t(1246)+"lTimeoutId"]),this[t(1246)+t(1713)+"Id"]=e.mIjOF(setInterval,()=>{let o=t;n[o(414)](n[o(1303)],n.MJahr)?this[o(1637)+o(1740)]():(this[o(877)+o(1271)+"Event"](_0x552c5a),_0xc5e642[o(510)](_0x54c2d1,_0x46fe79,_0x5e32ed[o(1399)].service))},this[t(1246)+"l"]))}async[r(1833)](){let t=r,n={wtBHS:function(o,c,f){return e.mvQxF(o,c,f)}};await this[t(679)].openDB()[t(568)](()=>{let o=t;if(e[o(563)]==="CZhUt")return _0x296622[o(1464)][DrTBrw.wtBHS(_0x1e9218,_0x1109c5,1)];this[o(1246)+o(1809)]()})}async[r(1637)+r(1740)](){let t=r,n={UmghU:e[t(1426)]};(await this[t(679)]?.getAll()||[])[t(1502)](({timestamp:f})=>f<Date[t(1447)]())[t(1170)](f=>{let g=t;if(n[g(1696)]!==n[g(1696)])return new _0x311155(_0x320b06,{message:_0x1f5b8e});this[g(679)]?.[g(586)](f.message_id)})}async[r(586)](t){return this[r(679)]?.del(t)}async set(t,n){return this[r(679)]?.set({message_id:t,timestamp:n})}async[r(1528)](t){let n=r;return this[n(679)]?.[n(1528)](t)}async[r(1704)](){let t=r;e.ZTSBr(clearInterval,this["_interva"+t(1713)+"Id"]),await this._qosDB?.[t(1704)]()}get isReady(){let t=r;return this[t(679)]?.[t(1893)]}}function tr(s){let t=r,n=!!this[t(1871)][t(1120)+"S"];if(!n)return{enabled:n,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=qe(s[t(1399)].headers,e[t(870)],"2"),c=o&&e[t(1101)](qe,s[t(1399)][t(934)],e[t(634)],"1"),f=o&&e[t(1101)](qe,s[t(1399)].headers,e.jRnqY,"1"),g=f?it(s[t(1399)].headers,e.HbOOs)?.[t(862)](",").filter(Boolean)||[]:[];return{enabled:n,isQoSMessage:o,isQoSAck:c,isAckCleanupMessage:f,ackMsgIds:g}}async function ps(){let s=r;return this._QoSManager||(this[s(1612)+s(1593)]=new fa),this[s(1612)+s(1593)][s(1893)]||await this[s(1612)+"ger"][s(1833)](),this["_QoSMana"+s(1593)]}async function da(s,t){let n=r,{enableAutoAck:o}=this._options,c=e[n(1101)](qe,s[n(1399)][n(934)],n(662),"1"),f=e[n(404)](qe,s[n(1399)][n(934)],e[n(1325)],"1"),g=tr[n(1236)](this,s);if(e[n(1643)](o,c)){let{SeqID:p,LogID:l,service:y,LogIDNew:k,method:v}=s.message;this._sendAck({SeqID:p,LogID:l,LogIDNew:k,service:y,method:v,headers:[{key:e[n(1325)],value:"1"},{key:e[n(1359)],value:k||""},{key:e.emwGa,value:"0"}]})}f&&!g[n(1762)]&&this[n(877)+n(711)+n(1599)](s),e.HYoBA(t)}async function la(s,t){let n=r;this[n(1424)]("received",s[n(1399)]),e.ftUfv(t)}async function ha(s,t){let n=r,o={kXwEq:function(f,g,p){return e[P(601)](f,g,p)},jpvQJ:e[n(1651)]},c=e[n(1718)](Qr,await hs(s[n(1779)]));try{if(e[n(511)](c[n(1485)],Uint8Array))if(e[n(1218)](e.jxwqa,e[n(581)])){let f=e[n(1771)](this[n(1871)]["payloadE"+n(1183)],Object)?{force:!!this[n(1871)][n(694)+n(1183)].force,encoding:this._options.payloadEncoding[n(1803)]?this[n(1871)][n(694)+"ncoding"][n(1803)].replace(/\s/g,"")[n(672)+"ase"]():""}:{force:!1,encoding:this._options[n(694)+n(1183)]?this[n(1871)][n(694)+n(1183)][n(1493)](/\s/g,"")[n(672)+"ase"]():""},g=c["payloadE"+n(1183)]?c[n(694)+n(1183)].replace(/\s/g,"")[n(672)+n(1042)]():"",p=e.Xzcri(this[n(1871)][n(1685)+n(1114)],Object)?{force:!!this._options[n(1685)+n(1114)].force,type:this[n(1871)][n(1685)+n(1114)][n(1433)]?this[n(1871)][n(1685)+n(1114)][n(1433)][n(1493)](/\s/g,"")[n(672)+n(1042)]():""}:{force:!1,type:this[n(1871)][n(1685)+n(1114)]?this[n(1871)][n(1685)+n(1114)][n(1493)](/\s/g,"").toLowerCase():""},l=c[n(1685)+n(1114)]?c[n(1685)+n(1114)][n(1493)](/\s/g,"")[n(672)+n(1042)]():"",y=p[n(569)]?p[n(1433)]:l||p.type,k=f[n(569)]?f[n(1803)]:g||f.encoding,v=[e[n(524)],e[n(742)],e[n(1214)],e[n(1414)]],A=[e[n(813)],e[n(1507)]];this._options[n(872)+n(1243)+"extPayload"]&&v.includes(y)&&(!k||A[n(1386)](k))?c[n(421)+n(671)]=e.IGjqQ(ls,c[n(1485)],0,c[n(1485)][n(986)+"th"]):c[n(421)+"oad"]=""}else{this[n(877)+"hCloseEv"+n(1222)](o[n(1207)](_0x2054bf,o.jpvQJ,{code:1e3,reason:"bye"})),this[n(1741)+n(1676)]?.[n(1828)+n(1582)+"fig"](),this._pingLossCounter?.[n(949)+"nter"]();return}else c["textPayl"+n(671)]=""}catch(f){c[n(421)+"oad"]="",console[n(1030)](f)}s[n(1399)]=c,t()}function ga(s,t,n){let o=r,c={eGLlO:function(f,g){return e[P(1619)](f,g)},ZekBq:function(f,g){return e.ZTSBr(f,g)},SfIWE:function(f,g){return f&g},KqHST:function(f,g){return e[P(730)](f,g)},JYDQC:function(f,g){return e.EOPUq(f,g)}};if(e[o(1824)]===e.SElGD)try{this[o(444)]&&this[o(444)].close(_0x4d9d04,_0x369e42)}catch{}else{let f=n||8192,g=e[o(1848)](f,1),p=null,l=f;return function(y){let k=o;if(y<1||y>g)return c[k(1173)](s,y);l+y>f&&(p=c[k(1624)](s,f),l=0);let v=t[k(1236)](p,l,l+=y);return c[k(1709)](7,l)&&(l=c.KqHST(c.JYDQC(7,l),1)),v}}}let pa=4294967295;function ma(s,t,n){let o=r;return e[o(897)](RangeError,e.GyJCA(e[o(1653)](e[o(413)](e.AlpjJ(o(585)+o(439)+o(1036),s),e[o(392)])+e[o(1091)](t,1),e[o(851)]),n))}function wa(s,t,n){let o=r;if(e[o(1568)](n,pa))throw new Error(o(1141)+o(658)+"e");let c=3;for(;c>=0;){let f=e[o(1734)](255,n);rr(f,s,e.yJVhE(t,c)),n>>>=8,c--}return t+4}function _a(s,t){let n=r;if(e[n(1562)](e.BkFTd,e[n(1479)])){let o=0,c=t,f=e.AGvJI(t,4);for(;c<f;){let{value:g,offset:p}=e[n(1197)](nr,s,c);c=p,o=e.DZGxx(e[n(1411)](o,8),0),o+=g}return{value:o,offset:f}}else return _0x40fc60||(_0x2819be=[_0x120ade,_0x5d4a21,_0x3862b7,_0x10f388,_0x2ada81])}function ya(s,t,n){let o=r,c=e[o(457)][o(862)]("|"),f=0;for(;;){switch(c[f++]){case"0":if(!s)return n;continue;case"1":return e[o(982)](Zn(s,t,n),n);case"2":if(t[o(1244)])return e.domhM(t[o(1244)](s,n),n);continue;case"3":if(t.utf8Write)return e[o(1830)](t[o(1805)+"e"](s,n),n);continue;case"4":if(e.MoGHH(s[o(1843)],40))return e[o(1018)](e[o(404)](Zn,s,t,n),n);continue}break}}function ba(s,t){let n=r,o=new O(e[n(969)](e[n(1462)](s[e[n(547)](t,4)],24)|s[t+5]<<16,e[n(1108)](s[t+6],8))|s[e[n(412)](t,7)],e[n(873)](e.LqIdV(e[n(423)](e.fqVCz(s[e[n(635)](t,0)],24),e.xoUPL(s[t+1],16)),e[n(794)](s[e[n(1162)](t,2)],8)),s[e[n(861)](t,3)]),!0);return t+=8,{value:o,offset:e[n(1431)](t,8)}}function va(s,t,n){let o=r,c=s[o(821)],f=s[o(1845)];return t[n]=e.RynrW(f,24),t[n+1]=e[o(1878)](f,16)&255,t[e[o(759)](n,2)]=e.SyTdW(f,8)&255,t[e[o(530)](n,3)]=e.qYYVI(255,f),t[e[o(1810)](n,4)]=e[o(915)](c,24),t[e[o(1807)](n,5)]=e.ELuwT(e[o(416)](c,16),255),t[e.lAVmG(n,6)]=e[o(473)](e[o(1321)](c,8),255),t[n+7]=e[o(1553)](255,c),n+=8,n}function nr(s,t){let n=r;if(e[n(1335)]!==n(1521))return s.readUInt8?{value:s.readUInt8(t),offset:e[n(971)](t,1)}:{value:255&s[t],offset:e.dbNHp(t,1)};_0x92fbfe[n(1030)](_0x22e644)}function rr(s,t,n){let o=r;return t[o(1171)+"t8"]?t.writeUint8(s,n):t[n]=e[o(1541)](255,s),e[o(1309)](n,1)}let Sa=function(s){return new Uint8Array(s)},Ea=e[r(1648)](r(399)+"d",typeof Buffer)?Buffer[r(1146)+r(830)]:ga(Sa,Uint8Array[r(1268)+"e"][r(1626)]);(()=>{let s=r,t={JZdpc:function(o,c){return e.LsWgr(o,c)},YQtAc:function(o,c){return e[P(1188)](o,c)},fNdgu:function(o,c){return e[P(1124)](o,c)},ijLUE:function(o,c){return o<<c},UCsyS:function(o,c){return e[P(1514)](o,c)},XWkYC:function(o,c){return o&c},jQOPs:function(o,c){return e[P(792)](o,c)},uwVOr:function(o,c){return o|c},UGmTH:function(o,c){return o<c},nJhtz:function(o,c){return e.OYrls(o,c)},TReoZ:function(o,c){return e.CZpya(o,c)},SwCGf:function(o,c){return e[P(1844)](o,c)},knQoN:function(o,c){return e[P(895)](o,c)},AkJOO:function(o,c){return e.puHMC(o,c)},HtYXy:s(430),KecrJ:function(o,c,f,g){return e[s(1326)](o,c,f,g)},wzAmY:function(o,c){return o|c}},n=4294967295;return function(o,c,f=!0){let g=s;if(n=t[g(1374)](t[g(562)](127,o[c]),0),o[c++]<128)return{value:f?n:t[g(402)](0,n),offset:c};if(n=(n|t[g(1827)](t.UCsyS(127,o[c]),7))>>>0,o[c++]<128)return{value:f?n:0|n,offset:c};if(n=(n|t[g(1827)](t[g(515)](127,o[c]),14))>>>0,t[g(956)](o[c++],128))return{value:f?n:0|n,offset:c};if(n=t[g(809)](n,t[g(1827)](t[g(562)](127,o[c]),21))>>>0,t.UGmTH(o[c++],128))return{value:f?n:t[g(1098)](0,n),offset:c};if(n=t[g(1412)](n|(15&o[c])<<28,0),t[g(1017)](o[c++],128))return{value:f?n:t[g(1681)](0,n),offset:c};if((c+=5)>o[g(1843)])if(t[g(1336)](t[g(1483)],t[g(1483)]))this[g(679)]?.[g(586)](_0x40e77c[g(1158)+"id"]);else throw c=o[g(1843)],t[g(1100)](ma,c,10,o[g(1843)]);return{value:f?n:t.wzAmY(0,n),offset:c}}})();let Ca=16,sr=32;function Aa(s){let t=r,n=0,o={};for(let c=0;c<s[t(1843)];c++)if(e[t(1102)](e[t(1798)],e[t(1692)])){let f=this[t(679)][t(1505)+t(1417)](this[t(1353)]);return _0x47daef[t(1525)](e.wXUWN(f,"{}"))[_0x1255ca]}else o[s[c][t(1437)+t(989)]]=e.cyyND(ds,s[c][t(1437)+t(989)]),n+=e.tAVjS(14,o[s[c][t(1437)+t(989)]]);return[n,o]}function ms(s,t,n){let o=r;if(e[o(1275)](e[o(1165)],e[o(1165)]))e[o(1449)](_0x2bafda,_0x1ae890,32),e[o(1394)](_0x4f8704,_0x4751e3,e[o(1826)](_0x3098cd,_0x455ae5));else{let[c,f]=e[o(1277)](Aa,s),g=Ea(c),p=0;return s[o(1170)](l=>{let y=o,k=e[y(1633)][y(862)]("|"),v=0;for(;;){switch(k[v++]){case"0":console[y(1030)](e[y(1216)],p);continue;case"1":console[y(1030)](e[y(998)],p);continue;case"2":p=rr(f[l[y(1437)+"ame"]],g,p);continue;case"3":console[y(1030)](e[y(1476)],l,l[y(1231)]);continue;case"4":console[y(1030)](y(777)+y(1546),p);continue;case"5":p=e[y(695)](va,O.fromNumber(l[y(1717)]||t),g,p);continue;case"6":p=e[y(1326)](ya,l[y(1437)+y(989)],g,p);continue;case"7":p=e[y(820)](wa,g,p,l[y(1231)]||0);continue;case"8":p=e[y(1101)](rr,0,g,p);continue;case"9":console[y(1030)](e.kvcDj,p);continue;case"10":console.log(y(1546),p);continue}break}}),{frameType:sr,headers:[{key:e[o(1153)],value:n}],payload:g}}}function ka(s){let t=r,n=0,o=[];for(;e.NvWik(n,s[t(986)+"th"]);)if(e.udtcl(e[t(1143)],t(696)))e[t(1106)](_0x578a15,e[t(1790)]),this[t(831)](t(1238)+"e_success",_0x9080aa),this[t(831)](e[t(1132)],_0x18d1b1);else{let{offset:c}=e[t(904)](nr,s,n);n=c;let f={cursor_name:"",cursor:0,service:0},{value:g,offset:p}=e.KuybI(_a,s,n);f[t(1231)]=g,n=p;let{value:l,offset:y}=e.CUubA(nr,s,n);n=y,f[t(1437)+"ame"]=e[t(404)](ls,s,n,e[t(1432)](n,l)),n+=l;let{value:k,offset:v}=e.iaJts(ba,s,n);f[t(1717)]=k[t(1312)](),n=v,o[t(483)](f)}return o}function Pa(){return{frameType:sr,headers:[{key:e.EyXNV,value:e.QYRLx}],payload:void 0}}class Ia{constructor(t,n,o){let c=r;this["_cursorN"+c(624)]=t,this["_cursorF"+c(826)]=n,this[c(1051)+c(785)]=o,this._qosDB=e[c(1394)](gs,this[c(1154)+c(624)],e.WMasM)}async[r(1833)](){let t=r;await this[t(679)][t(1833)]()}async[r(1313)+"rs"](){let t=r,n={FOgFp:function(o,c){return e[P(552)](o,c)},cdLpv:e[t(1790)],QFoIf:e[t(1132)],SRkKw:function(o,c){return o(c)},UiWAN:function(o,c,f){return o(c,f)},QmVqL:e[t(931)]};if(e.FpYXY(e[t(1842)],e[t(543)])){if(!this[t(679)][t(1893)])return;let o=this._messageStrategy,c=await this._qosDB.getAll();switch(console[t(1030)](e[t(636)],c),o){case e[t(974)]:return c&&c[t(1843)]?e.JHQyB(ms,c,0,this[t(1557)+t(826)]):void 0;case e[t(1088)]:return;case e[t(1084)]:return c&&c[t(1843)]?ms(c,0,this[t(1557)+t(826)]):Pa()}}else return new _0x4310d8((o,c)=>{let f=t,g={nQrwM:function(y,k){return n[P(1240)](y,k)},CzUDC:n[f(732)],bljTH:n[f(407)],gCpdX:function(y,k){return n.SRkKw(y,k)},QGeSk:f(1238)+f(1509)+"s"};this[f(1040)+f(1190)](),this[f(1867)+"gTimeoutId"]=n[f(970)](_0x451e04,this[f(1413)].bind(this),this[f(1871)][f(1671)+f(1178)]);let p=()=>{let y=f;g[y(1607)](o,g[y(1034)]),this.off("ping_onc"+y(1509)+"s",p),this[y(831)](g.bljTH,l)},l=()=>{let y=f;g[y(1794)](c,y(1398)),this[y(831)](g[y(1668)],p),this[y(831)](y(1238)+y(632)+"t",l)};this.on(n[f(1196)],p),this.on(n.QFoIf,l),this._ping()})}async[r(510)](t,n,o){let c=r;return console[c(1030)](e[c(1789)],t,n,o),this[c(679)][c(510)]({cursor_name:t,cursor:n,service:o})}async[r(1258)+"rs"](t){let n=r,o=e[n(1445)](ka,t);for(let c of o)console[n(1030)](e[n(1736)],o),await this[n(679)][n(510)](c)}async[r(1528)](t){let n=r;return(await this[n(679)][n(1528)](t))?.[n(1717)]}async[r(1704)](){let t=r;if(e[t(655)](e[t(704)],e[t(394)]))await this[t(679)][t(1704)]();else return!!(e.xRyJa(this[t(1062)+t(388)],this[t(1217)+"s"][t(1843)])||e[t(1377)](this[t(1062)+t(388)],e.OkhLy(this.endpoints.length,1))&&e[t(389)](this["currentEndpointT"+t(1338)+"t"],this[t(1770)+"es"]))}[r(1754)+r(710)+"Name"](t){this._cursorFileName=t}get[r(1893)](){let t=r;return this[t(679)][t(1893)]}}let Da=e.qjKKt;async function ws(s){let t=r,n={ytdQK:e[t(1877)]};if(e[t(900)](e[t(945)],e.UNgmt)){if(!this._options[t(1120)+"S"])return null;let{aID:o,fpID:c,messageStrategy:f}=this[t(1871)],g=e[t(578)](s,Da);try{if(this[t(921)+t(1837)]){if(e.NUEGi(e[t(1666)],e[t(765)]))return this._socket[t(871)+"ns"];s&&this[t(921)+t(1837)][t(1754)+t(710)+t(549)](s)}else this[t(921)+t(1837)]=new Ia(c+"_"+o+"_"+g,g,f);return this[t(921)+t(1837)][t(1893)]||await this[t(921)+t(1837)][t(1833)](),this[t(921)+t(1837)]}catch{return e[t(1562)](e[t(1073)],t(843))?null:_0xf1399e[t(1061)]()}}else{let o=_0x1292bd(n[t(1584)],{message:_0x4331ca[t(1399)],code:_0x1065d1[t(1123)+t(1768)],error:_0x1d9a5a});this[t(877)+t(925)+t(1222)](o)}}async function Ta(s,t){let n=r,o={Yzytt:e[n(739)],crkmg:function(g,p){return g!==p}};if(e[n(924)](e[n(1571)],e[n(1242)])){let g=o[n(762)][n(862)]("|"),p=0;for(;;){switch(g[p++]){case"0":if(NDwjXa.crkmg(void 0,c))return c.exports;continue;case"1":var c=_0x1ec981[_0x1c5947];continue;case"2":return f[n(1887)];case"3":_0x558ccd[_0x547061](f,f[n(1887)],_0x721850);continue;case"4":var f=_0x515c0d[_0x1e4401]={exports:{}};continue}break}}else{let g=e.nCdBf(qe,s[n(1399)][n(934)],e[n(1745)],"-1"),p=e[n(1286)](qe,s[n(1399)][n(934)],n(1863),"1"),l=e[n(456)](it,s[n(1399)][n(934)],e[n(1003)]),y=Number(e[n(514)](it,s[n(1399)].headers,e[n(1384)]))||0,k=tr[n(1236)](this,s),v=qe(s[n(1399)][n(934)],e[n(1229)],"2"),A=it(s[n(1399)][n(934)],n(1257)+n(403)+"e"),T=Number(e[n(1455)](it,s.message[n(934)],e[n(853)]));if(k.isQoSAck)return t();let G=k[n(590)+n(1127)]?await ps.call(this):null;if(e[n(1729)](s[n(1399)][n(1231)],0)&&p&&!g||s.message[n(1231)]>0){if(l&&k["isQoSMes"+n(1127)]&&G)return!!!await G[n(1528)](l)&&(this[n(877)+n(1271)+"Event"](s),await G.set(l,Date[n(1447)]()+y)),e[n(1249)](t);if(v){let M=await ws[n(1236)](this);if(!M)return this[n(877)+"hMessage"+n(883)](s),e[n(1249)](t);let X=await M[n(1528)](A)??-1;if(e[n(1844)](X,T))this[n(877)+n(1271)+"Event"](s),M[n(510)](A,T,s.message[n(1231)]);else throw new Error(n(1076)+n(1276)+n(1241)+T+(" larger "+n(714)+n(1898)+"r ")+X);return e[n(988)](t)}return this[n(877)+n(1271)+n(883)](s),t()}}}async function La(s,t){let n=r,o=tr[n(1236)](this,s);if(!o[n(590)+n(1127)])return e[n(1793)](t);let c=await ps[n(1236)](this);if(o[n(886)+n(559)+n(1066)]&&o.ackMsgIds[n(1843)])for(let f of o[n(1853)+"s"])await c[n(586)](f);e.mDsYa(t)}async function Ra(s,t){let n=r;if(e[n(758)](e[n(608)],e[n(1895)]))this[n(1308)+"er"]&&_0x50ca96[n(1149)+n(1538)](n(639),this["_handleO"+n(1714)]),this[n(1308)+"er"]&&_0x26a9b0[n(1149)+"Listener"](e[n(1597)],this._handleOffLine),this[n(1308)+"er"]&&_0x2df1b9[n(1149)+n(1538)](n(1054),this[n(491)+"ageHide"]),this[n(1308)+"er"]&&_0x3ae05f[n(1149)+n(1538)](e[n(766)],this[n(491)+n(393)]);else{let o=e[n(1235)](s[n(1399)].frameType,Ca),c=e[n(1531)](s.message.frameType,sr);if(e[n(1643)](!o,!c))return t();let f=e.SXiTD(it,s[n(1399)].headers,e[n(1153)]);if(!f)return e[n(519)](t);let g=await ws.call(this,f);if(!g)return e[n(705)](t);if(o){let p=await g[n(1313)+"rs"](),l={frameType:p?.[n(482)+"e"],SeqID:O.fromNumber(this[n(1490)]++),LogID:O[n(652)+"er"](this[n(1871)][n(427)+"erator"]()),service:9e3,method:5,headers:p?.[n(934)],payload:p?.[n(1485)]},y=C(l);this[n(444)]&&this._ws[n(1396)+"te"]&&this[n(444)][n(1611)](y)}if(c){let p=s[n(1399)].payload;p&&g[n(1258)+"rs"](p)}}}let Na=async function(s,t){let n=r;this._isInit=!1,clearTimeout(this[n(1254)+"ionTimeo"+n(864)]),e[n(923)](t)},Oa=async function(s,t){let n=r;if(!this[n(444)]||e[n(816)](this[n(444)][n(1396)+"te"],this[n(1554)]))return e[n(988)](t);let{pingInterval:o}=this[n(1871)];this[n(1741)+"tManager"]?.[n(1828)+n(1582)+n(1759)]();for(let f=0;e.AVFzs(f,this[n(1051)+"Queue"].length);f++){let g=this[n(1051)+n(1077)][f];if(e[n(703)](this[n(444)][n(1396)+"te"],this[n(1554)])&&e[n(816)](null,g))this[n(444)]&&this[n(444)][n(1611)](g),this[n(1051)+n(1077)][f]=null;else break}this[n(1051)+n(1077)]=this[n(1051)+n(1077)][n(1502)](f=>!!f),this[n(1867)+n(386)+"Id"]=e[n(1328)](setTimeout,()=>this[n(1413)](),o),this["_dispatc"+n(1458)+"nt"](s),this._isBrowser&&this[n(444)]&&(this[n(444)][n(1590)+"pe"]=this._binaryType);let c=this[n(1741)+"tManager"]?.[n(1372)+n(1210)+"nt"]();this[n(1424)]("open "+c+n(571)),t()},Ba=async function(s,t){let n=r,o=this[n(1741)+n(1676)]?.[n(1372)+n(1210)+"nt"]();this[n(1424)](n(517)+o),e.RfVdk(t)};class Ma extends Xn{constructor(t){let n=r,o={DVVeI:function(p,l){return p<l},WGqga:function(p,l){return e[P(1880)](p,l)},Xdjzn:function(p,l){return e[P(1195)](p,l)},CeUvm:function(p,l){return e.Hqhgm(p,l)},NaImU:function(p,l){return e[P(1450)](p,l)},RDElJ:function(p,l){return e[P(890)](p,l)},uAgAb:n(1119),jeLay:e[n(1651)],VjAfB:n(406),jkZnr:function(p,l){return p===l},gEfie:n(1453),qmYrx:e[n(1591)],WIeih:function(p,l){return e[n(798)](p,l)},xkixH:function(p,l,y){return e.RLmpN(p,l,y)},IQzvF:function(p,l,y){return e[n(1532)](p,l,y)}};super(),this["_miniNav"+n(1383)+"line"]=!0,this._isBrowser=st,this._isNode=Zo,this[n(802)+"T"]=Ve,this[n(673)+"X"]=vt,this[n(1380)+"r"]=St,this[n(1051)+n(1077)]=[],this[n(1741)+n(1676)]=null,this["_readyCl"+n(1133)]=!1,this[n(874)+n(1114)]=e[n(1655)],this[n(1254)+"Lock"]=!1,this[n(1254)+n(603)+n(864)]=null,this._reconnectTimeoutId=null,this[n(1867)+n(386)+"Id"]=null,this[n(1490)]=0,this._isInit=!1,this[n(1348)]="",this[n(1612)+n(1593)]=null,this[n(921)+n(1837)]=null,this[n(939)+"sCounter"]=null,this[n(1540)+"ls"]=n(411),this[n(946)]=3,this.CONNECTING=0,this[n(1554)]=1,this[n(1831)]=2,this[n(954)]=p=>{let l=n;try{e[l(1400)](fs,this,p,[Na,Oa,Ba])}catch(y){let k=e[l(529)](ue,e[l(1877)],{message:y[l(1399)],code:Fe[l(1137)+"OR"],error:y});this[l(877)+l(925)+l(1222)](k)}},this[n(1103)+"ge"]=async p=>{let l=n,{pingInterval:y,pingFrequency:k}=this._options;if((e[l(984)]("hi",p[l(1779)])&&e[l(1317)]===k||e[l(758)](l(1712),k))&&(this[l(1040)+l(1190)](),this[l(806)](e.qbBdr,e.JVUZW),this["_pingPon"+l(386)+"Id"]=setTimeout(this[l(1413)][l(953)](this),y)),p[l(1779)]!=="hi")try{e[l(1101)](fs,this,p,[ha,da,La,Ra,Ta,la])}catch(v){let A=ue(e.uRZCb,{message:v[l(1399)],code:Fe[l(1123)+"ERROR"],error:v});this["_dispatc"+l(925)+"ent"](A)}},this[n(1352)]=p=>{let l=n,y=this[l(1741)+"tManager"]?.[l(1350)+l(749)+"es"](),k=this[l(1741)+l(1676)]?.["getCurre"+l(1210)+"nt"]();if(y&&!p.message){let v=l(995)+k+(l(784)+l(1056)+l(677)+"ed");this["_dispatc"+l(925)+l(1222)](ue(e.uRZCb,{message:v,code:Fe[l(395)+l(1213)+"R"],error:p}));return}this._ws&&e.tVaAR(this[l(444)][l(1396)+"te"],this[l(1554)])&&this[l(448)+l(1297)](),this[l(877)+l(925)+l(1222)](e[l(775)](ue,e[l(1877)],{message:p[l(1399)],code:Fe[l(1620)+l(1013)],error:p}))},this._onClose=async p=>{let l=n,y={qvHll:function(v,A){return o.DVVeI(v,A)},pKbeH:function(v,A){return o[P(1840)](v,A)},FzEkS:function(v,A){return v&A},oVaLH:function(v,A){return o[P(718)](v,A)},tcSYo:function(v,A){return o[P(1840)](v,A)},NroXc:function(v,A){return v&A},xZQaF:function(v,A){return v>>A},YibXQ:function(v,A){return o[P(1840)](v,A)},ahAte:function(v,A){return o[P(975)](v,A)},vtvtD:function(v,A){return o[P(1001)](v,A)},rJIqW:function(v,A,T){return v(A,T)},NbOVR:function(v,A){return v|A},eIcgz:function(v,A){return o[P(1001)](v,A)}};this["_clearTi"+l(1344)](),this[l(1040)+l(1190)](),this[l(1838)+l(1470)+"rs"](),this._ws=null,this[l(1254)+l(688)]=!1;let k=this[l(1741)+l(1676)]?.[l(1350)+"chMaxTries"]();if(!k&&this["_navigat"+l(958)]()&&!this["_readyCl"+l(1133)])if(o[l(502)](o[l(968)],o[l(968)]))FafJKr[l(546)](_0x5ba17f,2048)?_0x17cb9c[_0x13b0f2++]=FafJKr[l(1693)](FafJKr[l(1902)](FafJKr.oVaLH(_0x51e8c4,6),31),192):(FafJKr[l(546)](_0x570ac5,65536)?_0x109f4b[_0x1f4edd++]=FafJKr[l(1885)](FafJKr[l(950)](FafJKr[l(863)](_0x5e272c,12),15),224):(_0x39507f[_0x205bf6++]=FafJKr[l(1578)](FafJKr[l(950)](_0x22e877>>18,7),240),_0x561ab9[_0x110cd2++]=FafJKr[l(950)](_0x51b550>>12,63)|128),_0x3412de[_0x1b25fa++]=FafJKr[l(1578)](FafJKr[l(1404)](_0x4cc913,6)&63,128)),_0x571416[_0x1ca6dd++]=FafJKr[l(1693)](FafJKr[l(1341)](63,_0x2614a0),128);else{let v=this["_endpoin"+l(1676)]?.["getCurre"+l(1210)+"nt"](),A=this._options["reconnec"+l(1872)+l(1585)](p[l(1726)],p[l(1517)]);this["_dispatc"+l(1523)+l(1222)](pe(o[l(617)],{code:1006,reason:p.reason||l(1220)+l(1721)+l(428)+l(1105)+l(1511)+l(1364)+v,willReconnect:A})),A&&this[l(1254)]();return}if(o[l(502)](1e3,p[l(1726)])&&this[l(398)+l(1133)]){this[l(877)+l(1523)+l(1222)](pe(l(1314),{code:1e3,reason:o[l(835)]})),this["_endpoin"+l(1676)]?.[l(1828)+l(1582)+"fig"](),this[l(939)+"sCounter"]?.[l(949)+"nter"]();return}if(p[l(1726)]!==1e3&&k)if(o[l(1773)](o[l(1742)],o[l(1300)]))FafJKr[l(1700)](_0x34d565,_0x514d10,FafJKr[l(1792)](FafJKr[l(1284)](127,_0x3dfb71),128)),_0xa3bccc>>>=7;else{let v=this[l(1741)+l(1676)]?.[l(1372)+l(1210)+"nt"](),A=p.reason;A||(A=await o[l(1695)](oa,this._url)),A=l(1220)+"ng faile"+l(1080)+A+(", hostna"+l(892))+v+(l(1737)+l(1049)+l(1545)),this["_dispatchCloseEv"+l(1222)](pe(o[l(617)],{code:p[l(1726)],reason:A}));let T="connect "+v+(l(784)+"ax retri"+l(677)+"ed");this[l(877)+l(925)+"ent"](o[l(1329)](ue,"error",{message:T,code:Fe["MAX_RETR"+l(1213)+"R"]})),this[l(1741)+l(1676)]?.["resetEndpointCon"+l(1759)](),this[l(939)+l(1409)]?.[l(949)+"nter"]();return}if(p[l(1726)]!==1e3&&!p.reason){let v=this[l(1741)+l(1676)]?.[l(1372)+"ntEndpoint"]();this[l(877)+l(1523)+"ent"](o[l(841)](pe,o[l(617)],{code:p[l(1726)],reason:l(1220)+l(1721)+l(428)+l(1105)+l(1511)+"ame: "+v})),this[l(1741)+l(1676)]?.[l(1828)+l(1582)+l(1759)](),this[l(939)+"sCounter"]?.[l(949)+l(917)]();return}this["_dispatc"+l(1523)+l(1222)](p),this[l(1741)+l(1676)]?.[l(1828)+l(1582)+l(1759)](),this[l(939)+"sCounter"]?.["resetCou"+l(917)]()},this[n(1722)]=null,this[n(463)]=null,this.onmessage=null,this[n(1725)]=null,this["onStartR"+n(857)]=null,this["onReceiv"+n(1369)]=null,this["onStopIm"+n(1900)+n(987)+"ct"]=null,this[n(396)+n(1714)]=this._handleOnLine[n(953)](this),this["_handleO"+n(1478)]=this[n(396)+n(1478)][n(953)](this),this["_handleP"+n(507)]=this[n(491)+"ageHide"][n(953)](this),this[n(491)+"ageShow"]=this[n(491)+"ageShow"][n(953)](this),this[n(1871)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[n(907)](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.QKoLZ,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e.vYpLc,env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:c,ws:f}=t,g=Array[n(659)](c)?c:e[n(1780)](e[n(1414)],typeof c)?[c]:[];if(!g||g.length===0)throw new Error(n(1549)+"rovide v"+n(1487));if(!e[n(1277)](na,f))throw new Error(e.ShQCX);Object[n(1738)](this[n(1871)],t),this["_endpoin"+n(1676)]=new us(g,this._options[n(1770)+"es"]),this[n(939)+"sCounter"]=new ia(this[n(1871)][n(588)+n(645)]),this[n(1871)][n(1224)+"cOpen"]&&(this[n(908)]=!0,this[n(1254)]()),this[n(1871)][n(771)+n(1576)+"nged"]&&(this._isMiniTT||this[n(673)+"X"]?this[n(1870)+n(990)+n(453)]():this._isBrowser&&this[n(1422)+"balEventListener"]())}[r(396)+r(1714)](){let t=r;this._options[t(1544)+t(1604)+t(1500)]||this[t(398)+"osed"]||this["_handleR"+t(857)]()}[r(396)+r(1478)](){let t=r;this[t(1346)+t(786)+"t"]();let n=Qn(e.yjWdV,{message:"stop imm"+t(1703)+t(1481)+"ct"});this[t(983)+t(1900)+t(987)+"ct"]&&this[t(983)+t(1900)+t(987)+"ct"](n)}[r(1422)+r(1774)+r(1538)](){let t=r;this[t(1308)+"er"]&&window[t(1149)+t(1538)](e.TiRHO,this[t(396)+t(1714)]),this[t(1308)+"er"]&&window[t(1149)+t(1538)](e[t(1597)],this["_handleO"+t(1478)]),this._isBrowser&&window[t(1149)+"Listener"](e[t(1020)],this[t(491)+"ageHide"]),this[t(1308)+"er"]&&window[t(1149)+t(1538)](e[t(766)],this[t(491)+"ageShow"])}[r(1043)+r(1774)+r(1538)](){let t=r,n={FROny:t(1851)};if(e.wVPRn(e[t(1519)],e.PUEmD))switch(_0xaebddf){case sQoQwC.FROny:case t(1690):return{[t(556)+_0x2a770b]:1,"x-tt-env":_0x2f6d95};default:return{}}else this[t(1308)+"er"]&&window[t(938)+"entListener"](e[t(487)],this[t(396)+"nLine"]),this[t(1308)+"er"]&&window[t(938)+t(1425)+t(733)](t(1356),this[t(396)+t(1478)]),this[t(1308)+"er"]&&window[t(938)+t(1425)+t(733)](e[t(1020)],this[t(491)+"ageHide"]),this[t(1308)+"er"]&&window[t(938)+t(1425)+t(733)](e[t(766)],this[t(491)+t(393)])}[r(491)+r(507)](t){let n=r;!t[n(1185)+"d"]&&(this[n(1308)+"er"]&&window["removeEv"+n(1425)+n(733)](e.fMYhO,this[n(491)+n(507)]),this._isBrowser&&window[n(938)+n(1425)+n(733)](n(616),this[n(491)+n(393)]),this.close()),this[n(1308)+"er"]&&window[n(938)+"entListe"+n(733)](e[n(487)],this[n(396)+n(1714)]),this[n(1308)+"er"]&&window[n(938)+n(1425)+n(733)](e[n(1597)],this[n(396)+"ffLine"])}["_handleP"+r(393)](t){let n=r;t[n(1185)+"d"]&&(this[n(1225)+n(958)]()&&(!this[n(444)]||e[n(1333)](this._ws[n(1396)+"te"],this[n(1554)])||e[n(1205)](this[n(444)].readyState,this[n(1786)+"NG"]))&&this[n(396)+"nLine"](),this._isBrowser&&window[n(1149)+n(1538)](e[n(487)],this["_handleO"+n(1714)]),this[n(1308)+"er"]&&window[n(1149)+"Listener"]("offline",this[n(396)+n(1478)]))}async[r(824)+r(1743)](t){let n=r,{fpID:o,deviceID:c,bddID:f,ttwID:g,accessKey:p,aID:l,customParams:y={},enableAutoAck:k,enableQoS:v,QoSLevel:A,env:T}=this._options,G,M,X;if(this[n(1308)+"er"]||this[n(673)+"X"]||this._isMiniTT)if(e[n(477)]===e[n(477)])G=location&&e[n(1113)](e[n(1131)],location[n(731)])?e[n(770)]:e[n(498)],M=t[n(1493)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),X=/^wss(.*:\/\/)/[n(1702)](t)?t:""+G+M;else return this._socket[n(748)];else G=e[n(770)],M=t[n(1493)](/(^http)((?:[s]*:\/\/))/,""),X=/(^ws)((?:[s]*:\/\/))/[n(1702)](M)?M:""+G+M;let _s=f?n(432):g?e.tnucL:e[n(1647)],ys=f||g||c;if(e[n(793)](!ys,!_s))throw new Error(e.NGFiD);let za=e.EGBrn(e[n(1836)],typeof y)?await e[n(1793)](y):y,Fa=T?e[n(1471)](sa,T[n(1389)],T[n(866)]):{},ir=Object[n(1738)]({device_platform:e.PXQmB,version_code:e.tcVxy,access_key:p,fpid:o,aid:l,[_s]:ys,xsack:k?1:0,xaack:k?1:0,xsqos:v?1:0,qos_level:v?A:void 0,qos_sdk_version:2,...Fa},za),qa=Object[n(1480)](ir)[n(1852)]((or,ar)=>ir[ar]!==void 0?""+or+(or?"&":"?")+ar+"="+ir[ar]:or,"");return X+n(1403)+qa}async[r(1254)](){let t=r;if(!(this[t(1254)+t(688)]||this[t(398)+t(1133)])){this[t(1254)+t(688)]=!0;try{let n=this[t(1741)+t(1676)]?.[t(1580)+t(424)+"ointReac"+t(1135)+"tries"](),{timeoutInterval:o}=this[t(1871)];if(n){let f=this["_endpoin"+t(1676)]?.[t(1372)+"ntEndpoint"](),g=this[t(1741)+t(1676)]?.[t(1788)+t(769)+"pointAnd"+t(1092)+t(1370)](),p=this[t(1741)+t(1676)]?.[t(1372)+"ntEndpoi"+t(909)+t(1142)]();if(g){let l=t(995)+f+(t(1679)+t(1737)+t(1049)+"ached, will use "+t(1482)+t(1181))+g+(t(1039)+"y"),y=ue(t(533),{message:l,code:Fe["MAX_RETR"+t(1213)+"R"]});this[t(1424)](l),this[t(877)+t(925)+t(1222)](y),this[t(1348)]=await this[t(824)+t(1743)](g),this[t(1424)](t(995)+g+" "+p+t(1496)),this[t(1838)+"sListeners"]()}else{let l=t(995)+f+(t(1679)+t(1737)+"tries re"+t(1545));this._debug(l),this[t(877)+t(925)+t(1222)](e[t(1461)](ue,e[t(1877)],{message:l,code:Fe[t(395)+t(1213)+"R"]}));return}}else{let f=this[t(1741)+t(1676)]?.["getCurre"+t(1210)+t(1200)+t(706)](),g=this[t(1741)+t(1676)]?.[t(1372)+"ntEndpoi"+t(909)+t(1142)]();this[t(1348)]=await this[t(824)+t(1743)](e.qPLCJ(f,"")),this._debug(t(995)+f+" "+g+t(1496)),this["_removeW"+t(1470)+"rs"]()}if(this[t(908)])this._isInit=!1;else{let f=e.lelbj(Qn,e[t(1674)],{message:e[t(561)]});this[t(602)+t(857)]&&this[t(602)+t(857)](f)}let c=this._endpointManager?.[t(1372)+t(1210)+t(909)+t(1142)]()||0;e[t(1429)](c,1)&&await this._wait(e[t(1672)](c,1)),this[t(1424)](t(1220)+t(592)+this._url+(t(818)+t(973))+this[t(1540)+"ls"]),this._ws=e[t(613)](ta,{url:this[t(1348)],protocols:[this[t(1540)+"ls"]],headers:this[t(1871)][t(1334)+t(1706)+"s"][t(1475)+"tpHeader"]},this._options.ws),(this[t(1308)+"er"]||this._isWorker)&&this[t(444)]&&(this[t(444)][t(1590)+"pe"]=this[t(874)+"ype"]),this["_addWsLi"+t(620)](),this[t(1254)+t(603)+t(864)]=e[t(1854)](setTimeout,this[t(1168)+"ut"].bind(this),o)}catch(n){throw this[t(1254)+t(688)]=!1,n}}}[r(1021)+r(1344)](){let t=r;e[t(1293)](clearTimeout,this[t(1254)+t(603)+"utId"]),this["_connect"+t(603)+t(864)]=null}[r(1040)+r(1190)](){let t=r;e[t(552)](clearTimeout,this._pingPongTimeoutId),e[t(1527)](clearTimeout,this[t(1387)+t(1621)+"tId"]),this[t(1867)+t(386)+"Id"]=null,this[t(1387)+"ctTimeou"+t(1683)]=null}[r(1424)](...t){let n=r;this._options.debug&&console.log[n(1203)](console,[e.oAhWv,...t])}_getIntervalValue(t){let n=r,{initReconnectInterval:o,maxReconnectInterval:c,reconnectIntervalGrowFactor:f}=this[n(1871)],g=e[n(1579)](o,Math[n(952)](f,e.LCvVA(t,1)));return e[n(709)](g,c)?c:g}[r(1413)](){let t=r;if(this[t(444)]&&e.twoSS(this[t(444)][t(1396)+"te"],this[t(1786)+"NG"])){this[t(1040)+t(1190)](),this[t(1867)+t(386)+"Id"]=e[t(657)](setTimeout,this[t(1413)][t(953)](this),this[t(1871)][t(1671)+t(1178)]);return}if(!this[t(444)]||e[t(699)](this[t(444)][t(1396)+"te"],this[t(1554)]))return void this[t(1510)+t(857)]();this[t(444)]&&this[t(444)][t(1611)]("hi"),this[t(1387)+t(1621)+t(1683)]=e[t(641)](setTimeout,this[t(1510)+t(857)+t(763)].bind(this),this[t(1871)][t(493)+"outInter"+t(1419)])}["_handleR"+r(857)+"Timeout"](){let t=r;this[t(939)+t(1409)]?.[t(495)](),this[t(806)](e[t(1132)],t(1398)),this._pingLossCounter?.[t(1350)+t(1215)+"nt"]()?this[t(1510)+"econnect"]():this._ping()}[r(1225)+r(958)](){let t=r;return this[t(802)+"T"]||this[t(673)+"X"]?this[t(1418)+t(1383)+t(647)]:(this[t(1308)+"er"]||this[t(1380)+"r"])&&this[t(1871)][t(771)+"tworkCha"+t(484)]?navigator[t(1550)]:!0}[r(1510)+"econnect"](){let t=r;!this["_navigat"+t(958)]()||this[t(398)+t(1133)]||(this[t(1741)+"tManager"]?.resetEndpointConfig(),this[t(939)+t(1409)]?.[t(949)+t(917)](),this[t(444)]?this[t(448)+t(1297)](1001,e[t(1874)],!0):this[t(1254)]())}[r(1870)+"etWorkCh"+r(453)](){let t=r,n={TdYGL:function(o,c){return e[P(578)](o,c)}};this._isMiniTT?tt[t(447)+t(955)+t(1555)](({isConnected:o})=>{let c=t;if(e.YgyaE(e[c(713)],e[c(713)]))this["_miniNav"+c(1383)+c(647)]=o,o?this[c(396)+c(1714)]():this[c(396)+"ffLine"]();else{let f=this[c(679)][c(504)](this[c(1353)]),g=_0x4de035[c(1525)](WHXqeu[c(1537)](f,"{}"));return g[_0x3c1e04]=void 0,this[c(679)].setItem(this[c(1353)],_0x3b9fc8[c(438)+"y"](g))}}):this._isMiniWX&&wx[t(447)+"kStatusC"+t(1555)](({isConnected:o})=>{let c=t;this[c(1418)+c(1383)+c(647)]=o,o?this["_handleO"+c(1714)]():this["_handleO"+c(1478)]()})}_wait(t){return new Promise(n=>{let o=P;setTimeout(n,this[o(606)+o(1008)+"e"](t))})}[r(448)+r(1297)](t=1e3,n="",o=!1){let c=r;this._ws&&this[c(1346)+"WebSocket"](t,n,o)}_onTimeout(){let t=r,n=this[t(1741)+t(1676)]?.[t(1372)+t(1210)+"nt"]();this[t(1424)](t(995)+n+t(1679)),this[t(448)+t(1297)](1001,e[t(1638)],!0)}[r(417)](t){let n=r,o=e[n(1074)]($n,t);this._ws&&e[n(1102)](this[n(444)].readyState,this.OPEN)&&(this[n(444)]&&this[n(444)].send(o),this[n(1424)](e[n(941)],t))}["_removeW"+r(1470)+"rs"](){let t=r;this[t(444)]&&(this._ws["removeEv"+t(1425)+"ner"](e[t(1631)],this._onOpen),this[t(444)][t(938)+t(1425)+t(733)](t(1314),this._onClose),this[t(444)][t(938)+t(1425)+t(733)](e[t(640)],this[t(1103)+"ge"]),this[t(444)][t(938)+t(1425)+t(733)]("error",this[t(1352)]))}[r(829)+r(620)](){let t=r;this._ws&&(this[t(444)][t(1149)+t(1538)](t(1875),this._onOpen),this[t(444)]["addEvent"+t(1538)](e[t(1651)],this[t(1613)]),this[t(444)].addEventListener(e[t(640)],this[t(1103)+"ge"]),this._ws[t(1149)+t(1538)](e[t(1877)],this[t(1352)]))}["_wsInsta"+r(779)](t=1e3,n=""){let o=r;try{this._ws&&this[o(444)].close(t,n)}catch{}}["_destroy"+r(786)+"t"](t=1e3,n="",o=!1){let c=r;if(this[c(1040)+c(1190)](),this[c(1021)+"mer"](),this[c(1838)+c(1470)+"rs"](),this[c(799)+c(779)](1e3,n),this[c(1254)+c(688)]=!1,o&&this[c(1225)+"orOnline"]()&&!this[c(398)+c(1133)])if(e.XJQQU(e.Fofiv,e[c(1283)])){if(this[c(1741)+c(1676)]?.[c(1350)+"chMaxTries"]()){let g=this[c(1741)+c(1676)]?.[c(1372)+c(1210)+"nt"]();this[c(877)+c(1523)+c(1222)](e[c(692)](pe,c(1314),{code:1006,reason:c(995)+g+(c(1679)+", max re"+c(1049)+c(1545)),wasClean:!0}))}else if(e.zpRKn(e.QCBLj,e[c(980)])){let g=this._options[c(1530)+c(1872)+"ptor"](t,n);this["_dispatc"+c(1523)+c(1222)](pe(e[c(1651)],{code:t,reason:n,wasClean:!0,willReconnect:g})),g&&this[c(1254)]()}else this["currentI"+c(388)]=0,this[c(1489)+c(654)+c(1338)+"t"]=0;return}else return _0x1abb14||(_0x1bf37c=[_0x41a6a9.prototype[c(1388)],_0x3a6627[c(1268)+"e"][c(1104)],_0xbc0b6c[c(1268)+"e"].continuePrimaryKey]);this[c(1225)+c(958)]()||this[c(398)+"osed"]?this[c(877)+c(1523)+c(1222)](e.JVJkD(pe,"close",{code:t,reason:c(406)})):this[c(877)+c(1523)+c(1222)](e[c(594)](pe,e[c(1651)],{code:1006,reason:e[c(1551)]})),this[c(444)]=null,this[c(1741)+c(1676)]?.[c(1828)+"pointCon"+c(1759)](),this[c(939)+c(1409)]?.[c(949)+c(917)]()}[r(877)+r(1458)+"nt"](t){let n=r;this[n(806)](e[n(1631)],t),this[n(1725)]&&this[n(1725)](t)}[r(877)+r(1271)+r(883)](t){let n=r;this.emit(e[n(640)],t),this[n(823)+"e"]&&this[n(823)+"e"](t)}[r(877)+r(711)+r(1599)](t){let n=r;this[n(806)](e.SJnwz,t),this[n(891)+n(1369)]&&this[n(891)+n(1369)](t)}[r(877)+r(925)+r(1222)](t){let n=r;this[n(806)](n(533),t),this[n(463)]&&this[n(463)](t)}[r(877)+r(1523)+r(1222)](t){let n=r;this.emit(n(1314),t),this[n(1722)]&&this.onclose(t)}get binaryType(){let t=r;return this._ws?this[t(444)][t(1590)+"pe"]:this["_binaryT"+t(1114)]}set[r(1590)+"pe"](t){let n=r;this[n(874)+n(1114)]=t,this._ws&&(this[n(444)][n(1590)+"pe"]=t)}get[r(795)+"nt"](){let t=r;return this[t(1741)+t(1676)]?.[t(1372)+"ntEndpoi"+t(909)+"ount"]()||0}get["buffered"+r(461)](){let t=r;return this[t(1051)+t(1077)].reduce((o,c)=>(o+=c&&c.byteLength||0,o),0)+(this[t(444)]?this[t(444)]["buffered"+t(461)]:0)}get[r(871)+"ns"](){let t=r;return this[t(444)]?this[t(444)][t(871)+"ns"]:""}get[r(731)](){let t=r;return this[t(444)]?this._ws[t(731)]:""}get[r(1396)+"te"](){let t=r;return this[t(444)]?this[t(444)][t(1396)+"te"]:this[t(1871)][t(1224)+t(1757)]?this[t(1786)+"NG"]:this[t(946)]}get[r(748)](){let t=r;return this[t(444)]?this[t(444)][t(748)]:this[t(1348)]}[r(1314)](t=1e3,n){let o=r,c=(o(1691)+o(776))[o(862)]("|"),f=0;for(;;){switch(c[f++]){case"0":this["_clearPi"+o(1190)]();continue;case"1":this[o(1043)+"balEvent"+o(1538)]();continue;case"2":this[o(1346)+o(786)+"t"](t,n);continue;case"3":if(!this[o(444)])return void this[o(1424)](o(545)+o(387)+"ce not i"+o(1839)+"ed");continue;case"4":if(e.DUfaG(this[o(444)][o(1396)+"te"],this[o(946)])||this[o(444)].readyState===this[o(1831)])return void this._debug(e.EuYOi);continue;case"5":this[o(1021)+o(1344)]();continue;case"6":this._QoSManager?.[o(1704)]();continue;case"7":this[o(398)+"osed"]=!0;continue}break}}async[r(1611)](t,n){let o=r,c={UzVFM:function(f,g){return e[P(1050)](f,g)},Frjbp:e[o(1767)],yIIsr:o(1665)+o(932),tFBKa:function(f,g){return e[o(1161)](f,g)},sxoSY:e[o(1097)],EMPYi:function(f,g,p){return e.rsyIF(f,g,p)},auJKo:function(f,g,p){return e[o(684)](f,g,p)}};if(e[o(1716)]===e[o(642)]){let f=_0x1dff97[o(596)+o(1420)](sgxtvQ.Frjbp);_0x1c49ea["frontier"+o(1639)]=g=>{let p=o;_0x3ade73[p(1457)][p(525)+p(884)](f),_0x469e98["frontier"+p(1639)]=void 0,sgxtvQ[p(666)](_0x1514e9,g&&g.msg||p(1518)+p(1517))},f[o(1433)]=sgxtvQ.yIIsr,f[o(842)]=sgxtvQ[o(633)](_0x2df7be.replace(/^ws/,sgxtvQ[o(920)]),o(1122)+o(1057)+"tierJSONP");try{_0x4386c9[o(1457)][o(1499)+o(884)](f)}catch{_0x6c27ee.body["removeCh"+o(884)](f)}}else{if(e.PjPcd(null,t))throw new Error(e[o(1410)]);e[o(548)]==typeof t&&(t=JSON[o(438)+"y"](t)),e[o(1846)](o(551),typeof t)&&!e[o(868)](t,ArrayBuffer)&&!(t[o(1548)]&&e[o(1602)](t.buffer,ArrayBuffer))&&(t=JSON.stringify(t));let f=await e[o(1826)](hs,t),g=ra(t),{method:p=0,service:l=this[o(1871)].service,logID:y=this[o(1871)][o(427)+o(1760)](),headers:k=this[o(1871)][o(934)],payloadEncoding:v=this._options["payloadE"+o(1183)],payloadType:A=this._options[o(1685)+o(1114)],logIDNew:T=this[o(1871)]["logIDNew"+o(1558)][o(480)+o(629)+o(643)+"ew"]?e.YXkPb(a,this[o(1871)]["logIDNew"+o(1558)][o(1816)]):""}=e[o(1801)](n,{});if(!l)throw new Error(e.xmVXT);let G={SeqID:O[o(652)+"er"](this[o(1490)]++),LogID:O[o(652)+"er"](y),service:l,method:p,headers:k,payloadEncoding:e[o(1856)](v,Object)?v[o(1803)]?v[o(1803)]:"":v,payloadType:e[o(419)](A,Object)?A[o(1433)]?A[o(1433)]:g:A||g,payload:f,LogIDNew:T},M=e[o(901)]($n,G);return this[o(444)]&&e[o(1408)](this._ws[o(1396)+"te"],this.OPEN)?(this[o(444)]&&this[o(444)][o(1611)](M),this[o(1424)](e[o(913)],G)):e[o(1698)](this[o(1051)+o(1077)][o(1843)],this._options[o(719)+o(814)+"ength"])?e[o(1167)]("rTnCp",e[o(723)])?(sgxtvQ[o(1606)](_0x3590d9,_0x3888d9,50),sgxtvQ[o(1879)](_0x5f01fa,_0x441fc2,_0x16ddbb)):(this[o(1051)+"Queue"].push(M),this[o(1424)](e[o(1761)],G)):(this[o(1051)+o(1077)][o(678)](),this[o(1051)+"Queue"][o(483)](M)),{seqID:this[o(1490)],logID:y,logIDNew:T}}}async[r(1530)+"t"](t){let n=r,{url:o}=e.nZAih(t,{}),c=Array[n(659)](o)?o:e[n(933)](e[n(1414)],typeof o)?[o]:[];t&&Object.assign(this[n(1871)],t),c&&c[n(1843)]?this[n(1741)+"tManager"]=new us(c,this[n(1871)][n(1770)+"es"]):this._endpointManager?.[n(1828)+n(1582)+n(1759)](),this["_pingLos"+n(1409)]?.["resetCou"+n(917)](this[n(1871)][n(588)+n(645)]),this[n(398)+n(1133)]=!1,this[n(444)]&&e[n(919)](this[n(444)][n(1396)+"te"],this[n(946)])?this[n(448)+n(1297)](1e3,e[n(1063)],!0):(this._isInit=!0,this._connect())}async connect(){let t=r;if(!this[t(1254)+t(688)]){let n=e.PyANF.split("|"),o=0;for(;;){switch(n[o++]){case"0":this[t(1741)+t(1676)]?.[t(1828)+t(1582)+t(1759)]();continue;case"1":this[t(908)]=!0;continue;case"2":this[t(939)+"sCounter"]?.[t(949)+t(917)]();continue;case"3":this["_readyCl"+t(1133)]=!1;continue;case"4":this[t(1254)]();continue}break}}}[r(1149)+"Listener"](t,n){this.on(t,n)}[r(1267)+r(883)](t){let n=r;if(e[n(1221)]("RALAP",e[n(663)])){let{type:o}=t;this.emit(o,t)}else{let o=_0x4e8423[n(1858)]();return o?(o[n(646)]=o.limit=0,o):{bytes:new _0x4f0c60(64),offset:0,limit:0}}}["removeEv"+r(1425)+r(733)](t,n){this[r(831)](t,n)}[r(1128)](){let t=r,n={GFDFj:e[t(537)],XpGpw:function(o,c){return o!=c},Imqlg:function(o,c){return e.QrUOq(o,c)},Bdjvo:e[t(1038)],mrQMZ:e[t(1790)],BlfEq:t(1238)+t(1509)+"s"};return new Promise((o,c)=>{let f=t,g={ylITT:function(y,k){return y(k)},WYgyh:e[f(1320)],jyVUB:f(1238)+f(1509)+"s",GNcor:f(1238)+"e_timeout"};this[f(1040)+f(1190)](),this[f(1867)+f(386)+"Id"]=e[f(1686)](setTimeout,this[f(1413)][f(953)](this),this[f(1871)].pingInterval);let p=()=>{let y=f,k={wyDnH:function(v,A){return v||A},vkFhJ:function(v,A){return v!=A},sggVP:n[y(1515)],LJUBr:function(v,A){return n[y(1340)](v,A)}};if(n[y(576)](y(1378),n[y(1299)])){if(tIkiUj[y(1351)](_0x2b84b1,_0x178b10))return new _0x404d2f(_0x5093a4,_0x444729);if(tIkiUj.wyDnH(_0x2dee9e,_0x3398f4)&&tIkiUj[y(649)](tIkiUj[y(665)],typeof _0x27eba3))return new _0x82f157(_0x1ff8ad,_0x253d97);if(tIkiUj[y(1351)](_0x8489fe,_0x456be6)&&tIkiUj[y(1371)](tIkiUj.sggVP,typeof _0x15c573))return new _0x195939(_0x3bf7d8,_0x3edac4);throw new _0x43a4e5(y(996)+y(1319)+"d")}else o(n[y(1347)]),this[y(831)](n[y(1121)],p),this.off(y(1238)+"e_timeout",l)},l=()=>{let y=f;g[y(1614)](c,g[y(1673)]),this[y(831)](g[y(574)],p),this[y(831)](g[y(918)],l)};this.on(e[f(931)],p),this.on(f(1238)+f(632)+"t",l),this._ping()})}}})(),Q[S(880)+S(627)]=$[S(880)+"oseEvent"],Q[S(505)+S(1287)]=$[S(505)+"rorEvent"],Q[S(1059)+"e"]=$[S(1059)+"e"],Q[S(883)]=$.Event,Q.FWS=$[S(410)],Q[S(1782)+S(1028)+"vent"]=$[S(1782)+S(1028)+"vent"],Q[S(1028)+S(1522)]=$["MessageE"+S(1522)],Q.OpenEvent=$.OpenEvent,Q[S(797)+"tEvent"]=$[S(797)+S(536)],Q[S(1882)+"oseEvent"]=$[S(1882)+S(627)],Q[S(1732)+S(1287)]=$["createEr"+S(1287)],Q[S(610)+"ssageEvent"]=$[S(610)+S(1503)+"nt"],Q[S(1179)+S(746)]=$[S(1179)+S(746)],Q[S(1891)+"connectE"+S(1522)]=$[S(1891)+S(1109)+S(1522)],Q[S(1186)+S(1896)]=$[S(1186)+"rame"],Q[S(1269)+S(989)]=$[S(1269)+S(989)];for(mn in $)[S(880)+S(627),S(505)+S(1287),"ErrorCode",S(883),S(410),"Frontier"+S(1028)+S(1522),"MessageE"+S(1522),S(618)+"t",S(797)+S(536),S(1882)+S(627),"createErrorEvent",S(610)+S(1503)+"nt",S(1179)+S(746),S(1891)+"connectE"+S(1522),S(1186)+S(1896),S(1269)+"ame"][S(397)](mn)===-1&&(Q[mn]=$[mn]);var mn;Object.defineProperty(Q,S(1795)+"le",{value:!0})});var Ne=se((bl,li)=>{"use strict";var fi=["nodebuffer","arraybuffer","fragments"],di=typeof Blob<"u";di&&fi.push("blob");li.exports={BINARY_TYPES:fi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:di,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Lt=se((vl,En)=>{"use strict";var{EMPTY_BUFFER:Tc}=Ne(),mr=Buffer[Symbol.species];function Lc(r,e){if(r.length===0)return Tc;if(r.length===1)return r[0];let i=Buffer.allocUnsafe(e),a=0;for(let x=0;x<r.length;x++){let u=r[x];i.set(u,a),a+=u.length}return a<e?new mr(i.buffer,i.byteOffset,a):i}function hi(r,e,i,a,x){for(let u=0;u<x;u++)i[a+u]=r[u]^e[u&3]}function gi(r,e){for(let i=0;i<r.length;i++)r[i]^=e[i&3]}function Rc(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function wr(r){if(wr.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new mr(r):ArrayBuffer.isView(r)?e=new mr(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),wr.readOnly=!1),e}En.exports={concat:Lc,mask:hi,toArrayBuffer:Rc,toBuffer:wr,unmask:gi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=Y("bufferutil");En.exports.mask=function(e,i,a,x,u){u<48?hi(e,i,a,x,u):r.mask(e,i,a,x,u)},En.exports.unmask=function(e,i){e.length<32?gi(e,i):r.unmask(e,i)}}catch{}});var wi=se((Sl,mi)=>{"use strict";var pi=Symbol("kDone"),_r=Symbol("kRun"),yr=class{constructor(e){this[pi]=()=>{this.pending--,this[_r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[_r]()}[_r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[pi])}}};mi.exports=yr});var lt=se((El,vi)=>{"use strict";var Rt=Y("zlib"),_i=Lt(),Nc=wi(),{kStatusCode:yi}=Ne(),Oc=Buffer[Symbol.species],Bc=Buffer.from([0,0,255,255]),An=Symbol("permessage-deflate"),Oe=Symbol("total-length"),ft=Symbol("callback"),Ge=Symbol("buffers"),dt=Symbol("error"),Cn,br=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Cn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cn=new Nc(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[ft];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 u=+x;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${x}`);x=u}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${a}": ${x}`)}else if(a==="server_max_window_bits"){let u=+x;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${x}`);x=u}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){Cn.add(x=>{this._decompress(e,i,(u,d)=>{x(),a(u,d)})})}compress(e,i,a){Cn.add(x=>{this._compress(e,i,(u,d)=>{x(),a(u,d)})})}_decompress(e,i,a){let x=this._isServer?"client":"server";if(!this._inflate){let u=`${x}_max_window_bits`,d=typeof this.params[u]!="number"?Rt.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Rt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[An]=this,this._inflate[Oe]=0,this._inflate[Ge]=[],this._inflate.on("error",zc),this._inflate.on("data",bi)}this._inflate[ft]=a,this._inflate.write(e),i&&this._inflate.write(Bc),this._inflate.flush(()=>{let u=this._inflate[dt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=_i.concat(this._inflate[Ge],this._inflate[Oe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Oe]=0,this._inflate[Ge]=[],i&&this.params[`${x}_no_context_takeover`]&&this._inflate.reset()),a(null,d)})}_compress(e,i,a){let x=this._isServer?"server":"client";if(!this._deflate){let u=`${x}_max_window_bits`,d=typeof this.params[u]!="number"?Rt.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Rt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Oe]=0,this._deflate[Ge]=[],this._deflate.on("data",Mc)}this._deflate[ft]=a,this._deflate.write(e),this._deflate.flush(Rt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=_i.concat(this._deflate[Ge],this._deflate[Oe]);i&&(u=new Oc(u.buffer,u.byteOffset,u.length-4)),this._deflate[ft]=null,this._deflate[Oe]=0,this._deflate[Ge]=[],i&&this.params[`${x}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};vi.exports=br;function Mc(r){this[Ge].push(r),this[Oe]+=r.length}function bi(r){if(this[Oe]+=r.length,this[An]._maxPayload<1||this[Oe]<=this[An]._maxPayload){this[Ge].push(r);return}this[dt]=new RangeError("Max payload size exceeded"),this[dt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[dt][yi]=1009,this.removeListener("data",bi),this.reset()}function zc(r){if(this[An]._inflate=null,this[dt]){this[ft](this[dt]);return}r[yi]=1007,this[ft](r)}});var ht=se((Cl,kn)=>{"use strict";var{isUtf8:Si}=Y("buffer"),{hasBlob:Fc}=Ne(),qc=[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 Uc(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function vr(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 Kc(r){return Fc&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}kn.exports={isBlob:Kc,isValidStatusCode:Uc,isValidUTF8:vr,tokenChars:qc};if(Si)kn.exports.isValidUTF8=function(r){return r.length<24?vr(r):Si(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=Y("utf-8-validate");kn.exports.isValidUTF8=function(e){return e.length<32?vr(e):r(e)}}catch{}});var kr=se((Al,Di)=>{"use strict";var{Writable:Hc}=Y("stream"),Ei=lt(),{BINARY_TYPES:Gc,EMPTY_BUFFER:Ci,kStatusCode:jc,kWebSocket:Wc}=Ne(),{concat:Sr,toArrayBuffer:Jc,unmask:Vc}=Lt(),{isValidStatusCode:Yc,isValidUTF8:Ai}=ht(),Pn=Buffer[Symbol.species],fe=0,ki=1,Pi=2,Ii=3,Er=4,Cr=5,In=6,Ar=class extends Hc{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Gc[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Wc]=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=fe}_write(e,i,a){if(this._opcode===8&&this._state==fe)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 fe:this.getInfo(e);break;case ki:this.getPayloadLength16(e);break;case Pi:this.getPayloadLength64(e);break;case Ii:this.getMask();break;case Er:this.getData(e);break;case Cr:case In: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[Ei.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=ki: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=Ii:this._state=Er}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Er}getData(e){let i=Ci;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&&Vc(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Cr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[Ei.extensionName].decompress(e,this._fin,(x,u)=>{if(x)return i(x);if(u.length){if(this._messageLength+=u.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(d);return}this._fragments.push(u)}this.dataMessage(i),this._state===fe&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=fe;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=Sr(a,i):this._binaryType==="arraybuffer"?x=Jc(Sr(a,i)):this._binaryType==="blob"?x=new Blob(a):x=a,this._allowSynchronousEvents?(this.emit("message",x,!0),this._state=fe):(this._state=In,setImmediate(()=>{this.emit("message",x,!0),this._state=fe,this.startLoop(e)}))}else{let x=Sr(a,i);if(!this._skipUTF8Validation&&!Ai(x)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===Cr||this._allowSynchronousEvents?(this.emit("message",x,!1),this._state=fe):(this._state=In,setImmediate(()=>{this.emit("message",x,!1),this._state=fe,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ci),this.end();else{let a=e.readUInt16BE(0);if(!Yc(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let x=new Pn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ai(x)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");i(u);return}this._loop=!1,this.emit("conclude",a,x),this.end()}this._state=fe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=fe):(this._state=In,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=fe,this.startLoop(i)}))}createError(e,i,a,x,u){this._loop=!1,this._errored=!0;let d=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(d,this.createError),d.code=u,d[jc]=x,d}};Di.exports=Ar});var Dr=se((Pl,Ri)=>{"use strict";var{Duplex:kl}=Y("stream"),{randomFillSync:$c}=Y("crypto"),Ti=lt(),{EMPTY_BUFFER:Qc,kWebSocket:Xc,NOOP:Zc}=Ne(),{isBlob:gt,isValidStatusCode:ex}=ht(),{mask:Li,toBuffer:$e}=Lt(),de=Symbol("kByteLength"),tx=Buffer.alloc(4),Dn=8*1024,Qe,pt=Dn,we=0,nx=1,rx=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=we,this.onerror=Zc,this[Xc]=void 0}static frame(e,i){let a,x=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||tx,i.generateMask?i.generateMask(a):(pt===Dn&&(Qe===void 0&&(Qe=Buffer.alloc(Dn)),$c(Qe,0,Dn),pt=0),a[0]=Qe[pt++],a[1]=Qe[pt++],a[2]=Qe[pt++],a[3]=Qe[pt++]),d=(a[0]|a[1]|a[2]|a[3])===0,u=6);let h;typeof e=="string"?(!i.mask||d)&&i[de]!==void 0?h=i[de]:(e=Buffer.from(e),h=e.length):(h=e.length,x=i.mask&&i.readOnly&&!d);let m=h;h>=65536?(u+=8,m=127):h>125&&(u+=2,m=126);let w=Buffer.allocUnsafe(x?h+u:u);return w[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(w[0]|=64),w[1]=m,m===126?w.writeUInt16BE(h,2):m===127&&(w[2]=w[3]=0,w.writeUIntBE(h,4,6)),i.mask?(w[1]|=128,w[u-4]=a[0],w[u-3]=a[1],w[u-2]=a[2],w[u-1]=a[3],d?[w,e]:x?(Li(e,a,w,u,h),[w]):(Li(e,a,e,0,h),[w,e])):[w,e]}close(e,i,a,x){let u;if(e===void 0)u=Qc;else{if(typeof e!="number"||!ex(e))throw new TypeError("First argument must be a valid error code number");if(i===void 0||!i.length)u=Buffer.allocUnsafe(2),u.writeUInt16BE(e,0);else{let h=Buffer.byteLength(i);if(h>123)throw new RangeError("The message must not be greater than 123 bytes");u=Buffer.allocUnsafe(2+h),u.writeUInt16BE(e,0),typeof i=="string"?u.write(i,2):u.set(i,2)}}let d={[de]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==we?this.enqueue([this.dispatch,u,!1,d,x]):this.sendFrame(r.frame(u,d),x)}ping(e,i,a){let x,u;if(typeof e=="string"?(x=Buffer.byteLength(e),u=!1):gt(e)?(x=e.size,u=!1):(e=$e(e),x=e.length,u=$e.readOnly),x>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[de]:x,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};gt(e)?this._state!==we?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==we?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(r.frame(e,d),a)}pong(e,i,a){let x,u;if(typeof e=="string"?(x=Buffer.byteLength(e),u=!1):gt(e)?(x=e.size,u=!1):(e=$e(e),x=e.length,u=$e.readOnly),x>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[de]:x,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};gt(e)?this._state!==we?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==we?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(r.frame(e,d),a)}send(e,i,a){let x=this._extensions[Ti.extensionName],u=i.binary?2:1,d=i.compress,h,m;typeof e=="string"?(h=Buffer.byteLength(e),m=!1):gt(e)?(h=e.size,m=!1):(e=$e(e),h=e.length,m=$e.readOnly),this._firstFragment?(this._firstFragment=!1,d&&x&&x.params[x._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=h>=x._threshold),this._compress=d):(d=!1,u=0),i.fin&&(this._firstFragment=!0);let w={[de]:h,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:m,rsv1:d};gt(e)?this._state!==we?this.enqueue([this.getBlobData,e,this._compress,w,a]):this.getBlobData(e,this._compress,w,a):this._state!==we?this.enqueue([this.dispatch,e,this._compress,w,a]):this.dispatch(e,this._compress,w,a)}getBlobData(e,i,a,x){this._bufferedBytes+=a[de],this._state=rx,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let h=new Error("The socket was closed while the blob was being read");process.nextTick(Ir,this,h,x);return}this._bufferedBytes-=a[de];let d=$e(u);i?this.dispatch(d,i,a,x):(this._state=we,this.sendFrame(r.frame(d,a),x),this.dequeue())}).catch(u=>{process.nextTick(sx,this,u,x)})}dispatch(e,i,a,x){if(!i){this.sendFrame(r.frame(e,a),x);return}let u=this._extensions[Ti.extensionName];this._bufferedBytes+=a[de],this._state=nx,u.compress(e,a.fin,(d,h)=>{if(this._socket.destroyed){let m=new Error("The socket was closed while data was being compressed");Ir(this,m,x);return}this._bufferedBytes-=a[de],this._state=we,a.readOnly=!1,this.sendFrame(r.frame(h,a),x),this.dequeue()})}dequeue(){for(;this._state===we&&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)}};Ri.exports=Pr;function Ir(r,e,i){typeof i=="function"&&i(e);for(let a=0;a<r._queue.length;a++){let x=r._queue[a],u=x[x.length-1];typeof u=="function"&&u(e)}}function sx(r,e,i){Ir(r,e,i),r.onerror(e)}});var Ki=se((Il,Ui)=>{"use strict";var{kForOnEventAttribute:Nt,kListener:Tr}=Ne(),Ni=Symbol("kCode"),Oi=Symbol("kData"),Bi=Symbol("kError"),Mi=Symbol("kMessage"),zi=Symbol("kReason"),mt=Symbol("kTarget"),Fi=Symbol("kType"),qi=Symbol("kWasClean"),Be=class{constructor(e){this[mt]=null,this[Fi]=e}get target(){return this[mt]}get type(){return this[Fi]}};Object.defineProperty(Be.prototype,"target",{enumerable:!0});Object.defineProperty(Be.prototype,"type",{enumerable:!0});var Xe=class extends Be{constructor(e,i={}){super(e),this[Ni]=i.code===void 0?0:i.code,this[zi]=i.reason===void 0?"":i.reason,this[qi]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[Ni]}get reason(){return this[zi]}get wasClean(){return this[qi]}};Object.defineProperty(Xe.prototype,"code",{enumerable:!0});Object.defineProperty(Xe.prototype,"reason",{enumerable:!0});Object.defineProperty(Xe.prototype,"wasClean",{enumerable:!0});var wt=class extends Be{constructor(e,i={}){super(e),this[Bi]=i.error===void 0?null:i.error,this[Mi]=i.message===void 0?"":i.message}get error(){return this[Bi]}get message(){return this[Mi]}};Object.defineProperty(wt.prototype,"error",{enumerable:!0});Object.defineProperty(wt.prototype,"message",{enumerable:!0});var Ot=class extends Be{constructor(e,i={}){super(e),this[Oi]=i.data===void 0?null:i.data}get data(){return this[Oi]}};Object.defineProperty(Ot.prototype,"data",{enumerable:!0});var ix={addEventListener(r,e,i={}){for(let x of this.listeners(r))if(!i[Nt]&&x[Tr]===e&&!x[Nt])return;let a;if(r==="message")a=function(u,d){let h=new Ot("message",{data:d?u:u.toString()});h[mt]=this,Tn(e,this,h)};else if(r==="close")a=function(u,d){let h=new Xe("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});h[mt]=this,Tn(e,this,h)};else if(r==="error")a=function(u){let d=new wt("error",{error:u,message:u.message});d[mt]=this,Tn(e,this,d)};else if(r==="open")a=function(){let u=new Be("open");u[mt]=this,Tn(e,this,u)};else return;a[Nt]=!!i[Nt],a[Tr]=e,i.once?this.once(r,a):this.on(r,a)},removeEventListener(r,e){for(let i of this.listeners(r))if(i[Tr]===e&&!i[Nt]){this.removeListener(r,i);break}}};Ui.exports={CloseEvent:Xe,ErrorEvent:wt,Event:Be,EventTarget:ix,MessageEvent:Ot};function Tn(r,e,i){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,i):r.call(e,i)}});var Ln=se((Dl,Hi)=>{"use strict";var{tokenChars:Bt}=ht();function Ae(r,e,i){r[e]===void 0?r[e]=[i]:r[e].push(i)}function ox(r){let e=Object.create(null),i=Object.create(null),a=!1,x=!1,u=!1,d,h,m=-1,w=-1,b=-1,_=0;for(;_<r.length;_++)if(w=r.charCodeAt(_),d===void 0)if(b===-1&&Bt[w]===1)m===-1&&(m=_);else if(_!==0&&(w===32||w===9))b===-1&&m!==-1&&(b=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);b===-1&&(b=_);let L=r.slice(m,b);w===44?(Ae(e,L,i),i=Object.create(null)):d=L,m=b=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===void 0)if(b===-1&&Bt[w]===1)m===-1&&(m=_);else if(w===32||w===9)b===-1&&m!==-1&&(b=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);b===-1&&(b=_),Ae(i,r.slice(m,b),!0),w===44&&(Ae(e,d,i),i=Object.create(null),d=void 0),m=b=-1}else if(w===61&&m!==-1&&b===-1)h=r.slice(m,_),m=b=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(x){if(Bt[w]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);m===-1?m=_:a||(a=!0),x=!1}else if(u)if(Bt[w]===1)m===-1&&(m=_);else if(w===34&&m!==-1)u=!1,b=_;else if(w===92)x=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(w===34&&r.charCodeAt(_-1)===61)u=!0;else if(b===-1&&Bt[w]===1)m===-1&&(m=_);else if(m!==-1&&(w===32||w===9))b===-1&&(b=_);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${_}`);b===-1&&(b=_);let L=r.slice(m,b);a&&(L=L.replace(/\\/g,""),a=!1),Ae(i,h,L),w===44&&(Ae(e,d,i),i=Object.create(null),d=void 0),h=void 0,m=b=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(m===-1||u||w===32||w===9)throw new SyntaxError("Unexpected end of input");b===-1&&(b=_);let C=r.slice(m,b);return d===void 0?Ae(e,C,i):(h===void 0?Ae(i,C,!0):a?Ae(i,h,C.replace(/\\/g,"")):Ae(i,h,C),Ae(e,d,i)),e}function ax(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 u=a[x];return Array.isArray(u)||(u=[u]),u.map(d=>d===!0?x:`${x}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Hi.exports={format:ax,parse:ox}});var Bn=se((Rl,to)=>{"use strict";var cx=Y("events"),xx=Y("https"),ux=Y("http"),Wi=Y("net"),fx=Y("tls"),{randomBytes:dx,createHash:lx}=Y("crypto"),{Duplex:Tl,Readable:Ll}=Y("stream"),{URL:Lr}=Y("url"),je=lt(),hx=kr(),gx=Dr(),{isBlob:px}=ht(),{BINARY_TYPES:Gi,CLOSE_TIMEOUT:mx,EMPTY_BUFFER:Rn,GUID:_x,kForOnEventAttribute:Rr,kListener:yx,kStatusCode:bx,kWebSocket:Z,NOOP:Ji}=Ne(),{EventTarget:{addEventListener:vx,removeEventListener:Sx}}=Ki(),{format:Ex,parse:Cx}=Ln(),{toBuffer:Ax}=Lt(),Vi=Symbol("kAborted"),Nr=[8,13],Me=["CONNECTING","OPEN","CLOSING","CLOSED"],kx=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,F=class r extends cx{constructor(e,i,a){super(),this._binaryType=Gi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Rn,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]),Yi(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gi.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 hx({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new gx(e,this._extensions,a.generateMask);this._receiver=x,this._sender=u,this._socket=e,x[Z]=this,u[Z]=this,e[Z]=this,x.on("conclude",Dx),x.on("drain",Tx),x.on("error",Lx),x.on("message",Rx),x.on("ping",Nx),x.on("pong",Ox),u.onerror=Bx,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",Xi),e.on("data",On),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[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){Or(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Rn,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){Or(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Rn,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){Or(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||Rn,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(F,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(F.prototype,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(F,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(F.prototype,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(F,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(F.prototype,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(F,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});Object.defineProperty(F.prototype,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(F.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(F.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Rr])return e[yx];return null},set(e){for(let i of this.listeners(r))if(i[Rr]){this.removeListener(r,i);break}typeof e=="function"&&this.addEventListener(r,e,{[Rr]:!0})}})});F.prototype.addEventListener=vx;F.prototype.removeEventListener=Sx;to.exports=F;function Yi(r,e,i,a){let x={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:mx,protocolVersion:Nr[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,!Nr.includes(x.protocolVersion))throw new RangeError(`Unsupported protocol version: ${x.protocolVersion} (supported versions: ${Nr.join(", ")})`);let u;if(e instanceof Lr)u=e;else try{u=new Lr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}u.protocol==="http:"?u.protocol="ws:":u.protocol==="https:"&&(u.protocol="wss:"),r._url=u.href;let d=u.protocol==="wss:",h=u.protocol==="ws+unix:",m;if(u.protocol!=="ws:"&&!d&&!h?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:h&&!u.pathname?m="The URL's pathname is empty":u.hash&&(m="The URL contains a fragment identifier"),m){let R=new SyntaxError(m);if(r._redirects===0)throw R;Nn(r,R);return}let w=d?443:80,b=dx(16).toString("base64"),_=d?xx.request:ux.request,C=new Set,L;if(x.createConnection=x.createConnection||(d?Ix:Px),x.defaultPort=x.defaultPort||w,x.port=u.port||w,x.host=u.hostname.startsWith("[")?u.hostname.slice(1,-1):u.hostname,x.headers={...x.headers,"Sec-WebSocket-Version":x.protocolVersion,"Sec-WebSocket-Key":b,Connection:"Upgrade",Upgrade:"websocket"},x.path=u.pathname+u.search,x.timeout=x.handshakeTimeout,x.perMessageDeflate&&(L=new je({...x.perMessageDeflate,isServer:!1,maxPayload:x.maxPayload}),x.headers["Sec-WebSocket-Extensions"]=Ex({[je.extensionName]:L.offer()})),i.length){for(let R of i){if(typeof R!="string"||!kx.test(R)||C.has(R))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(R)}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),(u.username||u.password)&&(x.auth=`${u.username}:${u.password}`),h){let R=x.path.split(":");x.socketPath=R[0],x.path=R[1]}let I;if(x.followRedirects){if(r._redirects===0){r._originalIpc=h,r._originalSecure=d,r._originalHostOrSocketPath=h?x.socketPath:u.host;let R=a&&a.headers;if(a={...a,headers:{}},R)for(let[z,ee]of Object.entries(R))a.headers[z.toLowerCase()]=ee}else if(r.listenerCount("redirect")===0){let R=h?r._originalIpc?x.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:u.host===r._originalHostOrSocketPath;(!R||r._originalSecure&&!d)&&(delete x.headers.authorization,delete x.headers.cookie,R||delete x.headers.host,x.auth=void 0)}x.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(x.auth).toString("base64")),I=r._req=_(x),r._redirects&&r.emit("redirect",r.url,I)}else I=r._req=_(x);x.timeout&&I.on("timeout",()=>{xe(r,I,"Opening handshake has timed out")}),I.on("error",R=>{I===null||I[Vi]||(I=r._req=null,Nn(r,R))}),I.on("response",R=>{let z=R.headers.location,ee=R.statusCode;if(z&&x.followRedirects&&ee>=300&&ee<400){if(++r._redirects>x.maxRedirects){xe(r,I,"Maximum redirects exceeded");return}I.abort();let le;try{le=new Lr(z,e)}catch{let oe=new SyntaxError(`Invalid URL: ${z}`);Nn(r,oe);return}Yi(r,le,i,a)}else r.emit("unexpected-response",I,R)||xe(r,I,`Unexpected server response: ${R.statusCode}`)}),I.on("upgrade",(R,z,ee)=>{if(r.emit("upgrade",R),r.readyState!==F.CONNECTING)return;I=r._req=null;let le=R.headers.upgrade;if(le===void 0||le.toLowerCase()!=="websocket"){xe(r,z,"Invalid Upgrade header");return}let _e=lx("sha1").update(b+_x).digest("base64");if(R.headers["sec-websocket-accept"]!==_e){xe(r,z,"Invalid Sec-WebSocket-Accept header");return}let oe=R.headers["sec-websocket-protocol"],D;if(oe!==void 0?C.size?C.has(oe)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":C.size&&(D="Server sent no subprotocol"),D){xe(r,z,D);return}oe&&(r._protocol=oe);let q=R.headers["sec-websocket-extensions"];if(q!==void 0){if(!L){xe(r,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=Cx(q)}catch{xe(r,z,"Invalid Sec-WebSocket-Extensions header");return}let he=Object.keys(V);if(he.length!==1||he[0]!==je.extensionName){xe(r,z,"Server indicated an extension that was not requested");return}try{L.accept(V[je.extensionName])}catch{xe(r,z,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[je.extensionName]=L}r.setSocket(z,ee,{allowSynchronousEvents:x.allowSynchronousEvents,generateMask:x.generateMask,maxPayload:x.maxPayload,skipUTF8Validation:x.skipUTF8Validation})}),x.finishRequest?x.finishRequest(I,r):I.end()}function Nn(r,e){r._readyState=F.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Px(r){return r.path=r.socketPath,Wi.connect(r)}function Ix(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Wi.isIP(r.host)?"":r.host),fx.connect(r)}function xe(r,e,i){r._readyState=F.CLOSING;let a=new Error(i);Error.captureStackTrace(a,xe),e.setHeader?(e[Vi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Nn,r,a)):(e.destroy(a),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function Or(r,e,i){if(e){let a=px(e)?e.size:Ax(e).length;r._socket?r._sender._bufferedBytes+=a:r._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${r.readyState} (${Me[r.readyState]})`);process.nextTick(i,a)}}function Dx(r,e){let i=this[Z];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=r,i._socket[Z]!==void 0&&(i._socket.removeListener("data",On),process.nextTick($i,i._socket),r===1005?i.close():i.close(r,e))}function Tx(){let r=this[Z];r.isPaused||r._socket.resume()}function Lx(r){let e=this[Z];e._socket[Z]!==void 0&&(e._socket.removeListener("data",On),process.nextTick($i,e._socket),e.close(r[bx])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ji(){this[Z].emitClose()}function Rx(r,e){this[Z].emit("message",r,e)}function Nx(r){let e=this[Z];e._autoPong&&e.pong(r,!this._isServer,Ji),e.emit("ping",r)}function Ox(r){this[Z].emit("pong",r)}function $i(r){r.resume()}function Bx(r){let e=this[Z];e.readyState!==F.CLOSED&&(e.readyState===F.OPEN&&(e._readyState=F.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 Xi(){let r=this[Z];if(this.removeListener("close",Xi),this.removeListener("data",On),this.removeListener("end",Zi),r._readyState=F.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 On(r){this[Z]._receiver.write(r)||this.pause()}function Zi(){let r=this[Z];r._readyState=F.CLOSING,r._receiver.end(),this.end()}function eo(){let r=this[Z];this.removeListener("error",eo),this.on("error",Ji),r&&(r._readyState=F.CLOSING,this.destroy())}});var io=se((Ol,so)=>{"use strict";var Nl=Bn(),{Duplex:Mx}=Y("stream");function no(r){r.emit("close")}function zx(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ro(r){this.removeListener("error",ro),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Fx(r,e){let i=!0,a=new Mx({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(u,d){let h=!d&&a._readableState.objectMode?u.toString():u;a.push(h)||r.pause()}),r.once("error",function(u){a.destroyed||(i=!1,a.destroy(u))}),r.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(x,u){if(r.readyState===r.CLOSED){u(x),process.nextTick(no,a);return}let d=!1;r.once("error",function(m){d=!0,u(m)}),r.once("close",function(){d||u(x),process.nextTick(no,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,u,d){if(r.readyState===r.CONNECTING){r.once("open",function(){a._write(x,u,d)});return}r.send(x,d)},a.on("end",zx),a.on("error",ro),a}so.exports=Fx});var Br=se((Bl,oo)=>{"use strict";var{tokenChars:qx}=ht();function Ux(r){let e=new Set,i=-1,a=-1,x=0;for(x;x<r.length;x++){let d=r.charCodeAt(x);if(a===-1&&qx[d]===1)i===-1&&(i=x);else if(x!==0&&(d===32||d===9))a===-1&&i!==-1&&(a=x);else if(d===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 u=r.slice(i,x);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return e.add(u),e}oo.exports={parse:Ux}});var ho=se((zl,lo)=>{"use strict";var Kx=Y("events"),Mn=Y("http"),{Duplex:Ml}=Y("stream"),{createHash:Hx}=Y("crypto"),ao=Ln(),Ze=lt(),Gx=Br(),jx=Bn(),{CLOSE_TIMEOUT:Wx,GUID:Jx,kWebSocket:Vx}=Ne(),Yx=/^[+/0-9A-Za-z]{22}==$/,co=0,xo=1,fo=2,Mr=class extends Kx{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Wx,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:jx,...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=Mn.createServer((a,x)=>{let u=Mn.STATUS_CODES[426];x.writeHead(426,{"Content-Length":u.length,"Content-Type":"text/plain"}),x.end(u)}),this._server.listen(e.port,e.host,e.backlog,i)):e.server&&(this._server=e.server),this._server){let a=this.emit.bind(this,"connection");this._removeListeners=$x(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(x,u,d)=>{this.handleUpgrade(x,u,d,a)}})}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!==xo)if(this._state=xo,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 i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{Mt(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",uo);let u=e.headers["sec-websocket-key"],d=e.headers.upgrade,h=+e.headers["sec-websocket-version"];if(e.method!=="GET"){et(this,e,i,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){et(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!Yx.test(u)){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)){zt(i,400);return}let m=e.headers["sec-websocket-protocol"],w=new Set;if(m!==void 0)try{w=Gx.parse(m)}catch{et(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let b=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&b!==void 0){let C=new Ze({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let L=ao.parse(b);L[Ze.extensionName]&&(C.accept(L[Ze.extensionName]),_[Ze.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,(L,I,R,z)=>{if(!L)return zt(i,I||401,R,z);this.completeUpgrade(_,u,w,e,i,a,x)});return}if(!this.options.verifyClient(C))return zt(i,401)}this.completeUpgrade(_,u,w,e,i,a,x)}completeUpgrade(e,i,a,x,u,d,h){if(!u.readable||!u.writable)return u.destroy();if(u[Vx])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>co)return zt(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Hx("sha1").update(i+Jx).digest("base64")}`],b=new this.options.WebSocket(null,void 0,this.options);if(a.size){let _=this.options.handleProtocols?this.options.handleProtocols(a,x):a.values().next().value;_&&(w.push(`Sec-WebSocket-Protocol: ${_}`),b._protocol=_)}if(e[Ze.extensionName]){let _=e[Ze.extensionName].params,C=ao.format({[Ze.extensionName]:[_]});w.push(`Sec-WebSocket-Extensions: ${C}`),b._extensions=e}this.emit("headers",w,x),u.write(w.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
- `)),u.removeListener("error",uo),b.setSocket(u,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(b),b.on("close",()=>{this.clients.delete(b),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Mt,this)})),h(b,x)}};lo.exports=Mr;function $x(r,e){for(let i of Object.keys(e))r.on(i,e[i]);return function(){for(let a of Object.keys(e))r.removeListener(a,e[a])}}function Mt(r){r._state=fo,r.emit("close")}function uo(){this.destroy()}function zt(r,e,i,a){i=i||Mn.STATUS_CODES[e],a={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(i),...a},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${Mn.STATUS_CODES[e]}\r
14
- `+Object.keys(a).map(x=>`${x}: ${a[x]}`).join(`\r
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
- `+i)}function et(r,e,i,a,x,u){if(r.listenerCount("wsClientError")){let d=new Error(x);Error.captureStackTrace(d,et),r.emit("wsClientError",d,i,e)}else zt(i,a,x,u)}});import{spawn as yu}from"node:child_process";import{existsSync as bu,openSync as vu}from"node:fs";import{mkdir as Su}from"node:fs/promises";import{dirname as Eu}from"node:path";import{fileURLToPath as Cu}from"node:url";function qr(r=H()){return bu(r.libEntry)?r.libEntry:Cu(new URL("../index.ts",import.meta.url))}async function Bo(r={}){let e=r.paths??H(),i=r.entryOverride??qr(e);await Su(Eu(e.logFile),{recursive:!0});let a=vu(e.logFile,"a"),u=i.endsWith(".ts")?["--import","tsx/esm",i,"--daemon"]:[i,"--daemon"],d=yu(process.execPath,u,{detached:!0,stdio:["ignore",a,a],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(d.unref(),typeof d.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Au.info("daemon spawned",{pid:d.pid,entry:i}),{pid:d.pid,entry:i}}var Au,Ur=Ie(()=>{"use strict";K();ae();Au=N("spawn-daemon")});import{spawn as Nu}from"node:child_process";import{mkdir as Ou,unlink as Bu,writeFile as Mu}from"node:fs/promises";import{dirname as zu,join as Fu}from"node:path";function jn(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Uo(r,e){return new Promise((i,a)=>{let x=Nu(r,e,{stdio:["ignore","pipe","pipe"]}),u="";x.stderr?.on("data",d=>{u+=d.toString("utf8")}),x.on("error",a),x.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var Gn,Gr,jr,Ko=Ie(()=>{"use strict";K();Gn=N("supervisor.launchd"),Gr="ai.coze.bridge",jr={platform:"darwin",renderConfig(r){return`<?xml version="1.0" encoding="UTF-8"?>
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}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>${Gr}</string>
22
+ <string>${Dn}</string>
23
23
  <key>ProgramArguments</key>
24
24
  <array>
25
- <string>${jn(r.nodeBin)}</string>
26
- <string>${jn(r.entry)}</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 Ua=Object.create;var cr=Object.defineProperty;var Ka=Object.getOwnPropertyDe
33
33
  <key>ThrottleInterval</key>
34
34
  <integer>10</integer>
35
35
  <key>StandardOutPath</key>
36
- <string>${jn(r.logFile)}</string>
36
+ <string>${mr(r.logFile)}</string>
37
37
  <key>StandardErrorPath</key>
38
- <string>${jn(r.logFile)}</string>
38
+ <string>${mr(r.logFile)}</string>
39
39
  </dict>
40
40
  </plist>
41
- `},configPath(r){return Fu(r.homeDir,"Library","LaunchAgents",`${Gr}.plist`)},async install(r){let e=this.configPath(r);await Ou(zu(e),{recursive:!0}),await Mu(e,this.renderConfig(r),"utf8"),Gn.info("plist written",{plistPath:e}),await Uo("launchctl",["load","-w",e]),Gn.info("launchd job loaded",{label:Gr})},async uninstall(r){let e=this.configPath(r);await Uo("launchctl",["unload","-w",e]).catch(i=>Gn.warn("launchctl unload failed (ignored)",{err:String(i)})),await Bu(e).catch(i=>{if(i.code!=="ENOENT")throw i}),Gn.info("launchd job removed",{plistPath:e})}}});import{spawn as qu}from"node:child_process";import{mkdir as Uu,unlink as Ku,writeFile as Hu}from"node:fs/promises";import{dirname as Gu,join as ju}from"node:path";function Vn(r,e){return new Promise((i,a)=>{let x=qu(r,e,{stdio:["ignore","pipe","pipe"]}),u="";x.stderr?.on("data",d=>{u+=d.toString("utf8")}),x.on("error",a),x.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var Wn,Jn,Wr,Ho=Ie(()=>{"use strict";K();Wn=N("supervisor.systemd"),Jn="coze-bridge.service",Wr={platform:"linux",renderConfig(r){return`[Unit]
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 ju(r.homeDir,".config","systemd","user",Jn)},async install(r){let e=this.configPath(r);await Uu(Gu(e),{recursive:!0}),await Hu(e,this.renderConfig(r),"utf8"),Wn.info("systemd unit written",{unitPath:e}),await Vn("systemctl",["--user","daemon-reload"]),await Vn("systemctl",["--user","enable","--now",Jn]),Wn.info("systemd unit enabled",{unitName:Jn})},async uninstall(r){let e=this.configPath(r);await Vn("systemctl",["--user","disable","--now",Jn]).catch(i=>Wn.warn("systemctl disable failed (ignored)",{err:String(i)})),await Ku(e).catch(i=>{if(i.code!=="ENOENT")throw i}),await Vn("systemctl",["--user","daemon-reload"]).catch(()=>{}),Wn.info("systemd unit removed",{unitPath:e})}}});import{spawn as Wu}from"node:child_process";import{join as Ju}from"node:path";function Go(r,e){return new Promise((i,a)=>{let x=Wu(r,e,{stdio:["ignore","pipe","pipe"],shell:!1}),u="";x.stderr?.on("data",d=>{u+=d.toString("utf8")}),x.on("error",a),x.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var Jr,Yn,Vr,jo=Ie(()=>{"use strict";K();Jr=N("supervisor.taskscheduler"),Yn="CozeBridge",Vr={platform:"win32",renderConfig(r){return`<?xml version="1.0" encoding="UTF-16"?>
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 Ju(r.homeDir,".coze","bridge","task.xml")},async install(r){let e=`"${r.nodeBin}" "${r.entry}" --daemon`;await Go("schtasks",["/Create","/SC","ONLOGON","/TN",Yn,"/TR",e,"/RU",r.userName,"/F"]),Jr.info("task scheduler entry created",{task:Yn})},async uninstall(r){await Go("schtasks",["/Delete","/TN",Yn,"/F"]).catch(e=>Jr.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Jr.info("task scheduler entry removed",{task:Yn})}}});var Yr={};bs(Yr,{buildContext:()=>Qu,getSupervisor:()=>$u,launchdSupervisor:()=>jr,systemdSupervisor:()=>Wr,taskSchedulerSupervisor:()=>Vr});import{homedir as Vu,userInfo as Yu}from"node:os";function $u(r=process.platform){switch(r){case"darwin":return jr;case"linux":return Wr;case"win32":return Vr;default:throw new Error(`unsupported platform for OS supervisor: ${r}`)}}function Qu(){let r=H();return{nodeBin:process.execPath,entry:qr(r),logFile:r.logFile,homeDir:Vu(),userName:Yu().username}}var $r=Ie(()=>{"use strict";ae();Ur();Ko();Ho();jo()});Ue();K();import{readdir as c0}from"node:fs/promises";import{mkdir as r0,writeFile as s0}from"node:fs/promises";import{join as i0}from"node:path";var o0={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ot(r,e,i,a){await r0(r,{recursive:!0});let x=o0[e],u=i0(r,x),d=a0(e,i,a);return await s0(u,d,"utf8"),u}function a0(r,e,i){let a=`# Coze Agent: ${e}
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
- `,x=i?.trim()?i.endsWith(`
84
- `)?i:`${i}
83
+ `,s=t?.trim()?t.endsWith(`
84
+ `)?t:`${t}
85
85
  `:`_No instructions provided._
86
- `;return`${a}---
86
+ `;return`${n}---
87
87
 
88
- ${x}`}var ve=N("agent-detail-sync"),$t=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await c0(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(u){ve.warn("detail sync failed for agent, skipping",{agentId:x,err:String(u)})}ve.info("detail sync done",{reason:e})}async syncOne(e){let i=await ce(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(d){ve.warn("detail RPC failed, using local data",{agentId:e,err:String(d)});return}if(a.agentId&&a.agentId!==e){ve.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:a.agentId});return}let x=!1,u=!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,u=!0),a.deployType&&ve.info("detail.deployType",{agentId:e,deployType:a.deployType}),!x){ve.debug("detail sync: no diff",{agentId:e});return}await me(i,this.opts.paths),ve.info("detail sync: config updated",{agentId:e,identityChanged:u,agentName:i.agentName}),u&&(await ot(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ue();import{spawn as Bs}from"node:child_process";import{lstat as dr,mkdir as x0,readFile as Ms,readdir as u0,rm as f0,stat as d0,writeFile as l0}from"node:fs/promises";import{join as Re,normalize as h0,relative as zs,resolve as g0,sep as Fs}from"node:path";var Se={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 Et(r){return r?.cozeDeployType==="cloud"?"cloud":"local"}function Ps(r){let{_meta:e,...i}=r;return{stripped:i,meta:e}}function at(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();ae();function Le(r,e){if(Et(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 Is="https://llm-gateway.coze.cn",ct="auto";function Ds(r){return{model:r.model??ct,...r.modelToken?{modelToken:r.modelToken}:{}}}function Ts(r){return!r||r===ct}function Ls(r){let e={};return r.modelToken&&(e.ANTHROPIC_BASE_URL=Is,e.ANTHROPIC_AUTH_TOKEN=r.modelToken),Ts(r.model)||(e.ANTHROPIC_MODEL=r.model),e}function Rs(r){let e=[];return Ts(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="${Is}/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 Ns(r){return r.modelToken?{OPENAI_API_KEY:r.modelToken}:{}}var ie=N("agent-handlers"),Os=5*1024*1024,p0=1,m0=6,w0=new Set(["node_modules",".git",".coze","dist","build",".next"]),Zt=class{constructor(e){this.opts=e}opts;async listSkills(e){Le(e._meta,"_agent/listSkills");let i=at(e._meta),a=await this.loadAgentCfg(i),x=a?.workspace??Te(i).workspace,u=a?.skills??[],d=[];for(let h of u){let m=Re(x,h.relPath,"SKILL.md");await d0(m).then(b=>b.isFile()).catch(()=>!1)&&d.push({skillId:h.skillId,skillName:h.skillName,downloadUrl:h.downloadUrl??"",...h.description?{description:h.description}:{},...h.version?{version:h.version}:{}})}return{skills:d}}async addSkills(e){Le(e._meta,"_agent/addSkills");let i=at(e._meta),a=await this.requireAgentCfg(i),x=e.skills??[],u=[...a.skills??[]],d=new Map(u.map((m,w)=>[m.skillId,w])),h=[];for(let m of x){if(!m.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let w=_0(m.skillName),b=y0(a.framework),_=Re(b,w),C=Re(a.workspace,_);await x0(C,{recursive:!0});let L=await S0(m.downloadUrl);C0(L)?await A0(L,C):await l0(Re(C,"SKILL.md"),L.toString("utf8"),"utf8");let I={skillId:m.skillId,skillName:m.skillName,relPath:_,installedAt:Date.now(),...m.description?{description:m.description}:{},...m.version?{version:m.version}:{},...m.downloadUrl?{downloadUrl:m.downloadUrl}:{}},R=d.get(m.skillId);R!==void 0?u[R]=I:(d.set(m.skillId,u.length),u.push(I)),h.push(m),ie.info("skill installed",{agentId:i,skillId:m.skillId,skillName:m.skillName,relPath:_})}return await Vt(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:h}}async removeSkills(e){Le(e._meta,"_agent/removeSkills");let i=at(e._meta),a=await this.requireAgentCfg(i),x=new Set(e.skillIds??[]),u=a.skills??[],d=[];for(let h of u){if(!x.has(h.skillId)){d.push(h);continue}let m=Re(a.workspace,h.relPath);await f0(m,{recursive:!0,force:!0}),ie.info("skill removed",{agentId:i,skillId:h.skillId,relPath:h.relPath})}return await Vt(i,d),await this.reloadAgentSessions(i,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,i){return this.reloadAgentSessions(e,i)}async reloadAgentSessions(e,i){let a=this.opts.agents.get(e);if(a&&a.framework!=="codex"){for(let[x,u]of a.sessions)if(!(!u.downstream||!u.acpSessionId)){u.loadingSession=!0;try{await u.downstream.sessionLoad({sessionId:u.acpSessionId,cwd:a.workspace}),ie.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:x,acpId:u.acpSessionId})}catch(d){ie.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:x,acpId:u.acpSessionId,err:String(d)})}finally{u.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return ie.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await ce(i);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(ie.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await me(a),await ot(a.workspace,a.framework,i,e.cozeIdentity),ie.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 ce(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await me(a),ie.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}):(ie.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Le(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:ct,a=await ce(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await me(a),ie.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}`)}),ie.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:i}),{ok:!0}):(ie.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0})}async resetAgent(e){if(Le(e._meta,Se.RESET),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Se.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Le(e._meta,Se.REPAIR),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new E("IPC_BAD_REQUEST",`${Se.REPAIR} only allowed for openclaw, got ${i.framework}`);return await this.runDetailSync(e.agentId,Se.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){ie.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(x){ie.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(x)})}}async getFileTree(e){Le(e._meta,"_agent/getFileTree");let i=e._meta,a=at(i),x=await this.resolveWorkspace(a),u=e.filePath??"",d=this.safeJoin(x,u),h=await dr(d).catch(()=>null);if(!h)throw new E("IPC_BAD_REQUEST",`path not found: ${u}`);if(h.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let m=P0(e.depth);return h.isDirectory()?{tree:await qs(x,d,u,m)}:{tree:[{name:I0(u),path:Us(u||"."),isDir:!1,size:h.size,modifiedAt:Math.floor(h.mtimeMs)}]}}async getFileContent(e){Le(e._meta,"_agent/getFileContent");let i=at(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),u=await dr(x).catch(()=>null);if(!u||!u.isFile())throw new E("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>Os)throw new E("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${Os})`);let d=await Ms(x);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:u.size}:{content:d.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await ce(e).catch(()=>null))?.workspace??Te(e).workspace}safeJoin(e,i){let a=g0(e,i||"."),x=zs(e,a);if(x.startsWith("..")||x===".."||x.startsWith(`..${Fs}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return ce(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 _0(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 y0(r){return r==="claude-code"?Re(".claude","skills"):Re(".agents","skills")}var b0=3e4,v0=50*1024*1024,en=3e4;async function S0(r){if(!r)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);Xt(e);let i=E0(r);return Xt(i.length),i}if(r.startsWith("file:")){let e=new URL(r).pathname,i=await Ms(e);return Xt(i.length),i}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),b0);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 Xt(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 Xt(r){if(r>v0)throw new E("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function E0(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 C0(r){return r.length>=2&&r[0]===31&&r[1]===139}async function A0(r,e){await k0(r),await new Promise((i,a)=>{let x=Bs("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";x.stderr?.on("data",h=>{u+=String(h)});let d=setTimeout(()=>{x.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar extract timeout (${en}ms)`))},en);x.on("error",h=>{clearTimeout(d),a(new E("IPC_BAD_REQUEST",`tar spawn failed: ${h.message}`,{cause:h}))}),x.on("exit",h=>{clearTimeout(d),h===0?i():a(new E("IPC_BAD_REQUEST",`tar exit ${h}${u?`: ${u.trim().slice(0,200)}`:""}`))}),x.stdin?.end(r)})}async function k0(r){let e=await new Promise((i,a)=>{let x=Bs("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",d="";x.stdout?.on("data",m=>{u+=String(m)}),x.stderr?.on("data",m=>{d+=String(m)});let h=setTimeout(()=>{x.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar list timeout (${en}ms)`))},en);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(u):a(new E("IPC_BAD_REQUEST",`tar list exit ${m}${d?`: ${d.trim().slice(0,200)}`:""}`))}),x.stdin?.end(r)});for(let i of e.split(`
89
- `)){let a=i.trim();if(!a)continue;let x=a.charCodeAt(0);if(x!==45&&x!==100)throw new E("IPC_BAD_REQUEST",`tar entry kind '${a[0]}' not allowed (symlink/hardlink/special): ${a.slice(0,100)}`);let d=(a.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!d)continue;if(d.startsWith("/"))throw new E("IPC_BAD_REQUEST",`tar entry absolute path: ${d}`);if(d.split(/[/\\]/).some(m=>m===".."))throw new E("IPC_BAD_REQUEST",`tar entry contains '..': ${d}`)}}async function qs(r,e,i,a){if(a<=0)return[];let x;try{x=await u0(e,{withFileTypes:!0})}catch{return[]}let u=[];for(let d of x){if(w0.has(d.name)||d.isSymbolicLink())continue;let h=Re(e,d.name),m=h0(Re(i,d.name)),w=null;try{w=await dr(h)}catch{continue}if(w.isSymbolicLink())continue;let b={name:d.name,path:Us(zs(r,h)),isDir:w.isDirectory(),size:w.size,modifiedAt:Math.floor(w.mtimeMs)};w.isDirectory()&&a>1&&(b.children=await qs(r,h,m,a-1)),u.push(b)}return u.sort((d,h)=>d.isDir!==h.isDir?d.isDir?-1:1:d.name.localeCompare(h.name)),u}function P0(r){return!r||r<=0?p0:Math.min(r,m0)}function I0(r){if(!r||r==="."||r==="/")return".";let e=r.split(/[/\\]/);return e[e.length-1]||"."}function Us(r){return r.split(Fs).join("/")}K();var Ct=N("agent-health-reporter"),D0=1e4,tn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??D0}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()}),Ct.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ct.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ct.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Ct.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let i=[];for(let x of this.opts.core.agents.values()){let u=T0(x);u&&i.push({agentId:x.agentId,status:u})}if(i.length===0)return;let a={agents:i,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",a)}catch(x){Ct.warn("heartbeat batch send failed",{count:i.length,err:String(x)})}}finally{this.inFlight=!1}}};function T0(r){return r.status==="error"?"error":r.activeTriggers.size>0?"busy":r.status==="ok"?"online":null}Ue();import{mkdir as lr,rm as j0}from"node:fs/promises";import{spawn as B0}from"node:child_process";function At(r,e,i){return i===void 0?{jsonrpc:"2.0",id:r,method:e}:{jsonrpc:"2.0",id:r,method:e,params:i}}function nn(r,e){return e===void 0?{jsonrpc:"2.0",method:r}:{jsonrpc:"2.0",method:r,params:e}}function xt(r,e){return{jsonrpc:"2.0",id:r,result:e}}function Ye(r,e){return{jsonrpc:"2.0",id:r,error:e}}var rn=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)}},j={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 Ks(r){return"method"in r&&"id"in r&&r.id!==void 0}function Hs(r){return"method"in r&&!("id"in r)}function sn(r){return!("method"in r)&&"id"in r}var L0={AGENT_NOT_FOUND:j.AGENT_NOT_FOUND,AGENT_BUSY:j.AGENT_BUSY,AGENT_DISCONNECTED:j.AGENT_DISCONNECTED,AGENT_TIMEOUT:j.AGENT_TIMEOUT,AGENT_SPAWN_FAILED:j.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:j.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:j.INTERNAL_ERROR,BRIDGE_INTERNAL:j.INTERNAL_ERROR,IPC_AUTH_FAILED:j.INTERNAL_ERROR,IPC_BAD_REQUEST:j.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:j.MODEL_TOKEN_GEN_FAILED,OPERATION_NOT_ALLOWED_FOR_LOCAL:j.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:j.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:j.INTERNAL_ERROR};function on(r){return r instanceof E?{code:L0[r.code]??j.INTERNAL_ERROR,message:r.message,data:{bridgeCode:r.code,retriable:r.retriable}}:{code:j.INTERNAL_ERROR,message:r instanceof Error?r.message:String(r)}}function Gs(r){let e=r.data,i=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new E(i,r.message,{retriable:e?.retriable??!1,cause:r.data})}function js(r){return`${JSON.stringify(r)}
90
- `}var an=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let i=this.buffer.split(`
91
- `);this.buffer=i.pop()??"";let a=[];for(let x of i){let u=x.replace(/\r$/,"").trim();if(u)try{a.push(JSON.parse(u))}catch(d){this.onError?.({line:u,error:d})}}return a}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(i){return this.onError?.({line:e,error:i}),[]}}};var Js={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},od=Object.fromEntries(Object.entries(Js).map(([r,e])=>[e,r])),R0={"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:[]},ut=class{seq=0;next(e,i){this.seq+=1;let a=Js[e]??N0(e),x=R0[a]??[],u=[a,String(this.seq)];if(x.length>0){let d=x.map(m=>Ws(i?.[m]??"")),h=O0(d).join(":");h&&u.push(h)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>Ws(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function N0(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Ws(r){return r.replace(/[:_\s]+/g,"-")}function O0(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}K();var M0=3e4;function Vs(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var Ke=class{constructor(e){this.opts=e;this.log=N(`downstream.${this.constructor.name}`),this.decoder=new an({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=B0(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 u of this.exitHandlers)u(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(u=>i.once("exit",()=>u()));Vs(i.pid,"SIGTERM");let x=setTimeout(()=>{i.killed||Vs(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(nn("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(xt(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=M0){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let x=this.idAllocator.next(e),u=At(x,e,i),d=a>0&&Number.isFinite(a);return new Promise((h,m)=>{let w=d?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:w,method:e});try{this.writeFrame(u)}catch(b){w&&clearTimeout(w),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(js(e))}dispatch(e){if(sn(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(Hs(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(Ks(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,on(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var z0="@agentclientprotocol/claude-agent-acp@latest";function F0(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 cn=class extends Ke{framework="claude-code";constructor(e){let i=e.command??"npx",a=e.args??["-y",z0],x={command:i,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(x)}sanitizeEnv(e){return F0(e)}};import{mkdtempSync as q0,rmSync as U0}from"node:fs";import{tmpdir as K0}from"node:os";import{join as H0}from"node:path";var G0="@zed-industries/codex-acp@latest",xn=class extends Ke{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=e.command??"npx",a=e.args??["-y",G0],x=e.extraArgs?[...a,...e.extraArgs]:a,u=e.isolateCodexHome?q0(H0(K0(),"coze-bridge-codex-home-")):void 0,d=u?{...e.env??{},CODEX_HOME:u}:e.env,h={command:i,args:x,cwd:e.cwd,...d?{env:d}:{}};super(h),this.authMethodId=e.authMethodId,this.codexHomeDir=u}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{U0(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};import{spawn as Ys}from"node:child_process";K();var un=class extends Ke{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}`],u={command:e.command,args:x,cwd:e.cwd,...e.env?{env:e.env}:{}};super(u),this.profile=i,this.agentId=e.agentId,this.sessionName=a,this.registerLog=N("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=Ys(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",u=>{x+=u.toString("utf8")}),a.on("error",i),a.on("close",u=>{u===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 ${u}: ${x.trim()}`))})})}async cleanup(e){this.registered&&await new Promise(i=>{let a=Ys(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",u=>{x+=u.toString("utf8")}),a.on("error",u=>{this.registerLog.warn("openclaw agents delete failed (best-effort)",{agentId:this.agentId,err:String(u)}),i()}),a.on("close",u=>{u===0?this.registerLog.info("agent unregistered",{agentId:this.agentId}):this.registerLog.warn("openclaw agents delete non-zero exit",{agentId:this.agentId,code:u,stderr:x.trim()}),this.registered=!1,i()})})}get acpSessionName(){return this.sessionName}};K();ae();var fn=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 dn=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 fn}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)kt(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function kt(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}var He=N("agent-manager"),W0=(r,e,i,a,x,u)=>{switch(r){case"claude-code":{let d=x?Ls(x):void 0;return new cn({cwd:i,...d&&Object.keys(d).length>0?{env:d}:{}})}case"codex":{let d=x?Rs(x):[],h=x?Ns(x):void 0,m=!!x;return new xn({cwd:i,...d.length>0?{extraArgs:d}:{},...h&&Object.keys(h).length>0?{env:h}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new un({command:e,cwd:i,agentId:a,...u?{sessionName:Qt(u)}:{}})}};function J0(r){return r==="claude-code"||r==="codex"}var V0={path:"",version:"cloud-deployed"},Y0={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},$0=2e4,ln=class{paths;config;registry;factory;createTimeoutMs;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??W0,this.createTimeoutMs=e.createTimeoutMs??$0}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=Et(e._meta)==="cloud";if(i&&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 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")He.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(_=>He.warn("dispose stale agent failed (ignored)",{err:String(_)})),this.registry.unregister(e.agentId);else return He.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),u=e.workspace??x.workspace,d=Et(e._meta),h=new AbortController,m=setTimeout(()=>h.abort(new E("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),w,b=!1;try{let _=()=>{if(h.signal.aborted)throw h.signal.reason instanceof Error?h.signal.reason:new E("AGENT_TIMEOUT","_agent/create aborted")};await lr(x.root,{recursive:!0}),await lr(u,{recursive:!0}),await lr(x.logs,{recursive:!0}),_(),await ot(u,e.framework,e.agentId,e.cozeIdentity),_();let C=await ce(e.agentId,this.paths).catch(()=>null),L=Ds({model:e.model??C?.model});if(w=new dn({agentId:e.agentId,framework:e.framework,workspace:u,model:L.model??ct,deployType:d}),w.status="ok",C?.sessions){for(let[z,ee]of Object.entries(C.sessions))w.sessions.set(z,{acpSessionId:ee.acpSessionId,modelToken:ee.modelToken,tokenGeneratedAt:ee.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1});let R=Object.keys(C.sessions).length;R>0&&He.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:R})}this.registry.register(w),b=!0;let I={agentId:e.agentId,framework:e.framework,workspace:u,cozeIdentity:e.cozeIdentity,createdAt:C?.createdAt??Date.now(),sessions:C?.sessions??{},model:L.model};return d==="cloud"&&(I.deployType="cloud"),C?.skills&&(I.skills=C.skills),C?.agentName&&(I.agentName=C.agentName),C?.description&&(I.description=C.description),await me(I,this.paths),He.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:d}),{ok:!0,agentId:e.agentId,workspace:u,framework:e.framework}}catch(_){throw He.error("agent create failed, rolling back",{agentId:e.agentId,err:String(_)}),b&&w&&(await w.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await j0(x.root,{recursive:!0,force:!0}).catch(C=>He.warn("rm agent dir failed (ignored)",{err:String(C)})),_ instanceof E?_:new E("AGENT_SPAWN_FAILED",String(_),{cause:_})}finally{clearTimeout(m)}}async spawnSessionDownstream(e,i,a){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&J0(e.framework))u=V0;else throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let d=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,h=this.factory(e.framework,u.path,e.workspace,e.agentId,d,a);try{return await h.start(),await h.initialize(Y0),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 Q0}from"node:child_process";import{constants as $s,access as X0}from"node:fs/promises";import{delimiter as Z0,join as ec}from"node:path";var tc=N("framework-detector"),Qs={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},nc=[".exe",".cmd",".bat",".ps1"],Pt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Q0,access:e.access??X0}}async detect(e){let i=Qs[e],a=await this.which(i);if(!a)return tc.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(Qs).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(Z0).filter(Boolean),a=this.env.platform==="win32"?["",...nc]:[""];for(let x of i)for(let u of a){let d=ec(x,e+u);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?$s.F_OK:$s.X_OK;return await this.env.access(e,i),!0}catch{return!1}}async probeVersion(e){return new Promise(i=>{let a="",x=!1,u,d=h=>{x||(x=!0,u&&clearTimeout(u),i(h.trim()||"unknown"))};try{let h=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});u=setTimeout(()=>{h.kill("SIGKILL"),d("unknown")},5e3),h.stdout?.on("data",m=>{a+=m.toString("utf8")}),h.on("error",()=>d("unknown")),h.on("close",()=>{let m=sc(a).split(/\r?\n/)[0]??"";d(m)})}catch{d("unknown")}})}},rc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function sc(r){return r.replace(rc,"")}xr();ae();var ic=10*6e4;function Xs(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ic:e}function hn(r){return Ht(r??H().configFile)}function It(r,e){return Gt(e??H().configFile,r)}import{randomBytes as oc}from"node:crypto";Ue();K();var W=N("core"),ac=3e4,cc=3e4,gn=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=Xs(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(u=>{a.loadingSession||this.forwardUpdate(e,u)}),x.onAgentRequest(u=>{this.handleAgentRequest(e,x,u)}),x.onExit((u,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),kt(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(sn(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,j.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(xt(i,x));return}if(e.method.startsWith("session/")){let a=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(xt(i,a));return}if(e.method==="initialize"){i!==null&&await this.upstream.send(xt(i,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}i!==null?await this.sendError(i,j.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,on(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 u=Date.now(),d=!1;try{let h=await x.msgQueue.enqueue(()=>this.dispatchSessionCall(x,e.method,i));return d=!0,h}finally{W.info("session call done",{agentId:x.agentId,method:e.method,durationMs:Date.now()-u,ok:d})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:x}=Ps(a);switch(i){case"session/new":{let u=xc();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=x;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=x,d=u.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/prompt: missing sessionId");let h=await this.ensureRuntime(e,d);if(await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new E("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let m=a._meta?.cozeTriggerMsgId;m?e.activeTriggers.set(h.acpSessionId,m):e.activeTriggers.delete(h.acpSessionId);try{let w=await h.downstream.sessionPrompt({...u,sessionId:h.acpSessionId});return h.lastActiveAt=Date.now(),w}finally{e.activeTriggers.delete(h.acpSessionId),h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=x.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/cancel: missing sessionId");let h=e.sessions.get(d);return h?.downstream?.isAlive()&&h.acpSessionId&&await h.downstream.sessionCancel({sessionId:h.acpSessionId}),{ok:!0}}default:throw new E("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1};return e.sessions.set(i,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let x=await this.sendRequest(Se.GEN_MODEL_TOKEN,a,cc);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(kt(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(u){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(u)}),a.acpSessionId=void 0;let d=await x.sessionNew({cwd:e.workspace});a.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let u=await x.sessionNew({cwd:e.workspace});a.acpSessionId=u.sessionId,await this.persistSessionMapping(e)}}armIdleTimer(e,i,a){kt(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(u=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(u)}))},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 u={cozeAgentId:e.agentId},d=e.activeTriggers.get(a);d&&(u.cozeTriggerMsgId=d),this.upstream.send(nn("session/update",{...i,sessionId:x,_meta:u})).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:j.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}forwardPermissionRequest(e,i,a){let x=this.upstreamIds.next("session/request_permission"),u=a.params??{},h=u.sessionId,m=h?e.activeTriggers.get(h):void 0,w={cozeAgentId:e.agentId};m&&(w.cozeTriggerMsgId=m);let b=h?this.reverseSessionId(e,h):void 0,_={...u,...b?{sessionId:b}:{},_meta:w};this.pendingUpstream.set(x,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),this.upstream.send(At(x,"session/request_permission",_)).catch(C=>{this.pendingUpstream.delete(x),W.error("forward permission request failed",{agentId:e.agentId,err:String(C)}),i.respondAgentRequestError(a.id,{code:j.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 rn(e.error)):a.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=ac){let x=this.upstreamIds.next(e);return new Promise((u,d)=>{let h=setTimeout(()=>{this.pendingBridge.delete(x),d(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(x,{method:e,resolve:u,reject:d,timer:h}),this.upstream.send(At(x,e,i)).catch(m=>{let w=this.pendingBridge.get(x);w&&(clearTimeout(w.timer),this.pendingBridge.delete(x)),d(m)})})}async persistSessionMapping(e){if(this.paths)try{let i=new Map;for(let[a,x]of e.sessions){let u={modelToken:x.modelToken,tokenGeneratedAt:x.tokenGeneratedAt};x.acpSessionId&&(u.acpSessionId=x.acpSessionId),i.set(a,u)}await fr(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 xc(){return oc(16).toString("hex")}K();ae();import{randomBytes as uc}from"node:crypto";import{chmod as fc,mkdir as dc,writeFile as Zs}from"node:fs/promises";import{createServer as lc}from"node:http";import{dirname as hc}from"node:path";var gc=1e6,hr=N("ipc"),pn=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=uc(32).toString("hex");let e=lc((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(),hr.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 dc(hc(this.paths.portFile),{recursive:!0}),await Zs(this.paths.portFile,String(this.port),"utf8"),await Zs(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await fc(this.paths.tokenFile,384)}catch(e){hr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Dt(i,401,{error:"unauthorized"});return}let x=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(x);if(!u){Dt(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await pc(e)}catch(h){Dt(i,400,{error:"invalid json",detail:String(h)});return}try{let h=await u.handler(d,e);Dt(i,200,h??{ok:!0})}catch(h){hr.error("IPC handler failed",{key:x,err:String(h)}),Dt(i,500,{error:h instanceof Error?h.message:String(h)})}}};function Dt(r,e,i){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(i))}async function pc(r){let e=[],i=0;for await(let x of r){let u=x;if(i+=u.length,i>gc)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var Ao=De(ui(),1);var Qx=De(io(),1),Xx=De(Ln(),1),Zx=De(lt(),1),eu=De(kr(),1),tu=De(Dr(),1),nu=De(Br(),1),go=De(Bn(),1),ru=De(ho(),1);var po=go.default;K();var zn="1008033",mo="1289";var wo="pbbp2",_o="https://www.coze.cn",yo="/api/coze_claw/resource/get_frontier_key",su="https://www.coze.cn",iu="wss://frontier.coze.cn";function bo(r){return r??process.env.COZE_BRIDGE_HANDSHAKE_URL??su}function vo(r){return r??process.env.COZE_BRIDGE_FRONTIER_URL??iu}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 ne=N("upstream.frontier"),Eo="application/json",Co="none",qn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:_o,...Fn(this.opts.ppeOverride)};class i extends po{constructor(h){super(h,wo,{headers:e})}send(h,...m){if(As("debug"))try{let w;typeof h=="string"?w=Buffer.from(h,"utf8"):h instanceof Buffer?w=h:h instanceof ArrayBuffer?w=new Uint8Array(h):ArrayBuffer.isView(h)?w=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):w=new Uint8Array(0);let b=Buffer.from(w.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:w.byteLength,headHex:b})}catch(w){ne.warn("WS raw frame dump failed",{err:String(w)})}super.send(h,...m)}}let a=vo(this.opts.urlOverride),x={url:a,ws:i,fpID:mo,aID:zn,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Eo,force:!0},payloadEncoding:{encoding:Co,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new Ao.FWS(x);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;ne.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:d,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:d})).catch(h=>ne.warn("onConnect handler threw (ignored)",{err:String(h)}))},u.onclose=d=>{this.opened=!1,ne.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{ne.warn("frontier error",{code:d.code,msg:d.message})},u.onmessage=d=>this.handleMessage(d),this.fws=u,await u.connect()}async stop(e){let i=this.fws;if(i){this.fws=null,this.opened=!1;try{i.close(1e3,e??"bridge shutdown")}catch(a){ne.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new E("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),x=e;ne.info("frontier frame out",{method:x.method,jsonrpcId:x.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:Eo,payloadEncoding:Co})}catch(u){throw new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){ne.debug("drop non-adapter frontier frame",{service:i});return}let a=cu(e);if(!a){ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ne.debug("frame received but no onFrame handler",{size:a.length});return}let x;try{x=JSON.parse(a)}catch(u){ne.warn("frontier message JSON parse failed",{err:String(u),head:a.slice(0,80)});return}ne.info("frontier frame in",{logid:au(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:x.id}),Promise.resolve(this.handler(x)).catch(u=>ne.warn("frontier frame handler threw",{err:String(u)}))}};function au(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function cu(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 ko=N("handshake");async function Io(r){let e=bo(r.endpoint),i=r.timeoutMs??1e4,a=`${xu(e)}${yo}?aid=${encodeURIComponent(zn)}`,x={Authorization:`Bearer ${r.privatecode}`,Accept:"application/json",...Fn(r.ppeOverride)},u=new AbortController,d=setTimeout(()=>u.abort(),i);ko.info("frontier key handshake",{base:e});try{let h=await fetch(a,{method:"GET",headers:x,signal:u.signal}),m=h.headers.get("x-tt-logid")??"",w=h.headers.get("x-tt-trace-id")??"";if(!h.ok){let L=await h.text().catch(()=>"");throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${h.status} logid=${m}: ${L.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 _=b.data?.access_key,C=b.data?.device_id;if(!_||!C)throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${m}: ${JSON.stringify(b)}`);return ko.info("handshake ok",{remoteDeviceId:C,logid:m,traceId:w}),{accessKey:_,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(d)}}function xu(r){return r.endsWith("/")?r.slice(0,-1):r}K();var zr=N("upstream.switchable"),Un=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;zr.info("swap upstream",{reason:i});let a=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(x){throw zr.error("swap target start failed, reverting",{err:String(x)}),this.inner=a,x}await a.stop(i??"swapped").catch(x=>zr.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=N("upstream"),Ft=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();ae();K();ae();import{execSync as uu}from"node:child_process";import{readFileSync as Do,unlinkSync as fu}from"node:fs";import{mkdir as du,readFile as To,unlink as Lo,writeFile as lu}from"node:fs/promises";import{dirname as hu}from"node:path";var gu=N("single-instance"),Kn=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&&(gu.warn("removing stale pid file",{stalePid:e}),await Lo(this.pidFile).catch(()=>{})),await du(hu(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 To(this.pidFile,"utf8")).trim()===String(process.pid)&&await Lo(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await To(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=Do(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=uu(`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{Do(this.pidFile,"utf8").trim()===String(process.pid)&&fu(this.pidFile)}catch{}})}};var B=N("daemon"),pu="coze-bridge-daemon";async function Oo(){let r=new Kn({processTitle:pu}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await hn(),a=i??{};ur({pid:process.pid}),B.info(i?"loaded bridge config":"initialized bridge config");try{let D=new Pt;a.frameworksCache=await D.detectAll(),B.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(D){B.warn("framework detection failed",{err:String(D)})}await It(a);let x=new Un(new Ft),u=H(),d=null,h=new gn({upstream:x,paths:u,bridgeConfig:a,sessionSpawner:async(D,q,V)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(D,q,V)}});await wu(u,h);let m=new ln({paths:u,config:a,registry:h});d=m;let w,b,_=null,C=null;h.registerExtension("_agent/create",async D=>m.createAgent(D.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let L={},I=new Zt({agents:h.agents,disposeAndMarkDisconnected:async(D,q)=>{let V=h.agents.get(D);V&&(await V.dispose(`disconnect: ${q}`).catch(he=>B.warn("dispose during disconnect failed (ignored)",{agentId:D,err:String(he)})),V.status="disconnected",h.unregister(D)),h.disconnectedAgents.add(D)},detailSyncer:async D=>{if(!L.ref)throw new Error("agent-detail-sync not initialized yet");await L.ref.syncOne(D)}});h.registerExtension("_agent/listSkills",D=>I.listSkills(D.params)),h.registerExtension("_agent/addSkills",D=>I.addSkills(D.params)),h.registerExtension("_agent/removeSkills",D=>I.removeSkills(D.params)),h.registerExtension("_agent/getFileTree",D=>I.getFileTree(D.params)),h.registerExtension("_agent/getFileContent",D=>I.getFileContent(D.params)),h.registerExtension("_agent/update",D=>I.updateAgent(D.params)),h.registerExtension("_agent/disconnect",D=>I.disconnectAgent(D.params)),h.registerExtension("_agent/switchModel",D=>I.switchModel(D.params)),h.registerExtension("_agent/reset",D=>I.resetAgent(D.params)),h.registerExtension("_agent/repair",D=>I.repairAgent(D.params));let R=new $t({paths:u,handlers:I,sendDetail:D=>h.sendRequest("_agent/detail",D)});L.ref=R,x.onConnect(({initial:D})=>{B.info("frontier upstream connected, triggering detail sync",{initial:D}),R.syncAll(D?"initial-connect":"reconnect").catch(q=>B.warn("detail sync top-level error (ignored)",{err:String(q)}))});let z=new pn({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...h.agents.keys()],deviceId:_??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async D=>{let q=D,V=q?.privatecode,he=q?.pairing_code;if(!V||!he)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ke=Po(q.env),ge=q.handshake_url,Je=q.frontier_url,yt=mu(q.env,ge,Je),qt=!!w&&w!==V,ye=b!==void 0&&b!==yt,be=qt||ye;if(be){B.warn("pair config switched, resetting agents",{pcChanged:qt,envChanged:ye,previousPc:w?Ro(w):"",nextPc:Ro(V),previousEnvKey:b??"",nextEnvKey:yt});for(let U of[...h.agents.values()])await U.dispose("pair config switch").catch(()=>{}),h.agents.delete(U.agentId);await x.swap(new Ft,"pair switch").catch(()=>{})}let Ut=await Io({privatecode:V,...ge?{endpoint:ge}:{},ppeOverride:ke});_=Ut.deviceId,ur({deviceId:_,pid:process.pid});let re=new qn({handshake:Ut,privatecode:V,...Je?{urlOverride:Je}:{},ppeOverride:ke});await x.swap(re,"pair");let Kt=Object.keys(a.frameworksCache??{});try{let U=await h.sendRequest("_agent/pair",{pairCode:he,patToken:V,frameworks:Kt,_meta:{cozeDeviceId:_}});B.info("_agent/pair ok",{pairResult:U}),w=V,b=yt,C||(C=new tn({core:h,getDeviceId:()=>_??""})),C.start(),be&&No(u,m).catch(Pe=>B.warn("post-pair-switch auto-revive error (ignored)",{err:String(Pe)}));let J;return q.agent_id&&(J=await _u(q.agent_id,u,m,Pe=>h.sendRequest("_agent/detail",Pe)).catch(Pe=>(B.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(Pe)}),{ok:!1,agentId:q.agent_id??"",note:String(Pe)}))),{ok:!0,note:"paired with cloud",...J?{agent:J}:{}}}catch(U){return B.error("_agent/pair failed",{err:String(U)}),{ok:!1,note:`pair failed: ${String(U)}`}}}},{method:"POST",path:"/_agent/create",handler:async D=>{let q=D;return{ok:!0,result:await m.createAgent(q)}}},{method:"POST",path:"/refresh",handler:async()=>{B.info("IPC /refresh: re-detecting frameworks");let D=new Pt;return a.frameworksCache=await D.detectAll(),await It(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(B.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ee,token:le}=await z.start();await h.start(),No(u,m).catch(D=>B.warn("auto-revive top-level error (ignored)",{err:String(D)}));let _e=null,oe={port:ee,token:le,core:h,ipc:z,shutdown(D){return _e||(B.info("daemon shutdown",{reason:D}),_e=(async()=>{C?.stop(),await h.stop(D),await z.stop(),await r.release()})(),_e)}};for(let D of["SIGTERM","SIGINT"])process.on(D,()=>{oe.shutdown(D).then(()=>process.exit(0))});return B.info("daemon ready",{port:ee,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),oe}function Ro(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function mu(r,e,i){return`${r??""}|${e??""}|${i??""}`}async function wu(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.agentsRoot)}catch{return}let{loadAgentConfig:x,enforceAgentConfigMode:u}=await Promise.resolve().then(()=>(Ue(),Yt));for(let d of a){await u(d,r).catch(h=>B.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(h)}));try{let h=await x(d,r);h?.disconnectedAt&&(e.disconnectedAgents.add(d),B.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:h.disconnectedAt,reason:h.disconnectReason??""}))}catch(h){B.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(h)})}}}async function _u(r,e,i,a){let{loadAgentConfig:x}=await Promise.resolve().then(()=>(Ue(),Yt)),u=await x(r,e);if(u){B.info("--agent-id: local config found, reconnecting",{agentId:r,framework:u.framework,hadDisconnect:!!u.disconnectedAt});let w={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{}};return await i.createAgent(w),{ok:!0,agentId:r,note:u.disconnectedAt?"revived from local config":"connected from local config"}}B.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let d=await a({_meta:{cozeAgentId:r}});if(!d.framework)throw new E("AGENT_NOT_FOUND",`agent ${r} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let h={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...d.deployType?{_meta:{cozeDeployType:d.deployType}}:{}};await i.createAgent(h);let m=d.deployType==="cloud"&&d.framework==="openclaw";return{ok:!0,agentId:r,note:m?"cloud agent acknowledged":"created from cloud detail"}}async function No(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(),Yt));B.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,d=0;for(let h of a){let m;try{m=await x(h,r)}catch(w){B.warn("auto-revive: load config failed (skipping)",{agentId:h,err:String(w)}),d+=1;continue}if(!m){d+=1;continue}if(m.disconnectedAt){B.info("auto-revive: skip disconnected agent",{agentId:h,disconnectedAt:m.disconnectedAt}),d+=1;continue}try{B.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:h,framework:m.framework}),await e.createAgent({agentId:m.agentId,framework:m.framework,...m.cozeIdentity?{cozeIdentity:m.cozeIdentity}:{},...m.model?{model:m.model}:{},...m.deployType?{_meta:{cozeDeployType:m.deployType}}:{}}),u+=1}catch(w){B.warn("auto-revive: createAgent failed (skipping)",{agentId:h,framework:m.framework,err:String(w)}),d+=1}}return B.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}Ur();ae();import{readFile as Mo}from"node:fs/promises";var We=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:Pu(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([Mo(this.paths.portFile,"utf8"),Mo(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 u=new AbortController,d=setTimeout(()=>u.abort(),i.timeoutMs??5e3);try{let h=await fetch(`http://127.0.0.1:${e.port}${i.path}`,{method:i.method,headers:x,body:a?JSON.stringify(i.body):void 0,signal:u.signal}),m=await h.text();return{status:h.status,body:ku(m)}}finally{clearTimeout(d)}}};function ku(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Pu(r){return r instanceof Error?r.message:String(r)}K();ae();import{copyFile as zo,mkdir as Iu,readFile as Kr,writeFile as Du}from"node:fs/promises";import{dirname as Tu,resolve as Hr,sep as Hn}from"node:path";import{fileURLToPath as Lu}from"node:url";K();ae();var Fo=N("dist-install");function Ru(r){let e=Lu(r),i=Tu(e),a=`${Hn}src${Hn}`;if(i.includes(a)||i.endsWith(`${Hn}src${Hn}cli`))return null;let x=Hr(i,"index.js"),u=Hr(i,"..","package.json");return{dist:x,pkgJson:u}}async function qo(r={}){let e=r.paths??H(),i=Ru(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 u;try{u=JSON.parse(await Kr(x,"utf8")).version??"unknown"}catch(_){return Fo.warn("cannot read source package.json,skip dist install",{err:String(_)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(_)}`}}let d=await hn(e.configFile)??{},h=d.libVersion;if(h===u)try{return await Kr(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await Iu(e.libDir,{recursive:!0}),await zo(a,e.libEntry),await zo(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let m=Hr(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
92
- `;return await Kr(m,"utf8").catch(()=>null)!==w&&await Du(m,w),d.libVersion=u,await It(d,e.configFile),Fo.info("dist installed",{libEntry:e.libEntry,fromVersion:h,toVersion:u}),h?{kind:"version-changed",fromVersion:h,toVersion:u,libEntry:e.libEntry}:{kind:"first-install",libVersion:u,libEntry:e.libEntry}}var Xu=N("cli");function _t(r,e){let i=[],a;for(let x=0;x<r.length;x++){let u=r[x];if(u===e){a=r[x+1],x+=1;continue}if(u.startsWith(`${e}=`)){a=u.slice(e.length+1);continue}i.push(u)}return{value:a,rest:i}}function Zu(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}=_t(i,"--pat-token");i=x;let{value:u,rest:d}=_t(i,"--pair-code");i=d;let{value:h,rest:m}=_t(i,"--env");i=m;let{value:w,rest:b}=_t(i,"--handshake-url");i=b;let{value:_,rest:C}=_t(i,"--frontier-url");i=C;let{value:L}=_t(i,"--agent-id");if(!a||!u)return{mode:"help"};let I={mode:"pair",privatecode:a,pairingCode:u};return h&&(I.env=h),w&&(I.handshakeUrl=w),_&&(I.frontierUrl=_),L&&(I.agentId=L),I}var ef=`
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 Wo(r=process.argv,e={}){let i=Zu(r);switch(i.mode){case"help":return process.stdout.write(ef),0;case"daemon":{try{await Oo()}catch(a){return Xu.error("daemon start failed",{err:String(a)}),1}return new Promise(()=>{})}case"status":return tf(e);case"stop":return nf(e);case"refresh":return rf(e);case"uninstall":return sf(e);case"install-service":return of();case"pair":{let a={};return i.env&&(a.env=i.env),i.handshakeUrl&&(a.handshakeUrl=i.handshakeUrl),i.frontierUrl&&(a.frontierUrl=i.frontierUrl),af(i.privatecode,i.pairingCode,e,a,i.agentId)}}}async function Jo(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 tf(r){let e=r.paths??H(),i=new We(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
120
- `),1;if(a.kind==="stale")return await Jo(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
121
- `),1;let x=await i.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
122
- ${JSON.stringify(x.body,null,2)}
123
- `),0}async function nf(r){let e=r.paths??H(),i=new We(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
124
- `),0;if(a.kind==="stale")return await Jo(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
125
- `),0;try{return await i.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
126
- `),0}catch(x){return process.stdout.write(`coze-bridge: stop failed: ${String(x)}
127
- `),1}}async function rf(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)
128
- `),1;try{let a=await e.request({method:"POST",path:"/refresh"});return a.status===200?(process.stdout.write(`coze-bridge: refreshed
129
- ${JSON.stringify(a.body,null,2)}
130
- `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(a.body)}
131
- `),1)}catch(a){return process.stderr.write(`coze-bridge: refresh failed: ${String(a)}
132
- `),1}}async function sf(r){let e=new We(r.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
133
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(u){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(u)}
134
- `)}await new Promise(u=>setTimeout(u,500))}if(!r.skipSupervisor)try{let{getSupervisor:u,buildContext:d}=await Promise.resolve().then(()=>($r(),Yr)),h=u();await h.uninstall(d()),process.stdout.write(`coze-bridge: ${h.platform} supervisor unregistered
135
- `)}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
136
- `)}let a=r.paths??H(),{rm:x}=await import("node:fs/promises");try{await x(a.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${a.cozeRoot}
137
- `)}catch(u){return process.stderr.write(`coze-bridge: remove failed: ${String(u)}
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 of(){try{let{getSupervisor:r,buildContext:e}=await Promise.resolve().then(()=>($r(),Yr)),i=r(),a=e();return process.stdout.write(`coze-bridge: installing ${i.platform} supervisor...
140
- `),await i.install(a),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
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 af(r,e,i,a={},x){let u=new We(i.paths),d=i.spawnDaemon??Bo;if(!i.skipDistInstall){let w=await qo({paths:i.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
143
- `),(await u.probe()).kind==="connected"&&(await u.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
144
- `)}let h=await u.probe();if(h.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
145
- `),await d({paths:i.paths}),h=await cf(u,i.waitTimeoutMs??1e4,i.sleep??xf),h.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
146
- `),1;let m={privatecode:r,pairing_code:e};a.env&&(m.env=a.env),a.handshakeUrl&&(m.handshake_url=a.handshakeUrl),a.frontierUrl&&(m.frontier_url=a.frontierUrl),x&&(m.agent_id=x);try{let w=await u.request({method:"POST",path:"/pair",body:m,timeoutMs:35e3});return w.status===200&&w.body?.ok?(process.stdout.write(`coze-bridge: paired (${w.body.note??"ok"})
147
- `),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
148
- `),1)}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
149
- `),1}}async function cf(r,e,i){let a=Date.now()+e;for(;Date.now()<a;){let x=await r.probe(500);if(x.kind==="connected")return x;await i(200)}return r.probe(500)}function xf(r){return new Promise(e=>setTimeout(e,r))}Wo(process.argv).then(r=>process.exit(r),r=>{process.stderr.write(`fatal: ${r instanceof Error?r.stack??r.message:String(r)}
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)});