coze-bridge 0.1.27 → 0.1.29

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 +66 -64
  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 sa=Object.create;var Dn=Object.defineProperty;var ia=Object.getOwnPropertyDescriptor;var oa=Object.getOwnPropertyNames;var aa=Object.getPrototypeOf,ca=Object.prototype.hasOwnProperty;var P=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Q=(n,e)=>()=>(n&&(e=n(n=0)),e);var F=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ln=(n,e)=>{for(var t in e)Dn(n,t,{get:e[t],enumerable:!0})},da=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oa(e))!ca.call(n,s)&&s!==t&&Dn(n,s,{get:()=>e[s],enumerable:!(r=ia(e,s))||r.enumerable});return n};var ue=(n,e,t)=>(t=n!=null?sa(aa(n)):{},da(e||!n||!n.__esModule?Dn(t,"default",{value:n,enumerable:!0}):t,n));import{chmod as la,mkdir as ua,readFile as fa,rename as rs,writeFile as ss}from"node:fs/promises";import{dirname as ha}from"node:path";async function De(n){try{let e=await fa(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function It(n,e,t){await ua(ha(n),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
9
- `,s=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{t?.mode!==void 0?await ss(s,r,{encoding:"utf8",mode:t.mode}):await ss(s,r,"utf8"),await rs(s,n),t?.mode!==void 0&&await la(n,t.mode)}catch(i){await rs(s,s).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(s,{force:!0}).catch(()=>{}),i}}var Tt=Q(()=>{"use strict"});function as(n){return Pt[is]<=Pt[n]}function Mn(n){os={...n}}function Rt(n,e,t,r){if(Pt[n]<Pt[is])return;let s=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:t,...os,...r});n==="error"||n==="warn"?pa.write(`${s}
10
- `):ga.write(`${s}
11
- `)}function w(n){return{debug:(e,t)=>Rt("debug",n,e,t),info:(e,t)=>Rt("info",n,e,t),warn:(e,t)=>Rt("warn",n,e,t),error:(e,t)=>Rt("error",n,e,t),child:e=>w(`${n}.${e}`)}}var Pt,is,ga,pa,os,k=Q(()=>{"use strict";Pt={debug:10,info:20,warn:30,error:40},is=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),ga=process.stdout,pa=process.stderr,os={}});import{homedir as ma}from"node:os";import{join as N}from"node:path";function T(n){let e=n??ma(),t=N(e,".coze"),r=N(t,"bridge"),s=N(r,"lib");return{cozeRoot:t,bridgeRoot:r,libDir:s,libEntry:N(s,"index.js"),pidFile:N(r,"bridge.pid"),portFile:N(r,"bridge.port"),tokenFile:N(r,"bridge.token"),logFile:N(r,"bridge.log"),installLock:N(r,"install.lock"),configFile:N(r,"config.json"),agentsRoot:N(t,"agents")}}function se(n,e=T()){let t=N(e.agentsRoot,n);return{root:t,config:N(t,"config.json"),workspace:N(t,"workspace"),logs:N(t,"logs")}}var U=Q(()=>{"use strict"});var Ot={};Ln(Ot,{AGENT_CONFIG_FILE_MODE:()=>At,enforceAgentConfigMode:()=>ya,loadAgentConfig:()=>$,persistAgentSessions:()=>Bn,persistAgentSkills:()=>Ct,saveAgentConfig:()=>K});import{chmod as _a,stat as wa}from"node:fs/promises";function $(n,e){return De(se(n,e).config)}function K(n,e){return It(se(n.agentId,e).config,n,{mode:At})}async function ya(n,e){if(process.platform==="win32")return;let t=se(n,e).config;try{let r=await wa(t);if(!r.isFile())return;let s=r.mode&511;s!==At&&(await _a(t,At),cs.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(r){if(r.code==="ENOENT")return;cs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(r)})}}async function Bn(n,e,t){let r=await $(n,t);r&&(r.sessions=Object.fromEntries(e),await K(r,t))}async function Ct(n,e,t){let r=await $(n,t);r&&(r.skills=e,await K(r,t))}var cs,At,fe=Q(()=>{"use strict";Tt();k();U();cs=w("agent-config"),At=384});function Yc(){return Xs||(Xs=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Zc(){return Ys||(Ys=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function ed(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(G(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Zs.set(t,n)}).catch(()=>{}),Vn.set(e,n),e}function td(n){if(jn.has(n))return;let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",o),n.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",o),n.addEventListener("abort",o)});jn.set(n,e)}function ti(n){Jn=n(Jn)}function nd(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let r=n.call(ut(this),e,...t);return ei.set(r,e.sort?e.sort():[e]),G(r)}:Zc().includes(n)?function(...e){return n.apply(ut(this),e),G(Zs.get(this))}:function(...e){return G(n.apply(ut(this),e))}}function rd(n){return typeof n=="function"?nd(n):(n instanceof IDBTransaction&&td(n),Xc(n,Yc())?new Proxy(n,Jn):n)}function G(n){if(n instanceof IDBRequest)return ed(n);if(Wn.has(n))return Wn.get(n);let e=rd(n);return e!==n&&(Wn.set(n,e),Vn.set(e,n)),e}var Xc,Xs,Ys,Zs,jn,ei,Wn,Vn,Jn,ut,Qn=Q(()=>{Xc=(n,e)=>e.some(t=>n instanceof t);Zs=new WeakMap,jn=new WeakMap,ei=new WeakMap,Wn=new WeakMap,Vn=new WeakMap;Jn={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return jn.get(n);if(e==="objectStoreNames")return n.objectStoreNames||ei.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return G(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};ut=n=>Vn.get(n)});var ri={};Ln(ri,{deleteDB:()=>id,openDB:()=>sd,unwrap:()=>ut,wrap:()=>G});function sd(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){let o=indexedDB.open(n,e),a=G(o);return r&&o.addEventListener("upgradeneeded",c=>{r(G(o.result),c.oldVersion,c.newVersion,G(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function id(n,{blocked:e}={}){let t=indexedDB.deleteDatabase(n);return e&&t.addEventListener("blocked",()=>e()),G(t).then(()=>{})}function ni(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Kn.get(e))return Kn.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,s=ad.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||od.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),d=c.store;return r&&(d=d.index(a.shift())),(await Promise.all([d[t](...a),s&&c.done]))[0]};return Kn.set(e,i),i}var od,ad,Kn,si=Q(()=>{Qn();Qn();od=["get","getKey","getAll","getAllKeys","count"],ad=["put","add","delete","clear"],Kn=new Map;ti(n=>({...n,get:(e,t,r)=>ni(e,t)||n.get(e,t,r),has:(e,t)=>!!ni(e,t)||n.has(e,t)}))});var ae=F((Rp,Ci)=>{"use strict";var Pi=["nodebuffer","arraybuffer","fragments"],Ai=typeof Blob<"u";Ai&&Pi.push("blob");Ci.exports={BINARY_TYPES:Pi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ai,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _t=F((Pp,an)=>{"use strict";var{EMPTY_BUFFER:ll}=ae(),yr=Buffer[Symbol.species];function ul(n,e){if(n.length===0)return ll;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new yr(t.buffer,t.byteOffset,r):t}function Oi(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ni(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function fl(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Sr(n){if(Sr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new yr(n):ArrayBuffer.isView(n)?e=new yr(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Sr.readOnly=!1),e}an.exports={concat:ul,mask:Oi,toArrayBuffer:fl,toBuffer:Sr,unmask:Ni};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=P("bufferutil");an.exports.mask=function(e,t,r,s,i){i<48?Oi(e,t,r,s,i):n.mask(e,t,r,s,i)},an.exports.unmask=function(e,t){e.length<32?Ni(e,t):n.unmask(e,t)}}catch{}});var Li=F((Ap,Di)=>{"use strict";var bi=Symbol("kDone"),Er=Symbol("kRun"),vr=class{constructor(e){this[bi]=()=>{this.pending--,this[Er]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Er]()}[Er](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bi])}}};Di.exports=vr});var Je=F((Cp,Ui)=>{"use strict";var wt=P("zlib"),Mi=_t(),hl=Li(),{kStatusCode:Bi}=ae(),gl=Buffer[Symbol.species],pl=Buffer.from([0,0,255,255]),dn=Symbol("permessage-deflate"),ce=Symbol("total-length"),We=Symbol("callback"),we=Symbol("buffers"),je=Symbol("error"),cn,kr=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!cn){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;cn=new hl(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[We];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){cn.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){cn.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[dn]=this,this._inflate[ce]=0,this._inflate[we]=[],this._inflate.on("error",_l),this._inflate.on("data",Fi)}this._inflate[We]=r,this._inflate.write(e),t&&this._inflate.write(pl),this._inflate.flush(()=>{let i=this._inflate[je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Mi.concat(this._inflate[we],this._inflate[ce]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ce]=0,this._inflate[we]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?wt.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ce]=0,this._deflate[we]=[],this._deflate.on("data",ml)}this._deflate[We]=r,this._deflate.write(e),this._deflate.flush(wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Mi.concat(this._deflate[we],this._deflate[ce]);t&&(i=new gl(i.buffer,i.byteOffset,i.length-4)),this._deflate[We]=null,this._deflate[ce]=0,this._deflate[we]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ui.exports=kr;function ml(n){this[we].push(n),this[ce]+=n.length}function Fi(n){if(this[ce]+=n.length,this[dn]._maxPayload<1||this[ce]<=this[dn]._maxPayload){this[we].push(n);return}this[je]=new RangeError("Max payload size exceeded"),this[je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[je][Bi]=1009,this.removeListener("data",Fi),this.reset()}function _l(n){if(this[dn]._inflate=null,this[je]){this[We](this[je]);return}n[Bi]=1007,this[We](n)}});var Ve=F((Op,ln)=>{"use strict";var{isUtf8:$i}=P("buffer"),{hasBlob:wl}=ae(),yl=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Sl(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function xr(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function El(n){return wl&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}ln.exports={isBlob:El,isValidStatusCode:Sl,isValidUTF8:xr,tokenChars:yl};if($i)ln.exports.isValidUTF8=function(n){return n.length<24?xr(n):$i(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=P("utf-8-validate");ln.exports.isValidUTF8=function(e){return e.length<32?xr(e):n(e)}}catch{}});var Ar=F((Np,Ji)=>{"use strict";var{Writable:vl}=P("stream"),zi=Je(),{BINARY_TYPES:kl,EMPTY_BUFFER:qi,kStatusCode:xl,kWebSocket:Il}=ae(),{concat:Ir,toArrayBuffer:Tl,unmask:Rl}=_t(),{isValidStatusCode:Pl,isValidUTF8:Gi}=Ve(),un=Buffer[Symbol.species],W=0,Hi=1,Wi=2,ji=3,Tr=4,Rr=5,fn=6,Pr=class extends vl{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kl[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Il]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=W}_write(e,t,r){if(this._opcode===8&&this._state==W)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new un(r.buffer,r.byteOffset+e,r.length-e),new un(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new un(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case W:this.getInfo(e);break;case Hi:this.getPayloadLength16(e);break;case Wi:this.getPayloadLength64(e);break;case ji:this.getMask();break;case Tr:this.getData(e);break;case Rr:case fn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[zi.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Hi:this._payloadLength===127?this._state=Wi:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=ji:this._state=Tr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Tr}getData(e){let t=qi;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Rl(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Rr,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[zi.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===W&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=W;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ir(r,t):this._binaryType==="arraybuffer"?s=Tl(Ir(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=W):(this._state=fn,setImmediate(()=>{this.emit("message",s,!0),this._state=W,this.startLoop(e)}))}else{let s=Ir(r,t);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Rr||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=W):(this._state=fn,setImmediate(()=>{this.emit("message",s,!1),this._state=W,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,qi),this.end();else{let r=e.readUInt16BE(0);if(!Pl(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new un(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Gi(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=W;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=W):(this._state=fn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=W,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[xl]=s,o}};Ji.exports=Pr});var Nr=F((Dp,Ki)=>{"use strict";var{Duplex:bp}=P("stream"),{randomFillSync:Al}=P("crypto"),Vi=Je(),{EMPTY_BUFFER:Cl,kWebSocket:Ol,NOOP:Nl}=ae(),{isBlob:Qe,isValidStatusCode:bl}=Ve(),{mask:Qi,toBuffer:Re}=_t(),j=Symbol("kByteLength"),Dl=Buffer.alloc(4),hn=8*1024,Pe,Ke=hn,Y=0,Ll=1,Ml=2,Cr=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Y,this.onerror=Nl,this[Ol]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Dl,t.generateMask?t.generateMask(r):(Ke===hn&&(Pe===void 0&&(Pe=Buffer.alloc(hn)),Al(Pe,0,hn),Ke=0),r[0]=Pe[Ke++],r[1]=Pe[Ke++],r[2]=Pe[Ke++],r[3]=Pe[Ke++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[j]!==void 0?a=t[j]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Qi(e,r,d,i,a),[d]):(Qi(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=Cl;else{if(typeof e!="number"||!bl(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[j]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Y?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Qe(e)?(s=e.size,i=!1):(e=Re(e),s=e.length,i=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Y?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Qe(e)?(s=e.size,i=!1):(e=Re(e),s=e.length,i=Re.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[j]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Y?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Vi.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Qe(e)?(a=e.size,c=!1):(e=Re(e),a=e.length,c=Re.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[j]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Qe(e)?this._state!==Y?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Y?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[j],this._state=Ml,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Or,this,a,s);return}this._bufferedBytes-=r[j];let o=Re(i);t?this.dispatch(o,t,r,s):(this._state=Y,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Bl,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Vi.extensionName];this._bufferedBytes+=r[j],this._state=Ll,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Or(this,c,s);return}this._bufferedBytes-=r[j],this._state=Y,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Y&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][j],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][j],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Ki.exports=Cr;function Or(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Bl(n,e,t){Or(n,e,t),n.onerror(e)}});var io=F((Lp,so)=>{"use strict";var{kForOnEventAttribute:yt,kListener:br}=ae(),Xi=Symbol("kCode"),Yi=Symbol("kData"),Zi=Symbol("kError"),eo=Symbol("kMessage"),to=Symbol("kReason"),Xe=Symbol("kTarget"),no=Symbol("kType"),ro=Symbol("kWasClean"),de=class{constructor(e){this[Xe]=null,this[no]=e}get target(){return this[Xe]}get type(){return this[no]}};Object.defineProperty(de.prototype,"target",{enumerable:!0});Object.defineProperty(de.prototype,"type",{enumerable:!0});var Ae=class extends de{constructor(e,t={}){super(e),this[Xi]=t.code===void 0?0:t.code,this[to]=t.reason===void 0?"":t.reason,this[ro]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Xi]}get reason(){return this[to]}get wasClean(){return this[ro]}};Object.defineProperty(Ae.prototype,"code",{enumerable:!0});Object.defineProperty(Ae.prototype,"reason",{enumerable:!0});Object.defineProperty(Ae.prototype,"wasClean",{enumerable:!0});var Ye=class extends de{constructor(e,t={}){super(e),this[Zi]=t.error===void 0?null:t.error,this[eo]=t.message===void 0?"":t.message}get error(){return this[Zi]}get message(){return this[eo]}};Object.defineProperty(Ye.prototype,"error",{enumerable:!0});Object.defineProperty(Ye.prototype,"message",{enumerable:!0});var St=class extends de{constructor(e,t={}){super(e),this[Yi]=t.data===void 0?null:t.data}get data(){return this[Yi]}};Object.defineProperty(St.prototype,"data",{enumerable:!0});var Fl={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[yt]&&s[br]===e&&!s[yt])return;let r;if(n==="message")r=function(i,o){let a=new St("message",{data:o?i:i.toString()});a[Xe]=this,gn(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ae("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Xe]=this,gn(e,this,a)};else if(n==="error")r=function(i){let o=new Ye("error",{error:i,message:i.message});o[Xe]=this,gn(e,this,o)};else if(n==="open")r=function(){let i=new de("open");i[Xe]=this,gn(e,this,i)};else return;r[yt]=!!t[yt],r[br]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[br]===e&&!t[yt]){this.removeListener(n,t);break}}};so.exports={CloseEvent:Ae,ErrorEvent:Ye,Event:de,EventTarget:Fl,MessageEvent:St};function gn(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var pn=F((Mp,oo)=>{"use strict";var{tokenChars:Et}=Ve();function ne(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Ul(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<n.length;u++)if(d=n.charCodeAt(u),o===void 0)if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let g=n.slice(c,l);d===44?(ne(e,g,t),t=Object.create(null)):o=g,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),ne(t,n.slice(c,l),!0),d===44&&(ne(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=n.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Et[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Et[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&n.charCodeAt(u-1)===61)i=!0;else if(l===-1&&Et[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let g=n.slice(c,l);r&&(g=g.replace(/\\/g,""),r=!1),ne(t,a,g),d===44&&(ne(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let f=n.slice(c,l);return o===void 0?ne(e,f,t):(a===void 0?ne(t,f,!0):r?ne(t,a,f.replace(/\\/g,"")):ne(t,a,f),ne(e,o,t)),e}function $l(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}oo.exports={format:$l,parse:Ul}});var yn=F((Up,yo)=>{"use strict";var zl=P("events"),ql=P("https"),Gl=P("http"),lo=P("net"),Hl=P("tls"),{randomBytes:Wl,createHash:jl}=P("crypto"),{Duplex:Bp,Readable:Fp}=P("stream"),{URL:Dr}=P("url"),ye=Je(),Jl=Ar(),Vl=Nr(),{isBlob:Ql}=Ve(),{BINARY_TYPES:ao,CLOSE_TIMEOUT:Kl,EMPTY_BUFFER:mn,GUID:Xl,kForOnEventAttribute:Lr,kListener:Yl,kStatusCode:Zl,kWebSocket:A,NOOP:uo}=ae(),{EventTarget:{addEventListener:eu,removeEventListener:tu}}=io(),{format:nu,parse:ru}=pn(),{toBuffer:su}=_t(),fo=Symbol("kAborted"),Mr=[8,13],le=["CONNECTING","OPEN","CLOSING","CLOSED"],iu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class n extends zl{constructor(e,t,r){super(),this._binaryType=ao[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=mn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),ho(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ao.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new Jl({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Vl(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",cu),s.on("drain",du),s.on("error",lu),s.on("message",uu),s.on("ping",fu),s.on("pong",hu),i.onerror=gu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",mo),e.on("data",wn),e.on("end",_o),e.on("error",wo),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ye.extensionName]&&this._extensions[ye.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),po(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Br(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||mn,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Br(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||mn,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Br(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ye.extensionName]||(s.compress=!1),this._sender.send(e||mn,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:le.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:le.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:le.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:le.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:le.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:le.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:le.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:le.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(x.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(x.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Lr])return e[Yl];return null},set(e){for(let t of this.listeners(n))if(t[Lr]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Lr]:!0})}})});x.prototype.addEventListener=eu;x.prototype.removeEventListener=tu;yo.exports=x;function ho(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Kl,protocolVersion:Mr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!Mr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Mr.join(", ")})`);let i;if(e instanceof Dr)i=e;else try{i=new Dr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let _=new SyntaxError(c);if(n._redirects===0)throw _;_n(n,_);return}let d=o?443:80,l=Wl(16).toString("base64"),u=o?ql.request:Gl.request,f=new Set,g;if(s.createConnection=s.createConnection||(o?au:ou),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new ye({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=nu({[ye.extensionName]:g.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!iu.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let _=s.path.split(":");s.socketPath=_[0],s.path=_[1]}let m;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let _=r&&r.headers;if(r={...r,headers:{}},_)for(let[E,L]of Object.entries(_))r.headers[E.toLowerCase()]=L}else if(n.listenerCount("redirect")===0){let _=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!_||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,_||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),m=n._req=u(s),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=u(s);s.timeout&&m.on("timeout",()=>{q(n,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[fo]||(m=n._req=null,_n(n,_))}),m.on("response",_=>{let E=_.headers.location,L=_.statusCode;if(E&&s.followRedirects&&L>=300&&L<400){if(++n._redirects>s.maxRedirects){q(n,m,"Maximum redirects exceeded");return}m.abort();let B;try{B=new Dr(E,e)}catch{let M=new SyntaxError(`Invalid URL: ${E}`);_n(n,M);return}ho(n,B,t,r)}else n.emit("unexpected-response",m,_)||q(n,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,E,L)=>{if(n.emit("upgrade",_),n.readyState!==x.CONNECTING)return;m=n._req=null;let B=_.headers.upgrade;if(B===void 0||B.toLowerCase()!=="websocket"){q(n,E,"Invalid Upgrade header");return}let re=jl("sha1").update(l+Xl).digest("base64");if(_.headers["sec-websocket-accept"]!==re){q(n,E,"Invalid Sec-WebSocket-Accept header");return}let M=_.headers["sec-websocket-protocol"],p;if(M!==void 0?f.size?f.has(M)||(p="Server sent an invalid subprotocol"):p="Server sent a subprotocol but none was requested":f.size&&(p="Server sent no subprotocol"),p){q(n,E,p);return}M&&(n._protocol=M);let S=_.headers["sec-websocket-extensions"];if(S!==void 0){if(!g){q(n,E,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=ru(S)}catch{q(n,E,"Invalid Sec-WebSocket-Extensions header");return}let J=Object.keys(I);if(J.length!==1||J[0]!==ye.extensionName){q(n,E,"Server indicated an extension that was not requested");return}try{g.accept(I[ye.extensionName])}catch{q(n,E,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ye.extensionName]=g}n.setSocket(E,L,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(m,n):m.end()}function _n(n,e){n._readyState=x.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function ou(n){return n.path=n.socketPath,lo.connect(n)}function au(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=lo.isIP(n.host)?"":n.host),Hl.connect(n)}function q(n,e,t){n._readyState=x.CLOSING;let r=new Error(t);Error.captureStackTrace(r,q),e.setHeader?(e[fo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_n,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function Br(n,e,t){if(e){let r=Ql(e)?e.size:su(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${le[n.readyState]})`);process.nextTick(t,r)}}function cu(n,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[A]!==void 0&&(t._socket.removeListener("data",wn),process.nextTick(go,t._socket),n===1005?t.close():t.close(n,e))}function du(){let n=this[A];n.isPaused||n._socket.resume()}function lu(n){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",wn),process.nextTick(go,e._socket),e.close(n[Zl])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function co(){this[A].emitClose()}function uu(n,e){this[A].emit("message",n,e)}function fu(n){let e=this[A];e._autoPong&&e.pong(n,!this._isServer,uo),e.emit("ping",n)}function hu(n){this[A].emit("pong",n)}function go(n){n.resume()}function gu(n){let e=this[A];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,po(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function po(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function mo(){let n=this[A];if(this.removeListener("close",mo),this.removeListener("data",wn),this.removeListener("end",_o),n._readyState=x.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[A]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",co),n._receiver.on("finish",co))}function wn(n){this[A]._receiver.write(n)||this.pause()}function _o(){let n=this[A];n._readyState=x.CLOSING,n._receiver.end(),this.end()}function wo(){let n=this[A];this.removeListener("error",wo),this.on("error",uo),n&&(n._readyState=x.CLOSING,this.destroy())}});var ko=F((zp,vo)=>{"use strict";var $p=yn(),{Duplex:pu}=P("stream");function So(n){n.emit("close")}function mu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Eo(n){this.removeListener("error",Eo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function _u(n,e){let t=!0,r=new pu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(So,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(So,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",mu),r.on("error",Eo),r}vo.exports=_u});var Fr=F((qp,xo)=>{"use strict";var{tokenChars:wu}=Ve();function yu(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&wu[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}xo.exports={parse:yu}});var Oo=F((Hp,Co)=>{"use strict";var Su=P("events"),Sn=P("http"),{Duplex:Gp}=P("stream"),{createHash:Eu}=P("crypto"),Io=pn(),Ce=Je(),vu=Fr(),ku=yn(),{CLOSE_TIMEOUT:xu,GUID:Iu,kWebSocket:Tu}=ae(),Ru=/^[+/0-9A-Za-z]{22}==$/,To=0,Ro=1,Ao=2,Ur=class extends Su{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ku,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Sn.createServer((r,s)=>{let i=Sn.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Pu(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=To}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Ao){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(vt,this);return}if(e&&this.once("close",e),this._state!==Ro)if(this._state=Ro,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(vt,this):process.nextTick(vt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{vt(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Po);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Oe(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Oe(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ru.test(i)){Oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Oe(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){kt(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=vu.parse(c)}catch{Oe(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let f=new Ce({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Io.parse(l);g[Ce.extensionName]&&(f.accept(g[Ce.extensionName]),u[Ce.extensionName]=f)}catch{Oe(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(g,m,_,E)=>{if(!g)return kt(t,m||401,_,E);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(f))return kt(t,401)}this.completeUpgrade(u,i,d,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Tu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>To)return kt(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Eu("sha1").update(t+Iu).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ce.extensionName]){let u=e[Ce.extensionName].params,f=Io.format({[Ce.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
8
+ var p0=Object.create;var Sr=Object.defineProperty;var m0=Object.getOwnPropertyDescriptor;var w0=Object.getOwnPropertyNames;var _0=Object.getPrototypeOf,y0=Object.prototype.hasOwnProperty;var X=(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 ae=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),zs=(r,e)=>{for(var i in e)Sr(r,i,{get:e[i],enumerable:!0})},v0=(r,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of w0(e))!y0.call(r,c)&&c!==i&&Sr(r,c,{get:()=>e[c],enumerable:!(a=m0(e,c))||a.enumerable});return r};var Re=(r,e,i)=>(i=r!=null?p0(_0(r)):{},v0(e||!r||!r.__esModule?Sr(i,"default",{value:r,enumerable:!0}):i,r));import{chmod as b0,mkdir as S0,readFile as E0,rename as qs,writeFile as Fs}from"node:fs/promises";import{dirname as C0}from"node:path";async function ft(r){try{let e=await E0(r,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function nn(r,e,i){await S0(C0(r),{recursive:!0});let a=`${JSON.stringify(e,null,2)}
9
+ `,c=`${r}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{i?.mode!==void 0?await Fs(c,a,{encoding:"utf8",mode:i.mode}):await Fs(c,a,"utf8"),await qs(c,r),i?.mode!==void 0&&await b0(r,i.mode)}catch(u){await qs(c,c).catch(()=>{});let{rm:d}=await import("node:fs/promises");throw await d(c,{force:!0}).catch(()=>{}),u}}var rn=Ie(()=>{"use strict"});function Gs(r){return on[Us]<=on[r]}function Er(r){Hs={...r}}function sn(r,e,i,a){if(on[r]<on[Us])return;let c=JSON.stringify({ts:new Date().toISOString(),level:r,module:e,msg:i,...Hs,...a});r==="error"||r==="warn"?P0.write(`${c}
10
+ `):A0.write(`${c}
11
+ `)}function R(r){return{debug:(e,i)=>sn("debug",r,e,i),info:(e,i)=>sn("info",r,e,i),warn:(e,i)=>sn("warn",r,e,i),error:(e,i)=>sn("error",r,e,i),child:e=>R(`${r}.${e}`)}}var on,Us,A0,P0,Hs,K=Ie(()=>{"use strict";on={debug:10,info:20,warn:30,error:40},Us=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),A0=process.stdout,P0=process.stderr,Hs={}});import{homedir as D0}from"node:os";import{join as re}from"node:path";function W(r){let e=r??D0(),i=re(e,".coze"),a=re(i,"bridge"),c=re(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:re(c,"index.js"),pidFile:re(a,"bridge.pid"),portFile:re(a,"bridge.port"),tokenFile:re(a,"bridge.token"),logFile:re(a,"bridge.log"),installLock:re(a,"install.lock"),configFile:re(a,"config.json"),agentsRoot:re(i,"agents")}}function Ne(r,e=W()){let i=re(e.agentsRoot,r);return{root:i,config:re(i,"config.json"),workspace:re(i,"workspace"),logs:re(i,"logs")}}var ue=Ie(()=>{"use strict"});var xn={};zs(xn,{AGENT_CONFIG_FILE_MODE:()=>an,enforceAgentConfigMode:()=>I0,loadAgentConfig:()=>fe,persistAgentSessions:()=>Cr,persistAgentSkills:()=>cn,saveAgentConfig:()=>we});import{chmod as k0,stat as T0}from"node:fs/promises";function fe(r,e){return ft(Ne(r,e).config)}function we(r,e){return nn(Ne(r.agentId,e).config,r,{mode:an})}async function I0(r,e){if(process.platform==="win32")return;let i=Ne(r,e).config;try{let a=await T0(i);if(!a.isFile())return;let c=a.mode&511;c!==an&&(await k0(i,an),Ks.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;Ks.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function Cr(r,e,i){let a=await fe(r,i);a&&(a.sessions=Object.fromEntries(e),await we(a,i))}async function cn(r,e,i){let a=await fe(r,i);a&&(a.skills=e,await we(a,i))}var Ks,an,Ge=Ie(()=>{"use strict";rn();K();ue();Ks=R("agent-config"),an=384});var Yi=ae(Q=>{"use strict";var b=N;(function(r,e){let i=N,a=r();for(;;)try{if(-parseInt(i(1391))/1+-parseInt(i(1602))/2+parseInt(i(1646))/3*(parseInt(i(774))/4)+-parseInt(i(1203))/5*(-parseInt(i(785))/6)+parseInt(i(582))/7+-parseInt(i(814))/8+parseInt(i(275))/9===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Un,487740);var mx=Object[b(503)+"operty"],_x=Object["getOwnPr"+b(815)+"mes"],Ki=(r,e)=>function(){return r&&(e=(0,r[_x(r)[0]])(r=0)),e},yx=(r,e)=>{for(var i in e)mx(r,i,{get:e[i],enumerable:!0})};function vx(){return qi||(qi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function N(r,e){r=r-208;let i=Un(),a=i[r];if(N.LwepBC===void 0){var c=function(m){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",v="",y="";for(let E=0,D,k,T=0;k=m.charAt(T++);~k&&(D=E%4?D*64+k:k,E++%4)?v+=String.fromCharCode(255&D>>(-2*E&6)):0)k=w.indexOf(k);for(let E=0,D=v.length;E<D;E++)y+="%"+("00"+v.charCodeAt(E).toString(16)).slice(-2);return decodeURIComponent(y)};N.AzgXZA=c,N.JvQiLW={},N.LwepBC=!0}let u=i[0],d=r+u,g=N.JvQiLW[d];return g?a=g:(a=N.AzgXZA(a),N.JvQiLW[d]=a),a}function bx(){let r=b;return Fi||(Fi=[IDBCursor[r(722)+"e"][r(837)],IDBCursor[r(722)+"e"][r(482)],IDBCursor[r(722)+"e"][r(482)+r(376)+"ey"]])}function Sx(r){let e=b,i={cMwDD:e(1144),EHwYd:e(765),sblTG:e(344),mbaVp:function(c,u){return c===u},uZiCa:e(1435),JqAvT:"DLDtp",LQAkN:function(c,u){return c(u)},eQQff:e(1393),raYsC:function(c,u){return c instanceof u}},a=new Promise((c,u)=>{let d=e,g={GKcQd:i[d(1335)],LNFAC:function(y,E){return y(E)}},m=()=>{let y=d;r["removeEv"+y(1473)+y(547)](i.cMwDD,w),r[y(1616)+y(1473)+y(547)](i[y(385)],v)},w=()=>{let y=d;if(g[y(1559)]!==y(1621))g[y(1361)](c,Ae(r[y(274)])),m();else return!!this[y(781)]},v=()=>{let y=d,E={aPadp:function(D,k,T){return D(k,T)},tIvsF:i[y(385)],CQEWd:i.sblTG};if(i[y(710)](i[y(1719)],i.JqAvT)){let D=E[y(956)](_0x2cdcd0,E[y(707)],{message:this[y(1504)+y(445)+y(861)](_0x2d8760)});this.emit(E[y(707)],D);let k=E.aPadp(_0x5a4c5a,E.CQEWd,{reason:this[y(1504)+y(445)+y(861)](_0x9d7191)});this[y(232)](y(344),k)}else i[y(660)](u,r[y(765)]),m()};r[d(1568)+d(786)](i[d(617)],w),r[d(1568)+"Listener"](i[d(385)],v)});return a[e(1356)](c=>{let u=e;i[u(308)](c,IDBCursor)&&Mr[u(1667)](c,r)})[e(950)](()=>{}),qn[e(1667)](a,r),a}function Ex(r){let e=b,i={zcdBr:function(c){return c()},ofPZN:function(c){return c()},onmfJ:e(1068),sRnMV:e(765),iziNv:e(1414),kmXbe:function(c,u){return c(u)}};if(zn[e(1520)](r))return;let a=new Promise((c,u)=>{let d=e,g={VgEKK:i[d(1206)],IDViV:i[d(1309)],jGOAU:i[d(1501)],YDgfZ:function(y,E){return i[d(1357)](y,E)},oHEPb:d(227)+"or",tPqXe:function(y){return i[d(1025)](y)}},m=()=>{let y=d;r[y(1616)+y(1473)+y(547)](g[y(1271)],w),r[y(1616)+y(1473)+y(547)](g[y(443)],v),r[y(1616)+y(1473)+y(547)](g[y(1649)],v)},w=()=>{let y=d;i.zcdBr(c),i[y(1025)](m)},v=()=>{let y=d;g.YDgfZ(u,r[y(765)]||new DOMException(g.oHEPb,g.oHEPb)),g.tPqXe(m)};r[d(1568)+"Listener"](i[d(1206)],w),r[d(1568)+d(786)](d(765),v),r[d(1568)+d(786)](i.iziNv,v)});zn[e(1667)](r,a)}function Cx(r){Fn={XNMjv:function(a,c){return a(c)}}[b(383)](r,Fn)}function Ax(r){let e=b,i={CrwXH:e(258),NKJlS:e(770),HsHeM:function(a,c){return a(c)},HUaHx:function(a,c){return a(c)},TAKaT:function(a,c){return a(c)},RuPea:function(a,c){return a===c},NQAsE:function(a,c){return a in c},rkebW:e(1712)+"oreNames",gBzNV:function(a,c){return a!==c},mTJbV:"dMJKW"};if(i[e(671)](r,IDBDatabase[e(722)+"e"][e(1216)+e(1373)])&&!i[e(1285)](i[e(391)],IDBTransaction[e(722)+"e"]))if(i.gBzNV(i[e(223)],e(382)))this[e(348)+e(1467)]()&&(!this[e(1466)]||this[e(1466)].readyState!==this.OPEN||this._ws[e(1463)+"te"]!==this[e(994)+"NG"])&&this[e(998)+"nLine"](),this[e(828)+"er"]&&_0x363000[e(1568)+e(786)](i[e(638)],this[e(998)+e(553)]),this._isBrowser&&_0x39994e[e(1568)+e(786)](i[e(675)],this[e(998)+e(679)]);else return function(a,...c){let u=e,d=r[u(934)](Kt(this),a,...c);return Lr[u(1667)](d,a.sort?a[u(596)]():[a]),i[u(868)](Ae,d)};return bx().includes(r)?function(...a){let c=e;return r[c(1083)](i[c(868)](Kt,this),a),i[c(670)](Ae,Mr[c(1477)](this))}:function(...a){let c=e;return i.TAKaT(Ae,r[c(1083)](i.HUaHx(Kt,this),a))}}function Px(r){let e=b,i={PkiTs:function(a,c){return a===c},QhENY:function(a,c){return a(c)},iMmye:function(a){return a()}};return i.PkiTs(typeof r,e(1529))?i.QhENY(Ax,r):(r instanceof IDBTransaction&&i.QhENY(Ex,r),ji(r,i.iMmye(vx))?new Proxy(r,Fn):r)}function Ae(r){let e=b,i={jeeWY:function(c,u){return c>=u},TZcjB:function(c,u){return c instanceof u},vEjiW:function(c,u){return c(u)},YYXOG:function(c,u){return c!==u},PxKst:e(1258),VRBLq:e(1374)};if(i[e(565)](r,IDBRequest))return i[e(1420)](Sx,r);if(On[e(1520)](r))return On[e(1477)](r);let a=i[e(1420)](Px,r);if(i[e(1338)](a,r))if(i.YYXOG(i.PxKst,i[e(414)]))On.set(r,a),qn.set(a,r);else return i.jeeWY(_0x724dae[e(1017)],_0x3a79c2[e(1396)]);return a}var ji,qi,Fi,Mr,zn,Lr,On,qn,Fn,Kt,Ui=Ki({"node_modules/idb/build/wrap-idb-value.js"(){let r=b,e={NiSnN:function(i,a){return i instanceof a},iwtLv:function(i,a){return i===a},bqoEw:r(1712)+r(1522),xWdyz:function(i,a){return i===a},uhIUL:"store",jlOCp:r(1623),NUcoe:function(i,a){return i in a}};ji=(i,a)=>a.some(c=>i instanceof c),Mr=new WeakMap,zn=new WeakMap,Lr=new WeakMap,On=new WeakMap,qn=new WeakMap,Fn={get(i,a,c){let u=r;if(e[u(1073)](i,IDBTransaction)){if(e[u(1163)](a,u(1623)))return zn[u(1477)](i);if(a===e[u(393)])return i[u(1712)+"oreNames"]||Lr[u(1477)](i);if(e[u(1538)](a,e[u(330)]))return c[u(1712)+u(1522)][1]?void 0:c[u(1712)+u(316)](c[u(1712)+u(1522)][0])}return Ae(i[a])},set(i,a,c){return i[a]=c,!0},has(i,a){let c=r;return i instanceof IDBTransaction&&(e[c(1538)](a,e[c(1418)])||a==="store")?!0:e[c(1369)](a,i)}},Kt=i=>qn.get(i)}}),Wi={};yx(Wi,{deleteDB:()=>kx,openDB:()=>Dx,unwrap:()=>Kt,wrap:()=>Ae});function Dx(r,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let d=b,g={BGsKb:function(v,y,E){return v(y,E)},jAtDk:function(v,y){return v(y)},cZwqY:function(v,y){return v!==y},kiHuH:d(1299),yCLJt:d(1341),Xymme:"close",ppIkF:d(562)+"hange",JCjHJ:function(v,y){return v(y)},plRCx:"upgradeneeded",NYVoG:d(693)},m=indexedDB[d(1694)](r,e),w=g[d(1408)](Ae,m);return a&&m[d(1568)+d(786)](g.plRCx,v=>{let y=d;g[y(729)](g[y(524)],g.yCLJt)?a(Ae(m[y(274)]),v[y(370)+"on"],v[y(591)+"on"],g.jAtDk(Ae,m[y(1216)+y(1373)])):(_0x113bbe(_0x20bfdc,24),g[y(767)](_0x47b589,_0x180194,g[y(1155)](_0x570c22,_0x784fa9)))}),i&&m.addEventListener(g[d(1086)],()=>i()),w[d(1356)](v=>{let y=d;u&&v[y(1568)+"Listener"](g[y(1385)],()=>u()),c&&v[y(1568)+"Listener"](g[y(499)],()=>c())}).catch(()=>{}),w}function kx(r,{blocked:e}={}){let i=b,a={udgVb:i(693),TgzPx:function(u,d){return u(d)}},c=indexedDB[i(281)+"tabase"](r);return e&&c[i(1568)+i(786)](a[i(598)],()=>e()),a.TgzPx(Ae,c)[i(1356)](()=>{})}function Hi(r,e){let i=b,a={VhCTt:i(1548)+"e",nMVYR:i(523),AkXaA:function(m,w){return m instanceof w},ELiex:function(m,w){return m===w},LMEjt:i(595),pgJmY:function(m,w){return m in w}};if(!(a[i(827)](r,IDBDatabase)&&!(e in r)&&a[i(790)](typeof e,a[i(879)])))return;if(Bn[i(1477)](e))return Bn[i(1477)](e);let c=e[i(1573)](/FromIndex$/,""),u=e!==c,d=Vi.includes(c);if(!a[i(1161)](c,(u?IDBIndex:IDBObjectStore)[i(722)+"e"])||!(d||Ji[i(1104)](c)))return;let g=async function(m,...w){let v=i,y=this[v(1216)+v(1373)](m,d?a[v(1600)]:a[v(1041)]),E=y[v(1311)];return u&&(E=E[v(271)](w[v(1318)]())),(await Promise.all([E[c](...w),d&&y[v(1623)]]))[0]};return Bn[i(1667)](e,g),g}var Ji,Vi,Bn,Tx=Ki({"node_modules/idb/build/index.js"(){let r=b,e={ckKLG:"get",CzyVT:r(290),YLmyd:"getAll",TSCRO:"getAllKeys",zvwIS:"count",fcbYH:"add",bfSwu:"delete",qvnOO:r(1627),cGffK:function(i,a){return i(a)}};Ui(),Ui(),Ji=[e.ckKLG,e.CzyVT,e[r(1217)],e[r(208)],e[r(1711)]],Vi=["put",e[r(508)],e[r(734)],e.qvnOO],Bn=new Map,e.cGffK(Cx,i=>({...i,get:(a,c,u)=>Hi(a,c)||i[r(1477)](a,c,u),has:(a,c)=>!!Hi(a,c)||i[r(1520)](a,c)}))}}),Ix={idb:function(r){let e=b;r[e(757)]=Promise[e(1608)]()[e(1356)](()=>(Tx(),Wi))[e(1356)](function(i){return i})}},Gi={};function Ce(r){let e=b,i={BIniP:"2|3|4|1|0",ezoUp:function(g,m){return g!==m}},a=i.BIniP[e(1742)]("|"),c=0;for(;;){switch(a[c++]){case"0":return d[e(757)];case"1":Ix[r](d,d[e(757)],Ce);continue;case"2":var u=Gi[r];continue;case"3":if(i.ezoUp(void 0,u))return u.exports;continue;case"4":var d=Gi[r]={exports:{}};continue}break}}Ce.d=(r,e)=>{let i=N;for(var a in e)Ce.o(e,a)&&!Ce.o(r,a)&&Object["definePr"+i(744)](r,a,{enumerable:!0,get:e[a]})},(()=>{let r=b;Ce.o=(e,i)=>Object[r(722)+"e"][r(1176)+r(744)][r(934)](e,i)})(),(()=>{let r=b,e={cciTt:"undefined",NZIpw:r(237),YRscD:r(1452)+"le"};Ce.r=i=>{let a=r;e.cciTt!=typeof Symbol&&Symbol[a(1284)+a(1757)]&&Object[a(503)+a(744)](i,Symbol.toStringTag,{value:e[a(563)]}),Object[a(503)+a(744)](i,e[a(659)],{value:!0})}})();var $={};function Un(){let r=["t0Tiq2i","CgXLyxnLiha","qvb4q0S","Affswxu","vgrfEgy","v3vPsgS","CMfUzg9T","DMfSDwvZ","BK5Oyvy","t3f4qLm","u3jMquC","Dg9tDhjPBMC","tLfbC0u","sNbZuuO","DgXlrwy","DwrXy0W","zvzcruW","ihrPBwvVDxq","ruvnB3K","BvbXC2e","rufTqMO","BfrPBwvVDxq","DeLUDgvYy2u","BMfTzq","rvDIvgW","zw9Nuei","ExPWELu","DfP1B0y","twfPAMq","AhPlsum","x3DHAxq","C3nHz2vfDMu","uhn4D2i","AvvyDhC","EwLeD2W","wefqsM4","C1jUtvy","B3bLBKrc","C3rVCMu","DxrMofDYAxq","BgvUz3rO","BNrfBMrWB2K","rgfpsNC","ChbL","uM9euKG","C2HPzNq","vgPYvfu","swLWD2O","CMP0vMC","Cg93","y3bZDwO","x3jLBw92zvC","tg9JAW","yKfXzMi","sLnptLa","D0vuEfy","tLzHsgq","C2XPy2u","C0fcEMO","C2vYDMvYvgK","CMfTugfYyw0","EvjLy29UBMu","zvfrzMy","x0vysvnu","CK9SwK4","wvLyt0C","y2HHCKnVzgu","y25JyLG","q2PxBu4","uLH2rgu","vwDxC1m","uhnOzgK","D21py3O","D2DWru0","uu16Dum","y0LwtMC","Dev2zw50","r2flyNy","zNjJALq","zg5pALq","Cg9PBNrdB24","B3PABMG","vuTbr28","DgHLBG","A21yyMu","yMfSrxzLBNq","zvvQtvy","AxjLza","te5gqum","CMvJB25Uzwm","BwfW","z2v0u3rVCMe","rgjnEfC","shD2s2y","qMruqMy","qvvzB3a","tLvJB2u","qwDqqNq","z29PBMCGyxC","tfrnC2y","Aw9U","vePTANu","AfDgBKW","tu9ACee","C2nYAxb0","tufyx1jfvfi","v1zdzwi","yuDzzNq","y3jLyxrLq2W","q29Kzq","ANrqBxq","rhLorKG","whLTBwu","qvH4wM4","nhWY","x2nSzwfYvgK","CezeEMi","x3bPBMDqB24","nZC4ntuXB2LZD2rQ","Dgv4DfbHEwW","Cfzcwhi","C2vYDMLJzq","tKfbseq","BgLTAxq","thDIvhO","ChjVDg9JB2W","zMLUza","ywDPwwS","A3jAuha","BIWGAg9ZDg4","y3vYC29Yx24","ufD1shO","EKrkvMO","z0XgEwC","BxLut20","sKnQseO","x2nYzwf0zvm","v2L5Bhu","x2LUAxrqCM8","t1bftL9fuLi","wePvwvm","ywjVCNq","z1jtBfu","AMvJDfn0B3i","vKjtv24","AMXpq3a","yKnvANO","DKvQAvC","z2v0sxrLBq","tMH5Dhu","EenJAM4","vgjwD0K","sLnjzem","tvvQq0m","swTHAwq","zxjHDg9Y","shjqBhe","AwnvAgu","CMTLCKDSB2i","CM92AwrLihC","ChrVCG","ywX3yxLZ","wwzjuei","DgLTzw91Da","y2XLyxjtDg8","twLMwhi","EuLQvMS","AvLtww4","B3v0sw50zxi","yxbWBgLJyxq","zM5Mwee","Bhrty3G","ruHvu3y","reTNEKG","x2LZtwLUAvC","y0LJs08","AhrHCgm","tMDcyuS","uu1nBwG","x19LC01Vzhu","thH1v1i","s21lvMy","Dg9iyxnO","z3vNsMq","Bfn0tKW","ueXIu2K","BxnN","n3WZFdL8mxW","u2vYDMLJzvC","uMvHzcbWyxm","CMvHzhLtDge","zsbHihn0CMK","quXZDgu","x3DZ","B3jpBMXPBMu","y29UBMvJDa","D2HMEhu","CKLkvLK","vKPIsgi","x2rPC3bHDgm","zw50tgLZDgu","Aw5KzxHpzG","swfICey","C3rLBMvYCW","z2v0","tNvWB0u","AenSB3nLrxy","m3WWFdf8nxW","Ae9Wzw5fDMu","AgfUz2u","AwrI","x29Ut3bLBG","vuDUtxG","AuXqD1G","ELPfyuK","vNvIswW","z0jxz1q","D3P0txK","vKnluuW","wLj2vKy","y0fQqKm","Dufrwxq","Dg9VigXHCMC","s1DmreO","CxbbAfe","AKLXqNG","CLvRu3O","AxmGDw5Kzwy","AxPPtNy","rLH5vwG","y29UC3rYDwm","x2zVCM1HDeu","C2v0zgi","vgLTzw91Da","v2vPuNK","reTbqxy","EgDuwMy","u2Xkr2u","Benusha","v3zIq2S","yMrFzgLK","vgH4wMK","yMfJA3vWigu","BwvKAwf0zwW","ywvMA2G","tgnzzM4","AwDHDg9Yt24","AgfZ","z2u6ia","B3jLtMfTzxm","y1bWr08","DLjqEM0","BuztCwu","Ew9Wr1m","AevYCM9Yrxy","y2uGBM90igK","zNvUy3rPB24","vg1XDMu","zKfmvNi","vgncr3m","x2rItMfTzq","Cxjxvxe","ywDLu2HVDW","Dw50","Cg14Dee","EfDKExO","Dg9cExrLC0W","wK1yBfK","zejtveW","Dw1YC0K","zwTpt2G","x29UugfNzu4","BwLUzW","zNPete0","vLPqwg0","CMvHzhDYAxq","CgLUz0XVC3m","y3vYDMfSDwu","zNjVBNrPzxi","qwLLvNe","uMvJB25Uzwm","Ef9MCM9UDgK","y2XVC2veqG","ufz4B0W","zxH0ugf5Bg8","x2vUzhbVAw4","r0TJuwq","z2vY","AgfeuNi","BMCGzMfPBgu","D2fKrwC","DNr3swm","CMXSse8","reDbCvG","ELDmr3e","ywrKrxzLBNq","tuL1tgO","x2rLC3rYB3K","verlyuG","s3bsEMO","CMvWBgfJzq","C0nqy2i","B215DxO","zw5XDwv1zq","qLnpzNK","DhjPzxm","zgvSzxrL","Cu9Xq3u","v01ksva","zw5HyMXLvhi","Aw5Lza","DgDbq0e","tg9NsurozxC","t0vfENu","DhLWzq","vuLXA2i","s2fUzwe","zcWGDw5RBM8","Ew90Cfu","shzhzMq","B25nzxnZywC","sgnuwvq","uwr4zwC","quDdz0W","AhHtDue","r3LxD0u","uLnkuve","vMHdvhq","quDSvwS","mta1nJm5meHOtNjuvW","tunVzMe","ANvzswK","u1rgrei","txDOCKO","tMT3BMK","CMvZB2X2zq","Ce9LDLG","vvflsw8","B25mAw5L","zNfVBNC","v2vPEgLUsLm","B0fwCvi","zgvS","CMvTB3zLrxy","tMXtB3u","yxjYyxLIDwy","BvjNEvG","vNP1yuG","ChzdBva","ufzct3K","zg9Uzq","ywDLsgLKzq","B2fK","Ew5cz24","y2XLyxi","rwXxugy","ANjlDNe","BxfRA2u","vM1QzMO","ywXSq3vYC28","yNvMzMvY","z1PvC2G","BMv4DcGPigm","Dhj1y3rVCIa","u2XmAfK","EsbJBg9Zzwq","z0DUz0O","rfnkv0y","rvLYEgO","ug5rC1O","rxjYB3jdB2q","ywrKt25L","BNrLCG","oda1mJbWyLPfs1a","BMDuAw1LCG","x2n1CNnVCKy","AKDpqvu","y3jLyxrLuMu","x3nLCuLK","zhjvweS","Avrbvgq","CerYsM0","zw5NDgG","ue5pB2S","vM1qBwq","BwLZzq","quLREha","uNH0vMu","BNrbBMrvCgq","B25VCgvU","B3nLza","Cw9htNK","whjXuKm","zLvMwvu","C2v0","x29WDgLVBNm","uu5Ts1y","Axr2Awm","DeLK","x3jLywr5q2W","quD4q20","DMLJzuLeig8","uwfks1i","vujnrLq","BwvY","u1Drr0q","AwDPsNa","tgr2A0O","tuvtu0fhrv8","v2rItfi","uLjpuG","uxnjz00","DxneEvO","zw5KCg9PBNq","whzOt0G","x29Uq2XVC2u","shvhz2i","EMjcAfm","CM9JDgu","Aw9UvgLTzw8","B0XVD0i","B3bLBG","B25Uzwn0Aw4","BNruCMLLC0m","rLfHAM8","BMvJDa","C2PssKq","DKLIvuG","Ahr0Chm6","vhz6v2m","z2v0qwXS","C3vIyxjYyxK","AKvdEMK","DMfS","CeDUEvm","sLHbBgW","vwXtAeW","A1n0yxr1C0m","ENz3svm","B2jQzwn0u3q","ww1erMm","DcbSAw1PDa","q09rCfO","D2jTCeG","C3vIC3rYAw4","DKTwwNa","DvPPq2e","AwXK","CxrOrw0","ChvZAa","DxjS","whP3CfC","zxjFDhrS","Bur1B3i","CM92AwrLigi","EfLpDNu","AMvYwhy","y3vYC29YlNm","yLnwsfe","AfLVyw8","zNjVBujPDhm","BwvZC2fNzq","B3nLrxzLBNq","qMTKvfO","Ewjxzu8","CMvJzwL2zwq","ywnR","B3jRig9MzMW","y3jLyxrLrwW","C3bSAxq","x2TLEvbHDgG","rM5XELG","BK5eEeq","zvvoA1K","wxbPse8","Bwf4uMv0CMK","wuPvAMS","uM5ywe0","y29Kzq","EgPuyMe","ELr6rvK","nhWYFdf8mhW","x2n1CNnVCK0","CMvWBgfJzui","vgfN","vuzRvNq","y3jLyxrLtwu","DLLLC3y","D2ruq0y","s21vt3O","qu9jzfm","tunrwhC","z2v0qwXSs2u","vfnduK8","x3nVy2TLDa","z2v0q3vYC28","CgfNzwHPzgu","qMztEu4","rxvqzMy","BLfXt1G","yMzXtfe","y3vYCMvUDeu","C2vUza","sxPHDem","ohWZFdj8mhW","D3jPDgvvAw4","CvLOtvm","z1nXveG","BvrkyLy","wNr0wfy","vxvpvhC","BLnjqMS","qwjVCNrfCNi","Dgv4Dc9Qyxy","CNzHBa","DvPfvfC","ywzL","zw1PDa","yxrHlcbKyxq","BwvZC2fNzv8","x1fVu01HBMe","vxbKyxrLq28","tw9KDwXL","Bw5YBhi","r1DMs20","rNjVBNrPzxi","DM5oz3q","C0zkyK0","igzPzwXKoIa","CerWruS","B2nRzxq","uNLwzwu","DMvUDa","ignVzgu6ia","D3PQrKq","zwLlyKe","B25tDgfYDfi","wLf2tve","y29UBMvJDgK","uxf4CNO","zwT0q2u","tKDFrvjst1i","rgPxC2i","B25SAw5L","zNjVBu51Bwi","r0DSrMC","uxLgEwe","yM5dvui","rwTyEeC","CLfdAwW","BgLZDgvUtMu","Aw1LCYbPBIa","t25cCfO","yMvpuey","r0jotMG","Aw5N","Aw5KzxG","yxv0BW","rvjst1i","CMvZDwX0","mtuZmZCZntbrAgPkA1u","AxnbCNjHEq","s2XvAhK","AxnmB25N","tvffy1m","y3vHywC","zgvSzxrLrge","t3nTvxa","yM9Sueu","zuH3Dgq","wwf3vgW","y2TzwMS","Eu1uqKy","y29Uy2f0","x194x21Zz18","z2v0s2v5","B3PuB2y","y0XWq2u","vNHfAgO","uhfzruy","zxj2AwnL","t0nMy1e","AxnrB1nnzxm","zwnVBM5Ly3q","zvPNzMS","CKjYyw0","DunXDhi","yKX3ANq","suLnv0O","CM92AwrLihy","zMfVB3e","vMLHEMq","wxvjDLe","CMfzC0m","Auv0uK0","mNW4Fdb8nxW","yxnJCMLWDa","Au1mtxO","y29UBMvJDfm","v293Egy","tM5lyMS","B3jL","CNzqvwS","AxnszwfKEq","AvLTuwu","DKzIEwK","q1zYwu0","Dg9cExrLC0i","yxKSig5LDhC","uuLVv3q","CLPcAfC","x3bYB3rVy28","revPuuC","AerHALK","whjKDgq","DwHjvuW","D2nxA2C","vNL0v2S","Cuz1y0e","zLbHwLi","vLjXwMm","q3vZDg9Tq2W","uNP3yuG","zMzMzG","ywXSzwqGBxu","shfWzeS","ufjhEuO","ywrK","qKDtzLa","y2XVC2u","ywnRtxnNswq","zMfgq3u","u2TPCcbWyxm","x25HDMLNyxq","D0PwuMO","yMLUza","rezIwMW","q29UzMLN","vKDPthm","yNL0zu9MzNm","n3W0Fdz8ma","ENruvLi","z2vrDwv1zuW","rwL2v0i","A0PeuLK","wejguKy","CMvJzxzPzwq","tujJuLy","ysbTDxn0igi","u0rqvem","Axnby2TdBgu","ExfHB0O","BMnVzgLUzW","t3fwrKC","B0nmDNq","B2XKvMvYC2K","yNL0zuXLBMC","ywWGy3vYC28","ANbTDha","DNb1zNq","u1btAhq","uhjPBwfYEuS","qw52EgC","DerpC0y","BhrPCgXLihq","BM9Uzv9UB24","igXHCMDLCIa","ze1ks1C","we5nANy","zxjYtM8","ruH3wwq","Ag9iv1K","CKDeDvC","q291BNq","D2vI","yMfSu2nVCgu","CMTLyLC","sevwzMq","yNfVrxC","AfDbze4","EKXivM4","y3fRuvu","ruT2CfG","suzVwfa","x21PBMLoyxy","rgj3A3a","ywnRx2LK","BgLUzw5V","CvveAMK","EKDqyLy","vKXXs2e","vxzxrLm","rhjmreC","uxL2sgC","zM9YrwfJAa","l3DZl3yY","vNfywvq","t3bLBKv2zw4","swztyMG","vLjcthe","zxjYtxnN","mdaWma","mhWYFdn8mxW","y3ruAw1LB3u","rxzLBNq","r2PeC28","CLzcA3O","yML2Dgq","Du1xshO","BMrWB2LUDfq","sNzbtuO","vNPRC2q","zNb5yxO","igfYCMf5yNu","DMvY","CwjAyMW","CefkA28","r2Tdze0","q2r0ruG","DhDVCMTdAge","zw5fDMvUDa","yw51Ce1LC3m","rgvKAwnHDgu","CLbgDKW","Dg9cExrLCW","Dw5RBM93BIa","s0fktuK","yvLNEK0","surwAvy","Dhr3Awq","CNjVCK1LC3m","y09Wzw4","t01rB3m","u3nHAK0","CNLwqwq","zgLZywjSzue","DKrhueu","zMLN","vvb1uNm","DxnLCKLW","sNDyA3u","twvZC2fNzuu","qwDsCxa","EMfrvLy","CLP4wui","ww9uAKi","Cgf5Bg9Hzfq","Dw5KzwzPBMu","ywXPzcb1CMW","sg9qC2S","BgnlvuG","CgfYC2u","BKDTweG","uxvLDwu","zMX1C2HfEha","A2Tjr3O","Bg93","BgLUzq","tuHMENa","BxnNsuq","aaaaaaaaaaa","AxnAzxjV","tKfusvzfx0u","A2zRu1m","svLyr3C","AK9jwhC","BMHTtei","y29UDgLUDwu","C3v0tKO","zw50zwqGDhK","suvtx0vsuK8","uxfgBMG","A2v5","zufJAW","Dw5mCuq","D2jbyMO","weTRBxi","yKX1zum","CMvKDwnL","mtb8oxW0FdC","zKTdq1y","CxbLDvO","zNjVBuj5Dgu","zMDdy0e","ChbjA0y","tMfTzq","v0P1B2W","DwTHDM4","zgvMAw5Luhi","revrvNG","vhf0seq","FdL8ohWW","AMjQv1m","zMnIwuG","uw9Ivg8","zurnyK8","CKTtD1m","r1f3AvK","D0vSB3y","DNfPAwu","AwXLtMfTzq","D0DtrKq","weXfDxa","rwL0wg8","wxzzrg0","t0HMwLy","DLrPwu8","Bu1kDKe","CMvHzg9UBhK","A2LiDuG","BMnLq2XVC2u","r2TMDxy","txDWBei","tLPgDLa","D2vUqLi","qxPPEgC","r3LKzNy","DLzvChi","BMvLzf9Hy2S","Ehr0C3i","CNnVCKzPBgu","z2vtEw5J","CMDfEuW","whvHreC","quDRtwC","Cw9Z","zNjHBwvuExa","t1fOu0y","Bg1xz1i","EK55zKS","x3jLy29UBMu","qNjPzgDL","BMvY","x2rYB3bhBg8","AxHqENi","q09esvG","BML0AwfSAxO","sxnjCvi","BKXPBMu","twLWC2C","x3bPBMDmB3m","DMvYC2LVBG","De1HBMfNzxi","EwrUAK4","rNbSswO","wMLutKe","BfLoCe8","DMvYC2LVBMm","tLPjChC","z3H2shK","vfPJAKi","C2v0sxrLBq","B2fOAMW","A2v0ignVBNm","ruDPrMC","zw5HyMXLqxu","rhr0ExC","x3bHDgHlzxK","BMDLza","twrOr3K","C3rHCNq","DhjPBq","C3Piwhu","q2zoDu0","m3WYFdf8nxW","q0jHAe0","DfHdtLy","mJa5mZGYnKvMBKLdyW","tg53AeC","wvfAANy","jMPZy2fSBgi","BfHrCwe","zKzKCgy","tNfLr08","ChjVy2vZCW","D2TTuKK","BMv3vMvYC2K","zMzwA3G","AgzkuMG","su5tvefova","C3rYAw5N","C29YDa","sfzQrgy","DwrNvMi","x2rLyNvN","x29UrxjYB3i","suzeB24","Dfj4v1C","vNH4ChG","yMzcweu","zenAEeS","C2v0u3rVCMe","C0Xf","D24GCMvHC28","DLjuzui","ufjJy2u","shDtC2O","v2vIu29JA2u","z1rPBwvVDxq","v0TTEwK","ihbYB3rVy28","Ahfhy3C","y013req","suPouKu","mdaWmdaWmda","lcbTyxGGCMu","yMLUyxj5","C3rYAw5NAwy","C0T1q2S","qwPtDNC","CMXlDfi","Cu5Vrw8","DM1ovfq","y3r4","Ae10uxe","yxrLq291BNq","rMnlsuK","zxmGCMvHy2G","CfbeCg8","ugrJywO","yujHtvy","BNjSvfa","CgDVAuy","q3j3weG","Cg9W","swHvDgS","yMznrKO","CMvZzxrfBMq","yxv0B21HDgK","x2DLBMvYyxq","CMvZzxruCMK","zwrPyxrLBhK","y0XPDNi","BhLquvO","C1vODLK","rNDxBei","vgrKCwy","u1LTt1K","zKrOBvG","AKPKuvC","uwfPsMi","Cgf5Bg9Hzeu","zxrxB3jRq2G","tMLTrhi","wvjZy0q","tffbA04","EwvPB3q","wKTuvwC","sfPkCMy","ywXSB2nvBNm","x2fKzfDZtgK","nhWZFdf8mhW","C0XPC3rLBMu","uNzcz3u","B25pCgvU","sfvHshG","uNvqzwe","DvLmDfG","CMLLC0nVDw4","CxfVr1G","tKTkBfm","x21LC3nHz2u","yw5Hz2vY","r3vovKS","zMzmAw5L","C0LuDvi","yw5Xuw8","u0PABgO","Eef1ru8","tuTTyLK","ywj4AM4","zNjVBunOyxi","ANnjtuS","uxHuD0K","CgvYC2LZDgu","ExbL","ugLpv2u","C2fNzq","yMXVy2TLza","yMnIqMG","ELr0tee","m3WY","zxH0zw5ZAw8","y1Pny24","vwfRu0S","ru1cvfm","yw5Nzq","sxPAEuy","B25ozxr3B3i","venltNi","BwLUAvbYB2C","v2LXsxm","DeL2C0y","uxrhsu0","tNfktMq","BwjHvNa","qNPzrMi","EgHcDhe","mhWXFdr8nxW","B2nRzxrtDwm","twnjzgq","EuPuyve","BfHAqK8","yw1Lu3bHy2u","CMvQzwn0","svPzu1i","Ae1LC3nHz2u","ChjVDg90Exa","Cgz2ueC","t25Mu1i","s3bMt0W","BLrTy0u","BwjtqKu","r0TsqMu","y1P3CvK","tvnor1i","vwT4wvq","EeHqEhq","whPVteu","yMztD3u","txvSwge","yM9KEq","DgHHBIbSB2m","yw5ZzM9YBvq","qvrIvxC","tMPQuu0","EMfVte4","rwnrtNa","zgPSzhC","B3bLCNr5","DLPXAuC","Cgf5Bg9Hza","sNvxCfK","wu9fD2u","rfb1sw4","vw5PBxbSzw0","z2v0q3vYCMu","AhLswKu","x3vYBa","rej6sMe","y3jLyxrLrxi","uNDpDhy","zxHWB3j0CW","BLnsy3C","CgfNzxnOB3C","zhnYBgW","AvzJDhC","tw10t2m","ywDLrxzLBNq","wfzYCgC","zxjYB3i","t3vVvxO","qKDZs2i","vuD0Bxq","BLf5ywq","B2zMBgLUzq","x2XPC3rLBMu","uMLyyLi","yvzzExG","ngzcBeDmwG","y3vYC29Yx2y","u2Hnu1i","suDkzgy","Cw51BKy","y2fdvwK","m3WXFdb8mNW","x3fVC0rc","BwPbAKi","x2HHBMrSzvi","qwT6r3G","nNjtCwPwqG","tgLZDgvUzxi","v2LUzg93","EwfPCgS","zw1LBNq","ruXPzxG","CgDwtfG","CgLUz09Uy2u","CMvZzxrdB3u","yxKSihrYEsa","Ec1TC2CTCw8","D1rVwNa","tLb4ALm","sNvnAu8","x2n1CNnVCK4","EvHwDxG","rhvvz3i","Cgu6ia","yxbWzw5Kq2G","yM9L","AxjwyNK","r1rby0C","Bxv1yNC","zMXyzxG","vxHJvKW","sMPpDKG","ChjgEw4","C2v0q3vYC28","CwzbD08","nte2mtqYneT0BurlvW","B3bLCNr5tMe","zwn0","EhP3wK0","qLPcDwe","BMCGDxjSoIa","zxjFCw9Zx2e","m3W2FdD8nhW","DwHqsLy","u3rYyxrLz3K","rKLmrv9ot1q","yxnL","vxzkv0m","qwTyyue","x2LZqNjVD3m","v0Dhwfa","ruzACum","C0ndB2W","nxWXmhWYFde","DgfYz2v0","B25fCNjVCG","zNDZxZeUmc4","ENDbDve","ywr2yw5Jzq","v1vXDNe","vw5Oyw5KBgu","B25JBg9Zzq","Ee5izNG","Ewn1Aw8","Bwf4twvZC2e","shPXzu4","BgvY","qxLOwfe","q2LgBvG","BwvZC2fNztO","CYbWyxjHBxm","Bg9N","zv9ZDwnJzxm","CuLYrxO","r0j5B2S","uMjtCLK","vxbZtuC","zv90Aw1LB3u","B2ftzMe","AM9PBG","wxPbyLC","BenPquy","ywDL","qLPpyxi","DLvgCMW","tKXzquG","zfDVCMTLCKC","rgD5EwK","uezAtw0","shnizu0","zxjFBxnNAwq","AgHXzw0","z1fTBfm","BMjHzeq","rKzkuuG","CMrUEw8","rLDt","BwnIrxC","CerpBKq","AgLNAa","te1fANq","Duv3q3i","rLbWCKW","DwXqqxq","x0rctMfTzq","ugHjCuG","yKjgyK8","C2vYDMLJzs0","CMvUDevUzha","zgrjrcWGzgu","y2HnyxHdB3u","x2LUDgvYDMe","shztzuq","EwXeB3e","DxbKyxrLq3u","vLf2zKi","q3vZDg9Trxi","Ew1rvfK","y2vZC0HHBMq","v2jquuG","y2HnyxHuCMK","AefJA01LC3m","DhPuENe","zgvIDwC","ufnAEfu","D3nZoI8V","reDeuKi","zw5JB2rPBMC","AgvHzgvYCW","zxq9DxrMltG","q0Xpu0ve","Chv0","x3nLBMrby2S","uMThD3u","A2j0qxa","ihrYEsbYzwm","tg9Nsuq","AxLxrK4","ywPIwuG","x29UvgLTzw8","reiGzMfPBgu","turPyKW","y291BNq","vhvYz2W","ELrnEgC","zNznvw4","BM93","Dw5ZAwDUzwq","CwDqr1y","zgPIAfu","zw5HyMXLuw8","Bg9Nsurhzw4","uK9hEuG","C0nVDw50zxi","Duvqs2O","y2fSBa","DhHrExa","zMHKsvC","DKTutwy","sxD0wha","mhW0Fdf8mNW","vu9jq1O","C0PcCuu","zgf0yq","zMLSzw5HBwu","B3vUDa","uNbnChu","Dxrjza","v3v4qM8","CgLUz0LUDgu","C2DnvwK","y2f0y2G","qvfytuG","AgvHzgvY","y1P4Aey","tgTVDvC","wgLhvgG","yvbHzha","CMvXDwLYzwq","C3rgAMy","BKDKq2W","CvboAwq","yMHfr20","A0DgCeu","EwHysuK","rNv2s2q","CeDwDu0","Cejluwm","AvHiweK","x2LZtwLUAvq","Bhm6ia","twr2CLu","yvLMt2K","BMrWB2LUDca","zcWG","CeTAAwG","vwvVA1y","yxnZAwDU","yw1L","x2LUAxq","v29pv0W","EwTQyue","CM5wy00","A2npv3m","Dw9lrxG","EfHPrLe","CwT5v0y","DNnWCwq","yNL0zxm","DMfSDwu","CMvHzfvjBNq","EwPOAeO","DwHiwuW","rLfHuKe","s3DoyNi","q09otKvdveK","tLfPBMe","y3jLyxrLt2i","vfPeCMq","x2HHBMrSzu8","zNnAsvG","D3jPDgu","C1bmqNO","y0PpDMW","B2zM","A3fWvMG","v2nWsLK","tuzkCxu","y3vZDg9Tshq","y3vmzfi","Dg9mB3DLCKm","CgfiCwy","A2v5CW","C3jJ","uxPruKC","B25LCNjVCG","B25TzxnZywC","zMXVB3i","B2zMC2v0","ihrVihjLDhi","zMzLCG","zgPlCKO","u0vtAMq","y2XVC2uSihC","q0Xpu0LorW","BNr6zxy","B2zqwK4","rLPLA2K","Au9RtKy","zhPjy3e","Aw5PDcbrB1m","s2XSENi","sMTvrxi","AvfYrw4","zKrHr3u","CNvtzva","Aw5KzxGGB3u","tMPdsLa","CMfTzq","zLHbtem","D2LSBfjLy28","yxGGCMv0CMK","BK1wwvi","y3vYC29Y","rKL2vLG","zgjyuuK","BLfst0O","BejPrw8","u0vUAhG","uNvVExq","x2rPC2nVBM4","zhbMC08","zw5OtuO","EhPtB2q","zgvJB2rLzey","AuzqBwm","zMLSDgvY","uLPLtxG","q09oveLovuu","zM9Yy2u","x2LZsw5PDa","v0vKu1G","q2v3Cva","Auz2Afi","zxjFAxnFywm","BwDcyMm","D252swW","Bgfjquy","teHdD1e","y29TCgXLDgu","x2HHBMrSzva","Dgv4Dc9WBge","yNvMzMvYzwq","wfnjA3O","tMLtBK4","swXirfy","wej4rMe","C21Ly1G","z3bVuvK","zwXwyvO","quTguKG","AgnHt1u","v1LluM0","CgLUz19VBMm","yxbWBhK","zw5JB2rLrNi","x2nSzwfYugK","tLLwB0C","yKLwuwe","Dg9Y","tNbXuKK","x3bYzwzPEa","AwvsvxO","BeHHBMrSzxi","C1jtqNK","r3LMCKC","sfDrtxa","zhzVv0i","zgv2AwnLx2K","teTuzfu","Cwf5wey","DgLUzYbZzxi","Aw47y2HHCNm","y3vYCMvUDeK","vhHJwKO","Aw5JBhvKzxm","o2nOyxjZzxq","y2TZAvu","Bvj6B2S","zKjlBg0","CMvHC29U","DhjPzxmGCMu","u2vXsuq","BMDey0G","AgvKtwf4uMu","CMvTB3zLq2G","rvPrExm","BgTgC00","C2v0y3vYC28","CvD3sgC","uwXIEwu","ihn1y2nLC3m","Aw5L","z1fNEge","yMLZr2O","r2Hjvfa","wuHMtK8","yNLL","x2DLDeLUDgu","z3fTEK4","BM5Ly3q","y21etKy","mNWZFdb8mxW","zwzVAwe","wevKt0i","zLnMvuW","vxLYwMi","zvvYBa","CMfhEeS","B013uLK","uvPOELK","AxnrB1nby2S","AuTmt3q","uNf4uhG","BNblDKO","C3vJy2vZCW","Cg5sr2y","EfvZzuvUDG","swXJugm","rMvvs04","DKDMDKG","y3jLyxrLt3a","zw50","x2nVBM5Ly3q","whDrywW","thznuLG","AKf0rgS","C2Piwgi","vwXTy3e","x3bPBMC","Ec11C2uT","wg96zwK","CgDkBvK","x2LZv29YA2u","AxD0thy","ENb3vuG","ugrnyvu","t2Lqrvm","rKXTs1q","BwfUDwfSihi","D3fAzKe","DgzouLO","Dxv0qLy","y2HLy2TdDxi","ywnOzwq","t1bftG","zfjss0C","AgfZt3DUuhi","B3jRzxjhBg8","B3bLBIa","y29SBM8","ihrPBwvZ","C0jf","D1L5DNe","x2jPBMfYEvq","vhjwvw0","DgvZDa","y29UBMvJDeu","CND6ruy","rMfwCuK","AKTPBMe","y29UDgv4Da","s0zszuG","B25tDg9Wsw0","CxvTqKO","DgLTzw91DcW","rgrgAeG","pxv0zI04","igzHAwWSig0","Avzsv3q","AxnFywnR","uxjzs1a","D3HWqKm","zcbLCNjVCI4","mJa0nZC4mePHAg9PDq","yMLUyxj5vhK","A3Pbz1K","B25TzKO","Bwf4tg9ZC0m","CfbkrKC","ENzYueC","z2vjBMzVu3K","s2zjsu8","C2H3DMO","Dg9oDw1Izxi","AKXttMu","rK1qwMG","DhjHBNnHy3q","wuXTEwq","B0rvueC","B25szwnLAxy","qw1VDw50","BMvdC2C","zNfwENO","EfDIyKq","CM9YrxzLBNq","y2HLy2Tszwe","vgXKy2y","z2f6weu","qKLXsvi","D1fgz0K","icSG","vgPzENq","CNzHBfzHBhu","y29UBMvJDca","ywnRDxbfBMq","x2LUAxrhBg8","B2LUDfjLywm","twzuqLK","EwzAquC","wKr4wuO","twLZC2LUzYa","D2PpB0m","rxPvCem","quXm","BgjNC2e","A3nfuLG","AwXSihvZzsa","z0j5z04","qvrJEve","uKTUy1u","B2nRzxrgywK","sfnsyNi","BfnWwLG","z3PXu2O","Ahr0Ca","vhPVzxy","sgnrzuu","x29UtwvZC2e","BwHAz0C","BezSDxnO","CwDVB28","BMrLEa","CgLUy0O","CvDpsu0","z3jfwem","suLmDMm","BMTzwwW","u3DnCuS","tLvjDfO","CKfiBK0","AuXyCgq","vMDfs0S","Bg9NsurozxC"];return Un=function(){return r},Un()}(()=>{let r=b,e={UBMFT:function(s,t){return s<t},sjRJD:function(s,t){return s===t},AKFRH:function(s,t){return s&t},SlJGe:function(s,t){return s+t},Wzfxr:"uciWL",VxEhj:r(1044),Vmjfj:function(s,t){return s(t)},xNHfx:function(s,t){return s+t},AQXMH:function(s,t){return s+t},fUfYU:function(s,t){return s*t},gxvHy:function(s,t){return s+t},TvzWc:function(s,t,n){return s(t,n)},YuIvQ:function(s,t){return s(t)},vDGPE:function(s,t){return s(t)},IYXGw:function(s,t){return s+t},COQpZ:"0000",qfAwO:r(338),nTmcE:function(s){return s()},cpsuj:"get",UIqkb:r(290),ztTVR:r(910),Gkfuv:r(342),bfqLQ:r(1579),IhUtk:function(s,t){return s===t},OeHlf:r(386),wnvIl:r(633),AkzGx:function(s,t){return s(t)},FwWlB:r(619)+r(619)+r(619)+r(619),WcpJY:function(s){return s()},BUnAP:function(s,t){return s(t)},jECzi:function(s,t,n){return s(t,n)},dCZxK:r(1642),qdtVx:"Rjcdk",AieVq:function(s,t){return s>t},MVGZI:function(s,t){return s!==t},xjTba:r(267),MfTBY:function(s,t){return s-t},zaQVV:function(s,t){return s!==t},MdhGy:function(s,t){return s===t},OqVFG:r(1302),cJOvl:r(760),TcBGs:function(s,t){return s!==t},lCiAF:function(s,t){return s-t},fnfXA:function(s,t){return s!==t},QobTo:function(s,t,n){return s(t,n)},iXHXI:function(s,t){return s!==t},XVrpg:function(s,t,n){return s(t,n)},WYKRm:function(s,t){return s(t)},CBahM:function(s,t){return s(t)},itvic:function(s,t){return s>>>t},krZPp:function(s,t){return s(t)},SWQGD:r(1240)+r(957)+r(243)+r(988),IlcPc:function(s,t){return s!==t},QsIgM:"ehPJc",djldw:function(s,t,n,o){return s(t,n,o)},PVBOy:r(533),cAjBC:r(1199),HviUS:r(401),PRcce:"ack_code",yRkuO:function(s,t){return s<t},MCofa:function(s,t){return s+t},AGxCm:function(s,t){return s-t},VmPmd:function(s,t){return s<<t},YYHJT:function(s,t){return s!==t},faooq:r(1182),JvAMJ:function(s,t,n){return s(t,n)},cmDNF:r(1487),faFCu:function(s){return s()},fpyaz:function(s,t){return s!==t},YQZjv:function(s,t,n){return s(t,n)},GyfrG:function(s,t,n){return s(t,n)},zLHVn:function(s,t){return s!==t},tzTzq:function(s,t,n){return s(t,n)},cqkQU:r(512),drUXK:function(s,t,n){return s(t,n)},wkmRI:function(s,t){return s!==t},kzAgY:function(s,t,n){return s(t,n)},AGkMg:function(s,t){return s===t},pDpEK:r(962),DCnOK:r(772),Tmqve:function(s,t,n){return s(t,n)},VLqKa:function(s,t){return s!==t},xhAQQ:r(997),UlShL:r(303),neCsg:function(s,t){return s(t)},FeUKN:function(s,t){return s(t)},PiOWe:function(s,t){return s(t)},GTAcG:function(s,t,n){return s(t,n)},hWAdN:function(s,t){return s(t)},qgooo:function(s,t){return s(t)},zvrPG:function(s,t){return s(t)},qpeuZ:function(s,t,n){return s(t,n)},VqXYT:function(s,t){return s===t},lXZBO:r(1240)+r(957)+" field: "+r(1111),SPSht:r(1240)+"required"+r(243)+"LogID",HSRbr:function(s,t){return s===t},ozTof:r(1240)+r(957)+r(243)+"service",YQtwn:r(1240)+r(957)+r(243)+"method",fKCCV:function(s,t){return s instanceof t},NVaHd:function(s,t){return s(t)},yaipk:function(s,t){return s!==t},GWfKm:r(331),PSZxU:r(1344),SJZlj:function(s,t){return s+t},AXxZn:function(s,t){return s+t},elVaZ:function(s,t){return s>>t},EAmBj:function(s,t){return s>=t},XvhOH:function(s,t){return s!==t},rIJVY:"qYhMS",hDuHA:function(s,t){return s>t},wmOcz:function(s,t){return s+t},ekOOh:r(347)+r(1714),SrfAG:function(s,t){return s+t},ZttXV:function(s,t){return s!==t},DFbZl:r(1531),oMwRY:function(s,t){return s>t},ybWeO:function(s,t){return s>t},yIjVk:"Read pas"+r(1714),wqZfA:function(s,t,n){return s(t,n)},APxCK:function(s,t){return s+t},hfJRh:function(s,t,n){return s(t,n)},iUXtw:function(s,t){return s<t},RXvDe:function(s,t){return s===t},LKTdU:function(s,t){return s&t},wadEg:function(s,t){return s&t},WUaWg:function(s,t){return s>=t},xCcjn:function(s,t){return s!==t},pPJFG:function(s,t){return s!==t},MQEcS:"Vfapq",nGdCl:function(s,t){return s|t},NqeGO:function(s,t){return s<<t},QyvHg:function(s,t){return s&t},WoOWL:function(s,t){return s&t},XKkmr:function(s,t){return s<t},grEXC:function(s,t){return s+t},fqonw:function(s,t){return s+t},RxtVe:function(s,t){return s!==t},RKncU:function(s,t){return s<<t},JpsQJ:function(s,t){return s|t},ektCe:function(s,t){return s|t},iYSYn:function(s,t){return s<<t},DKgzH:function(s,t){return s&t},vwliH:function(s,t){return s<=t},OCfcQ:function(s,t){return s>=t},kJDRY:function(s,t){return s+t},HdFEu:function(s,t){return s!==t},bnCUB:function(s,t){return s|t},EGiFg:function(s,t){return s|t},uMWHz:r(420),bivtd:function(s,t){return s|t},WbPQH:function(s,t){return s|t},jrKvq:function(s,t){return s<<t},qWwHg:function(s,t){return s<<t},XrqRC:function(s,t){return s<t},YJUjk:function(s,t,n){return s(t,n)},zTtLA:function(s,t){return s>>t},tXCNV:function(s,t){return s&t},Gydfv:function(s,t){return s>=t},EzUpC:function(s,t){return s+t},OqxBS:function(s,t){return s+t},pDrJm:function(s,t){return s<t},BzYFb:function(s,t){return s-t},UgWsS:function(s,t){return s+t},FZeki:function(s,t){return s<t},qoGNy:function(s,t){return s>>t},EEMoy:function(s,t){return s|t},wdTCF:function(s,t){return s&t},FXyUh:function(s,t){return s|t},LnwhG:function(s,t){return s>>t},EHUSv:function(s,t){return s|t},UuOTw:function(s,t){return s&t},LkouW:function(s,t){return s<t},Mipsg:function(s,t){return s+t},yvKxW:r(261),cPpGO:function(s,t,n){return s(t,n)},RSJQQ:function(s,t){return s<t},jLSNe:function(s,t){return s>=t},piRwp:function(s,t){return s|t},FJRWG:r(1623),UvJWC:r(1311),VJbHb:function(s,t){return s in t},OEEzu:function(s,t){return s(t)},EitXo:function(s,t){return s&t},htapc:function(s,t){return s&t},CewqP:function(s,t){return s(t)},YpiHO:function(s,t){return s<<t},vKTMf:function(s,t){return s&t},uCqtr:function(s,t){return s===t},eUjMV:function(s,t){return s&t},Tldcf:function(s,t){return s<<t},iDCCH:function(s,t){return s&t},NZFvP:function(s,t){return s<<t},wjOoC:function(s,t){return s<<t},tgACA:function(s,t){return s&t},lVuJU:function(s,t){return s&t},BcpTs:function(s,t){return s&t},fFdpf:function(s,t){return s&t},ZMXlY:function(s,t){return s(t)},tlKEf:function(s,t){return s<<t},gArSY:function(s,t){return s&t},OQhSF:function(s,t){return s<<t},WVCeb:function(s,t){return s>>>t},GuNVK:function(s,t){return s>>>t},MPymV:function(s,t){return s<t},EYrxj:function(s,t){return s<t},lcKUH:function(s,t,n){return s(t,n)},qNoEo:function(s,t){return s+t},QaJKR:function(s,t){return s&t},frcjT:function(s,t){return s+t},MHfzp:function(s,t){return s|t},zwAuQ:function(s,t){return s+t},DPuIn:function(s,t){return s!==t},UyrZb:function(s,t){return s&t},DKAAv:function(s,t){return s|t},lyPQZ:function(s,t){return s>>>t},abxjn:function(s,t){return s>>>t},rZxYB:function(s,t){return s+t},myTOm:function(s,t){return s>>>t},gRSlU:function(s,t){return s!==t},rQCil:function(s,t){return s>>>t},bfMFJ:function(s,t){return s&t},CdtEH:function(s,t){return s>>>t},ynBgn:function(s,t){return s&t},Maijd:function(s,t){return s&t},vZqiG:function(s,t){return s(t)},jbjWS:function(s,t){return s|t},YzAbW:function(s,t){return s|t},AgRqp:function(s,t){return s===t},mmbmd:function(s,t){return s|t},yJTaQ:function(s,t){return s<<t},zaoLN:function(s,t){return s|t},WdbLR:function(s,t){return s|t},pGCjK:function(s,t){return s|t},ixPzr:function(s,t){return s<<t},djKrJ:function(s,t){return s|t},RyVee:function(s,t){return s|t},QtGIM:function(s,t){return s<<t},djbhU:function(s,t){return s<<t},IsIqR:function(s,t){return s|t},QaiJb:function(s,t){return s>>>t},pGnyS:function(s,t){return s|t},KfIIO:function(s,t){return s<<t},uutBV:function(s,t){return s|t},oAVqR:function(s,t){return s&t},eHwtd:function(s,t){return s>>>t},SlLhY:function(s,t){return s>>>t},XaGMM:function(s,t){return s&t},iyWFN:function(s,t){return s&t},jOIXw:function(s,t){return s&t},VpATF:function(s,t){return s>>>t},fUIbh:function(s,t){return s<=t},vtICE:function(s,t){return s%t},lBiEo:function(s,t){return s/t},nSRcw:function(s,t){return s+t},HqpdK:function(s,t){return s*t},WMJIP:function(s,t){return s>>>t},IzZyF:r(1556),vRPzm:function(s,t){return s&t},ShMSR:function(s,t){return s&t},OMQos:function(s,t){return s>>>t},lAXxL:function(s,t){return s&t},Azixg:function(s,t){return s>>>t},Kanea:function(s,t){return s+t},SESjd:function(s,t){return s+t},NNvwy:function(s,t){return s|t},FAwhD:function(s,t){return s|t},fKogA:"MqEam",qOqCu:r(1716),SsajM:function(s,t){return s!==t},oRvuZ:function(s,t){return s>>>t},CcbKP:function(s,t){return s===t},lXQqa:function(s,t){return s===t},zNyfK:function(s,t){return s===t},fDhmX:function(s,t){return s===t},AyhXQ:function(s,t){return s===t},yopGS:function(s,t){return s+t},McIdd:function(s,t){return s+t},PLyAN:function(s,t){return s>>>t},UvWFS:function(s,t){return s&t},xzSod:function(s,t){return s>>>t},pmxtA:r(1591),PZLIc:r(680),EhzKW:function(s,t){return s&t},gQmlS:function(s,t){return s>>>t},iEtRM:function(s,t){return s>>>t},UeokV:function(s,t){return s>>>t},nQROJ:function(s,t){return s&t},NpqRI:r(1480)+r(1387),rdnyo:r(994)+r(256),pwsUg:r(1378)+"IES_ERROR",gGngJ:r(477)+r(1683),nGmXH:"OPEN_ERROR",ieRUz:r(1681)+r(273),RIkTB:"EwDGU",NjCJP:function(s,t,n){return s(t,n)},vDwNw:function(s,t){return s<<t},icUhe:r(1422),UGtmt:r(939)+"5|6|3",pRMTZ:r(417)+"4",smecX:function(s,t){return s===t},NlSou:r(1245),lmWgR:function(s,t){return s===t},Ruoyt:r(953),MmtOc:r(1738),iVctw:function(s){return s()},SwMqK:r(1188),irVby:function(s,t){return s-t},JwXku:function(s,t){return s===t},MCQXw:function(s,t){return s==t},KlUhy:r(1413),VCKQL:function(s,t){return s>>>t},iOkNF:function(s,t){return s<<t},Dbwkp:function(s,t){return s>>>t},UFkVt:r(294),MSNGR:"RYIFP",HuGgb:r(501),oCLvt:r(839)+r(1202),MwplB:r(765),rnVcM:function(s,t,n){return s(t,n)},bLwjt:"open",IZYSR:"close",kcYTz:"2|4|3|1|0",BwADJ:function(s,t){return s+t},BZBua:function(s,t,n,o){return s(t,n,o)},JjOvH:function(s,t){return s<t},eycWC:function(s,t,n,o){return s(t,n,o)},aYgzM:function(s,t){return s===t},QzQRG:"RgHyA",Xozei:function(s,t){return s instanceof t},cIcKO:r(1229),vVUpr:function(s,t){return s||t},nbadD:function(s,t){return s||t},bIVQa:function(s,t){return s!=t},vnNgt:r(462)+"d",wbAbj:function(s,t){return s!=t},DBzJa:function(s,t){return s<t},FIvVX:function(s,t){return s<t},Kllzr:function(s,t){return s===t},oNSSN:function(s,t){return s&t},rlKtR:"OLnXd",yTvGC:function(s,t){return s<t},HwSsj:function(s,t){return s<t},VBSWn:function(s,t){return s<t},vYesv:function(s,t){return s&t},vqiie:function(s,t){return s|t},KAJMI:function(s,t){return s|t},pDOnD:function(s,t){return s<<t},zpwUH:function(s,t){return s|t},WLgry:function(s,t){return s|t},gPjiM:function(s,t){return s|t},vRTeB:function(s,t){return s<<t},wGSFD:function(s,t){return s&t},GhITP:function(s,t){return s<<t},itGBx:function(s,t){return s&t},yiDwl:function(s,t){return s+t},HZJrf:function(s,t){return s<t},IILvc:function(s,t){return s===t},rvPUk:function(s,t){return s===t},GyWwE:function(s,t){return s&t},EMBTS:function(s,t){return s+t},MIuLj:function(s,t){return s+t},DjWsb:function(s,t){return s<<t},ngDcH:function(s,t){return s&t},VRqZc:function(s,t){return s&t},hWFnL:function(s,t){return s>>t},juYIi:function(s,t){return s&t},DyNFH:function(s,t){return s|t},jerXv:function(s,t){return s&t},sCPcb:function(s,t){return s>>t},cLpCe:r(1082)+r(851)+"s",FcKII:"string",RqxPx:function(s,t){return s===t},wJVRj:r(912),whfxu:function(s,t){return s instanceof t},EuPff:r(1442)+"ion/json",RbSrY:function(s,t){return s==t},WuxBo:r(804),aueYL:r(1316),iQrEn:function(s,t){return s!==t},KFReH:"unknown reason",kcOWs:r(1145),PdMaU:r(1377),gTefg:r(585)+"ack=frontierJSONP",bisGj:function(s,t){return s!==t},bCUjz:r(1483),QMzuC:"nNxTk",LcYfn:function(s,t,n){return s(t,n)},VYklx:r(1132),bLueC:function(s){return s()},mMJvA:r(1144),AUYop:function(s,t){return s===t},AjSvw:r(1175),mcbEw:function(s,t){return s===t},udqcL:r(1184),cLivr:"ytgxK",VYHgc:function(s,t){return s*t},ykjaA:r(1093),unLqD:function(s,t){return s!==t},wETxV:r(1308),LdvkJ:r(739),Tzoev:function(s,t){return s===t},SEnhx:"fqvQP",PWuHz:r(985),gBWgT:r(1488),TdExf:function(s,t,n){return s(t,n)},rGDuW:r(1131)+"4",fvMUn:function(s,t){return s===t},YqsvB:"DucQz",cuLdR:"UYsiG",eZgfk:function(s,t){return s|t},ZQvMQ:function(s,t){return s&t},XSIkz:function(s,t){return s<<t},YvYDm:function(s,t){return s+t},fDaGu:function(s,t){return s>>t},nrlTP:"bsbcA",XBFRF:function(s,t){return s|t},nhmLB:function(s,t){return s&t},tfNRZ:r(1547),FPprL:function(s,t){return s&t},sCCol:function(s,t){return s&t},nkYYl:function(s,t){return s&t},gqmzN:function(s,t){return s&t},enhMJ:r(960),iVRWt:function(s,t){return s||t},KZbap:function(s,t){return s||t},hYoao:r(1595),VGiLs:function(s,t){return s||t},hMtQq:function(s,t){return s||t},HBfuq:function(s,t){return s||t},rPFvL:function(s,t){return s!=t},OKHCb:r(1029)+r(919)+"d",oDUPG:"3|0|4|1|2",xXiFQ:function(s,t){return s!==t},zJQGi:r(1731),rKAGP:"ovDRx",YoTjB:function(s,t,n){return s(t,n)},YOEwe:r(540),MifXr:r(234)+"id",vtwIc:function(s,t){return s(t)},uhPJV:r(211),KWLDJ:r(759),ZRvVF:r(770),HWQMp:r(1763),Qlbye:function(s,t){return s(t)},gWHZy:r(1554)+"er_qos",AIkxp:function(s,t,n,o){return s(t,n,o)},ltScx:r(1554)+r(1063)+"k",wElov:function(s,t,n){return s(t,n)},ZDxYJ:r(1554)+"er_ack_msgid",MFJqu:r(1126),bAqfb:"fcsJX",rHZJG:r(986),IFoXP:function(s,t){return s&&t},IFDon:function(s){return s()},FZkhR:r(228)+r(311),fXALC:"http",hxXKS:function(s,t){return s(t)},eogPB:function(s,t){return s(t)},afsnT:function(s,t){return s!==t},dBSTL:"MUpkJ",OnfSR:function(s,t){return s instanceof t},yeiot:function(s,t){return s instanceof t},rVBkz:r(1070)+r(1101)+r(908),QqSmM:r(1442)+"ion/json"+r(1105)+r(1196),ONnvz:r(380)+"e",kPLtd:r(621),jKina:function(s,t){return s<t},LxuWR:function(s,t){return s>t},umrsI:function(s,t){return s>t},AGlUk:function(s,t){return s!==t},yfZAG:r(373),XLEup:function(s,t){return s|t},IzatC:function(s,t){return s!==t},EcQNp:r(1406),LvMRX:function(s,t){return s||t},YawTl:function(s,t){return s(t)},NUItZ:function(s,t){return s+t},pgoiF:r(1230),dWPhA:" > ",LwbTz:"integer "+r(1495)+"e",iLPwX:function(s,t){return s+t},nSIBk:function(s,t){return s<t},rAHnM:function(s,t,n){return s(t,n)},gZUsh:function(s,t){return s<t},yMTBF:function(s,t){return s+t},nNDxD:function(s,t,n,o){return s(t,n,o)},HcTYT:function(s,t){return s|t},URByT:function(s,t){return s<<t},WROJO:function(s,t){return s+t},ozZnh:function(s,t){return s+t},PnNzo:function(s,t){return s|t},WEdSX:function(s,t){return s|t},XzwpW:function(s,t){return s<<t},ntzev:function(s,t){return s+t},NEbkH:function(s,t){return s<<t},lkFsM:function(s,t){return s>>>t},iMToE:function(s,t){return s+t},TdolA:function(s,t){return s+t},zTzEY:function(s,t){return s&t},EkXxG:function(s,t){return s&t},RzwaH:function(s,t){return s>>>t},GByok:function(s,t){return s+t},WPwfC:function(s,t){return s&t},MBcRV:function(s,t){return s>>>t},CiFmX:function(s,t){return s>>>t},ydnjN:function(s,t){return s&t},wToZp:function(s,t){return s&t},XwQal:function(s,t){return s+t},GKRBe:function(s,t){return s<t},kORcm:function(s,t){return s|t},fqVzz:function(s,t){return s<t},dcLKx:function(s,t){return s>t},zDJVj:function(s,t,n,o){return s(t,n,o)},nNhaV:function(s,t){return s>>>t},BZOar:function(s,t){return s|t},sjHXb:function(s,t){return s<<t},MAuBv:function(s,t){return s&t},QNmKV:function(s,t){return s|t},OLmpj:function(s,t){return s<<t},vktJY:function(s,t){return s&t},Ikaid:function(s,t){return s<<t},AGCgL:function(s,t){return s>>>t},bhEGm:function(s,t){return s|t},FFJQH:function(s,t){return s<<t},xYOvu:function(s){return s()},gugJd:"fBtdi",NnKbk:"hWmhp",cksiU:r(1606),yhXII:function(s,t){return s(t)},MwWMe:function(s,t,n,o){return s(t,n,o)},DiStp:r(952),rOlZN:r(886)+r(1296),mgBbc:r(1550),QPwtJ:r(1730)+r(295),uoKEx:function(s,t,n,o){return s(t,n,o)},rwklB:function(s,t){return s(t)},kfkSS:r(775)+"ile_name",KmKVf:function(s,t,n){return s(t,n)},gQgxa:function(s,t){return s+t},sPLBz:r(1403)+r(977),Pdcaj:r(1632)+"rValues",qayXF:r(1243),KmUOz:r(594),pGVuM:r(1057),YmDFc:function(s,t,n){return s(t,n)},tWrHA:function(s,t){return s!==t},Cdnce:"NCdfG",ahmES:"setdb",qpAhQ:function(s,t){return s===t},bfBXE:"FTVgW",QIoWt:r(1410),prFyn:r(1575),rjtVg:r(1117)+"r",fzDLM:function(s,t){return s!==t},SMJjN:r(684),xneVG:r(713)+r(696),cZMcn:function(s,t,n,o){return s(t,n,o)},TjYzt:r(1751),Turgl:function(s,t,n,o){return s(t,n,o)},vIbUH:r(1554)+r(869),aefkh:r(1554)+r(1725),GkCdM:function(s,t,n,o){return s(t,n,o)},lYNpO:r(795)+"s",lStNL:"x-msg-cursor_name",KpfOL:function(s,t,n){return s(t,n)},RvBgu:"x-msg-cursor_value",kYJSB:function(s){return s()},OhifC:function(s,t){return s+t},RwOtv:function(s){return s()},mbSBE:function(s,t){return s<t},fubPv:function(s,t){return s!==t},IJNRE:"BHvIK",BIqIR:function(s){return s()},mFSqe:function(s){return s()},LTMsf:function(s,t){return s&&t},mnrlr:function(s){return s()},VQvfB:function(s,t,n){return s(t,n)},FnqzX:function(s,t){return s===t},KebvD:r(662),HzqeN:function(s){return s()},STFDB:function(s,t){return s<t},mPqsa:function(s,t){return s===t},sABzj:function(s,t){return s!==t},mxcZr:function(s){return s()},rZBhW:function(s,t){return s(t)},DrLDG:r(1434),pBKQc:r(272),hDajY:r(1253),vhnzE:function(s,t,n,o){return s(t,n,o)},GBNNh:function(s,t){return s!==t},eiKbA:"vniYy",ALste:function(s,t,n){return s(t,n)},cncbX:function(s,t){return s===t},IabpF:function(s,t,n){return s(t,n)},fBKlm:r(821)+r(832)+r(506),pOevX:function(s,t,n,o){return s(t,n,o)},BfSyN:"service",fgCcA:r(1296),vTiYO:function(s,t){return s!==t},plcGV:function(s,t){return s(t)},pincJ:function(s,t){return s||t},wzjFD:function(s,t){return s!==t},RrSwA:r(1168)+r(298)+r(270),PbkoN:r(852),EpgDQ:r(1618)+"fer",sKawS:function(s,t){return s===t},UDMGo:r(1274)+r(304)+r(463),ukavn:function(s,t){return s(t)},xAuEO:r(1274)+r(1432)+r(849)+", WebSoc"+r(568)+r(1636)+r(1500)+r(1583),DEQVx:function(s,t){return s(t)},xHPxt:function(s,t,n,o){return s(t,n,o)},ylDoq:r(1067),TqLws:r(1597),gBygN:function(s,t,n){return s(t,n)},jIqBx:r(1362)+"t",EFZqC:"stop imm"+r(646)+" reconnect",MulXa:function(s,t){return s(t)},ckYZk:r(300),OsmUp:r(258),Ulmcq:"IKXqA",uuBtG:function(s,t,n){return s(t,n)},paHqf:function(s,t){return s===t},ryVAd:r(797),dPFzm:"ghywG",DuUgr:r(1701),kqpVh:r(904),zzydu:"ws://",uZETW:r(1513),XuaDG:r(444),vktVb:r(1097)+"d",UHAvP:function(s,t){return s||t},wenBR:r(1274)+r(1727)+r(888)+r(1674)+"r ttwID",OHfZV:"function",iTATd:function(s){return s()},RwDxk:r(389),DyCMf:r(835)+"0",KbLaY:function(s,t,n){return s(t,n)},haDRr:function(s,t){return s===t},rUkSz:"hhYTn",uEwCr:r(575),bjXJS:function(s,t){return s>t},PhIqH:function(s,t,n){return s(t,n)},utsgk:function(s,t,n){return s(t,n)},fhdIW:r(882),iKLOt:function(s,t){return s*t},CVrYM:function(s,t){return s>t},WKmyi:function(s,t){return s!==t},xgTZf:function(s,t,n){return s(t,n)},flXex:"abort",fSfUL:r(227)+"or",beOPF:r(1068),JuWpY:r(314),tRxWW:r(1082)+r(856)+"t",zbBhS:r(1436),Dgyyi:function(s,t){return s<t},UQIFD:function(s,t,n){return s(t,n)},ruSeP:function(s,t){return s!==t},QrYKP:r(366),lbgsa:r(1534),UPuRs:function(s,t,n){return s(t,n)},qthEm:function(s,t){return s===t},kkIGz:r(214),xttsr:r(562)+r(1482),MDibL:"zApwm",EWbTl:r(1620),TqtHD:r(1194)+r(914)+r(1695)+"g",aBaMV:"send_ack",TCKNr:function(s,t){return s&t},IzmqN:"hyRZE",TjrTU:r(1754)+"3",GaKbv:r(1734),yjhhJ:r(666)+"2",DGAqX:function(s,t,n){return s(t,n)},MIrow:function(s,t,n){return s(t,n)},NgBaK:function(s,t,n){return s(t,n)},mqkke:function(s,t,n){return s(t,n)},SDPTC:r(1371)+r(323)+r(1740)+r(1121),ZiTNA:r(1739),WGGXP:r(1640),wxpBC:function(s,t){return s+t},PVxXh:function(s,t){return s&t},XzoLE:function(s,t){return s&t},ajbYH:function(s,t){return s(t)},TxcZJ:r(1227),gjIJo:r(579)+r(355),ElWPf:r(1022)+"s instan"+r(1528)+r(551)+"ed",mDuor:function(s,t){return s===t},SnqbE:r(1022)+"s alread"+r(1638),xhBtq:function(s,t){return s==t},uhHYL:"please provide a valid d"+r(233)+r(363)+r(1464)+"ng or an"+r(428)+r(1019),QZhzY:"number",Vxxpx:function(s,t){return s(t)},RpMpu:function(s,t){return s(t)},vGfvH:function(s,t){return s(t)},KpRzj:function(s,t){return s||t},iMLMz:r(1274)+"rovide a valid s"+r(295),zGPbV:"sent",iNagZ:function(s,t){return s!==t},QqFnh:r(1276),dpfsO:r(1315),gpoQY:r(403),sFJbM:function(s,t){return s===t},gBXpP:r(464),CODIX:function(s,t){return s!==t},FplIj:r(1708),qbZbl:function(s,t,n){return s(t,n)},aCISo:r(475),EGTaT:function(s,t){return s/t},aynHj:function(s,t){return s!=t},IlHDV:r(787),UakSK:function(s,t){return s!=t},hcaOU:"Object",cIVNg:r(437)+r(865)+"lobalScope",qWOIM:function(s,t){return s!=t},qQnTy:function(s,t){return s!=t},NAAHD:function(s,t){return s!=t},UOICZ:function(s,t){return s!=t},YTvDR:function(s,t){return s===t},JuMiO:"SharedWo"+r(1431)+"alScope",mRzok:function(s,t){return s!=t},ffVkx:function(s,t){return s!=t},KwNbr:r(289)+"qos__"};Ce.r($),Ce.d($,{FWS:()=>g0,CustomErrorEvent:()=>bs,createCloseEvent:()=>me,ReconnectEvent:()=>vs,createErrorEvent:()=>le,decodedFrame:()=>ps,createOpenEvent:()=>Ds,CustomCloseEvent:()=>Ss,createReconnectEvent:()=>lr,FrontierMessageEvent:()=>Cs,encodeFrame:()=>dr,createMessageEvent:()=>Ps,OpenEvent:()=>As,ErrorCode:()=>Ue,Event:()=>at,MessageEvent:()=>Es});let i="";function a(s=""){let t=r,n={PxVpC:function(o,x){return e[N(1676)](o,x)},PNwfh:function(o,x){return e.UBMFT(o,x)},iFPmc:function(o,x){return e.sjRJD(o,x)},sUhvY:function(o,x){return e.AKFRH(o,x)},iYmQe:function(o,x){return e.SlJGe(o,x)}};if(e.sjRJD(e.Wzfxr,e[t(293)]))_0x2477a0=_0x4a82d2[t(1339)+"At"](_0x12f41b),n.PxVpC(_0x4931dd,128)?_0x52d0da+=1:n.PNwfh(_0x3e521c,2048)?_0x2370e5+=2:n[t(1054)](n[t(649)](64512,_0x342be7),55296)&&(64512&_0x489322[t(1339)+"At"](n[t(319)](_0x166758,1)))===56320?(++_0x2564ad,_0x3d589d+=4):_0xd883b0+=3;else{let x=""+Date[t(925)](),f=i||(i=e[t(1631)](m,s)),l=Math[t(1279)]()[t(1284)](16)[t(1330)](-6);return e[t(841)](e.AQXMH("02",x)+f,l)}}function c(){let s=r;return e[s(951)](e[s(1666)](1e4,Date[s(925)]()),Math[s(1016)](1e4*Math.random()))}function u(s){let t=r;return e[t(564)](Array(8)[t(858)]("0"),e[t(1702)](parseInt,s,10)[t(1284)](2))[t(1330)](-8)}function d(s){let t=r;return(e[t(307)](Array,4)[t(858)]("0")+parseInt(s,2)[t(1284)](16))[t(1330)](-4)}function g(s){let t=r,n=s[t(1742)](/\./)[t(1363)](f=>u(f)),o=[];return o[0]=e[t(451)](d,n[0]+n[1]),o[1]=e[t(1631)](d,e[t(479)](n[2],n[3])),[e[t(1715)],t(416),t(416),e[t(1715)],e[t(1715)],e[t(813)],o[0],o[1]][t(858)]("")}function m(s){let t=r,n={OuoUz:function(o){return e[N(726)](o)},WuoXY:function(o){return e[N(726)](o)},IfSbh:e[t(1323)],TbVwI:e[t(1588)],rgEyL:t(1703),eDMbO:t(921),uEPKj:e[t(356)],PNOok:e[t(526)],EKvpX:e[t(215)],igiJp:t(1627),YXUuh:function(o,x){return e.Vmjfj(o,x)}};if(e[t(640)](e.OeHlf,e[t(1065)]))BSdHDx[t(766)](_0x4af263),BSdHDx.WuoXY(_0x1c8166),_0x2a93f9=[BSdHDx[t(413)],BSdHDx[t(1424)],BSdHDx[t(537)],"getAllKeys",BSdHDx[t(510)]],_0x467796=[BSdHDx[t(933)],BSdHDx[t(1656)],BSdHDx[t(397)],BSdHDx[t(1679)]],_0x5a7cc7=new _0x311d13,BSdHDx.YXUuh(_0x279cc0,o=>({...o,get:(x,f,l)=>_0xd60971(x,f)||o[t(1477)](x,f,l),has:(x,f)=>!!_0x27057e(x,f)||o[t(1520)](x,f)}));else{let o=/(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),x=/(([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 o?e[t(784)](g,s):x?w(s):e[t(650)]}}function w(s){let t=r,n="",o=[],x=0,f=0,l=!0,p=e[t(1715)];if(s.indexOf("::")>-1)if(e[t(605)]!==e.qdtVx){let h=s[t(1742)]("::");for(let C=0;e.UBMFT(C,h[t(1313)]);C++){let A=h[C];if(e.AieVq(A[t(1474)](":"),0)){if(e.MVGZI(e[t(1752)],e[t(1752)]))return!0;{let I=A[t(1742)](":");l&&(x=I.length),f+=I.length;for(let L=0;L<I[t(1313)];L++)if(I[L].length!==4){let M=p[t(1717)+"g"](0,e[t(1237)](4,I[L][t(1313)])),xe=M.concat(I[L]);o.push(xe)}else o.push(I[L]);l=!1}}else{if(e.zaQVV(4,A[t(1313)])){let I=p[t(1717)+"g"](0,4-A[t(1313)]),L=I.concat(A);o[t(1722)](L)}else o[t(1722)](A);l&&(x+=1),f+=1,l=!1}}let _="";for(let C=0;e[t(1676)](C,e[t(1237)](8,f));C++)_=_[t(288)](p);for(let C=0;C<o[t(1313)];C++)if(e.sjRJD(C,x))if(e[t(574)](e[t(368)],e.OqVFG))n=n[t(288)](_),n=n[t(288)](o[C]);else return this[t(1472)+t(721)+t(419)](_0x4c3ce2),e[t(726)](_0xec9961);else n=n.concat(o[C]);return n}else this[t(1059)]=!1,_0xe400(this[t(1152)+t(1692)+t(946)]),e[t(1005)](_0x3b5483);if(t(1212)===t(426))_0x5d7647(_0x51cd5e,32),_0x414b1f(_0x41428b,e.BUnAP(_0x3265a2,_0x322c1e));else{let h=s[t(1742)](":");for(let _=0;_<h.length;_++)if(e.cJOvl===e[t(1002)]){let C=h[_];if(e[t(1532)](4,h[_][t(1313)])){let A=p[t(1717)+"g"](0,e[t(860)](4,h[_][t(1313)])),I=A[t(288)](C);n=n[t(288)](I)}else n=n[t(288)](C)}else{this._clearPingTimer(),this[t(1390)+"gTimeoutId"]=e.jECzi(_0x19a151,this[t(1158)][t(350)](this),this._options[t(948)+t(229)]);return}return n}}function v(s,t){let n=r,o=s[n(487)];e[n(1443)](void 0,o)&&(e[n(1702)](Y,t,10),e[n(509)](be,t,o));let x=s[n(988)];e[n(967)](void 0,x)&&(e.jECzi(Y,t,18),e[n(764)](be,t,x))}function y(s){let t=r,n={};e:for(;!e.WYKRm(De,s);){let o=e[t(580)](F,s);switch(e[t(1670)](o,3)){case 0:break e;case 1:n[t(487)]=e[t(1705)](ve,s,e.krZPp(F,s));break;case 2:n.value=e[t(509)](ve,s,e.YuIvQ(F,s));break;default:e[t(509)](ie,s,7&o)}}if(e.MdhGy(void 0,n[t(487)]))throw new Error(t(1240)+"required field: key");if(e[t(640)](void 0,n[t(988)]))throw new Error(e[t(1678)]);return n}function E(s){let t=r;if(e[t(1147)](e[t(1684)],e.QsIgM))this[t(209)]&&this._socket[t(344)]({code:_0x313b0b,reason:_0x593761});else{let n=ce();return e[t(1705)](D,s,n),V(n)}}function D(s,t){let n=r,o={pKZih:function(O,q){return O(q)},rwzEF:function(O,q){return O&q},Nkwni:function(O,q){return e.yRkuO(O,q)},HVjDf:function(O,q){return e.MCofa(O,q)},cuaag:function(O,q){return e[N(1673)](O,q)},dnOjT:function(O,q){return e.VmPmd(O,q)},HrPlq:function(O,q){return e[N(1676)](O,q)},RZeMx:function(O,q){return O<q}},x=s[n(1111)];e.YYHJT(void 0,x)&&(e[n(764)](Y,t,8),e.XVrpg(kt,t,x));let f=s[n(915)];f!==void 0&&(e.TvzWc(Y,t,16),kt(t,f));let l=s[n(1394)];if(e[n(458)](void 0,l))if(e[n(305)]===e.faooq)Y(t,24),kt(t,e[n(1631)](te,l));else{let{enableAutoAck:O}=this[n(1668)],q=e[n(743)](_0x440955,_0x39b793[n(1734)][n(907)],e[n(1622)],"1"),Te=e[n(743)](_0x44bb8e,_0x2ac5ae.message[n(907)],e[n(1493)],"1"),Qe=_0x5a65ea.call(this,_0x1ce940);if(O&&q){let{SeqID:vr,LogID:Rt,service:br,LogIDNew:ut,method:Nt}=_0x55ec51.message;this[n(911)]({SeqID:vr,LogID:Rt,LogIDNew:ut,service:br,method:Nt,headers:[{key:e[n(1493)],value:"1"},{key:e.HviUS,value:ut||""},{key:e[n(610)],value:"0"}]})}Te&&!Qe[n(1140)]&&this[n(1472)+n(900)+n(763)](_0x22273f),e[n(1005)](_0x33bec)}let p=s.method;e[n(1147)](void 0,p)&&(e.TvzWc(Y,t,32),e[n(425)](kt,t,e[n(451)](te,p)));let h=s[n(907)];if(h!==void 0)for(let O of h)if(e[n(1130)]!==e.cmDNF){let q=0,Te=0,Qe;do Qe=o[n(974)](_0x25f038,_0x5008a9),q<32&&(Te|=o[n(1187)](127,Qe)<<q),q+=7;while(o.rwzEF(128,Qe));return Te}else{Y(t,42);let q=e[n(346)](ce);e[n(1705)](v,O,q),Y(t,q[n(1396)]),e[n(509)](en,t,q),e.YuIvQ(P,q)}let _=s[n(656)+n(367)];_!==void 0&&(e[n(509)](Y,t,50),be(t,_));let C=s[n(461)+"ype"];C!==void 0&&(Y(t,58),be(t,C));let A=s.payload;e[n(427)](void 0,A)&&(Y(t,66),e[n(584)](Y,t,A.length),e[n(1094)](Zt,t,A));let I=s[n(1585)];e[n(395)](void 0,I)&&(e[n(1702)](Y,t,74),e[n(901)](be,t,I));let L=s[n(1332)+n(1545)];if(L!==void 0)if(e[n(396)]===e[n(396)])e[n(1652)](Y,t,82),be(t,L);else{let O=_0x4457a5.charCodeAt(_0x348338);O>=55296&&O<=56319&&o[n(1607)](o[n(597)](_0x69311,1),_0x2632a6)&&(O=o[n(280)](o[n(1352)](O,10)+_0x24e31c.charCodeAt(++_0x219147),56613888)),_0x395021+=o[n(1429)](O,128)?1:o.Nkwni(O,2048)?2:o[n(1056)](O,65536)?3:4}let M=s[n(474)];e[n(590)](void 0,M)&&(e.JvAMJ(Y,t,90),e[n(1205)](be,t,M));let xe=s[n(541)+"e"];if(xe!==void 0){if(e[n(539)](e[n(244)],e.DCnOK))return new _0x20981d(_0x310666,{code:_0x1bda78,reason:_0x38b68e,wasClean:_0x11bab1,willReconnect:_0x2df7a2});Y(t,96),e[n(1530)](kt,t,e.BUnAP(te,xe))}}function k(s){let t=r;if(e[t(405)](e.xhAQQ,e[t(1709)]))return T(e[t(784)](G,s));this[t(1466)]&&this[t(1466)][t(344)](_0x381f4f,_0x29b6ff)}function T(s){let t=r,n={};e:for(;!De(s);){let o=e.neCsg(F,s);switch(e.itvic(o,3)){case 0:break e;case 1:n[t(1111)]=ke(s,!0);break;case 2:n.LogID=e[t(1205)](ke,s,!0);break;case 3:n[t(1394)]=e[t(1148)](F,s);break;case 4:n.method=e[t(1148)](F,s);break;case 5:{let x=e[t(691)](H,s);(n[t(907)]||(n.headers=[]))[t(1722)](e.CBahM(y,s)),s.limit=x;break}case 6:n["payloadE"+t(367)]=e[t(806)](ve,s,e[t(394)](F,s));break;case 7:n["payloadT"+t(690)]=e[t(509)](ve,s,F(s));break;case 8:n.payload=Dt(s,e[t(1260)](F,s));break;case 9:n.LogIDNew=e[t(806)](ve,s,e[t(580)](F,s));break;case 10:n[t(1332)+t(1545)]=e[t(1652)](ve,s,e[t(1148)](F,s));break;case 11:n[t(474)]=ve(s,e[t(1209)](F,s));break;case 12:n[t(541)+"e"]=F(s);break;default:e.qpeuZ(ie,s,e[t(1079)](7,o))}}if(e[t(411)](void 0,n[t(1111)]))throw new Error(e[t(717)]);if(n[t(915)]===void 0)throw new Error(e[t(375)]);if(e[t(1251)](void 0,n.service))throw new Error(e[t(291)]);if(e.HSRbr(void 0,n.method))throw new Error(e.YQtwn);return n}function H(s){let t=r;if(e[t(788)](e[t(239)],e[t(903)])){let n=e.PiOWe(F,s),o=s.limit;return s[t(1396)]=e[t(682)](s[t(1017)],n),o}else{if(WjNmlH[t(495)](_0x1f5d7b,_0x10a971))return WjNmlH[t(451)](_0x2b4015,_0x1b5689);if(_0x487f9c.has(_0x5efbe7))return _0x56876c.get(_0x134f9b);let n=WjNmlH[t(1329)](_0x231ab5,_0x45f139);return WjNmlH.TcBGs(n,_0x1fef38)&&(_0x57273b[t(1667)](_0x5be7e0,n),_0x2cac4f[t(1667)](n,_0x164acf)),n}}function ie(s,t){let n=r;switch(t){case 0:for(;e[n(1079)](128,oe(s)););break;case 2:ne(s,F(s));break;case 5:e.YQZjv(ne,s,4);break;case 1:e[n(764)](ne,s,8);break;default:throw new Error(e[n(1386)](n(750)+n(484)+n(802),t))}}function te(s){let t=r;return s|=0,{low:s,high:e[t(1078)](s,31),unsigned:e[t(1293)](s,0)}}let ye=[];function ce(){let s=r,t=ye[s(639)]();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function P(s){ye[r(1722)](s)}function G(s){let t=r;if(e.HSRbr(e[t(1470)],t(221)))return{bytes:s,offset:0,limit:s[t(1313)]};if(e.XvhOH(4,_0x269031[t(1313)])){let n=_0x3b0983.substring(0,e[t(1237)](4,_0x45500f[t(1313)])),o=n[t(288)](_0x106627);_0x3742c5[t(1722)](o)}else _0x403845[t(1722)](_0x128e1c);_0x634fc6&&(_0x55eeac+=1),_0x32613d+=1,_0x3de8d0=!1}function V(s){let t=r,n=s[t(987)],o=s[t(1396)];return e.MdhGy(n[t(1313)],o)?n:n[t(1704)](0,o)}function ne(s,t){let n=r;if(e.hDuHA(e.wmOcz(s[n(1017)],t),s[n(1396)]))throw new Error(e[n(1543)]);s[n(1017)]+=t}function De(s){let t=r;return s.offset>=s[t(1396)]}function pe(s,t){let n=r,o=s[n(987)],x=s.offset,f=s.limit,l=e[n(1283)](x,t);if(l>o[n(1313)])if(e[n(224)](e[n(351)],n(1355))){let p=new Uint8Array(2*l);p[n(1667)](o),s[n(987)]=p}else return this[n(1466)]?this[n(1466)].binaryType:this[n(1183)+n(690)];return s.offset=l,e[n(1138)](l,f)&&(s[n(1396)]=l),x}function Xe(s,t){let n=r,o=s[n(1017)];if(e[n(1737)](o+t,s[n(1396)]))throw new Error(e[n(1439)]);return s[n(1017)]+=t,o}function Dt(s,t){let n=r,o=e[n(1169)](Xe,s,t);return s[n(987)].subarray(o,e[n(1275)](o,t))}function Zt(s,t){let n=r,o=e.kzAgY(pe,s,t[n(1313)]);s[n(987)].set(t,o)}function ve(s,t){let n=r,o={vhcxT:function(_,C){return e[N(1148)](_,C)},FuvKd:function(_){return e.WcpJY(_)}},x=e[n(593)](Xe,s,t),f=String[n(686)+n(1382)],l=s[n(987)],p="\uFFFD",h="";for(let _=0;e[n(1306)](_,t);_++){let C=l[e[n(564)](_,x)],A,I,L,M;if(e[n(1342)](e[n(1098)](128,C),0))h+=f(C);else if(e[n(1563)](224,C)===192)if(e.WUaWg(_+1,t))h+=p;else if(A=l[_+x+1],e[n(1423)](e[n(1098)](192,A),128))h+=p;else{if(e[n(1208)](e[n(279)],e[n(279)]))return this._qosDB?.[n(1667)]({message_id:_0x1cd7c9,timestamp:_0x4322eb});M=e[n(959)](e[n(588)](e[n(408)](31,C),6),e.WoOWL(63,A)),e[n(491)](M,128)?h+=p:(h+=e[n(1401)](f,M),_++)}else e[n(1079)](240,C)==224?_+2>=t?h+=p:(A=l[e.grEXC(e[n(1612)](_,x),1)],I=l[_+x+2],e[n(1660)](e[n(1079)](e[n(959)](A,e[n(1249)](I,8)),49344),32896)?h+=p:(M=e[n(1286)](e[n(255)](e[n(1657)](e[n(979)](15,C),12),e[n(1440)](e[n(1098)](63,A),6)),e[n(1446)](63,I)),M<2048||e[n(1293)](M,55296)&&e.vwliH(M,57343)?h+=p:(h+=e[n(1631)](f,M),_+=2))):(248&C)==240?e[n(296)](e[n(359)](_,3),t)?h+=p:(A=l[e[n(1275)](e.AQXMH(_,x),1)],I=l[e[n(951)](e[n(1612)](_,x),2)],L=l[e[n(564)](_+x,3)],e.HdFEu(e.wadEg(e[n(262)](e[n(569)](A,e[n(1440)](I,8)),L<<16),12632256),8421504)?h+=p:e[n(1699)](e[n(423)],e[n(423)])?(M=e.bivtd(e[n(898)](e[n(959)](e[n(1629)](e[n(1098)](7,C),18),(63&A)<<12),e[n(1118)](63&I,6)),e[n(408)](63,L)),e[n(1665)](M,65536)||M>1114111?h+=p:(M-=65536,h+=e[n(1749)](f,e[n(1510)](e[n(695)](M,10),55296),e[n(1603)](e.tXCNV(1023,M),56320)),_+=3)):(DhWczB.vhcxT(_0x16c12d,_0x4ae539[n(765)]),DhWczB[n(964)](_0x2f68c4))):h+=p}return h}function be(s,t){let n=r,o=t[n(1313)],x=0;for(let p=0;e[n(1665)](p,o);p++){let h=t[n(1339)+"At"](p);e[n(531)](h,55296)&&h<=56319&&e[n(1676)](e[n(1242)](p,1),o)&&(h=e[n(1282)](e.VmPmd(h,10),t[n(1339)+"At"](++p))-56613888),x+=h<128?1:e[n(1676)](h,2048)?2:e[n(491)](h,65536)?3:4}e[n(593)](Y,s,x);let f=e[n(1702)](pe,s,x),l=s[n(987)];for(let p=0;p<o;p++){let h=t[n(1339)+"At"](p);e[n(531)](h,55296)&&h<=56319&&e[n(1654)](e.kJDRY(p,1),o)&&(h=e[n(711)](e[n(1343)](h<<10,t.charCodeAt(++p)),56613888)),e[n(1676)](h,128)?l[f++]=h:(e[n(1026)](h,2048)?l[f++]=e[n(979)](e.qoGNy(h,6),31)|192:(e[n(491)](h,65536)?l[f++]=e.EEMoy(e[n(581)](e[n(1664)](h,12),15),224):(l[f++]=e.WbPQH(e[n(1761)](e[n(1078)](h,18),7),240),l[f++]=e[n(1502)](e.qoGNy(h,12)&63,128)),l[f++]=e[n(1761)](e[n(583)](h,6),63)|128),l[f++]=e.EHUSv(e[n(225)](63,h),128))}}function en(s,t){let n=r,o=e.XVrpg(pe,s,t[n(1396)]),x=s[n(987)],f=t.bytes;for(let l=0,p=t[n(1396)];e[n(954)](l,p);l++)x[e[n(554)](l,o)]=f[l]}function oe(s){let t=r;if(e.yvKxW===t(1514))_0x10d21f[t(1392)+t(1625)]="",_0x16d45b[t(850)](_0x54487d);else return s.bytes[e[t(509)](Xe,s,1)]}function tn(s,t){let n=r,o=e[n(1523)](pe,s,1);s.bytes[o]=t}function F(s){let t=r,n=0,o=0,x;do x=e[t(1329)](oe,s),e[t(1599)](n,32)&&(o|=e[t(1118)](127&x,n)),n+=7;while(128&x);return o}function Y(s,t){let n=r;for(t>>>=0;e[n(1214)](t,128);)tn(s,e.piRwp(127&t,128)),t>>>=7;e[n(1523)](tn,s,t)}function ke(s,t){let n=r,o=0,x=0,f=0,l;if(l=e[n(1586)](oe,s),o=e[n(518)](127,l),e[n(1449)](128,l)&&(l=e.CewqP(oe,s),o|=e[n(1747)](e[n(1446)](127,l),7),e[n(937)](128,l)))if(e[n(301)]("sgMUi",n(949)))l=e[n(451)](oe,s),o|=e.NqeGO(e[n(1359)](127,l),14),128&l&&(l=e.WYKRm(oe,s),o|=e[n(1226)](127&l,21),e.iDCCH(128,l)&&(l=e[n(1586)](oe,s),x=e[n(1359)](127,l),128&l&&(l=oe(s),x|=e[n(528)](e[n(1761)](127,l),7),128&l&&(l=e[n(1329)](oe,s),x|=e[n(1241)](e.tgACA(127,l),14),e[n(518)](128,l)&&(l=oe(s),x|=e.lVuJU(127,l)<<21,e.BcpTs(128,l)&&(l=e[n(691)](oe,s),f=e[n(587)](127,l),e[n(937)](128,l)&&(l=e[n(1540)](oe,s),f|=e[n(1287)](e.gArSY(127,l),7))))))));else return WjNmlH[n(495)](_0x41f23f,_0x1dfd3b)&&(WjNmlH[n(1699)](_0x26d0e4,WjNmlH.FJRWG)||WjNmlH.HSRbr(_0x4dd9f1,WjNmlH[n(826)]))?!0:WjNmlH[n(1471)](_0x358c65,_0x308b38);return{low:o|e.OQhSF(x,28),high:e[n(959)](e[n(1379)](x,4),e[n(1287)](f,24)),unsigned:t}}function kt(s,t){let n=r,o=t[n(471)]>>>0,x=e[n(1379)](e[n(1379)](t[n(471)],28)|t[n(878)]<<4,0),f=e[n(678)](t[n(878)],24),l=f===0?e[n(301)](0,x)?e.MPymV(o,16384)?o<128?1:2:e[n(1676)](o,2097152)?3:4:e[n(1641)](x,16384)?e[n(491)](x,128)?5:6:x<2097152?7:8:e[n(1654)](f,128)?9:10,p=e.lcKUH(pe,s,l),h=s.bytes;switch(l){case 10:h[e[n(626)](p,9)]=e.QaJKR(e[n(1379)](f,7),1);case 9:h[e[n(1351)](p,8)]=l!==9?e.MHfzp(128,f):127&f;case 8:h[e[n(836)](p,7)]=e[n(749)](8,l)?e[n(1291)](e[n(1379)](x,21),128):e[n(1135)](e.itvic(x,21),127);case 7:h[e[n(1242)](p,6)]=e[n(1423)](7,l)?e[n(1508)](e[n(648)](x,14),128):x>>>14&127;case 6:h[e.frcjT(p,5)]=l!==6?e[n(422)](e[n(685)](x,7),128):e[n(225)](x>>>7,127);case 5:h[e[n(1510)](p,4)]=l!==5?e.bnCUB(128,x):127&x;case 4:h[e[n(459)](p,3)]=e[n(1423)](4,l)?e[n(262)](o>>>21,128):e.UuOTw(e[n(1407)](o,21),127);case 3:h[e[n(1351)](p,2)]=e[n(1415)](3,l)?e[n(1502)](e[n(264)](o,14),128):e[n(641)](e[n(1379)](o,14),127);case 2:h[e[n(1343)](p,1)]=l!==2?e[n(433)](o,7)|128:e[n(1626)](e[n(1670)](o,7),127);case 1:h[p]=l!==1?e.EGiFg(128,o):e[n(1301)](127,o)}}function ps(s){return e[r(1631)](k,s)}function dr(s){return e[r(745)](E,s)}let ms=65536,Aa=e.aCISo,ot=ms*ms,ws=e[r(1141)](ot,ot),_s=e.EGTaT(ws,2),Fe=String[r(722)+"e"][r(1339)+"At"];class U{constructor(t,n,o){let x=r;this.isLong=!0,this[x(471)]=e[x(507)](0,t),this[x(878)]=e[x(859)](0,n),this[x(926)]=!!o}static[r(278)](t){let n=r;return t&&e[n(457)](!0,t[n(278)])}static[r(1733)](t,n,o){return new U(t,n,o)}static[r(497)+"s"](t,n,o){let x=r;return o?U[x(497)+"sLE"](t,n):U["fromByte"+x(1181)](t,n)}static[r(497)+r(607)](t,n){let o=r;return new U(e[o(507)](e.mmbmd(e.bivtd(t[0],e[o(1287)](t[1],8)),e[o(716)](t[2],16)),t[3]<<24),e[o(741)](e[o(1682)](e.pGCjK(t[4],e[o(1440)](t[5],8)),e[o(1657)](t[6],16)),e[o(549)](t[7],24)),n)}static["fromByte"+r(1181)](t,n){let o=r;return new U(e.djKrJ(e[o(246)](e[o(1682)](e[o(708)](t[4],24),e[o(928)](t[5],16)),e[o(708)](t[6],8)),t[7]),e[o(552)](e[o(716)](t[0],24)|e[o(528)](t[1],16)|e.NqeGO(t[2],8),t[3]),n)}static fromHash(t){let n=r;return e[n(574)](t,Aa)?ys:new U(e[n(655)](e[n(959)](e[n(959)](e[n(1707)](Fe.call(t,0),Fe[n(934)](t,1)<<8),e[n(1657)](Fe[n(934)](t,2),16)),e[n(1211)](Fe[n(934)](t,3),24)),0),e.lyPQZ(e[n(1171)](e.nGdCl(Fe[n(934)](t,4)|e[n(1226)](Fe[n(934)](t,5),8),e.jrKvq(Fe[n(934)](t,6),16)),e.tlKEf(Fe[n(934)](t,7),24)),0),!0)}[r(1455)](){let t=r;return String["fromChar"+t(1382)](e[t(225)](255,this[t(471)]),e[t(1614)](e[t(284)](this[t(471)],8),255),e[t(1407)](this[t(471)],16)&255,e[t(1637)](this.low,24),e.XaGMM(255,this.high),e[t(916)](this[t(878)]>>>8,255),e[t(480)](e.VpATF(this.high,16),255),this.high>>>24)}static[r(259)+"er"](t,n=!0){let o=r;if(e[o(1260)](isNaN,t))return n?Pa:ys;if(n){if(e[o(1293)](t,ws))return ka}else{if(e.fUIbh(t,-_s))return Ta;if(e.Gydfv(e[o(1282)](t,1),_s))return Da}return U.fromBits(e.vtICE(t,ot)|0,e[o(1046)](t,ot)|0,n)}[r(1213)](){let t=r;return this.unsigned?e[t(758)](e.HqpdK(this[t(878)]>>>0,ot),e[t(1581)](this.low,0)):e[t(479)](e[t(340)](this[t(878)],ot),this[t(471)]>>>0)}[r(476)](){let t=r;if(e.zLHVn(t(681),e[t(702)]))return e[t(640)](0,this[t(878)])&&e[t(574)](0,this[t(471)]);this[t(232)](t(1734),_0x5089e3),this[t(1015)+"e"]&&this[t(1015)+"e"](_0x46139e)}[r(342)](t){let n=r;U[n(278)](t)||(t=U[n(259)+"er"](t));let o=e[n(678)](this[n(878)],16),x=e[n(1524)](65535,this.high),f=e[n(1407)](this[n(471)],16),l=e[n(776)](65535,this[n(471)]),p=e[n(447)](t[n(878)],16),h=e.lAXxL(65535,t.high),_=e.Azixg(t[n(471)],16),C=e[n(1301)](65535,t.low),A=0,I=0,L=0,M=0;return M+=e[n(1264)](l,C),L+=e[n(433)](M,16),M&=65535,L+=e[n(1589)](f,_),I+=e[n(284)](L,16),L&=65535,I+=e[n(1021)](x,h),A+=e[n(678)](I,16),I&=65535,A+=e.frcjT(o,p),A&=65535,U[n(1733)](e.NNvwy(L<<16,M),e.FAwhD(A<<16,I),this.unsigned)}equals(t){let n=r;return e[n(458)](e.fKogA,e[n(1580)])?(U[n(278)](t)||(t=U[n(259)+"er"](t)),e[n(448)](this[n(926)],t.unsigned)&&e[n(457)](e.oRvuZ(this[n(878)],31),1)&&e.CcbKP(t[n(878)]>>>31,1)?!1:e[n(1699)](this.high,t.high)&&e[n(586)](this[n(471)],t[n(471)])):n(1551)+"_"+this[n(883)]}[r(1644)](){let t=r;return e[t(544)](-1,this.low)&&e[t(653)](-1,this[t(878)])?U[t(1733)](0,0,this[t(926)]):e[t(846)](-1,this[t(471)])?U.fromBits(0,e[t(1526)](this[t(878)],1),this.unsigned):U.fromBits(e[t(715)](this.low,1),this[t(878)],this[t(926)])}[r(439)](t){let n=r;return t?this[n(1539)+"E"]():this[n(322)+"E"]()}toBytesLE(){let t=r,n=this.high,o=this[t(471)];return[e[t(1563)](255,o),e[t(1135)](e.PLyAN(o,8),255),e[t(406)](o>>>16,255),e[t(1637)](o,24),e.UuOTw(255,n),e[t(776)](n>>>8,255),e[t(979)](e[t(1052)](n,16),255),n>>>24]}[r(322)+"E"](){let t=r;if(e[t(1537)]===e.PZLIc)return this[t(1466)]?this[t(1466)].readyState:this[t(1668)][t(643)+t(446)]?this[t(994)+"NG"]:this[t(909)];{let n=this[t(878)],o=this[t(471)];return[e[t(530)](n,24),e.EhzKW(e[t(433)](n,16),255),e[t(408)](e[t(871)](n,8),255),e[t(1301)](255,n),e[t(309)](o,24),e[t(1301)](e[t(1052)](o,16),255),e.gArSY(e[t(975)](o,8),255),e[t(1045)](255,o)]}}}let ys=new U(0,0,!1),Pa=new U(0,0,!0),Da=U[r(1733)](-1,2147483647,!1),ka=U[r(1733)](-1,-1,!0),Ta=U[r(1733)](0,-2147483648,!1);var Ue=(function(s){let t=r,n=e[t(1089)][t(1742)]("|"),o=0;for(;;){switch(n[o++]){case"0":s[s.CONNECTING_ERROR=5002]=e[t(874)];continue;case"1":s[s[t(1378)+t(485)+"R"]=5003]=e.pwsUg;continue;case"2":return s;case"3":s[s[e[t(1639)]]=5001]=e[t(1639)];continue;case"4":s[s[e[t(467)]]=5005]=e[t(467)];continue;case"5":s[s[e[t(1091)]]=5004]=e.ieRUz;continue}break}})({});class at{constructor(t){let n=r;if(e[n(1423)](e.RIkTB,"EwDGU"))return _0x41a2c9.log(n(1505),_0x4f2abe,_0x9b78b6,_0x369a26),this._qosDB[n(1667)]({cursor_name:_0x142528,cursor:_0x9c34d2,service:_0x2aa212});this[n(1587)]=t,this[n(833)]=null}}class vs extends at{constructor(t,n){let o=r;if(e.VqXYT(o(511),e[o(1430)])){let x=0,f=_0x3e6d4f,l=e.gxvHy(_0x25523a,4);for(;f<l;){let{value:p,offset:h}=e[o(1036)](_0x116205,_0x5b7116,f);f=h,x=e[o(284)](e.vDwNw(x,8),0),x+=p}return{value:x,offset:l}}else super(t),this[o(1734)]=n&&n[o(1734)]||null}}class bs extends at{constructor(t,n){let o=r,x=e[o(768)][o(1742)]("|"),f=0;for(;;){switch(x[f++]){case"0":super(t);continue;case"1":this.colno=n&&n[o(1179)]||0;continue;case"2":this[o(943)]=n&&n[o(943)]||"";continue;case"3":this[o(1751)]=n&&n[o(1751)]||5001;continue;case"4":this[o(765)]=n&&n[o(765)]||null;continue;case"5":this[o(402)]=n&&n[o(402)]||0;continue;case"6":this[o(1734)]=n&&n[o(1734)]||"";continue}break}}}class Ss extends at{constructor(t,n){let o=r,x=e.pRMTZ[o(1742)]("|"),f=0;for(;;){switch(x[f++]){case"0":super(t);continue;case"1":this.wasClean=n&&n.wasClean||!1;continue;case"2":this[o(1751)]=n&&n.code||0;continue;case"3":this.reason=n&&n[o(1109)]||"";continue;case"4":this[o(1039)+o(1129)]=n&&n[o(1039)+o(1129)]||!1;continue}break}}}class Es extends at{constructor(t,n){let o=r;super(t),this.data=n&&n[o(942)]||null}}class Cs extends Es{constructor(t,n){let o=r;super(t),this[o(942)]=n&&n.data||null,this[o(1734)]=n&&n[o(1734)]||null}}class As extends at{constructor(t,n){let o=r;super(t),this[o(942)]=n&&n[o(942)]||null}}function le(s,{message:t,code:n,error:o}){return new bs(s,{message:t,code:n,error:o})}function me(s,{code:t,reason:n,wasClean:o,willReconnect:x}){let f=r;if(e[f(1617)]===f(1245))return new Ss(s,{code:t,reason:n,wasClean:o,willReconnect:x});{let l=_0x5c477a[f(987)],p=_0x4d94a5[f(1396)];return e[f(1076)](l.length,p)?l:l[f(1704)](0,p)}}function Ps(s,{data:t,message:n}){return new Cs(s,{data:t,message:n})}function Ds(s,{data:t}){return new As(s,{data:t})}function lr(s,{message:t}){return new vs(s,{message:t})}class ks{constructor(t,n){let o=r;this[o(1686)+"s"]=t,this[o(1748)+"es"]=n,this[o(1102)+o(1261)]=0,this[o(216)+o(424)+o(673)+"t"]=0}["resetEnd"+r(1353)+r(452)](){let t=r;this["currentI"+t(1261)]=0,this["currentE"+t(424)+t(673)+"t"]=0}[r(645)+"es"](){let t=r;this[t(216)+t(424)+t(673)+"t"]=0}[r(751)+r(1314)+"nt"](){let t=r;return e.lmWgR(e[t(1048)],e[t(1048)])?this[t(1686)+"s"][this["currentI"+t(1261)]]:_0x5234c5?.[t(1399)](n=>n.key===_0x2a8cab)?.[t(988)]}[r(751)+r(1314)+"ntTriesC"+r(944)](){let t=r;if(e[t(543)](e[t(1267)],e[t(1267)]))return this["currentEndpointT"+t(673)+"t"];this._debug(e[t(762)],_0x57510a[t(1734)]),e[t(761)](_0x1561ac)}["checkRea"+r(899)+"es"](){let t=r;return!!(this["currentI"+t(1261)]>=this[t(1686)+"s"][t(1313)]||this[t(1102)+t(1261)]===e[t(805)](this[t(1686)+"s"][t(1313)],1)&&e[t(455)](this[t(216)+"ndpointT"+t(673)+"t"],this[t(1748)+"es"]))}[r(1172)+"rentEndp"+r(1236)+r(1113)+r(1578)](){let t=r;return e[t(1764)](this["currentI"+t(1261)],this[t(1686)+"s"][t(1313)])?!0:e[t(1737)](this[t(216)+t(424)+t(673)+"t"],this.maxRetries)}[r(1756)+r(1234)+"pointAnd"+r(236)+"unt"](){let t=r;return this[t(216)+"ndpointT"+t(673)+"t"]=1,this[t(1102)+t(1261)]++,this[t(1686)+"s"][this["currentI"+t(1261)]]}[r(751)+r(1314)+"ntAndUpd"+r(630)](){let t=r;if(e[t(224)](e[t(277)],e[t(277)])){let n=_0x2c62fe[t(1734)][t(746)];n&&_0x5070ea[t(812)+"rs"](n)}else return this[t(216)+t(424)+t(673)+"t"]++,this[t(751)+t(1314)+"nt"]()}}let ct=(e[r(438)](e[r(241)],typeof globalThis)&&e[r(1010)](r(787),globalThis[r(1503)+r(1088)][r(1296)])||e.aynHj(e.vnNgt,typeof window)&&e[r(1721)](e[r(1074)],window[r(1503)+r(1088)][r(1296)]))&&e[r(699)](e[r(241)],typeof document),$e=e.wbAbj("undefined",typeof globalThis)&&(e[r(1080)]===globalThis[r(1503)+r(1088)].name||e[r(1348)]===globalThis["construc"+r(1088)][r(1296)])&&e[r(1263)](e[r(241)],typeof tt),Tt=(e.qQnTy(e[r(241)],typeof globalThis)&&e[r(1080)]===globalThis.constructor[r(1296)]||e[r(241)]==typeof globalThis||e[r(1395)](e.vnNgt,typeof globalThis)&&!!globalThis[r(1613)+r(546)])&&r(462)+"d"!=typeof wx,It=e[r(940)](e[r(241)],typeof globalThis)&&(e.YTvDR(e[r(1348)],globalThis[r(1503)+r(1088)].name)||e[r(798)]===globalThis["construc"+r(1088)][r(1296)]||r(1461)+r(1177)+r(390)===globalThis[r(1503)+"tor"][r(1296)])&&e[r(241)]!=typeof self,Ia=e[r(1107)](r(462)+"d",typeof globalThis)&&e[r(1080)]===globalThis[r(1503)+r(1088)][r(1296)]&&e[r(241)]!=typeof global&&e[r(1080)]===global[r(1503)+r(1088)][r(1296)]&&e[r(241)]!=typeof process&&!!process[r(556)];class hr{constructor(){let t=r;this[t(771)+"rs"]={}}[r(232)](t,...n){let o=r,x={DEiQG:function(f,l){return f===l},JkUEr:function(f,l){return e[N(1491)](f,l)},eVBEL:function(f,l){return e.WdbLR(f,l)},BkdTZ:function(f,l){return e[N(1027)](f,l)},yXNrt:function(f,l){return e[N(400)](f,l)},bBFbO:function(f,l){return e[N(1445)](f,l)},caCUi:function(f,l){return f<<l}};if(e[o(455)](e[o(1758)],e[o(730)]))return gfYOsn[o(327)](_0x56def6,_0x1e3ad9)?_0x25bdec:new _0x1c3dca(gfYOsn[o(1031)](gfYOsn[o(1289)](gfYOsn[o(1289)](gfYOsn[o(1289)](_0x53dc0a[o(934)](_0x5836e3,0),_0x9887bb.call(_0x14c631,1)<<8),gfYOsn[o(1736)](_0x17069d[o(934)](_0x3de4e7,2),16)),gfYOsn[o(1736)](_0x18efc4[o(934)](_0x460ef8,3),24)),0),gfYOsn.yXNrt(gfYOsn[o(885)](gfYOsn[o(885)](_0x108401[o(934)](_0x5b86e8,4),_0x997e6d[o(934)](_0x35b99c,5)<<8),_0x522924[o(934)](_0x96ff08,6)<<16)|gfYOsn[o(779)](_0x4f969[o(934)](_0x3f60ec,7),24),0),!0);{let f=this[o(771)+"rs"][t];if(f)f.slice()[o(409)](l=>l.fn[o(1083)](l[o(628)],n));else if(e.MdhGy(o(765),t)&&!this[o(1014)])if(e[o(458)](e[o(1689)],o(501))){let l=0,p={};for(let h=0;e[o(491)](h,_0x228896[o(1313)]);h++)p[_0x479d1f[h][o(1403)+"ame"]]=e[o(1081)](_0x50e4c8,_0x37083b[h][o(1403)+o(977)]),l+=14+p[_0x101678[h][o(1403)+o(977)]];return[l,p]}else{let l=n[o(1313)]&&n[0];if(l instanceof Error)throw l;let p=new Error(e[o(554)](e[o(369)],l?e[o(1510)](" (",l[o(1734)])+")":""));throw p[o(1190)]=l,l}return this}}[r(1003)](t,n){let o=r;if(e[o(1076)](void 0,t))this._listeners={};else if(e.HSRbr(void 0,n))this[o(771)+"rs"][t]=null;else{let x=this._listeners[t];if(x)for(let f=0;e[o(1641)](f,x.length);)x[f].fn===n?x.splice(f,1):++f}return this}on(t,n,o){let x=r;return(this._listeners[t]||(this[x(771)+"rs"][t]=[]))[x(1722)]({fn:n,ctx:o||this}),this}}class Ra extends hr{[r(1504)+r(445)+r(861)](t){let n=r;return t[n(415)]||t[n(384)]?(n(848)+" "+(t[n(415)]||"")+n(248)+(t[n(384)]||""))[n(576)]():JSON.stringify(t)}constructor(t,n,o){let x=r;super(),this[x(209)]=null,Tt&&wx[x(313)+x(245)]&&(this[x(209)]=wx["connectS"+x(245)]({url:t,protocols:n,header:o,fail:this[x(1409)+x(1250)+"lHandler"][x(350)](this),success:this[x(1409)+x(714)+x(897)+"ler"][x(350)](this)})),$e&&tt[x(313)+x(245)]&&(this._socket=tt[x(313)+"ocket"]({url:t,protocols:n,header:o,fail:this[x(1409)+x(1250)+x(1092)].bind(this),success:this[x(1409)+x(714)+x(897)+x(845)].bind(this)}))}["_createS"+r(714)+"cessHand"+r(845)](){let t=r,n={tOPcd:function(o,x){return e[N(586)](o,x)},Xrdtd:t(577)};Promise[t(1608)]()[t(1356)](()=>{let o=t;if(n.tOPcd(n[o(329)],o(577)))this[o(665)+o(1476)]();else{let x=this[o(1558)+"tManager"]?.[o(751)+o(1314)+"nt"]();this[o(599)](o(1233)+x+o(1290)),this[o(1049)+o(816)](1001,"timeout,"+o(914)+o(1695)+"g",!0)}})}[r(1409)+r(1250)+r(1092)](t){let n=r,o={tDOsF:e[n(527)],CxoWq:function(x,f,l){return e[n(981)](x,f,l)}};Promise[n(1608)]().then(()=>{let x=n,f=le(x(765),{message:this[x(1504)+x(445)+"age"](t)});this[x(232)](o[x(378)],f);let l=o.CxoWq(me,"close",{reason:this["_formatE"+x(445)+"age"](t)});this[x(232)](x(344),l)})}["_addWsLi"+r(1476)](){let t=r,n={Anvxg:function(o,x,f){return o(x,f)},Qqxrz:e[t(527)]};this._socket[t(669)](o=>{let x=t;this[x(232)](e.bLwjt,Ds(e[x(302)],{...o,data:o[x(415)]||""}))}),this[t(209)].onClose(o=>{let x=t;this[x(232)](e[x(720)],me(x(344),{...o}))}),this[t(209)][t(1593)+"e"](o=>{let x=t;this.emit(x(1734),n[x(377)](Ps,x(1734),{...o}))}),this[t(209)][t(834)](o=>{let x=t;this[x(232)](x(765),n[x(377)](le,n[x(254)],{...o,message:o.errMsg||""}))})}[r(217)](t){let n=r,o={iFvhR:e.kcYTz,XEdOB:function(x,f){return e.BwADJ(x,f)},jMjRb:function(x,f,l,p){return e.BZBua(x,f,l,p)},vpuft:function(x,f){return x+f},Viazd:function(x,f){return e[N(810)](x,f)},UxcVL:function(x,f,l,p){return e.eycWC(x,f,l,p)}};if(e[n(442)](e[n(1013)],e[n(1013)]))if(e[n(1160)](t,Uint8Array)){let x=t[n(1633)][n(1330)](t[n(354)+"et"],e[n(359)](t[n(371)+"th"],t[n(354)+"et"]));this[n(209)]&&this[n(209)][n(217)]({data:x,fail:f=>{let l=n;this[l(232)]("error",e[l(425)](le,e[l(527)],{message:this[l(1504)+l(445)+l(861)](f)}))}})}else this._socket&&this[n(209)][n(217)]({data:t,fail:x=>{let f=n;this[f(232)](e[f(527)],e[f(1169)](le,f(765),{message:this[f(1504)+f(445)+f(861)](x)}))}});else{let x=o[n(1062)][n(1742)]("|"),f=0;for(;;){switch(x[f++]){case"0":return o[n(1133)](o.jMjRb(_0x129dcc,_0x59d62c,_0x3048f3,_0x2b470f),_0x14f06f);case"1":if(_0x511496[n(1e3)])return _0x42406b.write(_0x4e1505,_0x58bf39)+_0xa55365;continue;case"2":if(!_0x2aedac)return _0x245687;continue;case"3":if(_0x33fa81[n(1312)+"e"])return o[n(374)](_0x261a04[n(1312)+"e"](_0x8cc6c4,_0x1682d3),_0x43d962);continue;case"4":if(o[n(306)](_0x46e776[n(1313)],40))return o.vpuft(o[n(809)](_0x5dd4b7,_0x2d6712,_0x230d23,_0x1b7c37),_0x1f7d0c);continue}break}}}[r(344)](t,n){let o=r;this[o(209)]&&this[o(209)].close({code:t,reason:n})}[r(1568)+r(786)](t,n){let o=r,x={qFucA:function(f,l){return e[N(1081)](f,l)}};if(e[o(1448)]!=="KyyUj")this.on(t,n);else return _0x14518e(_0x40115d[o(1083)](ZIsHuU[o(333)](_0x1d6078,this),_0x31b8b4))}[r(1616)+r(1473)+r(547)](t,n){this[r(1003)](t,n)}get[r(1463)+"te"](){return this[r(209)].readyState}get[r(1204)+"pe"](){return this[r(209)].binaryType}set[r(1204)+"pe"](t){}get[r(1723)](){let t=r;return this[t(209)][t(1723)]}get protocol(){return this._socket.protocol}get extensions(){let t=r;return this[t(209)][t(697)+"ns"]}get["buffered"+r(1220)](){return 0}}function Na(s,t){let n=r;if(t)return new t(s[n(1723)],s[n(1398)]);if(e[n(532)](Tt,$e))return new Ra(s.url,s[n(1398)],s[n(907)]);if(e[n(872)](ct,It)&&e[n(1087)](e[n(241)],typeof WebSocket)&&WebSocket)return new WebSocket(s[n(1723)],s.protocols)}function La(s){let t=r,n=(t(780)+"4")[t(1742)]("|"),o=0;for(;;){switch(n[o++]){case"0":if($e&&tt[t(313)+t(245)])return!0;continue;case"1":if(Tt&&wx["connectS"+t(245)])return!0;continue;case"2":if(e[t(532)](ct,It)&&e[t(490)](e.vnNgt,typeof WebSocket)&&WebSocket)return!0;continue;case"3":if(s)return!0;continue;case"4":return!1}break}}function Ts(s,t,n){let o=r,x={UpsMG:o(1635)+"alled mu"+o(379)+"imes in "+o(589),uKBoF:function(p,h){return e[o(457)](p,h)},vKVZp:function(p,h){return p+h}},f=-1;async function l(p){let h=o;return p<=f?Promise.reject(new Error(x[h(855)])):(f=p,x.uKBoF(p,n[h(1313)])?Promise.resolve():n[p].bind(s)(t,l[h(350)](null,x[h(1718)](p,1))))}l(0)}function Is(s){let t=r,n=0,o=0;for(let x=0;e[t(754)](x,s.length);++x)if(o=s[t(1339)+"At"](x),e[t(1043)](o,128))n+=1;else if(o<2048)n+=2;else if(e[t(408)](64512,o)===55296&&e[t(1030)](e.oNSSN(64512,s.charCodeAt(e[t(1283)](x,1))),56320)){if(e[t(653)](e[t(625)],"SCBmx"))return new _0x4a8c9d(_0x28c82c,{message:_0x2ca165});++x,n+=4}else n+=3;return n}function Rs(s,t,n){let o=r;if(e.yTvGC(n-t,1))return"";let x="";for(let f=t;e[o(611)](f,n);){let l=s[f++];if(l<=127)x+=String["fromChar"+o(1382)](l);else if(e.WUaWg(l,192)&&e[o(1417)](l,224))x+=String[o(686)+o(1382)](e.FXyUh(e[o(1760)](31,l)<<6,e.htapc(63,s[f++])));else if(e[o(1293)](l,224)&&l<240)x+=String[o(686)+"Code"](e[o(514)](e[o(441)](e[o(877)](15&l,12),e[o(937)](63,s[f++])<<6),e[o(1584)](63,s[f++])));else if(e[o(1214)](l,240)){let p=e[o(1164)](e.WLgry(e.gPjiM(e.NZFvP(7&l,18),e[o(609)](e[o(516)](63,s[f++]),12)),e[o(1124)](e.itGBx(63,s[f++]),6)),63&s[f++])-65536;x+=String[o(686)+o(1382)](55296+e[o(583)](p,10)),x+=String[o(686)+o(1382)](e[o(1307)](56320,1023&p))}}return x}function gr(s,t,n){let o=r,x=n,f,l;for(let p=0;p<s[o(1313)];++p)f=s[o(1339)+"At"](p),e[o(663)](f,128)?t[n++]=f:e.XKkmr(f,2048)?(t[n++]=e[o(741)](e.qoGNy(f,6),192),t[n++]=e[o(1682)](e.iyWFN(63,f),128)):e[o(1265)](64512&f,55296)&&e[o(317)](e[o(1598)](64512,l=s.charCodeAt(e[o(700)](p,1))),56320)?(f=e.McIdd(e[o(1569)](65536,e[o(257)](e[o(1112)](1023,f),10)),1023&l),++p,t[n++]=e.elVaZ(f,18)|240,t[n++]=e.zaoLN(e[o(335)](e[o(583)](f,12),63),128),t[n++]=e.KAJMI(e[o(1375)](f,6)&63,128),t[n++]=e[o(1604)](63,f)|128):(t[n++]=e[o(514)](e[o(1664)](f,12),224),t[n++]=e[o(1384)](e[o(1729)](e[o(1574)](f,6),63),128),t[n++]=e.bfMFJ(63,f)|128);return e[o(860)](n,x)}async function Ns(s){let t=r;if(e.MCQXw(e.FcKII,typeof s))if(e[t(1142)](e[t(349)],"RkGwu")){let n=new Uint8Array(e[t(1221)](Is,s));return gr(s,n,0),n}else _0x51e286(t(1144)),this[t(1003)](e[t(292)],_0x6547a5),this[t(1003)]("ping_once_timeout",_0x56ccec);return e[t(495)](s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s[t(371)+"th"])}function Ma(s){let t=r;try{return t(595)!=typeof s&&(e[t(1469)](s,ArrayBuffer)||s.buffer&&e[t(495)](s.buffer,ArrayBuffer))||e[t(1087)](e[t(631)],typeof s)?"":(JSON[t(466)](s),e[t(213)])}catch{return e[t(854)](t(595),typeof s)?t(1070)+t(1101)+"et=utf-8":""}}let Oa=(s,t)=>{let n=r;switch(s){case e[n(947)]:case e.aueYL:return{[n(1159)+s]:1,"x-tt-env":t};default:return{}}};class Ba{constructor(t){let n=r,o={AyAln:function(x,f,l){return e[N(1169)](x,f,l)},WuiHk:function(x,f,l){return e[N(465)](x,f,l)}};e[n(1032)]("ojgis","ojgis")?(bgpFnf.AyAln(_0x5a3848,_0x63724b,8),bgpFnf[n(1278)](_0x2ad545,_0x4e688f,_0x4d41c5)):(this[n(1207)+n(944)]=t,this[n(921)]=0)}addCount(){this.count++}["checkRea"+r(889)+"nt"](){return e[r(1214)](this.count,this.maxLossCount)}[r(793)+r(1645)](t=0){let n=r;this[n(1207)+n(944)]=t,this[n(921)]=0}}async function za(s){let t=r,n={EvETE:function(o,x){return o(x)},MdvrU:e[t(1191)],NQina:function(o,x){return o(x)},XBxFa:function(o,x){return o===x},CfNuM:e[t(982)],NLYAH:e[t(1165)],bMWLS:t(228)+t(311),dzIcq:function(o,x){return o+x},BOPcD:e.gTefg,WeiRy:function(o,x){return e[t(1123)](o,x)}};return new Promise(o=>{let x=t;if(!ct)return n[x(995)](o,n[x(970)]);try{if(n[x(1075)](n[x(578)],n[x(578)])){let f=document[x(1741)+x(789)](n[x(864)]);window[x(1551)+x(1327)]=l=>{let p=x;document[p(736)][p(1114)+p(1720)](f),window[p(1551)+p(1327)]=void 0,n.EvETE(o,l&&l.msg||n[p(970)])},f[x(1587)]=n.bMWLS,f[x(1012)]=n[x(1028)](s.replace(/^ws/,x(1254)),n.BOPcD);try{if(n[x(1507)](x(1610),x(1610))){let l=this[x(781)][x(1364)+x(536)](this[x(1090)]),p=_0x50aeb1[x(466)](l||"{}");return p[_0x28b73a]=void 0,this[x(781)][x(606)+x(536)](this[x(1090)],_0x9c9928[x(622)+"y"](p))}else document[x(736)][x(803)+x(1720)](f)}catch{document[x(736)]["removeCh"+x(1720)](f)}}else _0x4dadd6[x(850)](_0x5dafe5)}catch{window[x(1551)+"JSONP"]=void 0,o(n.MdvrU)}})}function He(s,t,n){let o=r;return!!s?.[o(1399)](x=>x[o(487)]===t&&x.value===n)}function xt(s,t){return s?.[r(1399)](o=>o.key===t)?.value}let pr=null;async function qa(){let s=r;return pr||(pr=Promise[s(1608)]()[s(1356)](Ce[s(350)](Ce,e[s(1419)]))),pr}class Fa extends hr{constructor(t,n){let o=r;super(),this._dbName=t,this._keyPath=n,this[o(781)]=void 0,this[o(1411)+o(1658)]=null}async[r(1310)](){await this._init()}async _init(){let t=r,n={HvSeD:e[t(1347)],nQyad:function(o,x,f){return e[t(1518)](o,x,f)},wztMy:function(o,x){return e[t(1032)](o,x)},EZQys:e.VYklx,yXVux:function(o){return e[t(492)](o)},UjWGD:function(o,x,f,l){return o(x,f,l)},qwNYI:function(o,x){return o===x},ylvwl:function(o,x){return e.AyhXQ(o,x)},bolPE:e.cLpCe,RoDRH:e.mMJvA,IGJdf:function(o,x,f){return e[t(496)](o,x,f)},RnXXM:function(o,x){return e[t(1368)](o,x)},Tddqf:function(o,x,f,l){return e[t(743)](o,x,f,l)},laIAF:t(765)};if(e[t(624)]===t(1175)){if(this._qosDB)return;if(this[t(1411)+t(1658)])return this[t(1411)+t(1658)];try{let o=this[t(1533)],x=this[t(1743)];this[t(1411)+t(1658)]=(async()=>{let f=t,l={mRgyX:function(p,h,_){return n[N(769)](p,h,_)},Dttyw:f(765),zWLGq:function(p,h){return p===h},QMMmh:function(p,h,_){return n.nQyad(p,h,_)}};if(n[f(1490)](n[f(1115)],n[f(1115)]))this[f(1207)+"ount"]=_0x4eb356,this[f(921)]=0;else{let{openDB:p}=await n[f(800)](qa);this[f(781)]=await n.UjWGD(p,f(1551)+"_"+o,1,{upgrade(h){let _=f;if(n[_(891)]===n[_(891)])h[_(996)+_(1416)+"e"](o,{keyPath:x});else{let C=this[_(1558)+_(557)]?.[_(1225)+_(899)+"es"](),A=this[_(1558)+_(557)]?.[_(751)+"ntEndpoint"]();if(C&&!_0x10af0d[_(1734)]){let I=_(1233)+A+(_(1197)+_(1040)+_(632)+"ed");this[_(1472)+_(1527)+"ent"](l[_(1619)](_0xd5fb4f,l.Dttyw,{message:I,code:_0x41035d[_(1378)+_(485)+"R"],error:_0x4c61c6}));return}this[_(1466)]&&l[_(1567)](this._ws[_(1463)+"te"],this.OPEN)&&this[_(1049)+_(816)](),this[_(1472)+_(1527)+_(1151)](l[_(1451)](_0x3ef0ea,l[_(571)],{message:_0x45685a.message,code:_0x231e95[_(477)+"RROR"],error:_0x11c581}))}}})}})(),await this[t(1411)+"mise"]}catch(o){if(e[t(876)](e[t(1288)],e[t(647)]))return this[t(1466)]?this[t(1466)][t(697)+"ns"]:"";console[t(850)](o)}finally{this[t(1411)+t(1658)]=null}}else{let{pingInterval:o,pingFrequency:x}=this[t(1668)];if((n.qwNYI("hi",_0x335153[t(942)])&&n.ylvwl(t(1434),x)||t(272)===x)&&(this[t(1085)+t(1647)](),this[t(232)](n[t(283)],n[t(1317)]),this[t(1390)+t(613)+"Id"]=n[t(777)](_0x242b27,this._ping.bind(this),o)),n[t(1750)]("hi",_0xda5b79[t(942)]))return;try{n[t(651)](_0x2aa3f3,this,_0x8d5fe,[_0x284577,_0x3699fe,_0x4a78ea,_0x5c9096,_0x570a60,_0x1dbd83])}catch(f){let l=n[t(777)](_0x29601a,n[t(1066)],{message:f.message,code:_0x52d7a5["MESSAGE_"+t(273)],error:f});this[t(1472)+t(1527)+"ent"](l)}}}async[r(1477)](t){let n=r,o={zzGeO:function(x,f){return e.VYHgc(x,f)},Gjnzm:function(x,f){return x-f},MUjCC:function(x,f){return e[N(1552)](x,f)}};try{if(e[n(980)]==="WaFOv"){let{initReconnectInterval:x,maxReconnectInterval:f,reconnectIntervalGrowFactor:l}=this[n(1668)],p=o.zzGeO(x,_0x9b35bc.pow(l,o.Gjnzm(_0x446de7,1)));return o[n(1426)](p,f)?f:p}else return await this[n(978)](),this._qosDB?.[n(1477)](this[n(1533)],t)}catch(x){e[n(489)](e[n(1328)],e[n(1680)])?console[n(850)](x):(this[n(399)+n(1519)+"line"]=_0x2ca63c,_0x3562d4?this[n(998)+n(553)]():this[n(998)+n(679)]())}}async[r(1667)](t,n){let o=r;return await this[o(978)](),this[o(781)]?.put(this[o(1533)],t)}async[r(1615)](t){let n=r;try{return await this[n(978)](),this[n(781)]?.[n(1579)](this._dbName,t)}catch(o){console[n(850)](o)}}async[r(1627)](){let t=r,n={aFRBx:e[t(292)],pgVLX:t(1082)+t(856)+"t"};if(e[t(1255)](e[t(1047)],e[t(1404)])){let o={ymQTY:function(x,f){return x(f)},FQaRA:n[t(791)],eUNkY:t(1436)};return new _0x4405c9((x,f)=>{let l=t;this[l(1085)+l(1647)](),this[l(1390)+"gTimeoutId"]=_0x284150(this[l(1158)][l(350)](this),this._options[l(948)+l(229)]);let p=()=>{let _=l;o[_(896)](x,_(1144)),this[_(1003)](_(1082)+_(851)+"s",p),this[_(1003)](o.FQaRA,h)},h=()=>{let _=l;o.ymQTY(f,o[_(1746)]),this[_(1003)](_(1082)+_(851)+"s",p),this[_(1003)](o[_(992)],h)};this.on(n.aFRBx,p),this.on(n[l(791)],h),this[l(1158)]()})}else try{return await this[t(978)](),this._qosDB?.[t(1627)](this[t(1533)])}catch(o){console[t(850)](o)}}async keys(){let t=r;return await this[t(978)](),this[t(781)]?.[t(1765)+"ys"](this[t(1533)])}async getAll(){let t=r,n={OiPES:function(o,x){return o<=x},vFbyi:t(1635)+t(339)+"ltiple t"+t(266)+t(589),agiYk:function(o,x){return e[t(411)](o,x)},oiTOP:function(o,x){return o+x}};return e[t(1142)](e[t(1489)],e[t(1489)])?(await this._init(),this[t(781)]?.getAll(this[t(1533)])):qpoKgt[t(1166)](_0xb35d2a,_0x2ee10a)?_0x35ecf2[t(719)](new _0x5a1400(qpoKgt[t(320)])):(_0x426a7f=_0x5efcd3,qpoKgt[t(1400)](_0x27340e,_0xa47b1a.length)?_0x3da8bf[t(1608)]():_0x3203ff[_0x4e4de3][t(350)](_0x2e3694)(_0x358090,_0x36d111[t(350)](null,qpoKgt.oiTOP(_0x3494ec,1))))}async[r(1555)](){let t=r,n={xSldk:e[t(387)]};if(e[t(924)](t(935),e.YqsvB)){let o=n.xSldk[t(1742)]("|"),x=0;for(;;){switch(o[x++]){case"0":this[t(1672)+"osed"]=!1;continue;case"1":this._isInit=!0;continue;case"2":this["_endpoin"+t(557)]?.["resetEnd"+t(1353)+"fig"]();continue;case"3":this["_pingLos"+t(932)]?.[t(793)+t(1645)]();continue;case"4":this[t(1152)]();continue}break}}else try{this[t(781)]?.[t(344)](),this[t(781)]=void 0}catch(o){e[t(1443)](e.cuLdR,e[t(1008)])?(e[t(1277)](_0x3bc65,_0x5b4c83,82),e[t(1205)](_0x5ca52b,_0x132d8c,_0x351125)):console[t(850)](o)}}get[r(318)](){let t=r,n={usDyZ:function(o,x){return e.AGxCm(o,x)},jJdQW:function(o,x){return o|x},tMlCM:function(o,x){return e[N(299)](o,x)},aVYyx:function(o,x){return e[N(1384)](o,x)},muubw:function(o,x){return e[N(252)](o,x)},PRGyJ:function(o,x){return e[N(1626)](o,x)},jtPmt:function(o,x){return e.XSIkz(o,x)},HEVfd:function(o,x){return e[N(519)](o,x)},aGYft:function(o,x){return e[N(1033)](o,x)}};try{if(t(842)===e[t(636)]){let o=NeJHBG[t(1685)](NeJHBG[t(654)](NeJHBG.tMlCM(NeJHBG[t(773)](NeJHBG[t(807)](7,_0x4cc765)<<18,NeJHBG.PRGyJ(63,_0x17d882[_0xebb41f++])<<12),NeJHBG[t(1383)](NeJHBG[t(341)](63,_0x5ad3f6[_0x24bb5b++]),6)),NeJHBG[t(341)](63,_0x116db0[_0x28124d++])),65536);_0x29a60a+=_0x416397[t(686)+t(1382)](NeJHBG.HEVfd(55296,NeJHBG[t(1380)](o,10))),_0x47865b+=_0x13ed43[t(686)+t(1382)](NeJHBG[t(392)](56320,NeJHBG[t(341)](1023,o)))}else return!!this._qosDB}catch(o){return console.log(o),!1}}}class Ua{constructor(t,n){let o=r;this[o(883)]=t,this._pathKey=n,this[o(781)]=localStorage}async[r(1310)](){}get[r(1090)](){let t=r;return t(1551)+"_"+this[t(883)]}async get(t){let n=r,o=this[n(781)][n(1421)](this[n(1090)]);return JSON[n(466)](e.nbadD(o,"{}"))[t]}async set(t,n){let o=r,x=this[o(781)][o(1421)](this[o(1090)]),f=JSON[o(466)](e[o(872)](x,"{}"));return f[n||t[this[o(572)]]]=t,this[o(781)][o(566)](this[o(1090)],JSON.stringify(f)),n||t[this[o(572)]]}async[r(1615)](t){let n=r,o={bcbBh:function(x,f,l){return x(f,l)},oahjl:function(x,f){return e[N(360)](x,f)},znpTu:function(x,f){return e[N(481)](x,f)}};if(e[n(411)](e.tfNRZ,e[n(1170)])){let x=this[n(781)].getItem(this[n(1090)]),f=JSON.parse(e[n(532)](x,"{}"));return f[t]=void 0,this[n(781)][n(566)](this[n(1090)],JSON[n(622)+"y"](f))}else nFxGKs[n(694)](_0x49fab2,_0x434197,nFxGKs[n(567)](nFxGKs.znpTu(127,_0xf15e62),128)),_0x2f73b9>>>=7}async[r(1627)](){let t=r;return this[t(781)][t(1627)]()}async keys(){let t=r,n=this[t(781)][t(1421)](this[t(1090)]),o=JSON.parse(n||"{}");return Object[t(1011)](o)}async[r(1703)](){let t=r,n=this[t(781)][t(1421)](this[t(1090)]),o=JSON[t(466)](e[t(532)](n,"{}"));return Object[t(1280)](o)}[r(1555)](){return Promise[r(1608)]()}get[r(318)](){return!!this[r(781)]}}class Ha{constructor(t,n){let o=r;if(e[o(1051)]!=="qPNid"){let x=this[o(878)],f=this[o(471)];return[e[o(1584)](255,f),e.Maijd(e.WVCeb(f,8),255),e[o(881)](f>>>16,255),e.VCKQL(f,24),e[o(831)](255,x),e[o(1266)](x>>>8,255),e[o(1128)](e[o(1637)](x,16),255),x>>>24]}else this[o(883)]=t,this[o(572)]=n,this[o(781)]=$e?tt:Tt?wx:null}async[r(1310)](){}get _prefix(){let t=r;return t(1551)+"_"+this[t(883)]}async get(t){let n=r,o=this[n(781)][n(1364)+n(536)](this[n(1090)]);return JSON[n(466)](e[n(1198)](o,"{}"))[t]}async set(t,n){let o=r,x=this[o(781)][o(1364)+o(536)](this[o(1090)]),f=JSON[o(466)](e.KZbap(x,"{}"));return f[n||t[this._pathKey]]=t,this[o(781)].setStorageSync(this[o(1090)],JSON[o(622)+"y"](f)),n||t[this[o(572)]]}async[r(1615)](t){let n=r;if(e[n(405)](e.hYoao,e[n(1732)]))this.on(_0x1b7d00,_0x3f0d7a);else{let o=this[n(781)][n(1364)+"geSync"](this._prefix),x=JSON.parse(e[n(353)](o,"{}"));return x[t]=void 0,this[n(781)][n(606)+"geSync"](this[n(1090)],JSON[n(622)+"y"](x))}}async[r(1627)](){let t=r;return this[t(781)][t(1437)+"rageSync"]()}async[r(1011)](){let t=r,n=this._qosDB[t(1364)+t(1210)+"nc"](this[t(1090)]),o=JSON[t(466)](e[t(532)](n,"{}"));return Object[t(1011)](o)}async[r(1703)](){let t=r,n=this[t(781)][t(1364)+t(1210)+"nc"](this._prefix),o=JSON[t(466)](e[t(872)](n,"{}"));return Object.values(o)}[r(1555)](){return Promise[r(1608)]()}get[r(318)](){return!!this[r(781)]}}function Ls(s,t){let n=r;if(e[n(629)]($e,$e))return new Ha(s,t);if(e.hMtQq(ct,It)&&e[n(241)]!=typeof indexedDB)return new Fa(s,t);if(e.HBfuq(ct,It)&&e[n(438)](n(462)+"d",typeof localStorage))return new Ua(s,t);throw new Error(e[n(1273)])}class Ga{constructor(){let t=r,n={HvGfd:e[t(1218)]};if(e[t(984)](e.zJQGi,e.rKAGP))this["_interva"+t(1294)+"Id"]=null,this[t(890)+"l"]=36e5,this[t(781)]=e[t(460)](Ls,e[t(748)],e[t(1438)]);else if(!this[t(1152)+"Lock"]){let o=n[t(1592)][t(1742)]("|"),x=0;for(;;){switch(o[x++]){case"0":this[t(555)+t(932)]?.resetCounter();continue;case"1":this._isInit=!0;continue;case"2":this._connect();continue;case"3":this["_endpoin"+t(557)]?.[t(642)+t(1353)+t(452)]();continue;case"4":this[t(1672)+t(1663)]=!1;continue}break}}}async[r(890)+"lFlush"](){let t=r;e[t(1564)](clearInterval,this["_interva"+t(1294)+"Id"]),this[t(890)+t(1294)+"Id"]=e[t(593)](setInterval,()=>{let n=t;this[n(469)+n(1360)]()},this._interval)}async openDB(){let t=r;await this[t(781)][t(1310)]()[t(1356)](()=>{let n=t;this[n(890)+n(1259)]()})}async[r(469)+"ired"](){let t=r;(await this._qosDB?.getAll()||[])[t(1055)](({timestamp:x})=>x<Date[t(925)]()).forEach(x=>{let f=t;this[f(781)]?.[f(1615)](x[f(234)+"id"])})}async[r(1615)](t){return this._qosDB?.del(t)}async[r(1667)](t,n){let o=r;return this[o(781)]?.[o(1667)]({message_id:t,timestamp:n})}async get(t){let n=r;if(e[n(544)]("UaOZy",e[n(1095)]))!_0x163901[n(689)+"d"]&&(this[n(828)+"er"]&&_0x22b730["removeEv"+n(1473)+"ner"](e[n(822)],this[n(1069)+n(1624)]),this[n(828)+"er"]&&_0x59de3d[n(1616)+n(1473)+n(547)](e[n(1496)],this[n(1069)+"ageShow"]),this[n(344)]()),this._isBrowser&&_0x2e295e[n(1616)+n(1473)+n(547)](n(258),this[n(998)+n(553)]),this[n(828)+"er"]&&_0x2c13ea["removeEv"+n(1473)+n(547)](e[n(1492)],this[n(998)+n(679)]);else return this[n(781)]?.[n(1477)](t)}async closeDB(){let t=r;e[t(1119)](clearInterval,this[t(890)+"lTimeoutId"]),await this[t(781)]?.closeDB()}get[r(318)](){let t=r;return this[t(781)]?.[t(318)]}}function mr(s){let t=r,n=!!this._options[t(929)+"S"];if(!n)return{enabled:n,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=He(s[t(1734)][t(907)],e.gWHZy,"2"),x=o&&e.djldw(He,s[t(1734)][t(907)],t(1554)+t(820)+"ck","1"),f=o&&e[t(1659)](He,s[t(1734)][t(907)],e[t(1444)],"1"),l=f?e[t(513)](xt,s[t(1734)][t(907)],e[t(1239)])?.split(",").filter(Boolean)||[]:[];return{enabled:n,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:f,ackMsgIds:l}}async function Ms(){let s=r;return this[s(235)+s(1560)]||(this[s(235)+"ger"]=new Ga),this[s(235)+"ger"][s(318)]||await this._QoSManager[s(1310)](),this[s(235)+s(1560)]}async function Ka(s,t){let n=r,o={WvbCk:function(x,f,l){return e[N(1652)](x,f,l)},uYLtX:n(344),sutNJ:e[n(1006)]};if(e[n(395)](e[n(1326)],e.rHZJG)){let{enableAutoAck:x}=this[n(1668)],f=He(s[n(1734)].headers,"need_ack","1"),l=e[n(818)](He,s.message.headers,e[n(1493)],"1"),p=mr[n(934)](this,s);if(e[n(398)](x,f)){let{SeqID:h,LogID:_,service:C,LogIDNew:A,method:I}=s[n(1734)];this[n(911)]({SeqID:h,LogID:_,LogIDNew:A,service:C,method:I,headers:[{key:e[n(1493)],value:"1"},{key:e.HviUS,value:e[n(1198)](A,"")},{key:e[n(610)],value:"0"}]})}l&&!p[n(1140)]&&this["_dispatc"+n(900)+n(763)](s),e[n(601)](t)}else{this[n(1472)+n(1479)+"ent"](o[n(1512)](_0x2fff74,o[n(672)],{code:1e3,reason:o[n(483)]})),this._endpointManager?.[n(642)+n(1353)+n(452)](),this["_pingLos"+n(932)]?.[n(793)+n(1645)]();return}}async function ja(s,t){let n=r;this[n(599)](e.MmtOc,s[n(1734)]),t()}async function Wa(s,t){let n=r,o=e.hxXKS(ps,await e[n(1298)](Ns,s[n(942)]));try{if(e.afsnT(n(817),e[n(1541)]))if(o[n(746)]instanceof Uint8Array){let x=e[n(724)](this[n(1668)][n(656)+n(367)],Object)?{force:!!this[n(1668)][n(656)+n(367)][n(1058)],encoding:this[n(1668)][n(656)+n(367)].encoding?this[n(1668)]["payloadE"+n(367)][n(906)][n(1573)](/\s/g,"")[n(1009)+n(825)]():""}:{force:!1,encoding:this[n(1668)][n(656)+n(367)]?this[n(1668)][n(656)+n(367)][n(1573)](/\s/g,"")[n(1009)+n(825)]():""},f=o[n(656)+n(367)]?o[n(656)+"ncoding"].replace(/\s/g,"")[n(1009)+n(825)]():"",l=e.yeiot(this[n(1668)][n(461)+n(690)],Object)?{force:!!this._options[n(461)+n(690)][n(1058)],type:this[n(1668)][n(461)+n(690)][n(1587)]?this[n(1668)][n(461)+n(690)][n(1587)][n(1573)](/\s/g,"")[n(1009)+n(825)]():""}:{force:!1,type:this._options["payloadT"+n(690)]?this._options[n(461)+n(690)][n(1573)](/\s/g,"")[n(1009)+"ase"]():""},p=o["payloadT"+n(690)]?o[n(461)+n(690)][n(1573)](/\s/g,"")[n(1009)+n(825)]():"",h=l[n(1058)]?l[n(1587)]:p||l[n(1587)],_=x[n(1058)]?x[n(906)]:f||x[n(906)],C=[e[n(421)],e[n(213)],e.QqSmM,e[n(631)]],A=[e.ONnvz,e.kPLtd];this[n(1668)][n(1582)+n(738)+n(1557)+"ad"]&&C.includes(h)&&(!_||A[n(1104)](_))?o["textPayl"+n(1625)]=Rs(o.payload,0,o[n(746)][n(371)+"th"]):o[n(1392)+n(1625)]=""}else o[n(1392)+n(1625)]="";else{let x={jsIMK:function(l,p){return e[n(1631)](l,p)},fPaZR:n(440)+n(1109)},f=_0xc2abe2[n(1741)+n(789)](e[n(1165)]);_0xe6ef9b[n(1551)+n(1327)]=l=>{let p=n;_0x49be72.body[p(1114)+p(1720)](f),_0xfdabb5[p(1551)+"JSONP"]=void 0,x[p(687)](_0x3c53e7,l&&l[p(1459)]||x[p(334)])},f[n(1587)]=e.FZkhR,f.src=_0x274a50[n(1573)](/^ws/,e[n(1038)])+(n(585)+"ack=frontierJSONP");try{_0x5ce6e4.body.appendChild(f)}catch{_0x145f62[n(736)][n(1114)+n(1720)](f)}}}catch(x){o[n(1392)+n(1625)]="",console[n(850)](x)}s[n(1734)]=o,t()}function Ja(s,t,n){let o=r;if(e[o(218)](e[o(742)],e[o(742)]))return this[o(209)].binaryType;{let x=e[o(1154)](n,8192),f=x>>>1,l=null,p=x;return function(h){let _=o;if(e[_(1189)](h,1)||e[_(1453)](h,f))return e[_(1401)](s,h);if(e[_(1542)](p+h,x)){if(e[_(1601)](e.yfZAG,e[_(1238)]))return null;l=e[_(1631)](s,x),p=0}let C=t[_(934)](l,p,p+=h);return e[_(1675)](7,p)&&(p=e[_(517)](7,p)+1),C}}}let Va=4294967295;function Ya(s,t,n){let o=r;return e[o(285)](RangeError,e[o(479)](e[o(1268)](o(1035)+"t of ran"+o(1521)+s,e[o(637)])+(t||1)+e.dWPhA,n))}function Xa(s,t,n){let o=r;if(e[o(1138)](n,Va))throw new Error(e[o(1397)]);let x=3;for(;e[o(1293)](x,0);){let f=e[o(1112)](255,n);e[o(818)](_r,f,s,e.kJDRY(t,x)),n>>>=8,x--}return e[o(1486)](t,4)}function $a(s,t){let n=r,o=0,x=t,f=e[n(459)](t,4);for(;e[n(226)](x,f);){let{value:l,offset:p}=e[n(1269)](wr,s,x);x=p,o=e[n(1581)](e[n(542)](o,8),0),o+=l}return{value:o,offset:f}}function Qa(s,t,n){let o=r;return s?e[o(1634)](s[o(1313)],40)?e[o(459)](gr(s,t,n),n):t.utf8Write?e[o(287)](t[o(1312)+"e"](s,n),n):t[o(1e3)]?e[o(1603)](t[o(1e3)](s,n),n):e[o(1264)](e[o(1745)](gr,s,t,n),n):n}function Za(s,t){let n=r,o=new U(e[n(473)](e[n(859)](e[n(1594)](e[n(877)](s[e.yMTBF(t,4)],24),e.ixPzr(s[t+5],16)),e.URByT(s[e.WROJO(t,6)],8)),s[e[n(1354)](t,7)]),e.PnNzo(e[n(1060)](e[n(1707)](e[n(1072)](s[e[n(1510)](t,0)],24),e[n(1724)](s[e[n(1024)](t,1)],16)),e.NEbkH(s[e[n(841)](t,2)],8)),s[e[n(1345)](t,3)]),!0);return t+=8,{value:o,offset:t+8}}function e0(s,t,n){let o=r,x=s.low,f=s[o(878)];return t[n]=e[o(1116)](f,24),t[e.iMToE(n,1)]=e[o(685)](f,16)&255,t[e.TdolA(n,2)]=e[o(1753)](e[o(655)](f,8),255),t[e[o(836)](n,3)]=e[o(263)](255,f),t[e[o(1510)](n,4)]=e[o(337)](x,24),t[e[o(853)](n,5)]=e.WPwfC(e[o(362)](x,16),255),t[n+6]=e[o(847)](x,8)&255,t[e[o(836)](n,7)]=e[o(558)](255,x),n+=8,n}function wr(s,t){let n=r;return s[n(989)+"8"]?{value:s[n(989)+"8"](t),offset:t+1}:{value:e[n(1135)](255,s[t]),offset:e.NUItZ(t,1)}}function _r(s,t,n){let o=r;return t[o(220)+"t8"]?t[o(220)+"t8"](s,n):t[n]=e[o(796)](255,s),e[o(1153)](n,1)}let t0=function(s){return new Uint8Array(s)},n0=e[r(592)](e[r(241)],typeof Buffer)?Buffer[r(664)+r(231)]:Ja(t0,Uint8Array.prototype.subarray),r0=16,yr=32;function s0(s){let t=r;if(e[t(1456)]===e[t(315)]){let n={kbtAp:function(o,x){return o(x)}};return function(o,...x){let f=t,l=_0x3d9f89[f(934)](n[f(913)](_0x4e66b2,this),o,...x);return _0x37cbbb[f(1667)](l,o[f(596)]?o[f(596)]():[o]),_0x4713d8(l)}}else{let n=0,o={};for(let x=0;e[t(663)](x,s[t(1313)]);x++)if(t(905)===e[t(1106)]){let f=e[t(1728)](_0x38f8e3);return e.XVrpg(_0x108d86,_0x18cd3e,f),e[t(1540)](_0x48ef8d,f)}else o[s[x][t(1403)+t(977)]]=e[t(963)](Is,s[x][t(1403)+"ame"]),n+=14+o[s[x][t(1403)+t(977)]];return[n,o]}}function Os(s,t,n){let o=r,[x,f]=e[o(784)](s0,s),l=e.rwklB(n0,x),p=0;return s[o(409)](h=>{let _=o,C=(_(219)+_(494)+"|1|6|5").split("|"),A=0;for(;;){switch(C[A++]){case"0":p=e.MwWMe(Xa,l,p,h[_(1394)]||0);continue;case"1":console[_(850)](_(1296),p);continue;case"2":console[_(850)](e.DiStp,p);continue;case"3":p=_r(0,l,p);continue;case"4":console[_(850)](e[_(1337)],p);continue;case"5":console[_(850)](e[_(1064)],p);continue;case"6":p=e0(U.fromNumber(h[_(1042)]||t),l,p);continue;case"7":p=Qa(h[_(1403)+_(977)],l,p);continue;case"8":console[_(850)](e.QPwtJ,h,h[_(1394)]);continue;case"9":p=e[_(983)](_r,f[h["cursor_n"+_(977)]],l,p);continue;case"10":console[_(850)](_(1394),p);continue}break}}),{frameType:yr,headers:[{key:e.kfkSS,value:n}],payload:l}}function i0(s){let t=r,n=0,o=[];for(;n<s[t(371)+"th"];){let{offset:x}=e.KmKVf(wr,s,n);n=x;let f={cursor_name:"",cursor:0,service:0},{value:l,offset:p}=$a(s,n);f[t(1394)]=l,n=p;let{value:h,offset:_}=wr(s,n);n=_,f[t(1403)+t(977)]=e[t(1405)](Rs,s,n,e[t(1122)](n,h)),n+=h;let{value:C,offset:A}=e.GyfrG(Za,s,n);f[t(1042)]=C[t(1213)](),n=A,o.push(f)}return o}function o0(){let s=r;return{frameType:yr,headers:[{key:e[s(478)],value:s(824)+s(1336)}],payload:void 0}}class a0{constructor(t,n,o){let x=r;this["_cursorN"+x(718)]=t,this[x(1648)+x(515)]=n,this["_message"+x(823)]=o,this[x(781)]=e[x(1454)](Ls,this[x(799)+"ameSpace"],e[x(1001)])}async[r(1310)](){let t=r;await this[t(781)][t(1310)]()}async[r(210)+"rs"](){let t=r;if(!this[t(781)][t(318)])return;let n=this[t(676)+t(823)],o=await this[t(781)].getAll();switch(console[t(850)](e[t(634)],o),n){case e[t(1099)]:return o&&o[t(1313)]?e[t(818)](Os,o,0,this[t(1648)+"ileName"]):void 0;case e[t(1762)]:return;case e[t(965)]:return o&&o.length?Os(o,0,this[t(1648)+"ileName"]):e[t(1728)](o0)}}async[r(1667)](t,n,o){let x=r;if(e.tWrHA(x(343),e.Cdnce))return console.log(e.ahmES,t,n,o),this[x(781)][x(1667)]({cursor_name:t,cursor:n,service:o});{_0x5e2f17(_0x8e345b,42);let f=e.iVctw(_0x2d8770);e[x(1713)](_0x3c8a09,_0x387817,f),e[x(496)](_0x57e91c,_0x54d122,f[x(1396)]),_0x27811c(_0x8b6dcf,f),_0x31cfe2(f)}}async[r(812)+"rs"](t){let n=r,o={gSqTH:function(x,f){return x(f)},wgpEM:function(x,f,l){return e[N(1705)](x,f,l)}};if(e[n(1497)](e[n(604)],e[n(324)]))lODqfy[n(222)](_0x1c2df2,this["_interva"+n(1294)+"Id"]),this["_interva"+n(1294)+"Id"]=lODqfy[n(1346)](_0x1dbbcb,()=>{let x=n;this[x(469)+x(1360)]()},this[n(890)+"l"]);else{let x=e[n(580)](i0,t);for(let f of x){if(e[n(811)]==="nzdrE")return new _0x59bcc7(_0x2ef000,_0x555b8b,_0x3bd818);console[n(850)](e[n(1321)],x),await this[n(781)][n(1667)](f)}}}async[r(1477)](t){let n=r;return(await this[n(781)].get(t))?.[n(1042)]}async[r(1555)](){let t=r;await this._qosDB[t(1555)]()}[r(893)+r(535)+r(500)](t){let n=r;if(e[n(1546)](n(616),e.SMJjN))this[n(1648)+"ileName"]=t;else return this[n(781)]?.[n(1615)](_0x2c1284)}get[r(318)](){return this._qosDB.isReady}}let c0=e[r(993)];async function Bs(s){let t=r;if(!this[t(1668)][t(929)+"S"])return null;let{aID:n,fpID:o,messageStrategy:x}=this._options,f=s||c0;try{return this["_cursorM"+t(677)]?s&&this[t(1755)+t(677)]["updateCu"+t(535)+t(500)](s):this[t(1755)+t(677)]=new a0(o+"_"+n+"_"+f,f,x),this["_cursorM"+t(677)][t(318)]||await this[t(1755)+t(677)][t(1310)](),this[t(1755)+t(677)]}catch{return null}}async function x0(s,t){let n=r,o={zTMxg:e.xneVG,IwtXp:e.gGngJ,NimDr:n(1378)+n(485)+"R",NjjQM:e[n(1091)]},x=e[n(698)](He,s.message.headers,e[n(1231)],"-1"),f=e[n(922)](He,s.message[n(907)],e[n(1493)],"1"),l=e[n(465)](xt,s.message[n(907)],e[n(1700)]),p=e[n(1586)](Number,e.YQZjv(xt,s[n(1734)][n(907)],e[n(1517)]))||0,h=mr[n(934)](this,s),_=e[n(432)](He,s[n(1734)].headers,e[n(561)],"2"),C=e.GyfrG(xt,s[n(1734)][n(907)],e[n(1457)]),A=e[n(1081)](Number,e[n(725)](xt,s.message[n(907)],e[n(668)]));if(h[n(1140)])return e.kYJSB(t);let I=h[n(297)+n(692)]?await Ms[n(934)](this):null;if(e.umrsI(s[n(1734)][n(1394)],0)&&f&&!x||s[n(1734)][n(1394)]>0){if(l&&h.isQoSMessage&&I)return!!!await I[n(1477)](l)&&(this[n(1472)+"hMessage"+n(419)](s),await I[n(1667)](l,e.OhifC(Date.now(),p))),t();if(_){let L=await Bs.call(this);if(!L)return this[n(1472)+n(721)+n(419)](s),e[n(756)](t);let M=await L[n(1477)](C)??-1;if(e[n(727)](M,A))if(e.fubPv(e[n(618)],e[n(618)])){let xe=o[n(923)][n(1742)]("|"),O=0;for(;;){switch(xe[O++]){case"0":_0x5832fd[_0x5c7f0b[n(477)+"RROR"]=5001]=AfMxSR[n(938)];continue;case"1":_0x22b572[_0x36b10c["CONNECTI"+n(256)]=5002]="CONNECTI"+n(256);continue;case"2":return _0x4b8bb8;case"3":_0x44244d[_0x261c02[n(1412)+"OR"]=5005]=n(1412)+"OR";continue;case"4":_0x47980f[_0x1c89fa[AfMxSR[n(658)]]=5003]="MAX_RETRIES_ERROR";continue;case"5":_0x594af7[_0xb7833d[AfMxSR[n(740)]]=5004]=AfMxSR[n(740)];continue}break}}else this[n(1472)+n(721)+"Event"](s),L.set(C,A,s.message[n(1394)]);else throw new Error(n(361)+" message cursor "+A+(n(381)+n(737)+n(372)+"r ")+M);return t()}return this["_dispatchMessage"+n(419)](s),t()}}async function u0(s,t){let n=r,o=mr[n(934)](this,s);if(!o[n(297)+"sage"])return e[n(1228)](t);let x=await Ms[n(934)](this);if(o[n(365)+n(436)+n(861)]&&o[n(345)+"s"][n(1313)])for(let f of o[n(345)+"s"])await x[n(1615)](f);e[n(1525)](t)}async function f0(s,t){let n=r,o=e[n(539)](s[n(1734)][n(541)+"e"],r0),x=s[n(1734)][n(541)+"e"]===yr;if(e[n(1372)](!o,!x))return e[n(238)](t);let f=e[n(894)](xt,s[n(1734)][n(907)],e[n(478)]);if(!f)return e[n(1005)](t);let l=await Bs[n(934)](this,f);if(!l)return t();if(o){let p=await l[n(210)+"rs"](),h={frameType:p?.["frameType"],SeqID:U[n(259)+"er"](this[n(1651)]++),LogID:U[n(259)+"er"](this[n(1668)][n(930)+n(1428)]()),service:9e3,method:5,headers:p?.[n(907)],payload:p?.[n(746)]},_=e[n(691)](E,h);this[n(1466)]&&this[n(1466)][n(1463)+"te"]&&this._ws[n(217)](_)}if(x){let p=s[n(1734)].payload;p&&l.setCursors(p)}}let d0=async function(s,t){let n=r;if(e[n(1744)](e.KebvD,e.KebvD))this._isInit=!1,e[n(1061)](clearTimeout,this[n(1152)+n(1692)+n(946)]),e.RwOtv(t);else{let o=_0x50833d[n(934)](WjNmlH.yhXII(_0x24537b,this),_0x1e9091,..._0x43997a);return _0x2edc12[n(1667)](o,_0x142619[n(596)]?_0x109ed5[n(596)]():[_0x39014f]),WjNmlH[n(1061)](_0x7f514,o)}},l0=async function(s,t){let n=r;if(e[n(1687)](n(1143),"npKvJ")){if(!this._ws)return;this["_destroy"+n(612)+"t"](_0x57a2ec,_0x1547c7,_0x36aaea)}else{if(!this[n(1466)]||this[n(1466)][n(1463)+"te"]!==this.OPEN)return e[n(844)](t);let{pingInterval:o}=this[n(1668)];this[n(1558)+n(557)]?.["resetEndpointCon"+n(452)]();for(let f=0;e[n(1605)](f,this[n(676)+"Queue"][n(1313)]);f++){let l=this["_message"+n(468)][f];if(e[n(1292)](this._ws[n(1463)+"te"],this[n(1174)])&&e[n(1331)](null,l))this[n(1466)]&&this._ws[n(217)](l),this["_message"+n(468)][f]=null;else break}this["_message"+n(468)]=this[n(676)+n(468)][n(1055)](f=>!!f),this[n(1390)+n(613)+"Id"]=setTimeout(()=>this[n(1158)](),o),this["_dispatc"+n(1481)+"nt"](s),this[n(828)+"er"]&&this[n(1466)]&&(this[n(1466)][n(1204)+"pe"]=this[n(1183)+n(690)]);let x=this[n(1558)+n(557)]?.[n(751)+"ntEndpoint"]();this._debug(n(1178)+x+n(1120)),e.mxcZr(t)}},h0=async function(s,t){let n=r,o=this[n(1558)+"tManager"]?.["getCurre"+n(1314)+"nt"]();this[n(599)](n(1178)+o),t()};class g0 extends hr{constructor(t){let n=r,o={pfvPG:function(x,f,l){return e[N(513)](x,f,l)},GGlFg:e[n(527)],UhfKk:e[n(1108)],YHfNO:e.mgBbc,UGnMx:function(x,f,l,p){return e[n(432)](x,f,l,p)},CoYmO:n(886)+n(1296),iLXpd:function(x,f,l,p){return e[n(1609)](x,f,l,p)},MOZpA:e[n(212)],htjYh:function(x,f,l,p){return e[n(432)](x,f,l,p)},qQrlY:n(952),aYfOi:function(x,f,l,p){return e[n(698)](x,f,l,p)},JIeRi:e[n(498)],HwvKf:function(x,f,l,p){return e[n(1405)](x,f,l,p)},xWbbD:e[n(720)],Psxwb:function(x,f){return e[n(521)](x,f)},UkxYT:e[n(1006)],LHDWg:function(x,f){return e.plcGV(x,f)},tZuoF:function(x,f,l){return e[n(1094)](x,f,l)},vUFrl:function(x,f,l){return x(f,l)},DdFhH:function(x,f){return e[n(1262)](x,f)},NupoE:function(x,f){return e[n(854)](x,f)},xWRUz:function(x,f){return e[n(249)](x,f)},DbMxW:e.RrSwA};if(e[n(1265)](n(852),e.PbkoN)){super(),this["_miniNav"+n(1519)+n(472)]=!0,this[n(828)+"er"]=ct,this._isNode=Ia,this._isMiniTT=$e,this._isMiniWX=Tt,this[n(1162)+"r"]=It,this[n(676)+n(468)]=[],this["_endpoin"+n(557)]=null,this[n(1672)+n(1663)]=!1,this[n(1183)+n(690)]=e.EpgDQ,this[n(1152)+n(1325)]=!1,this[n(1152)+n(1692)+n(946)]=null,this[n(545)+n(418)+n(1671)]=null,this["_pingPon"+n(613)+"Id"]=null,this._seqId=0,this._isInit=!1,this[n(753)]="",this[n(235)+n(1560)]=null,this[n(1755)+"anager"]=null,this._pingLossCounter=null,this[n(326)+"ls"]="pbbp2",this[n(909)]=3,this[n(994)+"NG"]=0,this[n(1174)]=1,this.CLOSING=2,this._onOpen=p=>{let h=n;try{Ts(this,p,[d0,l0,h0])}catch(_){let C=o[h(723)](le,o[h(260)],{message:_.message,code:Ue.OPEN_ERROR,error:_});this["_dispatchErrorEv"+h(1151)](C)}},this[n(1257)+"ge"]=async p=>{let h=n,_={fsZIX:function(I,L){return e[N(325)](I,L)},qumBJ:function(I){return e.iVctw(I)}},{pingInterval:C,pingFrequency:A}=this._options;if((e.FnqzX("hi",p[h(942)])&&e[h(1699)](e[h(407)],A)||e[h(544)](e[h(966)],A))&&(e.aYgzM(e[h(328)],h(1425))?(_0x2fabba(DNqVbi[h(999)](_0x111b99,_0x58842d[h(274)])),DNqVbi[h(1193)](_0x44d1dd)):(this[h(1085)+h(1647)](),this.emit(e[h(292)],h(1144)),this[h(1390)+"gTimeoutId"]=e[h(725)](setTimeout,this._ping.bind(this),C))),!e[h(640)]("hi",p[h(942)]))try{e.vhnzE(Ts,this,p,[Wa,Ka,u0,f0,x0,ja])}catch(I){if(e.GBNNh(h(1691),e[h(250)])){let L=e[h(1465)](le,e.MwplB,{message:I[h(1734)],code:Ue[h(1681)+h(273)],error:I});this[h(1472)+h(1527)+h(1151)](L)}else{let L=o.UhfKk[h(1742)]("|"),M=0;for(;;){switch(L[M++]){case"0":_0x21ffde.log(WzFPWC[h(1125)],_0x48b7e4);continue;case"1":_0x49610c=WzFPWC[h(1485)](_0x38716f,_0x4e96c6[h(1403)+h(977)],_0x2d4c9b,_0x5ecf08);continue;case"2":_0x52ed2b[h(850)](WzFPWC.CoYmO,_0x182409);continue;case"3":_0x2dd689.log(h(1730)+h(295),_0x188cf0,_0x4b40db.service);continue;case"4":_0x52be45=WzFPWC[h(1270)](_0x4c69f1,_0xc16b1b,_0x26d029,_0xc0daba[h(1394)]||0);continue;case"5":_0x45b6da[h(850)](WzFPWC[h(1376)],_0x26b67a);continue;case"6":_0x1ceb71=WzFPWC.htjYh(_0x28eb5d,0,_0x2a3333,_0x5ed383);continue;case"7":_0x2bffa4.log(WzFPWC.qQrlY,_0x4e2ab9);continue;case"8":_0x16bb7b=WzFPWC[h(971)](_0x1a7845,_0x5548bd.fromNumber(_0x146c52[h(1042)]||_0x3157fb),_0x19705f,_0xd2a3da);continue;case"9":_0x412f53[h(850)](WzFPWC.JIeRi,_0x4acbc2);continue;case"10":_0x36a747=WzFPWC[h(1366)](_0xf6083e,_0x50cb28[_0x51e5aa[h(1403)+h(977)]],_0x1c180d,_0x4fea20);continue}break}}}},this[n(600)]=p=>{let h=n,_=this[h(1558)+h(557)]?.[h(1225)+h(899)+"es"](),C=this[h(1558)+h(557)]?.["getCurre"+h(1314)+"nt"]();if(_&&!p[h(1734)]){let A=h(1233)+C+(h(1197)+h(1040)+h(632)+"ed");this["_dispatchErrorEv"+h(1151)](le(h(765),{message:A,code:Ue[h(1378)+"IES_ERROR"],error:p}));return}this[h(1466)]&&e[h(1340)](this[h(1466)][h(1463)+"te"],this[h(1174)])&&this[h(1049)+h(816)](),this["_dispatc"+h(1527)+h(1151)](e[h(1475)](le,e.MwplB,{message:p.message,code:Ue[h(477)+h(1683)],error:p}))},this[n(1688)]=async p=>{let h=n;this[h(1388)+h(1677)](),this._clearPingTimer(),this[h(1324)+h(667)+"rs"](),this._ws=null,this[h(1152)+"Lock"]=!1;let _=this[h(1558)+"tManager"]?.[h(1225)+"chMaxTries"]();if(!_&&this[h(348)+"orOnline"]()&&!this[h(1672)+h(1663)]){let C=this[h(1558)+h(557)]?.["getCurre"+h(1314)+"nt"](),A=this[h(1668)][h(1362)+h(1295)+h(1433)](p.code,p.reason);this[h(1472)+h(1479)+h(1151)](me(o[h(1223)],{code:1006,reason:p[h(1109)]||h(253)+h(1562)+h(1590)+h(608)+h(1402)+"ame: "+C,willReconnect:A})),A&&this[h(1152)]();return}if(o.Psxwb(1e3,p[h(1751)])&&this["_readyCl"+h(1663)]){this["_dispatchCloseEv"+h(1151)](me(o[h(1223)],{code:1e3,reason:o[h(731)]})),this._endpointManager?.[h(642)+h(1353)+h(452)](),this[h(555)+"sCounter"]?.[h(793)+h(1645)]();return}if(p[h(1751)]!==1e3&&_){let C=this[h(1558)+h(557)]?.[h(751)+h(1314)+"nt"](),A=p[h(1109)];A||(A=await o.LHDWg(za,this[h(753)])),A=h(253)+h(1562)+h(973)+A+", hostname: "+C+(h(620)+h(1110)+h(1173)),this[h(1472)+h(1479)+h(1151)](o[h(1300)](me,o[h(1223)],{code:p[h(1751)],reason:A}));let I=h(1233)+C+(h(1197)+"ax retri"+h(632)+"ed");this["_dispatchErrorEv"+h(1151)](o[h(863)](le,h(765),{message:I,code:Ue["MAX_RETR"+h(485)+"R"]})),this["_endpoin"+h(557)]?.[h(642)+h(1353)+"fig"](),this[h(555)+h(932)]?.resetCounter();return}if(o[h(1305)](1e3,p[h(1751)])&&!p[h(1109)]){let C=this[h(1558)+h(557)]?.[h(751)+h(1314)+"nt"]();this[h(1472)+h(1479)+"ent"](me(o[h(1223)],{code:p[h(1751)],reason:"connecti"+h(1562)+h(1590)+h(608)+h(1402)+"ame: "+C})),this[h(1558)+h(557)]?.["resetEnd"+h(1353)+h(452)](),this[h(555)+h(932)]?.[h(793)+"nter"]();return}this._dispatchCloseEvent(p),this[h(1558)+h(557)]?.["resetEnd"+h(1353)+h(452)](),this[h(555)+h(932)]?.[h(793)+h(1645)]()},this.onclose=null,this[n(1014)]=null,this[n(1015)+"e"]=null,this[n(1662)]=null,this[n(251)+n(298)]=null,this[n(1219)+n(488)]=null,this[n(1192)+n(1516)+n(1334)+"ct"]=null,this[n(998)+"nLine"]=this[n(998)+"nLine"][n(350)](this),this["_handleO"+n(679)]=this["_handleO"+n(679)][n(350)](this),this[n(1069)+n(1624)]=this[n(1069)+n(1624)].bind(this),this[n(1069)+n(1535)]=this[n(1069)+n(1535)][n(350)](this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.lBiEo(1,0),service:0,logIDGenerator:c,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[n(966)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[n(965)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:f}=t,l=Array.isArray(x)?x:e[n(1764)](e.FcKII,typeof x)?[x]:[];if(!l||e.sKawS(0,l[n(1313)]))throw new Error(e.UDMGo);if(!e[n(502)](La,f))throw new Error(e[n(683)]);Object[n(976)](this._options,t),this[n(1558)+n(557)]=new ks(l,this[n(1668)][n(1748)+"es"]),this[n(555)+n(932)]=new Ba(this._options[n(1549)+n(388)]),this._options[n(643)+n(446)]&&(this[n(1059)]=!0,this[n(1152)]()),this[n(1668)][n(265)+n(434)+n(573)]&&(this._isMiniTT||this[n(1447)+"X"]?this[n(1544)+n(657)+n(701)]():this[n(828)+"er"]&&this[n(1235)+n(1358)+n(786)]())}else{let{url:x}=o[n(1195)](_0x26509e,{}),f=_0x4f7005[n(276)](x)?x:o[n(1478)](n(595),typeof x)?[x]:[];_0x55679a&&_0x51992b[n(976)](this[n(1668)],_0x2b055d),f&&f[n(1313)]?this[n(1558)+n(557)]=new _0x2d7b74(f,this[n(1668)][n(1748)+"es"]):this[n(1558)+n(557)]?.[n(642)+"pointConfig"](),this[n(555)+n(932)]?.[n(793)+n(1645)](this[n(1668)][n(1549)+n(388)]),this["_readyCl"+n(1663)]=!1,this[n(1466)]&&o.xWRUz(this[n(1466)].readyState,this.CLOSED)?this[n(1049)+n(816)](1e3,o[n(1365)],!0):(this[n(1059)]=!0,this[n(1152)]())}}[r(998)+r(553)](){let t=r;if(e[t(892)]!==e.TqLws){if(this._options[t(450)+"utoRecon"+t(1698)]||this[t(1672)+t(1663)])return;this[t(783)+t(298)]()}else{if(e[t(631)]==typeof _0x11f997){let n=new _0x9b605e(e[t(504)](_0x274c4b,_0x155b76));return e[t(732)](_0x3fa026,_0x2445c1,n,0),n}return e[t(661)](_0x7bcfbc,_0x2c22fc)?new _0x246e4b(_0x1e1c92):new _0x43ca67(_0x5391bc[t(1633)],_0x498dd0[t(354)+"et"],_0x4c2555[t(371)+"th"])}}[r(998)+"ffLine"](){let t=r;this["_destroy"+t(612)+"t"]();let n=e[t(1247)](lr,e[t(1498)],{message:e[t(830)]});this[t(1192)+t(1516)+t(1334)+"ct"]&&this["onStopIm"+t(1516)+"yReconnect"](n)}[r(1235)+r(1358)+r(786)](){let t=r;this._isBrowser&&window[t(1568)+t(786)](t(258),this[t(998)+t(553)]),this._isBrowser&&window["addEvent"+t(786)](e[t(1492)],this[t(998)+t(679)]),this[t(828)+"er"]&&window[t(1568)+t(786)](e[t(822)],this["_handleP"+t(1624)]),this._isBrowser&&window[t(1568)+t(786)](t(759),this._handlePageShow)}[r(548)+r(1358)+r(786)](){let t=r;if(e[t(286)]!=="rBram")return _0x4a5d28[t(1083)](WjNmlH[t(1540)](_0x30daa,this),_0x384436),WjNmlH[t(735)](_0x1b2282,_0x44e027[t(1477)](this));this[t(828)+"er"]&&window[t(1616)+t(1473)+t(547)](e[t(282)],this[t(998)+t(553)]),this[t(828)+"er"]&&window[t(1616)+"entListe"+t(547)](e[t(1492)],this["_handleO"+t(679)]),this._isBrowser&&window[t(1616)+"entListener"](e[t(822)],this["_handleP"+t(1624)]),this[t(828)+"er"]&&window[t(1616)+"entListe"+t(547)](e[t(1496)],this["_handleP"+t(1535)])}[r(1069)+r(1624)](t){let n=r,o={stFjf:function(x,f,l){return x(f,l)}};if(e.AyhXQ(e[n(1157)],n(870)))return new _0x5b3d7e(x=>{let f=n;o[f(958)](_0x1d97dc,x,this["_getInte"+f(1232)+"e"](_0x8847f))});!t.persisted&&(this[n(828)+"er"]&&window[n(1616)+n(1473)+n(547)](e.uhPJV,this._handlePageHide),this[n(828)+"er"]&&window[n(1616)+n(1473)+n(547)](e[n(1496)],this[n(1069)+n(1535)]),this[n(344)]()),this._isBrowser&&window[n(1616)+n(1473)+"ner"](e[n(282)],this[n(998)+"nLine"]),this[n(828)+"er"]&&window[n(1616)+n(1473)+"ner"](n(770),this[n(998)+n(679)])}[r(1069)+"ageShow"](t){let n=r,o={IeMbI:function(x,f,l){return e.uuBtG(x,f,l)}};if(t[n(689)+"d"]){if(e[n(1010)](e[n(449)],e.dPFzm))return _0x17bcd5[n(987)][nwtpur.IeMbI(_0x4bd22d,_0x3aae59,1)];this[n(348)+n(1467)]()&&(!this[n(1466)]||this[n(1466)].readyState!==this[n(1174)]||this._ws[n(1463)+"te"]!==this[n(994)+"NG"])&&this["_handleO"+n(553)](),this[n(828)+"er"]&&window["addEvent"+n(786)]("online",this[n(998)+n(553)]),this[n(828)+"er"]&&window[n(1568)+n(786)](e[n(1492)],this[n(998)+n(679)])}}async _generateUrl(t){let n=r,{fpID:o,deviceID:x,bddID:f,ttwID:l,accessKey:p,aID:h,customParams:_={},enableAutoAck:C,enableQoS:A,QoSLevel:I,env:L}=this._options,M,xe,O;this[n(828)+"er"]||this[n(1447)+"X"]||this[n(968)+"T"]?(M=location&&e.RbSrY(e[n(801)],location[n(1398)])?e[n(1004)]:e.zzydu,xe=t[n(1573)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),O=/^wss(.*:\/\/)/[n(1185)](t)?t:""+M+xe):(M=e[n(1004)],xe=t[n(1573)](/(^http)((?:[s]*:\/\/))/,""),O=/(^ws)((?:[s]*:\/\/))/.test(xe)?xe:""+M+xe);let q=f?e[n(230)]:l?e[n(538)]:e.vktVb,Te=f||l||x;if(e.UHAvP(!Te,!q))throw new Error(e[n(529)]);let Qe=e[n(520)]==typeof _?await e[n(1653)](_):_,vr=L?e.JvAMJ(Oa,L[n(1146)],L.xTTEnv):{},Rt=Object[n(976)]({device_platform:e.RwDxk,version_code:e.DyCMf,access_key:p,fpid:o,aid:h,[q]:Te,xsack:C?1:0,xaack:C?1:0,xsqos:A?1:0,qos_level:A?I:void 0,qos_sdk_version:2,...vr},Qe),br=Object[n(1011)](Rt)[n(493)]((ut,Nt)=>Rt[Nt]!==void 0?""+ut+(ut?"&":"?")+Nt+"="+Rt[Nt]:ut,"");return O+n(410)+br}async _connect(){let t=r;if(!(this[t(1152)+t(1325)]||this["_readyCl"+t(1663)])){this[t(1152)+t(1325)]=!0;try{let n=this[t(1558)+"tManager"]?.[t(1172)+t(887)+t(1236)+t(1113)+"tries"](),{timeoutInterval:o}=this[t(1668)];if(n){let f=this[t(1558)+"tManager"]?.[t(751)+"ntEndpoint"](),l=this[t(1558)+"tManager"]?.[t(1756)+"ackupEndpointAndUpdateCo"+t(1536)](),p=this[t(1558)+t(557)]?.[t(751)+"ntEndpoi"+t(1696)+t(944)]();if(l){let h="connect "+f+(t(1290)+t(620)+t(1110)+"ached, w"+t(1246)+t(1515)+t(972))+l+(t(1018)+"y"),_=e.KbLaY(le,e[t(527)],{message:h,code:Ue[t(1378)+t(485)+"R"]});this[t(599)](h),this[t(1472)+t(1527)+t(1151)](_),this[t(753)]=await this[t(644)+"eUrl"](l),this[t(599)]("connect "+l+" "+p+t(1180)),this[t(1324)+t(667)+"rs"]()}else{let h=t(1233)+f+(t(1290)+t(620)+"tries re"+t(1173));this[t(599)](h),this[t(1472)+t(1527)+t(1151)](e[t(1277)](le,t(765),{message:h,code:Ue[t(1378)+t(485)+"R"]}));return}}else if(e[t(1561)](e.rUkSz,e[t(1499)])){let f=this[t(1558)+t(557)]?.[t(751)+t(1314)+t(1661)+t(630)](),l=this[t(1558)+t(557)]?.["getCurre"+t(1314)+t(1696)+t(944)]();this._url=await this[t(644)+t(1136)](f||""),this[t(599)](t(1233)+f+" "+l+t(1180)),this[t(1324)+"sListeners"]()}else{let f=this[t(1558)+t(557)]?.["getCurre"+t(1314)+"nt"]();this._debug(t(1178)+f),e.xYOvu(_0x175897)}if(this[t(1059)])this[t(1059)]=!1;else{let f=e[t(1530)](lr,"reconnect",{message:e[t(880)]});this[t(251)+t(298)]&&this.onStartReconnect(f)}let x=this["_endpoin"+t(557)]?.[t(751)+t(1314)+t(1696)+t(944)]()||0;e.bjXJS(x,1)&&await this[t(1303)](e.BzYFb(x,1)),this[t(599)]("connecti"+t(819)+this[t(753)]+(t(615)+t(969))+this._protocols),this._ws=e[t(884)](Na,{url:this[t(753)],protocols:[this[t(326)+"ls"]],headers:this._options[t(705)+t(1333)+"s"][t(1007)+"tpHeader"]},this[t(1668)].ws),(this[t(828)+"er"]||this[t(1162)+"r"])&&this[t(1466)]&&(this[t(1466)].binaryType=this["_binaryT"+t(690)]),this._addWsListeners(),this[t(1152)+t(1692)+t(946)]=e.utsgk(setTimeout,this._onTimeout[t(350)](this),o)}catch(n){throw this[t(1152)+t(1325)]=!1,n}}}[r(1388)+r(1677)](){let t=r;clearTimeout(this[t(1152)+t(1692)+t(946)]),this["_connect"+t(1692)+t(946)]=null}[r(1085)+"ngTimer"](){let t=r;e[t(502)](clearTimeout,this[t(1390)+"gTimeoutId"]),e[t(504)](clearTimeout,this["_reconnectTimeou"+t(1671)]),this[t(1390)+"gTimeoutId"]=null,this[t(545)+t(418)+t(1671)]=null}_debug(...t){let n=r,o={ATcyQ:function(x,f,l){return x(f,l)},aBVAu:n(1362)+"t",HcQeE:n(575)};if(e[n(1368)](e[n(936)],n(1167))){let x=HmKTOy[n(1248)](_0x435975,HmKTOy.aBVAu,{message:HmKTOy[n(1256)]});this[n(251)+n(298)]&&this[n(251)+n(298)](x)}else this[n(1668)][n(902)]&&console[n(850)][n(1083)](console,["FRONTIER>",...t])}[r(1127)+r(1232)+"e"](t){let n=r,{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:f}=this._options,l=e.iKLOt(o,Math[n(1322)](f,e[n(1237)](t,1)));return e[n(321)](l,x)?x:l}[r(1158)](){let t=r;if(this[t(1466)]&&this[t(1466)][t(1463)+"te"]===this[t(994)+"NG"]){this[t(1085)+t(1647)](),this[t(1390)+t(613)+"Id"]=setTimeout(this._ping.bind(this),this._options[t(948)+t(229)]);return}if(!this[t(1466)]||e[t(614)](this[t(1466)].readyState,this[t(1174)]))return void this[t(783)+t(298)]();this[t(1466)]&&this[t(1466)][t(217)]("hi"),this[t(545)+t(418)+t(1671)]=e[t(1509)](setTimeout,this[t(783)+t(298)+t(1506)][t(350)](this),this[t(1668)]["pingTime"+t(1441)+t(1706)])}["_handleR"+r(298)+r(1506)](){let t=r;if(e[t(457)](e[t(747)],e[t(747)]))this[t(555)+t(932)]?.addCount(),this[t(232)](e[t(602)],e[t(1690)]),this[t(555)+t(932)]?.[t(1225)+"chMaxCount"]()?this["_handleR"+t(298)]():this[t(1158)]();else{let n={PFZMm:t(1068),WiqIs:WjNmlH[t(808)],sKuCk:function(l){return l()},vmNTT:function(l,p){let h=t;return WjNmlH[h(504)](l,p)},oaSfa:WjNmlH[t(1134)]},o=()=>{let l=t;_0x33cad8["removeEventListe"+l(547)](n[l(867)],x),_0x4b2a94[l(1616)+l(1473)+l(547)](l(765),f),_0x350d94[l(1616)+l(1473)+l(547)](n[l(706)],f)},x=()=>{let l=t;n[l(623)](_0x25c8a9),n[l(623)](o)},f=()=>{let l=t;n[l(627)](_0x2cd15b,_0x50561b[l(765)]||new _0x37bdb4(n.oaSfa,n[l(857)])),o()};_0x62ec07[t(1568)+t(786)](WjNmlH[t(268)],x),_0x528860[t(1568)+t(786)](WjNmlH[t(527)],f),_0xd7c3d4[t(1568)+"Listener"](WjNmlH[t(808)],f)}}["_navigat"+r(1467)](){let t=r;return this[t(968)+"T"]||this[t(1447)+"X"]?this["_miniNav"+t(1519)+t(472)]:(this[t(828)+"er"]||this[t(1162)+"r"])&&this[t(1668)][t(265)+t(434)+t(573)]?navigator[t(1611)]:!0}[r(783)+r(298)](){let t=r;if(e[t(1034)](e[t(1200)],e[t(1244)])){if(!this._navigatorOnline()||this[t(1672)+t(1663)])return;this["_endpoin"+t(557)]?.[t(642)+t(1353)+"fig"](),this[t(555)+t(932)]?.resetCounter(),this[t(1466)]?this[t(1049)+"ect"](1001,"going aw"+t(794)+t(1362)+t(1100)+t(429),!0):this[t(1152)]()}else{let n=0,o=[];for(;e[t(866)](n,_0x114322.byteLength);){let{offset:x}=e.rAHnM(_0x2c3187,_0x279041,n);n=x;let f={cursor_name:"",cursor:0,service:0},{value:l,offset:p}=_0x2470f9(_0x3b992e,n);f[t(1394)]=l,n=p;let{value:h,offset:_}=e[t(1652)](_0xe9fdd8,_0x52e1db,n);n=_,f[t(1403)+"ame"]=e.djldw(_0x3923ff,_0x528027,n,n+h),n+=h;let{value:C,offset:A}=e.UQIFD(_0x2a3533,_0x3fe106,n);f[t(1042)]=C.toNumber(),n=A,o[t(1722)](f)}return o}}[r(1544)+r(657)+"ange"](){let t=r,n={TDKaH:function(o,x){return o!==x},GkbvW:t(931)};this[t(968)+"T"]?tt[t(703)+t(1710)+t(1482)](({isConnected:o})=>{let x=t;this[x(399)+x(1519)+x(472)]=o,o?this["_handleO"+x(553)]():this[x(998)+"ffLine"]()}):this[t(1447)+"X"]&&wx[t(703)+t(1710)+t(1482)](({isConnected:o})=>{let x=t;n[x(1571)](x(931),n.GkbvW)?(_0x420dec(_0x29ae1d,50),_0x301505(_0x472243,_0x4b4c69)):(this[x(399)+x(1519)+x(472)]=o,o?this[x(998)+x(553)]():this[x(998)+"ffLine"]())})}[r(1303)](t){let n=r,o={WUqvq:function(x,f,l){return e[N(453)](x,f,l)},tjSYA:function(x,f){return x||f}};if(e.qthEm(e[n(470)],n(214)))return new Promise(x=>{let f=n;o[f(838)](setTimeout,x,this[f(1127)+f(1232)+"e"](t))});{let x=this[n(781)]["getStora"+n(536)](this[n(1090)]);return _0x258380[n(466)](ruXDaD.tjSYA(x,"{}"))[_0x458eb6]}}[r(1049)+r(816)](t=1e3,n="",o=!1){let x=r;this[x(1466)]&&this[x(1570)+x(612)+"t"](t,n,o)}[r(918)+"ut"](){let t=r,n={pAJko:t(344),NKOgl:e[t(534)]};if(e[t(269)](e[t(920)],e[t(1297)])){let o=this["_endpoin"+t(557)]?.["getCurre"+t(1314)+"nt"]();this[t(599)](t(1233)+o+t(1290)),this["_disconn"+t(816)](1001,e[t(505)],!0)}else _0x471d21&&_0x3eb8e1[t(1568)+t(786)](lFHsxX[t(431)],()=>_0x20220c()),_0x4dc21e&&_0x3e2af9[t(1568)+"Listener"](lFHsxX.NKOgl,()=>_0x12b70f())}[r(911)](t){let n=r,o=dr(t);this[n(1466)]&&e[n(457)](this._ws.readyState,this[n(1174)])&&(this[n(1466)]&&this[n(1466)][n(217)](o),this[n(599)](e[n(635)],t))}[r(1324)+"sListeners"](){let t=r,n={AgPBt:function(o,x){return o|x},FQajo:function(o,x){return e[N(1664)](o,x)},rllHO:function(o,x){return e.FAwhD(o,x)},SYmOY:function(o,x){return e[N(704)](o,x)},dvoWB:function(o,x){return e.qoGNy(o,x)}};if(e.IlcPc(e.IzmqN,t(752)))_0x3c358c[_0x15f641++]=xwVpPY[t(1370)](xwVpPY[t(1697)](_0x471f53,12),224),_0x2ee10d[_0x30de4e++]=xwVpPY[t(1565)](xwVpPY[t(652)](xwVpPY[t(1096)](_0x2ca0c1,6),63),128),_0x4ea2dc[_0x43f234++]=63&_0x3be2c2|128;else{let o=e[t(1319)][t(1742)]("|"),x=0;for(;;){switch(o[x++]){case"0":this[t(1466)][t(1616)+"entListener"](e[t(1350)],this[t(1257)+"ge"]);continue;case"1":this[t(1466)][t(1616)+"entListe"+t(547)](e[t(720)],this._onClose);continue;case"2":this[t(1466)][t(1616)+t(1473)+t(547)](e[t(302)],this._onOpen);continue;case"3":this[t(1466)][t(1616)+t(1473)+t(547)](e[t(527)],this[t(600)]);continue;case"4":if(!this._ws)return;continue}break}}}[r(665)+r(1476)](){let t=r,n=e[t(990)][t(1742)]("|"),o=0;for(;;){switch(n[o++]){case"0":this[t(1466)][t(1568)+t(786)](e.GaKbv,this[t(1257)+"ge"]);continue;case"1":this[t(1466)]["addEvent"+t(786)](e.IZYSR,this[t(1688)]);continue;case"2":this._ws.addEventListener(e[t(527)],this._onError);continue;case"3":this._ws[t(1568)+t(786)](t(1694),this[t(1484)]);continue;case"4":if(!this._ws)return;continue}break}}_wsInstanceClose(t=1e3,n=""){let o=r;try{this[o(1466)]&&this[o(1466)][o(344)](t,n)}catch{}}[r(1570)+"WebSocket"](t=1e3,n="",o=!1){let x=r;if(this[x(1085)+x(1647)](),this[x(1388)+x(1677)](),this["_removeW"+x(667)+"rs"](),this["_wsInsta"+x(525)](1e3,n),this[x(1152)+"Lock"]=!1,o&&this["_navigat"+x(1467)]()&&!this[x(1672)+x(1663)]){if(this[x(1558)+"tManager"]?.[x(1225)+"chMaxTries"]()){let l=this[x(1558)+x(557)]?.[x(751)+x(1314)+"nt"]();this["_dispatchCloseEv"+x(1151)](e[x(1566)](me,x(344),{code:1006,reason:x(1233)+l+(x(1290)+x(620)+"tries re"+x(1173)),wasClean:!0}))}else{let l=this[x(1668)][x(1362)+x(1295)+x(1433)](t,n);this[x(1472)+x(1479)+x(1151)](e.MIrow(me,"close",{code:t,reason:n,wasClean:!0,willReconnect:l})),l&&this[x(1152)]()}return}this[x(348)+"orOnline"]()||this[x(1672)+"osed"]?this[x(1472)+"hCloseEv"+x(1151)](e[x(1450)](me,e[x(720)],{code:t,reason:x(1126)})):this[x(1472)+x(1479)+x(1151)](e[x(1630)](me,e[x(720)],{code:1006,reason:e[x(364)]})),this[x(1466)]=null,this[x(1558)+"tManager"]?.[x(642)+x(1353)+x(452)](),this[x(555)+x(932)]?.[x(793)+x(1645)]()}["_dispatc"+r(1481)+"nt"](t){let n=r;this[n(232)](e[n(302)],t),this.onopen&&this[n(1662)](t)}[r(1472)+r(721)+"Event"](t){let n=r;this.emit(e[n(1350)],t),this[n(1015)+"e"]&&this[n(1015)+"e"](t)}[r(1472)+"hAckMessageEvent"](t){let n=r;this.emit(e[n(560)],t),this[n(1219)+n(488)]&&this.onReceiveAck(t)}[r(1472)+r(1527)+r(1151)](t){let n=r;this[n(232)](e[n(527)],t),this[n(1014)]&&this.onerror(t)}[r(1472)+"hCloseEv"+r(1151)](t){let n=r;this[n(232)](e[n(720)],t),this[n(840)]&&this.onclose(t)}get binaryType(){let t=r,n={sJBqE:function(o,x){return o>x},QxTwI:function(o,x){return o+x}};if(t(1137)===e[t(829)]){let o=_0x2c7127.offset;if(zSYpdm[t(941)](zSYpdm[t(688)](o,_0x1e6ff8),_0xdeabef.limit))throw new _0x5bbded(t(1462)+t(1714));return _0x552c42[t(1017)]+=_0x4424a7,o}else return this[t(1466)]?this[t(1466)].binaryType:this[t(1183)+t(690)]}set[r(1204)+"pe"](t){let n=r;this[n(1183)+n(690)]=t,this._ws&&(this[n(1466)][n(1204)+"pe"]=t)}get retryCount(){let t=r;return this["_endpoin"+t(557)]?.["getCurrentEndpointTriesC"+t(944)]()||0}get[r(1071)+r(1220)](){let t=r,n=this._messageQueue[t(493)]((o,x)=>(o+=x&&x[t(371)+"th"]||0,o),0);return e[t(1201)](n,this[t(1466)]?this[t(1466)][t(1071)+t(1220)]:0)}get[r(697)+"ns"](){let t=r;return this[t(1466)]?this._ws[t(697)+"ns"]:""}get[r(1398)](){let t=r;return this[t(1466)]?this[t(1466)].protocol:""}get[r(1463)+"te"](){let t=r;return this[t(1466)]?this._ws[t(1463)+"te"]:this[t(1668)][t(643)+t(446)]?this[t(994)+"NG"]:this.CLOSED}get url(){let t=r;return this[t(1466)]?this._ws[t(1723)]:this[t(753)]}[r(344)](t=1e3,n){let o=r,x={FMPZh:function(f,l){return e[N(1282)](f,l)},lCTHp:function(f,l){return e.AGlUk(f,l)},mjAjB:function(f,l){return e.PVxXh(f,l)},AQAgt:function(f,l){return e[N(928)](f,l)},uAQYt:function(f,l){return e[N(1729)](f,l)},VytWk:function(f,l){return e[N(733)](f,l)},Iipwj:function(f,l){return e[N(1043)](f,l)},BSOfy:function(f,l){return e[N(917)](f,l)}};if(e[o(1103)]===e[o(1103)]){let f=e.gjIJo[o(1742)]("|"),l=0;for(;;){switch(f[l++]){case"0":this[o(1570)+o(612)+"t"](t,n);continue;case"1":this[o(1085)+o(1647)]();continue;case"2":this[o(1388)+"mer"]();continue;case"3":this[o(1672)+o(1663)]=!0;continue;case"4":if(!this[o(1466)])return void this[o(599)](e[o(1628)]);continue;case"5":this[o(548)+o(1358)+o(786)]();continue;case"6":if(e.AyhXQ(this[o(1466)].readyState,this[o(909)])||e[o(1726)](this._ws.readyState,this[o(1023)]))return void this[o(599)](e.SnqbE);continue;case"7":this[o(235)+o(1560)]?.closeDB();continue}break}}else _0x1b51e6=_0x141cbf[muDjKE[o(1215)](muDjKE.FMPZh(_0x4c3ebf,_0x58ca79),1)],muDjKE[o(1511)](muDjKE[o(782)](192,_0x5a6579),128)?_0x40408c+=_0x2cc3e2:(_0x10ddca=muDjKE.AQAgt(muDjKE[o(1494)](31,_0x40c402),6)|muDjKE[o(332)](63,_0x571408),muDjKE[o(1320)](_0x10e18c,128)?_0x17a4bf+=_0x56e5a1:(_0x432870+=muDjKE[o(1577)](_0x255138,_0x4c77f2),_0x5b6530++))}async[r(217)](t,n){let o=r;if(e[o(712)](null,t))throw new Error(e[o(991)]);e[o(1139)]==typeof t&&(t=JSON[o(622)+"y"](t)),e[o(1087)](e.FcKII,typeof t)&&!(t instanceof ArrayBuffer)&&!(t[o(1633)]&&e[o(1160)](t[o(1633)],ArrayBuffer))&&(t=JSON[o(622)+"y"](t));let x=await e[o(603)](Ns,t),f=e[o(945)](Ma,t),{method:l=0,service:p=this._options[o(1394)],logID:h=this[o(1668)][o(930)+"erator"](),headers:_=this[o(1668)].headers,payloadEncoding:C=this[o(1668)][o(656)+o(367)],payloadType:A=this._options[o(461)+o(690)],logIDNew:I=this[o(1668)].logIDNewConfig[o(570)+"toGenerateLogIDNew"]?e[o(1149)](a,this[o(1668)][o(1272)+o(352)][o(454)]):""}=e[o(1572)](n,{});if(!p)throw new Error(e[o(312)]);let L={SeqID:U[o(259)+"er"](this._seqId++),LogID:U[o(259)+"er"](h),service:p,method:l,headers:_,payloadEncoding:e.OnfSR(C,Object)?C.encoding?C[o(906)]:"":C,payloadType:e[o(495)](A,Object)?A[o(1587)]?A.type:f:A||f,payload:x,LogIDNew:I},M=e[o(1061)](dr,L);return this[o(1466)]&&this[o(1466)].readyState===this[o(1174)]?(this[o(1466)]&&this[o(1466)][o(217)](M),this[o(599)](e[o(404)],L)):e[o(1634)](this[o(676)+"Queue"][o(1313)],this._options[o(843)+o(357)+o(1655)])?(this[o(676)+"Queue"].push(M),this._debug(o(1576),L)):(this["_message"+o(468)][o(1318)](),this[o(676)+o(468)][o(1722)](M)),{seqID:this[o(1651)],logID:h,logIDNew:I}}async[r(1362)+"t"](t){let n=r,o={pFDzb:n(1403)+n(977)},{url:x}=e[n(629)](t,{}),f=Array[n(276)](x)?x:e[n(1764)](e.FcKII,typeof x)?[x]:[];t&&Object[n(976)](this[n(1668)],t),f&&f[n(1313)]?this[n(1558)+"tManager"]=new ks(f,this[n(1668)].maxRetries):this[n(1558)+"tManager"]?.[n(642)+n(1353)+n(452)](),this[n(555)+n(932)]?.[n(793)+n(1645)](this[n(1668)][n(1549)+n(388)]),this[n(1672)+n(1663)]=!1,this[n(1466)]&&e.iNagZ(this[n(1466)][n(1463)+"te"],this[n(909)])?this["_disconn"+n(816)](1e3,n(1168)+n(298)+n(270),!0):e[n(486)]===e[n(1050)]?(this["_cursorN"+n(718)]=_0x2ca586,this[n(1648)+"ileName"]=_0x11f0f4,this["_message"+n(823)]=_0x5a704d,this[n(781)]=_0x5ae915(this[n(799)+n(718)],eiSVvO[n(1389)])):(this[n(1059)]=!0,this._connect())}async[r(1468)](){let t=r;!this[t(1152)+t(1325)]&&(this["_endpoin"+t(557)]?.[t(642)+t(1353)+t(452)](),this[t(555)+t(932)]?.[t(793)+t(1645)](),this["_readyCl"+t(1663)]=!1,this[t(1059)]=!0,this[t(1152)]())}[r(1568)+r(786)](t,n){let o=r;o(403)===e[o(1077)]?this.on(t,n):WjNmlH[o(495)](_0x4591c8,_0x54bdf7)&&_0x4b83fb[o(1667)](_0x5704c4,_0x3509e3)}["dispatch"+r(419)](t){let{type:n}=t;this.emit(n,t)}[r(1616)+r(1473)+r(547)](t,n){let o=r;if(e[o(242)](o(927),e.gBXpP))return new _0x17d24d(_0x424333,{data:_0x41b085});this.off(t,n)}[r(792)](){let t=r,n={hQLwG:function(o,x){return o(x)},NqJNd:e[t(1690)],jmeyN:e[t(602)],lZtqq:e[t(522)],lSpZX:e[t(292)],PLbSi:function(o,x){return e[t(550)](o,x)},EivWB:e[t(559)],XiGTh:function(o,x,f){return e[t(430)](o,x,f)}};return new Promise((o,x)=>{let f=t,l={oLowB:function(p,h){return p(h)},qnunF:n.lZtqq,BdTBf:n[f(1252)],qqoGX:n.jmeyN};if(n[f(1458)](n[f(358)],n.EivWB))return _0x32f95e+=_0x257d62&&_0x4ce770[f(371)+"th"]||0,_0x345d85;{this[f(1085)+"ngTimer"](),this["_pingPon"+f(613)+"Id"]=n[f(955)](setTimeout,this[f(1158)][f(350)](this),this[f(1668)][f(948)+f(229)]);let p=()=>{let _=f;l[_(1693)](o,l[_(778)]),this[_(1003)](l[_(1367)],p),this.off(l[_(674)],h)},h=()=>{let _=f;n.hQLwG(x,n[_(709)]),this[_(1003)]("ping_onc"+_(851)+"s",p),this.off(n.jmeyN,h)};this.on(n[f(1252)],p),this.on("ping_onc"+f(856)+"t",h),this[f(1158)]()}})}}})(),Q[b(336)+b(1735)]=$[b(336)+"oseEvent"],Q["CustomEr"+b(1224)]=$[b(895)+"rorEvent"],Q[b(1643)+"e"]=$[b(1643)+"e"],Q[b(419)]=$[b(419)],Q[b(875)]=$[b(875)],Q[b(240)+b(456)+b(247)]=$["Frontier"+b(456)+b(247)],Q["MessageE"+b(247)]=$["MessageE"+b(247)],Q.OpenEvent=$[b(412)+"t"],Q[b(1553)+b(1349)]=$.ReconnectEvent,Q[b(1381)+b(1735)]=$[b(1381)+b(1735)],Q[b(755)+b(1224)]=$[b(755)+"rorEvent"],Q[b(1759)+b(1304)+"nt"]=$[b(1759)+"ssageEvent"],Q[b(1150)+b(435)]=$[b(1150)+b(435)],Q["createRe"+b(1186)+b(247)]=$[b(1650)+"connectE"+b(247)],Q[b(1053)+"rame"]=$[b(1053)+b(1037)],Q[b(1084)+"ame"]=$[b(1084)+b(977)];for(Mn in $)[b(336)+b(1735),"CustomEr"+b(1224),b(1643)+"e",b(419),"FWS",b(240)+b(456)+"vent",b(456)+"vent",b(412)+"t","Reconnec"+b(1349),b(1381)+b(1735),b(755)+b(1224),b(1759)+b(1304)+"nt",b(1150)+b(435),b(1650)+"connectE"+b(247),b(1053)+b(1037),b(1084)+b(977)][b(1474)](Mn)===-1&&(Q[Mn]=$[Mn]);var Mn;Object[b(503)+b(744)](Q,b(1452)+"le",{value:!0})});var Oe=ae((Zh,Qi)=>{"use strict";var Xi=["nodebuffer","arraybuffer","fragments"],$i=typeof Blob<"u";$i&&Xi.push("blob");Qi.exports={BINARY_TYPES:Xi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:$i,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var jt=ae((eg,Hn)=>{"use strict";var{EMPTY_BUFFER:Rx}=Oe(),Or=Buffer[Symbol.species];function Nx(r,e){if(r.length===0)return Rx;if(r.length===1)return r[0];let i=Buffer.allocUnsafe(e),a=0;for(let c=0;c<r.length;c++){let u=r[c];i.set(u,a),a+=u.length}return a<e?new Or(i.buffer,i.byteOffset,a):i}function Zi(r,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=r[u]^e[u&3]}function eo(r,e){for(let i=0;i<r.length;i++)r[i]^=e[i&3]}function Lx(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Br(r){if(Br.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Or(r):ArrayBuffer.isView(r)?e=new Or(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Br.readOnly=!1),e}Hn.exports={concat:Nx,mask:Zi,toArrayBuffer:Lx,toBuffer:Br,unmask:eo};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=X("bufferutil");Hn.exports.mask=function(e,i,a,c,u){u<48?Zi(e,i,a,c,u):r.mask(e,i,a,c,u)},Hn.exports.unmask=function(e,i){e.length<32?eo(e,i):r.unmask(e,i)}}catch{}});var ro=ae((tg,no)=>{"use strict";var to=Symbol("kDone"),zr=Symbol("kRun"),qr=class{constructor(e){this[to]=()=>{this.pending--,this[zr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[zr]()}[zr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[to])}}};no.exports=qr});var vt=ae((ng,ao)=>{"use strict";var Wt=X("zlib"),so=jt(),Mx=ro(),{kStatusCode:io}=Oe(),Ox=Buffer[Symbol.species],Bx=Buffer.from([0,0,255,255]),Kn=Symbol("permessage-deflate"),Be=Symbol("total-length"),_t=Symbol("callback"),Je=Symbol("buffers"),yt=Symbol("error"),Gn,Fr=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,!Gn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Gn=new Mx(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[_t];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let i=this._options,a=e.find(c=>!(i.serverNoContextTakeover===!1&&c.server_no_context_takeover||c.server_max_window_bits&&(i.serverMaxWindowBits===!1||typeof i.serverMaxWindowBits=="number"&&i.serverMaxWindowBits>c.server_max_window_bits)||typeof i.clientMaxWindowBits=="number"&&!c.client_max_window_bits));if(!a)throw new Error("None of the extension offers can be accepted");return i.serverNoContextTakeover&&(a.server_no_context_takeover=!0),i.clientNoContextTakeover&&(a.client_no_context_takeover=!0),typeof i.serverMaxWindowBits=="number"&&(a.server_max_window_bits=i.serverMaxWindowBits),typeof i.clientMaxWindowBits=="number"?a.client_max_window_bits=i.clientMaxWindowBits:(a.client_max_window_bits===!0||i.clientMaxWindowBits===!1)&&delete a.client_max_window_bits,a}acceptAsClient(e){let i=e[0];if(this._options.clientNoContextTakeover===!1&&i.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!i.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(i.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&i.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return i}normalizeParams(e){return e.forEach(i=>{Object.keys(i).forEach(a=>{let c=i[a];if(c.length>1)throw new Error(`Parameter "${a}" must have only a single value`);if(c=c[0],a==="client_max_window_bits"){if(c!==!0){let u=+c;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${c}`);c=u}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${a}": ${c}`)}else if(a==="server_max_window_bits"){let u=+c;if(!Number.isInteger(u)||u<8||u>15)throw new TypeError(`Invalid value for parameter "${a}": ${c}`);c=u}else if(a==="client_no_context_takeover"||a==="server_no_context_takeover"){if(c!==!0)throw new TypeError(`Invalid value for parameter "${a}": ${c}`)}else throw new Error(`Unknown parameter "${a}"`);i[a]=c})}),e}decompress(e,i,a){Gn.add(c=>{this._decompress(e,i,(u,d)=>{c(),a(u,d)})})}compress(e,i,a){Gn.add(c=>{this._compress(e,i,(u,d)=>{c(),a(u,d)})})}_decompress(e,i,a){let c=this._isServer?"client":"server";if(!this._inflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Wt.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Wt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[Kn]=this,this._inflate[Be]=0,this._inflate[Je]=[],this._inflate.on("error",qx),this._inflate.on("data",oo)}this._inflate[_t]=a,this._inflate.write(e),i&&this._inflate.write(Bx),this._inflate.flush(()=>{let u=this._inflate[yt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=so.concat(this._inflate[Je],this._inflate[Be]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Be]=0,this._inflate[Je]=[],i&&this.params[`${c}_no_context_takeover`]&&this._inflate.reset()),a(null,d)})}_compress(e,i,a){let c=this._isServer?"server":"client";if(!this._deflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Wt.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Wt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Be]=0,this._deflate[Je]=[],this._deflate.on("data",zx)}this._deflate[_t]=a,this._deflate.write(e),this._deflate.flush(Wt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=so.concat(this._deflate[Je],this._deflate[Be]);i&&(u=new Ox(u.buffer,u.byteOffset,u.length-4)),this._deflate[_t]=null,this._deflate[Be]=0,this._deflate[Je]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};ao.exports=Fr;function zx(r){this[Je].push(r),this[Be]+=r.length}function oo(r){if(this[Be]+=r.length,this[Kn]._maxPayload<1||this[Be]<=this[Kn]._maxPayload){this[Je].push(r);return}this[yt]=new RangeError("Max payload size exceeded"),this[yt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[yt][io]=1009,this.removeListener("data",oo),this.reset()}function qx(r){if(this[Kn]._inflate=null,this[yt]){this[_t](this[yt]);return}r[io]=1007,this[_t](r)}});var bt=ae((rg,jn)=>{"use strict";var{isUtf8:co}=X("buffer"),{hasBlob:Fx}=Oe(),Ux=[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 Hx(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Ur(r){let e=r.length,i=0;for(;i<e;)if((r[i]&128)===0)i++;else if((r[i]&224)===192){if(i+1===e||(r[i+1]&192)!==128||(r[i]&254)===192)return!1;i+=2}else if((r[i]&240)===224){if(i+2>=e||(r[i+1]&192)!==128||(r[i+2]&192)!==128||r[i]===224&&(r[i+1]&224)===128||r[i]===237&&(r[i+1]&224)===160)return!1;i+=3}else if((r[i]&248)===240){if(i+3>=e||(r[i+1]&192)!==128||(r[i+2]&192)!==128||(r[i+3]&192)!==128||r[i]===240&&(r[i+1]&240)===128||r[i]===244&&r[i+1]>143||r[i]>244)return!1;i+=4}else return!1;return!0}function Gx(r){return Fx&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}jn.exports={isBlob:Gx,isValidStatusCode:Hx,isValidUTF8:Ur,tokenChars:Ux};if(co)jn.exports.isValidUTF8=function(r){return r.length<24?Ur(r):co(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=X("utf-8-validate");jn.exports.isValidUTF8=function(e){return e.length<32?Ur(e):r(e)}}catch{}});var Wr=ae((sg,po)=>{"use strict";var{Writable:Kx}=X("stream"),xo=vt(),{BINARY_TYPES:jx,EMPTY_BUFFER:uo,kStatusCode:Wx,kWebSocket:Jx}=Oe(),{concat:Hr,toArrayBuffer:Vx,unmask:Yx}=jt(),{isValidStatusCode:Xx,isValidUTF8:fo}=bt(),Wn=Buffer[Symbol.species],he=0,lo=1,ho=2,go=3,Gr=4,Kr=5,Jn=6,jr=class extends Kx{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||jx[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Jx]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=he}_write(e,i,a){if(this._opcode===8&&this._state==he)return a();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(a)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let a=this._buffers[0];return this._buffers[0]=new Wn(a.buffer,a.byteOffset+e,a.length-e),new Wn(a.buffer,a.byteOffset,e)}let i=Buffer.allocUnsafe(e);do{let a=this._buffers[0],c=i.length-e;e>=a.length?i.set(this._buffers.shift(),c):(i.set(new Uint8Array(a.buffer,a.byteOffset,e),c),this._buffers[0]=new Wn(a.buffer,a.byteOffset+e,a.length-e)),e-=a.length}while(e>0);return i}startLoop(e){this._loop=!0;do switch(this._state){case he:this.getInfo(e);break;case lo:this.getPayloadLength16(e);break;case ho:this.getPayloadLength64(e);break;case go:this.getMask();break;case Gr:this.getData(e);break;case Kr:case Jn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let i=this.consume(2);if((i[0]&48)!==0){let c=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(c);return}let a=(i[0]&64)===64;if(a&&!this._extensions[xo.extensionName]){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(this._fin=(i[0]&128)===128,this._opcode=i[0]&15,this._payloadLength=i[1]&127,this._opcode===0){if(a){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(!this._fragmented){let c=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let c=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}this._compressed=a}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let c=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(c);return}if(a){let c=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(c);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let c=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(c);return}}else{let c=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(c);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(i[1]&128)===128,this._isServer){if(!this._masked){let c=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(c);return}}else if(this._masked){let c=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(c);return}this._payloadLength===126?this._state=lo:this._payloadLength===127?this._state=ho:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let i=this.consume(8),a=i.readUInt32BE(0);if(a>Math.pow(2,21)-1){let c=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(c);return}this._payloadLength=a*Math.pow(2,32)+i.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(i);return}this._masked?this._state=go:this._state=Gr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Gr}getData(e){let i=uo;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&&Yx(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Kr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[xo.extensionName].decompress(e,this._fin,(c,u)=>{if(c)return i(c);if(u.length){if(this._messageLength+=u.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(d);return}this._fragments.push(u)}this.dataMessage(i),this._state===he&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=he;return}let i=this._messageLength,a=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let c;this._binaryType==="nodebuffer"?c=Hr(a,i):this._binaryType==="arraybuffer"?c=Vx(Hr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=he):(this._state=Jn,setImmediate(()=>{this.emit("message",c,!0),this._state=he,this.startLoop(e)}))}else{let c=Hr(a,i);if(!this._skipUTF8Validation&&!fo(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=he):(this._state=Jn,setImmediate(()=>{this.emit("message",c,!1),this._state=he,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,uo),this.end();else{let a=e.readUInt16BE(0);if(!Xx(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new Wn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!fo(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");i(u);return}this._loop=!1,this.emit("conclude",a,c),this.end()}this._state=he;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=he):(this._state=Jn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=he,this.startLoop(i)}))}createError(e,i,a,c,u){this._loop=!1,this._errored=!0;let d=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(d,this.createError),d.code=u,d[Wx]=c,d}};po.exports=jr});var Yr=ae((og,_o)=>{"use strict";var{Duplex:ig}=X("stream"),{randomFillSync:$x}=X("crypto"),mo=vt(),{EMPTY_BUFFER:Qx,kWebSocket:Zx,NOOP:eu}=Oe(),{isBlob:St,isValidStatusCode:tu}=bt(),{mask:wo,toBuffer:et}=jt(),ge=Symbol("kByteLength"),nu=Buffer.alloc(4),Vn=8*1024,nt,Et=Vn,_e=0,ru=1,su=2,Jr=class r{constructor(e,i,a){this._extensions=i||{},a&&(this._generateMask=a,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=_e,this.onerror=eu,this[Zx]=void 0}static frame(e,i){let a,c=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||nu,i.generateMask?i.generateMask(a):(Et===Vn&&(nt===void 0&&(nt=Buffer.alloc(Vn)),$x(nt,0,Vn),Et=0),a[0]=nt[Et++],a[1]=nt[Et++],a[2]=nt[Et++],a[3]=nt[Et++]),d=(a[0]|a[1]|a[2]|a[3])===0,u=6);let g;typeof e=="string"?(!i.mask||d)&&i[ge]!==void 0?g=i[ge]:(e=Buffer.from(e),g=e.length):(g=e.length,c=i.mask&&i.readOnly&&!d);let m=g;g>=65536?(u+=8,m=127):g>125&&(u+=2,m=126);let w=Buffer.allocUnsafe(c?g+u:u);return w[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(w[0]|=64),w[1]=m,m===126?w.writeUInt16BE(g,2):m===127&&(w[2]=w[3]=0,w.writeUIntBE(g,4,6)),i.mask?(w[1]|=128,w[u-4]=a[0],w[u-3]=a[1],w[u-2]=a[2],w[u-1]=a[3],d?[w,e]:c?(wo(e,a,w,u,g),[w]):(wo(e,a,e,0,g),[w,e])):[w,e]}close(e,i,a,c){let u;if(e===void 0)u=Qx;else{if(typeof e!="number"||!tu(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 g=Buffer.byteLength(i);if(g>123)throw new RangeError("The message must not be greater than 123 bytes");u=Buffer.allocUnsafe(2+g),u.writeUInt16BE(e,0),typeof i=="string"?u.write(i,2):u.set(i,2)}}let d={[ge]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==_e?this.enqueue([this.dispatch,u,!1,d,c]):this.sendFrame(r.frame(u,d),c)}ping(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):St(e)?(c=e.size,u=!1):(e=et(e),c=e.length,u=et.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ge]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};St(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(r.frame(e,d),a)}pong(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):St(e)?(c=e.size,u=!1):(e=et(e),c=e.length,u=et.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[ge]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};St(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(r.frame(e,d),a)}send(e,i,a){let c=this._extensions[mo.extensionName],u=i.binary?2:1,d=i.compress,g,m;typeof e=="string"?(g=Buffer.byteLength(e),m=!1):St(e)?(g=e.size,m=!1):(e=et(e),g=e.length,m=et.readOnly),this._firstFragment?(this._firstFragment=!1,d&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=g>=c._threshold),this._compress=d):(d=!1,u=0),i.fin&&(this._firstFragment=!0);let w={[ge]:g,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:m,rsv1:d};St(e)?this._state!==_e?this.enqueue([this.getBlobData,e,this._compress,w,a]):this.getBlobData(e,this._compress,w,a):this._state!==_e?this.enqueue([this.dispatch,e,this._compress,w,a]):this.dispatch(e,this._compress,w,a)}getBlobData(e,i,a,c){this._bufferedBytes+=a[ge],this._state=su,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let g=new Error("The socket was closed while the blob was being read");process.nextTick(Vr,this,g,c);return}this._bufferedBytes-=a[ge];let d=et(u);i?this.dispatch(d,i,a,c):(this._state=_e,this.sendFrame(r.frame(d,a),c),this.dequeue())}).catch(u=>{process.nextTick(iu,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(r.frame(e,a),c);return}let u=this._extensions[mo.extensionName];this._bufferedBytes+=a[ge],this._state=ru,u.compress(e,a.fin,(d,g)=>{if(this._socket.destroyed){let m=new Error("The socket was closed while data was being compressed");Vr(this,m,c);return}this._bufferedBytes-=a[ge],this._state=_e,a.readOnly=!1,this.sendFrame(r.frame(g,a),c),this.dequeue()})}dequeue(){for(;this._state===_e&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ge],this._queue.push(e)}sendFrame(e,i){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],i),this._socket.uncork()):this._socket.write(e[0],i)}};_o.exports=Jr;function Vr(r,e,i){typeof i=="function"&&i(e);for(let a=0;a<r._queue.length;a++){let c=r._queue[a],u=c[c.length-1];typeof u=="function"&&u(e)}}function iu(r,e,i){Vr(r,e,i),r.onerror(e)}});var Do=ae((ag,Po)=>{"use strict";var{kForOnEventAttribute:Jt,kListener:Xr}=Oe(),yo=Symbol("kCode"),vo=Symbol("kData"),bo=Symbol("kError"),So=Symbol("kMessage"),Eo=Symbol("kReason"),Ct=Symbol("kTarget"),Co=Symbol("kType"),Ao=Symbol("kWasClean"),ze=class{constructor(e){this[Ct]=null,this[Co]=e}get target(){return this[Ct]}get type(){return this[Co]}};Object.defineProperty(ze.prototype,"target",{enumerable:!0});Object.defineProperty(ze.prototype,"type",{enumerable:!0});var rt=class extends ze{constructor(e,i={}){super(e),this[yo]=i.code===void 0?0:i.code,this[Eo]=i.reason===void 0?"":i.reason,this[Ao]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[yo]}get reason(){return this[Eo]}get wasClean(){return this[Ao]}};Object.defineProperty(rt.prototype,"code",{enumerable:!0});Object.defineProperty(rt.prototype,"reason",{enumerable:!0});Object.defineProperty(rt.prototype,"wasClean",{enumerable:!0});var At=class extends ze{constructor(e,i={}){super(e),this[bo]=i.error===void 0?null:i.error,this[So]=i.message===void 0?"":i.message}get error(){return this[bo]}get message(){return this[So]}};Object.defineProperty(At.prototype,"error",{enumerable:!0});Object.defineProperty(At.prototype,"message",{enumerable:!0});var Vt=class extends ze{constructor(e,i={}){super(e),this[vo]=i.data===void 0?null:i.data}get data(){return this[vo]}};Object.defineProperty(Vt.prototype,"data",{enumerable:!0});var ou={addEventListener(r,e,i={}){for(let c of this.listeners(r))if(!i[Jt]&&c[Xr]===e&&!c[Jt])return;let a;if(r==="message")a=function(u,d){let g=new Vt("message",{data:d?u:u.toString()});g[Ct]=this,Yn(e,this,g)};else if(r==="close")a=function(u,d){let g=new rt("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});g[Ct]=this,Yn(e,this,g)};else if(r==="error")a=function(u){let d=new At("error",{error:u,message:u.message});d[Ct]=this,Yn(e,this,d)};else if(r==="open")a=function(){let u=new ze("open");u[Ct]=this,Yn(e,this,u)};else return;a[Jt]=!!i[Jt],a[Xr]=e,i.once?this.once(r,a):this.on(r,a)},removeEventListener(r,e){for(let i of this.listeners(r))if(i[Xr]===e&&!i[Jt]){this.removeListener(r,i);break}}};Po.exports={CloseEvent:rt,ErrorEvent:At,Event:ze,EventTarget:ou,MessageEvent:Vt};function Yn(r,e,i){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,i):r.call(e,i)}});var Xn=ae((cg,ko)=>{"use strict";var{tokenChars:Yt}=bt();function Pe(r,e,i){r[e]===void 0?r[e]=[i]:r[e].push(i)}function au(r){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,d,g,m=-1,w=-1,v=-1,y=0;for(;y<r.length;y++)if(w=r.charCodeAt(y),d===void 0)if(v===-1&&Yt[w]===1)m===-1&&(m=y);else if(y!==0&&(w===32||w===9))v===-1&&m!==-1&&(v=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);v===-1&&(v=y);let D=r.slice(m,v);w===44?(Pe(e,D,i),i=Object.create(null)):d=D,m=v=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);else if(g===void 0)if(v===-1&&Yt[w]===1)m===-1&&(m=y);else if(w===32||w===9)v===-1&&m!==-1&&(v=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);v===-1&&(v=y),Pe(i,r.slice(m,v),!0),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),m=v=-1}else if(w===61&&m!==-1&&v===-1)g=r.slice(m,y),m=v=-1;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(c){if(Yt[w]!==1)throw new SyntaxError(`Unexpected character at index ${y}`);m===-1?m=y:a||(a=!0),c=!1}else if(u)if(Yt[w]===1)m===-1&&(m=y);else if(w===34&&m!==-1)u=!1,v=y;else if(w===92)c=!0;else throw new SyntaxError(`Unexpected character at index ${y}`);else if(w===34&&r.charCodeAt(y-1)===61)u=!0;else if(v===-1&&Yt[w]===1)m===-1&&(m=y);else if(m!==-1&&(w===32||w===9))v===-1&&(v=y);else if(w===59||w===44){if(m===-1)throw new SyntaxError(`Unexpected character at index ${y}`);v===-1&&(v=y);let D=r.slice(m,v);a&&(D=D.replace(/\\/g,""),a=!1),Pe(i,g,D),w===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),g=void 0,m=v=-1}else throw new SyntaxError(`Unexpected character at index ${y}`);if(m===-1||u||w===32||w===9)throw new SyntaxError("Unexpected end of input");v===-1&&(v=y);let E=r.slice(m,v);return d===void 0?Pe(e,E,i):(g===void 0?Pe(i,E,!0):a?Pe(i,g,E.replace(/\\/g,"")):Pe(i,g,E),Pe(e,d,i)),e}function cu(r){return Object.keys(r).map(e=>{let i=r[e];return Array.isArray(i)||(i=[i]),i.map(a=>[e].concat(Object.keys(a).map(c=>{let u=a[c];return Array.isArray(u)||(u=[u]),u.map(d=>d===!0?c:`${c}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ko.exports={format:cu,parse:au}});var er=ae((fg,Uo)=>{"use strict";var xu=X("events"),uu=X("https"),fu=X("http"),Ro=X("net"),du=X("tls"),{randomBytes:lu,createHash:hu}=X("crypto"),{Duplex:xg,Readable:ug}=X("stream"),{URL:$r}=X("url"),Ve=vt(),gu=Wr(),pu=Yr(),{isBlob:mu}=bt(),{BINARY_TYPES:To,CLOSE_TIMEOUT:wu,EMPTY_BUFFER:$n,GUID:_u,kForOnEventAttribute:Qr,kListener:yu,kStatusCode:vu,kWebSocket:Z,NOOP:No}=Oe(),{EventTarget:{addEventListener:bu,removeEventListener:Su}}=Do(),{format:Eu,parse:Cu}=Xn(),{toBuffer:Au}=jt(),Lo=Symbol("kAborted"),Zr=[8,13],qe=["CONNECTING","OPEN","CLOSING","CLOSED"],Pu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,j=class r extends xu{constructor(e,i,a){super(),this._binaryType=To[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=$n,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=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]),Mo(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){To.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,i,a){let c=new gu({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new pu(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[Z]=this,u[Z]=this,e[Z]=this,c.on("conclude",Tu),c.on("drain",Iu),c.on("error",Ru),c.on("message",Nu),c.on("ping",Lu),c.on("pong",Mu),u.onerror=Ou,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",zo),e.on("data",Zn),e.on("end",qo),e.on("error",Fo),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Ve.extensionName]&&this._extensions[Ve.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,i){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){de(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())}),Bo(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){es(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||$n,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){es(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||$n,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){es(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[Ve.extensionName]||(c.compress=!1),this._sender.send(e||$n,c,a)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){de(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(j,"CONNECTING",{enumerable:!0,value:qe.indexOf("CONNECTING")});Object.defineProperty(j.prototype,"CONNECTING",{enumerable:!0,value:qe.indexOf("CONNECTING")});Object.defineProperty(j,"OPEN",{enumerable:!0,value:qe.indexOf("OPEN")});Object.defineProperty(j.prototype,"OPEN",{enumerable:!0,value:qe.indexOf("OPEN")});Object.defineProperty(j,"CLOSING",{enumerable:!0,value:qe.indexOf("CLOSING")});Object.defineProperty(j.prototype,"CLOSING",{enumerable:!0,value:qe.indexOf("CLOSING")});Object.defineProperty(j,"CLOSED",{enumerable:!0,value:qe.indexOf("CLOSED")});Object.defineProperty(j.prototype,"CLOSED",{enumerable:!0,value:qe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(j.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(j.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Qr])return e[yu];return null},set(e){for(let i of this.listeners(r))if(i[Qr]){this.removeListener(r,i);break}typeof e=="function"&&this.addEventListener(r,e,{[Qr]:!0})}})});j.prototype.addEventListener=bu;j.prototype.removeEventListener=Su;Uo.exports=j;function Mo(r,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wu,protocolVersion:Zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=c.autoPong,r._closeTimeout=c.closeTimeout,!Zr.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${Zr.join(", ")})`);let u;if(e instanceof $r)u=e;else try{u=new $r(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:",g=u.protocol==="ws+unix:",m;if(u.protocol!=="ws:"&&!d&&!g?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:g&&!u.pathname?m="The URL's pathname is empty":u.hash&&(m="The URL contains a fragment identifier"),m){let T=new SyntaxError(m);if(r._redirects===0)throw T;Qn(r,T);return}let w=d?443:80,v=lu(16).toString("base64"),y=d?uu.request:fu.request,E=new Set,D;if(c.createConnection=c.createConnection||(d?ku:Du),c.defaultPort=c.defaultPort||w,c.port=u.port||w,c.host=u.hostname.startsWith("[")?u.hostname.slice(1,-1):u.hostname,c.headers={...c.headers,"Sec-WebSocket-Version":c.protocolVersion,"Sec-WebSocket-Key":v,Connection:"Upgrade",Upgrade:"websocket"},c.path=u.pathname+u.search,c.timeout=c.handshakeTimeout,c.perMessageDeflate&&(D=new Ve({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=Eu({[Ve.extensionName]:D.offer()})),i.length){for(let T of i){if(typeof T!="string"||!Pu.test(T)||E.has(T))throw new SyntaxError("An invalid or duplicated subprotocol was specified");E.add(T)}c.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(c.origin&&(c.protocolVersion<13?c.headers["Sec-WebSocket-Origin"]=c.origin:c.headers.Origin=c.origin),(u.username||u.password)&&(c.auth=`${u.username}:${u.password}`),g){let T=c.path.split(":");c.socketPath=T[0],c.path=T[1]}let k;if(c.followRedirects){if(r._redirects===0){r._originalIpc=g,r._originalSecure=d,r._originalHostOrSocketPath=g?c.socketPath:u.host;let T=a&&a.headers;if(a={...a,headers:{}},T)for(let[H,ie]of Object.entries(T))a.headers[H.toLowerCase()]=ie}else if(r.listenerCount("redirect")===0){let T=g?r._originalIpc?c.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:u.host===r._originalHostOrSocketPath;(!T||r._originalSecure&&!d)&&(delete c.headers.authorization,delete c.headers.cookie,T||delete c.headers.host,c.auth=void 0)}c.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(c.auth).toString("base64")),k=r._req=y(c),r._redirects&&r.emit("redirect",r.url,k)}else k=r._req=y(c);c.timeout&&k.on("timeout",()=>{de(r,k,"Opening handshake has timed out")}),k.on("error",T=>{k===null||k[Lo]||(k=r._req=null,Qn(r,T))}),k.on("response",T=>{let H=T.headers.location,ie=T.statusCode;if(H&&c.followRedirects&&ie>=300&&ie<400){if(++r._redirects>c.maxRedirects){de(r,k,"Maximum redirects exceeded");return}k.abort();let te;try{te=new $r(H,e)}catch{let ce=new SyntaxError(`Invalid URL: ${H}`);Qn(r,ce);return}Mo(r,te,i,a)}else r.emit("unexpected-response",k,T)||de(r,k,`Unexpected server response: ${T.statusCode}`)}),k.on("upgrade",(T,H,ie)=>{if(r.emit("upgrade",T),r.readyState!==j.CONNECTING)return;k=r._req=null;let te=T.headers.upgrade;if(te===void 0||te.toLowerCase()!=="websocket"){de(r,H,"Invalid Upgrade header");return}let ye=hu("sha1").update(v+_u).digest("base64");if(T.headers["sec-websocket-accept"]!==ye){de(r,H,"Invalid Sec-WebSocket-Accept header");return}let ce=T.headers["sec-websocket-protocol"],P;if(ce!==void 0?E.size?E.has(ce)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":E.size&&(P="Server sent no subprotocol"),P){de(r,H,P);return}ce&&(r._protocol=ce);let G=T.headers["sec-websocket-extensions"];if(G!==void 0){if(!D){de(r,H,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let V;try{V=Cu(G)}catch{de(r,H,"Invalid Sec-WebSocket-Extensions header");return}let ne=Object.keys(V);if(ne.length!==1||ne[0]!==Ve.extensionName){de(r,H,"Server indicated an extension that was not requested");return}try{D.accept(V[Ve.extensionName])}catch{de(r,H,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Ve.extensionName]=D}r.setSocket(H,ie,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(k,r):k.end()}function Qn(r,e){r._readyState=j.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Du(r){return r.path=r.socketPath,Ro.connect(r)}function ku(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=Ro.isIP(r.host)?"":r.host),du.connect(r)}function de(r,e,i){r._readyState=j.CLOSING;let a=new Error(i);Error.captureStackTrace(a,de),e.setHeader?(e[Lo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qn,r,a)):(e.destroy(a),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function es(r,e,i){if(e){let a=mu(e)?e.size:Au(e).length;r._socket?r._sender._bufferedBytes+=a:r._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${r.readyState} (${qe[r.readyState]})`);process.nextTick(i,a)}}function Tu(r,e){let i=this[Z];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=r,i._socket[Z]!==void 0&&(i._socket.removeListener("data",Zn),process.nextTick(Oo,i._socket),r===1005?i.close():i.close(r,e))}function Iu(){let r=this[Z];r.isPaused||r._socket.resume()}function Ru(r){let e=this[Z];e._socket[Z]!==void 0&&(e._socket.removeListener("data",Zn),process.nextTick(Oo,e._socket),e.close(r[vu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Io(){this[Z].emitClose()}function Nu(r,e){this[Z].emit("message",r,e)}function Lu(r){let e=this[Z];e._autoPong&&e.pong(r,!this._isServer,No),e.emit("ping",r)}function Mu(r){this[Z].emit("pong",r)}function Oo(r){r.resume()}function Ou(r){let e=this[Z];e.readyState!==j.CLOSED&&(e.readyState===j.OPEN&&(e._readyState=j.CLOSING,Bo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Bo(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function zo(){let r=this[Z];if(this.removeListener("close",zo),this.removeListener("data",Zn),this.removeListener("end",qo),r._readyState=j.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",Io),r._receiver.on("finish",Io))}function Zn(r){this[Z]._receiver.write(r)||this.pause()}function qo(){let r=this[Z];r._readyState=j.CLOSING,r._receiver.end(),this.end()}function Fo(){let r=this[Z];this.removeListener("error",Fo),this.on("error",No),r&&(r._readyState=j.CLOSING,this.destroy())}});var jo=ae((lg,Ko)=>{"use strict";var dg=er(),{Duplex:Bu}=X("stream");function Ho(r){r.emit("close")}function zu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Go(r){this.removeListener("error",Go),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function qu(r,e){let i=!0,a=new Bu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(u,d){let g=!d&&a._readableState.objectMode?u.toString():u;a.push(g)||r.pause()}),r.once("error",function(u){a.destroyed||(i=!1,a.destroy(u))}),r.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(c,u){if(r.readyState===r.CLOSED){u(c),process.nextTick(Ho,a);return}let d=!1;r.once("error",function(m){d=!0,u(m)}),r.once("close",function(){d||u(c),process.nextTick(Ho,a)}),i&&r.terminate()},a._final=function(c){if(r.readyState===r.CONNECTING){r.once("open",function(){a._final(c)});return}r._socket!==null&&(r._socket._writableState.finished?(c(),a._readableState.endEmitted&&a.destroy()):(r._socket.once("finish",function(){c()}),r.close()))},a._read=function(){r.isPaused&&r.resume()},a._write=function(c,u,d){if(r.readyState===r.CONNECTING){r.once("open",function(){a._write(c,u,d)});return}r.send(c,d)},a.on("end",zu),a.on("error",Go),a}Ko.exports=qu});var ts=ae((hg,Wo)=>{"use strict";var{tokenChars:Fu}=bt();function Uu(r){let e=new Set,i=-1,a=-1,c=0;for(c;c<r.length;c++){let d=r.charCodeAt(c);if(a===-1&&Fu[d]===1)i===-1&&(i=c);else if(c!==0&&(d===32||d===9))a===-1&&i!==-1&&(a=c);else if(d===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);let g=r.slice(i,a);if(e.has(g))throw new SyntaxError(`The "${g}" subprotocol is duplicated`);e.add(g),i=a=-1}else throw new SyntaxError(`Unexpected character at index ${c}`)}if(i===-1||a!==-1)throw new SyntaxError("Unexpected end of input");let u=r.slice(i,c);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return e.add(u),e}Wo.exports={parse:Uu}});var Zo=ae((pg,Qo)=>{"use strict";var Hu=X("events"),tr=X("http"),{Duplex:gg}=X("stream"),{createHash:Gu}=X("crypto"),Jo=Xn(),st=vt(),Ku=ts(),ju=er(),{CLOSE_TIMEOUT:Wu,GUID:Ju,kWebSocket:Vu}=Oe(),Yu=/^[+/0-9A-Za-z]{22}==$/,Vo=0,Yo=1,$o=2,ns=class extends Hu{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Wu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:ju,...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=tr.createServer((a,c)=>{let u=tr.STATUS_CODES[426];c.writeHead(426,{"Content-Length":u.length,"Content-Type":"text/plain"}),c.end(u)}),this._server.listen(e.port,e.host,e.backlog,i)):e.server&&(this._server=e.server),this._server){let a=this.emit.bind(this,"connection");this._removeListeners=Xu(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(c,u,d)=>{this.handleUpgrade(c,u,d,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Vo}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===$o){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xt,this);return}if(e&&this.once("close",e),this._state!==Yo)if(this._state=Yo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Xt,this):process.nextTick(Xt,this);else{let i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{Xt(this)})}}shouldHandle(e){if(this.options.path){let i=e.url.indexOf("?");if((i!==-1?e.url.slice(0,i):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,i,a,c){i.on("error",Xo);let u=e.headers["sec-websocket-key"],d=e.headers.upgrade,g=+e.headers["sec-websocket-version"];if(e.method!=="GET"){it(this,e,i,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){it(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!Yu.test(u)){it(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(g!==13&&g!==8){it(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){$t(i,400);return}let m=e.headers["sec-websocket-protocol"],w=new Set;if(m!==void 0)try{w=Ku.parse(m)}catch{it(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&v!==void 0){let E=new st({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let D=Jo.parse(v);D[st.extensionName]&&(E.accept(D[st.extensionName]),y[st.extensionName]=E)}catch{it(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let E={origin:e.headers[`${g===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(E,(D,k,T,H)=>{if(!D)return $t(i,k||401,T,H);this.completeUpgrade(y,u,w,e,i,a,c)});return}if(!this.options.verifyClient(E))return $t(i,401)}this.completeUpgrade(y,u,w,e,i,a,c)}completeUpgrade(e,i,a,c,u,d,g){if(!u.readable||!u.writable)return u.destroy();if(u[Vu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Vo)return $t(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gu("sha1").update(i+Ju).digest("base64")}`],v=new this.options.WebSocket(null,void 0,this.options);if(a.size){let y=this.options.handleProtocols?this.options.handleProtocols(a,c):a.values().next().value;y&&(w.push(`Sec-WebSocket-Protocol: ${y}`),v._protocol=y)}if(e[st.extensionName]){let y=e[st.extensionName].params,E=Jo.format({[st.extensionName]:[y]});w.push(`Sec-WebSocket-Extensions: ${E}`),v._extensions=e}this.emit("headers",w,c),u.write(w.concat(`\r
12
12
  `).join(`\r
13
- `)),i.removeListener("error",Po),l.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(vt,this)})),a(l,s)}};Co.exports=Ur;function Pu(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function vt(n){n._state=Ao,n.emit("close")}function Po(){this.destroy()}function kt(n,e,t,r){t=t||Sn.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Sn.STATUS_CODES[e]}\r
14
- `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
13
+ `)),u.removeListener("error",Xo),v.setSocket(u,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(v),v.on("close",()=>{this.clients.delete(v),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xt,this)})),g(v,c)}};Qo.exports=ns;function Xu(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 Xt(r){r._state=$o,r.emit("close")}function Xo(){this.destroy()}function $t(r,e,i,a){i=i||tr.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} ${tr.STATUS_CODES[e]}\r
14
+ `+Object.keys(a).map(c=>`${c}: ${a[c]}`).join(`\r
15
15
  `)+`\r
16
16
  \r
17
- `+t)}function Oe(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Oe),n.emit("wsClientError",o,t,e)}else kt(t,r,s,i)}});import{spawn as Qu}from"node:child_process";import{existsSync as Ku,openSync as Xu}from"node:fs";import{mkdir as Yu}from"node:fs/promises";import{dirname as Zu}from"node:path";import{fileURLToPath as ef}from"node:url";function qr(n=T()){return Ku(n.libEntry)?n.libEntry:ef(new URL("../index.ts",import.meta.url))}async function Ho(n={}){let e=n.paths??T(),t=n.entryOverride??qr(e);await Yu(Zu(e.logFile),{recursive:!0});let r=Xu(e.logFile,"a"),i=t.endsWith(".ts")?["--import","tsx/esm",t,"--daemon"]:[t,"--daemon"],o=Qu(process.execPath,i,{detached:!0,stdio:["ignore",r,r],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return tf.info("daemon spawned",{pid:o.pid,entry:t}),{pid:o.pid,entry:t}}var tf,Gr=Q(()=>{"use strict";k();U();tf=w("spawn-daemon")});import{spawn as lf}from"node:child_process";import{mkdir as uf,unlink as ff,writeFile as hf}from"node:fs/promises";import{dirname as gf,join as pf}from"node:path";function Tn(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Qo(n,e){return new Promise((t,r)=>{let s=lf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var In,jr,Jr,Ko=Q(()=>{"use strict";k();In=w("supervisor.launchd"),jr="ai.coze.bridge",Jr={platform:"darwin",renderConfig(n){return`<?xml version="1.0" encoding="UTF-8"?>
17
+ `+i)}function it(r,e,i,a,c,u){if(r.listenerCount("wsClientError")){let d=new Error(c);Error.captureStackTrace(d,it),r.emit("wsClientError",d,i,e)}else $t(i,a,c,u)}});import{spawn as _f}from"node:child_process";import{existsSync as yf,openSync as vf}from"node:fs";import{mkdir as bf}from"node:fs/promises";import{dirname as Sf}from"node:path";import{fileURLToPath as Ef}from"node:url";function is(r=W()){return yf(r.libEntry)?r.libEntry:Ef(new URL("../index.ts",import.meta.url))}async function ha(r={}){let e=r.paths??W(),i=r.entryOverride??is(e);await bf(Sf(e.logFile),{recursive:!0});let a=vf(e.logFile,"a"),u=i.endsWith(".ts")?["--import","tsx/esm",i,"--daemon"]:[i,"--daemon"],d=_f(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 Cf.info("daemon spawned",{pid:d.pid,entry:i}),{pid:d.pid,entry:i}}var Cf,os=Ie(()=>{"use strict";K();ue();Cf=R("spawn-daemon")});import{spawn as Nf}from"node:child_process";import{mkdir as Lf,unlink as Mf,writeFile as Of}from"node:fs/promises";import{dirname as Bf,join as zf}from"node:path";function ar(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function _a(r,e){return new Promise((i,a)=>{let c=Nf(r,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var or,xs,us,ya=Ie(()=>{"use strict";K();or=R("supervisor.launchd"),xs="ai.coze.bridge",us={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>${jr}</string>
22
+ <string>${xs}</string>
23
23
  <key>ProgramArguments</key>
24
24
  <array>
25
- <string>${Tn(n.nodeBin)}</string>
26
- <string>${Tn(n.entry)}</string>
25
+ <string>${ar(r.nodeBin)}</string>
26
+ <string>${ar(r.entry)}</string>
27
27
  <string>--daemon</string>
28
28
  </array>
29
29
  <key>RunAtLoad</key>
@@ -33,65 +33,67 @@ var sa=Object.create;var Dn=Object.defineProperty;var ia=Object.getOwnPropertyDe
33
33
  <key>ThrottleInterval</key>
34
34
  <integer>10</integer>
35
35
  <key>StandardOutPath</key>
36
- <string>${Tn(n.logFile)}</string>
36
+ <string>${ar(r.logFile)}</string>
37
37
  <key>StandardErrorPath</key>
38
- <string>${Tn(n.logFile)}</string>
38
+ <string>${ar(r.logFile)}</string>
39
39
  </dict>
40
40
  </plist>
41
- `},configPath(n){return pf(n.homeDir,"Library","LaunchAgents",`${jr}.plist`)},async install(n){let e=this.configPath(n);await uf(gf(e),{recursive:!0}),await hf(e,this.renderConfig(n),"utf8"),In.info("plist written",{plistPath:e}),await Qo("launchctl",["load","-w",e]),In.info("launchd job loaded",{label:jr})},async uninstall(n){let e=this.configPath(n);await Qo("launchctl",["unload","-w",e]).catch(t=>In.warn("launchctl unload failed (ignored)",{err:String(t)})),await ff(e).catch(t=>{if(t.code!=="ENOENT")throw t}),In.info("launchd job removed",{plistPath:e})}}});import{spawn as mf}from"node:child_process";import{mkdir as _f,unlink as wf,writeFile as yf}from"node:fs/promises";import{dirname as Sf,join as Ef}from"node:path";function An(n,e){return new Promise((t,r)=>{let s=mf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Rn,Pn,Vr,Xo=Q(()=>{"use strict";k();Rn=w("supervisor.systemd"),Pn="coze-bridge.service",Vr={platform:"linux",renderConfig(n){return`[Unit]
41
+ `},configPath(r){return zf(r.homeDir,"Library","LaunchAgents",`${xs}.plist`)},async install(r){let e=this.configPath(r);await Lf(Bf(e),{recursive:!0}),await Of(e,this.renderConfig(r),"utf8"),or.info("plist written",{plistPath:e}),await _a("launchctl",["load","-w",e]),or.info("launchd job loaded",{label:xs})},async uninstall(r){let e=this.configPath(r);await _a("launchctl",["unload","-w",e]).catch(i=>or.warn("launchctl unload failed (ignored)",{err:String(i)})),await Mf(e).catch(i=>{if(i.code!=="ENOENT")throw i}),or.info("launchd job removed",{plistPath:e})}}});import{spawn as qf}from"node:child_process";import{mkdir as Ff,unlink as Uf,writeFile as Hf}from"node:fs/promises";import{dirname as Gf,join as Kf}from"node:path";function ur(r,e){return new Promise((i,a)=>{let c=qf(r,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var cr,xr,fs,va=Ie(()=>{"use strict";K();cr=R("supervisor.systemd"),xr="coze-bridge.service",fs={platform:"linux",renderConfig(r){return`[Unit]
42
42
  Description=Coze Bridge daemon
43
43
  After=network.target
44
44
 
45
45
  [Service]
46
46
  Type=simple
47
- ExecStart=${n.nodeBin} ${n.entry} --daemon
47
+ ExecStart=${r.nodeBin} ${r.entry} --daemon
48
48
  Restart=always
49
49
  RestartSec=3
50
- StandardOutput=append:${n.logFile}
51
- StandardError=append:${n.logFile}
50
+ StandardOutput=append:${r.logFile}
51
+ StandardError=append:${r.logFile}
52
52
 
53
53
  [Install]
54
54
  WantedBy=default.target
55
- `},configPath(n){return Ef(n.homeDir,".config","systemd","user",Pn)},async install(n){let e=this.configPath(n);await _f(Sf(e),{recursive:!0}),await yf(e,this.renderConfig(n),"utf8"),Rn.info("systemd unit written",{unitPath:e}),await An("systemctl",["--user","daemon-reload"]),await An("systemctl",["--user","enable","--now",Pn]),Rn.info("systemd unit enabled",{unitName:Pn})},async uninstall(n){let e=this.configPath(n);await An("systemctl",["--user","disable","--now",Pn]).catch(t=>Rn.warn("systemctl disable failed (ignored)",{err:String(t)})),await wf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),await An("systemctl",["--user","daemon-reload"]).catch(()=>{}),Rn.info("systemd unit removed",{unitPath:e})}}});import{spawn as vf}from"node:child_process";import{join as kf}from"node:path";function Yo(n,e){return new Promise((t,r)=>{let s=vf(n,e,{stdio:["ignore","pipe","pipe"],shell:!1}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Qr,Cn,Kr,Zo=Q(()=>{"use strict";k();Qr=w("supervisor.taskscheduler"),Cn="CozeBridge",Kr={platform:"win32",renderConfig(n){return`<?xml version="1.0" encoding="UTF-16"?>
55
+ `},configPath(r){return Kf(r.homeDir,".config","systemd","user",xr)},async install(r){let e=this.configPath(r);await Ff(Gf(e),{recursive:!0}),await Hf(e,this.renderConfig(r),"utf8"),cr.info("systemd unit written",{unitPath:e}),await ur("systemctl",["--user","daemon-reload"]),await ur("systemctl",["--user","enable","--now",xr]),cr.info("systemd unit enabled",{unitName:xr})},async uninstall(r){let e=this.configPath(r);await ur("systemctl",["--user","disable","--now",xr]).catch(i=>cr.warn("systemctl disable failed (ignored)",{err:String(i)})),await Uf(e).catch(i=>{if(i.code!=="ENOENT")throw i}),await ur("systemctl",["--user","daemon-reload"]).catch(()=>{}),cr.info("systemd unit removed",{unitPath:e})}}});import{spawn as jf}from"node:child_process";import{join as Wf}from"node:path";function ba(r,e){return new Promise((i,a)=>{let c=jf(r,e,{stdio:["ignore","pipe","pipe"],shell:!1}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${r} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var ds,fr,ls,Sa=Ie(()=>{"use strict";K();ds=R("supervisor.taskscheduler"),fr="CozeBridge",ls={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>
59
59
  </RegistrationInfo>
60
60
  <Triggers>
61
61
  <LogonTrigger>
62
- <UserId>${n.userName}</UserId>
62
+ <UserId>${r.userName}</UserId>
63
63
  </LogonTrigger>
64
64
  </Triggers>
65
65
  <Principals>
66
66
  <Principal>
67
- <UserId>${n.userName}</UserId>
67
+ <UserId>${r.userName}</UserId>
68
68
  <LogonType>InteractiveToken</LogonType>
69
69
  <RunLevel>LeastPrivilege</RunLevel>
70
70
  </Principal>
71
71
  </Principals>
72
72
  <Actions>
73
73
  <Exec>
74
- <Command>${n.nodeBin}</Command>
75
- <Arguments>"${n.entry}" --daemon</Arguments>
74
+ <Command>${r.nodeBin}</Command>
75
+ <Arguments>"${r.entry}" --daemon</Arguments>
76
76
  </Exec>
77
77
  </Actions>
78
78
  </Task>
79
- `},configPath(n){return kf(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await Yo("schtasks",["/Create","/SC","ONLOGON","/TN",Cn,"/TR",e,"/RU",n.userName,"/F"]),Qr.info("task scheduler entry created",{task:Cn})},async uninstall(n){await Yo("schtasks",["/Delete","/TN",Cn,"/F"]).catch(e=>Qr.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Qr.info("task scheduler entry removed",{task:Cn})}}});var Xr={};Ln(Xr,{buildContext:()=>Rf,getSupervisor:()=>Tf,launchdSupervisor:()=>Jr,systemdSupervisor:()=>Vr,taskSchedulerSupervisor:()=>Kr});import{homedir as xf,userInfo as If}from"node:os";function Tf(n=process.platform){switch(n){case"darwin":return Jr;case"linux":return Vr;case"win32":return Kr;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function Rf(){let n=T();return{nodeBin:process.execPath,entry:qr(n),logFile:n.logFile,homeDir:xf(),userName:If().username}}var Yr=Q(()=>{"use strict";U();Gr();Ko();Xo();Zo()});fe();k();import{readdir as Ia}from"node:fs/promises";import{mkdir as Sa,writeFile as Ea}from"node:fs/promises";import{join as va}from"node:path";var ka={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Le(n,e,t,r){await Sa(n,{recursive:!0});let s=ka[e],i=va(n,s),o=xa(e,t,r);return await Ea(i,o,"utf8"),i}function xa(n,e,t){let r=`# Coze Agent: ${e}
79
+ `},configPath(r){return Wf(r.homeDir,".coze","bridge","task.xml")},async install(r){let e=`"${r.nodeBin}" "${r.entry}" --daemon`;await ba("schtasks",["/Create","/SC","ONLOGON","/TN",fr,"/TR",e,"/RU",r.userName,"/F"]),ds.info("task scheduler entry created",{task:fr})},async uninstall(r){await ba("schtasks",["/Delete","/TN",fr,"/F"]).catch(e=>ds.warn("schtasks /Delete failed (ignored)",{err:String(e)})),ds.info("task scheduler entry removed",{task:fr})}}});var hs={};zs(hs,{buildContext:()=>Xf,getSupervisor:()=>Yf,launchdSupervisor:()=>us,systemdSupervisor:()=>fs,taskSchedulerSupervisor:()=>ls});import{homedir as Jf,userInfo as Vf}from"node:os";function Yf(r=process.platform){switch(r){case"darwin":return us;case"linux":return fs;case"win32":return ls;default:throw new Error(`unsupported platform for OS supervisor: ${r}`)}}function Xf(){let r=W();return{nodeBin:process.execPath,entry:is(r),logFile:r.logFile,homeDir:Jf(),userName:Vf().username}}var gs=Ie(()=>{"use strict";ue();os();ya();va();Sa()});Ge();K();import{readdir as B0}from"node:fs/promises";import{mkdir as R0,writeFile as N0}from"node:fs/promises";import{join as L0}from"node:path";var M0={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function dt(r,e,i,a){await R0(r,{recursive:!0});let c=M0[e],u=L0(r,c),d=O0(e,i,a);return await N0(u,d,"utf8"),u}function O0(r,e,i){let a=`# Coze Agent: ${e}
80
80
 
81
- > framework: \`${n}\`
81
+ > framework: \`${r}\`
82
82
 
83
- `,s=t?.trim()?t.endsWith(`
84
- `)?t:`${t}
83
+ `,c=i?.trim()?i.endsWith(`
84
+ `)?i:`${i}
85
85
  `:`_No instructions provided._
86
- `;return`${r}---
86
+ `;return`${a}---
87
87
 
88
- ${s}`}var Z=w("agent-detail-sync"),Nt=class{constructor(e){this.opts=e}opts;async syncAll(e){let t=this.opts.paths.agentsRoot,r;try{r=await Ia(t)}catch(s){Z.info("agents dir not found, skip detail sync",{root:t,err:String(s)});return}Z.info("starting detail sync",{reason:e,count:r.length});for(let s of r)try{await this.syncOne(s)}catch(i){Z.warn("detail sync failed for agent, skipping",{agentId:s,err:String(i)})}Z.info("detail sync done",{reason:e})}async syncOne(e){let t=await $(e,this.opts.paths);if(!t){Z.info("detail sync: agent config missing, skip",{agentId:e});return}let r;try{r=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(o){Z.warn("detail RPC failed, using local data",{agentId:e,err:String(o)});return}if(r.agentId&&r.agentId!==e){Z.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:r.agentId});return}let s=!1,i=!1;if(r.agentName&&r.agentName!==t.agentName&&(t.agentName=r.agentName,s=!0),r.description!==void 0&&r.description!==t.description&&(t.description=r.description,s=!0),r.cozeIdentity&&r.cozeIdentity!==t.cozeIdentity&&(t.cozeIdentity=r.cozeIdentity,s=!0,i=!0),r.deployType&&Z.info("detail.deployType",{agentId:e,deployType:r.deployType}),!s){Z.debug("detail sync: no diff",{agentId:e});return}await K(t,this.opts.paths),Z.info("detail sync: config updated",{agentId:e,identityChanged:i,agentName:t.agentName}),i&&(await Le(t.workspace,t.framework,e,t.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};fe();import{spawn as Ts}from"node:child_process";import{lstat as zn,mkdir as Aa,readFile as Rs,readdir as Ca,rm as Oa,stat as Na,writeFile as ba}from"node:fs/promises";import{join as oe,normalize as Da,relative as Ps,resolve as La,sep as As}from"node:path";var ee={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",DELETE:"_agent/delete"};function nt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function ds(n){let{_meta:e,...t}=n;return{stripped:t,meta:e}}function Me(n){if(!n?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return n.cozeAgentId}var h=class extends Error{code;retriable;cause;constructor(e,t,r){super(t),this.name="BridgeError",this.code=e,this.retriable=r?.retriable??!1,r?.cause!==void 0&&(this.cause=r.cause)}};k();U();function ie(n,e){if(nt(n)!=="cloud")throw new h("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function rt(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}k();var bt="1008033",ls="1289";var us="pbbp2",fs="https://www.coze.cn",hs="/api/coze_claw/resource/get_frontier_key",Ta="https://www.coze.cn",Ra="wss://frontier.coze.cn";function gs(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??Ta}function ps(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??Ra}function Dt(n){let e={},t=n?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,r=n?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return t&&(e["x-tt-env"]=t),r&&(e["x-use-ppe"]=r),e}function Lt(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var ms=w("handshake");async function _s(n){let e=gs(n.endpoint),t=n.timeoutMs??1e4,r=`${Pa(e)}${hs}?aid=${encodeURIComponent(bt)}`,s={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...Dt(n.ppeOverride)},i=new AbortController,o=setTimeout(()=>i.abort(),t);ms.info("frontier key handshake",{base:e});try{let a=await fetch(r,{method:"GET",headers:s,signal:i.signal}),c=a.headers.get("x-tt-logid")??"",d=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let g=await a.text().catch(()=>"");throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${g.slice(0,200)}`)}let l=await a.json();if(l.code!==void 0&&l.code!==0)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${l.code} msg=${l.msg??"-"} logid=${c}`);let u=l.data?.access_key,f=l.data?.device_id;if(!u||!f)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${c}: ${JSON.stringify(l)}`);return ms.info("handshake ok",{remoteDeviceId:f,logid:c,traceId:d}),{accessKey:u,deviceId:f}}catch(a){throw a instanceof h?a:a.name==="AbortError"?new h("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${t}ms)`):new h("UPSTREAM_HANDSHAKE_FAILED",String(a),{cause:a})}finally{clearTimeout(o)}}function Pa(n){return n.endsWith("/")?n.slice(0,-1):n}var Fn="https://llm-gateway.coze.cn",he="auto";function ws(n){return{model:n.model??he,...n.modelToken?{modelToken:n.modelToken}:{}}}function st(n){return!n||n===he}function ys(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=Fn,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||he):st(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function Ss(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||he}"`):st(n.model)||e.push("-c",`model="${n.model}"`),n.modelToken&&(e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Fn}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"')),e}function Es(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function Un(n){let{ttEnv:e,usePpe:t}=Lt(n),r={};return e&&(r["x-tt-env"]=e),t&&(r["x-use-ppe"]=t),r}function vs(n,e){if(!n.modelToken)return{};let t=Un(e);return Object.keys(t).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(t).map(([s,i])=>`${s}:${i}`).join(`
89
- `)}}function $n(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ks(n,e){if(!n.modelToken||st(n.model))return null;let t=Un(e),r={baseUrl:`${Fn}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:n.model,name:n.model,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(t).length>0&&(r.headers=t),r}function xs(n,e){if(!n.modelToken)return[];let t=Un(e),r=[];for(let[s,i]of Object.entries(t))r.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return r}var b=w("agent-handlers"),Is=5*1024*1024,Ma=1,Ba=6,Fa=new Set(["node_modules",".git",".coze","dist","build",".next"]),Bt=class{constructor(e){this.opts=e}opts;async listSkills(e){ie(e._meta,"_agent/listSkills");let t=Me(e._meta),r=await this.loadAgentCfg(t),s=r?.workspace??se(t).workspace,i=r?.skills??[],o=[];for(let a of i){let c=oe(s,a.relPath,"SKILL.md");await Na(c).then(l=>l.isFile()).catch(()=>!1)&&o.push({skillId:a.skillId,skillName:a.skillName,downloadUrl:a.downloadUrl??"",...a.description?{description:a.description}:{},...a.version?{version:a.version}:{}})}return{skills:o}}async addSkills(e){ie(e._meta,"_agent/addSkills");let t=Me(e._meta),r=await this.requireAgentCfg(t),s=e.skills??[],i=[...r.skills??[]],o=new Map(i.map((c,d)=>[c.skillId,d])),a=[];for(let c of s){if(!c.skillName)throw new h("IPC_BAD_REQUEST","skill missing skillName");let d=Ua(c.skillName),l=$a(r.framework),u=oe(l,d),f=oe(r.workspace,u);await Aa(f,{recursive:!0});let g=await Ga(c.downloadUrl);Wa(g)?await ja(g,f):await ba(oe(f,"SKILL.md"),g.toString("utf8"),"utf8");let m={skillId:c.skillId,skillName:c.skillName,relPath:u,installedAt:Date.now(),...c.description?{description:c.description}:{},...c.version?{version:c.version}:{},...c.downloadUrl?{downloadUrl:c.downloadUrl}:{}},_=o.get(c.skillId);_!==void 0?i[_]=m:(o.set(c.skillId,i.length),i.push(m)),a.push(c),b.info("skill installed",{agentId:t,skillId:c.skillId,skillName:c.skillName,relPath:u})}return await Ct(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){ie(e._meta,"_agent/removeSkills");let t=Me(e._meta),r=await this.requireAgentCfg(t),s=new Set(e.skillIds??[]),i=r.skills??[],o=[];for(let a of i){if(!s.has(a.skillId)){o.push(a);continue}let c=oe(r.workspace,a.relPath);await Oa(c,{recursive:!0,force:!0}),b.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await Ct(t,o),await this.reloadAgentSessions(t,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,t){return this.reloadAgentSessions(e,t)}async reloadAgentSessions(e,t){let r=this.opts.agents.get(e);if(r&&r.framework!=="codex"){for(let[s,i]of r.sessions)if(!(!i.downstream||!i.acpSessionId)){i.loadingSession=!0;try{await i.downstream.sessionLoad({sessionId:i.acpSessionId,cwd:r.workspace}),b.info("session reloaded",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){b.warn("session reload failed",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId,err:String(o)})}finally{i.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return b.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,r=await $(t);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return r.cozeIdentity===e.cozeIdentity?(b.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(r.cozeIdentity=e.cozeIdentity,await K(r),await Le(r.workspace,r.framework,t,e.cozeIdentity),b.info("_agent/update: cozeIdentity rewritten",{agentId:t,framework:r.framework}),await this.reloadAgentSessions(t,"identity-changed"),{ok:!0})}async disconnectAgent(e){let t=e.agentId;if(!t)throw new h("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let r=await $(t);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await K(r),b.info("agent disconnected",{agentId:t,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(t,e.reason??"disconnect"),{ok:!0}):(b.warn("_agent/disconnect: agent not found, ignoring",{agentId:t}),{ok:!0})}async switchModel(e){if(ie(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:he,r=await $(e.agentId);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=t,await K(r),b.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return b.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};s.model=t;let i=[];for(let[o,a]of s.allSessionQueues())i.push(a.enqueue(async()=>{let c=s.sessions.get(o);c?.downstream&&(await c.downstream.stop(`switchModel: ${t}`).catch(()=>{}),c.downstream=void 0)}));return await Promise.all(i),b.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:t,cloudSessions:i.length}),{ok:!0}}async resetAgent(e){if(ie(e._meta,ee.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${ee.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,ee.RESET,e.reason),{ok:!0}}async repairAgent(e){if(ie(e._meta,ee.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${ee.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${ee.REPAIR} only allowed for openclaw, got ${t.framework}`);if(t&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,t.workspace)}catch(r){b.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,ee.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,r){if(!this.opts.detailSyncer){b.warn("detailSyncer not wired, skipping sync",{method:t,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){b.warn("detail sync failed (ignored)",{method:t,agentId:e,reason:r,err:String(s)})}}async getFileTree(e){ie(e._meta,"_agent/getFileTree");let t=e._meta,r=Me(t),s=await this.resolveWorkspace(r),i=e.filePath??"",o=this.safeJoin(s,i),a=await zn(o).catch(()=>null);if(!a)throw new h("IPC_BAD_REQUEST",`path not found: ${i}`);if(a.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${i}`);let c=Va(e.depth);return a.isDirectory()?{tree:await Cs(s,o,i,c)}:{tree:[{name:Qa(i),path:Os(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){ie(e._meta,"_agent/getFileContent");let t=Me(e._meta),r=await this.resolveWorkspace(t);if(!e.filePath)throw new h("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(r,e.filePath),i=await zn(s).catch(()=>null);if(!i||!i.isFile())throw new h("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(i.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(i.size>Is)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${Is})`);let o=await Rs(s);return o.includes(0)?{content:o.toString("base64"),encoding:"base64",size:i.size}:{content:o.toString("utf8"),encoding:"utf-8",size:i.size}}async resolveWorkspace(e){let t=this.opts.agents.get(e);return t?t.workspace:(await $(e).catch(()=>null))?.workspace??se(e).workspace}safeJoin(e,t){let r=La(e,t||"."),s=Ps(e,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${As}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}loadAgentCfg(e){return $(e)}async requireAgentCfg(e){let t=await this.loadAgentCfg(e);if(!t)throw new h("AGENT_NOT_FOUND",`no config for agent: ${e}`);return t}};function Ua(n){let e=rt(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function $a(n){return n==="claude-code"?oe(".claude","skills"):oe(".agents","skills")}var za=3e4,qa=50*1024*1024,Ft=3e4;async function Ga(n){if(!n)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);Mt(e);let t=Ha(n);return Mt(t.length),t}if(n.startsWith("file:")){let e=new URL(n).pathname,t=await Rs(e);return Mt(t.length),t}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),za);try{let r=await fetch(n,{signal:e.signal});if(!r.ok)throw new h("IPC_BAD_REQUEST",`fetch skill failed HTTP ${r.status} ${n}`);let s=await r.arrayBuffer();return Mt(s.byteLength),Buffer.from(s)}finally{clearTimeout(t)}}throw new h("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function Mt(n){if(n>qa)throw new h("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function Ha(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new h("IPC_BAD_REQUEST","bad data URL");let t=!!e[2],r=e[3]??"";return t?Buffer.from(r,"base64"):Buffer.from(decodeURIComponent(r),"utf8")}function Wa(n){return n.length>=2&&n[0]===31&&n[1]===139}async function ja(n,e){await Ja(n),await new Promise((t,r)=>{let s=Ts("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),i="";s.stderr?.on("data",a=>{i+=String(a)});let o=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar extract timeout (${Ft}ms)`))},Ft);s.on("error",a=>{clearTimeout(o),r(new h("IPC_BAD_REQUEST",`tar spawn failed: ${a.message}`,{cause:a}))}),s.on("exit",a=>{clearTimeout(o),a===0?t():r(new h("IPC_BAD_REQUEST",`tar exit ${a}${i?`: ${i.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)})}async function Ja(n){let e=await new Promise((t,r)=>{let s=Ts("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),i="",o="";s.stdout?.on("data",c=>{i+=String(c)}),s.stderr?.on("data",c=>{o+=String(c)});let a=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar list timeout (${Ft}ms)`))},Ft);s.on("error",c=>{clearTimeout(a),r(new h("IPC_BAD_REQUEST",`tar list spawn failed: ${c.message}`))}),s.on("exit",c=>{clearTimeout(a),c===0?t(i):r(new h("IPC_BAD_REQUEST",`tar list exit ${c}${o?`: ${o.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)});for(let t of e.split(`
90
- `)){let r=t.trim();if(!r)continue;let s=r.charCodeAt(0);if(s!==45&&s!==100)throw new h("IPC_BAD_REQUEST",`tar entry kind '${r[0]}' not allowed (symlink/hardlink/special): ${r.slice(0,100)}`);let o=(r.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!o)continue;if(o.startsWith("/"))throw new h("IPC_BAD_REQUEST",`tar entry absolute path: ${o}`);if(o.split(/[/\\]/).some(c=>c===".."))throw new h("IPC_BAD_REQUEST",`tar entry contains '..': ${o}`)}}async function Cs(n,e,t,r){if(r<=0)return[];let s;try{s=await Ca(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(Fa.has(o.name)||o.isSymbolicLink())continue;let a=oe(e,o.name),c=Da(oe(t,o.name)),d=null;try{d=await zn(a)}catch{continue}if(d.isSymbolicLink())continue;let l={name:o.name,path:Os(Ps(n,a)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&r>1&&(l.children=await Cs(n,a,c,r-1)),i.push(l)}return i.sort((o,a)=>o.isDir!==a.isDir?o.isDir?-1:1:o.name.localeCompare(a.name)),i}function Va(n){return!n||n<=0?Ma:Math.min(n,Ba)}function Qa(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function Os(n){return n.split(As).join("/")}k();import{readFileSync as Dh}from"node:fs";import{dirname as Mh,join as Bh}from"node:path";import{fileURLToPath as Uh}from"node:url";var Ut="0.1.25";var it=w("agent-health-reporter"),Ka=1e4,$t=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Ka}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),it.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),it.info("heartbeat stopped"))}async tick(){if(this.inFlight){it.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){it.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let t=[];for(let s of this.opts.core.agents.values()){let i=Xa(s);i&&t.push({agentId:s.agentId,status:i})}if(t.length===0)return;let r={agents:t,bridgeVersion:Ut,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",r)}catch(s){it.warn("heartbeat batch send failed",{count:t.length,err:String(s)})}}finally{this.inFlight=!1}}};function Xa(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}fe();import{mkdir as Gn,rm as Ic}from"node:fs/promises";k();import{execFile as Ya}from"node:child_process";import{promisify as Za}from"node:util";var bs=Za(Ya),ot=w("agents.acp-installer"),ec={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},tc=5e4,nc=5e3,rc=5*6e4,qt=new Map,zt=new Map,qn=new Map;async function Ns(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:t}=await bs(e,[n],{timeout:nc});return t.split(`
91
- `)[0]?.trim()||void 0}catch{return}}async function sc(n){ot.info("npm install -g start",{npmPackage:n}),await bs("npm",["install","-g",`${n}@latest`],{timeout:tc,maxBuffer:10*1024*1024}),ot.info("npm install -g done",{npmPackage:n})}async function Ds(n){let e=ec[n];if(!e)return;let t=qt.get(n);if(t)return t;let r=zt.get(n);if(r&&Date.now()-r<rc)return;let s=qn.get(n);if(s)return s;let i=(async()=>{let o=await Ns(e.binary);if(o)return qt.set(n,o),ot.info("acp wrapper found on PATH",{binary:e.binary,path:o}),o;try{await sc(e.npmPackage)}catch(c){ot.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(c)}),zt.set(n,Date.now());return}let a=await Ns(e.binary);if(!a){ot.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),zt.set(n,Date.now());return}return qt.set(n,a),zt.delete(n),a})().finally(()=>{qn.delete(n)});return qn.set(n,i),i}function Gt(n){return qt.get(n)}import{spawn as dc}from"node:child_process";function at(n,e,t){return t===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:t}}function Ht(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function Be(n,e){return{jsonrpc:"2.0",id:n,result:e}}function Ee(n,e){return{jsonrpc:"2.0",id:n,error:e}}var Wt=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},R={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009};function Ls(n){return"method"in n&&"id"in n&&n.id!==void 0}function Ms(n){return"method"in n&&!("id"in n)}function jt(n){return!("method"in n)&&"id"in n}var ic={AGENT_NOT_FOUND:R.AGENT_NOT_FOUND,AGENT_BUSY:R.AGENT_BUSY,AGENT_DISCONNECTED:R.AGENT_DISCONNECTED,AGENT_TIMEOUT:R.AGENT_TIMEOUT,AGENT_SPAWN_FAILED:R.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:R.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:R.INTERNAL_ERROR,BRIDGE_INTERNAL:R.INTERNAL_ERROR,IPC_AUTH_FAILED:R.INTERNAL_ERROR,IPC_BAD_REQUEST:R.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:R.MODEL_TOKEN_GEN_FAILED,OPERATION_NOT_ALLOWED_FOR_LOCAL:R.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:R.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:R.INTERNAL_ERROR};function Jt(n){return n instanceof h?{code:ic[n.code]??R.INTERNAL_ERROR,message:n.message,data:{bridgeCode:n.code,retriable:n.retriable}}:{code:R.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)}}function Bs(n){let e=n.data,t=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new h(t,n.message,{retriable:e?.retriable??!1,cause:n.data})}function Fs(n){return`${JSON.stringify(n)}
92
- `}var Vt=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let t=this.buffer.split(`
93
- `);this.buffer=t.pop()??"";let r=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{r.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return r}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(t){return this.onError?.({line:e,error:t}),[]}}};var $s={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},eg=Object.fromEntries(Object.entries($s).map(([n,e])=>[e,n])),oc={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},Fe=class{seq=0;next(e,t){this.seq+=1;let r=$s[e]??ac(e),s=oc[r]??[],i=[r,String(this.seq)];if(s.length>0){let o=s.map(c=>Us(t?.[c]??"")),a=cc(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>Us(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function ac(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Us(n){return n.replace(/[:_\s]+/g,"-")}function cc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}k();var lc=3e4,uc=50,fc=20,zs=500;function hc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=zs?n:`${e.slice(0,zs)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function qs(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var ge=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Vt({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Fe;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new h("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",t=dc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=t,t.stdout?.setEncoding("utf8"),t.stdout?.on("data",r=>{for(let s of this.decoder.push(r))this.dispatch(s)}),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{let s=r.trimEnd();this.stderrRing.push(s),this.stderrRing.length>uc&&this.stderrRing.shift(),this.log.debug("stderr",{text:s})}),t.on("exit",(r,s)=>{this.stopped=!0,(r!==0||s!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:r,signal:s,recentStderr:this.stderrRing.slice(-fc)}),this.failAllPending(new h("AGENT_PROTOCOL_ERROR",`agent exited (${r}/${s})`));for(let o of this.exitHandlers)o(r,s)}),t.on("error",r=>{this.log.error("child error",{err:String(r)}),this.failAllPending(new h("AGENT_SPAWN_FAILED",String(r),{cause:r}))}),this.log.info("downstream started",{command:this.opts.command,pid:t.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let t=this.child,r=new Promise(i=>t.once("exit",()=>i()));qs(t.pid,"SIGTERM");let s=setTimeout(()=>{t.killed||qs(t.pid,"SIGKILL")},5e3);try{await r}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Ht("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Be(e,t))}catch(r){this.log.warn("respondAgentRequest write failed",{id:e,err:String(r)})}}respondAgentRequestError(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Ee(e,t))}catch(r){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(r)})}}onExit(e){this.exitHandlers.push(e)}call(e,t,r=lc){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=at(s,e,t),o=r>0&&Number.isFinite(r);return new Promise((a,c)=>{let d=o?setTimeout(()=>{this.pending.delete(s),c(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r):null;this.pending.set(s,{resolve:a,reject:c,timer:d,method:e});try{this.writeFrame(i)}catch(l){d&&clearTimeout(d),this.pending.delete(s),c(l)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new h("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Fs(e))}dispatch(e){if(jt(e)){let t=e.id!==null?this.pending.get(e.id):void 0;if(!t){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),t.timer&&clearTimeout(t.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:t.method,code:e.error.code,message:e.error.message,data:e.error.data}),t.reject(Bs(e.error))):(this.log.info("downstream returned result",{id:e.id,method:t.method,result:hc(e.result)}),t.resolve(e.result));return}if(Ms(e)){if(e.method==="session/update")for(let t of this.updateHandlers)Promise.resolve(t(e.params)).catch(r=>this.log.warn("update handler failed",{err:String(r)}));else this.log.debug("unknown notification",{method:e.method});return}if(Ls(e)){let t=e;this.handleAgentRequest(t).catch(r=>this.log.error("agent request handler failed",{method:t.method,err:String(r)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Ee(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let t of this.agentRequestHandlers)try{await t(e)}catch(r){this.log.error("agentRequestHandler threw",{method:e.method,err:String(r)});try{this.writeFrame(Ee(e.id,Jt(r)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var gc="@agentclientprotocol/claude-agent-acp@latest";function pc(n){let e={};for(let[t,r]of Object.entries(n))r!==void 0&&(t.startsWith("CLAUDE")||t==="AI_AGENT"||t==="BAGGAGE"||(e[t]=r));return e}var Qt=class extends ge{framework="claude-code";constructor(e){let t=Gt("claude-code"),[r,s]=t?[t,[]]:["npx",["-y",gc]],i=e.command??r,o=e.args??s,a={command:i,args:o,cwd:e.cwd,...e.env?{env:e.env}:{}};super(a)}sanitizeEnv(e){return pc(e)}};import{mkdtempSync as mc,rmSync as _c}from"node:fs";import{tmpdir as wc}from"node:os";import{join as yc}from"node:path";var Sc="@zed-industries/codex-acp@latest",Kt=class extends ge{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=Gt("codex"),[r,s]=t?[t,[]]:["npx",["-y",Sc]],i=e.command??r,o=e.args??s,a=e.extraArgs?[...o,...e.extraArgs]:o,c=e.isolateCodexHome?mc(yc(wc(),"coze-bridge-codex-home-")):void 0,d=c?{...e.env??{},CODEX_HOME:c}:e.env,l={command:i,args:a,cwd:e.cwd,...d?{env:d}:{}};super(l),this.authMethodId=e.authMethodId,this.codexHomeDir=c}async initialize(e){let t=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),t}async stop(e){if(await super.stop(e),this.codexHomeDir)try{_c(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var ct=class extends ge{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let t=e.sessionName??"default",r=["acp","--session",`agent:${e.agentId}:${t}`];e.gatewayToken&&r.push("--token",e.gatewayToken);let s={command:e.command,args:r,cwd:e.cwd,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=t,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};k();U();var Ue=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((t,r)=>{this.slots.push({task:e,resolve:t,reject:r}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}}finally{this.running=!1}}}};var Xt=class{agentId;framework;workspace;deployType;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local"}getSessionQueue(e){let t=this.sessionQueues.get(e);return t||(t=new Ue,this.sessionQueues.set(e,t)),t}allSessionQueues(){return this.sessionQueues.entries()}async dispose(e){this.status="stopped";let t=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let r of this.sessionQueues.values())r.dispose(t);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let t=[];for(let[,r]of this.sessions)dt(r),r.downstream&&(t.push(r.downstream.stop(e).catch(()=>{})),r.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function dt(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Ec}from"node:child_process";import{homedir as vc}from"node:os";import{join as kc}from"node:path";Tt();k();async function Ws(){let n=kc(vc(),".openclaw/openclaw.json");return(await De(n))?.gateway?.auth?.token??""}var Gs=w("openclaw.config"),xc=[0,5e3,5e3],Hs="models.providers.",Yt="agents.defaults.models",Zt=class{command;env;retryDelaysMs;queue=new Ue;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??xc}async withRetry(e,t){let r;for(let s=0;s<this.retryDelaysMs.length;s++){let i=this.retryDelaysMs[s]??0;i>0&&await new Promise(o=>setTimeout(o,i));try{return await t()}catch(o){r=o,Gs.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(o)})}}throw new h("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${r?.message??"unknown"}`)}runCli(e){return new Promise((t,r)=>{let s=Ec(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`exit ${o}: ${i.trim().slice(0,500)}`))})})}async runCliTolerant(e,t){try{await this.runCli(e)}catch(r){let s=String(r);if(t.some(i=>s.includes(i)))return;throw r}}async bestEffortUnset(e,t){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",t])))}catch(r){Gs.warn(`${e} failed (best-effort)`,{configPath:t,err:String(r)})}}ensureProvider(e,t){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Hs}${e}`,JSON.stringify(t),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Hs}${e}`)}addModelToAllowlist(e,t){let r={[e]:t?{alias:t}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Yt}[${e}]`,()=>this.runCli(["config","set",Yt,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Yt}[${e}]`,`${Yt}.${e}`)}ensureAgent(e,t,r){let s=["agents","add",e,"--workspace",t,"--non-interactive"];return r&&s.push("--model",r),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var pe=w("agent-manager"),Tc=(n,e,t,r,s,i,o)=>{switch(n){case"claude-code":{let a=s?{...ys(s),...vs(s,o)}:void 0;return new Qt({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...Ss(s),...xs(s,o)]:[],c=s?Es(s):void 0,d=!!s;return new Kt({cwd:t,...a.length>0?{extraArgs:a}:{},...c&&Object.keys(c).length>0?{env:c}:{},...d?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new ct({command:e,cwd:t,agentId:r,...i?{sessionName:rt(i)}:{}})}};function js(n){return n==="claude-code"||n==="codex"}var Rc={path:"",version:"cloud-deployed"},Pc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ac=6e4,en=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Tc,this.createTimeoutMs=e.createTimeoutMs??Ac}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new h("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new Zt({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new h("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new h("IPC_BAD_REQUEST","framework required");let t=nt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let r=this.registry.get(e.agentId);if(r){if(r.framework!==e.framework)throw new h("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${r.framework})`);if(r.status==="error")pe.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(f=>pe.warn("dispose stale agent failed (ignored)",{err:String(f)})),this.registry.unregister(e.agentId);else return pe.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:r.agentId,workspace:r.workspace,framework:r.framework}}if(!t&&!this.config.frameworksCache?.[e.framework])throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);t&&js(e.framework)&&await Ds(e.framework);let i=se(e.agentId,this.paths),o=e.workspace??i.workspace,a=nt(e._meta),c=new AbortController,d=setTimeout(()=>c.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),l,u=!1;try{let f=()=>{if(c.signal.aborted)throw c.signal.reason instanceof Error?c.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await Gn(i.root,{recursive:!0}),await Gn(o,{recursive:!0}),await Gn(i.logs,{recursive:!0}),f(),await Le(o,e.framework,e.agentId,e.cozeIdentity),f();let g=await $(e.agentId,this.paths).catch(()=>null),m=ws({model:e.model??g?.model});if(l=new Xt({agentId:e.agentId,framework:e.framework,workspace:o,model:m.model??he,deployType:a}),l.status="ok",g?.sessions){for(let[L,B]of Object.entries(g.sessions))l.sessions.set(L,{acpSessionId:B.acpSessionId,modelToken:B.modelToken,tokenGeneratedAt:B.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let E=Object.keys(g.sessions).length;E>0&&pe.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:E})}this.registry.register(l),u=!0;let _={agentId:e.agentId,framework:e.framework,workspace:o,cozeIdentity:e.cozeIdentity,createdAt:g?.createdAt??Date.now(),sessions:g?.sessions??{},model:m.model};return a==="cloud"&&(_.deployType="cloud"),g?.skills&&(_.skills=g.skills),g?.agentName&&(_.agentName=g.agentName),g?.description&&(_.description=g.description),await K(_,this.paths),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,o):pe.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId})),pe.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:a}),{ok:!0,agentId:e.agentId,workspace:o,framework:e.framework}}catch(f){throw pe.error("agent create failed, rolling back",{agentId:e.agentId,err:String(f)}),u&&l&&(await l.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ic(i.root,{recursive:!0,force:!0}).catch(g=>pe.warn("rm agent dir failed (ignored)",{err:String(g)})),f instanceof h?f:new h("AGENT_SPAWN_FAILED",String(f),{cause:f})}finally{clearTimeout(d)}}async spawnSessionDownstream(e,t,r,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&js(e.framework))o=Rc;else throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let a=e.deployType==="cloud"?{model:e.model,modelToken:t}:void 0,c;e.framework==="openclaw"?c=await this.buildOpenclawDownstream({session:e,modelConfig:a,cloudSessionId:r,cozeEnv:s,command:o.path}):c=this.factory(e.framework,o.path,e.workspace,e.agentId,a,r,s);try{return await c.start(),await c.initialize(Pc),c}catch(d){throw await c.stop("spawnSessionDownstream failed").catch(()=>{}),d instanceof h?d:new h("AGENT_SPAWN_FAILED",d instanceof Error?d.message:String(d),{cause:d})}}async buildOpenclawDownstream(e){let{session:t,modelConfig:r,cloudSessionId:s,cozeEnv:i,command:o}=e,a=rt(s),c=await Ws(),d=r?.modelToken&&!st(r.model)?ks(r,i):null,l;if(d){let u=$n(s),f=`${u}/${r.model}`;if(!this.ensuredProviders.has(f)){let g=this.getOpenclawConfig();await g.ensureProvider(u,d),await g.addModelToAllowlist(f),this.ensuredProviders.add(f)}l=f}return new ct({command:o,cwd:t.workspace,agentId:t.agentId,sessionName:a,...c?{gatewayToken:c}:{},...l?{slashModelOnStart:l}:{}})}async openclawRepair(e,t){let r=this.getOpenclawConfig();await r.deleteAgent(e),await r.ensureAgent(e,t)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let t=this.openclawConfigCache;for(let r of e.sessions.keys()){let s=$n(r),i=`${s}/${e.model}`;this.ensuredProviders.delete(i),await t.removeProvider(s),await t.removeModelFromAllowlist(i)}}};k();import{spawn as Cc}from"node:child_process";import{constants as Js,access as Oc}from"node:fs/promises";import{delimiter as Nc,join as bc}from"node:path";var Dc=w("framework-detector"),Vs={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Lc=[".exe",".cmd",".bat",".ps1"],$e=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Cc,access:e.access??Oc}}async detect(e){let t=Vs[e],r=await this.which(t);if(!r)return Dc.debug("framework binary not found",{framework:e,bin:t}),null;let s=await this.probeVersion(r);return{path:r,version:s}}async detectAll(){let e=await Promise.all(Object.keys(Vs).map(async r=>[r,await this.detect(r)])),t={};for(let[r,s]of e)s&&(t[r]=s);return t}async which(e){let t=this.env.pathEnv.split(Nc).filter(Boolean),r=this.env.platform==="win32"?["",...Lc]:[""];for(let s of t)for(let i of r){let o=bc(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?Js.F_OK:Js.X_OK;return await this.env.access(e,t),!0}catch{return!1}}async probeVersion(e){return new Promise(t=>{let r="",s=!1,i,o=a=>{s||(s=!0,i&&clearTimeout(i),t(a.trim()||"unknown"))};try{let a=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});i=setTimeout(()=>{a.kill("SIGKILL"),o("unknown")},5e3),a.stdout?.on("data",c=>{r+=c.toString("utf8")}),a.on("error",()=>o("unknown")),a.on("close",()=>{let c=Bc(r).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},Mc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Bc(n){return n.replace(Mc,"")}Tt();U();var Fc=10*6e4;function Qs(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Fc:e}function tn(n){return De(n??T().configFile)}function ze(n,e){return It(e??T().configFile,n)}import{randomBytes as Uc}from"node:crypto";fe();k();var v=w("core"),$c=3e4,zc=3e4,nn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Fe;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Qs(e.bridgeConfig)}registerExtension(e,t){this.extensions[e]=t}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),v.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){v.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(t=>t.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),v.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(r){v.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(r)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&v.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,t,r){let s=r.downstream;s&&(s.onUpdate(i=>{r.loadingSession||this.forwardUpdate(e,i)}),s.onAgentRequest(i=>{this.handleAgentRequest(e,s,i)}),s.onExit((i,o)=>{v.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),dt(r),r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId)}))}async handleFrame(e){if(jt(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let t="id"in e&&e.id!==void 0?e.id:null,r=e.params?._meta?.cozeEnv;r&&(this.currentCozeEnv=r);try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):v.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Be(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Be(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Be(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):v.warn("drop unknown notification",{method:e.method})}catch(s){v.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(Ee(t,Jt(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new h("IPC_BAD_REQUEST",`${e.method} requires params`);let t=e.params,r=t._meta?.cozeAgentId;if(!r)throw new h("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(r);if(!s)throw this.disconnectedAgents.has(r)?new h("AGENT_DISCONNECTED",`agent ${r} has been disconnected; cloud must _agent/create to revive`):new h("AGENT_NOT_FOUND",`agent not found: ${r}`);let i=typeof t.sessionId=="string"?t.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!i)return this.dispatchSessionCall(s,e.method,t);let o=Date.now(),a=!1;try{let c=await s.getSessionQueue(i).enqueue(()=>this.dispatchSessionCall(s,e.method,t));return a=!0,c}finally{v.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,t,r){e.lastActiveAt=Date.now();let{stripped:s}=ds(r);switch(t){case"session/new":{let i=qc();return v.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return v.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:i.sessionId}),{}}case"session/prompt":{let i=s,o=i.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new h("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=r._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);try{let d=await a.downstream.sessionPrompt({...i,sessionId:a.acpSessionId});return a.lastActiveAt=Date.now(),d}finally{e.activeTriggers.delete(a.acpSessionId),a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=s.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new h("IPC_BAD_REQUEST",`session method not supported: ${t}`)}}async ensureRuntime(e,t){let r=e.sessions.get(t);if(r)return r;let i={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,t):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(t,i),await this.persistSessionMapping(e),i}async requestSessionToken(e,t){let r={sessionId:t,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(ee.GEN_MODEL_TOKEN,r,zc);if(!s?.modelToken)throw new h("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${t})`);return s.modelToken}catch(s){throw s instanceof h&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new h("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,t,r){if(dt(r),r.downstream?.isAlive())return;if(!this.sessionSpawner)throw new h("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=await this.sessionSpawner(e,r.modelToken,t,this.currentCozeEnv);if(r.downstream=s,this.attachRuntimeHooks(e,t,r),r.acpSessionId){r.loadingSession=!0;try{await s.sessionLoad({sessionId:r.acpSessionId,cwd:e.workspace}),v.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId})}catch(i){v.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId,err:String(i)}),r.acpSessionId=void 0;let o=await s.sessionNew({cwd:e.workspace});r.acpSessionId=o.sessionId,await this.persistSessionMapping(e)}finally{r.loadingSession=!1}}else{let i=await s.sessionNew({cwd:e.workspace});r.acpSessionId=i.sessionId,await this.persistSessionMapping(e)}s.afterSessionEstablished&&r.acpSessionId&&await s.afterSessionEstablished(r.acpSessionId)}armIdleTimer(e,t,r){if(dt(r),this.isRuntimeBusy(e,r)){v.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:t});return}r.idleTimer=setTimeout(()=>{if(r.idleTimer=void 0,this.isRuntimeBusy(e,r)){v.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:t}),this.armIdleTimer(e,t,r);return}v.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:t});let s=r.downstream;r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId),s&&s.stop("idle timeout").catch(i=>v.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:t,err:String(i)}))},this.sessionIdleTimeoutMs),r.idleTimer.unref?.()}isRuntimeBusy(e,t){if(t.acpSessionId&&e.activeTriggers.has(t.acpSessionId))return!0;let r=t.downstream;if(!r)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===r)return!0;return!1}forwardUpdate(e,t){let r=t.sessionId,s=this.reverseSessionId(e,r);if(!s){v.debug("drop update for unknown session",{agentId:e.agentId,acpId:r});return}let i=e.sessions.get(s);if(!i){v.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(Gc(t)){v.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:r});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++i.replySeq},a=e.activeTriggers.get(r);a&&(o.cozeTriggerMsgId=a),this.upstream.send(Ht("session/update",{...t,sessionId:s,_meta:o})).catch(c=>v.warn("forward update failed",{agentId:e.agentId,err:String(c)}))}handleAgentRequest(e,t,r){if(r.method==="session/request_permission"){this.forwardPermissionRequest(e,t,r);return}v.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:r.method}),t.respondAgentRequestError(r.id,{code:R.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${r.method}`})}forwardPermissionRequest(e,t,r){let s=this.upstreamIds.next("session/request_permission"),i=r.params??{},a=i.sessionId,c=a?e.activeTriggers.get(a):void 0,d={cozeAgentId:e.agentId};c&&(d.cozeTriggerMsgId=c);let l=a?this.reverseSessionId(e,a):void 0,u={...i,...l?{sessionId:l}:{},_meta:d};this.pendingUpstream.set(s,{agentRequestId:r.id,agentId:e.agentId,downstream:t,method:r.method}),this.upstream.send(at(s,"session/request_permission",u)).catch(f=>{this.pendingUpstream.delete(s),v.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),t.respondAgentRequestError(r.id,{code:R.INTERNAL_ERROR,message:`upstream send failed: ${String(f)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let t=this.pendingUpstream.get(e.id);if(t){this.pendingUpstream.delete(e.id),e.error?t.downstream.respondAgentRequestError(t.agentRequestId,e.error):t.downstream.respondAgentRequest(t.agentRequestId,e.result);return}let r=this.pendingBridge.get(e.id);if(r){this.pendingBridge.delete(e.id),clearTimeout(r.timer),e.error?r.reject(new Wt(e.error)):r.resolve(e.result);return}v.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,r=$c){let s=this.upstreamIds.next(e);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(s),o(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r);this.pendingBridge.set(s,{method:e,resolve:i,reject:o,timer:a}),this.upstream.send(at(s,e,t)).catch(c=>{let d=this.pendingBridge.get(s);d&&(clearTimeout(d.timer),this.pendingBridge.delete(s)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let t=new Map;for(let[r,s]of e.sessions){let i={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(i.acpSessionId=s.acpSessionId),t.set(r,i)}await Bn(e.agentId,t,this.paths)}catch(t){v.warn("persist session mapping failed",{agentId:e.agentId,err:String(t)})}}reverseSessionId(e,t){for(let[r,s]of e.sessions.entries())if(s.acpSessionId===t)return r}sendError(e,t,r){return this.upstream.send(Ee(e,{code:t,message:r}))}};function qc(){return Uc(16).toString("hex")}function Gc(n){let e=n.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let t=e.content;if(!t||typeof t!="object")return!1;let r=t;return r.type!=="text"||typeof r.text!="string"?!1:r.text.startsWith("Model metadata for `")}k();U();import{randomBytes as Hc}from"node:crypto";import{chmod as Wc,mkdir as jc,writeFile as Ks}from"node:fs/promises";import{createServer as Jc}from"node:http";import{dirname as Vc}from"node:path";var Qc=1e6,Hn=w("ipc"),rn=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(t=>[`${t.method} ${t.path}`,t])),this.paths=e.paths??T()}async start(){this.token=Hc(32).toString("hex");let e=Jc((r,s)=>{this.dispatch(r,s)});this.server=e,await new Promise((r,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>r())});let t=e.address();if(!t||typeof t!="object")throw new Error("failed to obtain IPC port");return this.port=t.port,await this.persistAuthFiles(),Hn.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((t,r)=>{e.close(s=>s?r(s):t())}),this.server=null)}async persistAuthFiles(){await jc(Vc(this.paths.portFile),{recursive:!0}),await Ks(this.paths.portFile,String(this.port),"utf8"),await Ks(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Wc(this.paths.tokenFile,384)}catch(e){Hn.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){lt(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){lt(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await Kc(e)}catch(a){lt(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);lt(t,200,a??{ok:!0})}catch(a){Hn.error("IPC handler failed",{key:s,err:String(a)}),lt(t,500,{error:a instanceof Error?a.message:String(a)})}}};function lt(n,e,t){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(t))}async function Kc(n){let e=[],t=0;for await(let s of n){let i=s;if(t+=i.length,t>Qc)throw new Error("body too large");e.push(i)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var ii="";function cd(n=""){let t=`${Date.now()}`,r=ii||(ii=fd(n)),s=Math.random().toString(16).slice(-6);return"02"+t+r+s}function dd(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function ld(n){return(Array(8).join("0")+parseInt(n,10).toString(2)).slice(-8)}function oi(n){return(Array(4).join("0")+parseInt(n,2).toString(16)).slice(-4)}function ud(n){let e=n.split(/\./).map(s=>ld(s)),t=[];return t[0]=oi(e[0]+e[1]),t[1]=oi(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function fd(n){let e=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(n),t=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(n);return e?ud(n):t?hd(n):"00000000000000000000000000000000"}function hd(n){let e="",t=[],r=0,s=0,i=!0,o="0000";if(n.indexOf("::")>-1){let a=n.split("::");for(let d=0;d<a.length;d++){let l=a[d];if(l.indexOf(":")>0){let u=l.split(":");i&&(r=u.length),s+=u.length;for(let f=0;f<u.length;f++)if(u[f].length!==4){let m=o.substring(0,4-u[f].length).concat(u[f]);t.push(m)}else t.push(u[f]);i=!1}else{if(l.length!==4){let f=o.substring(0,4-l.length).concat(l);t.push(f)}else t.push(l);i&&(r+=1),s+=1,i=!1}}let c="";for(let d=0;d<8-s;d++)c=c.concat(o);for(let d=0;d<t.length;d++)d===r&&(e=e.concat(c)),e=e.concat(t[d]);return e}{let a=n.split(":");for(let c=0;c<a.length;c++){let d=a[c];if(a[c].length!==4){let u=o.substring(0,4-a[c].length).concat(d);e=e.concat(u)}else e=e.concat(d)}return e}}function gd(n,e){let t=n.key;t!==void 0&&(C(e,10),xe(e,t));let r=n.value;r!==void 0&&(C(e,18),xe(e,r))}function pd(n){let e={};e:for(;!Si(n);){let t=D(n);switch(t>>>3){case 0:break e;case 1:e.key=ke(n,D(n));break;case 2:e.value=ke(n,D(n));break;default:_i(n,7&t)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function mi(n){let e=yi();return md(n,e),vd(e)}function md(n,e){let t=n.SeqID;t!==void 0&&(C(e,8),ft(e,t));let r=n.LogID;r!==void 0&&(C(e,16),ft(e,r));let s=n.service;s!==void 0&&(C(e,24),ft(e,Xn(s)));let i=n.method;i!==void 0&&(C(e,32),ft(e,Xn(i)));let o=n.headers;if(o!==void 0)for(let m of o){C(e,42);let _=yi();gd(m,_),C(e,_.limit),Id(e,_),Sd(_)}let a=n.payloadEncoding;a!==void 0&&(C(e,50),xe(e,a));let c=n.payloadType;c!==void 0&&(C(e,58),xe(e,c));let d=n.payload;d!==void 0&&(C(e,66),C(e,d.length),xd(e,d));let l=n.LogIDNew;l!==void 0&&(C(e,74),xe(e,l));let u=n.serverTiming;u!==void 0&&(C(e,82),xe(e,u));let f=n.msgID;f!==void 0&&(C(e,90),xe(e,f));let g=n.frameType;g!==void 0&&(C(e,96),ft(e,Xn(g)))}function _d(n){return wd(Ed(n))}function wd(n){let e={};e:for(;!Si(n);){let t=D(n);switch(t>>>3){case 0:break e;case 1:e.SeqID=ci(n,!0);break;case 2:e.LogID=ci(n,!0);break;case 3:e.service=D(n);break;case 4:e.method=D(n);break;case 5:{let r=yd(n);(e.headers||(e.headers=[])).push(pd(n)),n.limit=r;break}case 6:e.payloadEncoding=ke(n,D(n));break;case 7:e.payloadType=ke(n,D(n));break;case 8:e.payload=kd(n,D(n));break;case 9:e.LogIDNew=ke(n,D(n));break;case 10:e.serverTiming=ke(n,D(n));break;case 11:e.msgID=ke(n,D(n));break;case 12:e.frameType=D(n);break;default:_i(n,7&t)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function yd(n){let e=D(n),t=n.limit;return n.limit=n.offset+e,t}function _i(n,e){switch(e){case 0:for(;128&H(n););break;case 2:Yn(n,D(n));break;case 5:Yn(n,4);break;case 1:Yn(n,8);break;default:throw new Error("Unimplemented type: "+e)}}function Xn(n){return n|=0,{low:n,high:n>>31,unsigned:n>=0}}var wi=[];function yi(){let n=wi.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function Sd(n){wi.push(n)}function Ed(n){return{bytes:n,offset:0,limit:n.length}}function vd(n){let e=n.bytes,t=n.limit;return e.length===t?e:e.subarray(0,t)}function Yn(n,e){if(n.offset+e>n.limit)throw new Error("Skip past limit");n.offset+=e}function Si(n){return n.offset>=n.limit}function pt(n,e){let t=n.bytes,r=n.offset,s=n.limit,i=r+e;if(i>t.length){let o=new Uint8Array(2*i);o.set(t),n.bytes=o}return n.offset=i,i>s&&(n.limit=i),r}function mr(n,e){let t=n.offset;if(t+e>n.limit)throw new Error("Read past limit");return n.offset+=e,t}function kd(n,e){let t=mr(n,e);return n.bytes.subarray(t,t+e)}function xd(n,e){let t=pt(n,e.length);n.bytes.set(e,t)}function ke(n,e){let t=mr(n,e),r=String.fromCharCode,s=n.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],d,l,u,f;(128&c)===0?o+=r(c):(224&c)===192?a+1>=e?o+=i:(d=s[a+t+1],(192&d)!==128?o+=i:(f=(31&c)<<6|63&d,f<128?o+=i:(o+=r(f),a++))):(240&c)==224?a+2>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],((d|l<<8)&49344)!==32896?o+=i:(f=(15&c)<<12|(63&d)<<6|63&l,f<2048||f>=55296&&f<=57343?o+=i:(o+=r(f),a+=2))):(248&c)==240?a+3>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],u=s[a+t+3],((d|l<<8|u<<16)&12632256)!==8421504?o+=i:(f=(7&c)<<18|(63&d)<<12|(63&l)<<6|63&u,f<65536||f>1114111?o+=i:(f-=65536,o+=r((f>>10)+55296,(1023&f)+56320),a+=3))):o+=i}return o}function xe(n,e){let t=e.length,r=0;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),r+=a<128?1:a<2048?2:a<65536?3:4}C(n,r);let s=pt(n,r),i=n.bytes;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?i[s++]=a:(a<2048?i[s++]=a>>6&31|192:(a<65536?i[s++]=a>>12&15|224:(i[s++]=a>>18&7|240,i[s++]=a>>12&63|128),i[s++]=a>>6&63|128),i[s++]=63&a|128)}}function Id(n,e){let t=pt(n,e.limit),r=n.bytes,s=e.bytes;for(let i=0,o=e.limit;i<o;i++)r[i+t]=s[i]}function H(n){return n.bytes[mr(n,1)]}function ai(n,e){let t=pt(n,1);n.bytes[t]=e}function D(n){let e=0,t=0,r;do r=H(n),e<32&&(t|=(127&r)<<e),e+=7;while(128&r);return t}function C(n,e){for(e>>>=0;e>=128;)ai(n,127&e|128),e>>>=7;ai(n,e)}function ci(n,e){let t=0,r=0,s=0,i;return i=H(n),t=127&i,128&i&&(i=H(n),t|=(127&i)<<7,128&i&&(i=H(n),t|=(127&i)<<14,128&i&&(i=H(n),t|=(127&i)<<21,128&i&&(i=H(n),r=127&i,128&i&&(i=H(n),r|=(127&i)<<7,128&i&&(i=H(n),r|=(127&i)<<14,128&i&&(i=H(n),r|=(127&i)<<21,128&i&&(i=H(n),s=127&i,128&i&&(i=H(n),s|=(127&i)<<7))))))))),{low:t|r<<28,high:r>>>4|s<<24,unsigned:e}}function ft(n,e){let t=e.low>>>0,r=(e.low>>>28|e.high<<4)>>>0,s=e.high>>>24,i=s===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:s<128?9:10,o=pt(n,i),a=n.bytes;switch(i){case 10:a[o+9]=s>>>7&1;case 9:a[o+8]=i!==9?128|s:127&s;case 8:a[o+7]=i!==8?r>>>21|128:r>>>21&127;case 7:a[o+6]=i!==7?r>>>14|128:r>>>14&127;case 6:a[o+5]=i!==6?r>>>7|128:r>>>7&127;case 5:a[o+4]=i!==5?128|r:127&r;case 4:a[o+3]=i!==4?t>>>21|128:t>>>21&127;case 3:a[o+2]=i!==3?t>>>14|128:t>>>14&127;case 2:a[o+1]=i!==2?t>>>7|128:t>>>7&127;case 1:a[o]=i!==1?128|t:127&t}}function Td(n){return _d(n)}function di(n){return mi(n)}var li=65536,Rd="\0\0\0\0\0\0\0\0",qe=li*li,Ei=qe*qe,ui=Ei/2,me=String.prototype.charCodeAt,z=class n{constructor(e,t,r){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!r}static isLong(e){return e&&e.isLong===!0}static fromBits(e,t,r){return new n(e,t,r)}static fromBytes(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)}static fromBytesLE(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return e===Rd?fi:new n((me.call(e,0)|me.call(e,1)<<8|me.call(e,2)<<16|me.call(e,3)<<24)>>>0,(me.call(e,4)|me.call(e,5)<<8|me.call(e,6)<<16|me.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,t=!0){if(isNaN(e))return t?Pd:fi;if(t){if(e>=Ei)return Cd}else{if(e<=-ui)return Od;if(e+1>=ui)return Ad}return n.fromBits(e%qe|0,e/qe|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*qe+(this.low>>>0):this.high*qe+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){n.isLong(e)||(e=n.fromNumber(e));let t=this.high>>>16,r=65535&this.high,s=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,d=65535&e.low,l=0,u=0,f=0,g=0;return g+=i+d,f+=g>>>16,g&=65535,f+=s+c,u+=f>>>16,f&=65535,u+=r+a,l+=u>>>16,u&=65535,l+=t+o,l&=65535,n.fromBits(f<<16|g,l<<16|u,this.unsigned)}equals(e){return n.isLong(e)||(e=n.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?n.fromBits(0,0,this.unsigned):this.low===-1?n.fromBits(0,this.high+1,this.unsigned):n.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}},fi=new z(0,0,!1),Pd=new z(0,0,!0),Ad=z.fromBits(-1,2147483647,!1),Cd=z.fromBits(-1,-1,!0),Od=z.fromBits(0,-2147483648,!1),ve=(function(n){return n[n.NATIVE_ERROR=5001]="NATIVE_ERROR",n[n.CONNECTING_ERROR=5002]="CONNECTING_ERROR",n[n.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",n[n.MESSAGE_ERROR=5004]="MESSAGE_ERROR",n[n.OPEN_ERROR=5005]="OPEN_ERROR",n})({}),Ie=class{constructor(e){this.type=e,this.target=null}},er=class extends Ie{constructor(e,t){super(e),this.message=t&&t.message||null}},tr=class extends Ie{constructor(e,t){super(e),this.error=t&&t.error||null,this.colno=t&&t.colno||0,this.filename=t&&t.filename||"",this.lineno=t&&t.lineno||0,this.message=t&&t.message||"",this.code=t&&t.code||5001}},nr=class extends Ie{constructor(e,t){super(e),this.code=t&&t.code||0,this.reason=t&&t.reason||"",this.wasClean=t&&t.wasClean||!1,this.willReconnect=t&&t.willReconnect||!1}},rr=class extends Ie{constructor(e,t){super(e),this.data=t&&t.data||null}},sr=class extends rr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},ir=class extends Ie{constructor(e,t){super(e),this.data=t&&t.data||null}};function X(n,{message:e,code:t,error:r}){return new tr(n,{message:e,code:t,error:r})}function te(n,{code:e,reason:t,wasClean:r,willReconnect:s}){return new nr(n,{code:e,reason:t,wasClean:r,willReconnect:s})}function Nd(n,{data:e,message:t}){return new sr(n,{data:e,message:t})}function bd(n,{data:e}){return new ir(n,{data:e})}function hi(n,{message:e}){return new er(n,{message:e})}var sn=class{constructor(e,t){this.endpoints=e,this.maxRetries=t,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length?!0:this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}},He=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Te=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",mt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",ht=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",Dd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,gt=class{constructor(){this._listeners={}}emit(e,...t){let r=this._listeners[e];if(r)r.slice().forEach(s=>s.fn.apply(s.ctx,t));else if(e==="error"&&!this.onerror){let s=t.length&&t[0];if(s instanceof Error)throw s;let i=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw i.context=s,s}return this}off(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=null;else{let r=this._listeners[e];if(r)for(let s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this}on(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this}},or=class extends gt{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,t,r){super(),this._socket=null,mt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Te&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let t=X("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let r=te("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",bd("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",te("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",Nd("message",{...e}))}),this._socket.onError(e=>{this.emit("error",X("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:r=>{this.emit("error",X("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",X("error",{message:this._formatErrorMessage(t)}))}})}close(e,t){this._socket&&this._socket.close({code:e,reason:t})}addEventListener(e,t){this.on(e,t)}removeEventListener(e,t){this.off(e,t)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}};function Ld(n,e){if(e)return new e(n.url,n.protocol);if(mt||Te)return new or(n.url,n.protocol,n.headers);if((He||ht)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(n.url,n.protocols)}function Md(n){return!!(n||mt&&wx.connectSocket||Te&&tt.connectSocket||(He||ht)&&typeof WebSocket<"u"&&WebSocket)}function gi(n,e,t){let r=-1;async function s(i){return i<=r?Promise.reject(new Error("next() called multiple times in process")):(r=i,i===t.length?Promise.resolve():t[i].bind(n)(e,s.bind(null,i+1)))}s(0)}function vi(n){let e=0,t=0;for(let r=0;r<n.length;++r)t=n.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(64512&t)===55296&&(64512&n.charCodeAt(r+1))===56320?(++r,e+=4):e+=3;return e}function ki(n,e,t){if(t-e<1)return"";let r="";for(let s=e;s<t;){let i=n[s++];if(i<=127)r+=String.fromCharCode(i);else if(i>=192&&i<224)r+=String.fromCharCode((31&i)<<6|63&n[s++]);else if(i>=224&&i<240)r+=String.fromCharCode((15&i)<<12|(63&n[s++])<<6|63&n[s++]);else if(i>=240){let o=((7&i)<<18|(63&n[s++])<<12|(63&n[s++])<<6|63&n[s++])-65536;r+=String.fromCharCode(55296+(o>>10)),r+=String.fromCharCode(56320+(1023&o))}}return r}function ar(n,e,t){let r=t,s,i;for(let o=0;o<n.length;++o)s=n.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=63&s|128):(64512&s)===55296&&(64512&(i=n.charCodeAt(o+1)))===56320?(s=65536+((1023&s)<<10)+(1023&i),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=63&s|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=63&s|128);return t-r}async function xi(n){if(typeof n=="string"){let e=new Uint8Array(vi(n));return ar(n,e,0),e}return n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Bd(n){try{return typeof n!="string"&&(n instanceof ArrayBuffer||n.buffer&&n.buffer instanceof ArrayBuffer)||typeof n!="string"?"":(JSON.parse(n),"application/json")}catch{return typeof n=="string"?"text/plain;charset=utf-8":""}}var Fd=(n,e)=>{switch(n){case"boe":case"ppe":return{[`x-use-${n}`]:1,"x-tt-env":e};default:return{}}},cr=class{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}};async function Ud(n){return new Promise(e=>{if(!He)return e("unknown reason");try{let t=document.createElement("script");window.frontierJSONP=r=>{document.body.removeChild(t),window.frontierJSONP=void 0,e(r&&r.msg||"unknown reason")},t.type="text/javascript",t.src=n.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(t)}catch{document.body.removeChild(t)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function _e(n,e,t){return!!n?.find(r=>r.key===e&&r.value===t)}function Ge(n,e){return n?.find(t=>t.key===e)?.value}var Zn=null;async function $d(){return Zn||(Zn=Promise.resolve().then(()=>(si(),ri))),Zn}var dr=class extends gt{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,t=this._keyPath;this._initPromise=(async()=>{let{openDB:r}=await $d();this._qosDB=await r(`frontier_${e}`,1,{upgrade(s){s.createObjectStore(e,{keyPath:t})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(t){console.log(t)}}async set(e,t){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(t){console.log(t)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},lr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getItem(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getItem(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},ur=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Te?tt:mt?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getStorageSync(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getStorageSync(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function Ii(n,e){if(Te||Te)return new ur(n,e);if((He||ht)&&typeof indexedDB<"u")return new dr(n,e);if((He||ht)&&typeof localStorage<"u")return new lr(n,e);throw new Error("init QoSDB failed")}var fr=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Ii("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:r})=>r<Date.now()).forEach(r=>{this._qosDB?.del(r.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,t){return this._qosDB?.set({message_id:e,timestamp:t})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function _r(n){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=_e(n.message.headers,"x_frontier_qos","2"),r=t&&_e(n.message.headers,"x_frontier_qos_ack","1"),s=t&&_e(n.message.headers,"x_frontier_is_ack","1"),i=s?Ge(n.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:r,isAckCleanupMessage:s,ackMsgIds:i}}async function Ti(){return this._QoSManager||(this._QoSManager=new fr),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function zd(n,e){let{enableAutoAck:t}=this._options,r=_e(n.message.headers,"need_ack","1"),s=_e(n.message.headers,"is_ack","1"),i=_r.call(this,n);if(t&&r){let{SeqID:o,LogID:a,service:c,LogIDNew:d,method:l}=n.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:d,service:c,method:l,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:d||""},{key:"ack_code",value:"0"}]})}s&&!i.isQoSAck&&this._dispatchAckMessageEvent(n),e()}async function qd(n,e){this._debug("received",n.message),e()}async function Gd(n,e){let t=Td(await xi(n.data));try{if(t.payload instanceof Uint8Array){let r=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},s=t.payloadEncoding?t.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=t.payloadType?t.payloadType.replace(/\s/g,"").toLowerCase():"",a=i.force?i.type:o||i.type,c=r.force?r.encoding:s||r.encoding,d=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],l=["none_none","binary"];this._options.enableTransformTextPayload&&d.includes(a)&&(!c||l.includes(c))?t.textPayload=ki(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(r){t.textPayload="",console.log(r)}n.message=t,e()}function Hd(n,e,t){let r=t||8192,s=r>>>1,i=null,o=r;return function(a){if(a<1||a>s)return n(a);o+a>r&&(i=n(r),o=0);let c=e.call(i,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var Wd=4294967295;function jd(n,e,t){if(t>Wd)throw new Error("integer too large");let r=3;for(;r>=0;){let s=255&t;gr(s,n,e+r),t>>>=8,r--}return e+4}function Jd(n,e){let t=0,r=e,s=e+4;for(;r<s;){let{value:i,offset:o}=hr(n,r);r=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function Vd(n,e,t){return n?n.length<40?ar(n,e,t)+t:e.utf8Write?e.utf8Write(n,t)+t:e.write?e.write(n,t)+t:ar(n,e,t)+t:t}function Qd(n,e){let t=new z(n[e+4]<<24|n[e+5]<<16|n[e+6]<<8|n[e+7],n[e+0]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3],!0);return e+=8,{value:t,offset:e+8}}function Kd(n,e,t){let r=n.low,s=n.high;return e[t]=s>>>24,e[t+1]=s>>>16&255,e[t+2]=s>>>8&255,e[t+3]=255&s,e[t+4]=r>>>24,e[t+5]=r>>>16&255,e[t+6]=r>>>8&255,e[t+7]=255&r,t+=8,t}function hr(n,e){return n.readUInt8?{value:n.readUInt8(e),offset:e+1}:{value:255&n[e],offset:e+1}}function gr(n,e,t){return e.writeUint8?e.writeUint8(n,t):e[t]=255&n,t+1}var Xd=function(n){return new Uint8Array(n)},Yd=typeof Buffer<"u"?Buffer.allocUnsafe:Hd(Xd,Uint8Array.prototype.subarray),Zd=16,wr=32;function el(n){let e=0,t={};for(let r=0;r<n.length;r++)t[n[r].cursor_name]=vi(n[r].cursor_name),e+=14+t[n[r].cursor_name];return[e,t]}function pi(n,e,t){let[r,s]=el(n),i=Yd(r),o=0;return n.forEach(a=>{console.log("cursor.service",a,a.service),o=gr(0,i,o),console.log("header",o),o=jd(i,o,a.service||0),console.log("service",o),o=gr(s[a.cursor_name],i,o),console.log("service-name",o),o=Vd(a.cursor_name,i,o),console.log("name",o),o=Kd(z.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:wr,headers:[{key:"cursor_file_name",value:t}],payload:i}}function tl(n){let e=0,t=[];for(;e<n.byteLength;){let{offset:r}=hr(n,e);e=r;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=Jd(n,e);s.service=i,e=o;let{value:a,offset:c}=hr(n,e);e=c,s.cursor_name=ki(n,e,e+a),e+=a;let{value:d,offset:l}=Qd(n,e);s.cursor=d.toNumber(),e=l,t.push(s)}return t}function nl(){return{frameType:wr,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var pr=class{constructor(e,t,r){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=r,this._qosDB=Ii(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,t=await this._qosDB.getAll();switch(console.log("allCursorValues",t),e){case"ALL":return t&&t.length?pi(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?pi(t,0,this._cursorFileName):nl()}}async set(e,t,r){return console.log("setdb",e,t,r),this._qosDB.set({cursor_name:e,cursor:t,service:r})}async setCursors(e){let t=tl(e);for(let r of t)console.log("setcursor",t),await this._qosDB.set(r)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},rl="__x_msg_qos__";async function Ri(n){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:r}=this._options,s=n||rl;try{return this._cursorManager?n&&this._cursorManager.updateCursorFileName(n):this._cursorManager=new pr(`${t}_${e}_${s}`,s,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function sl(n,e){let t=_e(n.message.headers,"code","-1"),r=_e(n.message.headers,"is_ack","1"),s=Ge(n.message.headers,"x_frontier_msgid"),i=Number(Ge(n.message.headers,"x_frontier_ttl"))||0,o=_r.call(this,n),a=_e(n.message.headers,"x-msg-qos","2"),c=Ge(n.message.headers,"x-msg-cursor_name"),d=Number(Ge(n.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let l=o.isQoSMessage?await Ti.call(this):null;if(n.message.service>0&&r&&!t||n.message.service>0){if(s&&o.isQoSMessage&&l)return await l.get(s)||(this._dispatchMessageEvent(n),await l.set(s,Date.now()+i)),e();if(a){let u=await Ri.call(this);if(!u)return this._dispatchMessageEvent(n),e();let f=await u.get(c)??-1;if(f<d)this._dispatchMessageEvent(n),u.set(c,d,n.message.service);else throw new Error(`recevied message cursor ${d} larger than local cursor ${f}`);return e()}return this._dispatchMessageEvent(n),e()}}async function il(n,e){let t=_r.call(this,n);if(!t.isQoSMessage)return e();let r=await Ti.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await r.del(s);e()}async function ol(n,e){let t=n.message.frameType===Zd,r=n.message.frameType===wr;if(!t&&!r)return e();let s=Ge(n.message.headers,"cursor_file_name");if(!s)return e();let i=await Ri.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:z.fromNumber(this._seqId++),LogID:z.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=mi(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=n.message.payload;o&&i.setCursors(o)}}var al=async function(n,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},cl=async function(n,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},dl=async function(n,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:t}=this._options;this._endpointManager?.resetEndpointConfig();for(let s=0;s<this._messageQueue.length;s++){let i=this._messageQueue[s];if(this._ws.readyState===this.OPEN&&i!==null)this._ws&&this._ws.send(i),this._messageQueue[s]=null;else break}this._messageQueue=this._messageQueue.filter(s=>!!s),this._pingPongTimeoutId=setTimeout(()=>this._ping(),t),this._dispatchOpenEvent(n),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r} success`),e()},on=class extends gt{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=He,this._isNode=Dd,this._isMiniTT=Te,this._isMiniWX=mt,this._isWorker=ht,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=i=>{try{gi(this,i,[al,dl,cl])}catch(o){let a=X("error",{message:o.message,code:ve.OPEN_ERROR,error:o});this._dispatchErrorEvent(a)}},this._onMessage=async i=>{let{pingInterval:o,pingFrequency:a}=this._options;if((i.data==="hi"&&a==="always"||a==="auto")&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),o)),i.data!=="hi")try{gi(this,i,[Gd,zd,il,ol,sl,qd])}catch(c){let d=X("error",{message:c.message,code:ve.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(d)}},this._onError=i=>{let o=this._endpointManager?.checkReachMaxTries(),a=this._endpointManager?.getCurrentEndpoint();if(o&&!i.message){let c=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(X("error",{message:c,code:ve.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(X("error",{message:i.message,code:ve.NATIVE_ERROR,error:i}))},this._onClose=async i=>{this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;let o=this._endpointManager?.checkReachMaxTries();if(!o&&this._navigatorOnline()&&!this._readyClosed){let a=this._endpointManager?.getCurrentEndpoint(),c=this._options.reconnectInterceptor(i.code,i.reason);this._dispatchCloseEvent(te("close",{code:1006,reason:i.reason||`connecting failed, unknown reason, hostname: ${a}`,willReconnect:c})),c&&this._connect();return}if(i.code!==1e3&&this._readyClosed){this._dispatchCloseEvent(te("close",{code:1e3,reason:"bye"})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&o){let a=this._endpointManager?.getCurrentEndpoint(),c=i.reason;c||(c=await Ud(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(te("close",{code:i.code,reason:c}));let d=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(X("error",{message:d,code:ve.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(te("close",{code:i.code,reason:`connecting failed, unknown reason, hostname: ${a}`})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}this._dispatchCloseEvent(i),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:dd,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:t,ws:r}=e,s=Array.isArray(t)?t:typeof t=="string"?[t]:[];if(!s||s.length===0)throw new Error("please provide valid url");if(!Md(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new sn(s,this._options.maxRetries),this._pingLossCounter=new cr(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();let e=hi("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:t,deviceID:r,bddID:s,ttwID:i,accessKey:o,aID:a,customParams:c={},enableAutoAck:d,enableQoS:l,QoSLevel:u,env:f}=this._options,g,m,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(g=location&&location.protocol=="https:"?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${g}${m}`):(g="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${g}${m}`);let E=s?"bd_did":i?"ttwid":"device_id",L=s||i||r;if(!L||!E)throw new Error("please provide bddID, deviceID or ttwID");let B=typeof c=="function"?await c():c,re=f?Fd(f.xUseEnv,f.xTTEnv):{},M=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[E]:L,xsack:d?1:0,xaack:d?1:0,xsqos:l?1:0,qos_level:l?u:void 0,qos_sdk_version:2,...re},B),p=Object.keys(M).reduce((S,I)=>M[I]!==void 0?`${S}${S?"&":"?"}${I}=${M[I]}`:S,"");return`${_}/ws/v2${p}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:t}=this._options;if(e){let s=this._endpointManager?.getCurrentEndpoint(),i=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(i){let a=`connect ${s} timeout, max retries reached, will use backup endpoint ${i} to retry`,c=X("error",{message:a,code:ve.MAX_RETRIES_ERROR});this._debug(a),this._dispatchErrorEvent(c),this._url=await this._generateUrl(i),this._debug(`connect ${i} ${o} times`),this._removeWsListeners()}else{let a=`connect ${s} timeout, max retries reached`;this._debug(a),this._dispatchErrorEvent(X("error",{message:a,code:ve.MAX_RETRIES_ERROR}));return}}else{let s=this._endpointManager?.getCurrentEndpointAndUpdateCount(),i=this._endpointManager?.getCurrentEndpointTriesCount();this._url=await this._generateUrl(s||""),this._debug(`connect ${s} ${i} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{let s=hi("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(s)}let r=this._endpointManager?.getCurrentEndpointTriesCount()||0;r>1&&await this._wait(r-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=Ld({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),t)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:t,maxReconnectInterval:r,reconnectIntervalGrowFactor:s}=this._options,i=t*Math.pow(s,e-1);return i>r?r:i}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(t=>{setTimeout(t,this._getIntervalValue(e))})}_disconnect(e=1e3,t="",r=!1){this._ws&&this._destroyWebSocket(e,t,r)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let t=di(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch{}}_destroyWebSocket(e=1e3,t="",r=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,r&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let i=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(te("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(te("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(te("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(te("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((t,r)=>(t+=r&&r.byteLength||0,t),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,t)}async send(e,t){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let r=await xi(e),s=Bd(e),{method:i=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:d=this._options.payloadEncoding,payloadType:l=this._options.payloadType,logIDNew:u=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?cd(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let f={SeqID:z.fromNumber(this._seqId++),LogID:z.fromNumber(a),service:o,method:i,headers:c,payloadEncoding:d instanceof Object?d.encoding?d.encoding:"":d,payloadType:l instanceof Object?l.type?l.type:s:l||s,payload:r,LogIDNew:u},g=di(f);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(g),this._debug("sent",f)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(g),this._debug("enqueue",f)):(this._messageQueue.shift(),this._messageQueue.push(g)),{seqID:this._seqId,logID:a,logIDNew:u}}async reconnect(e){let{url:t}=e||{},r=Array.isArray(t)?t:typeof t=="string"?[t]:[];e&&Object.assign(this._options,e),r&&r.length?this._endpointManager=new sn(r,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){let{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let r=()=>{e("success"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)},s=()=>{t("timeout"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)};this.on("ping_once_success",r),this.on("ping_once_timeout",s),this._ping()})}};var Au=ue(ko(),1),Cu=ue(pn(),1),Ou=ue(Je(),1),Nu=ue(Ar(),1),bu=ue(Nr(),1),Du=ue(Fr(),1),No=ue(yn(),1),Lu=ue(Oo(),1);var bo=No.default;k();var O=w("upstream.frontier"),Lo="application/json",Mo="none",En=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){O.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:fs,...Dt(this.opts.ppeOverride)};class t extends bo{constructor(a){super(a,us,{headers:e})}send(a,...c){if(as("debug"))try{let d;typeof a=="string"?d=Buffer.from(a,"utf8"):a instanceof Buffer?d=a:a instanceof ArrayBuffer?d=new Uint8Array(a):ArrayBuffer.isView(a)?d=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):d=new Uint8Array(0);let l=Buffer.from(d.slice(0,128)).toString("hex");O.debug("WS raw frame out",{bytes:d.byteLength,headHex:l})}catch(d){O.warn("WS raw frame dump failed",{err:String(d)})}super.send(a,...c)}}let r=ps(this.opts.urlOverride),s={url:r,ws:t,fpID:ls,aID:bt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Lo,force:!0},payloadEncoding:{encoding:Mo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new on(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;O.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:o,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:o})).catch(a=>O.warn("onConnect handler threw (ignored)",{err:String(a)}))},i.onclose=o=>{this.opened=!1,O.info("frontier closed",{code:o.code,reason:o.reason,willReconnect:o.willReconnect})},i.onerror=o=>{O.warn("frontier error",{code:o.code,msg:o.message})},i.onmessage=o=>this.handleMessage(o),this.fws=i,await i.connect()}async stop(e){let t=this.fws;if(t){this.fws=null,this.opened=!1;try{t.close(1e3,e??"bridge shutdown")}catch(r){O.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let t=this.fws;if(!t)throw new h("UPSTREAM_DISCONNECTED","frontier upstream not started");let r=JSON.stringify(e),s=e;Bo(s)||O.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:r.length});try{await t.send(r,{service:33555712,method:1,payloadType:Lo,payloadEncoding:Mo})}catch(o){throw O.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(o)}),new h("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(o)}`,{cause:o})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let t=e.message?.service;if(t!==33555712){O.debug("drop non-adapter frontier frame",{service:t});return}let r=Fu(e);if(!r){O.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){O.debug("frame received but no onFrame handler",{size:r.length});return}let s;try{s=JSON.parse(r)}catch(o){O.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let i=s;Bo(i)||O.info("frontier frame in",{logid:Bu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:i.id}),Promise.resolve(this.handler(s)).catch(o=>O.warn("frontier frame handler threw",{err:String(o)}))}};function Bo(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}function Bu(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function Fu(n){let e=n.message;if(e?.textPayload)return e.textPayload;let t=e?.payload;if(!t)return null;try{return Buffer.from(t).toString("utf8")}catch{return null}}k();var $r=w("upstream.switchable"),vn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;$r.info("swap upstream",{reason:t});let r=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(s){throw $r.error("swap target start failed, reverting",{err:String(s)}),this.inner=r,s}await r.stop(t??"swapped").catch(s=>$r.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};k();var zr=w("upstream"),xt=class{handler=null;async start(){zr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){zr.info("NoopUpstream stopped",{reason:e})}async send(e){zr.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};k();U();k();U();import{execSync as Uu}from"node:child_process";import{readFileSync as Fo,unlinkSync as $u}from"node:fs";import{mkdir as zu,readFile as Uo,unlink as $o,writeFile as qu}from"node:fs/promises";import{dirname as Gu}from"node:path";var Hu=w("single-instance"),kn=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??T().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(Hu.warn("removing stale pid file",{stalePid:e}),await $o(this.pidFile).catch(()=>{})),await zu(Gu(this.pidFile),{recursive:!0}),await qu(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Uo(this.pidFile,"utf8")).trim()===String(process.pid)&&await $o(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Uo(this.pidFile,"utf8"),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return this.matchesDaemonTitle(e)}matchesDaemonTitle(e){try{let t=Fo(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=Uu(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return t.trim()?t.includes("coze-bridge-daemon")||t.includes("lib/index.js"):!1}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Fo(this.pidFile,"utf8").trim()===String(process.pid)&&$u(this.pidFile)}catch{}})}};var y=w("daemon"),Wu="coze-bridge-daemon";async function Go(){let n=new kn({processTitle:Wu}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await tn(),r=t??{};Mn({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let p=new $e;r.frameworksCache=await p.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(r.frameworksCache)})}catch(p){y.warn("framework detection failed",{err:String(p)})}await ze(r);let s=new vn(new xt),i=T(),o=null,a=new nn({upstream:s,paths:i,bridgeConfig:r,sessionSpawner:async(p,S,I,J)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(p,S,I,J)}});await Ju(i,a);let c=new en({paths:i,config:r,registry:a});o=c;let d,l,u=null,f=null;a.registerExtension("_agent/create",async p=>c.createAgent(p.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let g={},m=new Bt({agents:a.agents,disposeAndMarkDisconnected:async(p,S)=>{let I=a.agents.get(p);I&&(await c.cleanupOpenclawSessionProviders(I).catch(J=>y.warn("cleanup openclaw providers failed (ignored)",{agentId:p,err:String(J)})),await I.dispose(`disconnect: ${S}`).catch(J=>y.warn("dispose during disconnect failed (ignored)",{agentId:p,err:String(J)})),I.status="disconnected",a.unregister(p)),a.disconnectedAgents.add(p)},detailSyncer:async p=>{if(!g.ref)throw new Error("agent-detail-sync not initialized yet");await g.ref.syncOne(p)},openclawRepair:async(p,S)=>{await c.openclawRepair(p,S)}});a.registerExtension("_agent/listSkills",p=>m.listSkills(p.params)),a.registerExtension("_agent/addSkills",p=>m.addSkills(p.params)),a.registerExtension("_agent/removeSkills",p=>m.removeSkills(p.params)),a.registerExtension("_agent/getFileTree",p=>m.getFileTree(p.params)),a.registerExtension("_agent/getFileContent",p=>m.getFileContent(p.params)),a.registerExtension("_agent/update",p=>m.updateAgent(p.params)),a.registerExtension("_agent/disconnect",p=>m.disconnectAgent(p.params)),a.registerExtension("_agent/switchModel",p=>m.switchModel(p.params)),a.registerExtension("_agent/reset",p=>m.resetAgent(p.params)),a.registerExtension("_agent/repair",p=>m.repairAgent(p.params));let _=new Nt({paths:i,handlers:m,sendDetail:p=>a.sendRequest("_agent/detail",p)});g.ref=_,s.onConnect(({initial:p})=>{y.info("frontier upstream connected, triggering detail sync",{initial:p}),_.syncAll(p?"initial-connect":"reconnect").catch(S=>y.warn("detail sync top-level error (ignored)",{err:String(S)}))});let E=new rn({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:u??"",frameworksCache:r.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async p=>{let S=p,I=S?.privatecode,J=S?.pairing_code;if(!I||!J)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ne=Lt(S.env),et=S.handshake_url,On=S.frontier_url,Nn=ju(S.env,et,On),Zr=!!d&&d!==I,es=l!==void 0&&l!==Nn,ts=Zr||es;if(ts){y.warn("pair config switched, resetting agents",{pcChanged:Zr,envChanged:es,previousPc:d?zo(d):"",nextPc:zo(I),previousEnvKey:l??"",nextEnvKey:Nn});for(let V of[...a.agents.values()])await V.dispose("pair config switch").catch(()=>{}),a.agents.delete(V.agentId);await s.swap(new xt,"pair switch").catch(()=>{})}let ns=await _s({privatecode:I,...et?{endpoint:et}:{},ppeOverride:Ne});u=ns.deviceId,Mn({deviceId:u,pid:process.pid});let na=new En({handshake:ns,privatecode:I,...On?{urlOverride:On}:{},ppeOverride:Ne});await s.swap(na,"pair");try{let V=new $e;r.frameworksCache=await V.detectAll(),await ze(r),y.info("frameworks_cache refreshed before pair",{detected:Object.keys(r.frameworksCache)})}catch(V){y.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(V)})}let ra=Object.keys(r.frameworksCache??{});try{let V=await a.sendRequest("_agent/pair",{pairCode:J,patToken:I,frameworks:ra,_meta:{cozeDeviceId:u}});y.info("_agent/pair ok",{pairResult:V}),d=I,l=Nn,f||(f=new $t({core:a,getDeviceId:()=>u??""})),f.start(),ts&&qo(i,c).catch(be=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(be)}));let bn;return S.agent_id&&(bn=await Vu(S.agent_id,i,c,be=>a.sendRequest("_agent/detail",be)).catch(be=>(y.error("--agent-id ensureAgent failed",{agentId:S.agent_id,err:String(be)}),{ok:!1,agentId:S.agent_id??"",note:String(be)}))),{ok:!0,note:"paired with cloud",...bn?{agent:bn}:{}}}catch(V){return y.error("_agent/pair failed",{err:String(V)}),{ok:!1,note:`pair failed: ${String(V)}`}}}},{method:"POST",path:"/_agent/create",handler:async p=>{let S=p;return{ok:!0,result:await c.createAgent(S)}}},{method:"POST",path:"/refresh",handler:async()=>{y.info("IPC /refresh: re-detecting frameworks");let p=new $e;return r.frameworksCache=await p.detectAll(),await ze(r),{ok:!0,frameworks:r.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{M.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:L,token:B}=await E.start();await a.start(),qo(i,c).catch(p=>y.warn("auto-revive top-level error (ignored)",{err:String(p)}));let re=null,M={port:L,token:B,core:a,ipc:E,shutdown(p){return re||(y.info("daemon shutdown",{reason:p}),re=(async()=>{f?.stop(),await a.stop(p),await E.stop(),await n.release()})(),re)}};for(let p of["SIGTERM","SIGINT"])process.on(p,()=>{M.shutdown(p).then(()=>process.exit(0))});return y.info("daemon ready",{port:L,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(r.frameworksCache??{}),libVersion:r.libVersion??"dev"}),M}function zo(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function ju(n,e,t){return`${n??""}|${e??""}|${t??""}`}async function Ju(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return}let{loadAgentConfig:s,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(fe(),Ot));for(let o of r){await i(o,n).catch(a=>y.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await s(o,n);a?.disconnectedAt&&(e.disconnectedAgents.add(o),y.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){y.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function Vu(n,e,t,r){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(fe(),Ot)),i=await s(n,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:n,framework:i.framework,hadDisconnect:!!i.disconnectedAt});let d={agentId:i.agentId,framework:i.framework,...i.cozeIdentity?{cozeIdentity:i.cozeIdentity}:{},...i.model?{model:i.model}:{}};return await t.createAgent(d),{ok:!0,agentId:n,note:i.disconnectedAt?"revived from local config":"connected from local config"}}y.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let o=await r({_meta:{cozeAgentId:n}});if(!o.framework)throw new h("AGENT_NOT_FOUND",`agent ${n} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let a={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...o.deployType?{_meta:{cozeDeployType:o.deployType}}:{}};await t.createAgent(a);let c=o.deployType==="cloud"&&o.framework==="openclaw";return{ok:!0,agentId:n,note:c?"cloud agent acknowledged":"created from cloud detail"}}async function qo(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(r.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(fe(),Ot));y.info("auto-revive: scanning local agents on startup",{count:r.length});let i=0,o=0;for(let a of r){let c;try{c=await s(a,n)}catch(d){y.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(d)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){y.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{y.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework}),await e.createAgent({agentId:c.agentId,framework:c.framework,...c.cozeIdentity?{cozeIdentity:c.cozeIdentity}:{},...c.model?{model:c.model}:{},...c.deployType?{_meta:{cozeDeployType:c.deployType}}:{}}),i+=1}catch(d){y.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(d)}),o+=1}}return y.info("auto-revive: done",{revived:i,skipped:o,total:r.length}),{revived:i,skipped:o,total:r.length}}Gr();U();import{readFile as Wo}from"node:fs/promises";var Se=class{paths;constructor(e){this.paths=e??T()}async probe(e=1e3){let t=await this.readAuth();if(!t)return{kind:"not-running"};try{let r=await this.fetch(t,{method:"GET",path:"/status",timeoutMs:e});return r.status===200?{kind:"connected",...t}:{kind:"stale",reason:`unexpected status ${r.status}`}}catch(r){return{kind:"stale",reason:rf(r)}}}async request(e){let t=await this.readAuth();if(!t)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(t,e)}async readAuth(){try{let[e,t]=await Promise.all([Wo(this.paths.portFile,"utf8"),Wo(this.paths.tokenFile,"utf8")]),r=Number.parseInt(e.trim(),10),s=t.trim();return!Number.isFinite(r)||r<=0||!s?null:{port:r,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,t){let r=t.body!==void 0,s={Authorization:`Bearer ${e.token}`};r&&(s["content-type"]="application/json");let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${t.path}`,{method:t.method,headers:s,body:r?JSON.stringify(t.body):void 0,signal:i.signal}),c=await a.text();return{status:a.status,body:nf(c)}}finally{clearTimeout(o)}}};function nf(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function rf(n){return n instanceof Error?n.message:String(n)}k();U();import{copyFile as jo,mkdir as sf,readFile as Hr,writeFile as of}from"node:fs/promises";import{dirname as af,resolve as Wr,sep as xn}from"node:path";import{fileURLToPath as cf}from"node:url";k();U();var Jo=w("dist-install");function df(n){let e=cf(n),t=af(e),r=`${xn}src${xn}`;if(t.includes(r)||t.endsWith(`${xn}src${xn}cli`))return null;let s=Wr(t,"index.js"),i=Wr(t,"..","package.json");return{dist:s,pkgJson:i}}async function Vo(n={}){let e=n.paths??T(),t=df(import.meta.url),r=n.sourceDist??t?.dist,s=n.sourcePackageJson??t?.pkgJson;if(!r||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let i;try{i=JSON.parse(await Hr(s,"utf8")).version??"unknown"}catch(u){return Jo.warn("cannot read source package.json,skip dist install",{err:String(u)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(u)}`}}let o=await tn(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Hr(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await sf(e.libDir,{recursive:!0}),await jo(r,e.libEntry),await jo(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Wr(e.libDir,"package.json"),d=`${JSON.stringify({type:"module"},null,2)}
94
- `;return await Hr(c,"utf8").catch(()=>null)!==d&&await of(c,d),o.libVersion=i,await ze(o,e.configFile),Jo.info("dist installed",{libEntry:e.libEntry,fromVersion:a,toVersion:i}),a?{kind:"version-changed",fromVersion:a,toVersion:i,libEntry:e.libEntry}:{kind:"first-install",libVersion:i,libEntry:e.libEntry}}var Pf=w("cli");function Ze(n,e){let t=[],r;for(let s=0;s<n.length;s++){let i=n[s];if(i===e){r=n[s+1],s+=1;continue}if(i.startsWith(`${e}=`)){r=i.slice(e.length+1);continue}t.push(i)}return{value:r,rest:t}}function Af(n){let e=n.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let t=e,{value:r,rest:s}=Ze(t,"--pat-token");t=s;let{value:i,rest:o}=Ze(t,"--pair-code");t=o;let{value:a,rest:c}=Ze(t,"--env");t=c;let{value:d,rest:l}=Ze(t,"--handshake-url");t=l;let{value:u,rest:f}=Ze(t,"--frontier-url");t=f;let{value:g}=Ze(t,"--agent-id");if(!r||!i)return{mode:"help"};let m={mode:"pair",privatecode:r,pairingCode:i};return a&&(m.env=a),d&&(m.handshakeUrl=d),u&&(m.frontierUrl=u),g&&(m.agentId=g),m}var Cf=`
88
+ ${c}`}var Se=R("agent-detail-sync"),un=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await B0(i)}catch(c){Se.info("agents dir not found, skip detail sync",{root:i,err:String(c)});return}Se.info("starting detail sync",{reason:e,count:a.length});for(let c of a)try{await this.syncOne(c)}catch(u){Se.warn("detail sync failed for agent, skipping",{agentId:c,err:String(u)})}Se.info("detail sync done",{reason:e})}async syncOne(e){let i=await fe(e,this.opts.paths);if(!i){Se.info("detail sync: agent config missing, skip",{agentId:e});return}let a;try{a=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(d){Se.warn("detail RPC failed, using local data",{agentId:e,err:String(d)});return}if(a.agentId&&a.agentId!==e){Se.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:a.agentId});return}let c=!1,u=!1;if(a.agentName&&a.agentName!==i.agentName&&(i.agentName=a.agentName,c=!0),a.description!==void 0&&a.description!==i.description&&(i.description=a.description,c=!0),a.cozeIdentity&&a.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=a.cozeIdentity,c=!0,u=!0),a.deployType&&Se.info("detail.deployType",{agentId:e,deployType:a.deployType}),!c){Se.debug("detail sync: no diff",{agentId:e});return}await we(i,this.opts.paths),Se.info("detail sync: config updated",{agentId:e,identityChanged:u,agentName:i.agentName}),u&&(await dt(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ge();import{spawn as ci}from"node:child_process";import{lstat as kr,mkdir as U0,readFile as xi,readdir as H0,rm as G0,stat as K0,writeFile as j0}from"node:fs/promises";import{join as Me,normalize as W0,relative as ui,resolve as J0,sep as fi}from"node:path";var Ee={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",DELETE:"_agent/delete"};function Lt(r){return r?.cozeDeployType==="cloud"?"cloud":"local"}function js(r){let{_meta:e,...i}=r;return{stripped:i,meta:e}}function lt(r){if(!r?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return r.cozeAgentId}var S=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();ue();function Le(r,e){if(Lt(r)!=="cloud")throw new S("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Mt(r){return r.replace(/[^A-Za-z0-9._-]+/g,"-")}K();var fn="1008033",Ws="1289";var Js="pbbp2",Vs="https://www.coze.cn",Ys="/api/coze_claw/resource/get_frontier_key",z0="https://www.coze.cn",q0="wss://frontier.coze.cn";function Xs(r){return r??process.env.COZE_BRIDGE_HANDSHAKE_URL??z0}function $s(r){return r??process.env.COZE_BRIDGE_FRONTIER_URL??q0}function dn(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}function ln(r){return r?r.startsWith("boe_")?{ttEnv:r}:{ttEnv:r,usePpe:"1"}:{}}var Qs=R("handshake");async function Zs(r){let e=Xs(r.endpoint),i=r.timeoutMs??1e4,a=`${F0(e)}${Ys}?aid=${encodeURIComponent(fn)}`,c={Authorization:`Bearer ${r.privatecode}`,Accept:"application/json",...dn(r.ppeOverride)},u=new AbortController,d=setTimeout(()=>u.abort(),i);Qs.info("frontier key handshake",{base:e});try{let g=await fetch(a,{method:"GET",headers:c,signal:u.signal}),m=g.headers.get("x-tt-logid")??"",w=g.headers.get("x-tt-trace-id")??"";if(!g.ok){let D=await g.text().catch(()=>"");throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${g.status} logid=${m}: ${D.slice(0,200)}`)}let v=await g.json();if(v.code!==void 0&&v.code!==0)throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${v.code} msg=${v.msg??"-"} logid=${m}`);let y=v.data?.access_key,E=v.data?.device_id;if(!y||!E)throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${m}: ${JSON.stringify(v)}`);return Qs.info("handshake ok",{remoteDeviceId:E,logid:m,traceId:w}),{accessKey:y,deviceId:E}}catch(g){throw g instanceof S?g:g.name==="AbortError"?new S("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${i}ms)`):new S("UPSTREAM_HANDSHAKE_FAILED",String(g),{cause:g})}finally{clearTimeout(d)}}function F0(r){return r.endsWith("/")?r.slice(0,-1):r}var Ar="https://llm-gateway.coze.cn",Ke="auto";function ei(r){return{model:r.model??Ke,...r.modelToken?{modelToken:r.modelToken}:{}}}function Ot(r){return!r||r===Ke}function ti(r){let e={};return r.modelToken?(e.ANTHROPIC_BASE_URL=Ar,e.ANTHROPIC_AUTH_TOKEN=r.modelToken,e.ANTHROPIC_MODEL=r.model||Ke):Ot(r.model)||(e.ANTHROPIC_MODEL=r.model),e}function ni(r){let e=[];return r.modelToken?e.push("-c",`model="${r.model||Ke}"`):Ot(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="${Ar}/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 ri(r){return r.modelToken?{OPENAI_API_KEY:r.modelToken}:{}}function Pr(r){let{ttEnv:e,usePpe:i}=ln(r),a={};return e&&(a["x-tt-env"]=e),i&&(a["x-use-ppe"]=i),a}function si(r,e){if(!r.modelToken)return{};let i=Pr(e);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,u])=>`${c}:${u}`).join(`
89
+ `)}}function Dr(r){return`coze-session-${r.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ii(r,e){if(!r.modelToken||Ot(r.model))return null;let i=Pr(e),a={baseUrl:`${Ar}/v1`,api:"openai-completions",apiKey:r.modelToken,models:[{id:r.model,name:r.model,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(a.headers=i),a}function oi(r,e){if(!r.modelToken)return[];let i=Pr(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var se=R("agent-handlers"),ai=5*1024*1024,V0=1,Y0=6,X0=new Set(["node_modules",".git",".coze","dist","build",".next"]),gn=class{constructor(e){this.opts=e}opts;async listSkills(e){Le(e._meta,"_agent/listSkills");let i=lt(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Ne(i).workspace,u=a?.skills??[],d=[];for(let g of u){let m=Me(c,g.relPath,"SKILL.md");await K0(m).then(v=>v.isFile()).catch(()=>!1)&&d.push({skillId:g.skillId,skillName:g.skillName,downloadUrl:g.downloadUrl??"",...g.description?{description:g.description}:{},...g.version?{version:g.version}:{}})}return{skills:d}}async addSkills(e){Le(e._meta,"_agent/addSkills");let i=lt(e._meta),a=await this.requireAgentCfg(i),c=e.skills??[],u=[...a.skills??[]],d=new Map(u.map((m,w)=>[m.skillId,w])),g=[];for(let m of c){if(!m.skillName)throw new S("IPC_BAD_REQUEST","skill missing skillName");let w=$0(m.skillName),v=Q0(a.framework),y=Me(v,w),E=Me(a.workspace,y);await U0(E,{recursive:!0});let D=await tc(m.downloadUrl);rc(D)?await sc(D,E):await j0(Me(E,"SKILL.md"),D.toString("utf8"),"utf8");let k={skillId:m.skillId,skillName:m.skillName,relPath:y,installedAt:Date.now(),...m.description?{description:m.description}:{},...m.version?{version:m.version}:{},...m.downloadUrl?{downloadUrl:m.downloadUrl}:{}},T=d.get(m.skillId);T!==void 0?u[T]=k:(d.set(m.skillId,u.length),u.push(k)),g.push(m),se.info("skill installed",{agentId:i,skillId:m.skillId,skillName:m.skillName,relPath:y})}return await cn(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:g}}async removeSkills(e){Le(e._meta,"_agent/removeSkills");let i=lt(e._meta),a=await this.requireAgentCfg(i),c=new Set(e.skillIds??[]),u=a.skills??[],d=[];for(let g of u){if(!c.has(g.skillId)){d.push(g);continue}let m=Me(a.workspace,g.relPath);await G0(m,{recursive:!0,force:!0}),se.info("skill removed",{agentId:i,skillId:g.skillId,relPath:g.relPath})}return await cn(i,d),await this.reloadAgentSessions(i,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,i){return this.reloadAgentSessions(e,i)}async reloadAgentSessions(e,i){let a=this.opts.agents.get(e);if(a&&a.framework!=="codex"){for(let[c,u]of a.sessions)if(!(!u.downstream||!u.acpSessionId)){u.loadingSession=!0;try{await u.downstream.sessionLoad({sessionId:u.acpSessionId,cwd:a.workspace}),se.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(d){se.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId,err:String(d)})}finally{u.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return se.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await fe(i);if(!a)throw new S("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(se.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await we(a),await dt(a.workspace,a.framework,i,e.cozeIdentity),se.info("_agent/update: cozeIdentity rewritten",{agentId:i,framework:a.framework}),await this.reloadAgentSessions(i,"identity-changed"),{ok:!0})}async disconnectAgent(e){let i=e.agentId;if(!i)throw new S("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let a=await fe(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await we(a),se.info("agent disconnected",{agentId:i,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(i,e.reason??"disconnect"),{ok:!0}):(se.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Le(e._meta,"_agent/switchModel"),!e.agentId)throw new S("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:Ke,a=await fe(e.agentId);if(!a)throw new S("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await we(a),se.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return se.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};c.model=i;let u=[];for(let[d,g]of c.allSessionQueues())u.push(g.enqueue(async()=>{let m=c.sessions.get(d);m?.downstream&&(await m.downstream.stop(`switchModel: ${i}`).catch(()=>{}),m.downstream=void 0)}));return await Promise.all(u),se.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:i,cloudSessions:u.length}),{ok:!0}}async resetAgent(e){if(Le(e._meta,Ee.RESET),!e.agentId)throw new S("IPC_BAD_REQUEST",`${Ee.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Ee.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Le(e._meta,Ee.REPAIR),!e.agentId)throw new S("IPC_BAD_REQUEST",`${Ee.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new S("IPC_BAD_REQUEST",`${Ee.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){se.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(a)})}return await this.runDetailSync(e.agentId,Ee.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){se.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){se.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(c)})}}async getFileTree(e){Le(e._meta,"_agent/getFileTree");let i=e._meta,a=lt(i),c=await this.resolveWorkspace(a),u=e.filePath??"",d=this.safeJoin(c,u),g=await kr(d).catch(()=>null);if(!g)throw new S("IPC_BAD_REQUEST",`path not found: ${u}`);if(g.isSymbolicLink())throw new S("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let m=oc(e.depth);return g.isDirectory()?{tree:await di(c,d,u,m)}:{tree:[{name:ac(u),path:li(u||"."),isDir:!1,size:g.size,modifiedAt:Math.floor(g.mtimeMs)}]}}async getFileContent(e){Le(e._meta,"_agent/getFileContent");let i=lt(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new S("IPC_BAD_REQUEST","filePath required");let c=this.safeJoin(a,e.filePath),u=await kr(c).catch(()=>null);if(!u||!u.isFile())throw new S("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new S("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>ai)throw new S("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${ai})`);let d=await xi(c);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:u.size}:{content:d.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await fe(e).catch(()=>null))?.workspace??Ne(e).workspace}safeJoin(e,i){let a=J0(e,i||"."),c=ui(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${fi}`))throw new S("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return fe(e)}async requireAgentCfg(e){let i=await this.loadAgentCfg(e);if(!i)throw new S("AGENT_NOT_FOUND",`no config for agent: ${e}`);return i}};function $0(r){let e=Mt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new S("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function Q0(r){return r==="claude-code"?Me(".claude","skills"):Me(".agents","skills")}var Z0=3e4,ec=50*1024*1024,pn=3e4;async function tc(r){if(!r)throw new S("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);hn(e);let i=nc(r);return hn(i.length),i}if(r.startsWith("file:")){let e=new URL(r).pathname,i=await xi(e);return hn(i.length),i}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),Z0);try{let a=await fetch(r,{signal:e.signal});if(!a.ok)throw new S("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${r}`);let c=await a.arrayBuffer();return hn(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new S("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function hn(r){if(r>ec)throw new S("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function nc(r){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(r);if(!e)throw new S("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 rc(r){return r.length>=2&&r[0]===31&&r[1]===139}async function sc(r,e){await ic(r),await new Promise((i,a)=>{let c=ci("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";c.stderr?.on("data",g=>{u+=String(g)});let d=setTimeout(()=>{c.kill("SIGKILL"),a(new S("IPC_BAD_REQUEST",`tar extract timeout (${pn}ms)`))},pn);c.on("error",g=>{clearTimeout(d),a(new S("IPC_BAD_REQUEST",`tar spawn failed: ${g.message}`,{cause:g}))}),c.on("exit",g=>{clearTimeout(d),g===0?i():a(new S("IPC_BAD_REQUEST",`tar exit ${g}${u?`: ${u.trim().slice(0,200)}`:""}`))}),c.stdin?.end(r)})}async function ic(r){let e=await new Promise((i,a)=>{let c=ci("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",d="";c.stdout?.on("data",m=>{u+=String(m)}),c.stderr?.on("data",m=>{d+=String(m)});let g=setTimeout(()=>{c.kill("SIGKILL"),a(new S("IPC_BAD_REQUEST",`tar list timeout (${pn}ms)`))},pn);c.on("error",m=>{clearTimeout(g),a(new S("IPC_BAD_REQUEST",`tar list spawn failed: ${m.message}`))}),c.on("exit",m=>{clearTimeout(g),m===0?i(u):a(new S("IPC_BAD_REQUEST",`tar list exit ${m}${d?`: ${d.trim().slice(0,200)}`:""}`))}),c.stdin?.end(r)});for(let i of e.split(`
90
+ `)){let a=i.trim();if(!a)continue;let c=a.charCodeAt(0);if(c!==45&&c!==100)throw new S("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 S("IPC_BAD_REQUEST",`tar entry absolute path: ${d}`);if(d.split(/[/\\]/).some(m=>m===".."))throw new S("IPC_BAD_REQUEST",`tar entry contains '..': ${d}`)}}async function di(r,e,i,a){if(a<=0)return[];let c;try{c=await H0(e,{withFileTypes:!0})}catch{return[]}let u=[];for(let d of c){if(X0.has(d.name)||d.isSymbolicLink())continue;let g=Me(e,d.name),m=W0(Me(i,d.name)),w=null;try{w=await kr(g)}catch{continue}if(w.isSymbolicLink())continue;let v={name:d.name,path:li(ui(r,g)),isDir:w.isDirectory(),size:w.size,modifiedAt:Math.floor(w.mtimeMs)};w.isDirectory()&&a>1&&(v.children=await di(r,g,m,a-1)),u.push(v)}return u.sort((d,g)=>d.isDir!==g.isDir?d.isDir?-1:1:d.name.localeCompare(g.name)),u}function oc(r){return!r||r<=0?V0:Math.min(r,Y0)}function ac(r){if(!r||r==="."||r==="/")return".";let e=r.split(/[/\\]/);return e[e.length-1]||"."}function li(r){return r.split(fi).join("/")}K();import{readFileSync as rl}from"node:fs";import{dirname as il,join as ol}from"node:path";import{fileURLToPath as cl}from"node:url";var mn="0.1.29";var Bt=R("agent-health-reporter"),cc=1e4,wn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??cc}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()}),Bt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Bt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Bt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Bt.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let i=[];for(let c of this.opts.core.agents.values()){let u=xc(c);u&&i.push({agentId:c.agentId,status:u})}if(i.length===0)return;let a={agents:i,bridgeVersion:mn,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",a)}catch(c){Bt.warn("heartbeat batch send failed",{count:i.length,err:String(c)})}}finally{this.inFlight=!1}}};function xc(r){return r.status==="error"?"error":r.activeTriggers.size>0?"busy":r.status==="ok"?"online":null}Ge();import{mkdir as Ir,rm as Bc}from"node:fs/promises";K();import{execFile as uc}from"node:child_process";import{promisify as fc}from"node:util";var gi=fc(uc),zt=R("agents.acp-installer"),dc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},lc=5e4,hc=5e3,gc=5*6e4,yn=new Map,_n=new Map,Tr=new Map;async function hi(r){let e=process.platform==="win32"?"where":"which";try{let{stdout:i}=await gi(e,[r],{timeout:hc});return i.split(`
91
+ `)[0]?.trim()||void 0}catch{return}}async function pc(r){zt.info("npm install -g start",{npmPackage:r}),await gi("npm",["install","-g",`${r}@latest`],{timeout:lc,maxBuffer:10*1024*1024}),zt.info("npm install -g done",{npmPackage:r})}async function pi(r){let e=dc[r];if(!e)return;let i=yn.get(r);if(i)return i;let a=_n.get(r);if(a&&Date.now()-a<gc)return;let c=Tr.get(r);if(c)return c;let u=(async()=>{let d=await hi(e.binary);if(d)return yn.set(r,d),zt.info("acp wrapper found on PATH",{binary:e.binary,path:d}),d;try{await pc(e.npmPackage)}catch(m){zt.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(m)}),_n.set(r,Date.now());return}let g=await hi(e.binary);if(!g){zt.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),_n.set(r,Date.now());return}return yn.set(r,g),_n.delete(r),g})().finally(()=>{Tr.delete(r)});return Tr.set(r,u),u}function vn(r){return yn.get(r)}import{spawn as vc}from"node:child_process";function qt(r,e,i){return i===void 0?{jsonrpc:"2.0",id:r,method:e}:{jsonrpc:"2.0",id:r,method:e,params:i}}function bn(r,e){return e===void 0?{jsonrpc:"2.0",method:r}:{jsonrpc:"2.0",method:r,params:e}}function ht(r,e){return{jsonrpc:"2.0",id:r,result:e}}function Ze(r,e){return{jsonrpc:"2.0",id:r,error:e}}var Sn=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 mi(r){return"method"in r&&"id"in r&&r.id!==void 0}function wi(r){return"method"in r&&!("id"in r)}function En(r){return!("method"in r)&&"id"in r}var mc={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 Ft(r){return r instanceof S?{code:mc[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 _i(r){let e=r.data,i=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new S(i,r.message,{retriable:e?.retriable??!1,cause:r.data})}function yi(r){return`${JSON.stringify(r)}
92
+ `}var Cn=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(`
93
+ `);this.buffer=i.pop()??"";let a=[];for(let c of i){let u=c.replace(/\r$/,"").trim();if(u)try{a.push(JSON.parse(u))}catch(d){this.onError?.({line:u,error:d})}}return a}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(i){return this.onError?.({line:e,error:i}),[]}}};var bi={"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"},Sl=Object.fromEntries(Object.entries(bi).map(([r,e])=>[e,r])),wc={"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:[]},gt=class{seq=0;next(e,i){this.seq+=1;let a=bi[e]??_c(e),c=wc[a]??[],u=[a,String(this.seq)];if(c.length>0){let d=c.map(m=>vi(i?.[m]??"")),g=yc(d).join(":");g&&u.push(g)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>vi(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function _c(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function vi(r){return r.replace(/[:_\s]+/g,"-")}function yc(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}K();var bc=3e4,Sc=50,Ec=20,Si=500;function Cc(r){try{let e=JSON.stringify(r);return e===void 0||e.length<=Si?r:`${e.slice(0,Si)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ei(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var je=class{constructor(e){this.opts=e;this.log=R(`downstream.${this.constructor.name}`),this.decoder=new Cn({onError:i=>this.log.warn("decode line failed",{line:i.line})})}opts;child;decoder;pending=new Map;idAllocator=new gt;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new S("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=vc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=i,i.stdout?.setEncoding("utf8"),i.stdout?.on("data",a=>{for(let c of this.decoder.push(a))this.dispatch(c)}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{let c=a.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Sc&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.on("exit",(a,c)=>{this.stopped=!0,(a!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:a,signal:c,recentStderr:this.stderrRing.slice(-Ec)}),this.failAllPending(new S("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${c})`));for(let d of this.exitHandlers)d(a,c)}),i.on("error",a=>{this.log.error("child error",{err:String(a)}),this.failAllPending(new S("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()));Ei(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||Ei(i.pid,"SIGKILL")},5e3);try{await a}finally{clearTimeout(c)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(bn("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(ht(e,i))}catch(a){this.log.warn("respondAgentRequest write failed",{id:e,err:String(a)})}}respondAgentRequestError(e,i){if(!(!this.child||this.stopped))try{this.writeFrame(Ze(e,i))}catch(a){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(a)})}}onExit(e){this.exitHandlers.push(e)}call(e,i,a=bc){if(!this.child||this.stopped)return Promise.reject(new S("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=qt(c,e,i),d=a>0&&Number.isFinite(a);return new Promise((g,m)=>{let w=d?setTimeout(()=>{this.pending.delete(c),m(new S("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(c,{resolve:g,reject:m,timer:w,method:e});try{this.writeFrame(u)}catch(v){w&&clearTimeout(w),this.pending.delete(c),m(v)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new S("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(yi(e))}dispatch(e){if(En(e)){let i=e.id!==null?this.pending.get(e.id):void 0;if(!i){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),i.timer&&clearTimeout(i.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:i.method,code:e.error.code,message:e.error.message,data:e.error.data}),i.reject(_i(e.error))):(this.log.info("downstream returned result",{id:e.id,method:i.method,result:Cc(e.result)}),i.resolve(e.result));return}if(wi(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(mi(e)){let i=e;this.handleAgentRequest(i).catch(a=>this.log.error("agent request handler failed",{method:i.method,err:String(a)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Ze(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let i of this.agentRequestHandlers)try{await i(e)}catch(a){this.log.error("agentRequestHandler threw",{method:e.method,err:String(a)});try{this.writeFrame(Ze(e.id,Ft(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var Ac="@agentclientprotocol/claude-agent-acp@latest";function Pc(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 An=class extends je{framework="claude-code";constructor(e){let i=vn("claude-code"),[a,c]=i?[i,[]]:["npx",["-y",Ac]],u=e.command??a,d=e.args??c,g={command:u,args:d,cwd:e.cwd,...e.env?{env:e.env}:{}};super(g)}sanitizeEnv(e){return Pc(e)}};import{mkdtempSync as Dc,rmSync as kc}from"node:fs";import{tmpdir as Tc}from"node:os";import{join as Ic}from"node:path";var Rc="@zed-industries/codex-acp@latest",Pn=class extends je{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=vn("codex"),[a,c]=i?[i,[]]:["npx",["-y",Rc]],u=e.command??a,d=e.args??c,g=e.extraArgs?[...d,...e.extraArgs]:d,m=e.isolateCodexHome?Dc(Ic(Tc(),"coze-bridge-codex-home-")):void 0,w=m?{...e.env??{},CODEX_HOME:m}:e.env,v={command:u,args:g,cwd:e.cwd,...w?{env:w}:{}};super(v),this.authMethodId=e.authMethodId,this.codexHomeDir=m}async initialize(e){let i=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),i}async stop(e){if(await super.stop(e),this.codexHomeDir)try{kc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var Ut=class extends je{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let i=e.sessionName??"default",a=["acp","--session",`agent:${e.agentId}:${i}`];e.gatewayToken&&a.push("--token",e.gatewayToken);let c={command:e.command,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(c),this.agentId=e.agentId,this.sessionName=i,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};K();ue();var pt=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;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local"}getSessionQueue(e){let i=this.sessionQueues.get(e);return i||(i=new pt,this.sessionQueues.set(e,i)),i}allSessionQueues(){return this.sessionQueues.entries()}async dispose(e){this.status="stopped";let i=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let a of this.sessionQueues.values())a.dispose(i);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let i=[];for(let[,a]of this.sessions)Ht(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Ht(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}import{spawn as Nc}from"node:child_process";import{homedir as Lc}from"node:os";import{join as Mc}from"node:path";rn();K();async function Pi(){let r=Mc(Lc(),".openclaw/openclaw.json");return(await ft(r))?.gateway?.auth?.token??""}var Ci=R("openclaw.config"),Oc=[0,5e3,5e3],Ai="models.providers.",kn="agents.defaults.models",Tn=class{command;env;retryDelaysMs;queue=new pt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Oc}async withRetry(e,i){let a;for(let c=0;c<this.retryDelaysMs.length;c++){let u=this.retryDelaysMs[c]??0;u>0&&await new Promise(d=>setTimeout(d,u));try{return await i()}catch(d){a=d,Ci.warn("openclaw cli failed, will retry",{label:e,attempt:c+1,err:String(d)})}}throw new S("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${a?.message??"unknown"}`)}runCli(e){return new Promise((i,a)=>{let c=Nc(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`exit ${d}: ${u.trim().slice(0,500)}`))})})}async runCliTolerant(e,i){try{await this.runCli(e)}catch(a){let c=String(a);if(i.some(u=>c.includes(u)))return;throw a}}async bestEffortUnset(e,i){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",i])))}catch(a){Ci.warn(`${e} failed (best-effort)`,{configPath:i,err:String(a)})}}ensureProvider(e,i){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Ai}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Ai}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${kn}[${e}]`,()=>this.runCli(["config","set",kn,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${kn}[${e}]`,`${kn}.${e}`)}ensureAgent(e,i,a){let c=["agents","add",e,"--workspace",i,"--non-interactive"];return a&&c.push("--model",a),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(c,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var We=R("agent-manager"),zc=(r,e,i,a,c,u,d)=>{switch(r){case"claude-code":{let g=c?{...ti(c),...si(c,d)}:void 0;return new An({cwd:i,...g&&Object.keys(g).length>0?{env:g}:{}})}case"codex":{let g=c?[...ni(c),...oi(c,d)]:[],m=c?ri(c):void 0,w=!!c;return new Pn({cwd:i,...g.length>0?{extraArgs:g}:{},...m&&Object.keys(m).length>0?{env:m}:{},...w?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ut({command:e,cwd:i,agentId:a,...u?{sessionName:Mt(u)}:{}})}};function Di(r){return r==="claude-code"||r==="codex"}var qc={path:"",version:"cloud-deployed"},Fc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Uc=6e4,In=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??zc,this.createTimeoutMs=e.createTimeoutMs??Uc}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new S("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new Tn({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new S("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new S("IPC_BAD_REQUEST","framework required");let i=Lt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new S("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")We.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(E=>We.warn("dispose stale agent failed (ignored)",{err:String(E)})),this.registry.unregister(e.agentId);else return We.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}if(!i&&!this.config.frameworksCache?.[e.framework])throw new S("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);i&&Di(e.framework)&&await pi(e.framework);let u=Ne(e.agentId,this.paths),d=e.workspace??u.workspace,g=Lt(e._meta),m=new AbortController,w=setTimeout(()=>m.abort(new S("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),v,y=!1;try{let E=()=>{if(m.signal.aborted)throw m.signal.reason instanceof Error?m.signal.reason:new S("AGENT_TIMEOUT","_agent/create aborted")};await Ir(u.root,{recursive:!0}),await Ir(d,{recursive:!0}),await Ir(u.logs,{recursive:!0}),E(),await dt(d,e.framework,e.agentId,e.cozeIdentity),E();let D=await fe(e.agentId,this.paths).catch(()=>null),k=ei({model:e.model??D?.model});if(v=new Dn({agentId:e.agentId,framework:e.framework,workspace:d,model:k.model??Ke,deployType:g}),v.status="ok",D?.sessions){for(let[ie,te]of Object.entries(D.sessions))v.sessions.set(ie,{acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let H=Object.keys(D.sessions).length;H>0&&We.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:H})}this.registry.register(v),y=!0;let T={agentId:e.agentId,framework:e.framework,workspace:d,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:k.model};return g==="cloud"&&(T.deployType="cloud"),D?.skills&&(T.skills=D.skills),D?.agentName&&(T.agentName=D.agentName),D?.description&&(T.description=D.description),await we(T,this.paths),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,d):We.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId})),We.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:g}),{ok:!0,agentId:e.agentId,workspace:d,framework:e.framework}}catch(E){throw We.error("agent create failed, rolling back",{agentId:e.agentId,err:String(E)}),y&&v&&(await v.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Bc(u.root,{recursive:!0,force:!0}).catch(D=>We.warn("rm agent dir failed (ignored)",{err:String(D)})),E instanceof S?E:new S("AGENT_SPAWN_FAILED",String(E),{cause:E})}finally{clearTimeout(w)}}async spawnSessionDownstream(e,i,a,c){let d=this.config.frameworksCache?.[e.framework];if(!d)if(e.deployType==="cloud"&&Di(e.framework))d=qc;else throw new S("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let g=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,m;e.framework==="openclaw"?m=await this.buildOpenclawDownstream({session:e,modelConfig:g,cloudSessionId:a,cozeEnv:c,command:d.path}):m=this.factory(e.framework,d.path,e.workspace,e.agentId,g,a,c);try{return await m.start(),await m.initialize(Fc),m}catch(w){throw await m.stop("spawnSessionDownstream failed").catch(()=>{}),w instanceof S?w:new S("AGENT_SPAWN_FAILED",w instanceof Error?w.message:String(w),{cause:w})}}async buildOpenclawDownstream(e){let{session:i,modelConfig:a,cloudSessionId:c,cozeEnv:u,command:d}=e,g=Mt(c),m=await Pi(),w=a?.modelToken&&!Ot(a.model)?ii(a,u):null,v;if(w){let y=Dr(c),E=`${y}/${a.model}`;if(!this.ensuredProviders.has(E)){let D=this.getOpenclawConfig();await D.ensureProvider(y,w),await D.addModelToAllowlist(E),this.ensuredProviders.add(E)}v=E}return new Ut({command:d,cwd:i.workspace,agentId:i.agentId,sessionName:g,...m?{gatewayToken:m}:{},...v?{slashModelOnStart:v}:{}})}async openclawRepair(e,i){let a=this.getOpenclawConfig();await a.deleteAgent(e),await a.ensureAgent(e,i)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let i=this.openclawConfigCache;for(let a of e.sessions.keys()){let c=Dr(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};K();import{spawn as Hc}from"node:child_process";import{constants as ki,access as Gc}from"node:fs/promises";import{delimiter as Kc,join as jc}from"node:path";var Wc=R("framework-detector"),Ti={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Jc=[".exe",".cmd",".bat",".ps1"],mt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Hc,access:e.access??Gc}}async detect(e){let i=Ti[e],a=await this.which(i);if(!a)return Wc.debug("framework binary not found",{framework:e,bin:i}),null;let c=await this.probeVersion(a);return{path:a,version:c}}async detectAll(){let e=await Promise.all(Object.keys(Ti).map(async a=>[a,await this.detect(a)])),i={};for(let[a,c]of e)c&&(i[a]=c);return i}async which(e){let i=this.env.pathEnv.split(Kc).filter(Boolean),a=this.env.platform==="win32"?["",...Jc]:[""];for(let c of i)for(let u of a){let d=jc(c,e+u);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?ki.F_OK:ki.X_OK;return await this.env.access(e,i),!0}catch{return!1}}async probeVersion(e){return new Promise(i=>{let a="",c=!1,u,d=g=>{c||(c=!0,u&&clearTimeout(u),i(g.trim()||"unknown"))};try{let g=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});u=setTimeout(()=>{g.kill("SIGKILL"),d("unknown")},5e3),g.stdout?.on("data",m=>{a+=m.toString("utf8")}),g.on("error",()=>d("unknown")),g.on("close",()=>{let m=Yc(a).split(/\r?\n/)[0]??"";d(m)})}catch{d("unknown")}})}},Vc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Yc(r){return r.replace(Vc,"")}rn();ue();var Xc=10*6e4;function Ii(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Xc:e}function Rn(r){return ft(r??W().configFile)}function wt(r,e){return nn(e??W().configFile,r)}import{randomBytes as ix}from"node:crypto";import{mkdir as $c,readFile as Qc,realpath as Zc,writeFile as ex}from"node:fs/promises";import{basename as tx,dirname as Rr,join as nx,relative as rx,resolve as Ri,sep as sx}from"node:path";K();var Li=R("fs-rpc");async function Mi(r,e){let i=await Bi(r.path,e);return await $c(Rr(i),{recursive:!0}),await ex(i,r.content,"utf8"),Li.info("fs/write_text_file ok",{path:i,size:r.content.length}),null}async function Oi(r,e){let i=await Bi(r.path,e),a=await Qc(i,"utf8"),c=a;if(typeof r.line=="number"||typeof r.limit=="number"){let u=a.split(`
94
+ `),d=Math.max(0,(r.line??1)-1),g=typeof r.limit=="number"?d+r.limit:void 0;c=u.slice(d,g).join(`
95
+ `)}return Li.info("fs/read_text_file ok",{path:i,size:c.length}),{content:c}}async function Bi(r,e){if(typeof r!="string"||r.length===0)throw new S("IPC_BAD_REQUEST","path must be a non-empty string");let[i,a]=await Promise.all([Ni(Ri(e)),Ni(Ri(r))]),c=rx(i,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${sx}`))throw new S("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return a}async function Ni(r){let e=[],i=r;for(;i!==Rr(i);)try{let a=await Zc(i);return e.length?nx(a,...e.reverse()):a}catch{e.push(tx(i)),i=Rr(i)}return r}Ge();K();var B=R("core"),ox=3e4,ax=3e4,Nn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new gt;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=Ii(e.bridgeConfig)}registerExtension(e,i){this.extensions[e]=i}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),B.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){B.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),B.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){B.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)&&B.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,i,a){let c=a.downstream;c&&(c.onUpdate(u=>{a.loadingSession||this.forwardUpdate(e,u)}),c.onAgentRequest(u=>{this.handleAgentRequest(e,c,u)}),c.onExit((u,d)=>{B.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),Ht(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(En(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let i="id"in e&&e.id!==void 0?e.id:null,a=e.params?._meta?.cozeEnv;a&&(this.currentCozeEnv=a);try{if(e.method.startsWith("_agent/")){let c=this.extensions[e.method];if(!c){i!==null?await this.sendError(i,J.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):B.warn("drop notification: extension not registered",{method:e.method});return}let u=await c(e,this);i!==null&&await this.upstream.send(ht(i,u));return}if(e.method.startsWith("session/")){let c=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(ht(i,c));return}if(e.method==="initialize"){i!==null&&await this.upstream.send(ht(i,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}i!==null?await this.sendError(i,J.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):B.warn("drop unknown notification",{method:e.method})}catch(c){B.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send(Ze(i,Ft(c)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new S("IPC_BAD_REQUEST",`${e.method} requires params`);let i=e.params,a=i._meta?.cozeAgentId;if(!a)throw new S("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let c=this.agents.get(a);if(!c)throw this.disconnectedAgents.has(a)?new S("AGENT_DISCONNECTED",`agent ${a} has been disconnected; cloud must _agent/create to revive`):new S("AGENT_NOT_FOUND",`agent not found: ${a}`);let u=typeof i.sessionId=="string"?i.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!u)return this.dispatchSessionCall(c,e.method,i);let d=Date.now(),g=!1;try{let m=await c.getSessionQueue(u).enqueue(()=>this.dispatchSessionCall(c,e.method,i));return g=!0,m}finally{B.info("session call done",{agentId:c.agentId,method:e.method,durationMs:Date.now()-d,ok:g})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:c}=js(a);switch(i){case"session/new":{let u=cx();return B.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return B.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=c,d=u.sessionId;if(!d)throw new S("IPC_BAD_REQUEST","session/prompt: missing sessionId");let g=await this.ensureRuntime(e,d);if(g.replySeq=0,await this.ensureDownstream(e,d,g),!g.downstream||!g.acpSessionId)throw new S("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let m=a._meta?.cozeTriggerMsgId;m?e.activeTriggers.set(g.acpSessionId,m):e.activeTriggers.delete(g.acpSessionId);try{let w=await g.downstream.sessionPrompt({...u,sessionId:g.acpSessionId});return g.lastActiveAt=Date.now(),w}finally{e.activeTriggers.delete(g.acpSessionId),g.downstream?.isAlive()&&this.armIdleTimer(e,d,g)}}case"session/cancel":{let d=c.sessionId;if(!d)throw new S("IPC_BAD_REQUEST","session/cancel: missing sessionId");let g=e.sessions.get(d);return g?.downstream?.isAlive()&&g.acpSessionId&&await g.downstream.sessionCancel({sessionId:g.acpSessionId}),{ok:!0}}default:throw new S("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(i,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let c=await this.sendRequest(Ee.GEN_MODEL_TOKEN,a,ax);if(!c?.modelToken)throw new S("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return c.modelToken}catch(c){throw c instanceof S&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new S("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,i,a){if(Ht(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new S("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let c=await this.sessionSpawner(e,a.modelToken,i,this.currentCozeEnv);if(a.downstream=c,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await c.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),B.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){B.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(u)}),a.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});a.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let u=await c.sessionNew({cwd:e.workspace});a.acpSessionId=u.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&a.acpSessionId&&await c.afterSessionEstablished(a.acpSessionId)}armIdleTimer(e,i,a){if(Ht(a),this.isRuntimeBusy(e,a)){B.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:i});return}a.idleTimer=setTimeout(()=>{if(a.idleTimer=void 0,this.isRuntimeBusy(e,a)){B.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:i}),this.armIdleTimer(e,i,a);return}B.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:i});let c=a.downstream;a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId),c&&c.stop("idle timeout").catch(u=>B.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(u)}))},this.sessionIdleTimeoutMs),a.idleTimer.unref?.()}isRuntimeBusy(e,i){if(i.acpSessionId&&e.activeTriggers.has(i.acpSessionId))return!0;let a=i.downstream;if(!a)return!1;for(let c of this.pendingUpstream.values())if(c.downstream===a)return!0;return!1}forwardUpdate(e,i){let a=i.sessionId,c=this.reverseSessionId(e,a);if(!c){B.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){B.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}if(xx(i)){B.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:a});return}let d={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},g=e.activeTriggers.get(a);g&&(d.cozeTriggerMsgId=g),this.upstream.send(bn("session/update",{...i,sessionId:c,_meta:d})).catch(m=>B.warn("forward update failed",{agentId:e.agentId,err:String(m)}))}handleAgentRequest(e,i,a){if(a.method==="session/request_permission"){this.forwardPermissionRequest(e,i,a);return}if(a.method==="fs/write_text_file"||a.method==="fs/read_text_file"){this.handleFsRpcRequest(e,i,a);return}B.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}`})}async handleFsRpcRequest(e,i,a){try{let c=e.workspace;if(a.method==="fs/write_text_file"){let u=a.params??{},d=await Mi(u,c);i.respondAgentRequest(a.id,d)}else{let u=a.params??{},d=await Oi(u,c);i.respondAgentRequest(a.id,d)}}catch(c){B.warn("fs rpc handler failed",{agentId:e.agentId,method:a.method,err:String(c)}),i.respondAgentRequestError(a.id,Ft(c))}}forwardPermissionRequest(e,i,a){let c=this.upstreamIds.next("session/request_permission"),u=a.params??{},g=u.sessionId,m=g?e.activeTriggers.get(g):void 0,w={cozeAgentId:e.agentId};m&&(w.cozeTriggerMsgId=m);let v=g?this.reverseSessionId(e,g):void 0,y={...u,...v?{sessionId:v}:{},_meta:w};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),B.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:c,acpSessionId:g,cloudSessionId:v,toolCallId:u.toolCall?.toolCallId,options:u.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(qt(c,"session/request_permission",y)).catch(E=>{this.pendingUpstream.delete(c),B.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),i.respondAgentRequestError(a.id,{code:J.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let i=this.pendingUpstream.get(e.id);if(i){this.pendingUpstream.delete(e.id),e.error?(B.info("upstream \u2192 permission response (error)",{agentId:i.agentId,upstreamId:e.id,method:i.method,error:e.error}),i.downstream.respondAgentRequestError(i.agentRequestId,e.error)):(B.info("upstream \u2192 permission response (result)",{agentId:i.agentId,upstreamId:e.id,method:i.method,result:e.result}),i.downstream.respondAgentRequest(i.agentRequestId,e.result));return}let a=this.pendingBridge.get(e.id);if(a){this.pendingBridge.delete(e.id),clearTimeout(a.timer),e.error?a.reject(new Sn(e.error)):a.resolve(e.result);return}B.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=ox){let c=this.upstreamIds.next(e);return new Promise((u,d)=>{let g=setTimeout(()=>{this.pendingBridge.delete(c),d(new S("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(c,{method:e,resolve:u,reject:d,timer:g}),this.upstream.send(qt(c,e,i)).catch(m=>{let w=this.pendingBridge.get(c);w&&(clearTimeout(w.timer),this.pendingBridge.delete(c)),d(m)})})}async persistSessionMapping(e){if(this.paths)try{let i=new Map;for(let[a,c]of e.sessions){let u={modelToken:c.modelToken,tokenGeneratedAt:c.tokenGeneratedAt};c.acpSessionId&&(u.acpSessionId=c.acpSessionId),i.set(a,u)}await Cr(e.agentId,i,this.paths)}catch(i){B.warn("persist session mapping failed",{agentId:e.agentId,err:String(i)})}}reverseSessionId(e,i){for(let[a,c]of e.sessions.entries())if(c.acpSessionId===i)return a}sendError(e,i,a){return this.upstream.send(Ze(e,{code:i,message:a}))}};function cx(){return ix(16).toString("hex")}function xx(r){let e=r.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let i=e.content;if(!i||typeof i!="object")return!1;let a=i;return a.type!=="text"||typeof a.text!="string"?!1:a.text.startsWith("Model metadata for `")}K();ue();import{randomBytes as ux}from"node:crypto";import{chmod as fx,mkdir as dx,writeFile as zi}from"node:fs/promises";import{createServer as lx}from"node:http";import{dirname as hx}from"node:path";var gx=1e6,Nr=R("ipc"),Ln=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??W()}async start(){this.token=ux(32).toString("hex");let e=lx((a,c)=>{this.dispatch(a,c)});this.server=e,await new Promise((a,c)=>{e.once("error",c),e.listen(0,"127.0.0.1",()=>a())});let i=e.address();if(!i||typeof i!="object")throw new Error("failed to obtain IPC port");return this.port=i.port,await this.persistAuthFiles(),Nr.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((i,a)=>{e.close(c=>c?a(c):i())}),this.server=null)}async persistAuthFiles(){await dx(hx(this.paths.portFile),{recursive:!0}),await zi(this.paths.portFile,String(this.port),"utf8"),await zi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await fx(this.paths.tokenFile,384)}catch(e){Nr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Gt(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){Gt(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await px(e)}catch(g){Gt(i,400,{error:"invalid json",detail:String(g)});return}try{let g=await u.handler(d,e);Gt(i,200,g??{ok:!0})}catch(g){Nr.error("IPC handler failed",{key:c,err:String(g)}),Gt(i,500,{error:g instanceof Error?g.message:String(g)})}}};function Gt(r,e,i){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(i))}async function px(r){let e=[],i=0;for await(let c of r){let u=c;if(i+=u.length,i>gx)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var aa=Re(Yi(),1);var $u=Re(jo(),1),Qu=Re(Xn(),1),Zu=Re(vt(),1),ef=Re(Wr(),1),tf=Re(Yr(),1),nf=Re(ts(),1),ea=Re(er(),1),rf=Re(Zo(),1);var ta=ea.default;K();var ee=R("upstream.frontier"),ra="application/json",sa="none",nr=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){ee.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Vs,...dn(this.opts.ppeOverride)};class i extends ta{constructor(g){super(g,Js,{headers:e})}send(g,...m){if(Gs("debug"))try{let w;typeof g=="string"?w=Buffer.from(g,"utf8"):g instanceof Buffer?w=g:g instanceof ArrayBuffer?w=new Uint8Array(g):ArrayBuffer.isView(g)?w=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):w=new Uint8Array(0);let v=Buffer.from(w.slice(0,128)).toString("hex");ee.debug("WS raw frame out",{bytes:w.byteLength,headHex:v})}catch(w){ee.warn("WS raw frame dump failed",{err:String(w)})}super.send(g,...m)}}let a=$s(this.opts.urlOverride),c={url:a,ws:i,fpID:Ws,aID:fn,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ra,force:!0},payloadEncoding:{encoding:sa,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new aa.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;ee.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:d,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:d})).catch(g=>ee.warn("onConnect handler threw (ignored)",{err:String(g)}))},u.onclose=d=>{this.opened=!1,ee.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{ee.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){ee.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new S("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),c=e;ia(c)||ee.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:ra,payloadEncoding:sa})}catch(d){throw ee.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(d)}),new S("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(d)}`,{cause:d})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){ee.debug("drop non-adapter frontier frame",{service:i});return}let a=cf(e);if(!a){ee.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ee.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(d){ee.warn("frontier message JSON parse failed",{err:String(d),head:a.slice(0,80)});return}let u=c;ia(u)||ee.info("frontier frame in",{logid:af(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:u.id,method:u.method,body:of(a)}),Promise.resolve(this.handler(c)).catch(d=>ee.warn("frontier frame handler threw",{err:String(d)}))}};function ia(r){return r.method==="_agent/health"?!0:typeof r.id=="string"&&r.id.startsWith("agent.health_")}var oa=2e3;function of(r){return r.length<=oa?r:`${r.slice(0,oa)}...<truncated, total ${r.length} chars>`}function af(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function cf(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();var rs=R("upstream.switchable"),rr=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;rs.info("swap upstream",{reason:i});let a=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(c){throw rs.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>rs.warn("previous upstream stop threw (ignored)",{err:String(c)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};K();var ss=R("upstream"),Qt=class{handler=null;async start(){ss.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){ss.info("NoopUpstream stopped",{reason:e})}async send(e){ss.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();ue();K();ue();import{execSync as xf}from"node:child_process";import{readFileSync as ca,unlinkSync as uf}from"node:fs";import{mkdir as ff,readFile as xa,unlink as ua,writeFile as df}from"node:fs/promises";import{dirname as lf}from"node:path";var hf=R("single-instance"),sr=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??W().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&&(hf.warn("removing stale pid file",{stalePid:e}),await ua(this.pidFile).catch(()=>{})),await ff(lf(this.pidFile),{recursive:!0}),await df(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await xa(this.pidFile,"utf8")).trim()===String(process.pid)&&await ua(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await xa(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=ca(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=xf(`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{ca(this.pidFile,"utf8").trim()===String(process.pid)&&uf(this.pidFile)}catch{}})}};var z=R("daemon"),gf="coze-bridge-daemon";async function la(){let r=new sr({processTitle:gf}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await Rn(),a=i??{};Er({pid:process.pid}),z.info(i?"loaded bridge config":"initialized bridge config");try{let P=new mt;a.frameworksCache=await P.detectAll(),z.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(P){z.warn("framework detection failed",{err:String(P)})}await wt(a);let c=new rr(new Qt),u=W(),d=null,g=new Nn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(P,G,V,ne)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,G,V,ne)}});await mf(u,g);let m=new In({paths:u,config:a,registry:g});d=m;let w,v,y=null,E=null;g.registerExtension("_agent/create",async P=>m.createAgent(P.params)),g.registerExtension("_agent/health",async()=>({ok:!0}));let D={},k=new gn({agents:g.agents,disposeAndMarkDisconnected:async(P,G)=>{let V=g.agents.get(P);V&&(await m.cleanupOpenclawSessionProviders(V).catch(ne=>z.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(ne)})),await V.dispose(`disconnect: ${G}`).catch(ne=>z.warn("dispose during disconnect failed (ignored)",{agentId:P,err:String(ne)})),V.status="disconnected",g.unregister(P)),g.disconnectedAgents.add(P)},detailSyncer:async P=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(P)},openclawRepair:async(P,G)=>{await m.openclawRepair(P,G)}});g.registerExtension("_agent/listSkills",P=>k.listSkills(P.params)),g.registerExtension("_agent/addSkills",P=>k.addSkills(P.params)),g.registerExtension("_agent/removeSkills",P=>k.removeSkills(P.params)),g.registerExtension("_agent/getFileTree",P=>k.getFileTree(P.params)),g.registerExtension("_agent/getFileContent",P=>k.getFileContent(P.params)),g.registerExtension("_agent/update",P=>k.updateAgent(P.params)),g.registerExtension("_agent/disconnect",P=>k.disconnectAgent(P.params)),g.registerExtension("_agent/switchModel",P=>k.switchModel(P.params)),g.registerExtension("_agent/reset",P=>k.resetAgent(P.params)),g.registerExtension("_agent/repair",P=>k.repairAgent(P.params));let T=new un({paths:u,handlers:k,sendDetail:P=>g.sendRequest("_agent/detail",P)});D.ref=T,c.onConnect(({initial:P})=>{z.info("frontier upstream connected, triggering detail sync",{initial:P}),T.syncAll(P?"initial-connect":"reconnect").catch(G=>z.warn("detail sync top-level error (ignored)",{err:String(G)}))});let H=new Ln({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...g.agents.keys()],deviceId:y??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async P=>{let G=P,V=G?.privatecode,ne=G?.pairing_code;if(!V||!ne)throw new S("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let De=ln(G.env),pe=G.handshake_url,Xe=G.frontier_url,Dt=pf(G.env,pe,Xe),Zt=!!w&&w!==V,ve=v!==void 0&&v!==Dt,be=Zt||ve;if(be){z.warn("pair config switched, resetting agents",{pcChanged:Zt,envChanged:ve,previousPc:w?fa(w):"",nextPc:fa(V),previousEnvKey:v??"",nextEnvKey:Dt});for(let F of[...g.agents.values()])await F.dispose("pair config switch").catch(()=>{}),g.agents.delete(F.agentId);await c.swap(new Qt,"pair switch").catch(()=>{})}let en=await Zs({privatecode:V,...pe?{endpoint:pe}:{},ppeOverride:De});y=en.deviceId,Er({deviceId:y,pid:process.pid});let oe=new nr({handshake:en,privatecode:V,...Xe?{urlOverride:Xe}:{},ppeOverride:De});await c.swap(oe,"pair");try{let F=new mt;a.frameworksCache=await F.detectAll(),await wt(a),z.info("frameworks_cache refreshed before pair",{detected:Object.keys(a.frameworksCache)})}catch(F){z.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(F)})}let tn=Object.keys(a.frameworksCache??{});try{let F=await g.sendRequest("_agent/pair",{pairCode:ne,patToken:V,frameworks:tn,_meta:{cozeDeviceId:y}});z.info("_agent/pair ok",{pairResult:F}),w=V,v=Dt,E||(E=new wn({core:g,getDeviceId:()=>y??""})),E.start(),be&&da(u,m).catch(ke=>z.warn("post-pair-switch auto-revive error (ignored)",{err:String(ke)}));let Y;return G.agent_id&&(Y=await wf(G.agent_id,u,m,ke=>g.sendRequest("_agent/detail",ke)).catch(ke=>(z.error("--agent-id ensureAgent failed",{agentId:G.agent_id,err:String(ke)}),{ok:!1,agentId:G.agent_id??"",note:String(ke)}))),{ok:!0,note:"paired with cloud",...Y?{agent:Y}:{}}}catch(F){return z.error("_agent/pair failed",{err:String(F)}),{ok:!1,note:`pair failed: ${String(F)}`}}}},{method:"POST",path:"/_agent/create",handler:async P=>{let G=P;return{ok:!0,result:await m.createAgent(G)}}},{method:"POST",path:"/refresh",handler:async()=>{z.info("IPC /refresh: re-detecting frameworks");let P=new mt;return a.frameworksCache=await P.detectAll(),await wt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(z.info("IPC /shutdown received"),setImmediate(()=>{ce.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ie,token:te}=await H.start();await g.start(),da(u,m).catch(P=>z.warn("auto-revive top-level error (ignored)",{err:String(P)}));let ye=null,ce={port:ie,token:te,core:g,ipc:H,shutdown(P){return ye||(z.info("daemon shutdown",{reason:P}),ye=(async()=>{E?.stop(),await g.stop(P),await H.stop(),await r.release()})(),ye)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{ce.shutdown(P).then(()=>process.exit(0))});return z.info("daemon ready",{port:ie,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),ce}function fa(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function pf(r,e,i){return`${r??""}|${e??""}|${i??""}`}async function mf(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.agentsRoot)}catch{return}let{loadAgentConfig:c,enforceAgentConfigMode:u}=await Promise.resolve().then(()=>(Ge(),xn));for(let d of a){await u(d,r).catch(g=>z.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(g)}));try{let g=await c(d,r);g?.disconnectedAt&&(e.disconnectedAgents.add(d),z.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:g.disconnectedAt,reason:g.disconnectReason??""}))}catch(g){z.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(g)})}}}async function wf(r,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ge(),xn)),u=await c(r,e);if(u){z.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"}}z.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 S("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 g={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(g);let m=d.deployType==="cloud"&&d.framework==="openclaw";return{ok:!0,agentId:r,note:m?"cloud agent acknowledged":"created from cloud detail"}}async function da(r,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(r.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(a.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ge(),xn));z.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,d=0;for(let g of a){let m;try{m=await c(g,r)}catch(w){z.warn("auto-revive: load config failed (skipping)",{agentId:g,err:String(w)}),d+=1;continue}if(!m){d+=1;continue}if(m.disconnectedAt){z.info("auto-revive: skip disconnected agent",{agentId:g,disconnectedAt:m.disconnectedAt}),d+=1;continue}try{z.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:g,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){z.warn("auto-revive: createAgent failed (skipping)",{agentId:g,framework:m.framework,err:String(w)}),d+=1}}return z.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}os();ue();import{readFile as ga}from"node:fs/promises";var Ye=class{paths;constructor(e){this.paths=e??W()}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:Pf(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([ga(this.paths.portFile,"utf8"),ga(this.paths.tokenFile,"utf8")]),a=Number.parseInt(e.trim(),10),c=i.trim();return!Number.isFinite(a)||a<=0||!c?null:{port:a,token:c}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,i){let a=i.body!==void 0,c={Authorization:`Bearer ${e.token}`};a&&(c["content-type"]="application/json");let u=new AbortController,d=setTimeout(()=>u.abort(),i.timeoutMs??5e3);try{let g=await fetch(`http://127.0.0.1:${e.port}${i.path}`,{method:i.method,headers:c,body:a?JSON.stringify(i.body):void 0,signal:u.signal}),m=await g.text();return{status:g.status,body:Af(m)}}finally{clearTimeout(d)}}};function Af(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Pf(r){return r instanceof Error?r.message:String(r)}K();ue();import{copyFile as pa,mkdir as Df,readFile as as,writeFile as kf}from"node:fs/promises";import{dirname as Tf,resolve as cs,sep as ir}from"node:path";import{fileURLToPath as If}from"node:url";K();ue();var ma=R("dist-install");function Rf(r){let e=If(r),i=Tf(e),a=`${ir}src${ir}`;if(i.includes(a)||i.endsWith(`${ir}src${ir}cli`))return null;let c=cs(i,"index.js"),u=cs(i,"..","package.json");return{dist:c,pkgJson:u}}async function wa(r={}){let e=r.paths??W(),i=Rf(import.meta.url),a=r.sourceDist??i?.dist,c=r.sourcePackageJson??i?.pkgJson;if(!a||!c)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let u;try{u=JSON.parse(await as(c,"utf8")).version??"unknown"}catch(y){return ma.warn("cannot read source package.json,skip dist install",{err:String(y)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(y)}`}}let d=await Rn(e.configFile)??{},g=d.libVersion;if(g===u)try{return await as(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await Df(e.libDir,{recursive:!0}),await pa(a,e.libEntry),await pa(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let m=cs(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
96
+ `;return await as(m,"utf8").catch(()=>null)!==w&&await kf(m,w),d.libVersion=u,await wt(d,e.configFile),ma.info("dist installed",{libEntry:e.libEntry,fromVersion:g,toVersion:u}),g?{kind:"version-changed",fromVersion:g,toVersion:u,libEntry:e.libEntry}:{kind:"first-install",libVersion:u,libEntry:e.libEntry}}var $f=R("cli");function Pt(r,e){let i=[],a;for(let c=0;c<r.length;c++){let u=r[c];if(u===e){a=r[c+1],c+=1;continue}if(u.startsWith(`${e}=`)){a=u.slice(e.length+1);continue}i.push(u)}return{value:a,rest:i}}function Qf(r){let e=r.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let i=e,{value:a,rest:c}=Pt(i,"--pat-token");i=c;let{value:u,rest:d}=Pt(i,"--pair-code");i=d;let{value:g,rest:m}=Pt(i,"--env");i=m;let{value:w,rest:v}=Pt(i,"--handshake-url");i=v;let{value:y,rest:E}=Pt(i,"--frontier-url");i=E;let{value:D}=Pt(i,"--agent-id");if(!a||!u)return{mode:"help"};let k={mode:"pair",privatecode:a,pairingCode:u};return g&&(k.env=g),w&&(k.handshakeUrl=w),y&&(k.frontierUrl=y),D&&(k.agentId=D),k}var Zf=`
95
97
  coze-bridge - local bridge daemon for cloud Agent Service
96
98
 
97
99
  Usage:
@@ -119,36 +121,36 @@ Auto-connect agent (optional):
119
121
 
120
122
  Internal:
121
123
  <node> <entry> --daemon daemon mode (OS supervisor only)
122
- `.trimStart();async function ea(n=process.argv,e={}){let t=Af(n);switch(t.mode){case"help":return process.stdout.write(Cf),0;case"version":return process.stdout.write(`${Ut}
123
- `),0;case"daemon":{try{await Go()}catch(r){return Pf.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return Of(e);case"stop":return Nf(e);case"refresh":return bf(e);case"uninstall":return Df(e);case"install-service":return Lf();case"pair":{let r={};return t.env&&(r.env=t.env),t.handshakeUrl&&(r.handshakeUrl=t.handshakeUrl),t.frontierUrl&&(r.frontierUrl=t.frontierUrl),Mf(t.privatecode,t.pairingCode,e,r,t.agentId)}}}async function ta(n){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(n.pidFile).catch(()=>{}),e(n.portFile).catch(()=>{}),e(n.tokenFile).catch(()=>{})])}async function Of(n){let e=n.paths??T(),t=new Se(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
124
- `),1;if(r.kind==="stale")return await ta(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
125
- `),1;let s=await t.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
126
- ${JSON.stringify(s.body,null,2)}
127
- `),0}async function Nf(n){let e=n.paths??T(),t=new Se(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
128
- `),0;if(r.kind==="stale")return await ta(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
129
- `),0;try{return await t.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
130
- `),0}catch(s){return process.stdout.write(`coze-bridge: stop failed: ${String(s)}
131
- `),1}}async function bf(n){let e=new Se(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
132
- `),1;try{let r=await e.request({method:"POST",path:"/refresh"});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
133
- ${JSON.stringify(r.body,null,2)}
134
- `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
135
- `),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
136
- `),1}}async function Df(n){let e=new Se(n.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
137
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(i){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(i)}
138
- `)}await new Promise(i=>setTimeout(i,500))}if(!n.skipSupervisor)try{let{getSupervisor:i,buildContext:o}=await Promise.resolve().then(()=>(Yr(),Xr)),a=i();await a.uninstall(o()),process.stdout.write(`coze-bridge: ${a.platform} supervisor unregistered
139
- `)}catch(i){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(i)}
140
- `)}let r=n.paths??T(),{rm:s}=await import("node:fs/promises");try{await s(r.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${r.cozeRoot}
141
- `)}catch(i){return process.stderr.write(`coze-bridge: remove failed: ${String(i)}
124
+ `.trimStart();async function Ea(r=process.argv,e={}){let i=Qf(r);switch(i.mode){case"help":return process.stdout.write(Zf),0;case"version":return process.stdout.write(`${mn}
125
+ `),0;case"daemon":{try{await la()}catch(a){return $f.error("daemon start failed",{err:String(a)}),1}return new Promise(()=>{})}case"status":return ed(e);case"stop":return td(e);case"refresh":return nd(e);case"uninstall":return rd(e);case"install-service":return sd();case"pair":{let a={};return i.env&&(a.env=i.env),i.handshakeUrl&&(a.handshakeUrl=i.handshakeUrl),i.frontierUrl&&(a.frontierUrl=i.frontierUrl),id(i.privatecode,i.pairingCode,e,a,i.agentId)}}}async function Ca(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 ed(r){let e=r.paths??W(),i=new Ye(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
126
+ `),1;if(a.kind==="stale")return await Ca(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
127
+ `),1;let c=await i.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
128
+ ${JSON.stringify(c.body,null,2)}
129
+ `),0}async function td(r){let e=r.paths??W(),i=new Ye(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
130
+ `),0;if(a.kind==="stale")return await Ca(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
131
+ `),0;try{return await i.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
132
+ `),0}catch(c){return process.stdout.write(`coze-bridge: stop failed: ${String(c)}
133
+ `),1}}async function nd(r){let e=new Ye(r.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
134
+ `),1;try{let a=await e.request({method:"POST",path:"/refresh"});return a.status===200?(process.stdout.write(`coze-bridge: refreshed
135
+ ${JSON.stringify(a.body,null,2)}
136
+ `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(a.body)}
137
+ `),1)}catch(a){return process.stderr.write(`coze-bridge: refresh failed: ${String(a)}
138
+ `),1}}async function rd(r){let e=new Ye(r.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
139
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(u){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(u)}
140
+ `)}await new Promise(u=>setTimeout(u,500))}if(!r.skipSupervisor)try{let{getSupervisor:u,buildContext:d}=await Promise.resolve().then(()=>(gs(),hs)),g=u();await g.uninstall(d()),process.stdout.write(`coze-bridge: ${g.platform} supervisor unregistered
141
+ `)}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
142
+ `)}let a=r.paths??W(),{rm:c}=await import("node:fs/promises");try{await c(a.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${a.cozeRoot}
143
+ `)}catch(u){return process.stderr.write(`coze-bridge: remove failed: ${String(u)}
142
144
  `),1}return process.stdout.write(`coze-bridge: uninstalled
143
- `),0}async function Lf(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(Yr(),Xr)),t=n(),r=e();return process.stdout.write(`coze-bridge: installing ${t.platform} supervisor...
144
- `),await t.install(r),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
145
- `),0}catch(n){return process.stderr.write(`coze-bridge: --install-service failed: ${String(n)}
146
- `),1}}async function Mf(n,e,t,r={},s){let i=new Se(t.paths),o=t.spawnDaemon??Ho;if(!t.skipDistInstall){let d=await Vo({paths:t.paths});d.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${d.fromVersion} \u2192 ${d.toVersion}
147
- `),(await i.probe()).kind==="connected"&&(await i.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(u=>setTimeout(u,500)))):d.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${d.libVersion}
148
- `)}let a=await i.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
149
- `),await o({paths:t.paths}),a=await Bf(i,t.waitTimeoutMs??1e4,t.sleep??Ff),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
150
- `),1;let c={privatecode:n,pairing_code:e};r.env&&(c.env=r.env),r.handshakeUrl&&(c.handshake_url=r.handshakeUrl),r.frontierUrl&&(c.frontier_url=r.frontierUrl),s&&(c.agent_id=s);try{let d=await i.request({method:"POST",path:"/pair",body:c,timeoutMs:35e3});return d.status===200&&d.body?.ok?(process.stdout.write(`coze-bridge: paired (${d.body.note??"ok"})
151
- `),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(d.body)}
152
- `),1)}catch(d){return process.stderr.write(`coze-bridge: pair failed: ${String(d)}
153
- `),1}}async function Bf(n,e,t){let r=Date.now()+e;for(;Date.now()<r;){let s=await n.probe(500);if(s.kind==="connected")return s;await t(200)}return n.probe(500)}function Ff(n){return new Promise(e=>setTimeout(e,n))}ea(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
145
+ `),0}async function sd(){try{let{getSupervisor:r,buildContext:e}=await Promise.resolve().then(()=>(gs(),hs)),i=r(),a=e();return process.stdout.write(`coze-bridge: installing ${i.platform} supervisor...
146
+ `),await i.install(a),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
147
+ `),0}catch(r){return process.stderr.write(`coze-bridge: --install-service failed: ${String(r)}
148
+ `),1}}async function id(r,e,i,a={},c){let u=new Ye(i.paths),d=i.spawnDaemon??ha;if(!i.skipDistInstall){let w=await wa({paths:i.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
149
+ `),(await u.probe()).kind==="connected"&&(await u.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
150
+ `)}let g=await u.probe();if(g.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
151
+ `),await d({paths:i.paths}),g=await od(u,i.waitTimeoutMs??1e4,i.sleep??ad),g.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${g.kind}
152
+ `),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),c&&(m.agent_id=c);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"})
153
+ `),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
154
+ `),1)}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
155
+ `),1}}async function od(r,e,i){let a=Date.now()+e;for(;Date.now()<a;){let c=await r.probe(500);if(c.kind==="connected")return c;await i(200)}return r.probe(500)}function ad(r){return new Promise(e=>setTimeout(e,r))}Ea(process.argv).then(r=>process.exit(r),r=>{process.stderr.write(`fatal: ${r instanceof Error?r.stack??r.message:String(r)}
154
156
  `),process.exit(1)});