coze-bridge 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +53 -53
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
|
|
|
5
5
|
const require = __coze_createRequire(import.meta.url);
|
|
6
6
|
const __filename = __coze_fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = __coze_dirname(__filename);
|
|
8
|
-
var $
|
|
9
|
-
`,
|
|
10
|
-
`):
|
|
11
|
-
`)}function w(r){return{debug:(e,t)=>Et("debug",r,e,t),info:(e,t)=>Et("info",r,e,t),warn:(e,t)=>Et("warn",r,e,t),error:(e,t)=>Et("error",r,e,t),child:e=>w(`${r}.${e}`)}}var vt,Jn,Ko,Xo,Vn,k=j(()=>{"use strict";vt={debug:10,info:20,warn:30,error:40},Jn=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),Ko=process.stdout,Xo=process.stderr,Vn={}});import{homedir as Yo}from"node:os";import{join as N}from"node:path";function x(r){let e=r??Yo(),t=N(e,".coze"),n=N(t,"bridge"),s=N(n,"lib");return{cozeRoot:t,bridgeRoot:n,libDir:s,libEntry:N(s,"index.js"),pidFile:N(n,"bridge.pid"),portFile:N(n,"bridge.port"),tokenFile:N(n,"bridge.token"),logFile:N(n,"bridge.log"),installLock:N(n,"install.lock"),configFile:N(n,"config.json"),agentsRoot:N(t,"agents")}}function ne(r,e=x()){let t=N(e.agentsRoot,r);return{root:t,config:N(t,"config.json"),workspace:N(t,"workspace"),logs:N(t,"logs")}}var F=j(()=>{"use strict"});var It={};Ir(It,{AGENT_CONFIG_FILE_MODE:()=>kt,enforceAgentConfigMode:()=>ta,loadAgentConfig:()=>U,persistAgentSessions:()=>Pr,persistAgentSkills:()=>xt,saveAgentConfig:()=>J});import{chmod as Zo,stat as ea}from"node:fs/promises";function U(r,e){return yt(ne(r,e).config)}function J(r,e){return St(ne(r.agentId,e).config,r,{mode:kt})}async function ta(r,e){if(process.platform==="win32")return;let t=ne(r,e).config;try{let n=await ea(t);if(!n.isFile())return;let s=n.mode&511;s!==kt&&(await Zo(t,kt),Kn.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(n){if(n.code==="ENOENT")return;Kn.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(n)})}}async function Pr(r,e,t){let n=await U(r,t);n&&(n.sessions=Object.fromEntries(e),await J(n,t))}async function xt(r,e,t){let n=await U(r,t);n&&(n.skills=e,await J(n,t))}var Kn,kt,ue=j(()=>{"use strict";Tr();k();F();Kn=w("agent-config"),kt=384});function Sc(){return Ds||(Ds=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ec(){return Ls||(Ls=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function vc(r){let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("success",i),r.removeEventListener("error",o)},i=()=>{t(q(r.result)),s()},o=()=>{n(r.error),s()};r.addEventListener("success",i),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Ms.set(t,r)}).catch(()=>{}),Lr.set(e,r),e}function kc(r){if(br.has(r))return;let e=new Promise((t,n)=>{let s=()=>{r.removeEventListener("complete",i),r.removeEventListener("error",o),r.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),s()};r.addEventListener("complete",i),r.addEventListener("error",o),r.addEventListener("abort",o)});br.set(r,e)}function Fs(r){Dr=r(Dr)}function xc(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(it(this),e,...t);return Bs.set(n,e.sort?e.sort():[e]),q(n)}:Ec().includes(r)?function(...e){return r.apply(it(this),e),q(Ms.get(this))}:function(...e){return q(r.apply(it(this),e))}}function Ic(r){return typeof r=="function"?xc(r):(r instanceof IDBTransaction&&kc(r),yc(r,Sc())?new Proxy(r,Dr):r)}function q(r){if(r instanceof IDBRequest)return vc(r);if(Nr.has(r))return Nr.get(r);let e=Ic(r);return e!==r&&(Nr.set(r,e),Lr.set(e,r)),e}var yc,Ds,Ls,Ms,br,Bs,Nr,Lr,Dr,it,Mr=j(()=>{yc=(r,e)=>e.some(t=>r instanceof t);Ms=new WeakMap,br=new WeakMap,Bs=new WeakMap,Nr=new WeakMap,Lr=new WeakMap;Dr={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return br.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Bs.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return q(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};it=r=>Lr.get(r)});var $s={};Ir($s,{deleteDB:()=>Rc,openDB:()=>Tc,unwrap:()=>it,wrap:()=>q});function Tc(r,e,{blocked:t,upgrade:n,blocking:s,terminated:i}={}){let o=indexedDB.open(r,e),a=q(o);return n&&o.addEventListener("upgradeneeded",c=>{n(q(o.result),c.oldVersion,c.newVersion,q(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function Rc(r,{blocked:e}={}){let t=indexedDB.deleteDatabase(r);return e&&t.addEventListener("blocked",()=>e()),q(t).then(()=>{})}function Us(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(Br.get(e))return Br.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,s=Ac.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(s||Pc.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),d=c.store;return n&&(d=d.index(a.shift())),(await Promise.all([d[t](...a),s&&c.done]))[0]};return Br.set(e,i),i}var Pc,Ac,Br,zs=j(()=>{Mr();Mr();Pc=["get","getKey","getAll","getAllKeys","count"],Ac=["put","add","delete","clear"],Br=new Map;Fs(r=>({...r,get:(e,t,n)=>Us(e,t)||r.get(e,t,n),has:(e,t)=>!!Us(e,t)||r.has(e,t)}))});var oe=B((Rg,hi)=>{"use strict";var ui=["nodebuffer","arraybuffer","fragments"],fi=typeof Blob<"u";fi&&ui.push("blob");hi.exports={BINARY_TYPES:ui,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:fi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ut=B((Pg,Xt)=>{"use strict";var{EMPTY_BUFFER:Nd}=oe(),an=Buffer[Symbol.species];function bd(r,e){if(r.length===0)return Nd;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),n=0;for(let s=0;s<r.length;s++){let i=r[s];t.set(i,n),n+=i.length}return n<e?new an(t.buffer,t.byteOffset,n):t}function gi(r,e,t,n,s){for(let i=0;i<s;i++)t[n+i]=r[i]^e[i&3]}function pi(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Dd(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function cn(r){if(cn.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new an(r):ArrayBuffer.isView(r)?e=new an(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),cn.readOnly=!1),e}Xt.exports={concat:bd,mask:gi,toArrayBuffer:Dd,toBuffer:cn,unmask:pi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=P("bufferutil");Xt.exports.mask=function(e,t,n,s,i){i<48?gi(e,t,n,s,i):r.mask(e,t,n,s,i)},Xt.exports.unmask=function(e,t){e.length<32?pi(e,t):r.unmask(e,t)}}catch{}});var wi=B((Ag,_i)=>{"use strict";var mi=Symbol("kDone"),dn=Symbol("kRun"),ln=class{constructor(e){this[mi]=()=>{this.pending--,this[dn]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[dn]()}[dn](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[mi])}}};_i.exports=ln});var Ge=B((Cg,vi)=>{"use strict";var ft=P("zlib"),yi=ut(),Ld=wi(),{kStatusCode:Si}=oe(),Md=Buffer[Symbol.species],Bd=Buffer.from([0,0,255,255]),Zt=Symbol("permessage-deflate"),ae=Symbol("total-length"),ze=Symbol("callback"),me=Symbol("buffers"),qe=Symbol("error"),Yt,un=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Yt){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Yt=new Ld(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ze];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,n=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(n=>{let s=t[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=i}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);t[n]=s})}),e}decompress(e,t,n){Yt.add(s=>{this._decompress(e,t,(i,o)=>{s(),n(i,o)})})}compress(e,t,n){Yt.add(s=>{this._compress(e,t,(i,o)=>{s(),n(i,o)})})}_decompress(e,t,n){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=ft.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Zt]=this,this._inflate[ae]=0,this._inflate[me]=[],this._inflate.on("error",Ud),this._inflate.on("data",Ei)}this._inflate[ze]=n,this._inflate.write(e),t&&this._inflate.write(Bd),this._inflate.flush(()=>{let i=this._inflate[qe];if(i){this._inflate.close(),this._inflate=null,n(i);return}let o=yi.concat(this._inflate[me],this._inflate[ae]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ae]=0,this._inflate[me]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,t,n){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?ft.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=ft.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ae]=0,this._deflate[me]=[],this._deflate.on("data",Fd)}this._deflate[ze]=n,this._deflate.write(e),this._deflate.flush(ft.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=yi.concat(this._deflate[me],this._deflate[ae]);t&&(i=new Md(i.buffer,i.byteOffset,i.length-4)),this._deflate[ze]=null,this._deflate[ae]=0,this._deflate[me]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,i)})}};vi.exports=un;function Fd(r){this[me].push(r),this[ae]+=r.length}function Ei(r){if(this[ae]+=r.length,this[Zt]._maxPayload<1||this[ae]<=this[Zt]._maxPayload){this[me].push(r);return}this[qe]=new RangeError("Max payload size exceeded"),this[qe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[qe][Si]=1009,this.removeListener("data",Ei),this.reset()}function Ud(r){if(this[Zt]._inflate=null,this[qe]){this[ze](this[qe]);return}r[Si]=1007,this[ze](r)}});var He=B((Og,er)=>{"use strict";var{isUtf8:ki}=P("buffer"),{hasBlob:$d}=oe(),zd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function qd(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function fn(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Gd(r){return $d&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}er.exports={isBlob:Gd,isValidStatusCode:qd,isValidUTF8:fn,tokenChars:zd};if(ki)er.exports.isValidUTF8=function(r){return r.length<24?fn(r):ki(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=P("utf-8-validate");er.exports.isValidUTF8=function(e){return e.length<32?fn(e):r(e)}}catch{}});var _n=B((Ng,Ci)=>{"use strict";var{Writable:Hd}=P("stream"),xi=Ge(),{BINARY_TYPES:Wd,EMPTY_BUFFER:Ii,kStatusCode:jd,kWebSocket:Jd}=oe(),{concat:hn,toArrayBuffer:Vd,unmask:Qd}=ut(),{isValidStatusCode:Kd,isValidUTF8:Ti}=He(),tr=Buffer[Symbol.species],H=0,Ri=1,Pi=2,Ai=3,gn=4,pn=5,rr=6,mn=class extends Hd{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Wd[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Jd]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=H}_write(e,t,n){if(this._opcode===8&&this._state==H)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new tr(n.buffer,n.byteOffset+e,n.length-e),new tr(n.buffer,n.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=t.length-e;e>=n.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new tr(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case H:this.getInfo(e);break;case Ri:this.getPayloadLength16(e);break;case Pi:this.getPayloadLength64(e);break;case Ai:this.getMask();break;case gn:this.getData(e);break;case pn:case rr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(t[0]&64)===64;if(n&&!this._extensions[xi.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Ri:this._payloadLength===127?this._state=Pi:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ai:this._state=gn}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=gn}getData(e){let t=Ii;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Qd(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=pn,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[xi.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===H&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=H;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=hn(n,t):this._binaryType==="arraybuffer"?s=Vd(hn(n,t)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=H):(this._state=rr,setImmediate(()=>{this.emit("message",s,!0),this._state=H,this.startLoop(e)}))}else{let s=hn(n,t);if(!this._skipUTF8Validation&&!Ti(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===pn||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=H):(this._state=rr,setImmediate(()=>{this.emit("message",s,!1),this._state=H,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ii),this.end();else{let n=e.readUInt16BE(0);if(!Kd(n)){let i=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new tr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ti(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=H;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=H):(this._state=rr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=H,this.startLoop(t)}))}createError(e,t,n,s,i){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[jd]=s,o}};Ci.exports=mn});var Sn=B((Dg,bi)=>{"use strict";var{Duplex:bg}=P("stream"),{randomFillSync:Xd}=P("crypto"),Oi=Ge(),{EMPTY_BUFFER:Yd,kWebSocket:Zd,NOOP:el}=oe(),{isBlob:We,isValidStatusCode:tl}=He(),{mask:Ni,toBuffer:Te}=ut(),W=Symbol("kByteLength"),rl=Buffer.alloc(4),nr=8*1024,Re,je=nr,Q=0,nl=1,sl=2,wn=class r{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Q,this.onerror=el,this[Zd]=void 0}static frame(e,t){let n,s=!1,i=2,o=!1;t.mask&&(n=t.maskBuffer||rl,t.generateMask?t.generateMask(n):(je===nr&&(Re===void 0&&(Re=Buffer.alloc(nr)),Xd(Re,0,nr),je=0),n[0]=Re[je++],n[1]=Re[je++],n[2]=Re[je++],n[3]=Re[je++]),o=(n[0]|n[1]|n[2]|n[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[W]!==void 0?a=t[W]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=n[0],d[i-3]=n[1],d[i-2]=n[2],d[i-1]=n[3],o?[d,e]:s?(Ni(e,n,d,i,a),[d]):(Ni(e,n,e,0,a),[d,e])):[d,e]}close(e,t,n,s){let i;if(e===void 0)i=Yd;else{if(typeof e!="number"||!tl(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[W]:i.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Q?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(r.frame(i,o),s)}ping(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):We(e)?(s=e.size,i=!1):(e=Te(e),s=e.length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[W]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Q?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}pong(e,t,n){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):We(e)?(s=e.size,i=!1):(e=Te(e),s=e.length,i=Te.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[W]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Q?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(r.frame(e,o),n)}send(e,t,n){let s=this._extensions[Oi.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):We(e)?(a=e.size,c=!1):(e=Te(e),a=e.length,c=Te.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[W]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};We(e)?this._state!==Q?this.enqueue([this.getBlobData,e,this._compress,d,n]):this.getBlobData(e,this._compress,d,n):this._state!==Q?this.enqueue([this.dispatch,e,this._compress,d,n]):this.dispatch(e,this._compress,d,n)}getBlobData(e,t,n,s){this._bufferedBytes+=n[W],this._state=sl,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(yn,this,a,s);return}this._bufferedBytes-=n[W];let o=Te(i);t?this.dispatch(o,t,n,s):(this._state=Q,this.sendFrame(r.frame(o,n),s),this.dequeue())}).catch(i=>{process.nextTick(il,this,i,s)})}dispatch(e,t,n,s){if(!t){this.sendFrame(r.frame(e,n),s);return}let i=this._extensions[Oi.extensionName];this._bufferedBytes+=n[W],this._state=nl,i.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");yn(this,c,s);return}this._bufferedBytes-=n[W],this._state=Q,n.readOnly=!1,this.sendFrame(r.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===Q&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][W],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][W],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};bi.exports=wn;function yn(r,e,t){typeof t=="function"&&t(e);for(let n=0;n<r._queue.length;n++){let s=r._queue[n],i=s[s.length-1];typeof i=="function"&&i(e)}}function il(r,e,t){yn(r,e,t),r.onerror(e)}});var qi=B((Lg,zi)=>{"use strict";var{kForOnEventAttribute:ht,kListener:En}=oe(),Di=Symbol("kCode"),Li=Symbol("kData"),Mi=Symbol("kError"),Bi=Symbol("kMessage"),Fi=Symbol("kReason"),Je=Symbol("kTarget"),Ui=Symbol("kType"),$i=Symbol("kWasClean"),ce=class{constructor(e){this[Je]=null,this[Ui]=e}get target(){return this[Je]}get type(){return this[Ui]}};Object.defineProperty(ce.prototype,"target",{enumerable:!0});Object.defineProperty(ce.prototype,"type",{enumerable:!0});var Pe=class extends ce{constructor(e,t={}){super(e),this[Di]=t.code===void 0?0:t.code,this[Fi]=t.reason===void 0?"":t.reason,this[$i]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Di]}get reason(){return this[Fi]}get wasClean(){return this[$i]}};Object.defineProperty(Pe.prototype,"code",{enumerable:!0});Object.defineProperty(Pe.prototype,"reason",{enumerable:!0});Object.defineProperty(Pe.prototype,"wasClean",{enumerable:!0});var Ve=class extends ce{constructor(e,t={}){super(e),this[Mi]=t.error===void 0?null:t.error,this[Bi]=t.message===void 0?"":t.message}get error(){return this[Mi]}get message(){return this[Bi]}};Object.defineProperty(Ve.prototype,"error",{enumerable:!0});Object.defineProperty(Ve.prototype,"message",{enumerable:!0});var gt=class extends ce{constructor(e,t={}){super(e),this[Li]=t.data===void 0?null:t.data}get data(){return this[Li]}};Object.defineProperty(gt.prototype,"data",{enumerable:!0});var ol={addEventListener(r,e,t={}){for(let s of this.listeners(r))if(!t[ht]&&s[En]===e&&!s[ht])return;let n;if(r==="message")n=function(i,o){let a=new gt("message",{data:o?i:i.toString()});a[Je]=this,sr(e,this,a)};else if(r==="close")n=function(i,o){let a=new Pe("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Je]=this,sr(e,this,a)};else if(r==="error")n=function(i){let o=new Ve("error",{error:i,message:i.message});o[Je]=this,sr(e,this,o)};else if(r==="open")n=function(){let i=new ce("open");i[Je]=this,sr(e,this,i)};else return;n[ht]=!!t[ht],n[En]=e,t.once?this.once(r,n):this.on(r,n)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[En]===e&&!t[ht]){this.removeListener(r,t);break}}};zi.exports={CloseEvent:Pe,ErrorEvent:Ve,Event:ce,EventTarget:ol,MessageEvent:gt};function sr(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var ir=B((Mg,Gi)=>{"use strict";var{tokenChars:pt}=He();function Z(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function al(r){let e=Object.create(null),t=Object.create(null),n=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<r.length;u++)if(d=r.charCodeAt(u),o===void 0)if(l===-1&&pt[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let m=r.slice(c,l);d===44?(Z(e,m,t),t=Object.create(null)):o=m,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&pt[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),Z(t,r.slice(c,l),!0),d===44&&(Z(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=r.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(pt[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:n||(n=!0),s=!1}else if(i)if(pt[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&r.charCodeAt(u-1)===61)i=!0;else if(l===-1&&pt[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let m=r.slice(c,l);n&&(m=m.replace(/\\/g,""),n=!1),Z(t,a,m),d===44&&(Z(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let f=r.slice(c,l);return o===void 0?Z(e,f,t):(a===void 0?Z(t,f,!0):n?Z(t,a,f.replace(/\\/g,"")):Z(t,a,f),Z(e,o,t)),e}function cl(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(n=>[e].concat(Object.keys(n).map(s=>{let i=n[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Gi.exports={format:cl,parse:al}});var dr=B((Ug,to)=>{"use strict";var dl=P("events"),ll=P("https"),ul=P("http"),ji=P("net"),fl=P("tls"),{randomBytes:hl,createHash:gl}=P("crypto"),{Duplex:Bg,Readable:Fg}=P("stream"),{URL:vn}=P("url"),_e=Ge(),pl=_n(),ml=Sn(),{isBlob:_l}=He(),{BINARY_TYPES:Hi,CLOSE_TIMEOUT:wl,EMPTY_BUFFER:or,GUID:yl,kForOnEventAttribute:kn,kListener:Sl,kStatusCode:El,kWebSocket:A,NOOP:Ji}=oe(),{EventTarget:{addEventListener:vl,removeEventListener:kl}}=qi(),{format:xl,parse:Il}=ir(),{toBuffer:Tl}=ut(),Vi=Symbol("kAborted"),xn=[8,13],de=["CONNECTING","OPEN","CLOSING","CLOSED"],Rl=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,v=class r extends dl{constructor(e,t,n){super(),this._binaryType=Hi[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=or,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(n=t,t=[]):t=[t]),Qi(this,e,t,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Hi.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,n){let s=new pl({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),i=new ml(e,this._extensions,n.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[A]=this,i[A]=this,e[A]=this,s.on("conclude",Cl),s.on("drain",Ol),s.on("error",Nl),s.on("message",bl),s.on("ping",Dl),s.on("pong",Ll),i.onerror=Ml,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Yi),e.on("data",cr),e.on("end",Zi),e.on("error",eo),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[_e.extensionName]&&this._extensions[_e.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){z(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Xi(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||or,t,n)}pong(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=t=void 0):typeof t=="function"&&(n=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||or,t,n)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,n){if(this.readyState===r.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(n=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==r.OPEN){In(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[_e.extensionName]||(s.compress=!1),this._sender.send(e||or,s,n)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){z(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(v,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(v.prototype,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")});Object.defineProperty(v,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(v.prototype,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")});Object.defineProperty(v,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(v.prototype,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")});Object.defineProperty(v,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});Object.defineProperty(v.prototype,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(v.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(v.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[kn])return e[Sl];return null},set(e){for(let t of this.listeners(r))if(t[kn]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[kn]:!0})}})});v.prototype.addEventListener=vl;v.prototype.removeEventListener=kl;to.exports=v;function Qi(r,e,t,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wl,protocolVersion:xn[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(r._autoPong=s.autoPong,r._closeTimeout=s.closeTimeout,!xn.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${xn.join(", ")})`);let i;if(e instanceof vn)i=e;else try{i=new vn(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let _=new SyntaxError(c);if(r._redirects===0)throw _;ar(r,_);return}let d=o?443:80,l=hl(16).toString("base64"),u=o?ll.request:ul.request,f=new Set,m;if(s.createConnection=s.createConnection||(o?Al:Pl),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(m=new _e({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=xl({[_e.extensionName]:m.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!Rl.test(_)||f.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(_)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let _=s.path.split(":");s.socketPath=_[0],s.path=_[1]}let p;if(s.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?s.socketPath:i.host;let _=n&&n.headers;if(n={...n,headers:{}},_)for(let[S,O]of Object.entries(_))n.headers[S.toLowerCase()]=O}else if(r.listenerCount("redirect")===0){let _=a?r._originalIpc?s.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!_||r._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,_||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=r._req=u(s),r._redirects&&r.emit("redirect",r.url,p)}else p=r._req=u(s);s.timeout&&p.on("timeout",()=>{z(r,p,"Opening handshake has timed out")}),p.on("error",_=>{p===null||p[Vi]||(p=r._req=null,ar(r,_))}),p.on("response",_=>{let S=_.headers.location,O=_.statusCode;if(S&&s.followRedirects&&O>=300&&O<400){if(++r._redirects>s.maxRedirects){z(r,p,"Maximum redirects exceeded");return}p.abort();let ee;try{ee=new vn(S,e)}catch{let L=new SyntaxError(`Invalid URL: ${S}`);ar(r,L);return}Qi(r,ee,t,n)}else r.emit("unexpected-response",p,_)||z(r,p,`Unexpected server response: ${_.statusCode}`)}),p.on("upgrade",(_,S,O)=>{if(r.emit("upgrade",_),r.readyState!==v.CONNECTING)return;p=r._req=null;let ee=_.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){z(r,S,"Invalid Upgrade header");return}let te=gl("sha1").update(l+yl).digest("base64");if(_.headers["sec-websocket-accept"]!==te){z(r,S,"Invalid Sec-WebSocket-Accept header");return}let L=_.headers["sec-websocket-protocol"],g;if(L!==void 0?f.size?f.has(L)||(g="Server sent an invalid subprotocol"):g="Server sent a subprotocol but none was requested":f.size&&(g="Server sent no subprotocol"),g){z(r,S,g);return}L&&(r._protocol=L);let E=_.headers["sec-websocket-extensions"];if(E!==void 0){if(!m){z(r,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=Il(E)}catch{z(r,S,"Invalid Sec-WebSocket-Extensions header");return}let re=Object.keys(T);if(re.length!==1||re[0]!==_e.extensionName){z(r,S,"Server indicated an extension that was not requested");return}try{m.accept(T[_e.extensionName])}catch{z(r,S,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[_e.extensionName]=m}r.setSocket(S,O,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,r):p.end()}function ar(r,e){r._readyState=v.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Pl(r){return r.path=r.socketPath,ji.connect(r)}function Al(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ji.isIP(r.host)?"":r.host),fl.connect(r)}function z(r,e,t){r._readyState=v.CLOSING;let n=new Error(t);Error.captureStackTrace(n,z),e.setHeader?(e[Vi]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ar,r,n)):(e.destroy(n),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function In(r,e,t){if(e){let n=_l(e)?e.size:Tl(e).length;r._socket?r._sender._bufferedBytes+=n:r._bufferedAmount+=n}if(t){let n=new Error(`WebSocket is not open: readyState ${r.readyState} (${de[r.readyState]})`);process.nextTick(t,n)}}function Cl(r,e){let t=this[A];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[A]!==void 0&&(t._socket.removeListener("data",cr),process.nextTick(Ki,t._socket),r===1005?t.close():t.close(r,e))}function Ol(){let r=this[A];r.isPaused||r._socket.resume()}function Nl(r){let e=this[A];e._socket[A]!==void 0&&(e._socket.removeListener("data",cr),process.nextTick(Ki,e._socket),e.close(r[El])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function Wi(){this[A].emitClose()}function bl(r,e){this[A].emit("message",r,e)}function Dl(r){let e=this[A];e._autoPong&&e.pong(r,!this._isServer,Ji),e.emit("ping",r)}function Ll(r){this[A].emit("pong",r)}function Ki(r){r.resume()}function Ml(r){let e=this[A];e.readyState!==v.CLOSED&&(e.readyState===v.OPEN&&(e._readyState=v.CLOSING,Xi(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function Xi(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function Yi(){let r=this[A];if(this.removeListener("close",Yi),this.removeListener("data",cr),this.removeListener("end",Zi),r._readyState=v.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[A]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",Wi),r._receiver.on("finish",Wi))}function cr(r){this[A]._receiver.write(r)||this.pause()}function Zi(){let r=this[A];r._readyState=v.CLOSING,r._receiver.end(),this.end()}function eo(){let r=this[A];this.removeListener("error",eo),this.on("error",Ji),r&&(r._readyState=v.CLOSING,this.destroy())}});var io=B((zg,so)=>{"use strict";var $g=dr(),{Duplex:Bl}=P("stream");function ro(r){r.emit("close")}function Fl(){!this.destroyed&&this._writableState.finished&&this.destroy()}function no(r){this.removeListener("error",no),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function Ul(r,e){let t=!0,n=new Bl({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&n._readableState.objectMode?i.toString():i;n.push(a)||r.pause()}),r.once("error",function(i){n.destroyed||(t=!1,n.destroy(i))}),r.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,i){if(r.readyState===r.CLOSED){i(s),process.nextTick(ro,n);return}let o=!1;r.once("error",function(c){o=!0,i(c)}),r.once("close",function(){o||i(s),process.nextTick(ro,n)}),t&&r.terminate()},n._final=function(s){if(r.readyState===r.CONNECTING){r.once("open",function(){n._final(s)});return}r._socket!==null&&(r._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(r._socket.once("finish",function(){s()}),r.close()))},n._read=function(){r.isPaused&&r.resume()},n._write=function(s,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){n._write(s,i,o)});return}r.send(s,o)},n.on("end",Fl),n.on("error",no),n}so.exports=Ul});var Tn=B((qg,oo)=>{"use strict";var{tokenChars:$l}=He();function zl(r){let e=new Set,t=-1,n=-1,s=0;for(s;s<r.length;s++){let o=r.charCodeAt(s);if(n===-1&&$l[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))n===-1&&t!==-1&&(n=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=r.slice(t,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}oo.exports={parse:zl}});var go=B((Hg,ho)=>{"use strict";var ql=P("events"),lr=P("http"),{Duplex:Gg}=P("stream"),{createHash:Gl}=P("crypto"),ao=ir(),Ae=Ge(),Hl=Tn(),Wl=dr(),{CLOSE_TIMEOUT:jl,GUID:Jl,kWebSocket:Vl}=oe(),Ql=/^[+/0-9A-Za-z]{22}==$/,co=0,lo=1,fo=2,Rn=class extends ql{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jl,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wl,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=lr.createServer((n,s)=>{let i=lr.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=Kl(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=co}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===fo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(mt,this);return}if(e&&this.once("close",e),this._state!==lo)if(this._state=lo,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(mt,this):process.nextTick(mt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{mt(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,s){t.on("error",uo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ce(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ce(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Ql.test(i)){Ce(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ce(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){_t(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Hl.parse(c)}catch{Ce(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let f=new Ae({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=ao.parse(l);m[Ae.extensionName]&&(f.accept(m[Ae.extensionName]),u[Ae.extensionName]=f)}catch{Ce(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(m,p,_,S)=>{if(!m)return _t(t,p||401,_,S);this.completeUpgrade(u,i,d,e,t,n,s)});return}if(!this.options.verifyClient(f))return _t(t,401)}this.completeUpgrade(u,i,d,e,t,n,s)}completeUpgrade(e,t,n,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Vl])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>co)return _t(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Gl("sha1").update(t+Jl).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ae.extensionName]){let u=e[Ae.extensionName].params,f=ao.format({[Ae.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
8
|
+
var $a=Object.create;var pr=Object.defineProperty;var Za=Object.getOwnPropertyDescriptor;var Qa=Object.getOwnPropertyNames;var e0=Object.getPrototypeOf,t0=Object.prototype.hasOwnProperty;var Y=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Le=(r,e)=>()=>(r&&(e=r(r=0)),e);var ce=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ds=(r,e)=>{for(var i in e)pr(r,i,{get:e[i],enumerable:!0})},n0=(r,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of Qa(e))!t0.call(r,c)&&c!==i&&pr(r,c,{get:()=>e[c],enumerable:!(a=Za(e,c))||a.enumerable});return r};var Ne=(r,e,i)=>(i=r!=null?$a(e0(r)):{},n0(e||!r||!r.__esModule?pr(i,"default",{value:r,enumerable:!0}):i,r));import{chmod as r0,mkdir as s0,readFile as i0,rename as Ts,writeFile as Is}from"node:fs/promises";import{dirname as o0}from"node:path";async function ct(r){try{let e=await i0(r,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function $t(r,e,i){await s0(o0(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 Is(c,a,{encoding:"utf8",mode:i.mode}):await Is(c,a,"utf8"),await Ts(c,r),i?.mode!==void 0&&await r0(r,i.mode)}catch(u){await Ts(c,c).catch(()=>{});let{rm:d}=await import("node:fs/promises");throw await d(c,{force:!0}).catch(()=>{}),u}}var Zt=Le(()=>{"use strict"});function Rs(r){return en[Ls]<=en[r]}function mr(r){Ns={...r}}function Qt(r,e,i,a){if(en[r]<en[Ls])return;let c=JSON.stringify({ts:new Date().toISOString(),level:r,module:e,msg:i,...Ns,...a});r==="error"||r==="warn"?x0.write(`${c}
|
|
10
|
+
`):a0.write(`${c}
|
|
11
|
+
`)}function R(r){return{debug:(e,i)=>Qt("debug",r,e,i),info:(e,i)=>Qt("info",r,e,i),warn:(e,i)=>Qt("warn",r,e,i),error:(e,i)=>Qt("error",r,e,i),child:e=>R(`${r}.${e}`)}}var en,Ls,a0,x0,Ns,H=Le(()=>{"use strict";en={debug:10,info:20,warn:30,error:40},Ls=(()=>{let r=process.env.COZE_BRIDGE_LOG_LEVEL;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:"info"})(),a0=process.stdout,x0=process.stderr,Ns={}});import{homedir as c0}from"node:os";import{join as se}from"node:path";function K(r){let e=r??c0(),i=se(e,".coze"),a=se(i,"bridge"),c=se(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:se(c,"index.js"),pidFile:se(a,"bridge.pid"),portFile:se(a,"bridge.port"),tokenFile:se(a,"bridge.token"),logFile:se(a,"bridge.log"),installLock:se(a,"install.lock"),configFile:se(a,"config.json"),agentsRoot:se(i,"agents")}}function Re(r,e=K()){let i=se(e.agentsRoot,r);return{root:i,config:se(i,"config.json"),workspace:se(i,"workspace"),logs:se(i,"logs")}}var fe=Le(()=>{"use strict"});var rn={};Ds(rn,{AGENT_CONFIG_FILE_MODE:()=>tn,enforceAgentConfigMode:()=>d0,loadAgentConfig:()=>de,persistAgentSessions:()=>_r,persistAgentSkills:()=>nn,saveAgentConfig:()=>we});import{chmod as u0,stat as f0}from"node:fs/promises";function de(r,e){return ct(Re(r,e).config)}function we(r,e){return $t(Re(r.agentId,e).config,r,{mode:tn})}async function d0(r,e){if(process.platform==="win32")return;let i=Re(r,e).config;try{let a=await f0(i);if(!a.isFile())return;let c=a.mode&511;c!==tn&&(await u0(i,tn),Ms.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;Ms.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function _r(r,e,i){let a=await de(r,i);a&&(a.sessions=Object.fromEntries(e),await we(a,i))}async function nn(r,e,i){let a=await de(r,i);a&&(a.skills=e,await we(a,i))}var Ms,tn,Ge=Le(()=>{"use strict";Zt();H();fe();Ms=R("agent-config"),tn=384});var Ti=ce(Z=>{"use strict";var S=D;(function(r,e){let i=D,a=r();for(;;)try{if(-parseInt(i(554))/1*(parseInt(i(1769))/2)+-parseInt(i(1665))/3+parseInt(i(1548))/4+parseInt(i(1317))/5+-parseInt(i(517))/6*(parseInt(i(1805))/7)+parseInt(i(868))/8+-parseInt(i(1361))/9===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Tn,243679);var Rx=Object[S(1198)+S(775)],Mx=Object["getOwnPropertyNa"+S(1595)],Ci=(r,e)=>function(){return r&&(e=(0,r[{nxkUk:function(u,d){return u(d)}}[S(869)](Mx,r)[0]])(r=0)),e},Ox=(r,e)=>{for(var i in e)Rx(r,i,{get:e[i],enumerable:!0})};function Tn(){let r=["B1PZzMi","De1HBMfNzxi","z2v0qwXS","x2n1CNnVCKy","Ae5nA20","qKX1Ee0","zNjVBu51Bwi","ruDWtve","z3frzfO","s05tDgu","x29UvgLTzw8","BwvZ","v3riCM4","AKDHC1K","zsbHihn0CMK","AxH6BeC","BxbYv1y","u3vmzKu","y29Uy2f0","tMnAueW","s1rxB1K","zuzSzxe","yxbWBhK","Eefosgi","B2jQzwn0u3q","vuPIq2W","s2jqBhO","yKHNDKi","yw5Hz2vY","u1zjC0y","EunkwxC","wMXmq0y","zxjYtxnN","wMH4v3e","x2rPC3bHDgm","zgjNCMK","B25ozxr3B3i","rvHKs3G","uMvHzcbWyxm","zvH4tu4","BgLUzq","C2vYDMvYvgK","y2XVC2uSihC","sgLjseW","DgfIyxnL","BM93","tufJvfy","B3v0sw50zxi","sfneqwG","B25tDg9Wsw0","x2rPC2nVBM4","rLb6tNC","q0Xpu0LorW","CuPrveK","mhW1Fdj8mxW","y3jLyxrLq2W","zcWGDw5RBM8","uK9dwu8","ywrKrxzLBNq","x25HDMLNyxq","CeXNyxa","se1dwvO","ufHdwu0","DerwwvO","seL4ugu","z1fODhK","Dw5RBM93BIa","BgvY","vvfLru4","ihrPBwvVDxq","o2nOyxjZzxq","vLvuqxe","rfPAt0i","uvfKqva","C3vJy2vZCW","ruzrBwC","Bwf4twvZC2e","C0PYyxu","sgjvzxe","CMvJB25Uzwm","D212shG","mtK4mtiZEeP1wLHX","rKH2qNa","A0H2svO","tgjZDg4","BhHLA2G","AwnVqxK","x2rItMfTzq","uu1VEgq","sNLttxu","Aw5KzxGGB3u","Cg9PBNrbBMq","u3zjz3m","BwvIwK0","CKDbENe","CNzHBa","uwHPtgS","su5tvefova","y29UBMvJDca","ENbnENi","sw9ZwLC","x2vUzhbVAw4","C3vIC3rYAw4","CLjAt3i","y29UBMvJDfm","qMrqtgi","Ew5OrMO","zK9OCve","x2HHBMrSzva","zxjFywnRx20","Eej6rvG","sxzuDeu","D2rXt24","t1rTsKG","zhvlD0S","rfHhsee","y2XVC2u","AenYBhm","EKzJsxO","CYbWyxjHBxm","Ec11C2uT","zxnsv2S","BwvZC2fNzq","rfvJEum","DvLAuNu","y3jLyxrLuMu","C1vPs1u","te1xB2m","z3zeBK8","D2vI","rxzLBNq","yKXevem","qw5fugy","Cufgs0C","CMvJzwL2zwq","BxnNsuq","Aw9xyLC","tuD0EKe","C1nTCuy","zff4vwW","CMvHC29U","zevZC20","zxHWB3j0CW","sMfYq3G","BgLUzw5V","rgH0vfK","CMLLC0nVDw4","wg95wgi","AevYCM9Yrxy","uxfzC3i","ANbOuMG","AgfWq2O","mxWWFdn8nhW","ywLRuwO","zxq9DxrMltG","DfnACNC","twvZC2fNzuu","tuvtu0fhrv8","C3rVCcbPBw0","CgzRCxO","vvz4C08","yMfSu2nVCgu","CKL6CxO","uK5RwKG","yxbWBgLJyxq","Cu9tzhm","x3fVC0rc","x2n1CNnVCK0","C2jdEfO","Cg93","C0LfyxC","Dgv4Dc9WBge","vxbKyxrLq28","q2PnteO","DwHHEu4","vuLVtwS","C3rHCNq","AefZt0C","zfjTBfi","CgLUz1rPBwu","B2XKvMvYC2K","rMneyKu","DxrVuMvJB24","rvLNzxK","ywr2yw5Jzq","mtaXntrRDxfpvLO","zw5fDMvUDa","rxfvsfK","DxnLCKLW","AgvHzgvY","C2nYAxb0","vMXbr2G","B2fK","yKDvs1i","id4G","rxjYB3jdB2q","uvPes04","z2v0u3rVCMe","q2jwr0G","Dg9Y","BwvZC2fNzv8","EMPQwhO","r1fPvu8","zw1LBNq","s2XvzMy","zMzmAw5L","sfjosNa","CMfUzg9T","x3vYBa","y3vYCMvUDeu","x2jPBMfYEvq","CfHhywy","zNjPvxi","t3zyuvC","CwDczMi","y3jLyxrLt3a","ChjVDg90Exa","BMrWB2LUDfq","x29UugfNzu4","u3bHyMe","AwXK","nJyWnZnqywHVz2u","yMfJA3vWigu","zgvJB2rLzey","sw9WDuu","EKn1wvG","rMXqBKS","A0fVCMS","AxmGDw5Kzwy","rNbuCKm","x2LZqNjVD3m","u2XwEMK","ysbTDxn0igi","vw5PBxbSzw0","Cgu6ia","CNnVCL9Uyw0","CMvZDwX0","zw5XDwv1zq","C2T1Cui","zfHAwe4","DhjPBq","CM92AwrLihy","ChfmsuK","zw5JB2rLrNi","u2TAD1a","zgrjrcWGzgu","wMnKvfK","vwLgvhq","AhPdrvO","mhWY","DxnRr3u","A0DnwwS","t2H6weK","Dg1fzLO","AgvKtwf4uMu","yNvMzMvY","zKT6vMu","svn2zee","rxrPBKi","C2XPy2u","rKj3v2m","suTnrM0","uwHtBvy","y3r4","z2v0q3vYC28","AhLMDe4","BMrLEa","yK5hz20","CM92AwrLigi","Bhm6ia","r0jTtu8","zNjVBunOyxi","quXm","D2HQr1i","AwXLx25HBwu","x2TLEvbHDgG","BvvSteO","nhWXFdv8m3W","v0DAwM0","qxruBMq","sg9Ytu4","z2v0q3vYCMu","CwXqyvy","Eg9bq3K","DMvYC2LVBMm","ANzSrLi","s0jqEwq","tvPfrMK","A0DstM8","zxjFBxnNAwq","C2z4qNG","zfHzuNq","BLDKq0C","EhHuree","Dg9VigXHCMC","ig1LC3nHz2u","uMT2B1G","tw5rrwC","mhW1Fdj8m3W","rM9hvNC","DMfSDwu","DwHMteW","Aw9dtw0","yxrLq291BNq","zv90Aw1LB3u","tufyx1jfvfi","Dg9cExrLC0W","CejjshG","vwDTtvC","BezSDxnO","zw5JB2rPBMC","t2joB0y","ChjVDg9JB2W","x2XPC3rLBMu","ve14zMS","s2DruMe","zcbLCNjVCI4","ywnOzwq","BvHjDvm","y2fSBa","ihzHBgLKihm","vKzfq0C","BfrPBwvVDxq","BgLTAxq","DwPPCuG","BLfPruS","ywXS","t1bvEg0","v1DzEM4","CMvHzhLtDge","D0fTrvG","ENLSyKC","EK91uNC","vwfeDMS","twjUqMO","y29UBMvJDeu","uu1QD2u","Bu5LAvq","r21dvg0","EwnYrvm","DhbizwfKzxi","CNnVCKzPBgu","BNrLCG","Bu1owgW","EgTZyMG","t0XPzva","DhjHBNnHy3q","BgvUz3rO","Bez1tu0","tvnAuhC","yxnL","Aw5KzxHpzG","uMLHzLK","whvzzMS","CgfYC2u","ywrK","BwLUzW","Bwu6ia","C3bbsvm","vfP2thi","AeryEva","zwnVBM5Ly3q","yNvMzMvYzwq","vvztyw0","uhfcsKG","x2LZsw5PDa","EK5xAgm","Aw5N","y2XVC2veqG","u2TIs3K","rxLMsve","AgnfzMy","EsbJBg9Zzwq","n3WXFdH8mhW","re5jqLG","x3bHDgHlzxK","qNL0uvu","ExbL","Ae1AEui","x2nYzwf0zvm","we9pzfu","BKjlAK8","tLfLB1C","tK9zugy","AxnAzxjV","shzjzeK","zNHcuKK","sufLrg0","yxzjDKG","zMLSzw5HBwu","C0jf","CMv0CNLdB3u","ywWGy3vYC28","zw50tgLZDgu","yw5Nzq","x2rLyNvN","sLfdyLO","wK5tsvC","u3LNvLe","rLjptLrjrvi","vwL4we8","yMnswhq","uMvJB25Uzwm","Bg9Nsurhzw4","rLbMz28","u3rYyxrLz3K","v01Lv3u","CMfTzq","AwDHDg9Yt24","z1rPBwvVDxq","EKjct1a","CMvTB3zLq2G","uMLdt1y","u1Dpvu8","Bwf4uMv0CMK","DMvUDa","CM92AwrLihC","DgHLBG","wwrXrgC","wMTRsLK","qLLXvNi","DcbVzIbYyw4","y2L3vgC","q09rAwO","ChbL","rNfVCuq","r2Xivu8","A1PNrwO","uhDgq1m","BNrbBMrvCgq","AfbxtvK","AxnrB1nby2S","vgfN","A1jhtxe","x2rLC3rYB3K","tfzYDwy","Dg9cExrLC0i","BeH5uei","DgvZDa","mJuYCLLJuvLU","Aw5Lza","BKX1uhK","rxnxrNi","DwLWA1q","svv4v3O","qxnfu1G","CMTLCKDSB2i","CvnwAe0","ywXSzwqGBxu","shbmy1K","rfHLBwm","vK9iAM4","rvPYBKG","ign1CNnVCIa","vuLUyu0","x2LUAxq","CvbKrwq","z2v0qwXSs2u","Aw5KzxG","yvrguwG","r1D6rLG","AvnWD3m","wxfUEKC","t3rgsLK","AgfUz2u","y2uGBM90igK","DuDWv2S","CNrABxG","Bwv0Ag9K","AxH1q1G","DvbAv0G","x29UtwvZC2e","CgLUz19VBMm","CMH3wKO","AxDqExe","Bwf4tg9ZC0m","oufMuuDhDq","rvjhsKe","zwTSsNi","zuTswxK","y2DPweu","yNL0yu0","ywXSq3vYC28","t0rPtfa","wNr1CMu","zgTithi","Dfrmtui","zMX1C2HfEha","ywnRDxbfBMq","rgX0wMe","uKvnEuC","zKrJu0W","B3jpBMXPBMu","wLLTuuu","DuDtAhq","r1z6q0m","DxbNCMfKzw4","vKHHtMS","CgXLyxnLiha","x29WDgLVBNm","CeH5ANG","DwzcwvK","ihrPBwvZ","Ae1LC3nHz2u","zuLZCMm","AwrI","EgHJwgy","zhzwzgu","y3ruAw1LB3u","suPfwhG","v2HhrfG","BwfW","ugTLD2u","ywX3yxLZ","B2zMC2v0","DcbSAw1PDa","qKzMDhi","y2HnyxHdB3u","vfPbr1y","B2nRzxrtDwm","te1XCxm","rff0qu0","y29UDgLUDwu","rMn5q3m","BNrfBMrWB2K","z2HzCKy","zxH0zw5ZAw8","B3bLBKrc","t3vyuvq","wwvPy2G","D3LVANi","zMvY","B25tDgfYDfi","tu9fCwe","vhnKBNK","ChvZAa","ChPfC1C","CM9YrxzLBNq","B25LCNjVCG","qNjKBve","s0foq3m","C3rYAw5NAwy","Chv0","q05sA28","wwT3rxi","tefPswW","EMzgwfC","zhjhDM0","q1v1vg8","x3bYB3rVy28","pxv0zI04","vhbYz2e","AefJA01LC3m","vKD1Cu8","AxnrB1nnzxm","sK5cChe","rMXjwxG","uMrnvgi","z2vjBMzVu3K","z2vtEw5J","y29UC3rYDwm","rwzgsei","DgLUzYbZzxi","lcbOB3n0BMe","AvPOtwm","Bfbcv0S","Dhr3Awq","y3jLyxrLrwW","rNzUDu0","r0zTrfe","CNjlAue","rwHAv24","zhnhB3O","qwjVCNrfCNi","z2jvrxm","AfvuzNu","uxbvq0K","Aw9Ul2PZB24","Cg9W","z1bhz3m","yMLUyxj5vhK","yxbmCfO","vNrUt2u","yw51Ce1LC3m","sgrHuxG","Aw47y2HHCNm","r1PLywO","rLnTD20","C3vIyxjYyxK","zgvSzxrLrge","wu5WvgG","D1PjBgu","vw5Lww8","sLrIBve","rhjuEKO","tgTouxe","Ahr0Ca","uvfftui","x1fVu01HBMe","Ahr0Chm6","rgvPzfO","DgHHBIbSB2m","x0rctMfTzq","vgLTzw91Da","AKXwA1u","qNjPzgDL","Dgv4Dc9Qyxy","vKvWteW","EMnczNG","zxLeqKS","thvuD0y","wevcBhu","yKDmr3y","zgvS","tfLSCfi","yvfRDNG","BvbUC2C","Agnfwum","x3DHAxq","BNHVqKq","C0Xf","Dg9iyxnO","C2DPza","z1nqB1u","vgP1BLC","A2TAAfq","zvbSALy","s1LSC24","rKzmC3a","DgDLDgG","DwjMDwm","A2v5CW","q0LfDeW","B2XSwxq","zw5HyMXLuw8","tKHguu8","t2PZBMK","q29UzMLN","DhjPzxm","x3nLBMrby2S","CwPrDeq","tuHJtMy","rLrpAei","yMPLsLy","x2HHBMrSzu8","jMPZy2fSBgi","yKT3uxm","zwXAzu8","yxHsAKq","tKfusvzfx0u","DhLWzq","u2Xht3a","vMLRCeu","CMvUDevUzha","qxDNsvi","q3rkBvC","veXOAg4","ExnUBKi","x2DLBMvYyxq","wKDyu1K","u3HTvLu","v0TNDNa","sw9iwK4","C2vUzf9Hy2S","qwD6uKO","B25pCgvU","D0f4uuK","DMvYC2LVBG","ve9fweq","v2ThrwK","zLPZsNK","AfPtqM0","z2v0","tNrgEeS","zNjVBuj5Dgu","r1nwAfm","x3DZsw5ZDge","wfDtCuy","BMv4DcGPigm","y2HusKq","y2HLy2Tszwe","yxnJCMLWDa","Aw92Cee","CNLHDfG","C29Tzq","DMfJwM4","igXHCMDLCIa","q09oveLovuu","rNjVBNrPzxi","zgTNB0q","qw1VDw50","DMvY","wK9vBKO","DhrkEvm","CgvjCei","yxnZAwDU","tfLVAMi","B3bLCNr5","BMnLq2XVC2u","C2rUr0e","uLDrz24","Fdb8nxWZ","vgjeDNO","yKPWwKu","yxrHlcbKyxq","u2j5A24","ywnOzwqSihC","y29SBM8","CfzfvMu","qLfpv3u","x2nSzwfYvgK","ExDgvu0","Avn4t3i","rfbKrxy","ywXRrKy","AMLmuNO","vNzvC0K","x3DZ","vNPfzKG","D0PRBgq","yxPKA0C","y2LpELa","D1fzu0e","B3jL","A0DprfC","BxHvD0S","zw5KCg9PBNq","zwvKzwq","uhvjqNK","mdaWmdaWmda","rvDzCuO","B3jRzxjhBg8","zLjdvgq","D1DTwwi","yxv0BW","z2u6ia","vKTWqxO","uxvLDwu","x2LZv29YA2u","CK1xqLC","zLrRC1O","B3jRig9MzMW","A1n0yxr1C0m","rePuugK","sKPUtg0","q3vZDg9Tq2W","BxnN","z1nczuG","y3jLyxrLrxi","s2HuCMq","CMvHzhDYAxq","sKHSCuS","sNLTEKW","DKfVEgC","DMLJzuLeig8","wgzywMK","BNHtC0O","A3fNqvO","uLbPzvi","rhb1tuS","t3bLBKv2zw4","x19LC01Vzhu","AhDHtfC","qKjps1y","sKDjs3m","CMvWBgfJzui","EwvxwwW","EwXOtw8","yufhwMS","quv3v2u","r1bPDxm","x29Ut3bLBG","Dw5PDee","r3vtuvC","vMfcvMG","rKLmrv9ot1q","ywnRx2LK","Dxrjza","ventAum","z2v0s2v5","rwDnr3y","rufetKO","tM1KBwO","vKnoBeS","DfrbCNa","rMPTuhy","v2Ttrxm","C3bSAxq","wMDzt2O","BfzQvgO","mJKWnJyWmeT1txn6Ba","BNHRvwS","AePUwwu","t1bftL9fuLi","CgLUz0LUDgu","D3rfDwe","C29YDa","sezfuKO","BwfUDwfSihi","DM16D1e","Exz4u3e","yxKSig5LDhC","u2HHCMvKv28","v0f2zwy","yxv0B21HDgK","AwXSihvZzsa","y2XLyxjtDg8","sLrHCuO","C2v0q3vYC28","uNfjEei","C3Hvs3u","DgzuANu","DgLTzw91DcW","Cvn6AMy","AxnszwfKEq","yKH4A2q","s0jIzhy","AxnmB25N","zw50zwqGDhK","vvz6t2u","CvHhvgu","BMCGzMfPBgu","mNW0","rvLesfa","s1vKEwi","B25dBg9Zzq","y1jUswW","BhnVAgi","zw50","CMPMwLm","vvzevxK","A1DUvfG","AxfdAhi","BMDLza","t2nxDfa","r3jIDve","tgLZDgvUzxi","CgfNzwHPzgu","q0Xpu0ve","ywrKq291BNq","AenSB3nLrxy","x2LUAxrhBg8","twLZC2LUzYa","BKjPCuy","x2HHBMrSzvi","r1DTD3a","zNDZxZeUmc4","D01XrgO","C0zSAuC","zv9ZDwnJzxm","C3rLBMvYCW","ExDpzLK","tMHgAM8","zLLvDKe","svvyrey","mxW0Fdy","z3r6zgG","rvjst1i","rKLTrgi","ELDSvgS","ywDL","DhDVCMTdAge","BeHHBMrSzxi","zLPKCxu","zg1orwW","C1bRtMC","zhbdv2G","yNrHugu","B25Uzwn0Aw4","tK5uEM4","wez2zgW","Dw5ZAwDUzwq","Cu95qw0","vxDWCKC","EK1msLq","twzHtKy","y3vYC29Y","D3nZoI8V","BKvLy0i","Ae9Wzw5fDMu","ALvysfC","wgzjwxm","C0nVDw50zxi","BM1iwNK","AMrMsvC","s1Pwv2i","mxWWFdj8nhW","txLotfu","vM5Lqwe","zw1PDa","CNDpsMi","rMPNzvi","DgPRsMy","zM1rzvK","uNrqugG","yNDbDwC","zg9Uzq","v2v2rKy","AgvHzgvYCW","uNrRsLi","zcWG","ihbYB3rVy28","D24GCMvHC28","vfvuqLq","wfPsCNC","EKXvEKC","tKjgu1i","CuPOBwq","s3zrDwe","q0XcvKC","uLHpv0S","uNreB3O","yLDksfa","ywTeqLG","Cw9Zx18","sMndt2i","s1Lhuuu","ruPwA2u","BuXXwvy","DeLK","re5Lwei","vwfdv0O","CgLUz0XVC3m","CMvZzxrdB3u","CfrcBKS","zerNu1a","y291BNq","Dg9oDw1Izxi","zxj2AwnL","B01rreO","v2vIu29JA2u","r2PNrMe","t1rmuLe","C3nHz2vfDMu","CMvTB3zLrxy","vw9gwNG","sNL6C3G","BNruCMLLC0m","yMXVy2TLza","zwHztuW","u0zrEfa","rwfRAK0","AfvhyvO","q054ru4","EvjLy29UBMu","y29UBMvJDa","zxjYB3i","AhjTqM4","yMzKA1a","nxW0Fdj8mxW","Aw5JBhvKzxm","DhfRu3u","yMLUza","uhnNEhe","C2vYDMLJzs0","B2XKy3m","igfYCMf5yNu","y1nhzM8","tvPYwhC","C2vUDa","BwvKAwf0zwW","BKT4DKy","zwzuwMK","zw5HyMXLqxu","AvvcwNm","rMXwrxC","AMPPAMq","AuL0vwK","BMHnENy","Def6BeC","D2fZq2XLyw4","DMfSDwvZ","Bg9NsurozxC","ueHSAve","DKPpBvi","ywnRtxnNswq","EwHHtee","v3jPtgS","u2rjD04","B3Dxzha","s293rvG","x21LC3nHz2u","A2j2vMe","C3nIAwm","wwHhvfm","sujxzxO","yNL0zxm","AxnFywnR","x3nVy2TLDa","zvftqNm","x2DLDeLUDgu","y3vYC29YlNm","B25VCgvU","vhLys1K","y2XLyxi","DLrbyLq","Bg9N","Avr3zva","zMXVB3i","DhjPzxmGCMu","zxjFCw9Z","ihrVihjLDhi","Afn6ue4","qwjdwwe","EKzPrLC","ywXPzcb1CMW","ChjVy2vZCW","z0nbDuK","BMrWB2LUDca","zNHYC1K","rejir2S","yMDqwxK","BwvY","thfjrhu","yvz2zeq","CwDYyuC","s2niwxK","z2v0sxrLBq","DNDls2u","B3jLtMfTzxm","uMrrD20","Cg9PBNrdB24","v3v6BKy","tNPvz2i","AxPXCNC","ue5rBei","Eu5cvwm","B0TYB0W","ywDLsgLKzq","vxrIBgu","AxnbCNjHEq","tMXev1a","v1rswhC","z2n4EMu","u1P2B00","ywDLrxzLBNq","Dhj1y3rVCIa","EwXOCMm","rfbpuuO","tKfzB1a","wKvkyNy","B3bLBIa","AundBvm","zvvYBa","u2vXsuq","igzHAwWSig0","DLnKrNG","tfrMvfm","Dg9cExrLCW","r2vjExC","vwXUAw4","thLQrhO","vuzmzxO","vg1eExC","zNjVBNrPzxi","z1vpCwC","yujZuMO","wLztseG","DK9OA1q","BhrPCgXLihq","qwvVB0C","q09otKvdveK","DeflvKq","AMTztwe","C2v0","C2vYDMLJzq","tKDFrvjst1i","zM9Yy2u","zM9YrwfJAa","CNjVCK1LC3m","CevxuuC","zwjAqva","B2zMBgLUzq","Cg1WDgW","x2nSzwfYugK","tfHmDhu","y2HLy2TdDxi","r21xA1m","x2LZtwLUAvC","C3rVCMu","wwHstLq","AwXLtMfTzq","zKTWtwC","icSG","BMXcy1K","ueXms2m","rhDlDgS","B25szwnLAxy","BMvY","z0LgyLy","yM9L","CNPrwwG","rwXQyuO","q2PHsvC","rhbmDNK","Aw1LCYbPBIa","B3vUDa","y0fdsKG","z1zmALO","DLHYz2m","zM9Qqw0","x3jLy29UBMu","zgvIDwC","BIWGAg9ZDg4","Cgf5Bg9Hzfq","BuHUy1K","ChrVCG","Ec1TC2CTy3u","Cw1NBg0","z0z6wgm","Dg9tDhjPBMC","uvbNB1K","zhrQqxq","CMvZzxruCMK","D0fID1m","u2vYDMLJzvC","y3vYC29Yx2y","zMLSDgvY","qxnTD2u","CYbHBhjLywq","zgvMAw5Luhi","rw5vr0W","x2LZtM9Kzq","y2vZC0HHBMq","yw1L","Du1vqw0","ELLXsve","AKTTy2y","yw1Lu3bHy2u","whDHuge","EhvID1q","z0jbsNa","EwvvEuy","wuXnue0","ufr4su4","sLnptLa","BhLAvuG","t3nMvvG","BffsBuK","B1nJBNa","ENDgu1e","EuHczMy","CMvWBgfJzq","y29UBMvJDgK","Dg9mB3DLCKm","y09Wzw4","ihzHBgLKigq","DMfS","AgzJEvu","x3bPBMDqB24","BxvcywW","lcbTyxGGCMu","nxWXFdn8mhW","zgf0yq","verjzwm","zxrxB3jRq2G","DxrMofDYAxq","C3bSAwnL","Aw50zwDLCIa","BMfTzq","x3bPBMDmB3m","rurUBhC","B3nLrxzLBNq","r2fUs0S","CfrjyLi","Dg9hzw5LCMe","vMvLru0","yMHws0e","qxbbyLq","D3m6lY8","DgTOvwi","C2fNzq","tuHquNe","Aw5L","zvDcC0W","rNLWCeO","CMvHzfvjBNq","x21PBMLoyxy","q29Kzq","q0HKtLy","sw5Vsfq","zufJAW","Cgf5Bg9Hzeu","vLrMAui","DeLUDgvYy2u","rLLpq1u","B3bvCKS","z1nYswC","Auf6qwK","quXZsKC","wef2DMu","BMDuAw1LCG","zvfKyKG","mNWWFdn8nhW","yujwzem","zwn0","zKHLyM0","vM51CM4","qvvRwhK","wNLRte8","Buv0EgG","uM10Dxy","wMHTAe8","AxPrD0i","v3PtDMq","C0vfA1C","Dw5KzwzPBMu","DgLTzw91Da","yNHVv3G","BKXPBMu","x3bYzwzPEa","CxPdENy","tg9JAW","DvvVDe8","B0T3uKe","Cgf5Bg9Hza","uLjpuG","A1LVq1a","y2HnyxHuCMK","sgrPrKS","C1vPwNC","sLzYDxy","rNDHu0S","x0vysvnu","Bg93","B3LduhG","qMnjBwK","zwrPyxrLBhK","q21Ut2S","qNLwtLi","qxzfvw0","rgXRseW","DeXLr3C","yMHnqxO","r1Hry24","DgXLzuu","Auvbyuu","v3Dlvxy","tvn4q1u","mtaWmZy3nxHfte5VtG","CuTMwLG","BwLZzq","zfnXtuq","Ef9MCM9UDgK","x3jLywr5q2W","z29PBMCGyxC","A1bwwgO","uhjPBwfYEuS","CwjNtee","BMnVzgLUzW","yvLsDw4","yxbWzw5Kq2G","zNbMzK8","BML0AwfSAxO","sKLnEhG","zNjVBuHHC2G","yNL0zuXLBMC","Ec1TC2CTCw8","DNLcyu0","yNL0zu9MzNm","y2HHCKnVzgu","ugjOCwe","Dev2zw50","uKLqALy","Eg9WDKm","ELP0uvq","ALLOuMS","Au5RCK8","uMjYsxa","DgnuD0W","yLnSsg4","zNjHBwvuExa","B25mAw5L","Aw9UvgLTzw8","rLDt","x3nLCuLK","q2T1Cuy","twzkBK8","B25TzxnZywC","vMjkBee","DeD5B28","Bg9IywXty28","y3jLyxrLtwu","oty5nJC4sezmr01Z","AxjLza","vxfWsg8","EKvnzg8","B2nRzxrgywK","y0H4tNC","q3nnDhy","B2nRzxq","y3jLyxrLt2i","svHvse4","zgvSzxrL","x3jLBw92zvC","CMvQzwn0","DLbZwee","uw52v0i","uLHbsfa","Aw5PDcbrB1m","swjXt08","yw1LoIa","yKnxtwi","yKvJC0q","yNLL","CNzHBfzHBhu","zxmGCMvHy2G","y29Kzq","ze95BMO","y3vZDg9Tshq","yxbNrKi","uhn2EMm","x2LUAxrqCM8","EhPtCMu","AgzHqKS","mNWZFdb8nxW","y3vYDMfSDwu","t2L0Euu","A2v5","x2LUDgvYDMe","Dgv4DfbHEwW","CYbPBNn0yw4","DezHDgO","wwfKBfC","AhvrCgC","C0vVuuW","wKnRtLK","CIb0DhDjra","v2vZrK8","C2vUza","z2vY","DvDICum","uvDhDhy","B3nLza","shLMwKG","ywnR","ywDLu2HVDW","AvnuEeu","vxDRzhi","DxzgrNK","yxGGCMv0CMK","C1zvzvK","wgrswM8","CM1QzKi","x3bPBMC","u2TPCcbWyxm","B2zM","vu1gD2O","sM5YvNO","mdaWma","yMfSrxzLBNq","rfbyA24","BvHwugW","DxbKyxrLq3u","CMvXDwLYzwq","BNHdq1O","Awvwyum","Cuzqyvi","C2v0u3rVCMe","tg9Nsuq","CLzHBhvLCW","wxbcAMq","B3fPuxy","x2rYB3bhBg8","zMLUza","ywnRx2nVzgu","AgLOu0u","s2PhDwu","u2P2zhG","C2v0sxrLBq","igzPzwXKoIa","u3nirNC","D2fcCLC","l3DZl3yY","thvqqMO","ihrYEsbYzwm","CMjSrva","x29Uq2XVC2u","AM9PBG","v2LgAhC","reHxwK0","D3jPDgvvAw4","zNjVBujPDhm","zNvUy3rPB24","CM92AwrLige","BMCGB3iGyw4","vencrKK","y29TCgXLDgu","zxjFCw9Zx2e","zxjHDg9Y","suXlsLO","zw5NDgG","z0XYEeu","B25JBg9Zzq","x2LZtwLUAvq","AgfZ","wNPOEKK","rMDKugG","CMfTugfYyw0","DwrrC0y","C3jJ","C0n0wLK","yxKSihrYEsa","zwvdt3q","EvDVCMO","m3W0Fdj8mte","u1zzv1y","C3vAt2u","rvL4A0C","D2LSBfjLy28","y3vYC29Yx24","zMLN","zxf1ywXZ","C3rYAw5N","D3jPDgu","nNW3Fdr8mq","CgjICdi","D1fMueq","AMvJDfn0B3i","s29kqva","tMfTzq","uNvRB1K","BujcALu","vwjfC0O","y3vYCMvUDeK","C2v0zgi","yMrFzgLK","x2fKzfDZtgK","nNW4Fdf8mta","y2fTDgC","C0XPC3rLBMu","zerkrgG","q0LiDfy","x29UrxjYB3i","t1bftG","thfms24","Cu9tyuq","wxHzAMS","A3rhvhi","CgfNzxnOB3C","s0DNsM0","yM9KEq","tw9YA1e","rMn0sfG","CgvYC2LZDgu","vgzQwui","EePxC0G","seLgvg0","AwrPBw4","BMvLzf9Hy2S","EfvZzuvUDG","B2LUDfjLywm","x2n1CNnVCK4","y2f0y2G","y254q3y","s3v3yNi","y1bKCeG","shjSqK8","CLvlD1i","Ew10AvK","EufuAMS","sKfmwNq","vwzOy1u","y256ChC","wNj3sMm","suvtx0vsuK8","ve5PA3i","zMzMzG","CMvZzxrfBMq","rLDOwwy","mte4mJeZmMvNufPOAq","vKnSAK8","zxH0ugf5Bg8","yLzJB0m","D3rbvKy","DeLStwm","zNrQs0m","u0zNsu8","x2zVCM1HDeu","BgnAsfG","werkzxm","vu1rreG","EKPxrhO","uwTAz3q","AgLNAa","vwjHyKu","q3vZDg9Trxi","q291BNq","BhvxDeS","Aw9U","BfPJA2O","ugrLAuq","CvPsC2S","zM1dzKu","CMvZB2X2zq","BMzjzwG","AgfZt3DUuhi","x2nVBM5Ly3q","uKDeq1m","rMD3yLC","u2jmEM8","uvfbuvq","t2jQzwn0","uKD1vNK","te1Mzg4","DxjS"];return Tn=function(){return r},Tn()}function Bx(){return yi||(yi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function zx(){let r=S;return bi||(bi=[IDBCursor.prototype[r(1768)],IDBCursor.prototype[r(600)],IDBCursor.prototype[r(600)+"PrimaryKey"]])}function qx(r){let e=S,i={rwOJb:e(1024),fgopR:"RSMyH",rtZmx:function(c,u){return c(u)},sdnGA:function(c){return c()},wyojr:"success",wtAVF:function(c,u){return c instanceof u}},a=new Promise((c,u)=>{let d=e,l={VbJlA:i.rwOJb,hDXyP:function(w,C){return w!==C},WevFF:i.fgopR,nBiqF:d(1573),fqQkh:function(w,C){return w(C)},grDUZ:function(w,C){return i[d(545)](w,C)},vmzwQ:function(w){return i[d(777)](w)}},p=()=>{let w=d;r["removeEventListe"+w(1166)](w(1658),_),r[w(1012)+w(1977)+"ner"](l[w(1357)],v)},_=()=>{let w=d;if(l[w(1944)](l[w(975)],l[w(921)]))l.fqQkh(c,l.grDUZ(ke,r.result)),l[w(877)](p);else return _0x18d1b6||(_0xdf8ed8=[_0x3bcfa1[w(1800)+"e"][w(1768)],_0x249ca4[w(1800)+"e"][w(600)],_0x220087[w(1800)+"e"][w(600)+w(1325)+"ey"]])},v=()=>{u(r[d(1024)]),p()};r[d(1642)+d(914)](i[d(608)],_),r[d(1642)+d(914)](i[d(968)],v)});return a[e(495)](c=>{let u=e;i[u(1552)](c,IDBCursor)&&Ar[u(1142)](c,r)})[e(1531)](()=>{}),Ln[e(1142)](a,r),a}function Fx(r){let e=S,i={fzuRL:e(651)+"or",TbDvz:function(c){return c()},PTxIN:e(1465),MfJnO:"error",huQpg:"abort"};if(In.has(r))return;let a=new Promise((c,u)=>{let d=e,l={LTfTS:i[d(1212)],Rmtuv:i[d(1355)],kLuQn:i[d(1402)],eKRYy:function(w){return w()},AsESX:function(w){return i[d(780)](w)}},p=()=>{let w=d;r["removeEventListe"+w(1166)](l[w(1125)],_),r["removeEv"+w(1977)+w(1166)](l[w(1279)],v),r[w(1012)+w(1977)+w(1166)](l.kLuQn,v)},_=()=>{let w=d;l[w(557)](c),l[w(523)](p)},v=()=>{let w=d;u(r[w(1024)]||new DOMException(w(651)+"or",i.fzuRL)),i.TbDvz(p)};r["addEvent"+d(914)](i[d(1212)],_),r[d(1642)+d(914)](i[d(1355)],v),r[d(1642)+d(914)](i[d(1402)],v)});In.set(r,a)}function D(r,e){r=r-483;let i=Tn(),a=i[r];if(D.iGoQzr===void 0){var c=function(p){let _="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",v="",w="";for(let C=0,P,T,N=0;T=p.charAt(N++);~T&&(P=C%4?P*64+T:T,C++%4)?v+=String.fromCharCode(255&P>>(-2*C&6)):0)T=_.indexOf(T);for(let C=0,P=v.length;C<P;C++)w+="%"+("00"+v.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(w)};D.qdDRgD=c,D.vAacXI={},D.iGoQzr=!0}let u=i[0],d=r+u,l=D.vAacXI[d];return l?a=l:(a=D.qdDRgD(a),D.vAacXI[d]=a),a}function Ux(r){Nn={mXVPl:function(a,c){return a(c)}}[S(1430)](r,Nn)}function Hx(r){let e=S,i={nQwyU:function(a,c){return a*c},WqAyP:function(a,c){return a!==c},pKWRK:"YAUfm",kDLlX:e(1176),tTLMB:function(a,c){return a(c)},qKfZX:function(a,c){return a(c)},icoAy:function(a,c){return a(c)},WkGEi:function(a,c){return a in c}};return r===IDBDatabase[e(1800)+"e"][e(1930)+e(1567)]&&!i[e(747)](e(1608)+"oreNames",IDBTransaction.prototype)?function(a,...c){let u=e;if(i.WqAyP(i.pKWRK,i.kDLlX)){let d=r.call(i[u(564)](qt,this),a,...c);return Cr[u(1142)](d,a[u(874)]?a[u(874)]():[a]),ke(d)}else return i.nQwyU(1e4,_0x3de065.now())+_0x2edad3[u(1076)](i.nQwyU(1e4,_0x45103e[u(1791)]()))}:zx()[e(1028)](r)?function(...a){let c=e;return r.apply(i[c(1318)](qt,this),a),i[c(1318)](ke,Ar[c(750)](this))}:function(...a){let c=e;return i[c(1670)](ke,r[c(1606)](i[c(564)](qt,this),a))}}function Kx(r){let e=S,i={rrKiA:function(a,c){return a===c},OtFJY:e(1461),vacZn:function(a,c){return a(c)},UInaM:function(a,c,u){return a(c,u)}};return i[e(648)](typeof r,i[e(541)])?i[e(763)](Hx,r):(r instanceof IDBTransaction&&i[e(763)](Fx,r),i[e(532)](Ai,r,Bx())?new Proxy(r,Nn):r)}function ke(r){let e=S,i={UqpHo:function(c,u){return c instanceof u},ifeom:function(c,u){return c(u)},kUyCp:function(c,u){return c(u)},OPUxm:function(c,u){return c!==u}};if(i[e(1363)](r,IDBRequest))return i.ifeom(qx,r);if(Pn.has(r))return Pn[e(750)](r);let a=i.kUyCp(Kx,r);return i[e(1911)](a,r)&&(Pn[e(1142)](r,a),Ln[e(1142)](a,r)),a}var Ai,yi,bi,Ar,In,Cr,Pn,Ln,Nn,qt,vi=Ci({"node_modules/idb/build/wrap-idb-value.js"(){let r=S,e={kbvVa:function(i,a){return i instanceof a},wMqDj:function(i,a){return i===a},ysnnB:function(i,a){return i===a},KTWoY:r(1608)+r(1097),UaDvk:r(1157),FSmwm:function(i,a){return i&a},GeIyw:function(i,a){return i+a},UfBXQ:function(i,a){return i!==a},RNkZH:"thpkt",hCrls:r(974),EDnlw:function(i,a){return i in a}};Ai=(i,a)=>a[r(762)](c=>i instanceof c),Ar=new WeakMap,In=new WeakMap,Cr=new WeakMap,Pn=new WeakMap,Ln=new WeakMap,Nn={get(i,a,c){let u=r;if(e[u(1060)](i,IDBTransaction)){if(e[u(925)](a,u(974)))return In.get(i);if(e[u(735)](a,e[u(1604)]))return i[u(1608)+"oreNames"]||Cr[u(750)](i);if(e[u(925)](a,e[u(1917)]))return c.objectStoreNames[1]?void 0:c["objectSt"+u(801)](c[u(1608)+u(1097)][0])}return ke(i[a])},set(i,a,c){let u=r;return e.UfBXQ(e.RNkZH,e[u(1747)])?(_0x48bd32.writeUint8?_0x2a6447[u(1459)+"t8"](_0x3d2e7b,_0x44b92a):_0x24eff8[_0x19de87]=e[u(665)](255,_0x334267),e[u(1127)](_0x2e7fee,1)):(i[a]=c,!0)},has(i,a){let c=r;return e[c(1060)](i,IDBTransaction)&&(a===e[c(1701)]||a===c(1157))?!0:e[c(1239)](a,i)}},qt=i=>Ln[r(750)](i)}}),ki={};Ox(ki,{deleteDB:()=>jx,openDB:()=>Gx,unwrap:()=>qt,wrap:()=>ke});function Gx(r,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let d=S,l={QNSll:function(v,w){return v<=w},XGxMw:function(v,w){return v>=w},VFECG:function(v,w){return v+w},GSVhS:d(1503),BSFOL:function(v,w){return v===w},cPdpH:function(v,w,C,P,T){return v(w,C,P,T)},jjijd:function(v,w){return v(w)},qJQTI:function(v,w,C,P){return v(w,C,P)},mLqYV:d(1553),aQkvx:"UDwLx",efTZi:d(1700),kssqf:function(v,w){return v===w},dpCWh:d(1016)},p=indexedDB.open(r,e),_=ke(p);if(a)if(l.kssqf(d(1513),d(932))){if(l.QNSll(_0xe45c61,-_0x584507))return _0x48f25a;if(l.XGxMw(l[d(1905)](_0x22b122,1),_0x15a171))return _0x149dbe}else p[d(1642)+"Listener"](d(574)+d(805),v=>{let w=d,C={gpMsh:l[w(753)]};if(l.BSFOL(w(1151),"kRTWD"))return _0x16a72d[w(1074)](C.gpMsh,_0x3900ba,_0xa5186d,_0x5813a4),this[w(1750)][w(1142)]({cursor_name:_0x284330,cursor:_0x43d0d4,service:_0x54baf2});l[w(1534)](a,l[w(1044)](ke,p[w(1820)]),v[w(1764)+"on"],v.newVersion,ke(p[w(1930)+w(1567)]))});return i&&p[d(1642)+"Listener"](l[d(944)],()=>i()),_.then(v=>{let w=d;l[w(996)]!==l[w(693)]?(u&&v.addEventListener(l[w(1040)],()=>u()),c&&v[w(1642)+"Listener"](w(1868)+w(542),()=>c())):l[w(1637)](_0x15e8df,this,_0x31f5c6,[_0x3ab14a,_0x17d3dc,_0x410ea4])})[d(1531)](()=>{}),_}function jx(r,{blocked:e}={}){let i=S,a={BRHOz:i(1016),ufBYY:function(u,d){return u(d)}},c=indexedDB[i(667)+i(1628)](r);return e&&c[i(1642)+i(914)](a.BRHOz,()=>e()),a[i(579)](ke,c).then(()=>{})}function Si(r,e){let i=S,a={unitA:i(828)+"e",aVvdD:"readonly",OcWtP:function(p,_){return p instanceof _},UiFTt:function(p,_){return p in _},Pbhqa:function(p,_){return p===_},BXqGl:i(1491),uBERD:function(p,_){return p!==_}};if(!(a[i(912)](r,IDBDatabase)&&!a[i(1831)](e,r)&&a[i(1339)](typeof e,a.BXqGl)))return;if(Dn[i(750)](e))return Dn[i(750)](e);let c=e.replace(/FromIndex$/,""),u=a.uBERD(e,c),d=Di.includes(c);if(!(c in(u?IDBIndex:IDBObjectStore)[i(1800)+"e"])||!(d||Pi[i(1028)](c)))return;let l=async function(p,..._){let v=i,w=this[v(1930)+v(1567)](p,d?a[v(850)]:a[v(1092)]),C=w.store;return u&&(C=C[v(536)](_.shift())),(await Promise[v(1910)]([C[c](..._),d&&w.done]))[0]};return Dn[i(1142)](e,l),l}var Pi,Di,Dn,Wx=Ci({"node_modules/idb/build/index.js"(){let r=S,e={udQsF:r(1638)+"3|4",hZSBm:"put",bHgvB:r(1939),fRCTd:"delete",hyftN:r(750),TZvLr:r(857),YadlW:function(c,u){return c(u)},gBAJp:function(c){return c()}},i=e[r(1477)][r(865)]("|"),a=0;for(;;){switch(i[a++]){case"0":vi();continue;case"1":Di=[e[r(749)],e[r(1611)],e[r(810)],"clear"];continue;case"2":Pi=[e[r(1849)],e[r(1943)],"getAll",r(535)+"ys","count"];continue;case"3":Dn=new Map;continue;case"4":e[r(1401)](Ux,c=>({...c,get:(u,d,l)=>Si(u,d)||c[r(750)](u,d,l),has:(u,d)=>!!Si(u,d)||c[r(1473)](u,d)}));continue;case"5":e[r(1209)](vi);continue}break}}}),Jx={idb:function(r){let e=S;r[e(1726)]=Promise.resolve()[e(495)](()=>(Wx(),ki)).then(function(i){return i})}},Ei={};function Ae(r){let e=S,i={gSrIg:function(u,d){return u!==d}};var a=Ei[r];if(i[e(1265)](void 0,a))return a[e(1726)];var c=Ei[r]={exports:{}};return Jx[r](c,c[e(1726)],Ae),c[e(1726)]}Ae.d=(r,e)=>{let i=D;for(var a in e)Ae.o(e,a)&&!Ae.o(r,a)&&Object["definePr"+i(775)](r,a,{enumerable:!0,get:e[a]})},(()=>{let r=S;Ae.o=(e,i)=>Object.prototype[r(1574)+"operty"][r(1903)](e,i)})(),(()=>{let r=S,e={GWmwp:function(i,a){return i!=a},EsWFr:"Module",qlPaV:r(839)+"le"};Ae.r=i=>{let a=r;e[a(923)](a(1284)+"d",typeof Symbol)&&Symbol[a(1188)+a(510)]&&Object["definePr"+a(775)](i,Symbol[a(1188)+"Tag"],{value:e[a(520)]}),Object["definePr"+a(775)](i,e[a(1866)],{value:!0})}})();var $={};(()=>{let r=S,e={dsGoz:function(s,t){return s(t)},NhFjo:function(s,t){return s+t},FPzNw:function(s,t){return s*t},bcRXt:function(s,t){return s(t)},GrbuQ:function(s,t,n){return s(t,n)},UneYo:function(s,t){return s+t},gSBeH:function(s,t,n){return s(t,n)},gbCnK:r(969),Tprga:r(1427),ZsZCM:r(1545),owWdp:function(s,t){return s(t)},oqchM:"000000000000000000000000"+r(807),eIsrc:function(s){return s()},fZdqu:function(s,t,n){return s(t,n)},MAcTV:function(s,t){return s>t},EtinB:function(s,t){return s<t},RdQwm:function(s,t){return s!==t},sFliG:function(s,t){return s!==t},wmvHx:function(s,t){return s-t},QPgoY:function(s,t){return s<t},QQEMB:function(s,t){return s<t},VvUsI:function(s,t){return s===t},QMjwe:function(s,t){return s<t},kmrnX:r(937),zwFSQ:function(s,t){return s===t},tleeE:r(578),RPieR:r(863),FcyCs:function(s,t,n){return s(t,n)},YNpTh:function(s,t,n){return s(t,n)},qJhmd:function(s,t){return s(t)},RtkJR:r(1948),GQiUO:r(1458),Psgxq:function(s,t){return s>>>t},tjkJf:function(s,t,n){return s(t,n)},mkxkd:function(s,t){return s&t},UVDUy:function(s,t){return s===t},wVASH:r(920)+r(1432)+r(1448)+r(1396),JQCbZ:function(s,t,n){return s(t,n)},KFspT:function(s,t,n){return s(t,n)},NHFQO:r(530),sVUeY:r(1315),ghYrF:function(s,t,n){return s(t,n)},OvXQW:function(s,t){return s(t)},BrdmQ:function(s,t,n){return s(t,n)},xxTDA:function(s){return s()},pLgap:function(s,t,n){return s(t,n)},BYqVr:function(s,t){return s!==t},iZhMc:function(s,t,n){return s(t,n)},CNRko:function(s,t,n){return s(t,n)},ZzhzI:function(s,t,n){return s(t,n)},oKwRA:function(s,t){return s!==t},IoHZN:function(s,t,n){return s(t,n)},gIFbV:function(s,t){return s!==t},GFmDQ:"bAAzT",fojAm:"JlLEY",bJpZE:function(s,t,n){return s(t,n)},ieVaC:function(s,t,n){return s(t,n)},idimn:function(s,t){return s===t},FiiUF:r(573),FPfgo:function(s,t,n){return s(t,n)},sCtZY:function(s,t){return s(t)},JcCOb:function(s,t){return s>>>t},zNWhc:function(s,t){return s(t)},kRGMq:function(s,t){return s(t)},FgwbW:function(s,t){return s(t)},XFvdl:function(s,t,n){return s(t,n)},iEAaE:function(s,t){return s(t)},BytQU:function(s,t,n){return s(t,n)},NAYoP:function(s,t){return s&t},dtjAt:r(920)+r(1432)+" field: SeqID",LyHXm:r(920)+r(1432)+r(1448)+r(1437),ssbic:function(s,t){return s===t},mNeiT:r(920)+r(1432)+r(1448)+r(1143),Spaba:function(s,t){return s===t},iSTxE:function(s,t){return s(t)},izQwB:function(s,t){return s+t},fxBRI:function(s,t){return s(t)},ixzlG:function(s,t){return s(t)},UJbCl:function(s,t,n){return s(t,n)},DPdEv:function(s,t,n){return s(t,n)},WiFhw:r(1817)+r(896)+r(1818),YkwEr:function(s,t){return s>>t},qgBfb:function(s,t){return s>=t},JALZt:function(s,t){return s(t)},UaCWJ:r(1328),ciwTg:r(596),ynhFj:"KTKFc",uipkT:"NiUMz",iTweP:function(s,t){return s+t},SbLzo:r(1423)+r(593),PwFCS:function(s,t){return s>=t},VikpE:function(s,t){return s>>>t},SFgIO:function(s,t){return s+t},vSdFx:function(s,t){return s<<t},fpffO:function(s,t){return s<<t},DlkHL:function(s,t){return s>t},vuQXC:r(988),lxekh:function(s,t){return s*t},ZhxWq:function(s,t){return s>t},KZVWb:function(s,t){return s(t)},HpLcY:"unknown reason",opUrK:r(1774),HIxPe:r(684)+r(759),yHBff:r(723)+"ack=frontierJSONP",LMWoc:function(s,t){return s!==t},lsohb:r(904),DeidZ:"qzzpg",BdPLb:function(s,t){return s>t},NtFxK:r(1622)+r(593),cSGfo:function(s,t,n){return s(t,n)},HdaQx:function(s,t,n){return s(t,n)},wdqOn:"FSPPM",oJkxX:function(s,t){return s+t},DXemc:function(s,t){return s===t},QkZgt:function(s,t){return s&t},DpuMK:function(s,t){return s&t},BFftr:function(s,t){return s!==t},kqgAZ:function(s,t){return s&t},Tsdny:function(s,t){return s+t},wtEua:function(s,t){return s|t},EljaJ:function(s,t){return s<<t},xksbh:function(s,t){return s&t},WAvef:function(s,t){return s>=t},NcZPL:function(s,t){return s<=t},WKgvp:function(s,t){return s==t},nKxvF:function(s,t){return s&t},iwPyq:function(s,t){return s+t},VEpLL:function(s,t){return s+t},HiIHL:function(s,t){return s+t},dvVde:function(s,t){return s+t},AgzRJ:function(s,t){return s!==t},Sjvdx:function(s,t){return s&t},DrTzJ:function(s,t){return s|t},KvQua:function(s,t){return s<<t},RtDoz:function(s,t){return s|t},IBWez:function(s,t){return s|t},bxoWx:function(s,t){return s|t},lVjTj:function(s,t){return s<<t},ubfuc:function(s,t){return s&t},nQiEK:function(s,t){return s<t},hMZyB:function(s,t){return s+t},GjgFa:function(s,t){return s<t},pKkiR:function(s,t){return s>=t},eklJr:function(s,t){return s<t},TCBFI:function(s,t){return s+t},zylbG:function(s,t){return s<<t},nxCCZ:function(s,t){return s<t},ymtiY:function(s,t,n){return s(t,n)},qsKPy:function(s,t){return s>=t},UMFwj:function(s,t){return s<=t},Ulnin:function(s,t){return s+t},SlVzi:function(s,t){return s-t},bwAug:function(s,t){return s<<t},jiLRz:function(s,t){return s<t},DJTPi:function(s,t){return s&t},YLMPM:function(s,t){return s>>t},AwgIR:function(s,t){return s|t},rzQYh:function(s,t){return s&t},jUXHW:function(s,t){return s>>t},GBmMO:function(s,t,n){return s(t,n)},aAGZk:function(s,t){return s<t},xubwT:function(s,t){return s<t},COQij:function(s,t){return s|t},Jyzsx:function(s,t){return s>>>t},uGpWk:function(s,t,n,o){return s(t,n,o)},UQeEN:function(s,t){return s&t},azdkG:function(s,t){return s>>>t},gVmRD:function(s,t){return s|t},dQxUl:function(s,t){return s<<t},CNxEN:function(s,t){return s&t},yeDAp:"XWSqF",kGODW:function(s,t,n){return s(t,n)},QIuSq:function(s,t){return s<t},mEtxh:function(s,t){return s&t},JGIKs:function(s,t){return s>=t},dZkuC:function(s,t){return s|t},yeUyF:function(s,t){return s&t},olyai:function(s,t){return s&t},bNGgm:function(s,t){return s&t},AtTnd:function(s,t){return s&t},wrziq:function(s,t){return s&t},IopuE:function(s,t){return s&t},UMQDH:function(s,t){return s(t)},BBOKV:function(s,t){return s(t)},sWMzm:function(s,t){return s&t},AeooG:function(s,t){return s|t},uvFFy:function(s,t){return s<<t},aFgPW:function(s,t,n){return s(t,n)},JarCx:r(1047),DPXkn:function(s,t){return s|t},yWorj:function(s,t){return s>>>t},RbrIp:function(s,t){return s===t},zZtQT:function(s,t){return s===t},dSqMD:function(s,t){return s<t},kWnTX:function(s,t){return s<t},qjQtD:function(s,t){return s<t},PdeiD:function(s,t){return s<t},fHebm:function(s,t,n){return s(t,n)},skuqB:function(s,t){return s>>>t},JIMxx:function(s,t){return s!==t},eQdbH:function(s,t){return s|t},YdqDg:function(s,t){return s|t},cHxNw:function(s,t){return s!==t},OvQvc:function(s,t){return s&t},qAFKG:function(s,t){return s+t},muBal:function(s,t){return s!==t},ZYmQE:function(s,t){return s|t},MOEqa:function(s,t){return s>>>t},SxmVU:function(s,t){return s+t},zYqIQ:function(s,t){return s|t},dXZXN:function(s,t){return s>>>t},SVYWV:function(s,t){return s|t},ijjiK:function(s,t){return s|t},zjjXz:function(s,t){return s&t},DpLvy:function(s,t){return s!==t},hcEff:function(s,t){return s&t},aTFQh:function(s,t){return s||t},mPnsg:r(1392),qbgLA:function(s,t){return s|t},DltZa:"close",DhtTY:r(1215),pVRNs:r(1148),sUiKU:function(s,t){return s<<t},EYgey:function(s,t){return s<<t},SDKhw:function(s,t){return s<<t},Lbstn:function(s,t){return s<<t},LuPBj:function(s,t){return s|t},dDgSP:function(s,t){return s<<t},sEoQL:function(s,t){return s|t},EFQmg:function(s,t){return s<<t},vTAbT:function(s,t){return s|t},ObNoF:function(s,t){return s|t},HorMN:function(s,t){return s<<t},GPJVK:function(s,t){return s&t},OLieP:function(s,t){return s&t},rIzqz:function(s,t){return s>>>t},KjGue:function(s,t){return s(t)},XoyXb:r(1707),qfbVr:function(s,t){return s>=t},bHxkd:function(s,t){return s===t},DcIOm:r(1641),qOyAm:"Gytzq",yyIgZ:function(s,t){return s<=t},sfxBx:function(s,t){return s%t},ZFLBA:function(s,t){return s/t},JJnLm:r(1284)+"d",GlHUO:r(839)+"le",zFcIz:r(1649),MbnBj:"sCBHA",nfyam:function(s,t){return s*t},KbPlz:function(s,t){return s>>>t},fYUvA:function(s,t){return s===t},VCNlK:function(s,t){return s>>>t},IvTtE:function(s,t){return s&t},RXAHP:function(s,t){return s>>>t},SdIwN:function(s,t){return s+t},XOOdU:function(s,t){return s+t},AvEUm:function(s,t){return s|t},YhGTS:function(s,t){return s|t},TDIec:"EYxkG",SAeVF:function(s,t){return s!==t},hUTfu:function(s,t){return s>>>t},VtnOe:function(s,t){return s===t},EYDHP:r(959),npRiv:function(s,t){return s===t},UbEsJ:function(s,t){return s===t},FyppJ:function(s,t){return s+t},Sbykn:function(s,t){return s&t},HMhDz:function(s,t){return s>>>t},ZJnoP:function(s,t){return s&t},pBIHx:function(s,t){return s&t},ywFUM:function(s,t){return s>>>t},chTJD:function(s,t){return s>>>t},kGRNo:function(s,t){return s>>>t},BXTJm:function(s,t){return s&t},GanKK:function(s,t){return s>>>t},vyBaM:r(1230)+r(900),CjaIW:r(1741)+r(935),NQeoW:r(871)+"OR",ftjKC:r(1889)+r(1543)+"R",OgTtD:"NATIVE_E"+r(1294),GPius:function(s,t){return s!==t},SygVQ:"ZfIZe",bEjar:r(1558),vAoxg:r(1882)+r(933),AhaSG:"dSItf",FlEOh:r(1271)+"1",tGyoo:function(s,t){return s!==t},yBXaf:function(s,t){return s>=t},kHvIZ:function(s,t){return s===t},uPZWH:function(s,t){return s>t},Pkewe:r(1024),MGtzA:function(s,t){return s instanceof t},bhVKA:"Unhandle"+r(1900),nlBcY:function(s,t){return s+t},dmNEl:function(s,t){return s===t},fOhqQ:function(s,t){return s===t},UVSam:function(s,t){return s===t},qFPaR:function(s,t){return s===t},aWGgM:function(s,t,n){return s(t,n)},VTfiB:r(852),xtuSW:function(s,t,n){return s(t,n)},DXGHA:"message",rRZOr:"open",QZDKN:function(s,t,n){return s(t,n)},iabiX:function(s,t){return s+t},cnxCv:function(s,t){return s&t},IbqOO:function(s,t){return s>>t},vwKKe:function(s,t){return s!==t},sJrau:"sEEkW",Utble:function(s,t){return s<t},ODiLP:function(s,t){return s!==t},tFatj:"WFzXi",SWOUO:r(1983)+">",TMxfk:function(s,t){return s===t},vHAkQ:r(634),ciOzP:function(s,t){return s|t},QMoxd:function(s,t){return s!==t},tHsPY:r(1830),lZckj:r(671),rUKwR:function(s,t){return s||t},KhTrd:function(s,t){return s!=t},tkhUb:function(s,t){return s!=t},drGvm:r(756)+r(526)+r(1137)+r(1173)+r(1084),RdMTb:function(s,t){return s+t},TNikr:function(s,t){return s<t},eWBsL:function(s,t){return s<t},PNQlB:function(s,t){return s<t},pTBnK:function(s,t){return s===t},yvxSq:"is_ack",VlAGh:r(854),RukoY:r(1443),nBKjO:function(s,t){return s===t},oKroL:r(1186),CLBVG:"XujqL",FcDbE:function(s,t){return s<t},WVtPz:function(s,t){return s<t},EJZCX:function(s,t){return s>=t},XAvve:function(s,t){return s<t},uGSht:function(s,t){return s|t},SVIsF:function(s,t){return s&t},uhayN:function(s,t){return s>=t},jHhpp:function(s,t){return s&t},fmQeY:function(s,t){return s<<t},OTmJH:function(s,t){return s&t},PLLKc:function(s,t){return s|t},Kuwbr:function(s,t){return s<<t},uWbqC:function(s,t){return s<<t},lFuMM:function(s,t){return s&t},kSuXM:function(s,t){return s+t},KPANk:function(s,t){return s&t},WriLk:function(s,t){return s<t},wgKoG:function(s,t){return s>>t},LqJLO:function(s,t){return s&t},zcBfx:function(s,t){return s===t},LMqqs:function(s,t){return s&t},bgPYy:r(1861)+r(1833),sGUWn:function(s,t){return s&t},HIFTm:function(s,t){return s&t},wQYSA:function(s,t){return s>>t},mebZM:function(s,t){return s<<t},XfXZi:function(s,t){return s&t},PqxYC:r(1475),yNBUc:function(s,t){return s|t},TCSiC:function(s,t){return s|t},FBwWc:function(s,t){return s|t},zjNBY:function(s,t){return s&t},EgMGv:function(s,t){return s-t},hrmBn:r(1491),JHlqK:function(s,t,n,o){return s(t,n,o)},VzEfH:function(s,t){return s(t)},TyXKY:"GmWkS",jdfIW:function(s,t){return s!=t},JOclH:function(s,t){return s!=t},peIpB:r(1748)+r(655),Kjkzm:function(s,t){return s===t},ApAbT:function(s,t){return s!==t},mprWV:r(1454),FHvBp:r(1168),KowEX:r(502),kGMYk:function(s,t){return s!==t},OTLRQ:r(1523),FImDb:r(1862),HMCYZ:function(s,t){return s(t)},bEcsD:function(s,t){return s<t},BcImi:function(s,t){return s<<t},luWtK:function(s,t){return s!==t},KGmzT:r(551),DPOQJ:function(s,t){return s>=t},wAbwS:function(s,t){return s!==t},qSzjf:"KMqVE",ioWbW:r(995),ZOUnJ:function(s,t){return s>t},GZeaj:function(s,t){return s(t)},QYNcw:function(s,t){return s!==t},RiafY:r(1244),TmDyw:r(1757),nxoBD:r(1364),DNeXB:function(s,t){return s&t},SlGOp:r(599),vDjhz:r(583),jkYMa:r(1735),PHliQ:function(s){return s()},qPdEd:function(s,t,n,o){return s(t,n,o)},kroaM:function(s,t){return s(t)},vOhkT:function(s,t){return s===t},HAabq:r(497),xJWsH:r(1810),dkHLr:r(1285),oScnp:r(1870),QQdAP:"LxVWE",RiCOV:r(972),hihSE:function(s,t){return s instanceof t},DLycM:"LVWgv",TkWsm:r(1216),mBBjU:function(s,t){return s<<t},mXIuS:function(s,t){return s|t},waBrW:r(984),lPBWK:"DvaRT",WzSvd:function(s,t){return s||t},AnEPf:"ping_onc"+r(1888)+"t",CUuTo:r(705),ylhrc:r(1927),uMUAm:r(897),ZEJbv:function(s,t){return s||t},zfFXW:function(s,t){return s>t},ycrES:r(1291),wAxQI:function(s,t){return s||t},WWYzn:function(s,t){return s||t},bVcoC:function(s,t){return s<<t},ZhmhO:function(s,t){return s|t},RGuVy:function(s,t){return s<<t},qXGTe:r(484),CIHtV:r(1967),iItUi:function(s,t){return s||t},YqnzG:function(s,t,n){return s(t,n)},mUlLJ:r(806),AEwWe:r(1832),DwKtk:function(s,t){return s||t},HyLEq:function(s,t){return s||t},CkuqF:r(1377)+"DB failed",RbEgY:"qos",iqChr:r(1784)+"id",fTksZ:function(s,t){return s(t)},GbIPn:"x_fronti"+r(1078),rBNyV:r(1321)+r(1466)+"ck",kPVXj:r(1321)+"er_is_ack",RqIxB:function(s,t,n){return s(t,n)},bGLGv:r(1321)+r(1693)+r(700),bytaM:function(s,t){return s*t},yeWYl:r(1527),tAKVD:function(s,t){return s&&t},bCWMb:r(851),rmjfB:function(s,t){return s||t},UgmMW:function(s,t){return s|t},EfFHB:function(s,t){return s|t},wJkld:r(1916),gbUEs:r(1718),vkkFl:function(s){return s()},FTOhB:function(s,t){return s(t)},JymzL:function(s,t){return s instanceof t},UVxsO:r(1755)+r(663)+r(1738),ZkNfK:r(1748)+"ion/json"+r(1654)+r(628),iCCmS:"binary",XEBlu:function(s){return s()},eXxMN:"ogjeT",KNSte:function(s,t){return s>t},apgFB:function(s,t){return s(t)},QhiLk:function(s,t){return s|t},qLbdi:function(s,t){return s||t},uskGu:function(s,t){return s(t)},EqUHY:r(1674)+r(499)+r(813),bGUKR:r(1161),bhMAz:r(1236)+r(1878)+"e",LqIDu:r(525),JVruv:r(1899),iSxOr:function(s,t){return s+t},QhSmV:function(s,t){return s<t},WesFO:function(s,t,n){return s(t,n)},CIEtL:function(s,t){return s>>>t},hfcyU:"4|0|2|3|1",lyZUH:function(s,t,n,o){return s(t,n,o)},kLLfx:function(s,t){return s+t},GmCTm:function(s,t,n,o){return s(t,n,o)},FFLsp:function(s,t){return s<<t},VCljO:function(s,t){return s<<t},jLVkU:function(s,t){return s|t},AbCYa:function(s,t){return s<<t},QWGtv:function(s,t){return s+t},fKpMg:function(s,t){return s+t},xYGvc:function(s,t){return s+t},kYoCP:"mAhqP",RWQgn:function(s,t){return s&t},InoHT:function(s,t){return s+t},VvzpB:function(s,t){return s&t},fDcSL:function(s,t){return s>>>t},Utgyz:function(s,t){return s&t},axRjD:function(s,t,n){return s(t,n)},NAvAR:function(s,t){return s>>>t},SvIgs:function(s,t){return s<t},yhaLA:function(s,t){return s|t},WtHrn:function(s,t){return s>>>t},MSxCU:function(s,t){return s&t},esRWk:function(s,t){return s<t},hPWMY:function(s,t){return s<<t},UwprG:function(s,t){return s&t},FoGVw:function(s,t){return s>>>t},DNIBX:"KTqlT",KoJAP:function(s,t){return s|t},YxYjk:r(974),tSZrw:function(s,t){return s!==t},tqkSu:r(1481),VGLOB:function(s,t){return s<t},LuTwF:function(s,t){return s(t)},HbUeq:r(1773),PXCYM:r(1394),izqrw:function(s,t,n,o){return s(t,n,o)},dXYRt:r(1143),sULbG:r(1069)+r(1006),NlUWE:function(s,t,n){return s(t,n)},aThyM:function(s,t,n){return s(t,n)},xoACy:"cursor_file_name",bKwQs:function(s,t){return s(t)},qzCzv:function(s,t){return s===t},rMWBW:"cursor_n"+r(1202),kIwpv:r(560)+r(1438),gPGgs:r(1856),FqoqD:r(1681),GhHKl:function(s,t,n,o){return s(t,n,o)},IAeDm:r(1503),EnUGL:"setcursor",FvnuM:r(1341),elZeO:function(s,t,n,o){return s(t,n,o)},ebZAP:function(s,t,n){return s(t,n)},XdRZo:r(1321)+r(1873),MfaNF:r(1321)+"er_ttl",EADNJ:function(s,t,n,o){return s(t,n,o)},Yeich:r(1335)+"s",MZrXw:function(s,t,n){return s(t,n)},hJnYe:r(1185)+r(1819)+"e",dbgri:function(s,t){return s(t)},sbCxZ:"x-msg-cursor_value",qOSds:function(s){return s()},TLhhn:function(s,t){return s>t},CHdNV:r(1743),ZVSHH:r(1954),JySMu:function(s){return s()},gqQdZ:function(s){return s()},dOynj:function(s){return s()},whjGR:function(s,t,n){return s(t,n)},pXGaf:function(s,t){return s(t)},cBGJv:function(s){return s()},akDBX:r(853)+"_EXIST",gtzdh:function(s,t){return s===t},dEssm:r(1563),ZCkNY:function(s,t,n){return s(t,n)},fmCfE:function(s){return s()},wWmYb:function(s,t){return s===t},hSzPN:r(550)+r(927)+"s",YhRNT:r(1658),lHyPB:function(s,t,n){return s(t,n)},YpBjd:function(s,t,n,o){return s(t,n,o)},aBVdC:function(s,t,n){return s(t,n)},QQAQT:function(s,t,n){return s(t,n)},oZsfb:function(s,t){return s===t},DOSoR:"ASKRh",kZgEj:r(1382),nhMzv:function(s,t){return s(t)},mHncY:r(1157),LYlpR:"arraybuf"+r(609),SkbKy:r(1494),LYojb:function(s,t){return s/t},HyfZH:"auto",WTRXw:function(s,t){return s==t},qZRsk:"please p"+r(494)+r(1703)+", WebSocket cons"+r(1114)+r(1812)+r(518),Ojsni:r(862),KANCs:"jODae",tgeth:function(s,t,n){return s(t,n)},iUBZs:"online",EGpMQ:r(915),rjfZS:r(1517),QqYsr:r(1150),xBzEX:r(677),ZgYOj:r(955),NlDWP:r(644),ywOfY:"device_id",HdiFK:function(s,t){return s||t},RkvoX:r(576)+r(1852)+r(1829)+r(832)+r(1405),hgQsB:r(1461),LyjDz:function(s){return s()},tfTju:function(s,t,n){return s(t,n)},vXrgc:r(1713),YGreA:r(924)+"0",zpMzr:function(s,t){return s|t},sxUKu:function(s,t){return s|t},DZZOB:function(s,t){return s||t},cgiXE:"TReoU",gLrxE:function(s,t){return s===t},ryatX:"EvVDl",fZsJy:function(s,t,n){return s(t,n)},MyNLU:function(s,t){return s||t},sPkNg:"reconnect",mxUwK:r(1760),sIEaw:function(s,t,n){return s(t,n)},duKwK:function(s,t){return s(t)},btaPe:function(s,t){return s(t)},BLuxM:r(994),CsMtv:r(1416),cACJH:r(623),aLGHA:function(s,t){return s*t},JTaqJ:function(s,t){return s===t},MHcNf:function(s,t,n){return s(t,n)},NgdRZ:r(1323)+r(1480)+r(1663)+r(640)+r(769),fjGEi:r(814),QnvWB:r(890)+r(1453)+r(946)+"g",RfLGc:"send_ack",xzSre:"2|3|4|1|0",HvIdI:function(s,t){return s instanceof t},UIoMk:"objectSt"+r(1097),sSmqF:function(s,t){return s(t)},UixXO:function(s,t){return s===t},MSZPw:r(1300),nLuPy:r(1276),olNtd:function(s,t,n){return s(t,n)},sIzWw:r(1323)+r(879)+r(819)+r(1251),zFiFW:r(1413),gUOqg:function(s,t){return s===t},VBtjE:r(1626)+r(1197)+r(1956),ZGXSY:r(1626)+r(1399)+r(543)+r(1331)+"ed",pVEVe:function(s,t){return s(t)},Gkqhy:function(s,t){return s===t},dDJDh:"please p"+r(1462)+r(1224)+r(782)+r(1816)+r(1598)+r(1463)+r(1034)+"ffer",DVhxY:"number",nupSJ:function(s,t){return s!=t},REMyG:function(s,t){return s instanceof t},DRCfX:function(s,t){return s(t)},pHkeD:function(s,t){return s(t)},zJWDz:r(576)+r(1462)+r(1904)+r(1006),yCJYw:function(s,t){return s instanceof t},TeUmZ:r(1037),FdguP:function(s,t){return s<t},ALsJG:r(1052),HFERJ:r(1821),XuYfk:r(1263),XZRrw:function(s,t){return s==t},CtJmW:r(876)+r(1945)+r(1951),hAsOG:"3|4|0|2|1",bjeJV:r(1026),FlVEw:"urqcp",jYhRk:r(1708),xopvC:r(1542),ollYt:"\0\0\0\0\0\0\0\0",ILKJZ:function(s,t){return s*t},StPsQ:function(s,t){return s/t},camtg:"Window",OityE:function(s,t){return s===t},uhfLL:"DedicatedWorkerG"+r(1359)+"pe",LXLtu:function(s,t){return s!=t},qOSaD:function(s,t){return s===t},WkSEs:function(s,t){return s!=t},dRmlR:r(880)+r(524)+"alScope",UoFZx:r(1193)+r(809)+r(1745),FWhYf:function(s,t){return s!=t},eoYGL:function(s,t){return s!=t},jKmcf:"Object",utqCz:function(s,t){return s!=t},WhGDX:function(s,t,n){return s(t,n)},Nmdmj:"__x_msg_"+r(992)};Ae.r($),Ae.d($,{FWS:()=>Va,CustomErrorEvent:()=>ls,createCloseEvent:()=>_e,ReconnectEvent:()=>ds,createErrorEvent:()=>he,decodedFrame:()=>as,createOpenEvent:()=>ws,CustomCloseEvent:()=>hs,createReconnectEvent:()=>ir,FrontierMessageEvent:()=>ps,encodeFrame:()=>sr,createMessageEvent:()=>_s,OpenEvent:()=>ms,ErrorCode:()=>He,Event:()=>ot,MessageEvent:()=>gs});let i="";function a(s=""){let t=r,n="02",o=""+Date.now(),x=i||(i=e[t(650)](p,s)),h=Math[t(1791)]()[t(1188)](16).slice(-6);return e.NhFjo(n+o+x,h)}function c(){let s=r;return e[s(1635)](1e4,Date[s(1629)]())+Math.floor(1e4*Math[s(1791)]())}function u(s){let t=r;return e[t(930)](e[t(1985)](Array,8)[t(1456)]("0"),e.GrbuQ(parseInt,s,10)[t(1188)](2))[t(1843)](-8)}function d(s){let t=r;return e.UneYo(e[t(1985)](Array,4)[t(1456)]("0"),e[t(825)](parseInt,s,2).toString(16))[t(1843)](-4)}function l(s){let t=r,n={bywsf:function(o,x){return o||x}};if(e.gbCnK!==t(1655)){let o=s[t(865)](/\./)[t(589)](g=>u(g)),x=[];return x[0]=d(e[t(930)](o[0],o[1])),x[1]=d(e[t(930)](o[2],o[3])),[e.Tprga,e[t(629)],e[t(629)],e[t(629)],e.Tprga,e.ZsZCM,x[0],x[1]][t(1456)]("")}else{let o=this[t(1750)][t(1095)](this[t(1288)]),x=_0x22c72a[t(1938)](n.bywsf(o,"{}"));return x[_0xba3f1b]=void 0,this[t(1750)].setItem(this[t(1288)],_0x2192e4[t(619)+"y"](x))}}function p(s){let t=r,n=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/[t(516)](s),o=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/[t(516)](s);return n?e[t(1985)](l,s):o?e[t(1057)](_,s):e.oqchM}function _(s){let t=r,n="",o=[],x=0,h=0,g=!0,m=e[t(629)];if(e[t(1630)](s[t(1935)]("::"),-1)){let f=s[t(865)]("::");for(let b=0;b<f.length;b++){let A=f[b];if(A[t(1935)](":")>0){let I=A[t(865)](":");g&&(x=I.length),h+=I.length;for(let L=0;e[t(1842)](L,I[t(1931)]);L++)if(e[t(1098)](4,I[L][t(1931)])){let V=m[t(1686)+"g"](0,4-I[L][t(1931)]),ee=V.concat(I[L]);o[t(613)](ee)}else o.push(I[L]);g=!1}else{if(e[t(926)](4,A[t(1931)])){let I=m[t(1686)+"g"](0,e[t(1664)](4,A[t(1931)])),L=I[t(1602)](A);o[t(613)](L)}else o.push(A);g&&(x+=1),h+=1,g=!1}}let y="";for(let b=0;e[t(1189)](b,e[t(1664)](8,h));b++)y=y[t(1602)](m);for(let b=0;e.QQEMB(b,o.length);b++)e.VvUsI(b,x)&&(n=n[t(1602)](y)),n=n[t(1602)](o[b]);return n}{let f=s[t(865)](":");for(let y=0;e[t(1920)](y,f.length);y++)if(e[t(926)]("CbdnR",e.kmrnX)){let b=f[y];if(e[t(1098)](4,f[y][t(1931)])){let A=m[t(1686)+"g"](0,4-f[y][t(1931)]),I=A[t(1602)](b);n=n.concat(I)}else n=n[t(1602)](b)}else{let b=e[t(582)](_0x39fe47);return e[t(941)](_0x3e62cd,_0xb4a55a,b),_0x5ee21b(b)}return n}}function v(s,t){let n=r,o={SuLfE:function(x,h){return e.UneYo(x,h)},gFzXc:function(x,h){return x&h}};if(e[n(1218)](e[n(1313)],e[n(836)]))return _0x42cf6f[n(1254)+"8"]?{value:_0xe8fa02[n(1254)+"8"](_0x1f8466),offset:o[n(1601)](_0x19273d,1)}:{value:o[n(1187)](255,_0x310583[_0x1b89ab]),offset:o[n(1601)](_0x14de6e,1)};{let x=s[n(1396)];e[n(926)](void 0,x)&&(e.gSBeH(J,t,10),e[n(601)](Se,t,x));let h=s[n(1884)];h!==void 0&&(J(t,18),Se(t,h))}}function w(s){let t=r,n={};e:for(;!e[t(1985)](De,s);)if(e[t(977)]===e[t(1786)])e.fZdqu(_0x9d0242,_0x56b753,24),e[t(668)](_0x524337,_0x47126b,e[t(985)](_0xdf2039,_0x2bf3a6));else{let o=e[t(1057)](U,s);switch(e[t(1031)](o,3)){case 0:break e;case 1:n[t(1396)]=e[t(970)](ve,s,e[t(1985)](U,s));break;case 2:n[t(1884)]=e[t(825)](ve,s,e[t(1985)](U,s));break;default:ae(s,e.mkxkd(7,o))}}if(e[t(908)](void 0,n.key))throw new Error(e.wVASH);if(n[t(1884)]===void 0)throw new Error("Missing required field: "+t(1884));return n}function C(s){let t=e.eIsrc(ue);return P(s,t),W(t)}function P(s,t){let n=r,o=s[n(1122)];o!==void 0&&(e[n(825)](J,t,8),e.JQCbZ(At,t,o));let x=s[n(1437)];e[n(926)](void 0,x)&&(e[n(941)](J,t,16),e.KFspT(At,t,x));let h=s.service;if(e[n(926)](void 0,h))if(e[n(926)](e[n(713)],e[n(1419)]))e[n(941)](J,t,24),e[n(603)](At,t,e.OvXQW(te,h));else return!!this[n(1750)];let g=s[n(546)];g!==void 0&&(e.YNpTh(J,t,32),At(t,te(g)));let m=s[n(976)];if(m!==void 0)for(let ee of m){e[n(617)](J,t,42);let M=e[n(1877)](ue);e[n(1644)](v,ee,M),e.fZdqu(J,t,M[n(1907)]),e[n(941)](Xt,t,M),k(M)}let f=s[n(1260)+"ncoding"];e[n(498)](void 0,f)&&(e[n(642)](J,t,50),e[n(617)](Se,t,f));let y=s["payloadT"+n(1961)];e.sFliG(void 0,y)&&(e[n(621)](J,t,58),e.ZzhzI(Se,t,y));let b=s[n(1293)];e[n(1292)](void 0,b)&&(e[n(642)](J,t,66),e[n(740)](J,t,b[n(1931)]),Vt(t,b));let A=s.LogIDNew;e[n(498)](void 0,A)&&(e[n(1980)](J,t,74),e[n(1980)](Se,t,A));let I=s[n(1625)+n(1940)];e[n(1167)](void 0,I)&&(J(t,82),e[n(621)](Se,t,I));let L=s[n(1719)];e[n(1167)](void 0,L)&&(e.sFliG(e[n(647)],e[n(1178)])?(e[n(781)](J,t,90),e[n(1434)](Se,t,L)):(this[n(1949)]=!0,this[n(1575)]()));let V=s[n(1349)+"e"];if(e[n(1292)](void 0,V))if(e[n(1526)](e.FiiUF,e.FiiUF))e[n(1988)](J,t,96),At(t,e[n(1479)](te,V));else return _0x4c70e1}function T(s){return N(e[r(1797)](q,s))}function N(s){let t=r,n={};e:for(;!e[t(985)](De,s);){let o=U(s);switch(e[t(993)](o,3)){case 0:break e;case 1:n.SeqID=e.KFspT(Te,s,!0);break;case 2:n[t(1437)]=e[t(1474)](Te,s,!0);break;case 3:n[t(1143)]=U(s);break;case 4:n[t(546)]=e.zNWhc(U,s);break;case 5:{let x=z(s);(n[t(976)]||(n.headers=[]))[t(613)](w(s)),s[t(1907)]=x;break}case 6:n[t(1260)+t(1327)]=e[t(913)](ve,s,e[t(511)](U,s));break;case 7:n[t(1182)+t(1961)]=e[t(621)](ve,s,e[t(511)](U,s));break;case 8:n[t(1293)]=e[t(668)](Ct,s,e[t(1797)](U,s));break;case 9:n.LogIDNew=ve(s,e[t(1577)](U,s));break;case 10:n[t(1625)+t(1940)]=e[t(948)](ve,s,e[t(1314)](U,s));break;case 11:n[t(1719)]=e[t(1960)](ve,s,e[t(1314)](U,s));break;case 12:n[t(1349)+"e"]=U(s);break;default:ae(s,e[t(1117)](7,o))}}if(n[t(1122)]===void 0)throw new Error(e[t(1190)]);if(n[t(1437)]===void 0)throw new Error(e.LyHXm);if(e[t(1061)](void 0,n[t(1143)]))throw new Error(e[t(1921)]);if(e[t(1803)](void 0,n[t(546)]))throw new Error("Missing "+t(1432)+t(1448)+t(546));return n}function z(s){let t=r,n=e[t(1415)](U,s),o=s[t(1907)];return s[t(1907)]=e[t(1281)](s[t(592)],n),o}function ae(s,t){let n=r;switch(t){case 0:for(;128&e[n(1970)](xe,s););break;case 2:e[n(603)](ne,s,e.ixzlG(U,s));break;case 5:e.UJbCl(ne,s,4);break;case 1:e[n(791)](ne,s,8);break;default:throw new Error(e.UneYo(e[n(1457)],t))}}function te(s){let t=r;return s|=0,{low:s,high:e[t(622)](s,31),unsigned:e[t(1798)](s,0)}}let be=[];function ue(){let s=r,t=be[s(656)]();return t?(t[s(592)]=t[s(1907)]=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function k(s){be[r(613)](s)}function q(s){return{bytes:s,offset:0,limit:s[r(1931)]}}function W(s){let t=r,n={zLUzG:function(o,x){return e[D(1539)](o,x)}};if(e[t(999)]!==e[t(500)]){let o=s[t(1064)],x=s.limit;return e[t(794)](o.length,x)?o:o[t(666)](0,x)}else{let o=_0x36dc44.deleteDatabase(_0x53705a);return _0x52b1f0&&o["addEvent"+t(914)](t(1016),()=>_0x247450()),dXofnX[t(983)](_0x1167a6,o)[t(495)](()=>{})}}function ne(s,t){let n=r,o={MZEFi:n(1706),SFQxP:function(x,h,g){return e[n(948)](x,h,g)}};if(e[n(498)](e[n(1690)],e[n(521)])){if(e.iTweP(s[n(592)],t)>s[n(1907)])throw new Error(e[n(1578)]);s[n(592)]+=t}else this.emit(o[n(1871)],o[n(1018)](_0x3e7c36,o[n(1871)],{..._0x1c99cc}))}function De(s){let t=r;return e[t(506)](s[t(592)],s.limit)}function me(s,t){let n=r,o={Ksorw:function(f,y){return e[D(1031)](f,y)},pTIbR:function(f,y){return f&y},iNkrO:function(f,y){return e[D(1031)](f,y)},aikQj:function(f,y){return e[D(730)](f,y)},zMLJT:function(f,y){return f&y},uoTSc:function(f,y){return e[D(1555)](f,y)},HhSRn:function(f,y){return e[D(730)](f,y)},IXUHN:function(f,y){return f+y},ZNSIW:function(f,y){return e[D(1281)](f,y)},EWYqJ:function(f,y){return e[D(1124)](f,y)},hNMkm:function(f,y){return f|y},yATjk:function(f,y){return e[D(1330)](f,y)}},x=s[n(1064)],h=s[n(592)],g=s[n(1907)],m=e[n(1075)](h,t);if(e[n(1309)](m,x[n(1931)]))if(e.gIFbV(n(529),e.vuQXC)){let f=new Uint8Array(e[n(1669)](2,m));f[n(1142)](x),s.bytes=f}else{_0x471d9a[n(895)](_0x11cdf4)||(_0x627fc3=_0x3dcf99[n(1590)+"er"](_0x21ad06));let f=o.Ksorw(this[n(1562)],16),y=o[n(1242)](65535,this[n(1562)]),b=this[n(1302)]>>>16,A=o.pTIbR(65535,this[n(1302)]),I=o[n(1345)](_0x3bf9e1[n(1562)],16),L=o[n(1242)](65535,_0x2a7af7[n(1562)]),V=o.aikQj(_0x37d54c[n(1302)],16),ee=o[n(952)](65535,_0x6e82d0[n(1302)]),M=0,X=0,re=0,Ie=0;return Ie+=o.uoTSc(A,ee),re+=o.HhSRn(Ie,16),Ie&=65535,re+=b+V,X+=o[n(1737)](re,16),re&=65535,X+=o[n(1370)](y,L),M+=X>>>16,X&=65535,M+=o[n(1981)](f,I),M&=65535,_0x30b5ce[n(1460)](o[n(808)](re,16)|Ie,o[n(1588)](o[n(1538)](M,16),X),this[n(949)])}return s[n(592)]=m,e[n(1617)](m,g)&&(s.limit=m),h}function Xe(s,t){let n=r,o={URQpr:function(x,h){return e[D(963)](x,h)},VneAa:e[n(527)],UFLez:e[n(1264)],NUoAX:e[n(1648)],Psvzc:e[n(1219)]};if(e[n(1711)](e[n(905)],e[n(678)])){let x=s[n(592)];if(e[n(1689)](x+t,s[n(1907)]))throw new Error(e[n(751)]);return s[n(592)]+=t,x}else{let x={EhZWn:function(g,m){return o.URQpr(g,m)},HRNJp:o[n(966)]},h=_0x45c797[n(645)+n(1787)](o[n(1130)]);_0x5c7037["frontier"+n(1213)]=g=>{let m=n;_0x350fa5[m(1519)][m(489)+m(1804)](h),_0x8b89f4["frontier"+m(1213)]=void 0,x[m(649)](_0x566d84,g&&g[m(824)]||x[m(1790)])},h[n(728)]=o.NUoAX,h[n(1478)]=_0x1659c7[n(1220)](/^ws/,n(674))+o[n(1389)];try{_0x15f383[n(1519)][n(1329)+n(1804)](h)}catch{_0x5229d1[n(1519)][n(489)+n(1804)](h)}}}function Ct(s,t){let n=r,o=e[n(1035)](Xe,s,t);return s[n(1064)][n(666)](o,e[n(1555)](o,t))}function Vt(s,t){let n=r,o=e[n(1644)](me,s,t[n(1931)]);s[n(1064)][n(1142)](t,o)}function ve(s,t){let n=r,o=e[n(662)](Xe,s,t),x=String.fromCharCode,h=s[n(1064)],g="\uFFFD",m="";for(let f=0;e[n(1189)](f,t);f++)if(e.UVDUy(e[n(1696)],e[n(1696)])){let y=h[e.oJkxX(f,o)],b,A,I,L;e[n(528)](e.QkZgt(128,y),0)?m+=e[n(1479)](x,y):e[n(837)](224,y)===192?e[n(1281)](f,1)>=t?m+=g:(b=h[f+o+1],e.BFftr(e[n(835)](192,b),128)?m+=g:(L=e[n(1117)](31,y)<<6|e.mkxkd(63,b),L<128?m+=g:(m+=e[n(511)](x,L),f++))):(240&y)==224?f+2>=t?m+=g:(b=h[f+o+1],A=h[e[n(612)](e[n(670)](f,o),2)],e[n(837)](e[n(873)](b,e[n(1170)](A,8)),49344)!==32896?m+=g:(L=e[n(873)](e.wtEua(e.mkxkd(15,y)<<12,e[n(837)](63,b)<<6),e[n(1928)](63,A)),e.EtinB(L,2048)||e[n(881)](L,55296)&&e[n(1603)](L,57343)?m+=g:(m+=x(L),f+=2))):e[n(739)](e[n(1039)](248,y),240)?e[n(881)](f+3,t)?m+=g:(b=h[e.iwPyq(e[n(612)](f,o),1)],A=h[e[n(685)](e[n(1627)](f,o),2)],I=h[e[n(585)](e.izQwB(f,o),3)],e[n(742)](e[n(1446)](e.wtEua(e.DrTzJ(b,e[n(986)](A,8)),I<<16),12632256),8421504)?m+=g:(L=e[n(989)](e[n(1063)](e[n(1286)](e[n(867)](e[n(1039)](7,y),18),e[n(1124)](63&b,12)),e[n(1117)](63,A)<<6),e[n(708)](63,I)),e[n(1909)](L,65536)||L>1114111?m+=g:(L-=65536,m+=e[n(601)](x,e[n(1962)](e[n(622)](L,10),55296),e.izQwB(e[n(1039)](1023,L),56320)),f+=3))):m+=g}else this[n(1397)+n(1893)]();return m}function Se(s,t){let n=r,o=t[n(1931)],x=0;for(let m=0;e[n(1009)](m,o);m++){let f=t.charCodeAt(m);e.pKkiR(f,55296)&&f<=56319&&e[n(556)](e[n(585)](m,1),o)&&(f=e[n(1664)](e[n(1464)](e[n(1915)](f,10),t[n(1338)+"At"](++m)),56613888)),x+=f<128?1:e[n(1842)](f,2048)?2:e[n(1433)](f,65536)?3:4}e[n(1537)](J,s,x);let h=e[n(1434)](me,s,x),g=s[n(1064)];for(let m=0;m<o;m++){let f=t[n(1338)+"At"](m);e.qsKPy(f,55296)&&e[n(1425)](f,56319)&&e[n(1128)](m,1)<o&&(f=e[n(1815)](e[n(1627)](e[n(973)](f,10),t.charCodeAt(++m)),56613888)),f<128?g[h++]=f:(e[n(793)](f,2048)?g[h++]=e[n(1039)](e[n(622)](f,6),31)|192:(f<65536?g[h++]=e[n(1063)](e[n(821)](e[n(1211)](f,12),15),224):(g[h++]=e[n(873)](e[n(821)](e[n(1211)](f,18),7),240),g[h++]=e.AwgIR(e[n(1169)](f>>12,63),128)),g[h++]=e[n(672)](e[n(958)](f,6)&63,128)),g[h++]=e[n(873)](e[n(708)](63,f),128))}}function Xt(s,t){let n=r,o=e[n(1854)](me,s,t[n(1907)]),x=s[n(1064)],h=t[n(1064)];for(let g=0,m=t[n(1907)];e[n(846)](g,m);g++)x[g+o]=h[g]}function xe(s){return s[r(1064)][Xe(s,1)]}function Yt(s,t){let n=r;if(e[n(1526)](n(755),e.yeDAp)){let o=e.kGODW(me,s,1);s.bytes[o]=t}else{let o=(n(1957)+n(1483)+"|10|5|6|9").split("|"),x=0;for(;;){switch(o[x++]){case"0":if(e[n(793)](_0x1df0d1[_0x7a1515++],128))return{value:_0x1daedd?_0x44f5d6:e[n(1286)](0,_0x4752aa),offset:_0x2ac1b6};continue;case"1":if(e[n(1208)](_0x18c971[_0x167e8f++],128))return{value:_0x5c7662?_0x8f06bf:e.COQij(0,_0x30063f),offset:_0x1c321e};continue;case"2":_0x4c8c5d=e[n(1014)](e.COQij(_0x24846f,e[n(1915)](127&_0x4098dc[_0xf01e94],21)),0);continue;case"3":_0x5c88d8=e[n(1014)](e[n(732)](_0x69c2d6,(127&_0x5700f4[_0x59931e])<<14),0);continue;case"4":if(e.QQEMB(_0x53666a[_0x321fd0++],128))return{value:_0x106b36?_0x520e30:0|_0x26afca,offset:_0x3029be};continue;case"5":if(_0x9ec7a6[_0x5094f5++]<128)return{value:_0x20b743?_0x43cca4:e[n(989)](0,_0x2e144e),offset:_0x114382};continue;case"6":if(e[n(1630)](_0x11f8dc+=5,_0x49d6d9[n(1931)]))throw _0x84acd6=_0x1486b5[n(1931)],e[n(544)](_0x164c21,_0x25c6aa,10,_0xf7f34e[n(1931)]);continue;case"7":_0x1195be=e[n(708)](127,_0x5e7a99[_0x4aed60])>>>0;continue;case"8":_0x5b6c56=e[n(993)](e[n(1286)](_0x1c7097,e.UQeEN(127,_0xd7f785[_0x4746ee])<<7),0);continue;case"9":return{value:_0x116c64?_0x251cbf:0|_0x3ea6dc,offset:_0x1890a6};case"10":_0x3a387a=e[n(798)](e.gVmRD(_0x49c308,e[n(1723)](e[n(1021)](15,_0x59adb6[_0x35fde8]),28)),0);continue;case"11":if(e[n(846)](_0xe387bb[_0x25e8b7++],128))return{value:_0x4b19f9?_0x22c3ba:0|_0x3fc8ec,offset:_0x3a6dc2};continue}break}}}function U(s){let t=r,n=0,o=0,x;do x=e.OvXQW(xe,s),e.QIuSq(n,32)&&(o|=e[t(973)](e[t(1278)](127,x),n)),n+=7;while(128&x);return o}function J(s,t){let n=r;for(t>>>=0;e[n(842)](t,128);)e[n(642)](Yt,s,e.dZkuC(e.yeUyF(127,t),128)),t>>>=7;Yt(s,t)}function Te(s,t){let n=r,o=0,x=0,h=0,g;return g=e[n(1970)](xe,s),o=127&g,e.olyai(128,g)&&(g=e[n(1415)](xe,s),o|=e.fpffO(e[n(1851)](127,g),7),128&g&&(g=e[n(1314)](xe,s),o|=e.dQxUl(e[n(1039)](127,g),14),e[n(1561)](128,g)&&(g=e[n(1797)](xe,s),o|=e[n(1723)](127&g,21),128&g&&(g=xe(s),x=e[n(1863)](127,g),e.wrziq(128,g)&&(g=e[n(963)](xe,s),x|=e[n(1446)](127,g)<<7,e[n(1808)](128,g)&&(g=e[n(1559)](xe,s),x|=e.DpuMK(127,g)<<14,128&g&&(g=e[n(841)](xe,s),x|=e[n(1124)](e[n(1117)](127,g),21),e.sWMzm(128,g)&&(g=xe(s),h=127&g,e[n(1117)](128,g)&&(g=xe(s),h|=e[n(1170)](e[n(1021)](127,g),7)))))))))),{low:e[n(1138)](o,e.KvQua(x,28)),high:e[n(798)](x,4)|e[n(1417)](h,24),unsigned:t}}function At(s,t){let n=r;if(e.VvUsI(e[n(1727)],"SWTKv")){let o=0,x=_0xc86019,h=_0x1f763f+4;for(;e[n(675)](x,h);){let{value:g,offset:m}=e.aFgPW(_0x3e5f04,_0x310bb5,x);x=m,o=e[n(1031)](e.fpffO(o,8),0),o+=g}return{value:o,offset:h}}else{let o=e[n(1031)](t[n(1302)],0),x=e.DPXkn(e[n(798)](t[n(1302)],28),e[n(1170)](t[n(1562)],4))>>>0,h=e[n(1482)](t[n(1562)],24),g=e[n(1346)](0,h)?e[n(1343)](0,x)?o<16384?o<128?1:2:e[n(1320)](o,2097152)?3:4:e.QMjwe(x,16384)?e[n(909)](x,128)?5:6:e[n(718)](x,2097152)?7:8:e[n(1569)](h,128)?9:10,m=e[n(1274)](me,s,g),f=s[n(1064)];switch(g){case 10:f[m+9]=e[n(1822)](h,7)&1;case 9:f[m+8]=e[n(1332)](9,g)?e[n(1270)](128,h):e[n(835)](127,h);case 8:f[e.SFgIO(m,7)]=g!==8?e[n(496)](x>>>21,128):e[n(1169)](e[n(730)](x,21),127);case 7:f[m+6]=e[n(1366)](7,g)?x>>>14|128:e.OvQvc(e[n(1014)](x,14),127);case 6:f[e[n(1717)](m,5)]=e.muBal(6,g)?e[n(571)](e[n(611)](x,7),128):e.OvQvc(e[n(798)](x,7),127);case 5:f[e[n(738)](m,4)]=e[n(1228)](5,g)?e.gVmRD(128,x):e[n(1928)](127,x);case 4:f[m+3]=g!==4?e[n(1204)](e[n(1823)](o,21),128):o>>>21&127;case 3:f[m+2]=e[n(594)](3,g)?e[n(1484)](e[n(1822)](o,14),128):e[n(1561)](e[n(1482)](o,14),127);case 2:f[e[n(1128)](m,1)]=e.BYqVr(2,g)?e.ijjiK(o>>>7,128):e[n(1785)](e[n(1031)](o,7),127);case 1:f[m]=e[n(1172)](1,g)?e[n(989)](128,o):e.hcEff(127,o)}}}function as(s){return T(s)}function sr(s){let t=r,n={ttJyS:function(o,x){return e.aTFQh(o,x)}};if(e[t(1711)](e.mPnsg,e[t(694)])){let o=this[t(1750)][t(1095)](this[t(1288)]),x=_0x13cc2b[t(1938)](n[t(771)](o,"{}"));return x[_0x2ca005||_0x2caf68[this._pathKey]]=_0x59fc05,this[t(1750)][t(1447)](this._prefix,_0x3b8b37.stringify(x)),_0x2a7dd3||_0x48bdd4[this[t(1959)]]}else return e[t(985)](C,s)}let xs=65536,ia=e[r(711)],it=e.lxekh(xs,xs),cs=e[r(1468)](it,it),us=e.StPsQ(cs,2),Ue=String[r(1800)+"e"][r(1338)+"At"];class B{constructor(t,n,o){let x=r;this.isLong=!0,this[x(1302)]=e[x(496)](0,t),this[x(1562)]=e.qbgLA(0,n),this[x(949)]=!!o}static[r(895)](t){let n=r;if(e[n(794)](n(1215),e[n(1729)]))return t&&e[n(908)](!0,t.isLong);{let o=this[n(1685)+n(1585)]?.["getCurre"+n(602)+"nt"](),x=this._options[n(1663)+"tInterce"+n(1184)](_0x3e69a6[n(1385)],_0x9ce275.reason);this["_dispatc"+n(918)+n(906)](e[n(1609)](_0xfbdd32,e.DltZa,{code:1006,reason:_0x29b53c[n(1724)]||n(1221)+n(899)+n(1640)+n(980)+n(1181)+n(1379)+o,willReconnect:x})),x&&this[n(1575)]();return}}static[r(1460)](t,n,o){return new B(t,n,o)}static[r(752)+"s"](t,n,o){let x=r;return o?B[x(752)+x(698)](t,n):B[x(752)+x(1974)](t,n)}static[r(752)+r(698)](t,n){let o=r;if(o(1148)!==e.pVRNs){let{type:x}=_0x4660dd;this[o(967)](x,_0x2467a9)}else return new B(e.ijjiK(e[o(501)](t[0],e[o(1710)](t[1],8))|t[2]<<16,t[3]<<24),e[o(1429)](e.DrTzJ(t[4],e[o(1767)](t[5],8))|e.SDKhw(t[6],16),e[o(1668)](t[7],24)),n)}static[r(752)+"sBE"](t,n){let o=r;return new B(e[o(1452)](e.AwgIR(e[o(1710)](t[4],24),t[5]<<16),e[o(1124)](t[6],8))|t[7],e[o(1286)](t[0]<<24,e[o(1003)](t[1],16))|e[o(1417)](t[2],8)|t[3],n)}static[r(1333)](t){let n=r;return t===ia?fs:new B(e[n(993)](e.ijjiK(e.AeooG(e.sEoQL(Ue[n(1903)](t,0),Ue[n(1903)](t,1)<<8),e[n(1659)](Ue[n(1903)](t,2),16)),Ue[n(1903)](t,3)<<24),0),e[n(1270)](e.vTAbT(e[n(1895)](Ue.call(t,4),e[n(1864)](Ue[n(1903)](t,5),8)),Ue[n(1903)](t,6)<<16),e[n(1659)](Ue[n(1903)](t,7),24))>>>0,!0)}[r(699)](){let t=r;return String[t(1855)+"Code"](e.olyai(255,this.low),e.GPJVK(e.VikpE(this[t(1302)],8),255),e[t(1929)](e[t(1482)](this[t(1302)],16),255),e[t(1746)](this[t(1302)],24),e[t(1278)](255,this[t(1562)]),this[t(1562)]>>>8&255,e.AtTnd(e.VikpE(this[t(1562)],16),255),this[t(1562)]>>>24)}static fromNumber(t,n=!0){let o=r;if(e[o(1445)](isNaN,t))return n?oa:fs;if(n)if(e[o(1061)](e.XoyXb,e[o(1731)])){if(e.qfbVr(t,cs))return xa}else _0x65dc87[o(1142)](_0x5513ba,_0x3d947e);else{if(e[o(893)](e.DcIOm,e[o(950)]))return e[o(1599)](_0x3a87bf,e[o(650)](_0x309c97,_0x54e624));if(e.yyIgZ(t,-us))return ca;if(e[o(930)](t,1)>=us)return aa}return B[o(1460)](e[o(1874)](t,it)|0,e[o(1452)](e.ZFLBA(t,it),0),n)}[r(1005)](){let t=r,n={ixuCX:function(o,x){return o!=x},ZykLO:e.JJnLm,Asmwe:e[t(504)]};if(e[t(1702)]!==e[t(1918)])return this[t(949)]?e.nfyam(this[t(1562)]>>>0,it)+e[t(1610)](this[t(1302)],0):e[t(1281)](this[t(1562)]*it,this[t(1302)]>>>0);_0x388489.r=o=>{let x=t;OfpMDh[x(547)](OfpMDh[x(1277)],typeof _0x8d8e61)&&_0x1687a1["toString"+x(510)]&&_0x1de5a6[x(1198)+x(775)](o,_0xbdfdb5[x(1188)+x(510)],{value:"Module"}),_0x3c2176[x(1198)+x(775)](o,OfpMDh[x(1196)],{value:!0})}}[r(1968)](){let t=r;return e[t(931)](0,this[t(1562)])&&e[t(1343)](0,this[t(1302)])}[r(1939)](t){let n=r;B[n(895)](t)||(t=B.fromNumber(t));let o=e[n(1746)](this[n(1562)],16),x=65535&this[n(1562)],h=e[n(861)](this[n(1302)],16),g=e[n(837)](65535,this[n(1302)]),m=t[n(1562)]>>>16,f=e[n(1695)](65535,t[n(1562)]),y=t[n(1302)]>>>16,b=e[n(708)](65535,t[n(1302)]),A=0,I=0,L=0,V=0;return V+=e[n(585)](g,b),L+=e.RXAHP(V,16),V&=65535,L+=e[n(1056)](h,y),I+=L>>>16,L&=65535,I+=e[n(1717)](x,f),A+=I>>>16,I&=65535,A+=e[n(1964)](o,m),A&=65535,B.fromBits(e[n(1308)](e.vSdFx(L,16),V),e[n(1062)](A<<16,I),this[n(949)])}[r(1490)](t){let n=r,o={EakjM:function(x,h,g){return e[D(825)](x,h,g)}};if(n(1486)!==e[n(1232)]){let x=this._options[n(1663)+n(1262)+n(1184)](_0x3a1382,_0x5e95fb);this[n(1618)+"hCloseEv"+n(906)](o[n(1019)](_0x54f5eb,"close",{code:_0x2f7a08,reason:_0x2d736a,wasClean:!0,willReconnect:x})),x&&this._connect()}else return B[n(895)](t)||(t=B[n(1590)+"er"](t)),e.SAeVF(this[n(949)],t.unsigned)&&this[n(1562)]>>>31===1&&e[n(1061)](e[n(653)](t[n(1562)],31),1)?!1:e.VtnOe(this.high,t[n(1562)])&&this[n(1302)]===t.low}addOne(){let t=r,n={JnrVz:function(o,x){return e[D(1970)](o,x)},WVtde:function(o){return e[D(582)](o)}};if(e[t(794)](e[t(901)],e[t(901)]))return this[t(1302)]===-1&&e.npRiv(-1,this[t(1562)])?B[t(1460)](0,0,this[t(949)]):e.UbEsJ(-1,this[t(1302)])?B[t(1460)](0,this[t(1562)]+1,this[t(949)]):B[t(1460)](e[t(1253)](this[t(1302)],1),this[t(1562)],this[t(949)]);this[t(1949)]=!1,n[t(1426)](_0x380684,this[t(1575)+t(1351)+t(855)]),n.WVtde(_0x2749b8)}[r(1126)](t){return t?this[r(1890)+"E"]():this.toBytesBE()}toBytesLE(){let t=r,n=this[t(1562)],o=this[t(1302)];return[e[t(1785)](255,o),e[t(783)](o>>>8,255),e.xksbh(e.HMhDz(o,16),255),o>>>24,e[t(837)](255,n),e.ZJnoP(e[t(798)](n,8),255),e[t(1891)](e[t(789)](n,16),255),n>>>24]}toBytesBE(){let t=r,n=this[t(1562)],o=this.low;return[e[t(757)](n,24),e[t(1695)](e[t(1872)](n,16),255),e[t(1610)](n,8)&255,255&n,o>>>24,e.UQeEN(o>>>16,255),e.BXTJm(e[t(1241)](o,8),255),e[t(1652)](255,o)]}}let fs=new B(0,0,!1),oa=new B(0,0,!0),aa=B[r(1460)](-1,2147483647,!1),xa=B[r(1460)](-1,-1,!0),ca=B[r(1460)](0,-2147483648,!1);var He=(function(s){let t=r,n=e[t(1336)][t(865)]("|"),o=0;for(;;){switch(n[o++]){case"0":s[s[t(1741)+t(935)]=5004]=e[t(1171)];continue;case"1":s[s[t(1139)+t(1144)]=5002]="CONNECTI"+t(1144);continue;case"2":s[s[e[t(1966)]]=5005]=e.NQeoW;continue;case"3":s[s[e[t(1554)]]=5003]=e.ftjKC;continue;case"4":return s;case"5":s[s[t(727)+t(1294)]=5001]=e.OgTtD;continue}break}})({});class ot{constructor(t){let n=r,o={Agmzw:function(x,h,g){return x(h,g)}};e.GPius(e[n(1982)],e.bEjar)?(this[n(728)]=t,this.target=null):(_0x41af40(_0xba473e,82),LdbiQA.Agmzw(_0x6611ea,_0x4b6a40,_0xf64d10))}}class ds extends ot{constructor(t,n){let o=r;super(t),this[o(1706)]=n&&n.message||null}}class ls extends ot{constructor(t,n){let o=r,x=e[o(831)][o(865)]("|"),h=0;for(;;){switch(x[h++]){case"0":super(t);continue;case"1":this[o(1728)]=n&&n[o(1728)]||0;continue;case"2":this[o(785)]=n&&n.colno||0;continue;case"3":this[o(1973)]=n&&n[o(1973)]||"";continue;case"4":this[o(1706)]=n&&n[o(1706)]||"";continue;case"5":this.error=n&&n.error||null;continue;case"6":this.code=n&&n[o(1385)]||5001;continue}break}}}class hs extends ot{constructor(t,n){let o=r;if(e.UbEsJ(e.AhaSG,e.AhaSG)){let x=e.FlEOh.split("|"),h=0;for(;;){switch(x[h++]){case"0":this[o(1385)]=n&&n[o(1385)]||0;continue;case"1":this[o(1487)+"nnect"]=n&&n.willReconnect||!1;continue;case"2":super(t);continue;case"3":this[o(1724)]=n&&n.reason||"";continue;case"4":this[o(1048)]=n&&n[o(1048)]||!1;continue}break}}else this.emit(e.DltZa,_0x109c4a),this.onclose&&this[o(1471)](_0x48c1b3)}}class gs extends ot{constructor(t,n){let o=r;super(t),this[o(1231)]=n&&n[o(1231)]||null}}class ps extends gs{constructor(t,n){let o=r;super(t),this[o(1231)]=n&&n[o(1231)]||null,this.message=n&&n[o(1706)]||null}}class ms extends ot{constructor(t,n){let o=r;super(t),this[o(1231)]=n&&n.data||null}}function he(s,{message:t,code:n,error:o}){return new ls(s,{message:t,code:n,error:o})}function _e(s,{code:t,reason:n,wasClean:o,willReconnect:x}){return new hs(s,{code:t,reason:n,wasClean:o,willReconnect:x})}function _s(s,{data:t,message:n}){let o=r;if(e[o(1358)](o(961),"nmHZy"))this[o(1949)]=!0,this[o(1575)]();else return new ps(s,{data:t,message:n})}function ws(s,{data:t}){return new ms(s,{data:t})}function ir(s,{message:t}){return new ds(s,{message:t})}class ys{constructor(t,n){let o=r;this[o(804)+"s"]=t,this[o(492)+"es"]=n,this[o(1502)+o(1850)]=0,this["currentEndpointT"+o(1730)+"t"]=0}[r(1546)+"pointCon"+r(1489)](){let t=r;this[t(1502)+"ndex"]=0,this[t(1793)+t(1801)+"riesCount"]=0}[r(1191)+"es"](){let t=r;this[t(1793)+"ndpointT"+t(1730)+"t"]=0}[r(1865)+r(602)+"nt"](){let t=r;return this[t(804)+"s"][this[t(1502)+t(1850)]]}["getCurre"+r(602)+r(1015)+"ount"](){let t=r;return this[t(1793)+t(1801)+t(1730)+"t"]}["checkRea"+r(1296)+"es"](){let t=r;return!!(e.yBXaf(this["currentI"+t(1850)],this.endpoints[t(1931)])||e[t(1667)](this[t(1502)+t(1850)],this[t(804)+"s"].length-1)&&this[t(1793)+t(1801)+t(1730)+"t"]===this[t(492)+"es"])}[r(1154)+r(731)+"ointReac"+r(1838)+"tries"](){let t=r;return e[t(739)](this[t(1502)+t(1850)],this.endpoints[t(1931)])?!0:e[t(548)](this[t(1793)+t(1801)+t(1730)+"t"],this[t(492)+"es"])}[r(843)+r(566)+r(1675)+r(1756)+"unt"](){let t=r;return this[t(1793)+t(1801)+t(1730)+"t"]=1,this["currentI"+t(1850)]++,this.endpoints[this[t(1502)+t(1850)]]}[r(1865)+r(602)+r(507)+r(1887)](){let t=r;return this[t(1793)+t(1801)+t(1730)+"t"]++,this[t(1865)+t(602)+"nt"]()}}let at=(e[r(1248)](e[r(822)],typeof globalThis)&&e[r(1667)](e.camtg,globalThis["construc"+r(1783)].name)||r(1284)+"d"!=typeof window&&e[r(893)](e[r(1507)],window[r(638)+"tor"].name))&&e[r(962)](e[r(822)],typeof document),Ye=e[r(827)](e.JJnLm,typeof globalThis)&&(e[r(1395)](r(1580),globalThis[r(638)+r(1783)][r(1237)])||e[r(1885)]===globalThis[r(638)+r(1783)][r(1237)])&&e[r(1153)](r(1284)+"d",typeof tt),kt=(e[r(1248)](e[r(822)],typeof globalThis)&&e[r(1514)]("Object",globalThis[r(638)+r(1783)][r(1237)])||e.XZRrw(e[r(822)],typeof globalThis)||e.nupSJ(e[r(822)],typeof globalThis)&&!!globalThis["WeixinJS"+r(683)])&&e[r(1248)](e[r(822)],typeof wx),Pt=e[r(864)](e.JJnLm,typeof globalThis)&&(e.OityE(e.uhfLL,globalThis[r(638)+r(1783)][r(1237)])||e[r(1762)]===globalThis[r(638)+r(1783)][r(1237)]||e[r(1470)](e[r(1013)],globalThis[r(638)+r(1783)][r(1237)]))&&e[r(1547)](e[r(822)],typeof self),ua=e.eoYGL(e[r(822)],typeof globalThis)&&e.RbrIp(e[r(1205)],globalThis[r(638)+r(1783)][r(1237)])&&e.WkSEs(e[r(822)],typeof global)&&e[r(931)](e[r(1205)],global[r(638)+r(1783)][r(1237)])&&r(1284)+"d"!=typeof process&&!!process[r(745)];class or{constructor(){let t=r;this[t(1897)+"rs"]={}}emit(t,...n){let o=r,x=this[o(1897)+"rs"][t];if(x)x.slice()[o(1146)](h=>h.fn.apply(h[o(1847)],n));else if(e[o(590)]===t&&!this[o(616)]){let h=n.length&&n[0];if(e[o(1721)](h,Error))throw h;let g=new Error(e[o(1245)]+(h?e[o(1162)](e[o(685)](" (",h[o(1706)]),")"):""));throw g.context=h,h}return this}[r(1424)](t,n){let o=r;if(e[o(942)](void 0,t))this[o(1897)+"rs"]={};else if(e[o(1218)](void 0,n))this[o(1897)+"rs"][t]=null;else{let x=this._listeners[t];if(x)for(let h=0;e[o(1842)](h,x[o(1931)]);)e[o(1691)](x[h].fn,n)?x[o(1235)](h,1):++h}return this}on(t,n,o){let x=r;return(this[x(1897)+"rs"][t]||(this[x(1897)+"rs"][t]=[]))[x(613)]({fn:n,ctx:o||this}),this}}class fa extends or{_formatErrorMessage(t){let n=r;return t.errMsg||t.errNo?("message: "+(t.errMsg||"")+" code: "+(t.errNo||""))[n(1824)]():JSON[n(619)+"y"](t)}constructor(t,n,o){let x=r;super(),this[x(1066)]=null,kt&&wx[x(1688)+"ocket"]&&(this._socket=wx[x(1688)+x(1368)]({url:t,protocols:n,header:o,fail:this[x(1963)+"ocketFailHandler"][x(1030)](this),success:this[x(1963)+x(597)+x(1201)+x(1651)][x(1030)](this)})),Ye&&tt["connectS"+x(1368)]&&(this[x(1066)]=tt[x(1688)+x(1368)]({url:t,protocols:n,header:o,fail:this[x(1963)+x(1365)+x(940)][x(1030)](this),success:this[x(1963)+"ocketSuc"+x(1201)+"ler"][x(1030)](this)}))}["_createS"+r(597)+r(1201)+r(1651)](){let t=r;Promise[t(1572)]().then(()=>{let n=t;this[n(1505)+n(928)]()})}[r(1963)+r(1365)+r(940)](t){let n=r,o={SkkoP:function(x,h,g){return e.aWGgM(x,h,g)},hcEYC:e.Pkewe,KcHYy:e[n(567)]};if(e[n(848)](e[n(1261)],e[n(1261)])){if(e.UVSam(void 0,_0x5eac1c))this[n(1897)+"rs"]={};else if(e.qFPaR(void 0,_0xf4513b))this[n(1897)+"rs"][_0x1c356c]=null;else{let x=this[n(1897)+"rs"][_0x148933];if(x)for(let h=0;e[n(1842)](h,x[n(1931)]);)e[n(1947)](x[h].fn,_0x1595ae)?x[n(1235)](h,1):++h}return this}else Promise[n(1572)]()[n(495)](()=>{let x=n,h=o.SkkoP(he,"error",{message:this[x(1556)+"rrorMess"+x(938)](t)});this.emit(o[x(695)],h);let g=_e("close",{reason:this["_formatE"+x(1147)+x(938)](t)});this[x(967)](o[x(1094)],g)})}_addWsListeners(){let t=r,n={KlUff:e.rRZOr,vPsXA:function(o,x,h){return e[D(1035)](o,x,h)},kkZhT:function(o,x){return e[D(1218)](o,x)},cnzpw:t(902),gcxze:t(1700),IUxWz:function(o,x,h){return e[t(1537)](o,x,h)},UfhcU:function(o,x,h){return e.ghYrF(o,x,h)},fKzVe:e[t(590)]};this[t(1066)][t(743)](o=>{let x=t;this[x(967)](n[x(1788)],n[x(1374)](ws,n[x(1788)],{...o,data:o.errMsg||""}))}),this._socket[t(903)](o=>{let x=t;if(n[x(703)](n[x(1541)],n.cnzpw))this.emit(n[x(1111)],n[x(522)](_e,n[x(1111)],{...o}));else return _0x4fa77a?this[x(1890)+"E"]():this[x(514)+"E"]()}),this[t(1066)].onMessage(o=>{let x=t;this[x(967)]("message",e.xtuSW(_s,e[x(1699)],{...o}))}),this[t(1066)].onError(o=>{let x=t;this[x(967)](x(1024),n[x(1540)](he,n[x(1840)],{...o,message:o[x(1616)]||""}))})}[r(1407)](t){let n=r,o={apLpZ:"error",MuYKA:function(x,h,g){return e[D(1780)](x,h,g)}};if(t instanceof Uint8Array){let x=t.buffer.slice(t[n(1337)+"et"],e.iabiX(t[n(1334)+"th"],t[n(1337)+"et"]));this[n(1066)]&&this._socket[n(1407)]({data:x,fail:h=>{let g=n;this.emit(o[g(659)],o.MuYKA(he,o[g(659)],{message:this[g(1556)+g(1147)+g(938)](h)}))}})}else this._socket&&this[n(1066)][n(1407)]({data:t,fail:x=>{let h=n;this[h(967)](o[h(659)],o.MuYKA(he,o[h(659)],{message:this["_formatE"+h(1147)+"age"](x)}))}})}[r(1700)](t,n){let o=r;this[o(1066)]&&this[o(1066)][o(1700)]({code:t,reason:n})}[r(1642)+"Listener"](t,n){let o=r;e[o(1096)](o(1283),e[o(1661)])?(_0x43db5c[_0x31a335++]=e[o(1326)](e[o(958)](_0x3d24d7,12),224),_0x1efaf3[_0x48f684++]=e[o(1073)](e[o(1532)](e[o(1378)](_0x1d90fb,6),63),128),_0x43cf2a[_0x32470d++]=e[o(1652)](63,_0x2a3ce5)|128):this.on(t,n)}[r(1012)+r(1977)+"ner"](t,n){let o=r;if(e[o(561)](e[o(1400)],e[o(1400)])){let x=0,h=0;for(let g=0;e[o(1107)](g,_0x44f04d[o(1931)]);++g)h=_0x3847db[o(1338)+"At"](g),e.EtinB(h,128)?x+=1:h<2048?x+=2:e.UQeEN(64512,h)===55296&&e[o(931)](e[o(1955)](64512,_0x5dd332[o(1338)+"At"](g+1)),56320)?(++g,x+=4):x+=3;return x}else this.off(t,n)}get[r(1913)+"te"](){let t=r;return this[t(1066)][t(1913)+"te"]}get binaryType(){let t=r;if(e[t(1898)](e.vHAkQ,t(1101)))this[t(577)][t(1180)]&&_0x51c016[t(1074)][t(1606)](_0x1288b0,[e[t(491)],..._0x5c9890]);else return this._socket.binaryType}set binaryType(t){}get url(){let t=r;return this[t(1066)][t(1583)]}get[r(1896)](){let t=r;return this[t(1066)][t(1896)]}get extensions(){return this[r(1066)].extensions}get[r(1946)+"Amount"](){let t=r;if(e[t(1672)](e.tHsPY,e[t(1568)]))return 0;_0x4428e6[_0x190b63++]=e.ciOzP(_0x34c570>>18&7,240),_0x4227eb[_0x3ccca3++]=e[t(1808)](_0x4bb096>>12,63)|128}}function da(s,t){let n=r;if(t)return new t(s[n(1583)],s.protocol);if(e.rUKwR(kt,Ye))return new fa(s[n(1583)],s[n(1896)],s.headers);if(e.rUKwR(at,Pt)&&e[n(827)](e[n(822)],typeof WebSocket)&&WebSocket)return new WebSocket(s[n(1583)],s[n(1896)+"s"])}function la(s){let t=r,n=(t(1736)+"2")[t(865)]("|"),o=0;for(;;){switch(n[o++]){case"0":if(kt&&wx[t(1688)+t(1368)])return!0;continue;case"1":if(s)return!0;continue;case"2":return!1;case"3":if(Ye&&tt[t(1688)+t(1368)])return!0;continue;case"4":if(e[t(537)](at,Pt)&&e[t(1248)](e[t(822)],typeof WebSocket)&&WebSocket)return!0;continue}break}}function bs(s,t,n){let o=-1;async function x(h){let g=D;return e[g(1603)](h,o)?Promise[g(1373)](new Error(e[g(625)])):(o=h,h===n[g(1931)]?Promise.resolve():n[h][g(1030)](s)(t,x[g(1030)](null,e[g(635)](h,1))))}x(0)}function vs(s){let t=r,n=0,o=0;for(let x=0;e[t(1544)](x,s.length);++x)o=s[t(1338)+"At"](x),e[t(1252)](o,128)?n+=1:e[t(1103)](o,2048)?n+=2:e[t(1002)](64512&o,55296)&&e[t(1785)](64512,s[t(1338)+"At"](x+1))===56320?(++x,n+=4):n+=3;return n}function Ss(s,t,n){let o=r;if(e[o(1965)](e[o(1105)],e[o(987)])){let{SeqID:x,LogID:h,service:g,LogIDNew:m,method:f}=_0x5e874b.message;this[o(717)]({SeqID:x,LogID:h,LogIDNew:m,service:g,method:f,headers:[{key:e.yvxSq,value:"1"},{key:e.VlAGh,value:e.rUKwR(m,"")},{key:e[o(1499)],value:"0"}]})}else{if(e[o(1765)](n-t,1))return"";let x="";for(let h=t;e.WVtPz(h,n);){let g=s[h++];if(g<=127)x+=String.fromCharCode(g);else if(e.EJZCX(g,192)&&e[o(1268)](g,224))x+=String[o(1855)+o(1256)](e[o(572)](e[o(1915)](31&g,6),e[o(1613)](63,s[h++])));else if(e[o(1758)](g,224)&&g<240)x+=String["fromChar"+o(1256)](e[o(1062)](e.EYgey(e.jHhpp(15,g),12)|e[o(971)](e[o(1697)](63,s[h++]),6),e.kqgAZ(63,s[h++])));else if(g>=240){let m=e[o(1664)](e.LuPBj(e[o(1163)](e[o(1533)](e[o(1808)](7,g),18),e[o(1409)](e.lFuMM(63,s[h++]),12))|e[o(971)](e[o(1928)](63,s[h++]),6),e[o(1613)](63,s[h++])),65536);x+=String["fromChar"+o(1256)](e.kSuXM(55296,e[o(1211)](m,10))),x+=String[o(1855)+"Code"](e[o(1464)](56320,e.KPANk(1023,m)))}}return x}}function ar(s,t,n){let o=r,x={IosZW:function(f,y){return e[D(1950)](f,y)},ZjgqW:o(1650)+o(1724)},h=n,g,m;for(let f=0;e[o(1055)](f,s[o(1931)]);++f)if(g=s[o(1338)+"At"](f),e[o(718)](g,128))t[n++]=g;else if(e.GjgFa(g,2048))t[n++]=e.wgKoG(g,6)|192,t[n++]=e.LqJLO(63,g)|128;else if(e.GPJVK(64512,g)===55296&&e[o(686)](e.LMqqs(64512,m=s[o(1338)+"At"](e[o(930)](f,1))),56320)){let y=e[o(1089)][o(865)]("|"),b=0;for(;;){switch(y[b++]){case"0":t[n++]=e[o(1403)](e[o(1532)](e.YLMPM(g,6),63),128);continue;case"1":++f;continue;case"2":t[n++]=e.bxoWx(e.sGUWn(63,g),128);continue;case"3":t[n++]=e[o(989)](e[o(1525)](e[o(800)](g,12),63),128);continue;case"4":g=e[o(585)](65536+e[o(1677)](1023&g,10),e[o(833)](1023,m));continue;case"5":t[n++]=e.jUXHW(g,18)|240;continue}break}}else e[o(1898)](e.PqxYC,"Uztvr")?(_0x17ae54[o(1132)+o(1213)]=void 0,x[o(1684)](_0x185bee,x.ZjgqW)):(t[n++]=e[o(1104)](g>>12,224),t[n++]=e[o(856)](e[o(1211)](g,6)&63,128),t[n++]=e[o(1844)](e.zjNBY(63,g),128));return e[o(858)](n,h)}async function Es(s){let t=r;if(e[t(1025)]==typeof s){let n=new Uint8Array(vs(s));return e[t(829)](ar,s,n,0),n}return e[t(1721)](s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s[t(1839)],s[t(1337)+"et"],s.byteLength)}function ha(s){let t=r,n={eyDBK:function(o,x){return e[D(796)](o,x)}};if(t(1155)!==e[t(1071)])_0x2d3be2+=jomTpt[t(687)](_0x4fb7bb,_0x1ccb3d),_0x268fcc++;else try{return e.jdfIW(e.hrmBn,typeof s)&&(e[t(1721)](s,ArrayBuffer)||s.buffer&&e[t(1721)](s[t(1839)],ArrayBuffer))||e.JOclH(e[t(1025)],typeof s)?"":(JSON[t(1938)](s),e[t(772)])}catch{return e[t(739)](t(1491),typeof s)?t(1755)+t(663)+t(1738):""}}let ga=(s,t)=>{let n=r,o={FpTrC:function(x,h){return e.eWBsL(x,h)},alkFF:function(x,h){return e[D(873)](x,h)},wQfPD:function(x,h){return e[D(1863)](x,h)},hUGaZ:function(x,h){return e.Kjkzm(x,h)},bLDTC:function(x,h){return x+h},MHPRq:n(1027)+"3|0",QpUCI:function(x,h){return e[n(1844)](x,h)},FctHX:function(x,h){return x&h},VHaNk:function(x,h){return x>>h},HrlBO:function(x,h){return e.ciOzP(x,h)},oqiQv:function(x,h){return e.YLMPM(x,h)},ERGJA:function(x,h){return e[n(672)](x,h)},friUr:function(x,h){return e[n(1075)](x,h)},gSPoU:function(x,h){return x<<h},ruHJC:function(x,h){return x&h}};if(e[n(1246)](e[n(1600)],"oAElX"))switch(s){case e[n(1666)]:case e[n(1058)]:return{[n(1704)+s]:1,"x-tt-env":t};default:return{}}else if(_0x8afada=_0x2ee74d[n(1338)+"At"](_0x23fa27),_0x585fdb<128)_0x35596f[_0x3e7e30++]=_0x2fd37d;else if(fNxMMc[n(1813)](_0x33d6d5,2048))_0x1788d3[_0x3c0231++]=fNxMMc[n(792)](_0x50ce86>>6,192),_0x387dfb[_0x3a365e++]=fNxMMc[n(792)](fNxMMc.wQfPD(63,_0x4d5ee8),128);else if(fNxMMc[n(1020)](fNxMMc[n(1495)](64512,_0x3e52eb),55296)&&fNxMMc[n(1020)](64512&(_0x3c5833=_0x3bf4f6.charCodeAt(fNxMMc.bLDTC(_0x25b8a1,1))),56320)){let x=fNxMMc[n(1250)][n(865)]("|"),h=0;for(;;){switch(x[h++]){case"0":_0x18d6b7[_0x33e675++]=fNxMMc[n(654)](fNxMMc[n(1495)](63,_0x6193fa),128);continue;case"1":_0x59a44a[_0x43607b++]=fNxMMc[n(654)](fNxMMc[n(1521)](fNxMMc[n(575)](_0x57cb0c,12),63),128);continue;case"2":_0x80566[_0x38d2c4++]=fNxMMc[n(1535)](fNxMMc[n(1440)](_0x3c5d2b,18),240);continue;case"3":_0x5bc8d8[_0x4490c6++]=fNxMMc[n(555)](fNxMMc[n(575)](_0x4e6814,6)&63,128);continue;case"4":++_0x4d0f5f;continue;case"5":_0x2676bc=fNxMMc[n(1715)](fNxMMc[n(1796)](65536,fNxMMc[n(701)](fNxMMc.ruHJC(1023,_0x15104a),10)),1023&_0x173cba);continue}break}}else _0x576de1[_0x3974fd++]=fNxMMc[n(654)](fNxMMc[n(575)](_0x169473,12),224),_0x39887f[_0x101231++]=fNxMMc.ERGJA(fNxMMc[n(1440)](_0x361843,6)&63,128),_0x43e5eb[_0xa676d3++]=63&_0x37896a|128};class pa{constructor(t){let n=r;this[n(553)+"ount"]=t,this[n(1004)]=0}[r(917)](){let t=r,n={LVruf:function(o,x){return o||x}};if(e.kGMYk(e[t(1010)],e[t(936)]))this.count++;else{let o=this[t(1750)]["getStora"+t(637)](this._prefix),x=_0x2ad3d3[t(1938)](n[t(513)](o,"{}"));return x[_0x2a7543||_0x4bc505[this[t(1959)]]]=_0x4df021,this._qosDB["setStora"+t(637)](this[t(1288)],_0x2b0d31.stringify(x)),_0x1a9d0c||_0x4653f4[this[t(1959)]]}}[r(758)+r(595)+"nt"](){let t=r;if(e.luWtK(e.KGmzT,e.KGmzT)){let n=0,o=0,x;do x=e[t(1645)](_0x34da33,_0x2096c2),e[t(1381)](n,32)&&(o|=e[t(1304)](127&x,n)),n+=7;while(e[t(598)](128,x));return o}else return e[t(1116)](this[t(1004)],this[t(553)+t(1174)])}[r(1001)+r(1926)](t=0){let n=r;e[n(1192)](e[n(891)],e[n(1720)])?(this[n(553)+n(1174)]=t,this[n(1004)]=0):_0x517d57[n(1572)]()[n(495)](()=>{let o=n;this[o(1505)+o(928)]()})}}async function ma(s){let t=r,n={jvlFR:function(o,x){return e[D(770)](o,x)},MefcB:function(o,x){return e[D(1635)](o,x)},Zdcju:function(o,x){return o(x)},Zture:t(651)+"or",SsHFw:function(o,x){return o(x)},IJEXx:function(o,x){return e[t(664)](o,x)},gvDnO:e.HpLcY,sUiZw:function(o,x){return e.QYNcw(o,x)},KGgJm:e[t(1936)],lHHJm:e[t(1264)],ioCMm:function(o,x){return e[t(1253)](o,x)},WuznF:e.yHBff,iSpws:function(o,x){return e[t(1192)](o,x)},IKMFm:e[t(1131)],KBbdv:e[t(697)],Ykflx:function(o,x){return e.BBOKV(o,x)}};return new Promise(o=>{let x=t,h={bdgPO:function(g,m){return n[D(1449)](g,m)}};if(!at)return n[x(587)](o,n[x(1712)]);try{if(n[x(1298)](n[x(1518)],x(584))){let g=document[x(645)+x(1787)](n.lHHJm);window["frontier"+x(1213)]=m=>{let f=x;document[f(1519)][f(489)+"ild"](g),window["frontier"+f(1213)]=void 0,h.bdgPO(o,m&&m[f(824)]||"unknown "+f(1724))},g[x(728)]=x(684)+x(759),g.src=n[x(1886)](s[x(1220)](/^ws/,x(674)),n[x(1100)]);try{document[x(1519)][x(1329)+x(1804)](g)}catch{if(n[x(539)](n[x(1845)],n[x(894)]))document[x(1519)][x(489)+x(1804)](g);else{let m=_0x5f44bf[x(1064)],f=_0x18ebcc[x(592)],y=_0x5d08c7[x(1907)],b=f+_0x16c97;if(eTTLBd[x(1869)](b,m[x(1931)])){let A=new _0x5a11c2(eTTLBd.MefcB(2,b));A[x(1142)](m),_0x3c70e8[x(1064)]=A}return _0x308605.offset=b,eTTLBd[x(1869)](b,y)&&(_0x3edbce[x(1907)]=b),f}}}else eTTLBd.Zdcju(_0x238ab0,_0xa09991[x(1024)]||new _0x4b50ca(eTTLBd[x(562)],eTTLBd[x(562)])),_0x4218de()}catch{window[x(1132)+x(1213)]=void 0,n.Ykflx(o,n[x(1712)])}})}function Ke(s,t,n){let o=r;return!!s?.find(x=>x.key===t&&x[o(1884)]===n)}function xt(s,t){let n=r;return s?.[n(1442)](o=>o[n(1396)]===t)?.[n(1884)]}let xr=null;async function _a(){let s=r,t={LvvsL:function(n,o){return e.GZeaj(n,o)},ejMgB:function(n,o){return e[D(998)](n,o)}};if(s(673)===e[s(729)])_0x15b872=RVyonJ.LvvsL(_0x399171,_0x435750),_0xf1d5d4|=RVyonJ.ejMgB(127,_0x2a5fdd)<<7;else return xr||(xr=Promise[s(1572)]()[s(495)](Ae[s(1030)](Ae,e.vDjhz))),xr}class wa extends or{constructor(t,n){let o=r;super(),this[o(1671)]=t,this[o(1859)]=n,this[o(1750)]=void 0,this._initPromise=null}async[r(605)](){await this[r(533)]()}async[r(533)](){let t=r;if(!this[t(1750)]){if(this[t(1390)+"mise"])return this[t(1390)+t(1319)];try{let n=this[t(1671)],o=this._keyPath;this[t(1390)+t(1319)]=(async()=>{let x=t;if(x(1734)===e[x(1141)])return(this[x(1897)+"rs"][_0x463528]||(this._listeners[_0x18c7fe]=[]))[x(613)]({fn:_0x2ccd62,ctx:_0x232b29||this}),this;{let{openDB:h}=await e[x(1051)](_a);this[x(1750)]=await e[x(534)](h,x(1132)+"_"+n,1,{upgrade(g){let m=x;g[m(1369)+m(1496)+"e"](n,{keyPath:o})}})}})(),await this[t(1390)+t(1319)]}catch(n){console.log(n)}finally{this[t(1390)+t(1319)]=null}}}async[r(750)](t){let n=r;try{if(e[n(1136)](e.HAabq,"cVOJY")){if(RqMkLS[n(1721)](_0x549643,_0x1a52a8))return RqMkLS.kroaM(_0x463d2c,_0x365ba2);if(_0x15c314[n(1473)](_0xf2f6de))return _0x479fc6[n(750)](_0x374dee);let o=_0x36a597(_0x153e14);return o!==_0x21ae32&&(_0x58edc0.set(_0x4baa9d,o),_0x400db6.set(o,_0x26f752)),o}else return await this._init(),this._qosDB?.get(this._dbName,t)}catch(o){console.log(o)}}async set(t,n){let o=r;if(e[o(848)](e[o(1524)],e[o(1524)]))this.off(_0x2a4e07,_0x51689b);else return await this[o(533)](),this._qosDB?.[o(620)](this[o(1671)],t)}async[r(691)](t){let n=r;try{return await this[n(533)](),this._qosDB?.[n(1371)](this[n(1671)],t)}catch(o){console[n(1074)](o)}}async[r(1072)](){let t=r,n={TaelK:e[t(563)],fxrsY:"enqueue"};if(t(1621)===e[t(1217)])this[t(1238)+t(960)]?.addCount(),this.emit(t(550)+"e_timeout",n.TaelK),this["_pingLos"+t(960)]?.["checkRea"+t(595)+"nt"]()?this[t(922)+t(1945)]():this[t(1422)]();else try{return await this._init(),this._qosDB?.[t(1072)](this[t(1671)])}catch(o){e.Kjkzm(e[t(1657)],e[t(490)])?(this._messageQueue[t(613)](_0x20601e),this[t(1979)](n[t(1087)],_0x2d4d37)):console[t(1074)](o)}}async keys(){let t=r;return await this[t(533)](),this[t(1750)]?.[t(535)+"ys"](this[t(1671)])}async[r(1586)](){let t=r;return await this._init(),this[t(1750)]?.[t(1586)](this[t(1671)])}async[r(1952)](){let t=r;try{e[t(908)](e.DLycM,e.TkWsm)?RqMkLS[t(1444)](_0x5df9d2,_0x4d7d56)&&_0x58758f[t(1142)](_0xfe7068,_0x3eb132):(this[t(1750)]?.[t(1700)](),this[t(1750)]=void 0)}catch(n){console.log(n)}}get isReady(){let t=r;try{return e[t(1096)](e[t(1450)],e[t(643)])?!!this[t(1750)]:new _0x5e71ca(_0x1f3099[0]|e[t(1500)](_0x1b6c10[1],8)|e[t(1170)](_0x4a5886[2],16)|_0x364a72[3]<<24,e[t(1902)](_0x2a68da[4],e[t(1500)](_0x1b3a32[5],8))|e[t(1533)](_0x291115[6],16)|e[t(973)](_0x4e0e1a[7],24),_0x5f7a40)}catch(n){return console[t(1074)](n),!1}}}class ya{constructor(t,n){let o=r;this[o(680)]=t,this[o(1959)]=n,this[o(1750)]=localStorage}async[r(605)](){}get[r(1288)](){return r(1132)+"_"+this._DBName}async[r(750)](t){let n=r,o=this[n(1750)].getItem(this._prefix);return JSON.parse(e[n(1282)](o,"{}"))[t]}async[r(1142)](t,n){let o=r,x=this[o(1750)][o(1095)](this[o(1288)]),h=JSON[o(1938)](e[o(1536)](x,"{}"));return h[n||t[this[o(1959)]]]=t,this[o(1750)][o(1447)](this[o(1288)],JSON[o(619)+"y"](h)),n||t[this._pathKey]}async[r(691)](t){let n=r,o=this[n(1750)][n(1095)](this._prefix),x=JSON.parse(e.WzSvd(o,"{}"));return x[t]=void 0,this[n(1750)].setItem(this[n(1288)],JSON.stringify(x))}async[r(1072)](){let t=r,n={OuXQT:function(o,x){return e[D(1985)](o,x)},SkZwP:e[t(1716)],tmEfZ:t(550)+"e_success",HSDAh:function(o,x,h){return e[t(1644)](o,x,h)}};if(e[t(660)](e[t(626)],t(705)))return this[t(1750)].clear();{let o={ePljV:function(g,m){return g(m)},LNHIU:"success",spAIS:n[t(1837)],qgraG:n[t(1828)]};this[t(1152)+t(1269)](),this[t(1227)+"gTimeoutId"]=n[t(1632)](_0x321341,this[t(1422)][t(1030)](this),this[t(577)]["pingInte"+t(1679)]);let x=()=>{let g=t;o[g(704)](_0x1e09fc,o.LNHIU),this[g(1424)](o[g(1942)],x),this[g(1424)](o[g(1093)],h)},h=()=>{let g=t;n[g(606)](_0x30ca0e,g(1285)),this.off(g(550)+g(927)+"s",x),this.off(n.SkZwP,h)};this.on(n.tmEfZ,x),this.on(n[t(1828)],h),this[t(1422)]()}}async[r(709)](){let t=r;if(e[t(926)](e[t(1115)],e[t(1203)])){let n=this[t(1750)][t(1095)](this[t(1288)]),o=JSON.parse(n||"{}");return Object.keys(o)}else this[t(1750)]?.del(_0x55dd00[t(1784)+"id"])}async[r(1586)](){let t=r,n=this[t(1750)][t(1095)](this[t(1288)]),o=JSON.parse(e[t(1118)](n,"{}"));return Object.values(o)}[r(1952)](){return Promise[r(1572)]()}get isReady(){return!!this[r(1750)]}}class ba{constructor(t,n){let o=r,x={avIvH:function(h,g){return e[D(739)](h,g)},RGDCS:function(h,g){return e[D(624)](h,g)}};if(e.sFliG(e[o(1923)],e[o(1923)]))return XnKdqg[o(1972)](this[o(1502)+"ndex"],this[o(804)+"s"].length)?!0:XnKdqg[o(1576)](this[o(1793)+o(1801)+"riesCount"],this.maxRetries);this[o(680)]=t,this[o(1959)]=n,this._qosDB=Ye?tt:kt?wx:null}async[r(605)](){}get[r(1288)](){let t=r;return t(1132)+"_"+this[t(680)]}async[r(750)](t){let n=r,o=this._qosDB["getStora"+n(637)](this[n(1288)]);return JSON.parse(e[n(744)](o,"{}"))[t]}async[r(1142)](t,n){let o=r,x=this[o(1750)][o(1781)+o(637)](this._prefix),h=JSON.parse(x||"{}");return h[n||t[this._pathKey]]=t,this[o(1750)][o(1436)+o(637)](this[o(1288)],JSON[o(619)+"y"](h)),n||t[this[o(1959)]]}async[r(691)](t){let n=r,o=this._qosDB[n(1781)+n(637)](this[n(1288)]),x=JSON.parse(e[n(1912)](o,"{}"));return x[t]=void 0,this._qosDB["setStora"+n(637)](this[n(1288)],JSON[n(619)+"y"](x))}async clear(){let t=r,n={iovpA:function(o,x){return e[D(1270)](o,x)},MorkQ:function(o,x){return e[D(1551)](o,x)},TOEXD:function(o,x){return e.IBWez(o,x)},VEmlZ:function(o,x){return e[D(1280)](o,x)},zBBOP:function(o,x){return e[D(1581)](o,x)},ktGTr:function(o,x){return o<<x}};return e[t(898)]===e[t(1510)]?new _0x578f80(NNLNfd.iovpA(NNLNfd[t(760)](NNLNfd.iovpA(NNLNfd[t(1520)](_0x5180e0[4],24),_0x26ae41[5]<<16),_0x480941[6]<<8),_0x38519d[7]),NNLNfd[t(746)](NNLNfd.VEmlZ(NNLNfd[t(488)](_0x1bf539[0],24),NNLNfd[t(488)](_0x17f528[1],16))|NNLNfd[t(1516)](_0x3765c8[2],8),_0x342c20[3]),_0x4c29e9):this[t(1750)][t(884)+"rageSync"]()}async[r(709)](){let t=r,n=this._qosDB[t(1781)+t(636)+"nc"](this[t(1288)]),o=JSON[t(1938)](n||"{}");return Object[t(709)](o)}async getAll(){let t=r,n=this[t(1750)][t(1781)+"geInfoSync"](this[t(1288)]),o=JSON[t(1938)](e[t(1045)](n,"{}"));return Object[t(1049)](o)}[r(1952)](){return Promise[r(1572)]()}get[r(892)](){let t=r,n={oMQDJ:function(o,x,h){return e[D(540)](o,x,h)}};if(e[t(1860)]===e[t(847)]){let o=n[t(1007)](_0x586dea,t(1024),{message:_0x46afb2[t(1706)],code:_0x51b82d[t(1741)+t(935)],error:_0x4ad276});this[t(1618)+t(1732)+t(906)](o)}else return!!this[t(1750)]}}function Cs(s,t){let n=r;if(e[n(1164)](Ye,Ye))return new ba(s,t);if(e[n(1164)](at,Pt)&&e.KhTrd("undefined",typeof indexedDB))return new wa(s,t);if(e.HyLEq(at,Pt)&&e.jdfIW(e[n(822)],typeof localStorage))return new ya(s,t);throw new Error(e[n(1354)])}class va{constructor(){let t=r;this[t(1397)+t(1906)+"Id"]=null,this[t(1397)+"l"]=36e5,this[t(1750)]=e[t(668)](Cs,e.RbEgY,e[t(910)])}async["_interva"+r(1893)](){let t=r;e[t(818)](clearInterval,this[t(1397)+t(1906)+"Id"]),this[t(1397)+"lTimeoutId"]=setInterval(()=>{let n=t;this[n(565)+n(1362)]()},this._interval)}async openDB(){let t=r;await this[t(1750)][t(605)]()[t(495)](()=>{let n=t;this[n(1397)+n(1893)]()})}async["flushExp"+r(1362)](){let t=r;(await this[t(1750)]?.[t(1586)]()||[])[t(1195)](({timestamp:x})=>x<Date[t(1629)]())[t(1146)](x=>{let h=t;this._qosDB?.[h(691)](x[h(1784)+"id"])})}async[r(691)](t){let n=r;return this._qosDB?.[n(691)](t)}async[r(1142)](t,n){let o=r;return this._qosDB?.[o(1142)]({message_id:t,timestamp:n})}async get(t){let n=r;return this[n(1750)]?.[n(750)](t)}async[r(1952)](){let t=r;e[t(650)](clearInterval,this[t(1397)+t(1906)+"Id"]),await this[t(1750)]?.closeDB()}get[r(892)](){let t=r;return this[t(1750)]?.[t(892)]}}function cr(s){let t=r,n=!!this[t(577)][t(712)+"S"];if(!n)return{enabled:n,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=e.JHlqK(Ke,s[t(1706)].headers,e.GbIPn,"2"),x=o&&Ke(s[t(1706)][t(976)],e.rBNyV,"1"),h=o&&Ke(s[t(1706)].headers,e[t(1324)],"1"),g=h?e[t(887)](xt,s[t(1706)][t(976)],e[t(690)])?.[t(865)](",")[t(1195)](Boolean)||[]:[];return{enabled:n,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:h,ackMsgIds:g}}async function As(){let s=r;if(s(840)===s(845)){let{initReconnectInterval:t,maxReconnectInterval:n,reconnectIntervalGrowFactor:o}=this[s(577)],x=e[s(559)](t,_0x24b287[s(1753)](o,_0x5c2a98-1));return e[s(1309)](x,n)?n:x}else return this[s(676)+s(1408)]||(this[s(676)+s(1408)]=new va),this[s(676)+s(1408)][s(892)]||await this[s(676)+"ger"][s(605)](),this[s(676)+s(1408)]}async function Sa(s,t){let n=r,o={OhzXI:function(f,y){return f<y},ImMXO:function(f,y){return e.Kjkzm(f,y)}},{enableAutoAck:x}=this[n(577)],h=e[n(829)](Ke,s[n(1706)][n(976)],e[n(844)],"1"),g=e[n(534)](Ke,s[n(1706)][n(976)],e.yvxSq,"1"),m=cr[n(1903)](this,s);if(e[n(1140)](x,h))if(e[n(893)](e[n(1380)],e[n(1380)])){let{SeqID:f,LogID:y,service:b,LogIDNew:A,method:I}=s.message;this[n(717)]({SeqID:f,LogID:y,LogIDNew:A,service:b,method:I,headers:[{key:n(1065),value:"1"},{key:e[n(1775)],value:e[n(1421)](A,"")},{key:n(1443),value:"0"}]})}else{let f=this._listeners[_0x2c39e6];if(f)for(let y=0;dWfcil[n(1836)](y,f.length);)dWfcil.ImMXO(f[y].fn,_0x2427b1)?f[n(1235)](y,1):++y}g&&!m[n(509)]&&this[n(1618)+"hAckMess"+n(1113)](s),t()}async function Ea(s,t){let n=r,o={JNBpq:function(x,h){return e[D(1892)](x,h)},tLeGw:function(x,h){return e[D(989)](x,h)},XwaPa:function(x,h){return x+h},nEecB:function(x,h){return e[D(1677)](x,h)},LMfdn:function(x,h){return e[D(639)](x,h)}};if(e.RdQwm(e[n(797)],e[n(797)])){let x=new _0x3c4fed(o[n(633)](o[n(1310)](o.tLeGw(_0x3c16c7[o.XwaPa(_0x12d2bf,4)]<<24,o[n(956)](_0x33d9c8[o[n(1207)](_0x5b3853,5)],16)),o.nEecB(_0x4751fb[o[n(1207)](_0x430aed,6)],8)),_0x4ee911[_0x20d582+7]),o.JNBpq(o[n(1582)](o.tLeGw(_0x430a13[o[n(1207)](_0x584dcd,0)]<<24,o.nEecB(_0x35b819[o.XwaPa(_0x4220cc,1)],16)),o[n(956)](_0x59d639[_0x2a8a2b+2],8)),_0x5727ea[_0x2708bc+3]),!0);return _0x20a0c0+=8,{value:x,offset:o[n(1207)](_0x247ba2,8)}}else this[n(1979)](e[n(652)],s[n(1706)]),e.vkkFl(t)}async function Ca(s,t){let n=r,o=e[n(720)](as,await e[n(1577)](Es,s[n(1231)]));try{if(e[n(1444)](o.payload,Uint8Array)){let x=this[n(577)][n(1260)+n(1327)]instanceof Object?{force:!!this[n(577)][n(1260)+n(1327)][n(1145)],encoding:this[n(577)]["payloadE"+n(1327)][n(1894)]?this._options[n(1260)+n(1327)].encoding[n(1220)](/\s/g,"")[n(1222)+n(1934)]():""}:{force:!1,encoding:this[n(577)][n(1260)+n(1327)]?this[n(577)][n(1260)+n(1327)][n(1220)](/\s/g,"")[n(1222)+n(1934)]():""},h=o["payloadE"+n(1327)]?o[n(1260)+n(1327)][n(1220)](/\s/g,"")[n(1222)+"ase"]():"",g=e[n(830)](this[n(577)][n(1182)+n(1961)],Object)?{force:!!this[n(577)]["payloadT"+n(1961)][n(1145)],type:this[n(577)][n(1182)+n(1961)][n(728)]?this._options[n(1182)+"ype"][n(728)][n(1220)](/\s/g,"")[n(1222)+"ase"]():""}:{force:!1,type:this[n(577)][n(1182)+n(1961)]?this._options[n(1182)+n(1961)][n(1220)](/\s/g,"")[n(1222)+"ase"]():""},m=o["payloadT"+n(1961)]?o[n(1182)+n(1961)][n(1220)](/\s/g,"")[n(1222)+n(1934)]():"",f=g.force?g[n(728)]:m||g[n(728)],y=x[n(1145)]?x.encoding:h||x[n(1894)],b=[e[n(1744)],e[n(772)],e.ZkNfK,e[n(1025)]],A=["none_none",e[n(1120)]];this._options["enableTransformT"+n(1550)+"ad"]&&b.includes(f)&&(!y||A[n(1028)](y))?o[n(1398)+n(1776)]=Ss(o[n(1293)],0,o[n(1293)][n(1334)+"th"]):o[n(1398)+n(1776)]=""}else o[n(1398)+n(1776)]=""}catch(x){o[n(1398)+n(1776)]="",console.log(x)}s[n(1706)]=o,e[n(689)](t)}function Aa(s,t,n){let o=r,x={ICtfC:function(y,b){return e.zwFSQ(y,b)},ppvuG:e[o(1623)],Vnurn:function(y,b){return e[o(1433)](y,b)},qkbYy:function(y,b){return e[o(1593)](y,b)},DBHGk:function(y,b){return e[o(1388)](y,b)},VGuqO:function(y,b){return y&b},MnQEg:function(y,b){return e[o(1281)](y,b)},pJLXD:function(y,b){return e[o(1680)](y,b)}},h=e.qLbdi(n,8192),g=e[o(1376)](h,1),m=null,f=h;return function(y){let b=o;if(x.ICtfC(x.ppvuG,"ogjeT")){if(x[b(1275)](y,1)||x.qkbYy(y,g))return x[b(1088)](s,y);f+y>h&&(m=s(h),f=0);let A=t.call(m,f,f+=y);return x[b(631)](7,f)&&(f=x[b(1881)](x.pJLXD(7,f),1)),A}else _0x1da048[b(1369)+b(1496)+"e"](_0x55cda3,{keyPath:_0x48c563})}}let ka=4294967295;function Pa(s,t,n){let o=r;return e[o(1834)](RangeError,e[o(1128)](e[o(1962)](e.TCBFI(e[o(1771)],s),e[o(1777)]),e[o(1164)](t,1))+o(1778)+n)}function Da(s,t,n){let o=r;if(e[o(1309)](n,ka))throw new Error(e[o(1311)]);let x=3;for(;e[o(1116)](x,0);){if(e[o(1091)]===e[o(1299)])return this[o(1750)]?.[o(892)];{let h=e[o(1863)](255,n);e.JHlqK(fr,h,s,e[o(1962)](t,x)),n>>>=8,x--}}return e[o(790)](t,4)}function Ta(s,t){let n=r,o=0,x=t,h=e.SFgIO(t,4);for(;e[n(1846)](x,h);){let{value:g,offset:m}=e[n(1406)](ur,s,x);x=m,o=e[n(710)](o<<8,0),o+=g}return{value:o,offset:h}}function Ia(s,t,n){let o=r,x=e[o(1226)][o(865)]("|"),h=0;for(;;){switch(x[h++]){case"0":if(s[o(1931)]<40)return e[o(1214)](ar,s,t,n)+n;continue;case"1":return e.kLLfx(e[o(1922)](ar,s,t,n),n);case"2":if(t[o(1234)+"e"])return e[o(1162)](t[o(1234)+"e"](s,n),n);continue;case"3":if(t[o(1492)])return t.write(s,n)+n;continue;case"4":if(!s)return n;continue}break}}function La(s,t){let n=r,o=new B(e[n(1892)](e.EfFHB(s[e.izQwB(t,4)]<<24|e[n(706)](s[t+5],16),e[n(1549)](s[e.nlBcY(t,6)],8)),s[e[n(1075)](t,7)]),e[n(682)](e[n(672)](e[n(732)](e[n(1668)](s[e[n(1464)](t,0)],24),e[n(1081)](s[t+1],16)),s[e[n(1410)](t,2)]<<8),s[e[n(1160)](t,3)]),!0);return t+=8,{value:o,offset:e.xYGvc(t,8)}}function Na(s,t,n){let o=r;if(e[o(1898)](e[o(1295)],e[o(1295)])){let x=s.low,h=s[o(1562)];return t[n]=h>>>24,t[e[o(1962)](n,1)]=e[o(778)](e[o(1823)](h,16),255),t[e[o(685)](n,2)]=e[o(1932)](e[o(710)](h,8),255),t[e[o(1253)](n,3)]=255&h,t[e[o(1258)](n,4)]=e[o(993)](x,24),t[e[o(552)](n,5)]=e[o(783)](e.kGRNo(x,16),255),t[e.Ulnin(n,6)]=e.VvzpB(e[o(569)](x,8),255),t[e[o(930)](n,7)]=255&x,n+=8,n}else _0x3d55cc(),RqMkLS[o(1051)](_0x5a5127)}function ur(s,t){let n=r;return s[n(1254)+"8"]?{value:s[n(1254)+"8"](t),offset:t+1}:{value:e.Utgyz(255,s[t]),offset:t+1}}function fr(s,t,n){let o=r;return t[o(1459)+"t8"]?t[o(1459)+"t8"](s,n):t[n]=e[o(1697)](255,s),e[o(552)](n,1)}let Ra=function(s){return new Uint8Array(s)},Ma=e.utqCz(e[r(822)],typeof Buffer)?Buffer.allocUnsafe:e[r(588)](Aa,Ra,Uint8Array[r(1800)+"e"][r(666)]),Oa=16,dr=32;function Ba(s){let t=r;if(e[t(1739)](e[t(1029)],e[t(1029)])){if(RqMkLS[t(1435)](_0x721bbf,RqMkLS[t(1515)]))return _0x19d4fd[t(750)](_0x3596a0);if(_0x3c1145===t(1608)+t(1097))return _0x3b75a0[t(1608)+t(1097)]||_0x591d55.get(_0x2511f5);if(_0x92e76c===t(1157))return _0x21f2cd[t(1608)+t(1097)][1]?void 0:_0x15b2c2["objectSt"+t(801)](_0x239fde["objectSt"+t(1097)][0])}else{let n=0,o={};for(let x=0;e.VGLOB(x,s.length);x++)o[s[x][t(1488)+t(1202)]]=e[t(688)](vs,s[x].cursor_name),n+=e.Tsdny(14,o[s[x][t(1488)+"ame"]]);return[n,o]}}function ks(s,t,n){let o=r,x={eFleq:o(1032)+o(1237),ZlLCF:e[o(1662)],osZhx:e[o(1646)],ISvdA:function(y,b,A,I){return e[o(1102)](y,b,A,I)},CbVGH:e[o(1875)],kAork:e.sULbG,biusS:function(y,b,A,I){return e[o(829)](y,b,A,I)}},[h,g]=e.VzEfH(Ba,s),m=e[o(688)](Ma,h),f=0;return s[o(1146)](y=>{let b=o,A=("9|7|2|4|"+b(1506)+b(779))[b(865)]("|"),I=0;for(;;){switch(A[I++]){case"0":console[b(1074)](b(1237),f);continue;case"1":console[b(1074)](x[b(1605)],f);continue;case"2":console.log(x[b(1615)],f);continue;case"3":console.log(x.osZhx,f);continue;case"4":f=x[b(1841)](Da,m,f,y[b(1143)]||0);continue;case"5":f=x.ISvdA(Na,B[b(1590)+"er"](y.cursor||t),m,f);continue;case"6":console.log(x[b(1782)],f);continue;case"7":f=x[b(1841)](fr,0,m,f);continue;case"8":f=fr(g[y[b(1488)+b(1202)]],m,f);continue;case"9":console[b(1074)](x[b(1811)],y,y[b(1143)]);continue;case"10":f=x.biusS(Ia,y["cursor_n"+b(1202)],m,f);continue}break}}),{frameType:dr,headers:[{key:"cursor_f"+o(1858),value:n}],payload:m}}function za(s){let t=r,n=0,o=[];for(;e.esRWk(n,s.byteLength);){let{offset:x}=e.NlUWE(ur,s,n);n=x;let h={cursor_name:"",cursor:0,service:0},{value:g,offset:m}=e[t(802)](Ta,s,n);h[t(1143)]=g,n=m;let{value:f,offset:y}=e.aThyM(ur,s,n);n=y,h[t(1488)+t(1202)]=e.lyZUH(Ss,s,n,e.dvVde(n,f)),n+=f;let{value:b,offset:A}=La(s,n);h[t(954)]=b[t(1005)](),n=A,o[t(613)](h)}return o}function qa(){let s=r;return{frameType:dr,headers:[{key:e[s(1867)],value:s(853)+s(1301)}],payload:void 0}}class Fa{constructor(t,n,o){let x=r;if(e[x(1501)](x(538),"GWzFX"))this["_cursorN"+x(1206)]=t,this[x(1587)+x(1159)]=n,this[x(1059)+x(483)]=o,this._qosDB=Cs(this[x(1530)+x(1206)],e[x(817)]);else{let h=e[x(724)](_0x13c09d,_0x431fb0);this[x(795)]&&e[x(1289)](this[x(795)][x(1913)+"te"],this[x(1512)])&&(this[x(795)]&&this[x(795)][x(1407)](h),this[x(1979)](x(741),_0x41bfe9))}}async[r(605)](){let t=r;await this[t(1750)][t(605)]()}async[r(1848)+"rs"](){let t=r;if(!this[t(1750)].isReady)return;let n=this[t(1059)+t(483)],o=await this._qosDB[t(1586)]();switch(console[t(1074)](e.kIwpv,o),n){case e[t(657)]:return o&&o[t(1931)]?ks(o,0,this[t(1587)+t(1159)]):void 0;case e[t(503)]:return;case t(765):return o&&o.length?e.GhHKl(ks,o,0,this[t(1587)+t(1159)]):qa()}}async set(t,n,o){let x=r;return console[x(1074)](e[x(1971)],t,n,o),this[x(1750)].set({cursor_name:t,cursor:n,service:o})}async[r(886)+"rs"](t){let n=r,o=e[n(724)](za,t);for(let x of o)console[n(1074)](e[n(1199)],o),await this[n(1750)][n(1142)](x)}async[r(750)](t){let n=r;return(await this[n(1750)][n(750)](t))?.[n(954)]}async[r(1952)](){await this[r(1750)].closeDB()}["updateCu"+r(1925)+r(1498)](t){let n=r;this[n(1587)+n(1159)]=t}get[r(892)](){let t=r;return this[t(1750)][t(892)]}}let Ua=e[r(860)];async function Ps(s){let t=r;if(!this[t(577)].enableQoS)return null;let{aID:n,fpID:o,messageStrategy:x}=this[t(577)],h=s||Ua;try{return this[t(1751)+t(1612)]?s&&this[t(1751)+"anager"][t(1431)+t(1925)+t(1498)](s):this["_cursorM"+t(1612)]=new Fa(o+"_"+n+"_"+h,h,x),this["_cursorM"+t(1612)][t(892)]||await this[t(1751)+t(1612)].openDB(),this["_cursorM"+t(1612)]}catch{if(e[t(646)]==="PRjXl"){let g=this[t(1685)+t(1585)]?.[t(1865)+t(602)+"nt"]();this[t(1618)+t(918)+"ent"](_0x1f160b(t(1700),{code:1006,reason:t(1682)+g+(t(1653)+t(1229)+t(1077)+t(1901)),wasClean:!0}))}else return null}}async function Ha(s,t){let n=r,o=e[n(725)](Ke,s[n(1706)][n(976)],n(1385),"-1"),x=Ke(s[n(1706)][n(976)],e[n(878)],"1"),h=e[n(1149)](xt,s.message[n(976)],e[n(1420)]),g=e[n(818)](Number,xt(s[n(1706)].headers,e[n(953)]))||0,m=cr.call(this,s),f=e[n(859)](Ke,s[n(1706)][n(976)],e[n(607)],"2"),y=e[n(1036)](xt,s[n(1706)][n(976)],e[n(870)]),b=e[n(1619)](Number,xt(s[n(1706)][n(976)],e[n(1752)]));if(m[n(509)])return e[n(1749)](t);let A=m[n(632)+n(1249)]?await As[n(1903)](this):null;if(e[n(734)](s[n(1706)][n(1143)],0)&&x&&!o||s[n(1706)][n(1143)]>0)if(e[n(1257)]!==e[n(1135)]){if(h&&m[n(632)+"sage"]&&A)return!!!await A[n(750)](h)&&(this[n(1618)+n(581)+n(1714)](s),await A.set(h,Date[n(1629)]()+g)),e[n(1051)](t);if(f){let I=await Ps[n(1903)](this);if(!I)return this[n(1618)+n(581)+"Event"](s),t();let L=await I[n(750)](y)??-1;if(e[n(1103)](L,b))this["_dispatc"+n(581)+n(1714)](s),I.set(y,b,s[n(1706)][n(1143)]);else throw new Error("recevied"+n(1879)+n(531)+b+(n(764)+n(679)+n(1976)+"r ")+L);return e[n(1673)](t)}return this[n(1618)+"hMessage"+n(1714)](s),e[n(689)](t)}else try{e[n(534)](_0x26ed12,this,_0x5ab292,[_0x2005df,_0x318127,_0x233988])}catch(I){let L=e[n(1780)](_0x33debb,e[n(590)],{message:I[n(1706)],code:_0x3f4fe3[n(871)+"OR"],error:I});this[n(1618)+"hErrorEv"+n(906)](L)}}async function Ka(s,t){let n=r,o=cr[n(1903)](this,s);if(!o[n(632)+n(1249)])return e[n(1592)](t);let x=await As[n(1903)](this);if(o["isAckCle"+n(661)+n(938)]&&o[n(1053)+"s"][n(1931)])for(let h of o[n(1053)+"s"])await x[n(691)](h);e[n(1386)](t)}async function Ga(s,t){let n=r,o=e.UbEsJ(s[n(1706)][n(1349)+"e"],Oa),x=e.fOhqQ(s.message[n(1349)+"e"],dr);if(!o&&!x)return e[n(1386)](t);let h=e[n(1857)](xt,s[n(1706)][n(976)],n(1194)+n(1858));if(!h)return e[n(1051)](t);let g=await Ps[n(1903)](this,h);if(!g)return e[n(582)](t);if(o){let m=await g[n(1848)+"rs"](),f={frameType:m?.[n(1349)+"e"],SeqID:B.fromNumber(this[n(1353)]++),LogID:B[n(1590)+"er"](this[n(577)]["logIDGen"+n(1467)]()),service:9e3,method:5,headers:m?.[n(976)],payload:m?.payload},y=e[n(1795)](C,f);this[n(795)]&&this[n(795)].readyState&&this._ws[n(1407)](y)}if(x){let m=s[n(1706)][n(1293)];m&&g[n(886)+"rs"](m)}}let ja=async function(s,t){let n=r;this[n(1949)]=!1,clearTimeout(this[n(1575)+n(1351)+n(855)]),e.cBGJv(t)},Wa=async function(s,t){let n=r,o={eQSBs:e[n(991)]};if(!this[n(795)]||this[n(795)].readyState!==this.OPEN)return e[n(1877)](t);let{pingInterval:x}=this[n(577)];this[n(1685)+n(1585)]?.[n(1546)+n(1099)+"fig"]();for(let g=0;e[n(1544)](g,this[n(1059)+n(815)][n(1931)]);g++){let m=this[n(1059)+n(815)][g];if(this[n(795)][n(1913)+"te"]===this[n(1512)]&&e[n(848)](null,m))if(e[n(934)](e[n(1725)],"UbabE"))this[n(795)]&&this[n(795)][n(1407)](m),this[n(1059)+"Queue"][g]=null;else return{frameType:_0x5c0f3d,headers:[{key:n(1194)+n(1858),value:KuVjXo[n(1067)]}],payload:void 0};else break}this[n(1059)+"Queue"]=this[n(1059)+n(815)][n(1195)](g=>!!g),this[n(1227)+n(487)+"Id"]=e[n(1404)](setTimeout,()=>this[n(1422)](),x),this[n(1618)+n(957)+"nt"](s),this[n(1814)+"er"]&&this._ws&&(this[n(795)].binaryType=this[n(1794)+n(1961)]);let h=this[n(1685)+n(1585)]?.[n(1865)+n(602)+"nt"]();this[n(1979)](n(1119)+h+" success"),e[n(1571)](t)},Ja=async function(s,t){let n=r,o=this[n(1685)+n(1585)]?.[n(1865)+n(602)+"nt"]();this._debug(n(1119)+o),t()};class Va extends or{constructor(t){let n=r,o={GXQcn:function(m,f,y){return e[D(1579)](m,f,y)},zCuYX:e[n(590)],ZMLwa:function(m,f,y){return m(f,y)},rGAzq:function(m,f){return e.oZsfb(m,f)},TjunW:function(m,f,y){return e.aThyM(m,f,y)},nxSsJ:function(m,f){return e[n(1566)](m,f)},dkgoD:e.DOSoR,ByVNR:n(990),xANHb:function(m,f){return e[n(1358)](m,f)},gOeha:function(m,f,y){return e[n(1780)](m,f,y)},SZvoM:e[n(567)],JEyGY:e.kZgEj,ehYML:function(m,f){return e[n(1046)](m,f)},bZlpI:function(m,f,y){return m(f,y)},ujiqH:function(m,f){return e.JymzL(m,f)},gCAuI:e[n(1515)],aBsRj:e[n(1183)]};super(),this["_miniNav"+n(486)+"line"]=!0,this._isBrowser=at,this[n(1200)]=ua,this[n(1472)+"T"]=Ye,this[n(1156)+"X"]=kt,this[n(816)+"r"]=Pt,this[n(1059)+n(815)]=[],this[n(1685)+"tManager"]=null,this[n(1322)+n(1411)]=!1,this[n(1794)+n(1961)]=e[n(692)],this[n(1575)+n(1290)]=!1,this[n(1575)+n(1351)+"utId"]=null,this["_reconne"+n(586)+n(997)]=null,this[n(1227)+n(487)+"Id"]=null,this[n(1353)]=0,this[n(1949)]=!1,this[n(1792)]="",this[n(676)+n(1408)]=null,this[n(1751)+n(1612)]=null,this[n(1238)+n(960)]=null,this[n(627)+"ls"]=e[n(1953)],this[n(916)]=3,this[n(1139)+"NG"]=0,this[n(1512)]=1,this[n(1636)]=2,this[n(849)]=m=>{let f=n;try{bs(this,m,[ja,Wa,Ja])}catch(y){let b=o[f(1312)](he,o[f(1809)],{message:y.message,code:He[f(871)+"OR"],error:y});this[f(1618)+f(1732)+f(906)](b)}},this[n(549)+"ge"]=async m=>{let f=n,{pingInterval:y,pingFrequency:b}=this[f(577)];if((m[f(1231)]==="hi"&&f(591)===b||e[f(811)](f(812),b))&&(this[f(1152)+f(1269)](),this[f(967)](e[f(1080)],e[f(1158)]),this[f(1227)+f(487)+"Id"]=e[f(515)](setTimeout,this[f(1422)][f(1030)](this),y)),!e.pTBnK("hi",m[f(1231)]))try{e[f(1439)](bs,this,m,[Ca,Sa,Ka,Ga,Ha,Ea])}catch(A){let I=e[f(1272)](he,f(1024),{message:A.message,code:He[f(1741)+f(935)],error:A});this[f(1618)+f(1732)+f(906)](I)}},this[n(1511)]=m=>{let f=n,y=this._endpointManager?.[f(758)+f(1296)+"es"](),b=this[f(1685)+f(1585)]?.[f(1865)+f(602)+"nt"]();if(y&&!m[f(1706)]){let A=f(1682)+b+(f(1123)+f(1418)+"es reached");this[f(1618)+f(1732)+f(906)](o.ZMLwa(he,o[f(1809)],{message:A,code:He[f(1889)+f(1543)+"R"],error:m}));return}this[f(795)]&&o[f(1678)](this._ws[f(1913)+"te"],this[f(1512)])&&this[f(1634)+f(1273)](),this[f(1618)+"hErrorEvent"](o[f(702)](he,o[f(1809)],{message:m[f(1706)],code:He[f(727)+f(1294)],error:m}))},this._onClose=async m=>{let f=n;this["_clearTi"+f(1090)](),this["_clearPi"+f(1269)](),this[f(1372)+f(1508)+"rs"](),this[f(795)]=null,this[f(1575)+f(1290)]=!1;let y=this[f(1685)+f(1585)]?.[f(758)+f(1296)+"es"]();if(!y&&this[f(1643)+"orOnline"]()&&!this["_readyCl"+f(1411)])if(o[f(834)](o[f(767)],o[f(1307)])){let b=this[f(1685)+f(1585)]?.[f(1865)+f(602)+"nt"](),A=this[f(577)]["reconnec"+f(1262)+"ptor"](m[f(1385)],m[f(1724)]);this[f(1618)+f(918)+f(906)](_e("close",{code:1006,reason:m[f(1724)]||f(1221)+f(899)+f(1640)+f(980)+f(1181)+"ame: "+b,willReconnect:A})),A&&this[f(1575)]();return}else return _0x522f38[f(1572)]();if(o[f(1607)](1e3,m.code)&&this[f(1322)+f(1411)]){this[f(1618)+f(918)+f(906)](o.gOeha(_e,o[f(1112)],{code:1e3,reason:o.JEyGY})),this[f(1685)+"tManager"]?.[f(1546)+"pointConfig"](),this["_pingLos"+f(960)]?.[f(1001)+f(1926)]();return}if(m[f(1385)]!==1e3&&y){let b=this[f(1685)+"tManager"]?.["getCurre"+f(602)+"nt"](),A=m[f(1724)];A||(A=await o[f(1017)](ma,this[f(1792)])),A=f(1221)+f(899)+f(978)+A+(f(641)+f(1941))+b+(f(1229)+f(1077)+f(1901)),this["_dispatchCloseEv"+f(906)](o.bZlpI(_e,o[f(1112)],{code:m[f(1385)],reason:A}));let I=f(1682)+b+(f(1123)+f(1418)+f(1384)+"ed");this[f(1618)+"hErrorEv"+f(906)](he(o[f(1809)],{message:I,code:He[f(1889)+f(1543)+"R"]})),this[f(1685)+f(1585)]?.[f(1546)+f(1099)+f(1489)](),this[f(1238)+f(960)]?.[f(1001)+"nter"]();return}if(m[f(1385)]!==1e3&&!m[f(1724)]){let b=this[f(1685)+f(1585)]?.[f(1865)+"ntEndpoint"]();this[f(1618)+f(918)+f(906)](o.GXQcn(_e,o[f(1112)],{code:m[f(1385)],reason:f(1221)+f(899)+"d, unkno"+f(980)+"n, hostname: "+b})),this[f(1685)+f(1585)]?.["resetEndpointCon"+f(1489)](),this[f(1238)+f(960)]?.[f(1001)+f(1926)]();return}this[f(1618)+"hCloseEv"+f(906)](m),this[f(1685)+f(1585)]?.[f(1546)+f(1099)+f(1489)](),this[f(1238)+"sCounter"]?.[f(1001)+f(1926)]()},this[n(1471)]=null,this[n(616)]=null,this.onmessage=null,this.onopen=null,this[n(610)+n(1945)]=null,this["onReceiv"+n(1259)]=null,this[n(1633)+n(1038)+n(1022)+"ct"]=null,this._handleOnLine=this[n(722)+"nLine"][n(1030)](this),this[n(722)+n(1789)]=this[n(722)+n(1789)][n(1030)](this),this[n(1692)+n(1106)]=this["_handleP"+n(1106)][n(1030)](this),this[n(1692)+n(1414)]=this[n(1692)+"ageShow"][n(1030)](this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[n(774)](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(1412)],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:x,ws:h}=t,g=Array[n(1108)](x)?x:e[n(1110)](e[n(1025)],typeof x)?[x]:[];if(!g||g[n(1931)]===0)throw new Error(n(576)+n(1825)+n(1083));if(!la(h))throw new Error(e[n(1570)]);if(Object[n(773)](this._options,t),this[n(1685)+"tManager"]=new ys(g,this[n(577)][n(492)+"es"]),this["_pingLos"+n(960)]=new pa(this._options[n(1e3)+n(1565)]),this._options[n(882)+n(1223)]){if(e[n(660)](e[n(714)],e[n(618)]))return VEgxxJ[n(1908)](_0x302796,_0x100d95)&&(VEgxxJ[n(1678)](_0x42f018,VEgxxJ[n(1085)])||VEgxxJ[n(1678)](_0x47712d,VEgxxJ[n(1134)]))?!0:_0x24a45e in _0x1c9798;this[n(1949)]=!0,this._connect()}this[n(577)]["listenNe"+n(939)+n(911)]&&(this._isMiniTT||this[n(1156)+"X"]?this[n(1802)+n(1233)+n(1978)]():this[n(1814)+"er"]&&this["_initGlo"+n(1428)+n(914)]())}[r(722)+"nLine"](){let t=r;this[t(577)]["disableA"+t(1766)+"nect"]||this[t(1322)+t(1411)]||this[t(922)+t(1945)]()}[r(722)+r(1789)](){let t=r;this["_destroy"+t(1008)+"t"]();let n=e[t(707)](ir,t(1663)+"t",{message:t(1742)+t(1305)+" reconnect"});this["onStopIm"+t(1038)+t(1022)+"ct"]&&this[t(1633)+t(1038)+t(1022)+"ct"](n)}[r(919)+"balEvent"+r(914)](){let t=r;this[t(1814)+"er"]&&window[t(1642)+t(914)](e[t(1042)],this["_handleO"+t(1287)]),this[t(1814)+"er"]&&window[t(1642)+"Listener"](t(1150),this[t(722)+t(1789)]),this[t(1814)+"er"]&&window["addEvent"+t(914)](e[t(1591)],this[t(1692)+t(1106)]),this._isBrowser&&window[t(1642)+t(914)](e[t(907)],this[t(1692)+t(1414)])}[r(1441)+r(1428)+r(914)](){let t=r;this[t(1814)+"er"]&&window[t(1012)+"entListe"+t(1166)](e[t(1042)],this[t(722)+t(1287)]),this._isBrowser&&window[t(1012)+t(1977)+t(1166)](e[t(1733)],this[t(722)+t(1789)]),this[t(1814)+"er"]&&window[t(1012)+t(1977)+t(1166)](e[t(1591)],this._handlePageHide),this[t(1814)+"er"]&&window[t(1012)+"entListe"+t(1166)](e[t(907)],this[t(1692)+t(1414)])}[r(1692)+r(1106)](t){let n=r;!t[n(1522)+"d"]&&(this._isBrowser&&window[n(1012)+n(1977)+n(1166)](e.EGpMQ,this["_handleP"+n(1106)]),this._isBrowser&&window[n(1012)+n(1977)+n(1166)](e.rjfZS,this[n(1692)+"ageShow"]),this[n(1700)]()),this._isBrowser&&window[n(1012)+n(1977)+"ner"](e.iUBZs,this["_handleO"+n(1287)]),this[n(1814)+"er"]&&window[n(1012)+n(1977)+"ner"](e[n(1733)],this[n(722)+"ffLine"])}["_handleP"+r(1414)](t){let n=r;t[n(1522)+"d"]&&(this[n(1643)+"orOnline"]()&&(!this[n(795)]||e[n(1672)](this[n(795)][n(1913)+"te"],this.OPEN)||this[n(795)][n(1913)+"te"]!==this[n(1139)+"NG"])&&this["_handleO"+n(1287)](),this[n(1814)+"er"]&&window[n(1642)+n(914)](e.iUBZs,this[n(722)+n(1287)]),this[n(1814)+"er"]&&window[n(1642)+n(914)](n(1150),this[n(722)+"ffLine"]))}async[r(736)+r(1121)](t){let n=r,{fpID:o,deviceID:x,bddID:h,ttwID:g,accessKey:m,aID:f,customParams:y={},enableAutoAck:b,enableQoS:A,QoSLevel:I,env:L}=this[n(577)],V,ee,M;this[n(1814)+"er"]||this._isMiniWX||this._isMiniTT?(V=location&&e.WTRXw(e[n(1694)],location.protocol)?n(955):n(1247),ee=t.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),M=/^wss(.*:\/\/)/[n(516)](t)?t:""+V+ee):(V=e[n(866)],ee=t.replace(/(^http)((?:[s]*:\/\/))/,""),M=/(^ws)((?:[s]*:\/\/))/[n(516)](ee)?ee:""+V+ee);let X=h?n(1504):g?e[n(1109)]:e[n(929)],re=h||g||x;if(e[n(1297)](!re,!X))throw new Error(e[n(1880)]);let Ie=e[n(1110)](e.hgQsB,typeof y)?await e[n(1129)](y):y,Xa=L?e[n(889)](ga,L[n(1528)],L.xTTEnv):{},lr=Object.assign({device_platform:e[n(1177)],version_code:e.YGreA,access_key:m,fpid:o,aid:f,[X]:re,xsack:b?1:0,xaack:b?1:0,xsqos:A?1:0,qos_level:A?I:void 0,qos_sdk_version:2,...Xa},Ie),Ya=Object[n(709)](lr).reduce((hr,gr)=>lr[gr]!==void 0?""+hr+(hr?"&":"?")+gr+"="+lr[gr]:hr,"");return M+n(1451)+Ya}async _connect(){let t=r,n={pzEsW:function(o,x){return e[D(1656)](o,x)}};if(e[t(1292)](t(1876),e[t(558)])){if(this._connectLock||this[t(1322)+t(1411)])return;this["_connect"+t(1290)]=!0;try{let o=this[t(1685)+"tManager"]?.[t(1154)+t(731)+t(1529)+t(1838)+t(716)](),{timeoutInterval:x}=this._options;if(o)if(e[t(1470)](e[t(761)],t(1826))){let g=this[t(1750)][t(1781)+t(637)](this[t(1288)]);return _0x12acc0[t(1938)](NbKfHJ[t(614)](g,"{}"))[_0x30da73]}else{let g=this[t(1685)+t(1585)]?.getCurrentEndpoint(),m=this[t(1685)+t(1585)]?.[t(843)+t(566)+t(1675)+t(1756)+"unt"](),f=this._endpointManager?.[t(1865)+t(602)+t(1015)+t(1174)]();if(m){let y=t(1682)+g+(t(1653)+", max re"+t(1077)+t(784)+t(883)+t(1806)+t(1086))+m+(t(1079)+"y"),b=e[t(748)](he,t(1024),{message:y,code:He[t(1889)+t(1543)+"R"]});this[t(1979)](y),this[t(1618)+t(1732)+t(906)](b),this[t(1792)]=await this[t(736)+t(1121)](m),this[t(1979)]("connect "+m+" "+f+t(580)),this[t(1372)+t(1508)+"rs"]()}else{let y="connect "+g+(" timeout"+t(1229)+t(1077)+t(1901));this[t(1979)](y),this[t(1618)+t(1732)+t(906)](he(e[t(590)],{message:y,code:He[t(1889)+"IES_ERROR"]}));return}}else{let g=this[t(1685)+t(1585)]?.[t(1865)+t(602)+t(507)+"ateCount"](),m=this[t(1685)+t(1585)]?.["getCurre"+t(602)+"ntTriesC"+t(1174)]();this._url=await this[t(736)+t(1121)](e[t(965)](g,"")),this[t(1979)](t(1682)+g+" "+m+t(580)),this[t(1372)+t(1508)+"rs"]()}if(this._isInit)this[t(1949)]=!1;else{let g=ir(e[t(943)],{message:e[t(803)]});this[t(610)+t(1945)]&&this[t(610)+t(1945)](g)}let h=this[t(1685)+t(1585)]?.[t(1865)+t(602)+"ntTriesCount"]()||0;e[t(1630)](h,1)&&await this[t(696)](e[t(1664)](h,1)),this[t(1979)](t(1221)+"ng url: "+this._url+(t(979)+t(1853))+this._protocols),this._ws=e[t(1404)](da,{url:this[t(1792)],protocols:[this._protocols],headers:this._options["miniProg"+t(1476)+"s"][t(1387)+t(1924)]},this._options.ws),(this[t(1814)+"er"]||this[t(816)+"r"])&&this[t(795)]&&(this[t(795)][t(658)+"pe"]=this._binaryType),this._addWsListeners(),this[t(1575)+t(1351)+t(855)]=e[t(1754)](setTimeout,this[t(1594)+"ut"].bind(this),x)}catch(o){throw this[t(1575)+t(1290)]=!1,o}}else return _0x19447b===_0xf5af0f?_0x4fab17:new _0xdeff9b(e[t(710)](e[t(1054)](e[t(1429)](e[t(1683)](_0x514783.call(_0x29d657,0),e[t(1767)](_0x580216[t(1903)](_0x36a49d,1),8)),_0x348f6d.call(_0x100fe6,2)<<16),e.dQxUl(_0x47d430[t(1903)](_0x2878e3,3),24)),0),e.DPXkn(e[t(888)](_0x1edd7f.call(_0x4d6109,4)|_0x4f8ebe[t(1903)](_0x358178,5)<<8,_0x55acb5[t(1903)](_0x1f341c,6)<<16),_0x17b1c4[t(1903)](_0xed7095,7)<<24)>>>0,!0)}[r(788)+r(1090)](){let t=r;e.dbgri(clearTimeout,this["_connect"+t(1351)+"utId"]),this[t(1575)+t(1351)+t(855)]=null}[r(1152)+r(1269)](){let t=r;e[t(1698)](clearTimeout,this[t(1227)+"gTimeoutId"]),e[t(945)](clearTimeout,this[t(1179)+t(586)+t(997)]),this["_pingPon"+t(487)+"Id"]=null,this["_reconne"+t(586)+t(997)]=null}[r(1979)](...t){let n=r;e[n(1589)]===e[n(1367)]?this["_addWsLi"+n(928)]():this[n(577)][n(1180)]&&console.log[n(1606)](console,[e[n(491)],...t])}[r(1068)+"rvalValue"](t){let n=r;if(e.zwFSQ(n(623),e[n(1175)])){let{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:h}=this[n(577)],g=e.aLGHA(o,Math[n(1753)](h,e[n(1664)](t,1)));return e[n(770)](g,x)?x:g}else _0x5733d5=_0x3763b1&&e[n(739)](e[n(1694)],_0x4780c9.protocol)?n(955):n(1247),_0x3340e0=_0x2126a2[n(1220)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x3de7b3=/^wss(.*:\/\/)/.test(_0xd9ba0d)?_0x453177:""+_0x4ad9f5+_0x5d4658}_ping(){let t=r;if(this[t(795)]&&e[t(885)](this[t(795)][t(1913)+"te"],this[t(1139)+"NG"])){this[t(1152)+"ngTimer"](),this["_pingPon"+t(487)+"Id"]=e.fHebm(setTimeout,this[t(1422)].bind(this),this[t(577)][t(872)+"rval"]);return}if(!this[t(795)]||e[t(1835)](this[t(795)][t(1913)+"te"],this[t(1512)]))return void this[t(922)+"econnect"]();this._ws&&this._ws[t(1407)]("hi"),this[t(1179)+t(586)+t(997)]=e[t(719)](setTimeout,this["_handleR"+t(1945)+t(681)][t(1030)](this),this[t(577)][t(1763)+t(1631)+t(1225)])}[r(922)+r(1945)+r(681)](){let t=r;this[t(1238)+"sCounter"]?.addCount(),this[t(967)](t(550)+t(1888)+"t",e.dkHLr),this[t(1238)+"sCounter"]?.["checkRea"+t(595)+"nt"]()?this["_handleR"+t(1945)]():this[t(1422)]()}[r(1643)+"orOnline"](){let t=r;return this._isMiniTT||this[t(1156)+"X"]?this["_miniNav"+t(486)+t(1624)]:(this._isBrowser||this._isWorker)&&this[t(577)]["listenNetworkCha"+t(911)]?navigator[t(1350)]:!0}["_handleR"+r(1945)](){let t=r;!this[t(1643)+t(570)]()||this[t(1322)+"osed"]||(this["_endpoin"+t(1585)]?.["resetEndpointCon"+t(1489)](),this[t(1238)+t(960)]?.[t(1001)+t(1926)](),this[t(795)]?this["_disconn"+t(1273)](1001,e.NgdRZ,!0):this._connect())}["_onPageN"+r(1233)+r(1978)](){let t=r;if(e.fjGEi===e.fjGEi)this[t(1472)+"T"]?tt[t(1620)+t(820)+t(542)](({isConnected:n})=>{let o=t;this[o(1255)+o(486)+o(1624)]=n,n?this["_handleO"+o(1287)]():this["_handleO"+o(1789)]()}):this[t(1156)+"X"]&&wx["onNetwor"+t(820)+t(542)](({isConnected:n})=>{let o=t;this[o(1255)+o(486)+o(1624)]=n,n?this[o(722)+o(1287)]():this[o(722)+o(1789)]()});else return this[t(1618)+t(581)+t(1714)](_0x45c265),_0x3fd81c()}_wait(t){let n={wAmEX:function(o,x,h){return o(x,h)}};return new Promise(o=>{let x=D;n[x(1914)](setTimeout,o,this[x(1068)+x(1383)+"e"](t))})}[r(1634)+r(1273)](t=1e3,n="",o=!1){let x=r;this._ws&&this[x(512)+x(1008)+"t"](t,n,o)}[r(1594)+"ut"](){let t=r,n=this[t(1685)+t(1585)]?.getCurrentEndpoint();this[t(1979)](t(1682)+n+t(1653)),this[t(1634)+"ect"](1001,e[t(1375)],!0)}[r(717)](t){let n=r,o=e[n(1415)](sr,t);this[n(795)]&&e[n(1584)](this[n(795)].readyState,this[n(1512)])&&(this[n(795)]&&this[n(795)][n(1407)](o),this._debug(e.RfLGc,t))}[r(1372)+r(1508)+"rs"](){let t=r,n=e[t(1391)][t(865)]("|"),o=0;for(;;){switch(n[o++]){case"0":this[t(795)][t(1012)+t(1977)+t(1166)](e[t(590)],this[t(1511)]);continue;case"1":this[t(795)]["removeEventListe"+t(1166)](t(1706),this._onMessage);continue;case"2":if(!this[t(795)])return;continue;case"3":this._ws[t(1012)+t(1977)+t(1166)]("open",this[t(849)]);continue;case"4":this[t(795)][t(1012)+"entListe"+t(1166)](e.DltZa,this[t(1455)]);continue}break}}["_addWsLi"+r(928)](){let t=r,n={mBoHC:function(o,x){return e[D(1969)](o,x)},jGasY:function(o,x){return e[D(1343)](o,x)},sagoU:e[t(1515)],byAIp:e[t(1759)],oyCPx:function(o,x){return e[t(942)](o,x)},BJCbu:t(1157),iAzAi:function(o,x){return e[t(1722)](o,x)}};if(e[t(1984)](t(1300),e[t(1933)])){let o=(t(964)+"3")[t(865)]("|"),x=0;for(;;){switch(o[x++]){case"0":this[t(795)][t(1642)+t(914)](e.rRZOr,this[t(849)]);continue;case"1":if(!this[t(795)])return;continue;case"2":this[t(795)][t(1642)+"Listener"](t(1700),this[t(1455)]);continue;case"3":this[t(795)]["addEvent"+t(914)]("error",this[t(1511)]);continue;case"4":this[t(795)][t(1642)+t(914)](e[t(1699)],this[t(549)+"ge"]);continue}break}}else{if(jXdcsn.mBoHC(_0x306576,_0x12214b)){if(jXdcsn[t(1597)](_0x41715c,jXdcsn.sagoU))return _0x553e0e.get(_0x24f74e);if(_0x34e979===jXdcsn.byAIp)return _0x2e0dea[t(1608)+t(1097)]||_0x4d0d65[t(750)](_0x509e17);if(jXdcsn[t(1303)](_0x55b82d,jXdcsn.BJCbu))return _0x3898d2[t(1608)+"oreNames"][1]?void 0:_0xad09f1[t(1608)+"ore"](_0x40357f[t(1608)+t(1097)][0])}return jXdcsn[t(1266)](_0x4f5891,_0x4f6b92[_0x411e04])}}[r(754)+r(776)](t=1e3,n=""){let o=r;try{if(e[o(519)]===o(1276))this[o(795)]&&this[o(795)][o(1700)](t,n);else return o(1132)+"_"+this[o(680)]}catch{}}["_destroy"+r(1008)+"t"](t=1e3,n="",o=!1){let x=r;if(this["_clearPi"+x(1269)](),this[x(788)+x(1090)](),this["_removeW"+x(1508)+"rs"](),this[x(754)+x(776)](1e3,n),this[x(1575)+x(1290)]=!1,o&&this[x(1643)+x(570)]()&&!this[x(1322)+x(1411)]){if(this["_endpoin"+x(1585)]?.[x(758)+x(1296)+"es"]()){let g=this[x(1685)+x(1585)]?.[x(1865)+x(602)+"nt"]();this[x(1618)+x(918)+"ent"](_e(e[x(567)],{code:1006,reason:x(1682)+g+(x(1653)+x(1229)+x(1077)+x(1901)),wasClean:!0}))}else{let g=this[x(577)][x(1663)+x(1262)+"ptor"](t,n);this[x(1618)+x(918)+x(906)](e.olNtd(_e,e[x(567)],{code:t,reason:n,wasClean:!0,willReconnect:g})),g&&this[x(1575)]()}return}this["_navigat"+x(570)]()||this[x(1322)+"osed"]?this[x(1618)+x(918)+x(906)](e[x(1980)](_e,e[x(567)],{code:t,reason:e[x(505)]})):this["_dispatchCloseEv"+x(906)](_e(e[x(567)],{code:1006,reason:e.sIzWw})),this._ws=null,this._endpointManager?.[x(1546)+x(1099)+x(1489)](),this[x(1238)+x(960)]?.["resetCou"+x(1926)]()}[r(1618)+r(957)+"nt"](t){let n=r;this[n(967)](e[n(1687)],t),this[n(1070)]&&this[n(1070)](t)}[r(1618)+r(581)+"Event"](t){let n=r;this[n(967)](e[n(1699)],t),this[n(1356)+"e"]&&this[n(1356)+"e"](t)}[r(1618)+r(630)+"ageEvent"](t){let n=r;this.emit(e[n(1082)],t),this[n(1165)+n(1259)]&&this[n(1165)+n(1259)](t)}["_dispatc"+r(1732)+r(906)](t){let n=r;this[n(967)](e[n(590)],t),this.onerror&&this[n(616)](t)}["_dispatchCloseEv"+r(906)](t){let n=r;this.emit(e.DltZa,t),this[n(1471)]&&this[n(1471)](t)}get[r(658)+"pe"](){let t=r;return this._ws?this._ws[t(658)+"pe"]:this["_binaryT"+t(1961)]}set[r(658)+"pe"](t){let n=r;this[n(1794)+n(1961)]=t,this._ws&&(this._ws[n(658)+"pe"]=t)}get[r(1975)+"nt"](){let t=r;return this[t(1685)+t(1585)]?.[t(1865)+t(602)+"ntTriesC"+t(1174)]()||0}get["buffered"+r(768)](){let t=r,n=this["_message"+t(815)].reduce((o,x)=>(o+=x&&x.byteLength||0,o),0);return e[t(1128)](n,this[t(795)]?this._ws[t(1946)+t(768)]:0)}get[r(604)+"ns"](){let t=r;return this._ws?this._ws[t(604)+"ns"]:""}get[r(1896)](){let t=r;return this._ws?this[t(795)][t(1896)]:""}get[r(1913)+"te"](){let t=r;return this[t(795)]?this[t(795)].readyState:this._options[t(882)+t(1223)]?this[t(1139)+"NG"]:this.CLOSED}get url(){let t=r;return this[t(795)]?this[t(795)][t(1583)]:this[t(1792)]}[r(1700)](t=1e3,n){let o=r,x=(o(1393)+o(1493)).split("|"),h=0;for(;;){switch(x[h++]){case"0":this[o(1152)+o(1269)]();continue;case"1":this[o(512)+"WebSocket"](t,n);continue;case"2":this[o(1322)+o(1411)]=!0;continue;case"3":this[o(788)+o(1090)]();continue;case"4":if(e[o(1501)](this[o(795)][o(1913)+"te"],this[o(916)])||e[o(1133)](this._ws[o(1913)+"te"],this[o(1636)]))return void this._debug(e.VBtjE);continue;case"5":this[o(1441)+o(1428)+o(914)]();continue;case"6":this[o(676)+o(1408)]?.[o(1952)]();continue;case"7":if(!this[o(795)])return void this[o(1979)](e[o(737)]);continue}break}}async[r(1407)](t,n){let o=r,x={tcTwL:function(M,X){return e[D(786)](M,X)},TUTBT:function(M,X){return e.LMWoc(M,X)},suZOe:function(M,X){return e[D(1526)](M,X)},lcZHX:function(M,X){return e.chTJD(M,X)},wZIle:function(M,X){return e.Gkqhy(M,X)}};if(t==null)throw new Error(e[o(1509)]);e.DVhxY==typeof t&&(t=JSON[o(619)+"y"](t)),e.nupSJ("string",typeof t)&&!e[o(568)](t,ArrayBuffer)&&!(t[o(1839)]&&e[o(1969)](t.buffer,ArrayBuffer))&&(t=JSON[o(619)+"y"](t));let h=await Es(t),g=e.DRCfX(ha,t),{method:m=0,service:f=this._options[o(1143)],logID:y=this[o(577)][o(1987)+"erator"](),headers:b=this[o(577)][o(976)],payloadEncoding:A=this[o(577)][o(1260)+o(1327)],payloadType:I=this[o(577)][o(1182)+o(1961)],logIDNew:L=this[o(577)][o(1050)+o(715)][o(1041)+o(1243)+"teLogIDNew"]?e.pHkeD(a,this[o(577)][o(1050)+o(715)][o(1772)]):""}=n||{};if(!f)throw new Error(e[o(1560)]);let V={SeqID:B[o(1590)+"er"](this[o(1353)]++),LogID:B[o(1590)+"er"](y),service:f,method:m,headers:b,payloadEncoding:e[o(1614)](A,Object)?A[o(1894)]?A[o(1894)]:"":A,payloadType:e.yCJYw(I,Object)?I[o(728)]?I.type:g:I||g,payload:h,LogIDNew:L},ee=sr(V);if(this[o(795)]&&this[o(795)][o(1913)+"te"]===this[o(1512)])this[o(795)]&&this[o(795)][o(1407)](ee),this._debug(e.TeUmZ,V);else if(e.FdguP(this[o(1059)+o(815)].length,this[o(577)][o(1660)+"geQueueL"+o(1469)]))if(e[o(1267)]===o(1052))this[o(1059)+o(815)].push(ee),this._debug(e[o(875)],V);else return function(M,...X){let re=o,Ie=_0x67a676.call(gjOsPl[re(1347)](_0x130b92,this),M,...X);return _0x108056[re(1142)](Ie,M[re(874)]?M[re(874)]():[M]),gjOsPl.tcTwL(_0x5ac00a,Ie)};else{if(e[o(1566)](e[o(1937)],e[o(1937)]))return _0x936f32[o(895)](_0x6a0d66)||(_0x53655e=_0x5a57c9.fromNumber(_0x25ed7a)),gjOsPl[o(981)](this[o(949)],_0x591722[o(949)])&&gjOsPl[o(1485)](gjOsPl[o(1557)](this[o(1562)],31),1)&&gjOsPl[o(669)](gjOsPl[o(1557)](_0x2dc76c.high,31),1)?!1:gjOsPl[o(1485)](this[o(1562)],_0xdb99f0[o(1562)])&&gjOsPl[o(1485)](this[o(1302)],_0x24246c[o(1302)]);this["_message"+o(815)].shift(),this[o(1059)+o(815)][o(613)](ee)}return{seqID:this[o(1353)],logID:y,logIDNew:L}}async reconnect(t){let n=r,{url:o}=t||{},x=Array[n(1108)](o)?o:e[n(982)](n(1491),typeof o)?[o]:[];t&&Object[n(773)](this._options,t),x&&x[n(1931)]?this[n(1685)+n(1585)]=new ys(x,this[n(577)][n(492)+"es"]):this[n(1685)+"tManager"]?.[n(1546)+n(1099)+n(1489)](),this[n(1238)+n(960)]?.["resetCou"+n(1926)](this._options[n(1e3)+n(1565)]),this[n(1322)+n(1411)]=!1,this[n(795)]&&this[n(795)][n(1913)+"te"]!==this[n(916)]?this[n(1634)+"ect"](1e3,e[n(733)],!0):(this[n(1949)]=!0,this[n(1575)]())}async[r(1023)](){let t=r;if(!this["_connect"+t(1290)]){let n=e[t(1761)].split("|"),o=0;for(;;){switch(n[o++]){case"0":this["_readyCl"+t(1411)]=!1;continue;case"1":this[t(1575)]();continue;case"2":this[t(1949)]=!0;continue;case"3":this["_endpoin"+t(1585)]?.[t(1546)+"pointCon"+t(1489)]();continue;case"4":this[t(1238)+t(960)]?.["resetCou"+t(1926)]();continue}break}}}[r(1642)+"Listener"](t,n){let o=r;if(e[o(1246)](e[o(721)],e[o(721)]))return!!this._qosDB;this.on(t,n)}dispatchEvent(t){let n=r;if(n(1647)!==e[n(1043)]){let{type:o}=t;this[n(967)](o,t)}else{this[n(1152)+n(1269)](),this[n(1227)+n(487)+"Id"]=_0x1b78d9(this._ping[n(1030)](this),this._options[n(872)+"rval"]);return}}[r(1012)+"entListe"+r(1166)](t,n){this.off(t,n)}pingOnce(){let t={bSlHn:function(n,o){return n||o}};return new Promise((n,o)=>{let x=D,h={BQOWu:e[x(1716)],CmnOk:function(g,m){return e[x(1577)](g,m)},oldcs:x(550)+x(927)+"s"};if(e[x(1366)](e[x(1344)],e[x(1342)])){this["_clearPi"+x(1269)](),this[x(1227)+x(487)+"Id"]=setTimeout(this[x(1422)][x(1030)](this),this[x(577)]["pingInte"+x(1679)]);let g=()=>{let f=x;n(f(1658)),this[f(1424)]("ping_once_success",g),this.off(h[f(787)],m)},m=()=>{let f=x;h[f(1306)](o,f(1285)),this[f(1424)](h[f(1033)],g),this[f(1424)](h[f(787)],m)};this.on(e[x(1080)],g),this.on(x(550)+x(1888)+"t",m),this[x(1422)]()}else{let g=this[x(1750)][x(1095)](this._prefix),m=_0x3ce6a8[x(1938)](Aobdgq[x(1348)](g,"{}"));return _0x3a4965[x(709)](m)}})}}})(),Z[S(823)+"oseEvent"]=$[S(823)+"oseEvent"],Z[S(1564)+"rorEvent"]=$[S(1564)+S(615)],Z[S(1779)+"e"]=$.ErrorCode,Z[S(1714)]=$[S(1714)],Z.FWS=$[S(1352)],Z[S(766)+S(1740)+S(493)]=$[S(766)+"MessageE"+S(493)],Z.MessageEvent=$[S(1740)+S(493)],Z[S(838)+"t"]=$[S(838)+"t"],Z[S(1986)+S(1340)]=$[S(1986)+"tEvent"],Z[S(1639)+S(1240)]=$[S(1639)+S(1240)],Z[S(826)+S(615)]=$[S(826)+S(615)],Z[S(1360)+S(1011)+"nt"]=$[S(1360)+S(1011)+"nt"],Z.createOpenEvent=$[S(1799)+S(1770)],Z[S(1709)+S(1919)+S(493)]=$[S(1709)+S(1919)+S(493)],Z[S(1807)+"rame"]=$[S(1807)+S(485)],Z["encodeFr"+S(1202)]=$[S(1827)+S(1202)];for(kn in $)[S(823)+S(1240),S(1564)+S(615),S(1779)+"e",S(1714),S(1352),S(766)+S(1740)+"vent",S(1740)+S(493),S(838)+"t",S(1986)+"tEvent","createCl"+S(1240),S(826)+"rorEvent",S(1360)+"ssageEvent",S(1799)+S(1770),"createRe"+S(1919)+S(493),S(1807)+S(485),S(1827)+S(1202)][S(1935)](kn)===-1&&(Z[kn]=$[kn]);var kn;Object["definePr"+S(775)](Z,"__esModule",{value:!0})});var Be=ce((Wl,Ni)=>{"use strict";var Ii=["nodebuffer","arraybuffer","fragments"],Li=typeof Blob<"u";Li&&Ii.push("blob");Ni.exports={BINARY_TYPES:Ii,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Li,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ft=ce((Jl,Rn)=>{"use strict";var{EMPTY_BUFFER:Vx}=Be(),kr=Buffer[Symbol.species];function Xx(r,e){if(r.length===0)return Vx;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 kr(i.buffer,i.byteOffset,a):i}function Ri(r,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=r[u]^e[u&3]}function Mi(r,e){for(let i=0;i<r.length;i++)r[i]^=e[i&3]}function Yx(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Pr(r){if(Pr.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new kr(r):ArrayBuffer.isView(r)?e=new kr(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Pr.readOnly=!1),e}Rn.exports={concat:Xx,mask:Ri,toArrayBuffer:Yx,toBuffer:Pr,unmask:Mi};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=Y("bufferutil");Rn.exports.mask=function(e,i,a,c,u){u<48?Ri(e,i,a,c,u):r.mask(e,i,a,c,u)},Rn.exports.unmask=function(e,i){e.length<32?Mi(e,i):r.unmask(e,i)}}catch{}});var zi=ce((Vl,Bi)=>{"use strict";var Oi=Symbol("kDone"),Dr=Symbol("kRun"),Tr=class{constructor(e){this[Oi]=()=>{this.pending--,this[Dr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Dr]()}[Dr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Oi])}}};Bi.exports=Tr});var _t=ce((Xl,Hi)=>{"use strict";var Ut=Y("zlib"),qi=Ft(),$x=zi(),{kStatusCode:Fi}=Be(),Zx=Buffer[Symbol.species],Qx=Buffer.from([0,0,255,255]),On=Symbol("permessage-deflate"),ze=Symbol("total-length"),pt=Symbol("callback"),We=Symbol("buffers"),mt=Symbol("error"),Mn,Ir=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,!Mn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Mn=new $x(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[pt];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){Mn.add(c=>{this._decompress(e,i,(u,d)=>{c(),a(u,d)})})}compress(e,i,a){Mn.add(c=>{this._compress(e,i,(u,d)=>{c(),a(u,d)})})}_decompress(e,i,a){let c=this._isServer?"client":"server";if(!this._inflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Ut.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[On]=this,this._inflate[ze]=0,this._inflate[We]=[],this._inflate.on("error",tc),this._inflate.on("data",Ui)}this._inflate[pt]=a,this._inflate.write(e),i&&this._inflate.write(Qx),this._inflate.flush(()=>{let u=this._inflate[mt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=qi.concat(this._inflate[We],this._inflate[ze]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ze]=0,this._inflate[We]=[],i&&this.params[`${c}_no_context_takeover`]&&this._inflate.reset()),a(null,d)})}_compress(e,i,a){let c=this._isServer?"server":"client";if(!this._deflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Ut.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Ut.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[ze]=0,this._deflate[We]=[],this._deflate.on("data",ec)}this._deflate[pt]=a,this._deflate.write(e),this._deflate.flush(Ut.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=qi.concat(this._deflate[We],this._deflate[ze]);i&&(u=new Zx(u.buffer,u.byteOffset,u.length-4)),this._deflate[pt]=null,this._deflate[ze]=0,this._deflate[We]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};Hi.exports=Ir;function ec(r){this[We].push(r),this[ze]+=r.length}function Ui(r){if(this[ze]+=r.length,this[On]._maxPayload<1||this[ze]<=this[On]._maxPayload){this[We].push(r);return}this[mt]=new RangeError("Max payload size exceeded"),this[mt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[mt][Fi]=1009,this.removeListener("data",Ui),this.reset()}function tc(r){if(this[On]._inflate=null,this[mt]){this[pt](this[mt]);return}r[Fi]=1007,this[pt](r)}});var wt=ce((Yl,Bn)=>{"use strict";var{isUtf8:Ki}=Y("buffer"),{hasBlob:nc}=Be(),rc=[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 sc(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Lr(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 ic(r){return nc&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}Bn.exports={isBlob:ic,isValidStatusCode:sc,isValidUTF8:Lr,tokenChars:rc};if(Ki)Bn.exports.isValidUTF8=function(r){return r.length<24?Lr(r):Ki(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=Y("utf-8-validate");Bn.exports.isValidUTF8=function(e){return e.length<32?Lr(e):r(e)}}catch{}});var Br=ce(($l,Yi)=>{"use strict";var{Writable:oc}=Y("stream"),Gi=_t(),{BINARY_TYPES:ac,EMPTY_BUFFER:ji,kStatusCode:xc,kWebSocket:cc}=Be(),{concat:Nr,toArrayBuffer:uc,unmask:fc}=Ft(),{isValidStatusCode:dc,isValidUTF8:Wi}=wt(),zn=Buffer[Symbol.species],ge=0,Ji=1,Vi=2,Xi=3,Rr=4,Mr=5,qn=6,Or=class extends oc{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||ac[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[cc]=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=ge}_write(e,i,a){if(this._opcode===8&&this._state==ge)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 zn(a.buffer,a.byteOffset+e,a.length-e),new zn(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 zn(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 ge:this.getInfo(e);break;case Ji:this.getPayloadLength16(e);break;case Vi:this.getPayloadLength64(e);break;case Xi:this.getMask();break;case Rr:this.getData(e);break;case Mr:case qn: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[Gi.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=Ji:this._payloadLength===127?this._state=Vi: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=Xi:this._state=Rr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Rr}getData(e){let i=ji;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&&fc(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Mr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[Gi.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===ge&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=ge;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=Nr(a,i):this._binaryType==="arraybuffer"?c=uc(Nr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=ge):(this._state=qn,setImmediate(()=>{this.emit("message",c,!0),this._state=ge,this.startLoop(e)}))}else{let c=Nr(a,i);if(!this._skipUTF8Validation&&!Wi(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===Mr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=ge):(this._state=qn,setImmediate(()=>{this.emit("message",c,!1),this._state=ge,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ji),this.end();else{let a=e.readUInt16BE(0);if(!dc(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new zn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Wi(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=ge;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ge):(this._state=qn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ge,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[xc]=c,d}};Yi.exports=Or});var Fr=ce((Ql,Qi)=>{"use strict";var{Duplex:Zl}=Y("stream"),{randomFillSync:lc}=Y("crypto"),$i=_t(),{EMPTY_BUFFER:hc,kWebSocket:gc,NOOP:pc}=Be(),{isBlob:yt,isValidStatusCode:mc}=wt(),{mask:Zi,toBuffer:Qe}=Ft(),pe=Symbol("kByteLength"),_c=Buffer.alloc(4),Fn=8*1024,et,bt=Fn,ye=0,wc=1,yc=2,zr=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=ye,this.onerror=pc,this[gc]=void 0}static frame(e,i){let a,c=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||_c,i.generateMask?i.generateMask(a):(bt===Fn&&(et===void 0&&(et=Buffer.alloc(Fn)),lc(et,0,Fn),bt=0),a[0]=et[bt++],a[1]=et[bt++],a[2]=et[bt++],a[3]=et[bt++]),d=(a[0]|a[1]|a[2]|a[3])===0,u=6);let l;typeof e=="string"?(!i.mask||d)&&i[pe]!==void 0?l=i[pe]:(e=Buffer.from(e),l=e.length):(l=e.length,c=i.mask&&i.readOnly&&!d);let p=l;l>=65536?(u+=8,p=127):l>125&&(u+=2,p=126);let _=Buffer.allocUnsafe(c?l+u:u);return _[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(_[0]|=64),_[1]=p,p===126?_.writeUInt16BE(l,2):p===127&&(_[2]=_[3]=0,_.writeUIntBE(l,4,6)),i.mask?(_[1]|=128,_[u-4]=a[0],_[u-3]=a[1],_[u-2]=a[2],_[u-1]=a[3],d?[_,e]:c?(Zi(e,a,_,u,l),[_]):(Zi(e,a,e,0,l),[_,e])):[_,e]}close(e,i,a,c){let u;if(e===void 0)u=hc;else{if(typeof e!="number"||!mc(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 l=Buffer.byteLength(i);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");u=Buffer.allocUnsafe(2+l),u.writeUInt16BE(e,0),typeof i=="string"?u.write(i,2):u.set(i,2)}}let d={[pe]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ye?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):yt(e)?(c=e.size,u=!1):(e=Qe(e),c=e.length,u=Qe.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pe]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};yt(e)?this._state!==ye?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==ye?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):yt(e)?(c=e.size,u=!1):(e=Qe(e),c=e.length,u=Qe.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[pe]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};yt(e)?this._state!==ye?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==ye?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(r.frame(e,d),a)}send(e,i,a){let c=this._extensions[$i.extensionName],u=i.binary?2:1,d=i.compress,l,p;typeof e=="string"?(l=Buffer.byteLength(e),p=!1):yt(e)?(l=e.size,p=!1):(e=Qe(e),l=e.length,p=Qe.readOnly),this._firstFragment?(this._firstFragment=!1,d&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=l>=c._threshold),this._compress=d):(d=!1,u=0),i.fin&&(this._firstFragment=!0);let _={[pe]:l,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:p,rsv1:d};yt(e)?this._state!==ye?this.enqueue([this.getBlobData,e,this._compress,_,a]):this.getBlobData(e,this._compress,_,a):this._state!==ye?this.enqueue([this.dispatch,e,this._compress,_,a]):this.dispatch(e,this._compress,_,a)}getBlobData(e,i,a,c){this._bufferedBytes+=a[pe],this._state=yc,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(qr,this,l,c);return}this._bufferedBytes-=a[pe];let d=Qe(u);i?this.dispatch(d,i,a,c):(this._state=ye,this.sendFrame(r.frame(d,a),c),this.dequeue())}).catch(u=>{process.nextTick(bc,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(r.frame(e,a),c);return}let u=this._extensions[$i.extensionName];this._bufferedBytes+=a[pe],this._state=wc,u.compress(e,a.fin,(d,l)=>{if(this._socket.destroyed){let p=new Error("The socket was closed while data was being compressed");qr(this,p,c);return}this._bufferedBytes-=a[pe],this._state=ye,a.readOnly=!1,this.sendFrame(r.frame(l,a),c),this.dequeue()})}dequeue(){for(;this._state===ye&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][pe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][pe],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)}};Qi.exports=zr;function qr(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 bc(r,e,i){qr(r,e,i),r.onerror(e)}});var xo=ce((eh,ao)=>{"use strict";var{kForOnEventAttribute:Ht,kListener:Ur}=Be(),eo=Symbol("kCode"),to=Symbol("kData"),no=Symbol("kError"),ro=Symbol("kMessage"),so=Symbol("kReason"),vt=Symbol("kTarget"),io=Symbol("kType"),oo=Symbol("kWasClean"),qe=class{constructor(e){this[vt]=null,this[io]=e}get target(){return this[vt]}get type(){return this[io]}};Object.defineProperty(qe.prototype,"target",{enumerable:!0});Object.defineProperty(qe.prototype,"type",{enumerable:!0});var nt=class extends qe{constructor(e,i={}){super(e),this[eo]=i.code===void 0?0:i.code,this[so]=i.reason===void 0?"":i.reason,this[oo]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[eo]}get reason(){return this[so]}get wasClean(){return this[oo]}};Object.defineProperty(nt.prototype,"code",{enumerable:!0});Object.defineProperty(nt.prototype,"reason",{enumerable:!0});Object.defineProperty(nt.prototype,"wasClean",{enumerable:!0});var St=class extends qe{constructor(e,i={}){super(e),this[no]=i.error===void 0?null:i.error,this[ro]=i.message===void 0?"":i.message}get error(){return this[no]}get message(){return this[ro]}};Object.defineProperty(St.prototype,"error",{enumerable:!0});Object.defineProperty(St.prototype,"message",{enumerable:!0});var Kt=class extends qe{constructor(e,i={}){super(e),this[to]=i.data===void 0?null:i.data}get data(){return this[to]}};Object.defineProperty(Kt.prototype,"data",{enumerable:!0});var vc={addEventListener(r,e,i={}){for(let c of this.listeners(r))if(!i[Ht]&&c[Ur]===e&&!c[Ht])return;let a;if(r==="message")a=function(u,d){let l=new Kt("message",{data:d?u:u.toString()});l[vt]=this,Un(e,this,l)};else if(r==="close")a=function(u,d){let l=new nt("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[vt]=this,Un(e,this,l)};else if(r==="error")a=function(u){let d=new St("error",{error:u,message:u.message});d[vt]=this,Un(e,this,d)};else if(r==="open")a=function(){let u=new qe("open");u[vt]=this,Un(e,this,u)};else return;a[Ht]=!!i[Ht],a[Ur]=e,i.once?this.once(r,a):this.on(r,a)},removeEventListener(r,e){for(let i of this.listeners(r))if(i[Ur]===e&&!i[Ht]){this.removeListener(r,i);break}}};ao.exports={CloseEvent:nt,ErrorEvent:St,Event:qe,EventTarget:vc,MessageEvent:Kt};function Un(r,e,i){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,i):r.call(e,i)}});var Hn=ce((th,co)=>{"use strict";var{tokenChars:Gt}=wt();function Pe(r,e,i){r[e]===void 0?r[e]=[i]:r[e].push(i)}function Sc(r){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,d,l,p=-1,_=-1,v=-1,w=0;for(;w<r.length;w++)if(_=r.charCodeAt(w),d===void 0)if(v===-1&&Gt[_]===1)p===-1&&(p=w);else if(w!==0&&(_===32||_===9))v===-1&&p!==-1&&(v=w);else if(_===59||_===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let P=r.slice(p,v);_===44?(Pe(e,P,i),i=Object.create(null)):d=P,p=v=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);else if(l===void 0)if(v===-1&&Gt[_]===1)p===-1&&(p=w);else if(_===32||_===9)v===-1&&p!==-1&&(v=w);else if(_===59||_===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w),Pe(i,r.slice(p,v),!0),_===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),p=v=-1}else if(_===61&&p!==-1&&v===-1)l=r.slice(p,w),p=v=-1;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(c){if(Gt[_]!==1)throw new SyntaxError(`Unexpected character at index ${w}`);p===-1?p=w:a||(a=!0),c=!1}else if(u)if(Gt[_]===1)p===-1&&(p=w);else if(_===34&&p!==-1)u=!1,v=w;else if(_===92)c=!0;else throw new SyntaxError(`Unexpected character at index ${w}`);else if(_===34&&r.charCodeAt(w-1)===61)u=!0;else if(v===-1&&Gt[_]===1)p===-1&&(p=w);else if(p!==-1&&(_===32||_===9))v===-1&&(v=w);else if(_===59||_===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${w}`);v===-1&&(v=w);let P=r.slice(p,v);a&&(P=P.replace(/\\/g,""),a=!1),Pe(i,l,P),_===44&&(Pe(e,d,i),i=Object.create(null),d=void 0),l=void 0,p=v=-1}else throw new SyntaxError(`Unexpected character at index ${w}`);if(p===-1||u||_===32||_===9)throw new SyntaxError("Unexpected end of input");v===-1&&(v=w);let C=r.slice(p,v);return d===void 0?Pe(e,C,i):(l===void 0?Pe(i,C,!0):a?Pe(i,l,C.replace(/\\/g,"")):Pe(i,l,C),Pe(e,d,i)),e}function Ec(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(", ")}co.exports={format:Ec,parse:Sc}});var Wn=ce((sh,vo)=>{"use strict";var Cc=Y("events"),Ac=Y("https"),kc=Y("http"),lo=Y("net"),Pc=Y("tls"),{randomBytes:Dc,createHash:Tc}=Y("crypto"),{Duplex:nh,Readable:rh}=Y("stream"),{URL:Hr}=Y("url"),Je=_t(),Ic=Br(),Lc=Fr(),{isBlob:Nc}=wt(),{BINARY_TYPES:uo,CLOSE_TIMEOUT:Rc,EMPTY_BUFFER:Kn,GUID:Mc,kForOnEventAttribute:Kr,kListener:Oc,kStatusCode:Bc,kWebSocket:Q,NOOP:ho}=Be(),{EventTarget:{addEventListener:zc,removeEventListener:qc}}=xo(),{format:Fc,parse:Uc}=Hn(),{toBuffer:Hc}=Ft(),go=Symbol("kAborted"),Gr=[8,13],Fe=["CONNECTING","OPEN","CLOSING","CLOSED"],Kc=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,F=class r extends Cc{constructor(e,i,a){super(),this._binaryType=uo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Kn,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]),po(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){uo.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 Ic({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new Lc(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[Q]=this,u[Q]=this,e[Q]=this,c.on("conclude",Wc),c.on("drain",Jc),c.on("error",Vc),c.on("message",Xc),c.on("ping",Yc),c.on("pong",$c),u.onerror=Zc,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",wo),e.on("data",jn),e.on("end",yo),e.on("error",bo),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Je.extensionName]&&this._extensions[Je.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,i){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){le(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())}),_o(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){jr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Kn,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){jr(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Kn,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){jr(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[Je.extensionName]||(c.compress=!1),this._sender.send(e||Kn,c,a)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(F,"CONNECTING",{enumerable:!0,value:Fe.indexOf("CONNECTING")});Object.defineProperty(F.prototype,"CONNECTING",{enumerable:!0,value:Fe.indexOf("CONNECTING")});Object.defineProperty(F,"OPEN",{enumerable:!0,value:Fe.indexOf("OPEN")});Object.defineProperty(F.prototype,"OPEN",{enumerable:!0,value:Fe.indexOf("OPEN")});Object.defineProperty(F,"CLOSING",{enumerable:!0,value:Fe.indexOf("CLOSING")});Object.defineProperty(F.prototype,"CLOSING",{enumerable:!0,value:Fe.indexOf("CLOSING")});Object.defineProperty(F,"CLOSED",{enumerable:!0,value:Fe.indexOf("CLOSED")});Object.defineProperty(F.prototype,"CLOSED",{enumerable:!0,value:Fe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(F.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(F.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[Kr])return e[Oc];return null},set(e){for(let i of this.listeners(r))if(i[Kr]){this.removeListener(r,i);break}typeof e=="function"&&this.addEventListener(r,e,{[Kr]:!0})}})});F.prototype.addEventListener=zc;F.prototype.removeEventListener=qc;vo.exports=F;function po(r,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Rc,protocolVersion:Gr[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,!Gr.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${Gr.join(", ")})`);let u;if(e instanceof Hr)u=e;else try{u=new Hr(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:",l=u.protocol==="ws+unix:",p;if(u.protocol!=="ws:"&&!d&&!l?p=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!u.pathname?p="The URL's pathname is empty":u.hash&&(p="The URL contains a fragment identifier"),p){let N=new SyntaxError(p);if(r._redirects===0)throw N;Gn(r,N);return}let _=d?443:80,v=Dc(16).toString("base64"),w=d?Ac.request:kc.request,C=new Set,P;if(c.createConnection=c.createConnection||(d?jc:Gc),c.defaultPort=c.defaultPort||_,c.port=u.port||_,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&&(P=new Je({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=Fc({[Je.extensionName]:P.offer()})),i.length){for(let N of i){if(typeof N!="string"||!Kc.test(N)||C.has(N))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(N)}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}`),l){let N=c.path.split(":");c.socketPath=N[0],c.path=N[1]}let T;if(c.followRedirects){if(r._redirects===0){r._originalIpc=l,r._originalSecure=d,r._originalHostOrSocketPath=l?c.socketPath:u.host;let N=a&&a.headers;if(a={...a,headers:{}},N)for(let[z,ae]of Object.entries(N))a.headers[z.toLowerCase()]=ae}else if(r.listenerCount("redirect")===0){let N=l?r._originalIpc?c.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:u.host===r._originalHostOrSocketPath;(!N||r._originalSecure&&!d)&&(delete c.headers.authorization,delete c.headers.cookie,N||delete c.headers.host,c.auth=void 0)}c.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(c.auth).toString("base64")),T=r._req=w(c),r._redirects&&r.emit("redirect",r.url,T)}else T=r._req=w(c);c.timeout&&T.on("timeout",()=>{le(r,T,"Opening handshake has timed out")}),T.on("error",N=>{T===null||T[go]||(T=r._req=null,Gn(r,N))}),T.on("response",N=>{let z=N.headers.location,ae=N.statusCode;if(z&&c.followRedirects&&ae>=300&&ae<400){if(++r._redirects>c.maxRedirects){le(r,T,"Maximum redirects exceeded");return}T.abort();let te;try{te=new Hr(z,e)}catch{let ue=new SyntaxError(`Invalid URL: ${z}`);Gn(r,ue);return}po(r,te,i,a)}else r.emit("unexpected-response",T,N)||le(r,T,`Unexpected server response: ${N.statusCode}`)}),T.on("upgrade",(N,z,ae)=>{if(r.emit("upgrade",N),r.readyState!==F.CONNECTING)return;T=r._req=null;let te=N.headers.upgrade;if(te===void 0||te.toLowerCase()!=="websocket"){le(r,z,"Invalid Upgrade header");return}let be=Tc("sha1").update(v+Mc).digest("base64");if(N.headers["sec-websocket-accept"]!==be){le(r,z,"Invalid Sec-WebSocket-Accept header");return}let ue=N.headers["sec-websocket-protocol"],k;if(ue!==void 0?C.size?C.has(ue)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":C.size&&(k="Server sent no subprotocol"),k){le(r,z,k);return}ue&&(r._protocol=ue);let q=N.headers["sec-websocket-extensions"];if(q!==void 0){if(!P){le(r,z,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let W;try{W=Uc(q)}catch{le(r,z,"Invalid Sec-WebSocket-Extensions header");return}let ne=Object.keys(W);if(ne.length!==1||ne[0]!==Je.extensionName){le(r,z,"Server indicated an extension that was not requested");return}try{P.accept(W[Je.extensionName])}catch{le(r,z,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[Je.extensionName]=P}r.setSocket(z,ae,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(T,r):T.end()}function Gn(r,e){r._readyState=F.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function Gc(r){return r.path=r.socketPath,lo.connect(r)}function jc(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=lo.isIP(r.host)?"":r.host),Pc.connect(r)}function le(r,e,i){r._readyState=F.CLOSING;let a=new Error(i);Error.captureStackTrace(a,le),e.setHeader?(e[go]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Gn,r,a)):(e.destroy(a),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function jr(r,e,i){if(e){let a=Nc(e)?e.size:Hc(e).length;r._socket?r._sender._bufferedBytes+=a:r._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${r.readyState} (${Fe[r.readyState]})`);process.nextTick(i,a)}}function Wc(r,e){let i=this[Q];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=r,i._socket[Q]!==void 0&&(i._socket.removeListener("data",jn),process.nextTick(mo,i._socket),r===1005?i.close():i.close(r,e))}function Jc(){let r=this[Q];r.isPaused||r._socket.resume()}function Vc(r){let e=this[Q];e._socket[Q]!==void 0&&(e._socket.removeListener("data",jn),process.nextTick(mo,e._socket),e.close(r[Bc])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function fo(){this[Q].emitClose()}function Xc(r,e){this[Q].emit("message",r,e)}function Yc(r){let e=this[Q];e._autoPong&&e.pong(r,!this._isServer,ho),e.emit("ping",r)}function $c(r){this[Q].emit("pong",r)}function mo(r){r.resume()}function Zc(r){let e=this[Q];e.readyState!==F.CLOSED&&(e.readyState===F.OPEN&&(e._readyState=F.CLOSING,_o(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function _o(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function wo(){let r=this[Q];if(this.removeListener("close",wo),this.removeListener("data",jn),this.removeListener("end",yo),r._readyState=F.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[Q]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",fo),r._receiver.on("finish",fo))}function jn(r){this[Q]._receiver.write(r)||this.pause()}function yo(){let r=this[Q];r._readyState=F.CLOSING,r._receiver.end(),this.end()}function bo(){let r=this[Q];this.removeListener("error",bo),this.on("error",ho),r&&(r._readyState=F.CLOSING,this.destroy())}});var Ao=ce((oh,Co)=>{"use strict";var ih=Wn(),{Duplex:Qc}=Y("stream");function So(r){r.emit("close")}function eu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Eo(r){this.removeListener("error",Eo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function tu(r,e){let i=!0,a=new Qc({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(u,d){let l=!d&&a._readableState.objectMode?u.toString():u;a.push(l)||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(So,a);return}let d=!1;r.once("error",function(p){d=!0,u(p)}),r.once("close",function(){d||u(c),process.nextTick(So,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",eu),a.on("error",Eo),a}Co.exports=tu});var Wr=ce((ah,ko)=>{"use strict";var{tokenChars:nu}=wt();function ru(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&&nu[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 l=r.slice(i,a);if(e.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);e.add(l),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}ko.exports={parse:ru}});var Ro=ce((ch,No)=>{"use strict";var su=Y("events"),Jn=Y("http"),{Duplex:xh}=Y("stream"),{createHash:iu}=Y("crypto"),Po=Hn(),rt=_t(),ou=Wr(),au=Wn(),{CLOSE_TIMEOUT:xu,GUID:cu,kWebSocket:uu}=Be(),fu=/^[+/0-9A-Za-z]{22}==$/,Do=0,To=1,Lo=2,Jr=class extends su{constructor(e,i){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:au,...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=Jn.createServer((a,c)=>{let u=Jn.STATUS_CODES[426];c.writeHead(426,{"Content-Length":u.length,"Content-Type":"text/plain"}),c.end(u)}),this._server.listen(e.port,e.host,e.backlog,i)):e.server&&(this._server=e.server),this._server){let a=this.emit.bind(this,"connection");this._removeListeners=du(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(c,u,d)=>{this.handleUpgrade(c,u,d,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Do}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===Lo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(jt,this);return}if(e&&this.once("close",e),this._state!==To)if(this._state=To,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(jt,this):process.nextTick(jt,this);else{let i=this._server;this._removeListeners(),this._removeListeners=this._server=null,i.close(()=>{jt(this)})}}shouldHandle(e){if(this.options.path){let i=e.url.indexOf("?");if((i!==-1?e.url.slice(0,i):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,i,a,c){i.on("error",Io);let u=e.headers["sec-websocket-key"],d=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){st(this,e,i,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){st(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!fu.test(u)){st(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){st(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Wt(i,400);return}let p=e.headers["sec-websocket-protocol"],_=new Set;if(p!==void 0)try{_=ou.parse(p)}catch{st(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let v=e.headers["sec-websocket-extensions"],w={};if(this.options.perMessageDeflate&&v!==void 0){let C=new rt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let P=Po.parse(v);P[rt.extensionName]&&(C.accept(P[rt.extensionName]),w[rt.extensionName]=C)}catch{st(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(P,T,N,z)=>{if(!P)return Wt(i,T||401,N,z);this.completeUpgrade(w,u,_,e,i,a,c)});return}if(!this.options.verifyClient(C))return Wt(i,401)}this.completeUpgrade(w,u,_,e,i,a,c)}completeUpgrade(e,i,a,c,u,d,l){if(!u.readable||!u.writable)return u.destroy();if(u[uu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Do)return Wt(u,503);let _=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${iu("sha1").update(i+cu).digest("base64")}`],v=new this.options.WebSocket(null,void 0,this.options);if(a.size){let w=this.options.handleProtocols?this.options.handleProtocols(a,c):a.values().next().value;w&&(_.push(`Sec-WebSocket-Protocol: ${w}`),v._protocol=w)}if(e[rt.extensionName]){let w=e[rt.extensionName].params,C=Po.format({[rt.extensionName]:[w]});_.push(`Sec-WebSocket-Extensions: ${C}`),v._extensions=e}this.emit("headers",_,c),u.write(_.concat(`\r
|
|
12
12
|
`).join(`\r
|
|
13
|
-
`)),
|
|
14
|
-
`+Object.keys(
|
|
13
|
+
`)),u.removeListener("error",Io),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(jt,this)})),l(v,c)}};No.exports=Jr;function du(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 jt(r){r._state=Lo,r.emit("close")}function Io(){this.destroy()}function Wt(r,e,i,a){i=i||Jn.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} ${Jn.STATUS_CODES[e]}\r
|
|
14
|
+
`+Object.keys(a).map(c=>`${c}: ${a[c]}`).join(`\r
|
|
15
15
|
`)+`\r
|
|
16
16
|
\r
|
|
17
|
-
`+
|
|
17
|
+
`+i)}function st(r,e,i,a,c,u){if(r.listenerCount("wsClientError")){let d=new Error(c);Error.captureStackTrace(d,st),r.emit("wsClientError",d,i,e)}else Wt(i,a,c,u)}});import{spawn as Nu}from"node:child_process";import{existsSync as Ru,openSync as Mu}from"node:fs";import{mkdir as Ou}from"node:fs/promises";import{dirname as Bu}from"node:path";import{fileURLToPath as zu}from"node:url";function Yr(r=K()){return Ru(r.libEntry)?r.libEntry:zu(new URL("../index.ts",import.meta.url))}async function Jo(r={}){let e=r.paths??K(),i=r.entryOverride??Yr(e);await Ou(Bu(e.logFile),{recursive:!0});let a=Mu(e.logFile,"a"),u=i.endsWith(".ts")?["--import","tsx/esm",i,"--daemon"]:[i,"--daemon"],d=Nu(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 qu.info("daemon spawned",{pid:d.pid,entry:i}),{pid:d.pid,entry:i}}var qu,$r=Le(()=>{"use strict";H();fe();qu=R("spawn-daemon")});import{spawn as Ju}from"node:child_process";import{mkdir as Vu,unlink as Xu,writeFile as Yu}from"node:fs/promises";import{dirname as $u,join as Zu}from"node:path";function Qn(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Zo(r,e){return new Promise((i,a)=>{let c=Ju(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 Zn,es,ts,Qo=Le(()=>{"use strict";H();Zn=R("supervisor.launchd"),es="ai.coze.bridge",ts={platform:"darwin",renderConfig(r){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
18
18
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
19
19
|
<plist version="1.0">
|
|
20
20
|
<dict>
|
|
21
21
|
<key>Label</key>
|
|
22
|
-
<string>${
|
|
22
|
+
<string>${es}</string>
|
|
23
23
|
<key>ProgramArguments</key>
|
|
24
24
|
<array>
|
|
25
|
-
<string>${
|
|
26
|
-
<string>${
|
|
25
|
+
<string>${Qn(r.nodeBin)}</string>
|
|
26
|
+
<string>${Qn(r.entry)}</string>
|
|
27
27
|
<string>--daemon</string>
|
|
28
28
|
</array>
|
|
29
29
|
<key>RunAtLoad</key>
|
|
@@ -33,12 +33,12 @@ var $o=Object.create;var xr=Object.defineProperty;var zo=Object.getOwnPropertyDe
|
|
|
33
33
|
<key>ThrottleInterval</key>
|
|
34
34
|
<integer>10</integer>
|
|
35
35
|
<key>StandardOutPath</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${Qn(r.logFile)}</string>
|
|
37
37
|
<key>StandardErrorPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${Qn(r.logFile)}</string>
|
|
39
39
|
</dict>
|
|
40
40
|
</plist>
|
|
41
|
-
`},configPath(r){return
|
|
41
|
+
`},configPath(r){return Zu(r.homeDir,"Library","LaunchAgents",`${es}.plist`)},async install(r){let e=this.configPath(r);await Vu($u(e),{recursive:!0}),await Yu(e,this.renderConfig(r),"utf8"),Zn.info("plist written",{plistPath:e}),await Zo("launchctl",["load","-w",e]),Zn.info("launchd job loaded",{label:es})},async uninstall(r){let e=this.configPath(r);await Zo("launchctl",["unload","-w",e]).catch(i=>Zn.warn("launchctl unload failed (ignored)",{err:String(i)})),await Xu(e).catch(i=>{if(i.code!=="ENOENT")throw i}),Zn.info("launchd job removed",{plistPath:e})}}});import{spawn as Qu}from"node:child_process";import{mkdir as ef,unlink as tf,writeFile as nf}from"node:fs/promises";import{dirname as rf,join as sf}from"node:path";function nr(r,e){return new Promise((i,a)=>{let c=Qu(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 er,tr,ns,ea=Le(()=>{"use strict";H();er=R("supervisor.systemd"),tr="coze-bridge.service",ns={platform:"linux",renderConfig(r){return`[Unit]
|
|
42
42
|
Description=Coze Bridge daemon
|
|
43
43
|
After=network.target
|
|
44
44
|
|
|
@@ -52,7 +52,7 @@ StandardError=append:${r.logFile}
|
|
|
52
52
|
|
|
53
53
|
[Install]
|
|
54
54
|
WantedBy=default.target
|
|
55
|
-
`},configPath(r){return
|
|
55
|
+
`},configPath(r){return sf(r.homeDir,".config","systemd","user",tr)},async install(r){let e=this.configPath(r);await ef(rf(e),{recursive:!0}),await nf(e,this.renderConfig(r),"utf8"),er.info("systemd unit written",{unitPath:e}),await nr("systemctl",["--user","daemon-reload"]),await nr("systemctl",["--user","enable","--now",tr]),er.info("systemd unit enabled",{unitName:tr})},async uninstall(r){let e=this.configPath(r);await nr("systemctl",["--user","disable","--now",tr]).catch(i=>er.warn("systemctl disable failed (ignored)",{err:String(i)})),await tf(e).catch(i=>{if(i.code!=="ENOENT")throw i}),await nr("systemctl",["--user","daemon-reload"]).catch(()=>{}),er.info("systemd unit removed",{unitPath:e})}}});import{spawn as of}from"node:child_process";import{join as af}from"node:path";function ta(r,e){return new Promise((i,a)=>{let c=of(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 rs,rr,ss,na=Le(()=>{"use strict";H();rs=R("supervisor.taskscheduler"),rr="CozeBridge",ss={platform:"win32",renderConfig(r){return`<?xml version="1.0" encoding="UTF-16"?>
|
|
56
56
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
57
57
|
<RegistrationInfo>
|
|
58
58
|
<Description>Coze Bridge daemon</Description>
|
|
@@ -76,21 +76,21 @@ WantedBy=default.target
|
|
|
76
76
|
</Exec>
|
|
77
77
|
</Actions>
|
|
78
78
|
</Task>
|
|
79
|
-
`},configPath(r){return
|
|
79
|
+
`},configPath(r){return af(r.homeDir,".coze","bridge","task.xml")},async install(r){let e=`"${r.nodeBin}" "${r.entry}" --daemon`;await ta("schtasks",["/Create","/SC","ONLOGON","/TN",rr,"/TR",e,"/RU",r.userName,"/F"]),rs.info("task scheduler entry created",{task:rr})},async uninstall(r){await ta("schtasks",["/Delete","/TN",rr,"/F"]).catch(e=>rs.warn("schtasks /Delete failed (ignored)",{err:String(e)})),rs.info("task scheduler entry removed",{task:rr})}}});var is={};Ds(is,{buildContext:()=>ff,getSupervisor:()=>uf,launchdSupervisor:()=>ts,systemdSupervisor:()=>ns,taskSchedulerSupervisor:()=>ss});import{homedir as xf,userInfo as cf}from"node:os";function uf(r=process.platform){switch(r){case"darwin":return ts;case"linux":return ns;case"win32":return ss;default:throw new Error(`unsupported platform for OS supervisor: ${r}`)}}function ff(){let r=K();return{nodeBin:process.execPath,entry:Yr(r),logFile:r.logFile,homeDir:xf(),userName:cf().username}}var os=Le(()=>{"use strict";fe();$r();Qo();ea();na()});Ge();H();import{readdir as _0}from"node:fs/promises";import{mkdir as l0,writeFile as h0}from"node:fs/promises";import{join as g0}from"node:path";var p0={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ut(r,e,i,a){await l0(r,{recursive:!0});let c=p0[e],u=g0(r,c),d=m0(e,i,a);return await h0(u,d,"utf8"),u}function m0(r,e,i){let a=`# Coze Agent: ${e}
|
|
80
80
|
|
|
81
81
|
> framework: \`${r}\`
|
|
82
82
|
|
|
83
|
-
`,
|
|
84
|
-
`)?
|
|
83
|
+
`,c=i?.trim()?i.endsWith(`
|
|
84
|
+
`)?i:`${i}
|
|
85
85
|
`:`_No instructions provided._
|
|
86
|
-
`;return`${
|
|
86
|
+
`;return`${a}---
|
|
87
87
|
|
|
88
|
-
${
|
|
89
|
-
`)}}function gs(r,e){if(!r.modelToken)return[];let t=fs(e),n=[];for(let[s,i]of Object.entries(t))n.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return n}var M=w("agent-handlers"),ps=5*1024*1024,wa=1,ya=6,Sa=new Set(["node_modules",".git",".coze","dist","build",".next"]),Nt=class{constructor(e){this.opts=e}opts;async listSkills(e){se(e._meta,"_agent/listSkills");let t=De(e._meta),n=await this.loadAgentCfg(t),s=n?.workspace??ne(t).workspace,i=n?.skills??[],o=[];for(let a of i){let c=ie(s,a.relPath,"SKILL.md");await ga(c).then(l=>l.isFile()).catch(()=>!1)&&o.push({skillId:a.skillId,skillName:a.skillName,downloadUrl:a.downloadUrl??"",...a.description?{description:a.description}:{},...a.version?{version:a.version}:{}})}return{skills:o}}async addSkills(e){se(e._meta,"_agent/addSkills");let t=De(e._meta),n=await this.requireAgentCfg(t),s=e.skills??[],i=[...n.skills??[]],o=new Map(i.map((c,d)=>[c.skillId,d])),a=[];for(let c of s){if(!c.skillName)throw new h("IPC_BAD_REQUEST","skill missing skillName");let d=Ea(c.skillName),l=va(n.framework),u=ie(l,d),f=ie(n.workspace,u);await ua(f,{recursive:!0});let m=await Ia(c.downloadUrl);Ra(m)?await Pa(m,f):await pa(ie(f,"SKILL.md"),m.toString("utf8"),"utf8");let p={skillId:c.skillId,skillName:c.skillName,relPath:u,installedAt:Date.now(),...c.description?{description:c.description}:{},...c.version?{version:c.version}:{},...c.downloadUrl?{downloadUrl:c.downloadUrl}:{}},_=o.get(c.skillId);_!==void 0?i[_]=p:(o.set(c.skillId,i.length),i.push(p)),a.push(c),M.info("skill installed",{agentId:t,skillId:c.skillId,skillName:c.skillName,relPath:u})}return await xt(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){se(e._meta,"_agent/removeSkills");let t=De(e._meta),n=await this.requireAgentCfg(t),s=new Set(e.skillIds??[]),i=n.skills??[],o=[];for(let a of i){if(!s.has(a.skillId)){o.push(a);continue}let c=ie(n.workspace,a.relPath);await ha(c,{recursive:!0,force:!0}),M.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await xt(t,o),await this.reloadAgentSessions(t,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,t){return this.reloadAgentSessions(e,t)}async reloadAgentSessions(e,t){let n=this.opts.agents.get(e);if(n&&n.framework!=="codex"){for(let[s,i]of n.sessions)if(!(!i.downstream||!i.acpSessionId)){i.loadingSession=!0;try{await i.downstream.sessionLoad({sessionId:i.acpSessionId,cwd:n.workspace}),M.info("session reloaded",{reason:t,agentId:e,framework:n.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){M.warn("session reload failed",{reason:t,agentId:e,framework:n.framework,cloudId:s,acpId:i.acpSessionId,err:String(o)})}finally{i.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return M.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,n=await U(t);if(!n)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return n.cozeIdentity===e.cozeIdentity?(M.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(n.cozeIdentity=e.cozeIdentity,await J(n),await be(n.workspace,n.framework,t,e.cozeIdentity),M.info("_agent/update: cozeIdentity rewritten",{agentId:t,framework:n.framework}),await this.reloadAgentSessions(t,"identity-changed"),{ok:!0})}async disconnectAgent(e){let t=e.agentId;if(!t)throw new h("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let n=await U(t);return n?(n.disconnectedAt=Date.now(),n.disconnectReason=e.reason??"",await J(n),M.info("agent disconnected",{agentId:t,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(t,e.reason??"disconnect"),{ok:!0}):(M.warn("_agent/disconnect: agent not found, ignoring",{agentId:t}),{ok:!0})}async switchModel(e){if(se(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:Le,n=await U(e.agentId);if(!n)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);n.model=t,await J(n),M.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);return s?(await s.msgQueue.enqueue(async()=>{s.model=t,await s.killAllRuntimes(`switchModel: ${t}`)}),M.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:t}),{ok:!0}):(M.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0})}async resetAgent(e){if(se(e._meta,X.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${X.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,X.RESET,e.reason),{ok:!0}}async repairAgent(e){if(se(e._meta,X.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${X.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${X.REPAIR} only allowed for openclaw, got ${t.framework}`);return await this.runDetailSync(e.agentId,X.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,n){if(!this.opts.detailSyncer){M.warn("detailSyncer not wired, skipping sync",{method:t,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(s){M.warn("detail sync failed (ignored)",{method:t,agentId:e,reason:n,err:String(s)})}}async getFileTree(e){se(e._meta,"_agent/getFileTree");let t=e._meta,n=De(t),s=await this.resolveWorkspace(n),i=e.filePath??"",o=this.safeJoin(s,i),a=await Ar(o).catch(()=>null);if(!a)throw new h("IPC_BAD_REQUEST",`path not found: ${i}`);if(a.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${i}`);let c=Ca(e.depth);return a.isDirectory()?{tree:await Ss(s,o,i,c)}:{tree:[{name:Oa(i),path:Es(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){se(e._meta,"_agent/getFileContent");let t=De(e._meta),n=await this.resolveWorkspace(t);if(!e.filePath)throw new h("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(n,e.filePath),i=await Ar(s).catch(()=>null);if(!i||!i.isFile())throw new h("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(i.isSymbolicLink())throw new h("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(i.size>ps)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${ps})`);let o=await _s(s);return o.includes(0)?{content:o.toString("base64"),encoding:"base64",size:i.size}:{content:o.toString("utf8"),encoding:"utf-8",size:i.size}}async resolveWorkspace(e){let t=this.opts.agents.get(e);return t?t.workspace:(await U(e).catch(()=>null))?.workspace??ne(e).workspace}safeJoin(e,t){let n=_a(e,t||"."),s=ws(e,n);if(s.startsWith("..")||s===".."||s.startsWith(`..${ys}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return n}loadAgentCfg(e){return U(e)}async requireAgentCfg(e){let t=await this.loadAgentCfg(e);if(!t)throw new h("AGENT_NOT_FOUND",`no config for agent: ${e}`);return t}};function Ea(r){let e=Rt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function va(r){return r==="claude-code"?ie(".claude","skills"):ie(".agents","skills")}var ka=3e4,xa=50*1024*1024,bt=3e4;async function Ia(r){if(!r)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);Ot(e);let t=Ta(r);return Ot(t.length),t}if(r.startsWith("file:")){let e=new URL(r).pathname,t=await _s(e);return Ot(t.length),t}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),ka);try{let n=await fetch(r,{signal:e.signal});if(!n.ok)throw new h("IPC_BAD_REQUEST",`fetch skill failed HTTP ${n.status} ${r}`);let s=await n.arrayBuffer();return Ot(s.byteLength),Buffer.from(s)}finally{clearTimeout(t)}}throw new h("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function Ot(r){if(r>xa)throw new h("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function Ta(r){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(r);if(!e)throw new h("IPC_BAD_REQUEST","bad data URL");let t=!!e[2],n=e[3]??"";return t?Buffer.from(n,"base64"):Buffer.from(decodeURIComponent(n),"utf8")}function Ra(r){return r.length>=2&&r[0]===31&&r[1]===139}async function Pa(r,e){await Aa(r),await new Promise((t,n)=>{let s=ms("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),i="";s.stderr?.on("data",a=>{i+=String(a)});let o=setTimeout(()=>{s.kill("SIGKILL"),n(new h("IPC_BAD_REQUEST",`tar extract timeout (${bt}ms)`))},bt);s.on("error",a=>{clearTimeout(o),n(new h("IPC_BAD_REQUEST",`tar spawn failed: ${a.message}`,{cause:a}))}),s.on("exit",a=>{clearTimeout(o),a===0?t():n(new h("IPC_BAD_REQUEST",`tar exit ${a}${i?`: ${i.trim().slice(0,200)}`:""}`))}),s.stdin?.end(r)})}async function Aa(r){let e=await new Promise((t,n)=>{let s=ms("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),i="",o="";s.stdout?.on("data",c=>{i+=String(c)}),s.stderr?.on("data",c=>{o+=String(c)});let a=setTimeout(()=>{s.kill("SIGKILL"),n(new h("IPC_BAD_REQUEST",`tar list timeout (${bt}ms)`))},bt);s.on("error",c=>{clearTimeout(a),n(new h("IPC_BAD_REQUEST",`tar list spawn failed: ${c.message}`))}),s.on("exit",c=>{clearTimeout(a),c===0?t(i):n(new h("IPC_BAD_REQUEST",`tar list exit ${c}${o?`: ${o.trim().slice(0,200)}`:""}`))}),s.stdin?.end(r)});for(let t of e.split(`
|
|
90
|
-
`)){let
|
|
91
|
-
`}var
|
|
92
|
-
`);this.buffer=t.pop()??"";let n=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{n.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return n}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(t){return this.onError?.({line:e,error:t}),[]}}};var Rs={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},dh=Object.fromEntries(Object.entries(Rs).map(([r,e])=>[e,r])),La={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},Be=class{seq=0;next(e,t){this.seq+=1;let n=Rs[e]??Ma(e),s=La[n]??[],i=[n,String(this.seq)];if(s.length>0){let o=s.map(c=>Ts(t?.[c]??"")),a=Ba(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>Ts(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function Ma(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Ts(r){return r.replace(/[:_\s]+/g,"-")}function Ba(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}k();var Ua=3e4;function Ps(r,e){if(!(typeof r!="number"||r<=0))try{process.platform==="win32"?process.kill(r,e):process.kill(-r,e)}catch{}}var fe=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Ut({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Be;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;sanitizeEnv(e){return e}async start(){if(this.child)throw new h("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",t=Fa(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=t,t.stdout?.setEncoding("utf8"),t.stdout?.on("data",n=>{for(let s of this.decoder.push(n))this.dispatch(s)}),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",n=>{this.log.debug("stderr",{text:n.trimEnd()})}),t.on("exit",(n,s)=>{this.stopped=!0,this.failAllPending(new h("AGENT_PROTOCOL_ERROR",`agent exited (${n}/${s})`));for(let i of this.exitHandlers)i(n,s)}),t.on("error",n=>{this.log.error("child error",{err:String(n)}),this.failAllPending(new h("AGENT_SPAWN_FAILED",String(n),{cause:n}))}),this.log.info("downstream started",{command:this.opts.command,pid:t.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let t=this.child,n=new Promise(i=>t.once("exit",()=>i()));Ps(t.pid,"SIGTERM");let s=setTimeout(()=>{t.killed||Ps(t.pid,"SIGKILL")},5e3);try{await n}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Lt("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Me(e,t))}catch(n){this.log.warn("respondAgentRequest write failed",{id:e,err:String(n)})}}respondAgentRequestError(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(Se(e,t))}catch(n){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(n)})}}onExit(e){this.exitHandlers.push(e)}call(e,t,n=Ua){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=Ze(s,e,t),o=n>0&&Number.isFinite(n);return new Promise((a,c)=>{let d=o?setTimeout(()=>{this.pending.delete(s),c(new h("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n):null;this.pending.set(s,{resolve:a,reject:c,timer:d,method:e});try{this.writeFrame(i)}catch(l){d&&clearTimeout(d),this.pending.delete(s),c(l)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new h("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Is(e))}dispatch(e){if(Bt(e)){let t=e.id!==null?this.pending.get(e.id):void 0;if(!t){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),t.timer&&clearTimeout(t.timer),e.error?t.reject(xs(e.error)):t.resolve(e.result);return}if(ks(e)){if(e.method==="session/update")for(let t of this.updateHandlers)Promise.resolve(t(e.params)).catch(n=>this.log.warn("update handler failed",{err:String(n)}));else this.log.debug("unknown notification",{method:e.method});return}if(vs(e)){let t=e;this.handleAgentRequest(t).catch(n=>this.log.error("agent request handler failed",{method:t.method,err:String(n)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Se(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let t of this.agentRequestHandlers)try{await t(e)}catch(n){this.log.error("agentRequestHandler threw",{method:e.method,err:String(n)});try{this.writeFrame(Se(e.id,Ft(n)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var $a="@agentclientprotocol/claude-agent-acp@latest";function za(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&(t.startsWith("CLAUDE")||t==="AI_AGENT"||t==="BAGGAGE"||(e[t]=n));return e}var $t=class extends fe{framework="claude-code";constructor(e){let t=e.command??"npx",n=e.args??["-y",$a],s={command:t,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(s)}sanitizeEnv(e){return za(e)}};import{mkdtempSync as qa,rmSync as Ga}from"node:fs";import{tmpdir as Ha}from"node:os";import{join as Wa}from"node:path";var ja="@zed-industries/codex-acp@latest",zt=class extends fe{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=e.command??"npx",n=e.args??["-y",ja],s=e.extraArgs?[...n,...e.extraArgs]:n,i=e.isolateCodexHome?qa(Wa(Ha(),"coze-bridge-codex-home-")):void 0,o=i?{...e.env??{},CODEX_HOME:i}:e.env,a={command:t,args:s,cwd:e.cwd,...o?{env:o}:{}};super(a),this.authMethodId=e.authMethodId,this.codexHomeDir=i}async initialize(e){let t=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),t}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Ga(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};import{spawn as As}from"node:child_process";k();var qt=class extends fe{framework="openclaw";registerLog;profile;agentId;sessionName;registered=!1;constructor(e){let t=e.profile??"coze",n=e.sessionName??"default",s=["--profile",t,"acp","--session",`agent:${e.agentId}:${n}`],i={command:e.command,args:s,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i),this.profile=t,this.agentId=e.agentId,this.sessionName=n,this.registerLog=w("downstream.openclaw.register")}async start(){await this.registerAgent().catch(e=>{this.registerLog.warn("openclaw agents add failed (will continue to acp anyway)",{agentId:this.agentId,err:String(e)})}),await super.start()}registerAgent(){return new Promise((e,t)=>{let n=As(this.opts.command,["--profile",this.profile,"agents","add",this.agentId,"--workspace",this.opts.cwd,"--non-interactive"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),s="";n.stderr?.on("data",i=>{s+=i.toString("utf8")}),n.on("error",t),n.on("close",i=>{i===0?(this.registered=!0,this.registerLog.info("agent registered",{agentId:this.agentId,profile:this.profile}),e()):t(new h("AGENT_SPAWN_FAILED",`openclaw agents add ${this.agentId} exited ${i}: ${s.trim()}`))})})}async cleanup(e){this.registered&&await new Promise(t=>{let n=As(this.opts.command,["--profile",this.profile,"agents","delete",this.agentId,"--force"],{stdio:["ignore","pipe","pipe"],env:{...process.env,...this.opts.env}}),s="";n.stderr?.on("data",i=>{s+=i.toString("utf8")}),n.on("error",i=>{this.registerLog.warn("openclaw agents delete failed (best-effort)",{agentId:this.agentId,err:String(i)}),t()}),n.on("close",i=>{i===0?this.registerLog.info("agent unregistered",{agentId:this.agentId}):this.registerLog.warn("openclaw agents delete non-zero exit",{agentId:this.agentId,code:i,stderr:s.trim()}),this.registered=!1,t()})})}get acpSessionName(){return this.sessionName}};k();F();var Gt=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((t,n)=>{this.slots.push({task:e,resolve:t,reject:n}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}}finally{this.running=!1}}}};var Ht=class{agentId;framework;workspace;deployType;msgQueue;sessions=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",this.msgQueue=new Gt}async dispose(e){this.status="stopped",this.msgQueue.dispose(new Error(`AgentSession disposed${e?`: ${e}`:""}`)),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let t=[];for(let[,n]of this.sessions)et(n),n.downstream&&(t.push(n.downstream.stop(e).catch(()=>{})),n.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function et(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}var he=w("agent-manager"),Va=(r,e,t,n,s,i,o)=>{switch(r){case"claude-code":{let a=s?{...ds(s),...hs(s,o)}:void 0;return new $t({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...ls(s),...gs(s,o)]:[],c=s?us(s):void 0,d=!!s;return new zt({cwd:t,...a.length>0?{extraArgs:a}:{},...c&&Object.keys(c).length>0?{env:c}:{},...d?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new qt({command:e,cwd:t,agentId:n,...i?{sessionName:Rt(i)}:{}})}};function Qa(r){return r==="claude-code"||r==="codex"}var Ka={path:"",version:"cloud-deployed"},Xa={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Ya=2e4,Wt=class{paths;config;registry;factory;createTimeoutMs;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Va,this.createTimeoutMs=e.createTimeoutMs??Ya}async createAgent(e){if(!e.agentId)throw new h("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new h("IPC_BAD_REQUEST","framework required");let t=Xe(e._meta)==="cloud";if(t&&e.framework==="openclaw")return he.info("cloud-deployed openclaw, ack without local spawn",{agentId:e.agentId,framework:e.framework}),{ok:!0,agentId:e.agentId,framework:e.framework};this.registry.reviveIfDisconnected?.(e.agentId);let n=this.registry.get(e.agentId);if(n){if(n.framework!==e.framework)throw new h("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${n.framework})`);if(n.status==="error")he.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await n.dispose("rebuild after error").catch(u=>he.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else return he.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:n.agentId,workspace:n.workspace,framework:n.framework}}if(!t&&!this.config.frameworksCache?.[e.framework])throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let s=ne(e.agentId,this.paths),i=e.workspace??s.workspace,o=Xe(e._meta),a=new AbortController,c=setTimeout(()=>a.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),d,l=!1;try{let u=()=>{if(a.signal.aborted)throw a.signal.reason instanceof Error?a.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await Cr(s.root,{recursive:!0}),await Cr(i,{recursive:!0}),await Cr(s.logs,{recursive:!0}),u(),await be(i,e.framework,e.agentId,e.cozeIdentity),u();let f=await U(e.agentId,this.paths).catch(()=>null),m=as({model:e.model??f?.model});if(d=new Ht({agentId:e.agentId,framework:e.framework,workspace:i,model:m.model??Le,deployType:o}),d.status="ok",f?.sessions){for(let[S,O]of Object.entries(f.sessions))d.sessions.set(S,{acpSessionId:O.acpSessionId,modelToken:O.modelToken,tokenGeneratedAt:O.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let _=Object.keys(f.sessions).length;_>0&&he.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:_})}this.registry.register(d),l=!0;let p={agentId:e.agentId,framework:e.framework,workspace:i,cozeIdentity:e.cozeIdentity,createdAt:f?.createdAt??Date.now(),sessions:f?.sessions??{},model:m.model};return o==="cloud"&&(p.deployType="cloud"),f?.skills&&(p.skills=f.skills),f?.agentName&&(p.agentName=f.agentName),f?.description&&(p.description=f.description),await J(p,this.paths),he.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:o}),{ok:!0,agentId:e.agentId,workspace:i,framework:e.framework}}catch(u){throw he.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),l&&d&&(await d.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ja(s.root,{recursive:!0,force:!0}).catch(f=>he.warn("rm agent dir failed (ignored)",{err:String(f)})),u instanceof h?u:new h("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(c)}}async spawnSessionDownstream(e,t,n,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&Qa(e.framework))o=Ka;else throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let a=e.deployType==="cloud"?{model:e.model,modelToken:t}:void 0,c=this.factory(e.framework,o.path,e.workspace,e.agentId,a,n,s);try{return await c.start(),await c.initialize(Xa),c}catch(d){throw await c.stop("spawnSessionDownstream failed").catch(()=>{}),d instanceof h?d:new h("AGENT_SPAWN_FAILED",d instanceof Error?d.message:String(d),{cause:d})}}};k();import{spawn as Za}from"node:child_process";import{constants as Cs,access as ec}from"node:fs/promises";import{delimiter as tc,join as rc}from"node:path";var nc=w("framework-detector"),Os={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sc=[".exe",".cmd",".bat",".ps1"],rt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Za,access:e.access??ec}}async detect(e){let t=Os[e],n=await this.which(t);if(!n)return nc.debug("framework binary not found",{framework:e,bin:t}),null;let s=await this.probeVersion(n);return{path:n,version:s}}async detectAll(){let e=await Promise.all(Object.keys(Os).map(async n=>[n,await this.detect(n)])),t={};for(let[n,s]of e)s&&(t[n]=s);return t}async which(e){let t=this.env.pathEnv.split(tc).filter(Boolean),n=this.env.platform==="win32"?["",...sc]:[""];for(let s of t)for(let i of n){let o=rc(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?Cs.F_OK:Cs.X_OK;return await this.env.access(e,t),!0}catch{return!1}}async probeVersion(e){return new Promise(t=>{let n="",s=!1,i,o=a=>{s||(s=!0,i&&clearTimeout(i),t(a.trim()||"unknown"))};try{let a=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});i=setTimeout(()=>{a.kill("SIGKILL"),o("unknown")},5e3),a.stdout?.on("data",c=>{n+=c.toString("utf8")}),a.on("error",()=>o("unknown")),a.on("close",()=>{let c=oc(n).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},ic=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function oc(r){return r.replace(ic,"")}Tr();F();var ac=10*6e4;function Ns(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ac:e}function jt(r){return yt(r??x().configFile)}function nt(r,e){return St(e??x().configFile,r)}import{randomBytes as cc}from"node:crypto";ue();k();var I=w("core"),dc=3e4,lc=3e4,Jt=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Be;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=Ns(e.bridgeConfig)}registerExtension(e,t){this.extensions[e]=t}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),I.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){I.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(t=>t.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),I.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(n){I.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(n)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&I.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,t,n){let s=n.downstream;s&&(s.onUpdate(i=>{n.loadingSession||this.forwardUpdate(e,i)}),s.onAgentRequest(i=>{this.handleAgentRequest(e,s,i)}),s.onExit((i,o)=>{I.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),et(n),n.downstream=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId)}))}async handleFrame(e){if(Bt(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let t="id"in e&&e.id!==void 0?e.id:null,n=e.params?._meta?.cozeEnv;n&&(this.currentCozeEnv=n);try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):I.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Me(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Me(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Me(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):I.warn("drop unknown notification",{method:e.method})}catch(s){I.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(Se(t,Ft(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new h("IPC_BAD_REQUEST",`${e.method} requires params`);let t=e.params,n=t._meta?.cozeAgentId;if(!n)throw new h("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(n);if(!s)throw this.disconnectedAgents.has(n)?new h("AGENT_DISCONNECTED",`agent ${n} has been disconnected; cloud must _agent/create to revive`):new h("AGENT_NOT_FOUND",`agent not found: ${n}`);if(e.method==="session/cancel")return this.dispatchSessionCall(s,e.method,t);let i=Date.now(),o=!1;try{let a=await s.msgQueue.enqueue(()=>this.dispatchSessionCall(s,e.method,t));return o=!0,a}finally{I.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-i,ok:o})}}async dispatchSessionCall(e,t,n){e.lastActiveAt=Date.now();let{stripped:s}=Xn(n);switch(t){case"session/new":{let i=uc();return I.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return I.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:i.sessionId}),{}}case"session/prompt":{let i=s,o=i.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new h("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=n._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);try{let d=await a.downstream.sessionPrompt({...i,sessionId:a.acpSessionId});return a.lastActiveAt=Date.now(),d}finally{e.activeTriggers.delete(a.acpSessionId),a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=s.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new h("IPC_BAD_REQUEST",`session method not supported: ${t}`)}}async ensureRuntime(e,t){let n=e.sessions.get(t);if(n)return n;let i={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,t):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(t,i),await this.persistSessionMapping(e),i}async requestSessionToken(e,t){let n={sessionId:t,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(X.GEN_MODEL_TOKEN,n,lc);if(!s?.modelToken)throw new h("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${t})`);return s.modelToken}catch(s){throw s instanceof h&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new h("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,t,n){if(et(n),n.downstream?.isAlive())return;if(!this.sessionSpawner)throw new h("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=await this.sessionSpawner(e,n.modelToken,t,this.currentCozeEnv);if(n.downstream=s,this.attachRuntimeHooks(e,t,n),n.acpSessionId){n.loadingSession=!0;try{await s.sessionLoad({sessionId:n.acpSessionId,cwd:e.workspace}),I.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:n.acpSessionId})}catch(i){I.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:t,acpId:n.acpSessionId,err:String(i)}),n.acpSessionId=void 0;let o=await s.sessionNew({cwd:e.workspace});n.acpSessionId=o.sessionId,await this.persistSessionMapping(e)}finally{n.loadingSession=!1}}else{let i=await s.sessionNew({cwd:e.workspace});n.acpSessionId=i.sessionId,await this.persistSessionMapping(e)}}armIdleTimer(e,t,n){et(n),n.idleTimer=setTimeout(()=>{I.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:t});let s=n.downstream;n.downstream=void 0,n.idleTimer=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),s&&s.stop("idle timeout").catch(i=>I.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:t,err:String(i)}))},this.sessionIdleTimeoutMs),n.idleTimer.unref?.()}forwardUpdate(e,t){let n=t.sessionId,s=this.reverseSessionId(e,n);if(!s){I.debug("drop update for unknown session",{agentId:e.agentId,acpId:n});return}let i=e.sessions.get(s);if(!i){I.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++i.replySeq},a=e.activeTriggers.get(n);a&&(o.cozeTriggerMsgId=a),this.upstream.send(Lt("session/update",{...t,sessionId:s,_meta:o})).catch(c=>I.warn("forward update failed",{agentId:e.agentId,err:String(c)}))}handleAgentRequest(e,t,n){if(n.method==="session/request_permission"){this.forwardPermissionRequest(e,t,n);return}I.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:n.method}),t.respondAgentRequestError(n.id,{code:R.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${n.method}`})}forwardPermissionRequest(e,t,n){let s=this.upstreamIds.next("session/request_permission"),i=n.params??{},a=i.sessionId,c=a?e.activeTriggers.get(a):void 0,d={cozeAgentId:e.agentId};c&&(d.cozeTriggerMsgId=c);let l=a?this.reverseSessionId(e,a):void 0,u={...i,...l?{sessionId:l}:{},_meta:d};this.pendingUpstream.set(s,{agentRequestId:n.id,agentId:e.agentId,downstream:t,method:n.method}),this.upstream.send(Ze(s,"session/request_permission",u)).catch(f=>{this.pendingUpstream.delete(s),I.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),t.respondAgentRequestError(n.id,{code:R.INTERNAL_ERROR,message:`upstream send failed: ${String(f)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let t=this.pendingUpstream.get(e.id);if(t){this.pendingUpstream.delete(e.id),e.error?t.downstream.respondAgentRequestError(t.agentRequestId,e.error):t.downstream.respondAgentRequest(t.agentRequestId,e.result);return}let n=this.pendingBridge.get(e.id);if(n){this.pendingBridge.delete(e.id),clearTimeout(n.timer),e.error?n.reject(new Mt(e.error)):n.resolve(e.result);return}I.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,n=dc){let s=this.upstreamIds.next(e);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(s),o(new h("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n);this.pendingBridge.set(s,{method:e,resolve:i,reject:o,timer:a}),this.upstream.send(Ze(s,e,t)).catch(c=>{let d=this.pendingBridge.get(s);d&&(clearTimeout(d.timer),this.pendingBridge.delete(s)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let t=new Map;for(let[n,s]of e.sessions){let i={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(i.acpSessionId=s.acpSessionId),t.set(n,i)}await Pr(e.agentId,t,this.paths)}catch(t){I.warn("persist session mapping failed",{agentId:e.agentId,err:String(t)})}}reverseSessionId(e,t){for(let[n,s]of e.sessions.entries())if(s.acpSessionId===t)return n}sendError(e,t,n){return this.upstream.send(Se(e,{code:t,message:n}))}};function uc(){return cc(16).toString("hex")}k();F();import{randomBytes as fc}from"node:crypto";import{chmod as hc,mkdir as gc,writeFile as bs}from"node:fs/promises";import{createServer as pc}from"node:http";import{dirname as mc}from"node:path";var _c=1e6,Or=w("ipc"),Vt=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(t=>[`${t.method} ${t.path}`,t])),this.paths=e.paths??x()}async start(){this.token=fc(32).toString("hex");let e=pc((n,s)=>{this.dispatch(n,s)});this.server=e,await new Promise((n,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>n())});let t=e.address();if(!t||typeof t!="object")throw new Error("failed to obtain IPC port");return this.port=t.port,await this.persistAuthFiles(),Or.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((t,n)=>{e.close(s=>s?n(s):t())}),this.server=null)}async persistAuthFiles(){await gc(mc(this.paths.portFile),{recursive:!0}),await bs(this.paths.portFile,String(this.port),"utf8"),await bs(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await hc(this.paths.tokenFile,384)}catch(e){Or.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){st(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){st(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await wc(e)}catch(a){st(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);st(t,200,a??{ok:!0})}catch(a){Or.error("IPC handler failed",{key:s,err:String(a)}),st(t,500,{error:a instanceof Error?a.message:String(a)})}}};function st(r,e,t){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(t))}async function wc(r){let e=[],t=0;for await(let s of r){let i=s;if(t+=i.length,t>_c)throw new Error("body too large");e.push(i)}let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):null}var qs="";function Cc(r=""){let t=`${Date.now()}`,n=qs||(qs=Dc(r)),s=Math.random().toString(16).slice(-6);return"02"+t+n+s}function Oc(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Nc(r){return(Array(8).join("0")+parseInt(r,10).toString(2)).slice(-8)}function Gs(r){return(Array(4).join("0")+parseInt(r,2).toString(16)).slice(-4)}function bc(r){let e=r.split(/\./).map(s=>Nc(s)),t=[];return t[0]=Gs(e[0]+e[1]),t[1]=Gs(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function Dc(r){let e=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(r),t=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(r);return e?bc(r):t?Lc(r):"00000000000000000000000000000000"}function Lc(r){let e="",t=[],n=0,s=0,i=!0,o="0000";if(r.indexOf("::")>-1){let a=r.split("::");for(let d=0;d<a.length;d++){let l=a[d];if(l.indexOf(":")>0){let u=l.split(":");i&&(n=u.length),s+=u.length;for(let f=0;f<u.length;f++)if(u[f].length!==4){let p=o.substring(0,4-u[f].length).concat(u[f]);t.push(p)}else t.push(u[f]);i=!1}else{if(l.length!==4){let f=o.substring(0,4-l.length).concat(l);t.push(f)}else t.push(l);i&&(n+=1),s+=1,i=!1}}let c="";for(let d=0;d<8-s;d++)c=c.concat(o);for(let d=0;d<t.length;d++)d===n&&(e=e.concat(c)),e=e.concat(t[d]);return e}{let a=r.split(":");for(let c=0;c<a.length;c++){let d=a[c];if(a[c].length!==4){let u=o.substring(0,4-a[c].length).concat(d);e=e.concat(u)}else e=e.concat(d)}return e}}function Mc(r,e){let t=r.key;t!==void 0&&(C(e,10),ke(e,t));let n=r.value;n!==void 0&&(C(e,18),ke(e,n))}function Bc(r){let e={};e:for(;!ni(r);){let t=b(r);switch(t>>>3){case 0:break e;case 1:e.key=ve(r,b(r));break;case 2:e.value=ve(r,b(r));break;default:ei(r,7&t)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function Zs(r){let e=ri();return Fc(r,e),Hc(e)}function Fc(r,e){let t=r.SeqID;t!==void 0&&(C(e,8),ot(e,t));let n=r.LogID;n!==void 0&&(C(e,16),ot(e,n));let s=r.service;s!==void 0&&(C(e,24),ot(e,Fr(s)));let i=r.method;i!==void 0&&(C(e,32),ot(e,Fr(i)));let o=r.headers;if(o!==void 0)for(let p of o){C(e,42);let _=ri();Mc(p,_),C(e,_.limit),Jc(e,_),qc(_)}let a=r.payloadEncoding;a!==void 0&&(C(e,50),ke(e,a));let c=r.payloadType;c!==void 0&&(C(e,58),ke(e,c));let d=r.payload;d!==void 0&&(C(e,66),C(e,d.length),jc(e,d));let l=r.LogIDNew;l!==void 0&&(C(e,74),ke(e,l));let u=r.serverTiming;u!==void 0&&(C(e,82),ke(e,u));let f=r.msgID;f!==void 0&&(C(e,90),ke(e,f));let m=r.frameType;m!==void 0&&(C(e,96),ot(e,Fr(m)))}function Uc(r){return $c(Gc(r))}function $c(r){let e={};e:for(;!ni(r);){let t=b(r);switch(t>>>3){case 0:break e;case 1:e.SeqID=Ws(r,!0);break;case 2:e.LogID=Ws(r,!0);break;case 3:e.service=b(r);break;case 4:e.method=b(r);break;case 5:{let n=zc(r);(e.headers||(e.headers=[])).push(Bc(r)),r.limit=n;break}case 6:e.payloadEncoding=ve(r,b(r));break;case 7:e.payloadType=ve(r,b(r));break;case 8:e.payload=Wc(r,b(r));break;case 9:e.LogIDNew=ve(r,b(r));break;case 10:e.serverTiming=ve(r,b(r));break;case 11:e.msgID=ve(r,b(r));break;case 12:e.frameType=b(r);break;default:ei(r,7&t)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function zc(r){let e=b(r),t=r.limit;return r.limit=r.offset+e,t}function ei(r,e){switch(e){case 0:for(;128&G(r););break;case 2:Ur(r,b(r));break;case 5:Ur(r,4);break;case 1:Ur(r,8);break;default:throw new Error("Unimplemented type: "+e)}}function Fr(r){return r|=0,{low:r,high:r>>31,unsigned:r>=0}}var ti=[];function ri(){let r=ti.pop();return r?(r.offset=r.limit=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}function qc(r){ti.push(r)}function Gc(r){return{bytes:r,offset:0,limit:r.length}}function Hc(r){let e=r.bytes,t=r.limit;return e.length===t?e:e.subarray(0,t)}function Ur(r,e){if(r.offset+e>r.limit)throw new Error("Skip past limit");r.offset+=e}function ni(r){return r.offset>=r.limit}function dt(r,e){let t=r.bytes,n=r.offset,s=r.limit,i=n+e;if(i>t.length){let o=new Uint8Array(2*i);o.set(t),r.bytes=o}return r.offset=i,i>s&&(r.limit=i),n}function nn(r,e){let t=r.offset;if(t+e>r.limit)throw new Error("Read past limit");return r.offset+=e,t}function Wc(r,e){let t=nn(r,e);return r.bytes.subarray(t,t+e)}function jc(r,e){let t=dt(r,e.length);r.bytes.set(e,t)}function ve(r,e){let t=nn(r,e),n=String.fromCharCode,s=r.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],d,l,u,f;(128&c)===0?o+=n(c):(224&c)===192?a+1>=e?o+=i:(d=s[a+t+1],(192&d)!==128?o+=i:(f=(31&c)<<6|63&d,f<128?o+=i:(o+=n(f),a++))):(240&c)==224?a+2>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],((d|l<<8)&49344)!==32896?o+=i:(f=(15&c)<<12|(63&d)<<6|63&l,f<2048||f>=55296&&f<=57343?o+=i:(o+=n(f),a+=2))):(248&c)==240?a+3>=e?o+=i:(d=s[a+t+1],l=s[a+t+2],u=s[a+t+3],((d|l<<8|u<<16)&12632256)!==8421504?o+=i:(f=(7&c)<<18|(63&d)<<12|(63&l)<<6|63&u,f<65536||f>1114111?o+=i:(f-=65536,o+=n((f>>10)+55296,(1023&f)+56320),a+=3))):o+=i}return o}function ke(r,e){let t=e.length,n=0;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),n+=a<128?1:a<2048?2:a<65536?3:4}C(r,n);let s=dt(r,n),i=r.bytes;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?i[s++]=a:(a<2048?i[s++]=a>>6&31|192:(a<65536?i[s++]=a>>12&15|224:(i[s++]=a>>18&7|240,i[s++]=a>>12&63|128),i[s++]=a>>6&63|128),i[s++]=63&a|128)}}function Jc(r,e){let t=dt(r,e.limit),n=r.bytes,s=e.bytes;for(let i=0,o=e.limit;i<o;i++)n[i+t]=s[i]}function G(r){return r.bytes[nn(r,1)]}function Hs(r,e){let t=dt(r,1);r.bytes[t]=e}function b(r){let e=0,t=0,n;do n=G(r),e<32&&(t|=(127&n)<<e),e+=7;while(128&n);return t}function C(r,e){for(e>>>=0;e>=128;)Hs(r,127&e|128),e>>>=7;Hs(r,e)}function Ws(r,e){let t=0,n=0,s=0,i;return i=G(r),t=127&i,128&i&&(i=G(r),t|=(127&i)<<7,128&i&&(i=G(r),t|=(127&i)<<14,128&i&&(i=G(r),t|=(127&i)<<21,128&i&&(i=G(r),n=127&i,128&i&&(i=G(r),n|=(127&i)<<7,128&i&&(i=G(r),n|=(127&i)<<14,128&i&&(i=G(r),n|=(127&i)<<21,128&i&&(i=G(r),s=127&i,128&i&&(i=G(r),s|=(127&i)<<7))))))))),{low:t|n<<28,high:n>>>4|s<<24,unsigned:e}}function ot(r,e){let t=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,s=e.high>>>24,i=s===0?n===0?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:s<128?9:10,o=dt(r,i),a=r.bytes;switch(i){case 10:a[o+9]=s>>>7&1;case 9:a[o+8]=i!==9?128|s:127&s;case 8:a[o+7]=i!==8?n>>>21|128:n>>>21&127;case 7:a[o+6]=i!==7?n>>>14|128:n>>>14&127;case 6:a[o+5]=i!==6?n>>>7|128:n>>>7&127;case 5:a[o+4]=i!==5?128|n:127&n;case 4:a[o+3]=i!==4?t>>>21|128:t>>>21&127;case 3:a[o+2]=i!==3?t>>>14|128:t>>>14&127;case 2:a[o+1]=i!==2?t>>>7|128:t>>>7&127;case 1:a[o]=i!==1?128|t:127&t}}function Vc(r){return Uc(r)}function js(r){return Zs(r)}var Js=65536,Qc="\0\0\0\0\0\0\0\0",Fe=Js*Js,si=Fe*Fe,Vs=si/2,ge=String.prototype.charCodeAt,$=class r{constructor(e,t,n){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!n}static isLong(e){return e&&e.isLong===!0}static fromBits(e,t,n){return new r(e,t,n)}static fromBytes(e,t,n){return n?r.fromBytesLE(e,t):r.fromBytesBE(e,t)}static fromBytesLE(e,t){return new r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return e===Qc?Qs:new r((ge.call(e,0)|ge.call(e,1)<<8|ge.call(e,2)<<16|ge.call(e,3)<<24)>>>0,(ge.call(e,4)|ge.call(e,5)<<8|ge.call(e,6)<<16|ge.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,t=!0){if(isNaN(e))return t?Kc:Qs;if(t){if(e>=si)return Yc}else{if(e<=-Vs)return Zc;if(e+1>=Vs)return Xc}return r.fromBits(e%Fe|0,e/Fe|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*Fe+(this.low>>>0):this.high*Fe+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){r.isLong(e)||(e=r.fromNumber(e));let t=this.high>>>16,n=65535&this.high,s=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,d=65535&e.low,l=0,u=0,f=0,m=0;return m+=i+d,f+=m>>>16,m&=65535,f+=s+c,u+=f>>>16,f&=65535,u+=n+a,l+=u>>>16,u&=65535,l+=t+o,l&=65535,r.fromBits(f<<16|m,l<<16|u,this.unsigned)}equals(e){return r.isLong(e)||(e=r.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?r.fromBits(0,0,this.unsigned):this.low===-1?r.fromBits(0,this.high+1,this.unsigned):r.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}},Qs=new $(0,0,!1),Kc=new $(0,0,!0),Xc=$.fromBits(-1,2147483647,!1),Yc=$.fromBits(-1,-1,!0),Zc=$.fromBits(0,-2147483648,!1),Ee=(function(r){return r[r.NATIVE_ERROR=5001]="NATIVE_ERROR",r[r.CONNECTING_ERROR=5002]="CONNECTING_ERROR",r[r.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",r[r.MESSAGE_ERROR=5004]="MESSAGE_ERROR",r[r.OPEN_ERROR=5005]="OPEN_ERROR",r})({}),xe=class{constructor(e){this.type=e,this.target=null}},zr=class extends xe{constructor(e,t){super(e),this.message=t&&t.message||null}},qr=class extends xe{constructor(e,t){super(e),this.error=t&&t.error||null,this.colno=t&&t.colno||0,this.filename=t&&t.filename||"",this.lineno=t&&t.lineno||0,this.message=t&&t.message||"",this.code=t&&t.code||5001}},Gr=class extends xe{constructor(e,t){super(e),this.code=t&&t.code||0,this.reason=t&&t.reason||"",this.wasClean=t&&t.wasClean||!1,this.willReconnect=t&&t.willReconnect||!1}},Hr=class extends xe{constructor(e,t){super(e),this.data=t&&t.data||null}},Wr=class extends Hr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},jr=class extends xe{constructor(e,t){super(e),this.data=t&&t.data||null}};function V(r,{message:e,code:t,error:n}){return new qr(r,{message:e,code:t,error:n})}function Y(r,{code:e,reason:t,wasClean:n,willReconnect:s}){return new Gr(r,{code:e,reason:t,wasClean:n,willReconnect:s})}function ed(r,{data:e,message:t}){return new Wr(r,{data:e,message:t})}function td(r,{data:e}){return new jr(r,{data:e})}function Ks(r,{message:e}){return new zr(r,{message:e})}var Qt=class{constructor(e,t){this.endpoints=e,this.maxRetries=t,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length?!0:this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}},$e=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Ie=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",lt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",at=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",rd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,ct=class{constructor(){this._listeners={}}emit(e,...t){let n=this._listeners[e];if(n)n.slice().forEach(s=>s.fn.apply(s.ctx,t));else if(e==="error"&&!this.onerror){let s=t.length&&t[0];if(s instanceof Error)throw s;let i=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw i.context=s,s}return this}off(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=null;else{let n=this._listeners[e];if(n)for(let s=0;s<n.length;)n[s].fn===t?n.splice(s,1):++s}return this}on(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this}},Jr=class extends ct{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,t,n){super(),this._socket=null,lt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Ie&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let t=V("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let n=Y("close",{reason:this._formatErrorMessage(e)});this.emit("close",n)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",td("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",Y("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",ed("message",{...e}))}),this._socket.onError(e=>{this.emit("error",V("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:n=>{this.emit("error",V("error",{message:this._formatErrorMessage(n)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",V("error",{message:this._formatErrorMessage(t)}))}})}close(e,t){this._socket&&this._socket.close({code:e,reason:t})}addEventListener(e,t){this.on(e,t)}removeEventListener(e,t){this.off(e,t)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}};function nd(r,e){if(e)return new e(r.url,r.protocol);if(lt||Ie)return new Jr(r.url,r.protocol,r.headers);if(($e||at)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(r.url,r.protocols)}function sd(r){return!!(r||lt&&wx.connectSocket||Ie&&tt.connectSocket||($e||at)&&typeof WebSocket<"u"&&WebSocket)}function Xs(r,e,t){let n=-1;async function s(i){return i<=n?Promise.reject(new Error("next() called multiple times in process")):(n=i,i===t.length?Promise.resolve():t[i].bind(r)(e,s.bind(null,i+1)))}s(0)}function ii(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(64512&t)===55296&&(64512&r.charCodeAt(n+1))===56320?(++n,e+=4):e+=3;return e}function oi(r,e,t){if(t-e<1)return"";let n="";for(let s=e;s<t;){let i=r[s++];if(i<=127)n+=String.fromCharCode(i);else if(i>=192&&i<224)n+=String.fromCharCode((31&i)<<6|63&r[s++]);else if(i>=224&&i<240)n+=String.fromCharCode((15&i)<<12|(63&r[s++])<<6|63&r[s++]);else if(i>=240){let o=((7&i)<<18|(63&r[s++])<<12|(63&r[s++])<<6|63&r[s++])-65536;n+=String.fromCharCode(55296+(o>>10)),n+=String.fromCharCode(56320+(1023&o))}}return n}function Vr(r,e,t){let n=t,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=63&s|128):(64512&s)===55296&&(64512&(i=r.charCodeAt(o+1)))===56320?(s=65536+((1023&s)<<10)+(1023&i),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=63&s|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=63&s|128);return t-n}async function ai(r){if(typeof r=="string"){let e=new Uint8Array(ii(r));return Vr(r,e,0),e}return r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}function id(r){try{return typeof r!="string"&&(r instanceof ArrayBuffer||r.buffer&&r.buffer instanceof ArrayBuffer)||typeof r!="string"?"":(JSON.parse(r),"application/json")}catch{return typeof r=="string"?"text/plain;charset=utf-8":""}}var od=(r,e)=>{switch(r){case"boe":case"ppe":return{[`x-use-${r}`]:1,"x-tt-env":e};default:return{}}},Qr=class{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}};async function ad(r){return new Promise(e=>{if(!$e)return e("unknown reason");try{let t=document.createElement("script");window.frontierJSONP=n=>{document.body.removeChild(t),window.frontierJSONP=void 0,e(n&&n.msg||"unknown reason")},t.type="text/javascript",t.src=r.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(t)}catch{document.body.removeChild(t)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function pe(r,e,t){return!!r?.find(n=>n.key===e&&n.value===t)}function Ue(r,e){return r?.find(t=>t.key===e)?.value}var $r=null;async function cd(){return $r||($r=Promise.resolve().then(()=>(zs(),$s))),$r}var Kr=class extends ct{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,t=this._keyPath;this._initPromise=(async()=>{let{openDB:n}=await cd();this._qosDB=await n(`frontier_${e}`,1,{upgrade(s){s.createObjectStore(e,{keyPath:t})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(t){console.log(t)}}async set(e,t){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(t){console.log(t)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},Xr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let n=this._qosDB.getItem(this._prefix),s=JSON.parse(n||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getItem(this._prefix),n=JSON.parse(t||"{}");return n[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},Yr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Ie?tt:lt?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let n=this._qosDB.getStorageSync(this._prefix),s=JSON.parse(n||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getStorageSync(this._prefix),n=JSON.parse(t||"{}");return n[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function ci(r,e){if(Ie||Ie)return new Yr(r,e);if(($e||at)&&typeof indexedDB<"u")return new Kr(r,e);if(($e||at)&&typeof localStorage<"u")return new Xr(r,e);throw new Error("init QoSDB failed")}var Zr=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=ci("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:n})=>n<Date.now()).forEach(n=>{this._qosDB?.del(n.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,t){return this._qosDB?.set({message_id:e,timestamp:t})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function sn(r){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=pe(r.message.headers,"x_frontier_qos","2"),n=t&&pe(r.message.headers,"x_frontier_qos_ack","1"),s=t&&pe(r.message.headers,"x_frontier_is_ack","1"),i=s?Ue(r.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:n,isAckCleanupMessage:s,ackMsgIds:i}}async function di(){return this._QoSManager||(this._QoSManager=new Zr),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function dd(r,e){let{enableAutoAck:t}=this._options,n=pe(r.message.headers,"need_ack","1"),s=pe(r.message.headers,"is_ack","1"),i=sn.call(this,r);if(t&&n){let{SeqID:o,LogID:a,service:c,LogIDNew:d,method:l}=r.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:d,service:c,method:l,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:d||""},{key:"ack_code",value:"0"}]})}s&&!i.isQoSAck&&this._dispatchAckMessageEvent(r),e()}async function ld(r,e){this._debug("received",r.message),e()}async function ud(r,e){let t=Vc(await ai(r.data));try{if(t.payload instanceof Uint8Array){let n=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},s=t.payloadEncoding?t.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=t.payloadType?t.payloadType.replace(/\s/g,"").toLowerCase():"",a=i.force?i.type:o||i.type,c=n.force?n.encoding:s||n.encoding,d=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],l=["none_none","binary"];this._options.enableTransformTextPayload&&d.includes(a)&&(!c||l.includes(c))?t.textPayload=oi(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(n){t.textPayload="",console.log(n)}r.message=t,e()}function fd(r,e,t){let n=t||8192,s=n>>>1,i=null,o=n;return function(a){if(a<1||a>s)return r(a);o+a>n&&(i=r(n),o=0);let c=e.call(i,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var hd=4294967295;function gd(r,e,t){if(t>hd)throw new Error("integer too large");let n=3;for(;n>=0;){let s=255&t;tn(s,r,e+n),t>>>=8,n--}return e+4}function pd(r,e){let t=0,n=e,s=e+4;for(;n<s;){let{value:i,offset:o}=en(r,n);n=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function md(r,e,t){return r?r.length<40?Vr(r,e,t)+t:e.utf8Write?e.utf8Write(r,t)+t:e.write?e.write(r,t)+t:Vr(r,e,t)+t:t}function _d(r,e){let t=new $(r[e+4]<<24|r[e+5]<<16|r[e+6]<<8|r[e+7],r[e+0]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3],!0);return e+=8,{value:t,offset:e+8}}function wd(r,e,t){let n=r.low,s=r.high;return e[t]=s>>>24,e[t+1]=s>>>16&255,e[t+2]=s>>>8&255,e[t+3]=255&s,e[t+4]=n>>>24,e[t+5]=n>>>16&255,e[t+6]=n>>>8&255,e[t+7]=255&n,t+=8,t}function en(r,e){return r.readUInt8?{value:r.readUInt8(e),offset:e+1}:{value:255&r[e],offset:e+1}}function tn(r,e,t){return e.writeUint8?e.writeUint8(r,t):e[t]=255&r,t+1}var yd=function(r){return new Uint8Array(r)},Sd=typeof Buffer<"u"?Buffer.allocUnsafe:fd(yd,Uint8Array.prototype.subarray),Ed=16,on=32;function vd(r){let e=0,t={};for(let n=0;n<r.length;n++)t[r[n].cursor_name]=ii(r[n].cursor_name),e+=14+t[r[n].cursor_name];return[e,t]}function Ys(r,e,t){let[n,s]=vd(r),i=Sd(n),o=0;return r.forEach(a=>{console.log("cursor.service",a,a.service),o=tn(0,i,o),console.log("header",o),o=gd(i,o,a.service||0),console.log("service",o),o=tn(s[a.cursor_name],i,o),console.log("service-name",o),o=md(a.cursor_name,i,o),console.log("name",o),o=wd($.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:on,headers:[{key:"cursor_file_name",value:t}],payload:i}}function kd(r){let e=0,t=[];for(;e<r.byteLength;){let{offset:n}=en(r,e);e=n;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=pd(r,e);s.service=i,e=o;let{value:a,offset:c}=en(r,e);e=c,s.cursor_name=oi(r,e,e+a),e+=a;let{value:d,offset:l}=_d(r,e);s.cursor=d.toNumber(),e=l,t.push(s)}return t}function xd(){return{frameType:on,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var rn=class{constructor(e,t,n){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=n,this._qosDB=ci(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,t=await this._qosDB.getAll();switch(console.log("allCursorValues",t),e){case"ALL":return t&&t.length?Ys(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?Ys(t,0,this._cursorFileName):xd()}}async set(e,t,n){return console.log("setdb",e,t,n),this._qosDB.set({cursor_name:e,cursor:t,service:n})}async setCursors(e){let t=kd(e);for(let n of t)console.log("setcursor",t),await this._qosDB.set(n)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},Id="__x_msg_qos__";async function li(r){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:n}=this._options,s=r||Id;try{return this._cursorManager?r&&this._cursorManager.updateCursorFileName(r):this._cursorManager=new rn(`${t}_${e}_${s}`,s,n),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function Td(r,e){let t=pe(r.message.headers,"code","-1"),n=pe(r.message.headers,"is_ack","1"),s=Ue(r.message.headers,"x_frontier_msgid"),i=Number(Ue(r.message.headers,"x_frontier_ttl"))||0,o=sn.call(this,r),a=pe(r.message.headers,"x-msg-qos","2"),c=Ue(r.message.headers,"x-msg-cursor_name"),d=Number(Ue(r.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let l=o.isQoSMessage?await di.call(this):null;if(r.message.service>0&&n&&!t||r.message.service>0){if(s&&o.isQoSMessage&&l)return await l.get(s)||(this._dispatchMessageEvent(r),await l.set(s,Date.now()+i)),e();if(a){let u=await li.call(this);if(!u)return this._dispatchMessageEvent(r),e();let f=await u.get(c)??-1;if(f<d)this._dispatchMessageEvent(r),u.set(c,d,r.message.service);else throw new Error(`recevied message cursor ${d} larger than local cursor ${f}`);return e()}return this._dispatchMessageEvent(r),e()}}async function Rd(r,e){let t=sn.call(this,r);if(!t.isQoSMessage)return e();let n=await di.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await n.del(s);e()}async function Pd(r,e){let t=r.message.frameType===Ed,n=r.message.frameType===on;if(!t&&!n)return e();let s=Ue(r.message.headers,"cursor_file_name");if(!s)return e();let i=await li.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:$.fromNumber(this._seqId++),LogID:$.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Zs(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(n){let o=r.message.payload;o&&i.setCursors(o)}}var Ad=async function(r,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},Cd=async function(r,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},Od=async function(r,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:t}=this._options;this._endpointManager?.resetEndpointConfig();for(let s=0;s<this._messageQueue.length;s++){let i=this._messageQueue[s];if(this._ws.readyState===this.OPEN&&i!==null)this._ws&&this._ws.send(i),this._messageQueue[s]=null;else break}this._messageQueue=this._messageQueue.filter(s=>!!s),this._pingPongTimeoutId=setTimeout(()=>this._ping(),t),this._dispatchOpenEvent(r),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n} success`),e()},Kt=class extends ct{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=$e,this._isNode=rd,this._isMiniTT=Ie,this._isMiniWX=lt,this._isWorker=at,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=i=>{try{Xs(this,i,[Ad,Od,Cd])}catch(o){let a=V("error",{message:o.message,code:Ee.OPEN_ERROR,error:o});this._dispatchErrorEvent(a)}},this._onMessage=async i=>{let{pingInterval:o,pingFrequency:a}=this._options;if((i.data==="hi"&&a==="always"||a==="auto")&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),o)),i.data!=="hi")try{Xs(this,i,[ud,dd,Rd,Pd,Td,ld])}catch(c){let d=V("error",{message:c.message,code:Ee.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(d)}},this._onError=i=>{let o=this._endpointManager?.checkReachMaxTries(),a=this._endpointManager?.getCurrentEndpoint();if(o&&!i.message){let c=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(V("error",{message:c,code:Ee.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(V("error",{message:i.message,code:Ee.NATIVE_ERROR,error:i}))},this._onClose=async i=>{this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;let o=this._endpointManager?.checkReachMaxTries();if(!o&&this._navigatorOnline()&&!this._readyClosed){let a=this._endpointManager?.getCurrentEndpoint(),c=this._options.reconnectInterceptor(i.code,i.reason);this._dispatchCloseEvent(Y("close",{code:1006,reason:i.reason||`connecting failed, unknown reason, hostname: ${a}`,willReconnect:c})),c&&this._connect();return}if(i.code!==1e3&&this._readyClosed){this._dispatchCloseEvent(Y("close",{code:1e3,reason:"bye"})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&o){let a=this._endpointManager?.getCurrentEndpoint(),c=i.reason;c||(c=await ad(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(Y("close",{code:i.code,reason:c}));let d=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(V("error",{message:d,code:Ee.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(Y("close",{code:i.code,reason:`connecting failed, unknown reason, hostname: ${a}`})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}this._dispatchCloseEvent(i),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:Oc,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:t,ws:n}=e,s=Array.isArray(t)?t:typeof t=="string"?[t]:[];if(!s||s.length===0)throw new Error("please provide valid url");if(!sd(n))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Qt(s,this._options.maxRetries),this._pingLossCounter=new Qr(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();let e=Ks("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:t,deviceID:n,bddID:s,ttwID:i,accessKey:o,aID:a,customParams:c={},enableAutoAck:d,enableQoS:l,QoSLevel:u,env:f}=this._options,m,p,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(m=location&&location.protocol=="https:"?"wss://":"ws://",p=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${m}${p}`):(m="wss://",p=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(p)?p:`${m}${p}`);let S=s?"bd_did":i?"ttwid":"device_id",O=s||i||n;if(!O||!S)throw new Error("please provide bddID, deviceID or ttwID");let ee=typeof c=="function"?await c():c,te=f?od(f.xUseEnv,f.xTTEnv):{},L=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[S]:O,xsack:d?1:0,xaack:d?1:0,xsqos:l?1:0,qos_level:l?u:void 0,qos_sdk_version:2,...te},ee),g=Object.keys(L).reduce((E,T)=>L[T]!==void 0?`${E}${E?"&":"?"}${T}=${L[T]}`:E,"");return`${_}/ws/v2${g}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:t}=this._options;if(e){let s=this._endpointManager?.getCurrentEndpoint(),i=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(i){let a=`connect ${s} timeout, max retries reached, will use backup endpoint ${i} to retry`,c=V("error",{message:a,code:Ee.MAX_RETRIES_ERROR});this._debug(a),this._dispatchErrorEvent(c),this._url=await this._generateUrl(i),this._debug(`connect ${i} ${o} times`),this._removeWsListeners()}else{let a=`connect ${s} timeout, max retries reached`;this._debug(a),this._dispatchErrorEvent(V("error",{message:a,code:Ee.MAX_RETRIES_ERROR}));return}}else{let s=this._endpointManager?.getCurrentEndpointAndUpdateCount(),i=this._endpointManager?.getCurrentEndpointTriesCount();this._url=await this._generateUrl(s||""),this._debug(`connect ${s} ${i} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{let s=Ks("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(s)}let n=this._endpointManager?.getCurrentEndpointTriesCount()||0;n>1&&await this._wait(n-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=nd({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),t)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:t,maxReconnectInterval:n,reconnectIntervalGrowFactor:s}=this._options,i=t*Math.pow(s,e-1);return i>n?n:i}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(t=>{setTimeout(t,this._getIntervalValue(e))})}_disconnect(e=1e3,t="",n=!1){this._ws&&this._destroyWebSocket(e,t,n)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let t=js(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch{}}_destroyWebSocket(e=1e3,t="",n=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,n&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let i=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(Y("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(Y("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(Y("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(Y("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((t,n)=>(t+=n&&n.byteLength||0,t),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,t)}async send(e,t){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let n=await ai(e),s=id(e),{method:i=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:d=this._options.payloadEncoding,payloadType:l=this._options.payloadType,logIDNew:u=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?Cc(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let f={SeqID:$.fromNumber(this._seqId++),LogID:$.fromNumber(a),service:o,method:i,headers:c,payloadEncoding:d instanceof Object?d.encoding?d.encoding:"":d,payloadType:l instanceof Object?l.type?l.type:s:l||s,payload:n,LogIDNew:u},m=js(f);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(m),this._debug("sent",f)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(m),this._debug("enqueue",f)):(this._messageQueue.shift(),this._messageQueue.push(m)),{seqID:this._seqId,logID:a,logIDNew:u}}async reconnect(e){let{url:t}=e||{},n=Array.isArray(t)?t:typeof t=="string"?[t]:[];e&&Object.assign(this._options,e),n&&n.length?this._endpointManager=new Qt(n,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){let{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let n=()=>{e("success"),this.off("ping_once_success",n),this.off("ping_once_timeout",s)},s=()=>{t("timeout"),this.off("ping_once_success",n),this.off("ping_once_timeout",s)};this.on("ping_once_success",n),this.on("ping_once_timeout",s),this._ping()})}};var Xl=le(io(),1),Yl=le(ir(),1),Zl=le(Ge(),1),eu=le(_n(),1),tu=le(Sn(),1),ru=le(Tn(),1),po=le(dr(),1),nu=le(go(),1);var mo=po.default;k();var D=w("upstream.frontier"),wo="application/json",yo="none",ur=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){D.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:es,...At(this.opts.ppeOverride)};class t extends mo{constructor(a){super(a,Zn,{headers:e})}send(a,...c){if(Qn("debug"))try{let d;typeof a=="string"?d=Buffer.from(a,"utf8"):a instanceof Buffer?d=a:a instanceof ArrayBuffer?d=new Uint8Array(a):ArrayBuffer.isView(a)?d=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):d=new Uint8Array(0);let l=Buffer.from(d.slice(0,128)).toString("hex");D.debug("WS raw frame out",{bytes:d.byteLength,headHex:l})}catch(d){D.warn("WS raw frame dump failed",{err:String(d)})}super.send(a,...c)}}let n=ns(this.opts.urlOverride),s={url:n,ws:t,fpID:Yn,aID:Pt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:wo,force:!0},payloadEncoding:{encoding:yo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new Kt(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;D.info("frontier opened",{url:n,remoteDeviceId:this.opts.handshake.deviceId,initial:o,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:o})).catch(a=>D.warn("onConnect handler threw (ignored)",{err:String(a)}))},i.onclose=o=>{this.opened=!1,D.info("frontier closed",{code:o.code,reason:o.reason,willReconnect:o.willReconnect})},i.onerror=o=>{D.warn("frontier error",{code:o.code,msg:o.message})},i.onmessage=o=>this.handleMessage(o),this.fws=i,await i.connect()}async stop(e){let t=this.fws;if(t){this.fws=null,this.opened=!1;try{t.close(1e3,e??"bridge shutdown")}catch(n){D.warn("frontier close threw (ignored)",{err:String(n)})}}}async send(e){let t=this.fws;if(!t)throw new h("UPSTREAM_DISCONNECTED","frontier upstream not started");let n=JSON.stringify(e),s=e;D.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:n.length});try{await t.send(n,{service:33555712,method:1,payloadType:wo,payloadEncoding:yo})}catch(i){throw new h("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(i)}`,{cause:i})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let t=e.message?.service;if(t!==33555712){D.debug("drop non-adapter frontier frame",{service:t});return}let n=ou(e);if(!n){D.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){D.debug("frame received but no onFrame handler",{size:n.length});return}let s;try{s=JSON.parse(n)}catch(i){D.warn("frontier message JSON parse failed",{err:String(i),head:n.slice(0,80)});return}D.info("frontier frame in",{logid:iu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id}),Promise.resolve(this.handler(s)).catch(i=>D.warn("frontier frame handler threw",{err:String(i)}))}};function iu(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function ou(r){let e=r.message;if(e?.textPayload)return e.textPayload;let t=e?.payload;if(!t)return null;try{return Buffer.from(t).toString("utf8")}catch{return null}}k();var Pn=w("upstream.switchable"),fr=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;Pn.info("swap upstream",{reason:t});let n=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(s){throw Pn.error("swap target start failed, reverting",{err:String(s)}),this.inner=n,s}await n.stop(t??"swapped").catch(s=>Pn.warn("previous upstream stop threw (ignored)",{err:String(s)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};k();var An=w("upstream"),wt=class{handler=null;async start(){An.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){An.info("NoopUpstream stopped",{reason:e})}async send(e){An.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};k();F();k();F();import{execSync as au}from"node:child_process";import{readFileSync as So,unlinkSync as cu}from"node:fs";import{mkdir as du,readFile as Eo,unlink as vo,writeFile as lu}from"node:fs/promises";import{dirname as uu}from"node:path";var fu=w("single-instance"),hr=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??x().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(fu.warn("removing stale pid file",{stalePid:e}),await vo(this.pidFile).catch(()=>{})),await du(uu(this.pidFile),{recursive:!0}),await lu(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Eo(this.pidFile,"utf8")).trim()===String(process.pid)&&await vo(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Eo(this.pidFile,"utf8"),t=Number.parseInt(e.trim(),10);return Number.isFinite(t)&&t>0?t:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return this.matchesDaemonTitle(e)}matchesDaemonTitle(e){try{let t=So(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=au(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return t.trim()?t.includes("coze-bridge-daemon")||t.includes("lib/index.js"):!1}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{So(this.pidFile,"utf8").trim()===String(process.pid)&&cu(this.pidFile)}catch{}})}};var y=w("daemon"),hu="coze-bridge-daemon";async function Io(){let r=new hr({processTitle:hu}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await jt(),n=t??{};Rr({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let g=new rt;n.frameworksCache=await g.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(n.frameworksCache)})}catch(g){y.warn("framework detection failed",{err:String(g)})}await nt(n);let s=new fr(new wt),i=x(),o=null,a=new Jt({upstream:s,paths:i,bridgeConfig:n,sessionSpawner:async(g,E,T,re)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(g,E,T,re)}});await pu(i,a);let c=new Wt({paths:i,config:n,registry:a});o=c;let d,l,u=null,f=null;a.registerExtension("_agent/create",async g=>c.createAgent(g.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let m={},p=new Nt({agents:a.agents,disposeAndMarkDisconnected:async(g,E)=>{let T=a.agents.get(g);T&&(await T.dispose(`disconnect: ${E}`).catch(re=>y.warn("dispose during disconnect failed (ignored)",{agentId:g,err:String(re)})),T.status="disconnected",a.unregister(g)),a.disconnectedAgents.add(g)},detailSyncer:async g=>{if(!m.ref)throw new Error("agent-detail-sync not initialized yet");await m.ref.syncOne(g)}});a.registerExtension("_agent/listSkills",g=>p.listSkills(g.params)),a.registerExtension("_agent/addSkills",g=>p.addSkills(g.params)),a.registerExtension("_agent/removeSkills",g=>p.removeSkills(g.params)),a.registerExtension("_agent/getFileTree",g=>p.getFileTree(g.params)),a.registerExtension("_agent/getFileContent",g=>p.getFileContent(g.params)),a.registerExtension("_agent/update",g=>p.updateAgent(g.params)),a.registerExtension("_agent/disconnect",g=>p.disconnectAgent(g.params)),a.registerExtension("_agent/switchModel",g=>p.switchModel(g.params)),a.registerExtension("_agent/reset",g=>p.resetAgent(g.params)),a.registerExtension("_agent/repair",g=>p.repairAgent(g.params));let _=new Tt({paths:i,handlers:p,sendDetail:g=>a.sendRequest("_agent/detail",g)});m.ref=_,s.onConnect(({initial:g})=>{y.info("frontier upstream connected, triggering detail sync",{initial:g}),_.syncAll(g?"initial-connect":"reconnect").catch(E=>y.warn("detail sync top-level error (ignored)",{err:String(E)}))});let S=new Vt({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:u??"",frameworksCache:n.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async g=>{let E=g,T=E?.privatecode,re=E?.pairing_code;if(!T||!re)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Oe=Ct(E.env),Ke=E.handshake_url,Er=E.frontier_url,vr=gu(E.env,Ke,Er),zn=!!d&&d!==T,qn=l!==void 0&&l!==vr,Gn=zn||qn;if(Gn){y.warn("pair config switched, resetting agents",{pcChanged:zn,envChanged:qn,previousPc:d?ko(d):"",nextPc:ko(T),previousEnvKey:l??"",nextEnvKey:vr});for(let ye of[...a.agents.values()])await ye.dispose("pair config switch").catch(()=>{}),a.agents.delete(ye.agentId);await s.swap(new wt,"pair switch").catch(()=>{})}let Hn=await is({privatecode:T,...Ke?{endpoint:Ke}:{},ppeOverride:Oe});u=Hn.deviceId,Rr({deviceId:u,pid:process.pid});let Fo=new ur({handshake:Hn,privatecode:T,...Er?{urlOverride:Er}:{},ppeOverride:Oe});await s.swap(Fo,"pair");let Uo=Object.keys(n.frameworksCache??{});try{let ye=await a.sendRequest("_agent/pair",{pairCode:re,patToken:T,frameworks:Uo,_meta:{cozeDeviceId:u}});y.info("_agent/pair ok",{pairResult:ye}),d=T,l=vr,f||(f=new Dt({core:a,getDeviceId:()=>u??""})),f.start(),Gn&&xo(i,c).catch(Ne=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ne)}));let kr;return E.agent_id&&(kr=await mu(E.agent_id,i,c,Ne=>a.sendRequest("_agent/detail",Ne)).catch(Ne=>(y.error("--agent-id ensureAgent failed",{agentId:E.agent_id,err:String(Ne)}),{ok:!1,agentId:E.agent_id??"",note:String(Ne)}))),{ok:!0,note:"paired with cloud",...kr?{agent:kr}:{}}}catch(ye){return y.error("_agent/pair failed",{err:String(ye)}),{ok:!1,note:`pair failed: ${String(ye)}`}}}},{method:"POST",path:"/_agent/create",handler:async g=>{let E=g;return{ok:!0,result:await c.createAgent(E)}}},{method:"POST",path:"/refresh",handler:async()=>{y.info("IPC /refresh: re-detecting frameworks");let g=new rt;return n.frameworksCache=await g.detectAll(),await nt(n),{ok:!0,frameworks:n.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{L.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:O,token:ee}=await S.start();await a.start(),xo(i,c).catch(g=>y.warn("auto-revive top-level error (ignored)",{err:String(g)}));let te=null,L={port:O,token:ee,core:a,ipc:S,shutdown(g){return te||(y.info("daemon shutdown",{reason:g}),te=(async()=>{f?.stop(),await a.stop(g),await S.stop(),await r.release()})(),te)}};for(let g of["SIGTERM","SIGINT"])process.on(g,()=>{L.shutdown(g).then(()=>process.exit(0))});return y.info("daemon ready",{port:O,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(n.frameworksCache??{}),libVersion:n.libVersion??"dev"}),L}function ko(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function gu(r,e,t){return`${r??""}|${e??""}|${t??""}`}async function pu(r,e){let{readdir:t}=await import("node:fs/promises"),n;try{n=await t(r.agentsRoot)}catch{return}let{loadAgentConfig:s,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(ue(),It));for(let o of n){await i(o,r).catch(a=>y.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await s(o,r);a?.disconnectedAt&&(e.disconnectedAgents.add(o),y.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){y.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function mu(r,e,t,n){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ue(),It)),i=await s(r,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:r,framework:i.framework,hadDisconnect:!!i.disconnectedAt});let d={agentId:i.agentId,framework:i.framework,...i.cozeIdentity?{cozeIdentity:i.cozeIdentity}:{},...i.model?{model:i.model}:{}};return await t.createAgent(d),{ok:!0,agentId:r,note:i.disconnectedAt?"revived from local config":"connected from local config"}}y.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let o=await n({_meta:{cozeAgentId:r}});if(!o.framework)throw new h("AGENT_NOT_FOUND",`agent ${r} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let a={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...o.deployType?{_meta:{cozeDeployType:o.deployType}}:{}};await t.createAgent(a);let c=o.deployType==="cloud"&&o.framework==="openclaw";return{ok:!0,agentId:r,note:c?"cloud agent acknowledged":"created from cloud detail"}}async function xo(r,e){let{readdir:t}=await import("node:fs/promises"),n;try{n=await t(r.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(n.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ue(),It));y.info("auto-revive: scanning local agents on startup",{count:n.length});let i=0,o=0;for(let a of n){let c;try{c=await s(a,r)}catch(d){y.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(d)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){y.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{y.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework}),await e.createAgent({agentId:c.agentId,framework:c.framework,...c.cozeIdentity?{cozeIdentity:c.cozeIdentity}:{},...c.model?{model:c.model}:{},...c.deployType?{_meta:{cozeDeployType:c.deployType}}:{}}),i+=1}catch(d){y.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(d)}),o+=1}}return y.info("auto-revive: done",{revived:i,skipped:o,total:n.length}),{revived:i,skipped:o,total:n.length}}On();F();import{readFile as Ro}from"node:fs/promises";var we=class{paths;constructor(e){this.paths=e??x()}async probe(e=1e3){let t=await this.readAuth();if(!t)return{kind:"not-running"};try{let n=await this.fetch(t,{method:"GET",path:"/status",timeoutMs:e});return n.status===200?{kind:"connected",...t}:{kind:"stale",reason:`unexpected status ${n.status}`}}catch(n){return{kind:"stale",reason:Iu(n)}}}async request(e){let t=await this.readAuth();if(!t)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(t,e)}async readAuth(){try{let[e,t]=await Promise.all([Ro(this.paths.portFile,"utf8"),Ro(this.paths.tokenFile,"utf8")]),n=Number.parseInt(e.trim(),10),s=t.trim();return!Number.isFinite(n)||n<=0||!s?null:{port:n,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,t){let n=t.body!==void 0,s={Authorization:`Bearer ${e.token}`};n&&(s["content-type"]="application/json");let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${t.path}`,{method:t.method,headers:s,body:n?JSON.stringify(t.body):void 0,signal:i.signal}),c=await a.text();return{status:a.status,body:xu(c)}}finally{clearTimeout(o)}}};function xu(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Iu(r){return r instanceof Error?r.message:String(r)}k();F();import{copyFile as Po,mkdir as Tu,readFile as Nn,writeFile as Ru}from"node:fs/promises";import{dirname as Pu,resolve as bn,sep as gr}from"node:path";import{fileURLToPath as Au}from"node:url";k();F();var Ao=w("dist-install");function Cu(r){let e=Au(r),t=Pu(e),n=`${gr}src${gr}`;if(t.includes(n)||t.endsWith(`${gr}src${gr}cli`))return null;let s=bn(t,"index.js"),i=bn(t,"..","package.json");return{dist:s,pkgJson:i}}async function Co(r={}){let e=r.paths??x(),t=Cu(import.meta.url),n=r.sourceDist??t?.dist,s=r.sourcePackageJson??t?.pkgJson;if(!n||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let i;try{i=JSON.parse(await Nn(s,"utf8")).version??"unknown"}catch(u){return Ao.warn("cannot read source package.json,skip dist install",{err:String(u)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(u)}`}}let o=await jt(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Nn(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await Tu(e.libDir,{recursive:!0}),await Po(n,e.libEntry),await Po(`${n}.map`,`${e.libEntry}.map`).catch(()=>{});let c=bn(e.libDir,"package.json"),d=`${JSON.stringify({type:"module"},null,2)}
|
|
93
|
-
`;return await
|
|
88
|
+
${c}`}var Ee=R("agent-detail-sync"),sn=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await _0(i)}catch(c){Ee.info("agents dir not found, skip detail sync",{root:i,err:String(c)});return}Ee.info("starting detail sync",{reason:e,count:a.length});for(let c of a)try{await this.syncOne(c)}catch(u){Ee.warn("detail sync failed for agent, skipping",{agentId:c,err:String(u)})}Ee.info("detail sync done",{reason:e})}async syncOne(e){let i=await de(e,this.opts.paths);if(!i){Ee.info("detail sync: agent config missing, skip",{agentId:e});return}let a;try{a=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(d){Ee.warn("detail RPC failed, using local data",{agentId:e,err:String(d)});return}if(a.agentId&&a.agentId!==e){Ee.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&&Ee.info("detail.deployType",{agentId:e,deployType:a.deployType}),!c){Ee.debug("detail sync: no diff",{agentId:e});return}await we(i,this.opts.paths),Ee.info("detail sync: config updated",{agentId:e,identityChanged:u,agentName:i.agentName}),u&&(await ut(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ge();import{spawn as Qs}from"node:child_process";import{lstat as vr,mkdir as v0,readFile as ei,readdir as S0,rm as E0,stat as C0,writeFile as A0}from"node:fs/promises";import{join as Oe,normalize as k0,relative as ti,resolve as P0,sep as ni}from"node:path";var Ce={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 Dt(r){return r?.cozeDeployType==="cloud"?"cloud":"local"}function Os(r){let{_meta:e,...i}=r;return{stripped:i,meta:e}}function ft(r){if(!r?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return r.cozeAgentId}var E=class extends Error{code;retriable;cause;constructor(e,i,a){super(i),this.name="BridgeError",this.code=e,this.retriable=a?.retriable??!1,a?.cause!==void 0&&(this.cause=a.cause)}};H();fe();function Me(r,e){if(Dt(r)!=="cloud")throw new E("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Tt(r){return r.replace(/[^A-Za-z0-9._-]+/g,"-")}H();var on="1008033",Bs="1289";var zs="pbbp2",qs="https://www.coze.cn",Fs="/api/coze_claw/resource/get_frontier_key",w0="https://www.coze.cn",y0="wss://frontier.coze.cn";function Us(r){return r??process.env.COZE_BRIDGE_HANDSHAKE_URL??w0}function Hs(r){return r??process.env.COZE_BRIDGE_FRONTIER_URL??y0}function an(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 xn(r){return r?r.startsWith("boe_")?{ttEnv:r}:{ttEnv:r,usePpe:"1"}:{}}var Ks=R("handshake");async function Gs(r){let e=Us(r.endpoint),i=r.timeoutMs??1e4,a=`${b0(e)}${Fs}?aid=${encodeURIComponent(on)}`,c={Authorization:`Bearer ${r.privatecode}`,Accept:"application/json",...an(r.ppeOverride)},u=new AbortController,d=setTimeout(()=>u.abort(),i);Ks.info("frontier key handshake",{base:e});try{let l=await fetch(a,{method:"GET",headers:c,signal:u.signal}),p=l.headers.get("x-tt-logid")??"",_=l.headers.get("x-tt-trace-id")??"";if(!l.ok){let P=await l.text().catch(()=>"");throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${l.status} logid=${p}: ${P.slice(0,200)}`)}let v=await l.json();if(v.code!==void 0&&v.code!==0)throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${v.code} msg=${v.msg??"-"} logid=${p}`);let w=v.data?.access_key,C=v.data?.device_id;if(!w||!C)throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${p}: ${JSON.stringify(v)}`);return Ks.info("handshake ok",{remoteDeviceId:C,logid:p,traceId:_}),{accessKey:w,deviceId:C}}catch(l){throw l instanceof E?l:l.name==="AbortError"?new E("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${i}ms)`):new E("UPSTREAM_HANDSHAKE_FAILED",String(l),{cause:l})}finally{clearTimeout(d)}}function b0(r){return r.endsWith("/")?r.slice(0,-1):r}var wr="https://llm-gateway.coze.cn",dt="auto";function js(r){return{model:r.model??dt,...r.modelToken?{modelToken:r.modelToken}:{}}}function It(r){return!r||r===dt}function Ws(r){let e={};return r.modelToken&&(e.ANTHROPIC_BASE_URL=wr,e.ANTHROPIC_AUTH_TOKEN=r.modelToken),It(r.model)||(e.ANTHROPIC_MODEL=r.model),e}function Js(r){let e=[];return It(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="${wr}/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 Vs(r){return r.modelToken?{OPENAI_API_KEY:r.modelToken}:{}}function yr(r){let{ttEnv:e,usePpe:i}=xn(r),a={};return e&&(a["x-tt-env"]=e),i&&(a["x-use-ppe"]=i),a}function Xs(r,e){if(!r.modelToken)return{};let i=yr(e);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,u])=>`${c}:${u}`).join(`
|
|
89
|
+
`)}}function br(r){return`coze-session-${r.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ys(r,e){if(!r.modelToken||It(r.model))return null;let i=yr(e),a={baseUrl:`${wr}/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 $s(r,e){if(!r.modelToken)return[];let i=yr(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var ie=R("agent-handlers"),Zs=5*1024*1024,D0=1,T0=6,I0=new Set(["node_modules",".git",".coze","dist","build",".next"]),un=class{constructor(e){this.opts=e}opts;async listSkills(e){Me(e._meta,"_agent/listSkills");let i=ft(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Re(i).workspace,u=a?.skills??[],d=[];for(let l of u){let p=Oe(c,l.relPath,"SKILL.md");await C0(p).then(v=>v.isFile()).catch(()=>!1)&&d.push({skillId:l.skillId,skillName:l.skillName,downloadUrl:l.downloadUrl??"",...l.description?{description:l.description}:{},...l.version?{version:l.version}:{}})}return{skills:d}}async addSkills(e){Me(e._meta,"_agent/addSkills");let i=ft(e._meta),a=await this.requireAgentCfg(i),c=e.skills??[],u=[...a.skills??[]],d=new Map(u.map((p,_)=>[p.skillId,_])),l=[];for(let p of c){if(!p.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let _=L0(p.skillName),v=N0(a.framework),w=Oe(v,_),C=Oe(a.workspace,w);await v0(C,{recursive:!0});let P=await O0(p.downloadUrl);z0(P)?await q0(P,C):await A0(Oe(C,"SKILL.md"),P.toString("utf8"),"utf8");let T={skillId:p.skillId,skillName:p.skillName,relPath:w,installedAt:Date.now(),...p.description?{description:p.description}:{},...p.version?{version:p.version}:{},...p.downloadUrl?{downloadUrl:p.downloadUrl}:{}},N=d.get(p.skillId);N!==void 0?u[N]=T:(d.set(p.skillId,u.length),u.push(T)),l.push(p),ie.info("skill installed",{agentId:i,skillId:p.skillId,skillName:p.skillName,relPath:w})}return await nn(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:l}}async removeSkills(e){Me(e._meta,"_agent/removeSkills");let i=ft(e._meta),a=await this.requireAgentCfg(i),c=new Set(e.skillIds??[]),u=a.skills??[],d=[];for(let l of u){if(!c.has(l.skillId)){d.push(l);continue}let p=Oe(a.workspace,l.relPath);await E0(p,{recursive:!0,force:!0}),ie.info("skill removed",{agentId:i,skillId:l.skillId,relPath:l.relPath})}return await nn(i,d),await this.reloadAgentSessions(i,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,i){return this.reloadAgentSessions(e,i)}async reloadAgentSessions(e,i){let a=this.opts.agents.get(e);if(a&&a.framework!=="codex"){for(let[c,u]of a.sessions)if(!(!u.downstream||!u.acpSessionId)){u.loadingSession=!0;try{await u.downstream.sessionLoad({sessionId:u.acpSessionId,cwd:a.workspace}),ie.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(d){ie.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 ie.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await de(i);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(ie.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await we(a),await ut(a.workspace,a.framework,i,e.cozeIdentity),ie.info("_agent/update: cozeIdentity rewritten",{agentId:i,framework:a.framework}),await this.reloadAgentSessions(i,"identity-changed"),{ok:!0})}async disconnectAgent(e){let i=e.agentId;if(!i)throw new E("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let a=await de(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await we(a),ie.info("agent disconnected",{agentId:i,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(i,e.reason??"disconnect"),{ok:!0}):(ie.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Me(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:dt,a=await de(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await we(a),ie.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return ie.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};c.model=i;let u=[];for(let[d,l]of c.allSessionQueues())u.push(l.enqueue(async()=>{let p=c.sessions.get(d);p?.downstream&&(await p.downstream.stop(`switchModel: ${i}`).catch(()=>{}),p.downstream=void 0)}));return await Promise.all(u),ie.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(Me(e._meta,Ce.RESET),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Ce.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Ce.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Me(e._meta,Ce.REPAIR),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Ce.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new E("IPC_BAD_REQUEST",`${Ce.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){ie.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(a)})}return await this.runDetailSync(e.agentId,Ce.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){ie.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){ie.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(c)})}}async getFileTree(e){Me(e._meta,"_agent/getFileTree");let i=e._meta,a=ft(i),c=await this.resolveWorkspace(a),u=e.filePath??"",d=this.safeJoin(c,u),l=await vr(d).catch(()=>null);if(!l)throw new E("IPC_BAD_REQUEST",`path not found: ${u}`);if(l.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let p=U0(e.depth);return l.isDirectory()?{tree:await ri(c,d,u,p)}:{tree:[{name:H0(u),path:si(u||"."),isDir:!1,size:l.size,modifiedAt:Math.floor(l.mtimeMs)}]}}async getFileContent(e){Me(e._meta,"_agent/getFileContent");let i=ft(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new E("IPC_BAD_REQUEST","filePath required");let c=this.safeJoin(a,e.filePath),u=await vr(c).catch(()=>null);if(!u||!u.isFile())throw new E("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>Zs)throw new E("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${Zs})`);let d=await ei(c);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:u.size}:{content:d.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await de(e).catch(()=>null))?.workspace??Re(e).workspace}safeJoin(e,i){let a=P0(e,i||"."),c=ti(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${ni}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return de(e)}async requireAgentCfg(e){let i=await this.loadAgentCfg(e);if(!i)throw new E("AGENT_NOT_FOUND",`no config for agent: ${e}`);return i}};function L0(r){let e=Tt(r.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new E("IPC_BAD_REQUEST",`invalid skill name: ${r}`);return e}function N0(r){return r==="claude-code"?Oe(".claude","skills"):Oe(".agents","skills")}var R0=3e4,M0=50*1024*1024,fn=3e4;async function O0(r){if(!r)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(r.startsWith("data:")){let e=Math.floor(r.length*3/4);cn(e);let i=B0(r);return cn(i.length),i}if(r.startsWith("file:")){let e=new URL(r).pathname,i=await ei(e);return cn(i.length),i}if(r.startsWith("http://")||r.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),R0);try{let a=await fetch(r,{signal:e.signal});if(!a.ok)throw new E("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${r}`);let c=await a.arrayBuffer();return cn(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new E("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${r.slice(0,80)}`)}function cn(r){if(r>M0)throw new E("IPC_BAD_REQUEST",`skill too large: ${r} bytes`)}function B0(r){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(r);if(!e)throw new E("IPC_BAD_REQUEST","bad data URL");let i=!!e[2],a=e[3]??"";return i?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8")}function z0(r){return r.length>=2&&r[0]===31&&r[1]===139}async function q0(r,e){await F0(r),await new Promise((i,a)=>{let c=Qs("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";c.stderr?.on("data",l=>{u+=String(l)});let d=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar extract timeout (${fn}ms)`))},fn);c.on("error",l=>{clearTimeout(d),a(new E("IPC_BAD_REQUEST",`tar spawn failed: ${l.message}`,{cause:l}))}),c.on("exit",l=>{clearTimeout(d),l===0?i():a(new E("IPC_BAD_REQUEST",`tar exit ${l}${u?`: ${u.trim().slice(0,200)}`:""}`))}),c.stdin?.end(r)})}async function F0(r){let e=await new Promise((i,a)=>{let c=Qs("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",d="";c.stdout?.on("data",p=>{u+=String(p)}),c.stderr?.on("data",p=>{d+=String(p)});let l=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar list timeout (${fn}ms)`))},fn);c.on("error",p=>{clearTimeout(l),a(new E("IPC_BAD_REQUEST",`tar list spawn failed: ${p.message}`))}),c.on("exit",p=>{clearTimeout(l),p===0?i(u):a(new E("IPC_BAD_REQUEST",`tar list exit ${p}${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 E("IPC_BAD_REQUEST",`tar entry kind '${a[0]}' not allowed (symlink/hardlink/special): ${a.slice(0,100)}`);let d=(a.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!d)continue;if(d.startsWith("/"))throw new E("IPC_BAD_REQUEST",`tar entry absolute path: ${d}`);if(d.split(/[/\\]/).some(p=>p===".."))throw new E("IPC_BAD_REQUEST",`tar entry contains '..': ${d}`)}}async function ri(r,e,i,a){if(a<=0)return[];let c;try{c=await S0(e,{withFileTypes:!0})}catch{return[]}let u=[];for(let d of c){if(I0.has(d.name)||d.isSymbolicLink())continue;let l=Oe(e,d.name),p=k0(Oe(i,d.name)),_=null;try{_=await vr(l)}catch{continue}if(_.isSymbolicLink())continue;let v={name:d.name,path:si(ti(r,l)),isDir:_.isDirectory(),size:_.size,modifiedAt:Math.floor(_.mtimeMs)};_.isDirectory()&&a>1&&(v.children=await ri(r,l,p,a-1)),u.push(v)}return u.sort((d,l)=>d.isDir!==l.isDir?d.isDir?-1:1:d.name.localeCompare(l.name)),u}function U0(r){return!r||r<=0?D0:Math.min(r,T0)}function H0(r){if(!r||r==="."||r==="/")return".";let e=r.split(/[/\\]/);return e[e.length-1]||"."}function si(r){return r.split(ni).join("/")}H();var Lt=R("agent-health-reporter"),K0=1e4,dn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??K0}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()}),Lt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Lt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Lt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Lt.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=G0(c);u&&i.push({agentId:c.agentId,status:u})}if(i.length===0)return;let a={agents:i,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",a)}catch(c){Lt.warn("heartbeat batch send failed",{count:i.length,err:String(c)})}}finally{this.inFlight=!1}}};function G0(r){return r.status==="error"?"error":r.activeTriggers.size>0?"busy":r.status==="ok"?"online":null}Ge();import{mkdir as Sr,rm as xx}from"node:fs/promises";import{spawn as X0}from"node:child_process";function Nt(r,e,i){return i===void 0?{jsonrpc:"2.0",id:r,method:e}:{jsonrpc:"2.0",id:r,method:e,params:i}}function ln(r,e){return e===void 0?{jsonrpc:"2.0",method:r}:{jsonrpc:"2.0",method:r,params:e}}function lt(r,e){return{jsonrpc:"2.0",id:r,result:e}}function $e(r,e){return{jsonrpc:"2.0",id:r,error:e}}var hn=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 ii(r){return"method"in r&&"id"in r&&r.id!==void 0}function oi(r){return"method"in r&&!("id"in r)}function gn(r){return!("method"in r)&&"id"in r}var j0={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 pn(r){return r instanceof E?{code:j0[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 ai(r){let e=r.data,i=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new E(i,r.message,{retriable:e?.retriable??!1,cause:r.data})}function xi(r){return`${JSON.stringify(r)}
|
|
91
|
+
`}var mn=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(`
|
|
92
|
+
`);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 ui={"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"},Cd=Object.fromEntries(Object.entries(ui).map(([r,e])=>[e,r])),W0={"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:[]},ht=class{seq=0;next(e,i){this.seq+=1;let a=ui[e]??J0(e),c=W0[a]??[],u=[a,String(this.seq)];if(c.length>0){let d=c.map(p=>ci(i?.[p]??"")),l=V0(d).join(":");l&&u.push(l)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>ci(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function J0(r){return r.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function ci(r){return r.replace(/[:_\s]+/g,"-")}function V0(r){let e=r.length;for(;e>0&&!r[e-1];)e-=1;return r.slice(0,e)}H();var Y0=3e4;function fi(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 mn({onError:i=>this.log.warn("decode line failed",{line:i.line})})}opts;child;decoder;pending=new Map;idAllocator=new ht;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;sanitizeEnv(e){return e}async start(){if(this.child)throw new E("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=X0(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=>{this.log.debug("stderr",{text:a.trimEnd()})}),i.on("exit",(a,c)=>{this.stopped=!0,this.failAllPending(new E("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${c})`));for(let u of this.exitHandlers)u(a,c)}),i.on("error",a=>{this.log.error("child error",{err:String(a)}),this.failAllPending(new E("AGENT_SPAWN_FAILED",String(a),{cause:a}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let i=this.child,a=new Promise(u=>i.once("exit",()=>u()));fi(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||fi(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(ln("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(lt(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($e(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=Y0){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=Nt(c,e,i),d=a>0&&Number.isFinite(a);return new Promise((l,p)=>{let _=d?setTimeout(()=>{this.pending.delete(c),p(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(c,{resolve:l,reject:p,timer:_,method:e});try{this.writeFrame(u)}catch(v){_&&clearTimeout(_),this.pending.delete(c),p(v)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new E("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(xi(e))}dispatch(e){if(gn(e)){let i=e.id!==null?this.pending.get(e.id):void 0;if(!i){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),i.timer&&clearTimeout(i.timer),e.error?i.reject(ai(e.error)):i.resolve(e.result);return}if(oi(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(ii(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($e(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($e(e.id,pn(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var $0="@agentclientprotocol/claude-agent-acp@latest";function Z0(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 _n=class extends je{framework="claude-code";constructor(e){let i=e.command??"npx",a=e.args??["-y",$0],c={command:i,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(c)}sanitizeEnv(e){return Z0(e)}};import{mkdtempSync as Q0,rmSync as ex}from"node:fs";import{tmpdir as tx}from"node:os";import{join as nx}from"node:path";var rx="@zed-industries/codex-acp@latest",wn=class extends je{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=e.command??"npx",a=e.args??["-y",rx],c=e.extraArgs?[...a,...e.extraArgs]:a,u=e.isolateCodexHome?Q0(nx(tx(),"coze-bridge-codex-home-")):void 0,d=u?{...e.env??{},CODEX_HOME:u}:e.env,l={command:i,args:c,cwd:e.cwd,...d?{env:d}:{}};super(l),this.authMethodId=e.authMethodId,this.codexHomeDir=u}async initialize(e){let i=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),i}async stop(e){if(await super.stop(e),this.codexHomeDir)try{ex(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var Rt=class extends je{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let i=e.sessionName??"default",a=["acp","--session",`agent:${e.agentId}:${i}`];e.gatewayToken&&a.push("--token",e.gatewayToken);let c={command:e.command,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(c),this.agentId=e.agentId,this.sessionName=i,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};H();fe();var gt=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((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 yn=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 gt,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)Mt(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Mt(r){r.idleTimer&&(clearTimeout(r.idleTimer),r.idleTimer=void 0)}import{spawn as sx}from"node:child_process";import{homedir as ix}from"node:os";import{join as ox}from"node:path";Zt();H();async function hi(){let r=ox(ix(),".openclaw/openclaw.json");return(await ct(r))?.gateway?.auth?.token??""}var di=R("openclaw.config"),ax=[0,5e3,5e3],li="models.providers.",bn="agents.defaults.models",vn=class{command;env;retryDelaysMs;queue=new gt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??ax}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,di.warn("openclaw cli failed, will retry",{label:e,attempt:c+1,err:String(d)})}}throw new E("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${a?.message??"unknown"}`)}runCli(e){return new Promise((i,a)=>{let c=sx(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){di.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",`${li}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${li}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${bn}[${e}]`,()=>this.runCli(["config","set",bn,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${bn}[${e}]`,`${bn}.${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 Ze=R("agent-manager"),cx=(r,e,i,a,c,u,d)=>{switch(r){case"claude-code":{let l=c?{...Ws(c),...Xs(c,d)}:void 0;return new _n({cwd:i,...l&&Object.keys(l).length>0?{env:l}:{}})}case"codex":{let l=c?[...Js(c),...$s(c,d)]:[],p=c?Vs(c):void 0,_=!!c;return new wn({cwd:i,...l.length>0?{extraArgs:l}:{},...p&&Object.keys(p).length>0?{env:p}:{},..._?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Rt({command:e,cwd:i,agentId:a,...u?{sessionName:Tt(u)}:{}})}};function gi(r){return r==="claude-code"||r==="codex"}var ux={path:"",version:"cloud-deployed"},fx={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},dx=2e4,Sn=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??cx,this.createTimeoutMs=e.createTimeoutMs??dx}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new E("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new vn({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new E("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new E("IPC_BAD_REQUEST","framework required");let i=Dt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new E("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")Ze.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>Ze.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else return Ze.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}if(!(i&&gi(e.framework))&&!this.config.frameworksCache?.[e.framework])throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Re(e.agentId,this.paths),d=e.workspace??u.workspace,l=Dt(e._meta),p=new AbortController,_=setTimeout(()=>p.abort(new E("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),v,w=!1;try{let C=()=>{if(p.signal.aborted)throw p.signal.reason instanceof Error?p.signal.reason:new E("AGENT_TIMEOUT","_agent/create aborted")};await Sr(u.root,{recursive:!0}),await Sr(d,{recursive:!0}),await Sr(u.logs,{recursive:!0}),C(),await ut(d,e.framework,e.agentId,e.cozeIdentity),C();let P=await de(e.agentId,this.paths).catch(()=>null),T=js({model:e.model??P?.model});if(v=new yn({agentId:e.agentId,framework:e.framework,workspace:d,model:T.model??dt,deployType:l}),v.status="ok",P?.sessions){for(let[ae,te]of Object.entries(P.sessions))v.sessions.set(ae,{acpSessionId:te.acpSessionId,modelToken:te.modelToken,tokenGeneratedAt:te.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let z=Object.keys(P.sessions).length;z>0&&Ze.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:z})}this.registry.register(v),w=!0;let N={agentId:e.agentId,framework:e.framework,workspace:d,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:T.model};return l==="cloud"&&(N.deployType="cloud"),P?.skills&&(N.skills=P.skills),P?.agentName&&(N.agentName=P.agentName),P?.description&&(N.description=P.description),await we(N,this.paths),e.framework==="openclaw"&&await this.getOpenclawConfig().ensureAgent(e.agentId,d),Ze.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:l}),{ok:!0,agentId:e.agentId,workspace:d,framework:e.framework}}catch(C){throw Ze.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),w&&v&&(await v.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await xx(u.root,{recursive:!0,force:!0}).catch(P=>Ze.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof E?C:new E("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(_)}}async spawnSessionDownstream(e,i,a,c){let d=this.config.frameworksCache?.[e.framework];if(!d)if(e.deployType==="cloud"&&gi(e.framework))d=ux;else throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let l=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,p;e.framework==="openclaw"?p=await this.buildOpenclawDownstream({session:e,modelConfig:l,cloudSessionId:a,cozeEnv:c,command:d.path}):p=this.factory(e.framework,d.path,e.workspace,e.agentId,l,a,c);try{return await p.start(),await p.initialize(fx),p}catch(_){throw await p.stop("spawnSessionDownstream failed").catch(()=>{}),_ instanceof E?_:new E("AGENT_SPAWN_FAILED",_ instanceof Error?_.message:String(_),{cause:_})}}async buildOpenclawDownstream(e){let{session:i,modelConfig:a,cloudSessionId:c,cozeEnv:u,command:d}=e,l=Tt(c),p=await hi(),_=a?.modelToken&&!It(a.model)?Ys(a,u):null,v;if(_){let w=br(c),C=`${w}/${a.model}`;if(!this.ensuredProviders.has(C)){let P=this.getOpenclawConfig();await P.ensureProvider(w,_),await P.addModelToAllowlist(C),this.ensuredProviders.add(C)}v=C}return new Rt({command:d,cwd:i.workspace,agentId:i.agentId,sessionName:l,...p?{gatewayToken:p}:{},...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=br(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};H();import{spawn as lx}from"node:child_process";import{constants as pi,access as hx}from"node:fs/promises";import{delimiter as gx,join as px}from"node:path";var mx=R("framework-detector"),mi={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},_x=[".exe",".cmd",".bat",".ps1"],Ot=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??lx,access:e.access??hx}}async detect(e){let i=mi[e],a=await this.which(i);if(!a)return mx.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(mi).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(gx).filter(Boolean),a=this.env.platform==="win32"?["",..._x]:[""];for(let c of i)for(let u of a){let d=px(c,e+u);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?pi.F_OK:pi.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=l=>{c||(c=!0,u&&clearTimeout(u),i(l.trim()||"unknown"))};try{let l=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});u=setTimeout(()=>{l.kill("SIGKILL"),d("unknown")},5e3),l.stdout?.on("data",p=>{a+=p.toString("utf8")}),l.on("error",()=>d("unknown")),l.on("close",()=>{let p=bx(a).split(/\r?\n/)[0]??"";d(p)})}catch{d("unknown")}})}},yx=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function bx(r){return r.replace(yx,"")}Zt();fe();var vx=10*6e4;function _i(r){let e=r?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?vx:e}function En(r){return ct(r??K().configFile)}function Bt(r,e){return $t(e??K().configFile,r)}import{randomBytes as Sx}from"node:crypto";Ge();H();var G=R("core"),Ex=3e4,Cx=3e4,Cn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new ht;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=_i(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(),G.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){G.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),G.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){G.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)&&G.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)=>{G.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),Mt(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(gn(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}`):G.warn("drop notification: extension not registered",{method:e.method});return}let u=await c(e,this);i!==null&&await this.upstream.send(lt(i,u));return}if(e.method.startsWith("session/")){let c=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(lt(i,c));return}if(e.method==="initialize"){i!==null&&await this.upstream.send(lt(i,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}i!==null?await this.sendError(i,j.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):G.warn("drop unknown notification",{method:e.method})}catch(c){G.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send($e(i,pn(c)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new E("IPC_BAD_REQUEST",`${e.method} requires params`);let i=e.params,a=i._meta?.cozeAgentId;if(!a)throw new E("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let c=this.agents.get(a);if(!c)throw this.disconnectedAgents.has(a)?new E("AGENT_DISCONNECTED",`agent ${a} has been disconnected; cloud must _agent/create to revive`):new E("AGENT_NOT_FOUND",`agent not found: ${a}`);let u=typeof i.sessionId=="string"?i.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!u)return this.dispatchSessionCall(c,e.method,i);let d=Date.now(),l=!1;try{let p=await c.getSessionQueue(u).enqueue(()=>this.dispatchSessionCall(c,e.method,i));return l=!0,p}finally{G.info("session call done",{agentId:c.agentId,method:e.method,durationMs:Date.now()-d,ok:l})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:c}=Os(a);switch(i){case"session/new":{let u=Ax();return G.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return G.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=c,d=u.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/prompt: missing sessionId");let l=await this.ensureRuntime(e,d);if(l.replySeq=0,await this.ensureDownstream(e,d,l),!l.downstream||!l.acpSessionId)throw new E("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let p=a._meta?.cozeTriggerMsgId;p?e.activeTriggers.set(l.acpSessionId,p):e.activeTriggers.delete(l.acpSessionId);try{let _=await l.downstream.sessionPrompt({...u,sessionId:l.acpSessionId});return l.lastActiveAt=Date.now(),_}finally{e.activeTriggers.delete(l.acpSessionId),l.downstream?.isAlive()&&this.armIdleTimer(e,d,l)}}case"session/cancel":{let d=c.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/cancel: missing sessionId");let l=e.sessions.get(d);return l?.downstream?.isAlive()&&l.acpSessionId&&await l.downstream.sessionCancel({sessionId:l.acpSessionId}),{ok:!0}}default:throw new E("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(i,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let c=await this.sendRequest(Ce.GEN_MODEL_TOKEN,a,Cx);if(!c?.modelToken)throw new E("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return c.modelToken}catch(c){throw c instanceof E&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new E("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,i,a){if(Mt(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new E("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let c=await this.sessionSpawner(e,a.modelToken,i,this.currentCozeEnv);if(a.downstream=c,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await c.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),G.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){G.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){Mt(a),a.idleTimer=setTimeout(()=>{G.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:i});let c=a.downstream;a.downstream=void 0,a.idleTimer=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId),c&&c.stop("idle timeout").catch(u=>G.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(u)}))},this.sessionIdleTimeoutMs),a.idleTimer.unref?.()}forwardUpdate(e,i){let a=i.sessionId,c=this.reverseSessionId(e,a);if(!c){G.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){G.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}let d={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},l=e.activeTriggers.get(a);l&&(d.cozeTriggerMsgId=l),this.upstream.send(ln("session/update",{...i,sessionId:c,_meta:d})).catch(p=>G.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,i,a){if(a.method==="session/request_permission"){this.forwardPermissionRequest(e,i,a);return}G.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:a.method}),i.respondAgentRequestError(a.id,{code:j.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}forwardPermissionRequest(e,i,a){let c=this.upstreamIds.next("session/request_permission"),u=a.params??{},l=u.sessionId,p=l?e.activeTriggers.get(l):void 0,_={cozeAgentId:e.agentId};p&&(_.cozeTriggerMsgId=p);let v=l?this.reverseSessionId(e,l):void 0,w={...u,...v?{sessionId:v}:{},_meta:_};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),this.upstream.send(Nt(c,"session/request_permission",w)).catch(C=>{this.pendingUpstream.delete(c),G.error("forward permission request failed",{agentId:e.agentId,err:String(C)}),i.respondAgentRequestError(a.id,{code:j.INTERNAL_ERROR,message:`upstream send failed: ${String(C)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let i=this.pendingUpstream.get(e.id);if(i){this.pendingUpstream.delete(e.id),e.error?i.downstream.respondAgentRequestError(i.agentRequestId,e.error):i.downstream.respondAgentRequest(i.agentRequestId,e.result);return}let a=this.pendingBridge.get(e.id);if(a){this.pendingBridge.delete(e.id),clearTimeout(a.timer),e.error?a.reject(new hn(e.error)):a.resolve(e.result);return}G.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=Ex){let c=this.upstreamIds.next(e);return new Promise((u,d)=>{let l=setTimeout(()=>{this.pendingBridge.delete(c),d(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(c,{method:e,resolve:u,reject:d,timer:l}),this.upstream.send(Nt(c,e,i)).catch(p=>{let _=this.pendingBridge.get(c);_&&(clearTimeout(_.timer),this.pendingBridge.delete(c)),d(p)})})}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 _r(e.agentId,i,this.paths)}catch(i){G.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($e(e,{code:i,message:a}))}};function Ax(){return Sx(16).toString("hex")}H();fe();import{randomBytes as kx}from"node:crypto";import{chmod as Px,mkdir as Dx,writeFile as wi}from"node:fs/promises";import{createServer as Tx}from"node:http";import{dirname as Ix}from"node:path";var Lx=1e6,Er=R("ipc"),An=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??K()}async start(){this.token=kx(32).toString("hex");let e=Tx((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(),Er.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(Ix(this.paths.portFile),{recursive:!0}),await wi(this.paths.portFile,String(this.port),"utf8"),await wi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Px(this.paths.tokenFile,384)}catch(e){Er.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){zt(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){zt(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await Nx(e)}catch(l){zt(i,400,{error:"invalid json",detail:String(l)});return}try{let l=await u.handler(d,e);zt(i,200,l??{ok:!0})}catch(l){Er.error("IPC handler failed",{key:c,err:String(l)}),zt(i,500,{error:l instanceof Error?l.message:String(l)})}}};function zt(r,e,i){r.statusCode=e,r.setHeader("content-type","application/json"),r.end(JSON.stringify(i))}async function Nx(r){let e=[],i=0;for await(let c of r){let u=c;if(i+=u.length,i>Lx)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var Fo=Ne(Ti(),1);var lu=Ne(Ao(),1),hu=Ne(Hn(),1),gu=Ne(_t(),1),pu=Ne(Br(),1),mu=Ne(Fr(),1),_u=Ne(Wr(),1),Mo=Ne(Wn(),1),wu=Ne(Ro(),1);var Oo=Mo.default;H();var oe=R("upstream.frontier"),zo="application/json",qo="none",Vn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){oe.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:qs,...an(this.opts.ppeOverride)};class i extends Oo{constructor(l){super(l,zs,{headers:e})}send(l,...p){if(Rs("debug"))try{let _;typeof l=="string"?_=Buffer.from(l,"utf8"):l instanceof Buffer?_=l:l instanceof ArrayBuffer?_=new Uint8Array(l):ArrayBuffer.isView(l)?_=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):_=new Uint8Array(0);let v=Buffer.from(_.slice(0,128)).toString("hex");oe.debug("WS raw frame out",{bytes:_.byteLength,headHex:v})}catch(_){oe.warn("WS raw frame dump failed",{err:String(_)})}super.send(l,...p)}}let a=Hs(this.opts.urlOverride),c={url:a,ws:i,fpID:Bs,aID:on,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:zo,force:!0},payloadEncoding:{encoding:qo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new Fo.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;oe.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:d,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:d})).catch(l=>oe.warn("onConnect handler threw (ignored)",{err:String(l)}))},u.onclose=d=>{this.opened=!1,oe.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{oe.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){oe.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new E("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),c=e;oe.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:zo,payloadEncoding:qo})}catch(u){throw new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){oe.debug("drop non-adapter frontier frame",{service:i});return}let a=vu(e);if(!a){oe.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){oe.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(u){oe.warn("frontier message JSON parse failed",{err:String(u),head:a.slice(0,80)});return}oe.info("frontier frame in",{logid:bu(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id}),Promise.resolve(this.handler(c)).catch(u=>oe.warn("frontier frame handler threw",{err:String(u)}))}};function bu(r){return r?r.high===0?String(r.low>>>0):`${r.high.toString(16)}${(r.low>>>0).toString(16).padStart(8,"0")}`:""}function vu(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}}H();var Vr=R("upstream.switchable"),Xn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;Vr.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 Vr.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>Vr.warn("previous upstream stop threw (ignored)",{err:String(c)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};H();var Xr=R("upstream"),Jt=class{handler=null;async start(){Xr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Xr.info("NoopUpstream stopped",{reason:e})}async send(e){Xr.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};H();fe();H();fe();import{execSync as Su}from"node:child_process";import{readFileSync as Uo,unlinkSync as Eu}from"node:fs";import{mkdir as Cu,readFile as Ho,unlink as Ko,writeFile as Au}from"node:fs/promises";import{dirname as ku}from"node:path";var Pu=R("single-instance"),Yn=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??K().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&&(Pu.warn("removing stale pid file",{stalePid:e}),await Ko(this.pidFile).catch(()=>{})),await Cu(ku(this.pidFile),{recursive:!0}),await Au(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Ho(this.pidFile,"utf8")).trim()===String(process.pid)&&await Ko(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Ho(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=Uo(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=Su(`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{Uo(this.pidFile,"utf8").trim()===String(process.pid)&&Eu(this.pidFile)}catch{}})}};var O=R("daemon"),Du="coze-bridge-daemon";async function Wo(){let r=new Yn({processTitle:Du}),e=await r.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await En(),a=i??{};mr({pid:process.pid}),O.info(i?"loaded bridge config":"initialized bridge config");try{let k=new Ot;a.frameworksCache=await k.detectAll(),O.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(k){O.warn("framework detection failed",{err:String(k)})}await Bt(a);let c=new Xn(new Jt),u=K(),d=null,l=new Cn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(k,q,W,ne)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(k,q,W,ne)}});await Iu(u,l);let p=new Sn({paths:u,config:a,registry:l});d=p;let _,v,w=null,C=null;l.registerExtension("_agent/create",async k=>p.createAgent(k.params)),l.registerExtension("_agent/health",async()=>({ok:!0}));let P={},T=new un({agents:l.agents,disposeAndMarkDisconnected:async(k,q)=>{let W=l.agents.get(k);W&&(await p.cleanupOpenclawSessionProviders(W).catch(ne=>O.warn("cleanup openclaw providers failed (ignored)",{agentId:k,err:String(ne)})),await W.dispose(`disconnect: ${q}`).catch(ne=>O.warn("dispose during disconnect failed (ignored)",{agentId:k,err:String(ne)})),W.status="disconnected",l.unregister(k)),l.disconnectedAgents.add(k)},detailSyncer:async k=>{if(!P.ref)throw new Error("agent-detail-sync not initialized yet");await P.ref.syncOne(k)},openclawRepair:async(k,q)=>{await p.openclawRepair(k,q)}});l.registerExtension("_agent/listSkills",k=>T.listSkills(k.params)),l.registerExtension("_agent/addSkills",k=>T.addSkills(k.params)),l.registerExtension("_agent/removeSkills",k=>T.removeSkills(k.params)),l.registerExtension("_agent/getFileTree",k=>T.getFileTree(k.params)),l.registerExtension("_agent/getFileContent",k=>T.getFileContent(k.params)),l.registerExtension("_agent/update",k=>T.updateAgent(k.params)),l.registerExtension("_agent/disconnect",k=>T.disconnectAgent(k.params)),l.registerExtension("_agent/switchModel",k=>T.switchModel(k.params)),l.registerExtension("_agent/reset",k=>T.resetAgent(k.params)),l.registerExtension("_agent/repair",k=>T.repairAgent(k.params));let N=new sn({paths:u,handlers:T,sendDetail:k=>l.sendRequest("_agent/detail",k)});P.ref=N,c.onConnect(({initial:k})=>{O.info("frontier upstream connected, triggering detail sync",{initial:k}),N.syncAll(k?"initial-connect":"reconnect").catch(q=>O.warn("detail sync top-level error (ignored)",{err:String(q)}))});let z=new An({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...l.agents.keys()],deviceId:w??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async k=>{let q=k,W=q?.privatecode,ne=q?.pairing_code;if(!W||!ne)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let De=xn(q.env),me=q.handshake_url,Xe=q.frontier_url,Ct=Tu(q.env,me,Xe),Vt=!!_&&_!==W,ve=v!==void 0&&v!==Ct,Se=Vt||ve;if(Se){O.warn("pair config switched, resetting agents",{pcChanged:Vt,envChanged:ve,previousPc:_?Go(_):"",nextPc:Go(W),previousEnvKey:v??"",nextEnvKey:Ct});for(let U of[...l.agents.values()])await U.dispose("pair config switch").catch(()=>{}),l.agents.delete(U.agentId);await c.swap(new Jt,"pair switch").catch(()=>{})}let Xt=await Gs({privatecode:W,...me?{endpoint:me}:{},ppeOverride:De});w=Xt.deviceId,mr({deviceId:w,pid:process.pid});let xe=new Vn({handshake:Xt,privatecode:W,...Xe?{urlOverride:Xe}:{},ppeOverride:De});await c.swap(xe,"pair");let Yt=Object.keys(a.frameworksCache??{});try{let U=await l.sendRequest("_agent/pair",{pairCode:ne,patToken:W,frameworks:Yt,_meta:{cozeDeviceId:w}});O.info("_agent/pair ok",{pairResult:U}),_=W,v=Ct,C||(C=new dn({core:l,getDeviceId:()=>w??""})),C.start(),Se&&jo(u,p).catch(Te=>O.warn("post-pair-switch auto-revive error (ignored)",{err:String(Te)}));let J;return q.agent_id&&(J=await Lu(q.agent_id,u,p,Te=>l.sendRequest("_agent/detail",Te)).catch(Te=>(O.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(Te)}),{ok:!1,agentId:q.agent_id??"",note:String(Te)}))),{ok:!0,note:"paired with cloud",...J?{agent:J}:{}}}catch(U){return O.error("_agent/pair failed",{err:String(U)}),{ok:!1,note:`pair failed: ${String(U)}`}}}},{method:"POST",path:"/_agent/create",handler:async k=>{let q=k;return{ok:!0,result:await p.createAgent(q)}}},{method:"POST",path:"/refresh",handler:async()=>{O.info("IPC /refresh: re-detecting frameworks");let k=new Ot;return a.frameworksCache=await k.detectAll(),await Bt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(O.info("IPC /shutdown received"),setImmediate(()=>{ue.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ae,token:te}=await z.start();await l.start(),jo(u,p).catch(k=>O.warn("auto-revive top-level error (ignored)",{err:String(k)}));let be=null,ue={port:ae,token:te,core:l,ipc:z,shutdown(k){return be||(O.info("daemon shutdown",{reason:k}),be=(async()=>{C?.stop(),await l.stop(k),await z.stop(),await r.release()})(),be)}};for(let k of["SIGTERM","SIGINT"])process.on(k,()=>{ue.shutdown(k).then(()=>process.exit(0))});return O.info("daemon ready",{port:ae,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),ue}function Go(r){return r.length<=8?"***":`${r.slice(0,4)}***${r.slice(-4)}`}function Tu(r,e,i){return`${r??""}|${e??""}|${i??""}`}async function Iu(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(),rn));for(let d of a){await u(d,r).catch(l=>O.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(l)}));try{let l=await c(d,r);l?.disconnectedAt&&(e.disconnectedAgents.add(d),O.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){O.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(l)})}}}async function Lu(r,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ge(),rn)),u=await c(r,e);if(u){O.info("--agent-id: local config found, reconnecting",{agentId:r,framework:u.framework,hadDisconnect:!!u.disconnectedAt});let _={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{}};return await i.createAgent(_),{ok:!0,agentId:r,note:u.disconnectedAt?"revived from local config":"connected from local config"}}O.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:r});let d=await a({_meta:{cozeAgentId:r}});if(!d.framework)throw new E("AGENT_NOT_FOUND",`agent ${r} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let l={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(l);let p=d.deployType==="cloud"&&d.framework==="openclaw";return{ok:!0,agentId:r,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function jo(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(),rn));O.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,d=0;for(let l of a){let p;try{p=await c(l,r)}catch(_){O.warn("auto-revive: load config failed (skipping)",{agentId:l,err:String(_)}),d+=1;continue}if(!p){d+=1;continue}if(p.disconnectedAt){O.info("auto-revive: skip disconnected agent",{agentId:l,disconnectedAt:p.disconnectedAt}),d+=1;continue}try{O.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:l,framework:p.framework}),await e.createAgent({agentId:p.agentId,framework:p.framework,...p.cozeIdentity?{cozeIdentity:p.cozeIdentity}:{},...p.model?{model:p.model}:{},...p.deployType?{_meta:{cozeDeployType:p.deployType}}:{}}),u+=1}catch(_){O.warn("auto-revive: createAgent failed (skipping)",{agentId:l,framework:p.framework,err:String(_)}),d+=1}}return O.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}$r();fe();import{readFile as Vo}from"node:fs/promises";var Ve=class{paths;constructor(e){this.paths=e??K()}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:Uu(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([Vo(this.paths.portFile,"utf8"),Vo(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 l=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}),p=await l.text();return{status:l.status,body:Fu(p)}}finally{clearTimeout(d)}}};function Fu(r){if(!r)return null;try{return JSON.parse(r)}catch{return r}}function Uu(r){return r instanceof Error?r.message:String(r)}H();fe();import{copyFile as Xo,mkdir as Hu,readFile as Zr,writeFile as Ku}from"node:fs/promises";import{dirname as Gu,resolve as Qr,sep as $n}from"node:path";import{fileURLToPath as ju}from"node:url";H();fe();var Yo=R("dist-install");function Wu(r){let e=ju(r),i=Gu(e),a=`${$n}src${$n}`;if(i.includes(a)||i.endsWith(`${$n}src${$n}cli`))return null;let c=Qr(i,"index.js"),u=Qr(i,"..","package.json");return{dist:c,pkgJson:u}}async function $o(r={}){let e=r.paths??K(),i=Wu(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 Zr(c,"utf8")).version??"unknown"}catch(w){return Yo.warn("cannot read source package.json,skip dist install",{err:String(w)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(w)}`}}let d=await En(e.configFile)??{},l=d.libVersion;if(l===u)try{return await Zr(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await Hu(e.libDir,{recursive:!0}),await Xo(a,e.libEntry),await Xo(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let p=Qr(e.libDir,"package.json"),_=`${JSON.stringify({type:"module"},null,2)}
|
|
93
|
+
`;return await Zr(p,"utf8").catch(()=>null)!==_&&await Ku(p,_),d.libVersion=u,await Bt(d,e.configFile),Yo.info("dist installed",{libEntry:e.libEntry,fromVersion:l,toVersion:u}),l?{kind:"version-changed",fromVersion:l,toVersion:u,libEntry:e.libEntry}:{kind:"first-install",libVersion:u,libEntry:e.libEntry}}var df=R("cli");function Et(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 lf(r){let e=r.slice(2);if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let i=e,{value:a,rest:c}=Et(i,"--pat-token");i=c;let{value:u,rest:d}=Et(i,"--pair-code");i=d;let{value:l,rest:p}=Et(i,"--env");i=p;let{value:_,rest:v}=Et(i,"--handshake-url");i=v;let{value:w,rest:C}=Et(i,"--frontier-url");i=C;let{value:P}=Et(i,"--agent-id");if(!a||!u)return{mode:"help"};let T={mode:"pair",privatecode:a,pairingCode:u};return l&&(T.env=l),_&&(T.handshakeUrl=_),w&&(T.frontierUrl=w),P&&(T.agentId=P),T}var hf=`
|
|
94
94
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
95
95
|
|
|
96
96
|
Usage:
|
|
@@ -117,35 +117,35 @@ Auto-connect agent (optional):
|
|
|
117
117
|
|
|
118
118
|
Internal:
|
|
119
119
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
120
|
-
`.trimStart();async function
|
|
121
|
-
`),1;if(
|
|
122
|
-
`),1;let
|
|
123
|
-
${JSON.stringify(
|
|
124
|
-
`),0}async function
|
|
125
|
-
`),0;if(
|
|
126
|
-
`),0;try{return await
|
|
127
|
-
`),0}catch(
|
|
128
|
-
`),1}}async function
|
|
129
|
-
`),1;try{let
|
|
130
|
-
${JSON.stringify(
|
|
131
|
-
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(
|
|
132
|
-
`),1)}catch(
|
|
133
|
-
`),1}}async function
|
|
134
|
-
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(
|
|
135
|
-
`)}await new Promise(
|
|
136
|
-
`)}catch(
|
|
137
|
-
`)}let
|
|
138
|
-
`)}catch(
|
|
120
|
+
`.trimStart();async function ra(r=process.argv,e={}){let i=lf(r);switch(i.mode){case"help":return process.stdout.write(hf),0;case"daemon":{try{await Wo()}catch(a){return df.error("daemon start failed",{err:String(a)}),1}return new Promise(()=>{})}case"status":return gf(e);case"stop":return pf(e);case"refresh":return mf(e);case"uninstall":return _f(e);case"install-service":return wf();case"pair":{let a={};return i.env&&(a.env=i.env),i.handshakeUrl&&(a.handshakeUrl=i.handshakeUrl),i.frontierUrl&&(a.frontierUrl=i.frontierUrl),yf(i.privatecode,i.pairingCode,e,a,i.agentId)}}}async function sa(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 gf(r){let e=r.paths??K(),i=new Ve(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
121
|
+
`),1;if(a.kind==="stale")return await sa(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
122
|
+
`),1;let c=await i.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
123
|
+
${JSON.stringify(c.body,null,2)}
|
|
124
|
+
`),0}async function pf(r){let e=r.paths??K(),i=new Ve(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
125
|
+
`),0;if(a.kind==="stale")return await sa(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
126
|
+
`),0;try{return await i.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
127
|
+
`),0}catch(c){return process.stdout.write(`coze-bridge: stop failed: ${String(c)}
|
|
128
|
+
`),1}}async function mf(r){let e=new Ve(r.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
129
|
+
`),1;try{let a=await e.request({method:"POST",path:"/refresh"});return a.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
130
|
+
${JSON.stringify(a.body,null,2)}
|
|
131
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(a.body)}
|
|
132
|
+
`),1)}catch(a){return process.stderr.write(`coze-bridge: refresh failed: ${String(a)}
|
|
133
|
+
`),1}}async function _f(r){let e=new Ve(r.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
134
|
+
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(u){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(u)}
|
|
135
|
+
`)}await new Promise(u=>setTimeout(u,500))}if(!r.skipSupervisor)try{let{getSupervisor:u,buildContext:d}=await Promise.resolve().then(()=>(os(),is)),l=u();await l.uninstall(d()),process.stdout.write(`coze-bridge: ${l.platform} supervisor unregistered
|
|
136
|
+
`)}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
|
|
137
|
+
`)}let a=r.paths??K(),{rm:c}=await import("node:fs/promises");try{await c(a.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${a.cozeRoot}
|
|
138
|
+
`)}catch(u){return process.stderr.write(`coze-bridge: remove failed: ${String(u)}
|
|
139
139
|
`),1}return process.stdout.write(`coze-bridge: uninstalled
|
|
140
|
-
`),0}async function
|
|
141
|
-
`),await
|
|
140
|
+
`),0}async function wf(){try{let{getSupervisor:r,buildContext:e}=await Promise.resolve().then(()=>(os(),is)),i=r(),a=e();return process.stdout.write(`coze-bridge: installing ${i.platform} supervisor...
|
|
141
|
+
`),await i.install(a),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
142
142
|
`),0}catch(r){return process.stderr.write(`coze-bridge: --install-service failed: ${String(r)}
|
|
143
|
-
`),1}}async function
|
|
144
|
-
`),(await
|
|
145
|
-
`)}let
|
|
146
|
-
`),await
|
|
147
|
-
`),1;let
|
|
148
|
-
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
149
|
-
`),1)}catch(
|
|
150
|
-
`),1}}async function
|
|
143
|
+
`),1}}async function yf(r,e,i,a={},c){let u=new Ve(i.paths),d=i.spawnDaemon??Jo;if(!i.skipDistInstall){let _=await $o({paths:i.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
|
|
144
|
+
`),(await u.probe()).kind==="connected"&&(await u.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(w=>setTimeout(w,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
|
|
145
|
+
`)}let l=await u.probe();if(l.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
146
|
+
`),await d({paths:i.paths}),l=await bf(u,i.waitTimeoutMs??1e4,i.sleep??vf),l.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${l.kind}
|
|
147
|
+
`),1;let p={privatecode:r,pairing_code:e};a.env&&(p.env=a.env),a.handshakeUrl&&(p.handshake_url=a.handshakeUrl),a.frontierUrl&&(p.frontier_url=a.frontierUrl),c&&(p.agent_id=c);try{let _=await u.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});return _.status===200&&_.body?.ok?(process.stdout.write(`coze-bridge: paired (${_.body.note??"ok"})
|
|
148
|
+
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
|
|
149
|
+
`),1)}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
|
|
150
|
+
`),1}}async function bf(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 vf(r){return new Promise(e=>setTimeout(e,r))}ra(process.argv).then(r=>process.exit(r),r=>{process.stderr.write(`fatal: ${r instanceof Error?r.stack??r.message:String(r)}
|
|
151
151
|
`),process.exit(1)});
|