coze-bridge 0.1.33 → 0.1.35
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 +58 -58
- 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(n){return{debug:(e,t)=>Ct("debug",n,e,t),info:(e,t)=>Ct("info",n,e,t),warn:(e,t)=>Ct("warn",n,e,t),error:(e,t)=>Ct("error",n,e,t),child:e=>w(`${n}.${e}`)}}var Ot,ds,ba,Na,us,k=K(()=>{"use strict";Ot={debug:10,info:20,warn:30,error:40},ds=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),ba=process.stdout,Na=process.stderr,us={}});import{homedir as Da}from"node:os";import{join as L}from"node:path";function T(n){let e=n??Da(),t=L(e,".coze"),r=L(t,"bridge"),s=L(r,"lib");return{cozeRoot:t,bridgeRoot:r,libDir:s,libEntry:L(s,"index.js"),pidFile:L(r,"bridge.pid"),portFile:L(r,"bridge.port"),tokenFile:L(r,"bridge.token"),logFile:L(r,"bridge.log"),installLock:L(r,"install.lock"),configFile:L(r,"config.json"),agentsRoot:L(t,"agents")}}function ae(n,e=T()){let t=L(e.agentsRoot,n);return{root:t,config:L(t,"config.json"),workspace:L(t,"workspace"),logs:L(t,"logs")}}var z=K(()=>{"use strict"});var Dt={};Mn(Dt,{AGENT_CONFIG_FILE_MODE:()=>bt,enforceAgentConfigMode:()=>Ba,loadAgentConfig:()=>q,persistAgentSessions:()=>Fn,persistAgentSkills:()=>Nt,saveAgentConfig:()=>X});import{chmod as La,stat as Ma}from"node:fs/promises";function q(n,e){return Le(ae(n,e).config)}function X(n,e){return Pt(ae(n.agentId,e).config,n,{mode:bt})}async function Ba(n,e){if(process.platform==="win32")return;let t=ae(n,e).config;try{let r=await Ma(t);if(!r.isFile())return;let s=r.mode&511;s!==bt&&(await La(t,bt),hs.warn("agent config mode auto-corrected to 0600",{path:t,from:s.toString(8)}))}catch(r){if(r.code==="ENOENT")return;hs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:t,err:String(r)})}}async function Fn(n,e,t){let r=await q(n,t);r&&(r.sessions=Object.fromEntries(e),await X(r,t))}async function Nt(n,e,t){let r=await q(n,t);r&&(r.skills=e,await X(r,t))}var hs,bt,ge=K(()=>{"use strict";At();k();z();hs=w("agent-config"),bt=384});function Ol(){return gi||(gi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bl(){return pi||(pi=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Nl(n){let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("success",i),n.removeEventListener("error",o)},i=()=>{t(W(n.result)),s()},o=()=>{r(n.error),s()};n.addEventListener("success",i),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&mi.set(t,n)}).catch(()=>{}),Zn.set(e,n),e}function Dl(n){if(Xn.has(n))return;let e=new Promise((t,r)=>{let s=()=>{n.removeEventListener("complete",i),n.removeEventListener("error",o),n.removeEventListener("abort",o)},i=()=>{t(),s()},o=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",i),n.addEventListener("error",o),n.addEventListener("abort",o)});Xn.set(n,e)}function wi(n){Yn=n(Yn)}function Ll(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let r=n.call(gt(this),e,...t);return _i.set(r,e.sort?e.sort():[e]),W(r)}:bl().includes(n)?function(...e){return n.apply(gt(this),e),W(mi.get(this))}:function(...e){return W(n.apply(gt(this),e))}}function Ml(n){return typeof n=="function"?Ll(n):(n instanceof IDBTransaction&&Dl(n),Cl(n,Ol())?new Proxy(n,Yn):n)}function W(n){if(n instanceof IDBRequest)return Nl(n);if(Kn.has(n))return Kn.get(n);let e=Ml(n);return e!==n&&(Kn.set(n,e),Zn.set(e,n)),e}var Cl,gi,pi,mi,Xn,_i,Kn,Zn,Yn,gt,er=K(()=>{Cl=(n,e)=>e.some(t=>n instanceof t);mi=new WeakMap,Xn=new WeakMap,_i=new WeakMap,Kn=new WeakMap,Zn=new WeakMap;Yn={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Xn.get(n);if(e==="objectStoreNames")return n.objectStoreNames||_i.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return W(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};gt=n=>Zn.get(n)});var Si={};Mn(Si,{deleteDB:()=>Fl,openDB:()=>Bl,unwrap:()=>gt,wrap:()=>W});function Bl(n,e,{blocked:t,upgrade:r,blocking:s,terminated:i}={}){let o=indexedDB.open(n,e),a=W(o);return r&&o.addEventListener("upgradeneeded",c=>{r(W(o.result),c.oldVersion,c.newVersion,W(o.transaction))}),t&&o.addEventListener("blocked",()=>t()),a.then(c=>{i&&c.addEventListener("close",()=>i()),s&&c.addEventListener("versionchange",()=>s())}).catch(()=>{}),a}function Fl(n,{blocked:e}={}){let t=indexedDB.deleteDatabase(n);return e&&t.addEventListener("blocked",()=>e()),W(t).then(()=>{})}function yi(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(tr.get(e))return tr.get(e);let t=e.replace(/FromIndex$/,""),r=e!==t,s=$l.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||Ul.includes(t)))return;let i=async function(o,...a){let c=this.transaction(o,s?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),s&&c.done]))[0]};return tr.set(e,i),i}var Ul,$l,tr,Ei=K(()=>{er();er();Ul=["get","getKey","getAll","getAllKeys","count"],$l=["put","add","delete","clear"],tr=new Map;wi(n=>({...n,get:(e,t,r)=>yi(e,t)||n.get(e,t,r),has:(e,t)=>!!yi(e,t)||n.has(e,t)}))});var le=$((wm,Ji)=>{"use strict";var Wi=["nodebuffer","arraybuffer","fragments"],ji=typeof Blob<"u";ji&&Wi.push("blob");Ji.exports={BINARY_TYPES:Wi,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ji,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var St=$((ym,cn)=>{"use strict";var{EMPTY_BUFFER:Gd}=le(),Ir=Buffer[Symbol.species];function Hd(n,e){if(n.length===0)return Gd;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Ir(t.buffer,t.byteOffset,r):t}function Vi(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Qi(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Wd(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function xr(n){if(xr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ir(n):ArrayBuffer.isView(n)?e=new Ir(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),xr.readOnly=!1),e}cn.exports={concat:Hd,mask:Vi,toArrayBuffer:Wd,toBuffer:xr,unmask:Qi};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=A("bufferutil");cn.exports.mask=function(e,t,r,s,i){i<48?Vi(e,t,r,s,i):n.mask(e,t,r,s,i)},cn.exports.unmask=function(e,t){e.length<32?Qi(e,t):n.unmask(e,t)}}catch{}});var Yi=$((Sm,Xi)=>{"use strict";var Ki=Symbol("kDone"),Tr=Symbol("kRun"),Rr=class{constructor(e){this[Ki]=()=>{this.pending--,this[Tr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Tr]()}[Tr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ki])}}};Xi.exports=Rr});var Ve=$((Em,no)=>{"use strict";var Et=A("zlib"),Zi=St(),jd=Yi(),{kStatusCode:eo}=le(),Jd=Buffer[Symbol.species],Vd=Buffer.from([0,0,255,255]),dn=Symbol("permessage-deflate"),de=Symbol("total-length"),je=Symbol("callback"),ye=Symbol("buffers"),Je=Symbol("error"),ln,Pr=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,!ln){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ln=new jd(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[je];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){ln.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){ln.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Et.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[dn]=this,this._inflate[de]=0,this._inflate[ye]=[],this._inflate.on("error",Kd),this._inflate.on("data",to)}this._inflate[je]=r,this._inflate.write(e),t&&this._inflate.write(Vd),this._inflate.flush(()=>{let i=this._inflate[Je];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Zi.concat(this._inflate[ye],this._inflate[de]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[de]=0,this._inflate[ye]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Et.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Et.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[de]=0,this._deflate[ye]=[],this._deflate.on("data",Qd)}this._deflate[je]=r,this._deflate.write(e),this._deflate.flush(Et.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Zi.concat(this._deflate[ye],this._deflate[de]);t&&(i=new Jd(i.buffer,i.byteOffset,i.length-4)),this._deflate[je]=null,this._deflate[de]=0,this._deflate[ye]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};no.exports=Pr;function Qd(n){this[ye].push(n),this[de]+=n.length}function to(n){if(this[de]+=n.length,this[dn]._maxPayload<1||this[de]<=this[dn]._maxPayload){this[ye].push(n);return}this[Je]=new RangeError("Max payload size exceeded"),this[Je].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Je][eo]=1009,this.removeListener("data",to),this.reset()}function Kd(n){if(this[dn]._inflate=null,this[Je]){this[je](this[Je]);return}n[eo]=1007,this[je](n)}});var Qe=$((vm,un)=>{"use strict";var{isUtf8:ro}=A("buffer"),{hasBlob:Xd}=le(),Yd=[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 Zd(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ar(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function eu(n){return Xd&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}un.exports={isBlob:eu,isValidStatusCode:Zd,isValidUTF8:Ar,tokenChars:Yd};if(ro)un.exports.isValidUTF8=function(n){return n.length<24?Ar(n):ro(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=A("utf-8-validate");un.exports.isValidUTF8=function(e){return e.length<32?Ar(e):n(e)}}catch{}});var Dr=$((km,uo)=>{"use strict";var{Writable:tu}=A("stream"),so=Ve(),{BINARY_TYPES:nu,EMPTY_BUFFER:io,kStatusCode:ru,kWebSocket:su}=le(),{concat:Cr,toArrayBuffer:iu,unmask:ou}=St(),{isValidStatusCode:au,isValidUTF8:oo}=Qe(),fn=Buffer[Symbol.species],J=0,ao=1,co=2,lo=3,Or=4,br=5,hn=6,Nr=class extends tu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||nu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[su]=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=J}_write(e,t,r){if(this._opcode===8&&this._state==J)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new fn(r.buffer,r.byteOffset+e,r.length-e),new fn(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new fn(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case J:this.getInfo(e);break;case ao:this.getPayloadLength16(e);break;case co:this.getPayloadLength64(e);break;case lo:this.getMask();break;case Or:this.getData(e);break;case br:case hn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[so.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=ao:this._payloadLength===127?this._state=co:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=lo:this._state=Or}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Or}getData(e){let t=io;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&&ou(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=br,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[so.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===J&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=J;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Cr(r,t):this._binaryType==="arraybuffer"?s=iu(Cr(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=J):(this._state=hn,setImmediate(()=>{this.emit("message",s,!0),this._state=J,this.startLoop(e)}))}else{let s=Cr(r,t);if(!this._skipUTF8Validation&&!oo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===br||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=J):(this._state=hn,setImmediate(()=>{this.emit("message",s,!1),this._state=J,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,io),this.end();else{let r=e.readUInt16BE(0);if(!au(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new fn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!oo(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=J;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=J):(this._state=hn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=J,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[ru]=s,o}};uo.exports=Nr});var Br=$((xm,go)=>{"use strict";var{Duplex:Im}=A("stream"),{randomFillSync:cu}=A("crypto"),fo=Ve(),{EMPTY_BUFFER:lu,kWebSocket:du,NOOP:uu}=le(),{isBlob:Ke,isValidStatusCode:fu}=Qe(),{mask:ho,toBuffer:Pe}=St(),V=Symbol("kByteLength"),hu=Buffer.alloc(4),gn=8*1024,Ae,Xe=gn,Z=0,gu=1,pu=2,Lr=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Z,this.onerror=uu,this[du]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||hu,t.generateMask?t.generateMask(r):(Xe===gn&&(Ae===void 0&&(Ae=Buffer.alloc(gn)),cu(Ae,0,gn),Xe=0),r[0]=Ae[Xe++],r[1]=Ae[Xe++],r[2]=Ae[Xe++],r[3]=Ae[Xe++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[V]!==void 0?a=t[V]:(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 l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],o?[l,e]:s?(ho(e,r,l,i,a),[l]):(ho(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=lu;else{if(typeof e!="number"||!fu(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={[V]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Z?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ke(e)?(s=e.size,i=!1):(e=Pe(e),s=e.length,i=Pe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[V]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Z?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):Ke(e)?(s=e.size,i=!1):(e=Pe(e),s=e.length,i=Pe.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[V]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Z?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[fo.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Ke(e)?(a=e.size,c=!1):(e=Pe(e),a=e.length,c=Pe.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 l={[V]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Ke(e)?this._state!==Z?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Z?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[V],this._state=pu,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mr,this,a,s);return}this._bufferedBytes-=r[V];let o=Pe(i);t?this.dispatch(o,t,r,s):(this._state=Z,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(mu,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[fo.extensionName];this._bufferedBytes+=r[V],this._state=gu,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Mr(this,c,s);return}this._bufferedBytes-=r[V],this._state=Z,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Z&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][V],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][V],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)}};go.exports=Lr;function Mr(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function mu(n,e,t){Mr(n,e,t),n.onerror(e)}});var ko=$((Tm,vo)=>{"use strict";var{kForOnEventAttribute:vt,kListener:Fr}=le(),po=Symbol("kCode"),mo=Symbol("kData"),_o=Symbol("kError"),wo=Symbol("kMessage"),yo=Symbol("kReason"),Ye=Symbol("kTarget"),So=Symbol("kType"),Eo=Symbol("kWasClean"),ue=class{constructor(e){this[Ye]=null,this[So]=e}get target(){return this[Ye]}get type(){return this[So]}};Object.defineProperty(ue.prototype,"target",{enumerable:!0});Object.defineProperty(ue.prototype,"type",{enumerable:!0});var Ce=class extends ue{constructor(e,t={}){super(e),this[po]=t.code===void 0?0:t.code,this[yo]=t.reason===void 0?"":t.reason,this[Eo]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[po]}get reason(){return this[yo]}get wasClean(){return this[Eo]}};Object.defineProperty(Ce.prototype,"code",{enumerable:!0});Object.defineProperty(Ce.prototype,"reason",{enumerable:!0});Object.defineProperty(Ce.prototype,"wasClean",{enumerable:!0});var Ze=class extends ue{constructor(e,t={}){super(e),this[_o]=t.error===void 0?null:t.error,this[wo]=t.message===void 0?"":t.message}get error(){return this[_o]}get message(){return this[wo]}};Object.defineProperty(Ze.prototype,"error",{enumerable:!0});Object.defineProperty(Ze.prototype,"message",{enumerable:!0});var kt=class extends ue{constructor(e,t={}){super(e),this[mo]=t.data===void 0?null:t.data}get data(){return this[mo]}};Object.defineProperty(kt.prototype,"data",{enumerable:!0});var _u={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[vt]&&s[Fr]===e&&!s[vt])return;let r;if(n==="message")r=function(i,o){let a=new kt("message",{data:o?i:i.toString()});a[Ye]=this,pn(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ce("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ye]=this,pn(e,this,a)};else if(n==="error")r=function(i){let o=new Ze("error",{error:i,message:i.message});o[Ye]=this,pn(e,this,o)};else if(n==="open")r=function(){let i=new ue("open");i[Ye]=this,pn(e,this,i)};else return;r[vt]=!!t[vt],r[Fr]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Fr]===e&&!t[vt]){this.removeListener(n,t);break}}};vo.exports={CloseEvent:Ce,ErrorEvent:Ze,Event:ue,EventTarget:_u,MessageEvent:kt};function pn(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var mn=$((Rm,Io)=>{"use strict";var{tokenChars:It}=Qe();function oe(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function wu(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,f=0;for(;f<n.length;f++)if(l=n.charCodeAt(f),o===void 0)if(d===-1&&It[l]===1)c===-1&&(c=f);else if(f!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f);let p=n.slice(c,d);l===44?(oe(e,p,t),t=Object.create(null)):o=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(d===-1&&It[l]===1)c===-1&&(c=f);else if(l===32||l===9)d===-1&&c!==-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f),oe(t,n.slice(c,d),!0),l===44&&(oe(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=n.slice(c,f),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(s){if(It[l]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);c===-1?c=f:r||(r=!0),s=!1}else if(i)if(It[l]===1)c===-1&&(c=f);else if(l===34&&c!==-1)i=!1,d=f;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(l===34&&n.charCodeAt(f-1)===61)i=!0;else if(d===-1&&It[l]===1)c===-1&&(c=f);else if(c!==-1&&(l===32||l===9))d===-1&&(d=f);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${f}`);d===-1&&(d=f);let p=n.slice(c,d);r&&(p=p.replace(/\\/g,""),r=!1),oe(t,a,p),l===44&&(oe(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=f);let u=n.slice(c,d);return o===void 0?oe(e,u,t):(a===void 0?oe(t,u,!0):r?oe(t,a,u.replace(/\\/g,"")):oe(t,a,u),oe(e,o,t)),e}function yu(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Io.exports={format:yu,parse:wu}});var Sn=$((Cm,Mo)=>{"use strict";var Su=A("events"),Eu=A("https"),vu=A("http"),Ro=A("net"),ku=A("tls"),{randomBytes:Iu,createHash:xu}=A("crypto"),{Duplex:Pm,Readable:Am}=A("stream"),{URL:Ur}=A("url"),Se=Ve(),Tu=Dr(),Ru=Br(),{isBlob:Pu}=Qe(),{BINARY_TYPES:xo,CLOSE_TIMEOUT:Au,EMPTY_BUFFER:_n,GUID:Cu,kForOnEventAttribute:$r,kListener:Ou,kStatusCode:bu,kWebSocket:O,NOOP:Po}=le(),{EventTarget:{addEventListener:Nu,removeEventListener:Du}}=ko(),{format:Lu,parse:Mu}=mn(),{toBuffer:Bu}=St(),Ao=Symbol("kAborted"),zr=[8,13],fe=["CONNECTING","OPEN","CLOSING","CLOSED"],Fu=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class n extends Su{constructor(e,t,r){super(),this._binaryType=xo[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_n,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),Co(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){xo.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new Tu({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Ru(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[O]=this,i[O]=this,e[O]=this,s.on("conclude",zu),s.on("drain",qu),s.on("error",Gu),s.on("message",Hu),s.on("ping",Wu),s.on("pong",ju),i.onerror=Ju,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",No),e.on("data",yn),e.on("end",Do),e.on("error",Lo),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Se.extensionName]&&this._extensions[Se.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){H(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),bo(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||_n,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||_n,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){qr(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Se.extensionName]||(s.compress=!1),this._sender.send(e||_n,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){H(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:fe.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:fe.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:fe.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:fe.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(x.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(x.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[$r])return e[Ou];return null},set(e){for(let t of this.listeners(n))if(t[$r]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[$r]:!0})}})});x.prototype.addEventListener=Nu;x.prototype.removeEventListener=Du;Mo.exports=x;function Co(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Au,protocolVersion:zr[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!zr.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${zr.join(", ")})`);let i;if(e instanceof Ur)i=e;else try{i=new Ur(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let _=new SyntaxError(c);if(n._redirects===0)throw _;wn(n,_);return}let l=o?443:80,d=Iu(16).toString("base64"),f=o?Eu.request:vu.request,u=new Set,p;if(s.createConnection=s.createConnection||(o?$u:Uu),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new Se({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Lu({[Se.extensionName]:p.offer()})),t.length){for(let _ of t){if(typeof _!="string"||!Fu.test(_)||u.has(_))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(_)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let _=s.path.split(":");s.socketPath=_[0],s.path=_[1]}let m;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let _=r&&r.headers;if(r={...r,headers:{}},_)for(let[v,C]of Object.entries(_))r.headers[v.toLowerCase()]=C}else if(n.listenerCount("redirect")===0){let _=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!_||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,_||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),m=n._req=f(s),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=f(s);s.timeout&&m.on("timeout",()=>{H(n,m,"Opening handshake has timed out")}),m.on("error",_=>{m===null||m[Ao]||(m=n._req=null,wn(n,_))}),m.on("response",_=>{let v=_.headers.location,C=_.statusCode;if(v&&s.followRedirects&&C>=300&&C<400){if(++n._redirects>s.maxRedirects){H(n,m,"Maximum redirects exceeded");return}m.abort();let F;try{F=new Ur(v,e)}catch{let P=new SyntaxError(`Invalid URL: ${v}`);wn(n,P);return}Co(n,F,t,r)}else n.emit("unexpected-response",m,_)||H(n,m,`Unexpected server response: ${_.statusCode}`)}),m.on("upgrade",(_,v,C)=>{if(n.emit("upgrade",_),n.readyState!==x.CONNECTING)return;m=n._req=null;let F=_.headers.upgrade;if(F===void 0||F.toLowerCase()!=="websocket"){H(n,v,"Invalid Upgrade header");return}let b=xu("sha1").update(d+Cu).digest("base64");if(_.headers["sec-websocket-accept"]!==b){H(n,v,"Invalid Sec-WebSocket-Accept header");return}let P=_.headers["sec-websocket-protocol"],g;if(P!==void 0?u.size?u.has(P)||(g="Server sent an invalid subprotocol"):g="Server sent a subprotocol but none was requested":u.size&&(g="Server sent no subprotocol"),g){H(n,v,g);return}P&&(n._protocol=P);let E=_.headers["sec-websocket-extensions"];if(E!==void 0){if(!p){H(n,v,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=Mu(E)}catch{H(n,v,"Invalid Sec-WebSocket-Extensions header");return}let Q=Object.keys(I);if(Q.length!==1||Q[0]!==Se.extensionName){H(n,v,"Server indicated an extension that was not requested");return}try{p.accept(I[Se.extensionName])}catch{H(n,v,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Se.extensionName]=p}n.setSocket(v,C,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(m,n):m.end()}function wn(n,e){n._readyState=x.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Uu(n){return n.path=n.socketPath,Ro.connect(n)}function $u(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Ro.isIP(n.host)?"":n.host),ku.connect(n)}function H(n,e,t){n._readyState=x.CLOSING;let r=new Error(t);Error.captureStackTrace(r,H),e.setHeader?(e[Ao]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(wn,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function qr(n,e,t){if(e){let r=Pu(e)?e.size:Bu(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${fe[n.readyState]})`);process.nextTick(t,r)}}function zu(n,e){let t=this[O];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[O]!==void 0&&(t._socket.removeListener("data",yn),process.nextTick(Oo,t._socket),n===1005?t.close():t.close(n,e))}function qu(){let n=this[O];n.isPaused||n._socket.resume()}function Gu(n){let e=this[O];e._socket[O]!==void 0&&(e._socket.removeListener("data",yn),process.nextTick(Oo,e._socket),e.close(n[bu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function To(){this[O].emitClose()}function Hu(n,e){this[O].emit("message",n,e)}function Wu(n){let e=this[O];e._autoPong&&e.pong(n,!this._isServer,Po),e.emit("ping",n)}function ju(n){this[O].emit("pong",n)}function Oo(n){n.resume()}function Ju(n){let e=this[O];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,bo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function bo(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function No(){let n=this[O];if(this.removeListener("close",No),this.removeListener("data",yn),this.removeListener("end",Do),n._readyState=x.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[O]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",To),n._receiver.on("finish",To))}function yn(n){this[O]._receiver.write(n)||this.pause()}function Do(){let n=this[O];n._readyState=x.CLOSING,n._receiver.end(),this.end()}function Lo(){let n=this[O];this.removeListener("error",Lo),this.on("error",Po),n&&(n._readyState=x.CLOSING,this.destroy())}});var $o=$((bm,Uo)=>{"use strict";var Om=Sn(),{Duplex:Vu}=A("stream");function Bo(n){n.emit("close")}function Qu(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Fo(n){this.removeListener("error",Fo),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Ku(n,e){let t=!0,r=new Vu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(Bo,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(Bo,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Qu),r.on("error",Fo),r}Uo.exports=Ku});var Gr=$((Nm,zo)=>{"use strict";var{tokenChars:Xu}=Qe();function Yu(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&Xu[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}zo.exports={parse:Yu}});var Vo=$((Lm,Jo)=>{"use strict";var Zu=A("events"),En=A("http"),{Duplex:Dm}=A("stream"),{createHash:ef}=A("crypto"),qo=mn(),Oe=Ve(),tf=Gr(),nf=Sn(),{CLOSE_TIMEOUT:rf,GUID:sf,kWebSocket:of}=le(),af=/^[+/0-9A-Za-z]{22}==$/,Go=0,Ho=1,jo=2,Hr=class extends Zu{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:rf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nf,...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=En.createServer((r,s)=>{let i=En.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=cf(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Go}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===jo){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(xt,this);return}if(e&&this.once("close",e),this._state!==Ho)if(this._state=Ho,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(xt,this):process.nextTick(xt,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{xt(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",Wo);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){be(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){be(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!af.test(i)){be(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){be(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Tt(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=tf.parse(c)}catch{be(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&d!==void 0){let u=new Oe({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=qo.parse(d);p[Oe.extensionName]&&(u.accept(p[Oe.extensionName]),f[Oe.extensionName]=u)}catch{be(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let u={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(u,(p,m,_,v)=>{if(!p)return Tt(t,m||401,_,v);this.completeUpgrade(f,i,l,e,t,r,s)});return}if(!this.options.verifyClient(u))return Tt(t,401)}this.completeUpgrade(f,i,l,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[of])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Go)return Tt(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${ef("sha1").update(t+sf).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;f&&(l.push(`Sec-WebSocket-Protocol: ${f}`),d._protocol=f)}if(e[Oe.extensionName]){let f=e[Oe.extensionName].params,u=qo.format({[Oe.extensionName]:[f]});l.push(`Sec-WebSocket-Extensions: ${u}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
8
|
+
var R0=Object.create;var yr=Object.defineProperty;var N0=Object.getOwnPropertyDescriptor;var L0=Object.getOwnPropertyNames;var O0=Object.getPrototypeOf,B0=Object.prototype.hasOwnProperty;var $=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,i)=>(typeof require<"u"?require:e)[i]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Le=(n,e)=>()=>(n&&(e=n(n=0)),e);var ce=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Hs=(n,e)=>{for(var i in e)yr(n,i,{get:e[i],enumerable:!0})},M0=(n,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of L0(e))!B0.call(n,c)&&c!==i&&yr(n,c,{get:()=>e[c],enumerable:!(a=N0(e,c))||a.enumerable});return n};var Oe=(n,e,i)=>(i=n!=null?R0(O0(n)):{},M0(e||!n||!n.__esModule?yr(i,"default",{value:n,enumerable:!0}):i,n));import{chmod as z0,mkdir as q0,readFile as F0,rename as Gs,writeFile as js}from"node:fs/promises";import{dirname as U0}from"node:path";async function ut(n){try{let e=await F0(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Qt(n,e,i){await q0(U0(n),{recursive:!0});let a=`${JSON.stringify(e,null,2)}
|
|
9
|
+
`,c=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{i?.mode!==void 0?await js(c,a,{encoding:"utf8",mode:i.mode}):await js(c,a,"utf8"),await Gs(c,n),i?.mode!==void 0&&await z0(n,i.mode)}catch(u){await Gs(c,c).catch(()=>{});let{rm:f}=await import("node:fs/promises");throw await f(c,{force:!0}).catch(()=>{}),u}}var en=Le(()=>{"use strict"});function Js(n){return nn[Ks]<=nn[n]}function br(n){Ws={...n}}function tn(n,e,i,a){if(nn[n]<nn[Ks])return;let c=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:i,...Ws,...a});n==="error"||n==="warn"?G0.write(`${c}
|
|
10
|
+
`):H0.write(`${c}
|
|
11
|
+
`)}function T(n){return{debug:(e,i)=>tn("debug",n,e,i),info:(e,i)=>tn("info",n,e,i),warn:(e,i)=>tn("warn",n,e,i),error:(e,i)=>tn("error",n,e,i),child:e=>T(`${n}.${e}`)}}var nn,Ks,H0,G0,Ws,F=Le(()=>{"use strict";nn={debug:10,info:20,warn:30,error:40},Ks=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),H0=process.stdout,G0=process.stderr,Ws={}});import{homedir as j0}from"node:os";import{join as ie}from"node:path";function K(n){let e=n??j0(),i=ie(e,".coze"),a=ie(i,"bridge"),c=ie(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:ie(c,"index.js"),pidFile:ie(a,"bridge.pid"),portFile:ie(a,"bridge.port"),tokenFile:ie(a,"bridge.token"),logFile:ie(a,"bridge.log"),installLock:ie(a,"install.lock"),configFile:ie(a,"config.json"),agentsRoot:ie(i,"agents")}}function Be(n,e=K()){let i=ie(e.agentsRoot,n);return{root:i,config:ie(i,"config.json"),workspace:ie(i,"workspace"),logs:ie(i,"logs")}}var xe=Le(()=>{"use strict"});var on={};Hs(on,{AGENT_CONFIG_FILE_MODE:()=>rn,enforceAgentConfigMode:()=>J0,loadAgentConfig:()=>ue,persistAgentSessions:()=>vr,persistAgentSkills:()=>sn,saveAgentConfig:()=>we});import{chmod as K0,stat as W0}from"node:fs/promises";function ue(n,e){return ut(Be(n,e).config)}function we(n,e){return Qt(Be(n.agentId,e).config,n,{mode:rn})}async function J0(n,e){if(process.platform==="win32")return;let i=Be(n,e).config;try{let a=await W0(i);if(!a.isFile())return;let c=a.mode&511;c!==rn&&(await K0(i,rn),Vs.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;Vs.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function vr(n,e,i){let a=await ue(n,i);a&&(a.sessions=Object.fromEntries(e),await we(a,i))}async function sn(n,e,i){let a=await ue(n,i);a&&(a.skills=e,await we(a,i))}var Vs,rn,Ke=Le(()=>{"use strict";en();F();xe();Vs=T("agent-config"),rn=384});var co=ce(Q=>{"use strict";var A=D;(function(n,e){let i=D,a=n();for(;;)try{if(-parseInt(i(814))/1+parseInt(i(1674))/2+-parseInt(i(1288))/3+parseInt(i(1535))/4+-parseInt(i(917))/5*(parseInt(i(730))/6)+parseInt(i(665))/7*(-parseInt(i(1644))/8)+parseInt(i(1624))/9*(parseInt(i(1192))/10)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(zn,873656);var Kx=Object[A(1608)+A(1727)],Wx=Object["getOwnPropertyNa"+A(1259)],ro=(n,e)=>function(){return n&&(e=(0,n[Wx(n)[0]])(n=0)),e},Jx=(n,e)=>{let i={uRgNp:function(c,u,f,l){return c(u,f,l)}};for(var a in e)i.uRgNp(Kx,n,a,{get:e[a],enumerable:!0})};function Vx(){return Zi||(Zi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function $x(){let n=A;return Qi||(Qi=[IDBCursor.prototype[n(919)],IDBCursor[n(408)+"e"][n(949)],IDBCursor[n(408)+"e"][n(949)+"PrimaryKey"]])}function Xx(n){let e=A,i={qXVnP:"success",hRSIC:e(421),WvPic:function(c,u){return c(u)},VHkHS:function(c){return c()},HEXli:e(513),zuapa:"vjkGR"},a=new Promise((c,u)=>{let f=e,l={NlFud:function(_,C){return _(C)},WTUEE:function(_,C){return i[D(732)](_,C)},pQrri:function(_){return _()},kqnCz:function(_){return i[D(735)](_)}},p=()=>{let _=D;n[_(611)+_(1121)+_(647)](i[_(1493)],w),n[_(611)+_(1121)+_(647)](i[_(620)],y)},w=()=>{let _=D;l.NlFud(c,l[_(933)](Pe,n[_(1275)])),l[_(577)](p)},y=()=>{let _=D;u(n[_(421)]),l[_(530)](p)};n[f(1257)+f(1682)](i[f(1493)],w),n["addEvent"+f(1682)](f(421),y)});return a[e(415)](c=>{let u=e;if(i.HEXli===i[u(817)])return _0x25fa4f.resolve();c instanceof IDBCursor&&Br[u(1043)](c,n)}).catch(()=>{}),Bn.set(a,n),a}function Yx(n){let e=A,i={zPdgv:function(c,u){return c!==u},fTvIT:function(c){return c()},hUIJZ:e(626),lVhRm:e(421),UMqNu:e(1783)};if(On[e(1771)](n))return;let a=new Promise((c,u)=>{let f=e,l={Xvbjg:i[f(1397)],LLrBH:i[f(1546)],NaIAA:i[f(830)],pyXrC:f(1754)+"or"},p=()=>{let _=f;n[_(611)+_(1121)+_(647)](l[_(1609)],w),n[_(611)+_(1121)+"ner"](l.LLrBH,y),n[_(611)+_(1121)+_(647)](l[_(725)],y)},w=()=>{let _=f;if(i.zPdgv(_(499),_(499)))return this[_(673)].clear();c(),i[_(1523)](p)},y=()=>{u(n[f(421)]||new DOMException(l.pyXrC,"AbortError")),p()};n[f(1257)+f(1682)](i[f(1397)],w),n["addEvent"+f(1682)](i[f(1546)],y),n[f(1257)+"Listener"](f(1783),y)});On[e(1043)](n,a)}function Zx(n){Mn=n(Mn)}function Qx(n){let e=A,i={pLAVh:function(a,c){return a(c)},nKcQc:e(421),vqHfA:function(a,c,u){return a(c,u)},pAFYK:function(a,c){return a(c)},DkOKx:function(a,c){return a===c},jGTms:"XURhq",AFSMU:function(a,c){return a===c},yXJhH:e(1730)+e(1587),JrmOM:function(a,c){return a!==c},cCbwC:e(992),SZLuN:e(1170),Lxhbi:function(a){return a()}};if(i[e(1286)](n,IDBDatabase.prototype[e(1055)+e(754)])&&!(i[e(1064)]in IDBTransaction[e(408)+"e"])){if(i.JrmOM(i[e(1569)],i[e(1148)]))return function(a,...c){let u=e,f=n[u(491)](Ut(this),a,...c);return Or.set(f,a[u(1595)]?a[u(1595)]():[a]),i[u(1739)](Pe,f)};this.emit(i[e(1311)],i[e(1488)](_0x4aaf6d,"error",{message:this[e(430)+"rrorMessage"](_0x470ab1)}))}return i[e(442)]($x)[e(1062)](n)?function(...a){let c=e;return n[c(1222)](i[c(1750)](Ut,this),a),i[c(1739)](Pe,Br[c(843)](this))}:function(...a){let c=e;return i[c(1794)]("XURhq",i.jGTms)?Pe(n[c(1222)](i[c(1739)](Ut,this),a)):this[c(638)][c(763)]}}function eu(n){let e=A,i={SmOtb:function(a,c){return a===c},geJjg:function(a,c){return a(c)},sfeyZ:function(a,c){return a instanceof c},NNvBU:function(a){return a()}};return i.SmOtb(typeof n,e(1405))?i[e(1240)](Qx,n):(i[e(1382)](n,IDBTransaction)&&Yx(n),so(n,i[e(1505)](Vx))?new Proxy(n,Mn):n)}function Pe(n){let e=A,i={grNQm:function(c,u){return c instanceof u},mxqmA:function(c,u){return c(u)},cmxnS:function(c,u){return c!==u}};if(i[e(1526)](n,IDBRequest))return i[e(872)](Xx,n);if(Nn[e(1771)](n))return Nn[e(843)](n);let a=eu(n);return i[e(957)](a,n)&&(Nn[e(1043)](n,a),Bn[e(1043)](a,n)),a}var so,Zi,Qi,Br,On,Or,Nn,Bn,Mn,Ut,eo=ro({"node_modules/idb/build/wrap-idb-value.js"(){let n=A,e={vtHGF:function(i,a){return i instanceof a},mfAhB:function(i,a){return i===a},CHMBt:n(1781),kqQQL:n(1730)+n(1587),FVnrF:"store",qtJlq:function(i,a){return i(a)},xeNSd:function(i,a){return i in a}};so=(i,a)=>a[n(1636)](c=>i instanceof c),Br=new WeakMap,On=new WeakMap,Or=new WeakMap,Nn=new WeakMap,Bn=new WeakMap,Mn={get(i,a,c){let u=n;if(e[u(584)](i,IDBTransaction)){if(e.mfAhB(a,e[u(907)]))return On[u(843)](i);if(a===e[u(608)])return i[u(1730)+u(1587)]||Or.get(i);if(a===e.FVnrF)return c[u(1730)+u(1587)][1]?void 0:c[u(1730)+u(743)](c[u(1730)+"oreNames"][0])}return e[u(1714)](Pe,i[a])},set(i,a,c){return i[a]=c,!0},has(i,a){let c=n;return e.vtHGF(i,IDBTransaction)&&(a===e[c(907)]||a===e.FVnrF)?!0:e[c(1139)](a,i)}},Ut=i=>Bn[n(843)](i)}}),io={};Jx(io,{deleteDB:()=>nu,openDB:()=>tu,unwrap:()=>Ut,wrap:()=>Pe});function tu(n,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let f=A,l={IvfnZ:function(y,_){return y(_)},unaHD:function(y,_){return y===_},oiBsK:f(462),bkIIN:"versionc"+f(1759),SsnUD:f(404)+f(939),SVlNe:f(1735)},p=indexedDB[f(1577)](n,e),w=l[f(1756)](Pe,p);return a&&p.addEventListener(l.SsnUD,y=>{let _=f;a(l[_(1756)](Pe,p[_(1275)]),y[_(1556)+"on"],y[_(809)+"on"],l[_(1756)](Pe,p.transaction))}),i&&p["addEvent"+f(1682)](l.SVlNe,()=>i()),w[f(415)](y=>{let _=f;l.unaHD("lgQVt",l[_(858)])?_0x32b8c2[_(1043)](_0x186f8d,_0x5b820c):(u&&y[_(1257)+_(1682)](_(1529),()=>u()),c&&y.addEventListener(l[_(1641)],()=>c()))})[f(1312)](()=>{}),w}function nu(n,{blocked:e}={}){let i=A,a={MoDBf:"blocked"},c=indexedDB[i(1702)+"tabase"](n);return e&&c[i(1257)+"Listener"](a.MoDBf,()=>e()),Pe(c)[i(415)](()=>{})}function to(n,e){let i=A,a={DAOJa:i(1516),HJRiX:"add",zJCjK:i(1346),LhHML:function(p){return p()},WRkOn:i(1235),cxFxb:i(1137),OJkiF:i(1555)+"ys",ykJhp:i(694),teVxa:function(p,w){return p(w)},zFwpW:function(p,w){return p(w)},MDEuP:function(p,w){return p!==w},vMNBN:i(1623),ZYiDV:i(658),ooRpE:i(1199)+"e",BEbsL:function(p,w){return p instanceof w},JNriN:function(p,w){return p in w},mBtjD:function(p,w){return p===w},tPLgI:i(1561),WCdsG:"qtwtM"};if(!(a[i(792)](n,IDBDatabase)&&!a.JNriN(e,n)&&a[i(562)](typeof e,a[i(1461)])))if(a[i(1166)](a.WCdsG,i(803))){let p=(i(1122)+i(1590)).split("|"),w=0;for(;;){switch(p[w++]){case"0":_0x13e501();continue;case"1":_0x5b8a2a=[a[i(701)],a[i(433)],i(518),a[i(1665)]];continue;case"2":a[i(1602)](_0x22765d);continue;case"3":_0x5d4408=[i(843),a[i(1458)],a.cxFxb,a[i(854)],a[i(566)]];continue;case"4":a[i(1468)](_0x3ecdb9,y=>({...y,get:(_,C,P)=>_0x5b678e(_,C)||y[i(843)](_,C,P),has:(_,C)=>!!_0x4198e9(_,C)||y[i(1771)](_,C)}));continue;case"5":_0x2db1bf=new _0x4c0ea2;continue}break}}else return;if(Ln[i(843)](e))return Ln[i(843)](e);let c=e[i(1042)](/FromIndex$/,""),u=a[i(1166)](e,c),f=ao[i(1062)](c);if(!(c in(u?IDBIndex:IDBObjectStore)[i(408)+"e"])||!(f||oo[i(1062)](c)))return;let l=async function(p,...w){let y=i,_={FoUTh:function(C,P){return a[D(1683)](C,P)}};if(a[y(1166)](a[y(533)],a[y(482)])){let C=this[y(1055)+y(754)](p,f?a[y(607)]:y(1076)),P=C[y(1431)];return u&&(P=P[y(1536)](w[y(784)]())),(await Promise[y(441)]([P[c](...w),f&&C.done]))[0]}else return _0x2fd5a8[y(1222)](OdVJpz.FoUTh(_0x55e227,this),_0x37b4c1),OdVJpz[y(1787)](_0x2cfd34,_0x1ca128[y(843)](this))};return Ln[i(1043)](e,l),l}var oo,ao,Ln,ru=ro({"node_modules/idb/build/index.js"(){let n=A,e={CDEhn:"1|4|0|5|"+n(585),NTRvj:"get",qagLp:n(1235),YuZRq:n(1137),WGAjU:n(1555)+"ys",tloud:n(694),EXuKl:function(c){return c()},BNaHO:function(c){return c()},daPeG:"put",iYKdx:"add",wpLlp:n(518),XqoAw:"clear"},i=e[n(1296)][n(542)]("|"),a=0;for(;;){switch(i[a++]){case"0":oo=[e.NTRvj,e.qagLp,e.YuZRq,e[n(1638)],e[n(600)]];continue;case"1":e[n(1262)](eo);continue;case"2":Zx(c=>({...c,get:(u,f,l)=>to(u,f)||c[n(843)](u,f,l),has:(u,f)=>!!to(u,f)||c[n(1771)](u,f)}));continue;case"3":Ln=new Map;continue;case"4":e[n(394)](eo);continue;case"5":ao=[e.daPeG,e[n(868)],e[n(796)],e[n(1081)]];continue}break}}}),su={idb:function(n){let e=A;n[e(1016)]=Promise[e(1129)]()[e(415)](()=>(ru(),io))[e(415)](function(i){return i})}},no={};function ke(n){let e=A,i={NEAEW:e(1732)+"4"},a=i[e(802)].split("|"),c=0;for(;;){switch(a[c++]){case"0":su[n](u,u.exports,ke);continue;case"1":var u=no[n]={exports:{}};continue;case"2":var f=no[n];continue;case"3":if(f!==void 0)return f[e(1016)];continue;case"4":return u[e(1016)]}break}}(()=>{let n={knufq:"SRZsZ"};ke.d=(e,i)=>{let a=D;if(n[a(447)]!==n[a(447)]){let u=_0x51b6c9[a(1460)].payload;u&&_0xf470b6[a(567)+"rs"](u)}else for(var c in i)ke.o(i,c)&&!ke.o(e,c)&&Object[a(1608)+a(1727)](e,c,{enumerable:!0,get:i[c]})}})(),(()=>{let n=A;ke.o=(e,i)=>Object[n(408)+"e"][n(1206)+n(1727)][n(491)](e,i)})(),(()=>{let n=A,e={JBxjn:function(i,a){return i!=a},TTaIE:n(1662)+"d",VqwqM:n(753),cQVDx:"__esModule"};ke.r=i=>{let a=n;e[a(1325)](e.TTaIE,typeof Symbol)&&Symbol[a(1398)+"Tag"]&&Object[a(1608)+a(1727)](i,Symbol["toString"+a(1747)],{value:e[a(769)]}),Object[a(1608)+a(1727)](i,e[a(1258)],{value:!0})}})();var X={};(()=>{let n=A,e={BDNvS:function(s,t){return s(t)},rJxLI:function(s,t){return s+t},HMYFY:function(s,t){return s+t},iWNrp:function(s,t){return s*t},XOPkJ:function(s,t){return s+t},szZvX:function(s,t){return s(t)},kenGQ:function(s,t){return s+t},xhPmz:function(s,t,r){return s(t,r)},czVNz:function(s,t){return s(t)},HNUtz:function(s,t){return s(t)},wsrjt:"0000",MzhFN:n(1718),MdwIJ:function(s,t){return s(t)},nWwLF:"00000000"+n(1220)+n(1220)+n(1220),vJVLR:function(s,t){return s(t)},blTTI:function(s,t){return s>t},jItIg:function(s,t){return s===t},GfmGL:n(1365),gMWSc:function(s,t){return s<t},WYTCn:function(s,t){return s<t},Hzylu:function(s,t){return s!==t},jliVQ:function(s,t){return s-t},sInvq:function(s,t){return s<t},XGtqM:function(s,t){return s!==t},ucnYk:function(s,t){return s-t},HeqFH:n(670),Jjlrg:n(1113),ywJKE:function(s,t,r){return s(t,r)},kBuYj:n(536),CTfwh:function(s,t){return s(t)},nHFSF:function(s,t){return s>>>t},WdCef:function(s,t,r){return s(t,r)},bQppb:function(s,t){return s(t)},qHLjj:function(s,t){return s(t)},gXTCl:function(s,t){return s&t},hfNxj:n(1726)+n(556)+n(1126)+n(1080),FNPSu:function(s,t){return s===t},UHKGp:n(1726)+"required"+n(1126)+"value",FwqtL:function(s){return s()},sEyys:function(s,t,r){return s(t,r)},xOzPb:function(s,t,r){return s(t,r)},oagiL:function(s,t,r){return s(t,r)},OgqsL:function(s,t){return s(t)},qRLFF:function(s,t,r){return s(t,r)},dwqJo:function(s,t,r){return s(t,r)},okhcn:function(s,t,r){return s(t,r)},PpUlh:function(s,t,r){return s(t,r)},qiJnj:function(s,t,r){return s(t,r)},yKywI:function(s,t){return s!==t},cnOxV:function(s,t){return s!==t},ZRSze:function(s,t,r){return s(t,r)},QlbVb:function(s,t,r){return s(t,r)},vjRee:function(s,t,r){return s(t,r)},Zrkfn:function(s,t){return s!==t},ZCJJz:"kDzFa",thGwE:function(s,t){return s>>>t},xqMCx:function(s,t,r){return s(t,r)},NJwpg:function(s,t,r){return s(t,r)},mTcHf:function(s,t){return s(t)},NoDif:function(s,t){return s(t)},dwEGf:function(s,t){return s(t)},TsJUV:function(s,t){return s===t},NmEVp:n(1726)+"required"+n(1126)+n(457),zqCBm:function(s,t){return s(t)},EshMr:n(421),FUMNq:n(1263),tTBIH:n(531),ZoQCx:function(s,t){return s&t},vdtvq:n(583)+n(806)+n(781),awfyP:n(438)+n(1760),VuYEa:function(s,t){return s===t},FKQuX:function(s,t){return s>>t},RjSLM:function(s,t){return s>=t},fWAxV:function(s,t){return s==t},SJyHR:n(1561),XjRUQ:function(s,t,r,o){return s(t,r,o)},ELase:function(s,t){return s!==t},yVVYV:function(s,t){return s+t},jMPdx:function(s,t){return s>=t},ktzNQ:function(s,t){return s+t},hdksA:function(s,t){return s*t},kvXCM:function(s,t){return s>t},hYIxH:n(572)+n(1178),jRqdu:function(s,t){return s+t},MdhBG:n(1662)+"d",zXenh:n(753),RRGtV:n(1517)+"le",NmKmj:function(s,t,r){return s(t,r)},nHNjn:function(s,t){return s+t},auXOf:function(s,t){return s&t},rmVtt:function(s,t){return s+t},bvgyn:function(s,t){return s===t},opoSe:n(841),HPFWO:n(496),hOuJt:function(s,t){return s|t},qPHRQ:function(s,t){return s<<t},ZUlgU:function(s,t){return s&t},lwYOi:n(1123),xkdSF:function(s,t){return s(t)},pZnKa:function(s,t){return s&t},wMAak:function(s,t){return s+t},ilZAX:function(s,t){return s+t},cotqg:function(s,t){return s+t},aXXnC:function(s,t){return s+t},TObCV:function(s,t){return s!==t},LzEWx:function(s,t){return s<<t},NfCVD:function(s,t){return s===t},lzwMR:"KQIJg",EkCov:function(s,t){return s&t},xMJKa:function(s,t){return s<t},AvDHH:function(s,t){return s<=t},kfehf:function(s,t){return s==t},BEcLD:function(s,t){return s>=t},hHjfV:function(s,t){return s+t},wDByM:function(s,t){return s+t},uEkoC:function(s,t){return s|t},NEVvS:function(s,t){return s<<t},MLdVa:function(s,t){return s|t},CngdK:function(s,t){return s<<t},SqKhY:function(s,t){return s&t},ducCV:function(s,t){return s&t},RThtp:function(s,t){return s&t},LBvDV:function(s,t){return s<t},ETkje:function(s,t){return s>>t},XwwCb:function(s,t){return s&t},NbBAO:function(s,t){return s<t},RPONd:function(s,t){return s<t},WdLcB:function(s,t){return s+t},sjCEr:function(s,t){return s-t},ENUhU:function(s,t){return s+t},Qvuzd:function(s,t){return s<t},vESEw:function(s,t){return s<t},gHtJb:function(s,t,r){return s(t,r)},BFowm:function(s,t){return s<t},PhbGV:function(s,t){return s!==t},gOoji:"NBsWg",rjjdy:function(s,t){return s<t},pNgNP:function(s,t){return s+t},OklqS:function(s,t){return s|t},FLDxT:function(s,t){return s&t},TIJGi:function(s,t){return s|t},mVPOc:function(s,t){return s|t},CKpjg:function(s,t){return s|t},FfoNc:function(s,t){return s&t},Syqsj:function(s,t){return s<t},RZhqi:function(s,t){return s+t},rzDsZ:function(s,t,r){return s(t,r)},wnPIU:function(s,t){return s(t)},IimCg:function(s,t){return s<t},IREtk:function(s,t){return s<<t},cbxME:function(s,t){return s&t},CKGJo:function(s,t){return s|t},UErtm:n(804)+n(1509)+"t",KLbls:"vHbDU",IXGHE:function(s,t){return s(t)},XAUQV:function(s,t){return s<<t},rKjBu:function(s,t){return s(t)},VMnRm:function(s,t){return s<<t},Qziza:function(s,t){return s===t},mHGhH:n(731),rAbTs:function(s,t){return s&t},ozaqm:function(s,t){return s(t)},BiuXS:function(s,t){return s&t},pFhmB:function(s,t){return s<<t},BjyzZ:function(s,t){return s&t},KKHao:function(s,t){return s&t},wdcPn:function(s,t){return s&t},ymNAV:function(s,t){return s<<t},zHLfd:function(s,t){return s<<t},dIuvs:"upgraden"+n(939),MxHMP:function(s,t,r,o,x){return s(t,r,o,x)},ljbmr:function(s,t){return s(t)},PwJOT:function(s,t){return s!==t},zlTcT:n(822),wLYYS:n(1410),OgFtG:function(s,t){return s>>>t},JwaOi:function(s,t){return s|t},GhqZz:function(s,t){return s<t},oPXTX:function(s,t){return s<t},TdhWQ:function(s,t){return s<t},ctmEG:function(s,t,r){return s(t,r)},SChCa:function(s,t){return s+t},CbTaw:function(s,t){return s&t},NNUet:function(s,t){return s+t},lmYtM:function(s,t){return s|t},KRXRz:function(s,t){return s&t},iuBTV:function(s,t){return s+t},WPDqt:function(s,t){return s|t},AkJse:function(s,t){return s&t},kKaVX:function(s,t){return s>>>t},EBbGy:function(s,t){return s+t},ddPep:function(s,t){return s>>>t},FYygo:function(s,t){return s|t},ReDfj:function(s,t){return s>>>t},Fltgv:function(s,t){return s&t},OJDAg:function(s,t){return s+t},VOibV:function(s,t){return s&t},iTFrK:function(s,t){return s|t},ALDRE:function(s,t){return s&t},DjumR:function(s,t){return s+t},aWDOC:function(s,t){return s!==t},vDfje:function(s,t){return s>>>t},NcOOv:function(s,t){return s>>>t},KSeos:function(s,t){return s&t},oQlaG:"GSFrG",EjCLZ:n(1363),TZfEx:function(s,t){return s(t)},FETVm:function(s,t){return s(t)},XBAvF:function(s,t){return s|t},VxzIV:function(s,t){return s<<t},gJuJf:function(s,t){return s<<t},NDeFM:function(s,t){return s|t},iAnJP:function(s,t){return s<<t},RLKTY:function(s,t){return s|t},IXJFr:function(s,t){return s<<t},AdfoP:function(s,t){return s<<t},jAszQ:function(s,t){return s|t},dbFOe:function(s,t){return s|t},DfHxK:function(s,t){return s<<t},FTRHO:function(s,t){return s===t},VOVCV:function(s,t){return s<<t},wguaj:function(s,t){return s<<t},wdqCu:function(s,t){return s&t},yyFGd:function(s,t){return s>>>t},eyKGf:function(s,t){return s&t},iHLSx:function(s,t){return s>>>t},AKqox:function(s,t,r){return s(t,r)},rpOUm:function(s,t){return s>=t},jQHlJ:function(s,t){return s+t},USXrC:function(s,t){return s|t},rPfuJ:function(s,t){return s%t},qlbjl:function(s,t){return s/t},OIJpU:function(s,t){return s>>>t},ZPNNC:function(s,t){return s(t)},OigdD:function(s,t){return s>=t},SQJTI:function(s,t){return s<=t},iCKpg:function(s,t){return s>=t},lryiN:function(s,t){return s|t},AqFyD:function(s,t){return s!==t},WzccU:n(1281),NQVqc:function(s,t){return s===t},qEYZR:function(s,t){return s>>>t},WmLpU:function(s,t){return s&t},nMBXl:function(s,t){return s>>>t},LRVhg:function(s,t){return s+t},nQZXi:function(s,t){return s>>>t},eUuWx:function(s,t){return s+t},qhzWT:function(s,t){return s|t},wqQud:function(s,t){return s<<t},jQnzu:function(s,t){return s<<t},SKjQa:function(s,t){return s===t},KgclX:function(s,t){return s===t},veWaF:function(s,t){return s===t},NQdit:function(s,t){return s===t},fJyTt:function(s,t,r){return s(t,r)},mvNUN:n(1231),iirmv:n(463),AMcfU:function(s,t){return s&t},pDfYF:function(s,t){return s&t},KFsbh:function(s,t){return s>>>t},qIxvM:function(s,t){return s>>>t},NFfRW:function(s,t){return s&t},SZzsj:function(s,t){return s&t},YhdNW:function(s,t){return s>>>t},FsuHm:function(s,t){return s&t},QOpoE:function(s,t){return s&t},gVNYM:function(s,t){return s&t},hFUwR:n(1550)+n(1703),HQkXh:n(624)+n(1319),JFcEZ:n(419)+n(862)+"R",eeLJr:n(889)+"OR",jqMyw:n(1542)+n(436),ZbZAf:n(597)+"RROR",vhZQm:n(1212)+n(1116),upZkh:function(s,t){return s!==t},hpplf:"NeaTn",nRQVQ:n(986),RkJRs:n(1358),Urkzu:"OIUON",ZssjQ:function(s,t){return s===t},GXYdN:n(1607),xDKUh:function(s,t){return s||t},ptcrz:n(847),ClBLA:"omTIg",MhwIh:function(s,t){return s==t},kjKAl:function(s,t){return s>t},VrsGR:"ZEOvF",Yyiqf:function(s,t){return s===t},FtgzH:n(1185)+n(1681),FDDlS:function(s,t){return s+t},BhBnw:function(s,t){return s+t},uzfYy:function(s,t){return s===t},NftMx:function(s,t){return s===t},JMRsu:function(s,t){return s+t},wbxwP:function(s,t){return s>>>t},YzGfu:function(s,t){return s===t},pZQHG:n(1529),oeAhp:function(s,t,r){return s(t,r)},KWVlj:n(1460),JWMIt:function(s,t){return s!==t},KoUtC:n(865),arXFZ:function(s,t){return s===t},FFAjp:function(s,t){return s===t},evpGf:function(s,t){return s+t},QOnkd:function(s,t,r){return s(t,r)},PhTjk:function(s,t){return s instanceof t},sGVvq:n(1049),rpxCE:n(1152),TkPFi:n(633),vEvhp:n(1604),mgadO:"eBNrt",XUUZZ:function(s,t,r,o){return s(t,r,o)},GerJI:"IqKQB",FQhUh:function(s,t){return s!=t},oLxEM:n(444)+"4",fnNbY:function(s,t){return s<=t},PcOgu:function(s,t){return s<t},vRNhy:function(s,t){return s&t},ryHBg:function(s,t){return s instanceof t},ohDDh:n(1466)+"in;chars"+n(826),oLZjP:"applicat"+n(1648),pYBnu:n(1743)+n(1648)+";charset=utf-8",qDgaC:n(527)+"e",zJBEU:n(1163),ogShs:function(s,t){return s===t},lzbEK:n(709),UiZAM:n(416),kRzEk:function(s,t){return s<t},UHTDU:function(s,t){return s-t},gvvCt:"RLWDn",pzcwW:function(s,t){return s<=t},yQBMq:function(s,t){return s>=t},ZTVOR:function(s,t){return s&t},SzXzG:function(s,t){return s&t},tyWEs:function(s,t){return s&t},ZsmPh:function(s,t){return s<<t},QvdRu:function(s,t){return s-t},PpAKe:function(s,t){return s|t},vQrgR:function(s,t){return s<<t},KaRlz:function(s,t){return s&t},BDVfH:function(s,t){return s&t},jlLUs:function(s,t){return s+t},jucHB:function(s,t){return s+t},kScrN:function(s,t){return s<t},RXttS:function(s,t){return s|t},vZlQM:function(s,t){return s===t},iiZBy:function(s,t){return s===t},CrzuC:function(s,t){return s+t},smfZZ:function(s,t){return s+t},pKcGk:function(s,t){return s<<t},zUOwJ:function(s,t){return s&t},wazjQ:function(s,t){return s|t},FgwOR:function(s,t){return s>>t},bUgKo:function(s,t){return s&t},MqprC:function(s,t){return s&t},kaLaG:function(s,t){return s|t},RurpD:function(s,t){return s|t},kRZim:function(s,t){return s<<t},SLglc:function(s,t){return s==t},EfaRb:n(1003),BXsUI:"JJaUV",RIXjh:function(s,t){return s instanceof t},VMYOQ:function(s,t){return s instanceof t},hVXcR:function(s,t){return s!=t},ZAaot:n(1660),tSNAB:"boe",xCUNH:n(975),SkSge:function(s,t){return s>=t},oHTnb:function(s,t){return s!==t},LqNvk:"DWypi",vaKlf:n(1538),WuzWV:n(982),KsZta:n(435),xSCnF:n(923),gojmr:function(s,t){return s(t)},bGZXI:n(1125),IyIdp:function(s){return s()},mVtgo:n(1056),fSzrG:n(515),FujtT:n(1202),lAfvb:"PMxZn",byDVl:function(s,t){return s||t},QiPTo:function(s,t){return s||t},RncHq:function(s,t){return s||t},MchlK:n(1735),bJFjb:function(s,t){return s(t)},bjjRZ:function(s,t){return s===t},nXgUi:n(993),WWhwN:function(s,t){return s|t},gQPqT:function(s,t){return s&t},CTGGZ:function(s,t){return s|t},lsNiM:function(s,t){return s|t},bmigf:function(s,t){return s|t},vHBGP:n(1157),IVVlq:function(s,t){return s===t},IlZui:n(965),MeWLD:function(s,t){return s||t},wyghl:n(1689)+n(1077)+"d",tSGuy:n(490),DYuOd:n(1406)+"id",gRtqE:function(s,t,r){return s(t,r)},wGAUY:"IVrNK",pkCld:function(s,t){return s(t)},EmfAH:function(s,t,r,o){return s(t,r,o)},lwsni:n(1287)+"er_qos_ack",musMi:function(s,t,r,o){return s(t,r,o)},iGJMJ:n(610),oBGVL:n(379),SBBWz:function(s,t){return s&&t},TAIxb:n(642),tcgrJ:n(1210),fMmjF:function(s){return s()},SmuKx:"received",jibGN:function(s){return s()},EZeaV:function(s,t){return s(t)},PCvVp:function(s,t){return s instanceof t},Hqimn:function(s,t,r,o){return s(t,r,o)},tould:function(s){return s()},sLYRs:function(s,t){return s(t)},acxuC:function(s,t){return s&t},PNDGs:function(s,t){return s+t},KrYHw:function(s,t){return s===t},okDcK:n(1710),lpqVo:"QmwnL",qvFdX:function(s,t){return s>>>t},ygDOh:function(s,t){return s+t},lQqAZ:function(s,t){return s+t},FIPzm:function(s,t){return s+t},YteMY:n(682),WZXjd:function(s,t){return s+t},teSCo:function(s,t){return s>>>t},JHJrc:n(1359)+"3",XfNaD:function(s,t){return s+t},uwPsK:function(s,t){return s|t},OAplw:function(s,t){return s<<t},KWxZf:function(s,t){return s+t},swqpe:function(s,t){return s|t},JaokL:function(s,t){return s+t},eqGKd:function(s,t){return s+t},uYmrp:function(s,t){return s===t},krehw:"xOBRw",QVKGH:function(s,t){return s+t},vfRhj:function(s,t){return s>>>t},oOkaS:function(s,t){return s&t},usRsY:function(s,t){return s>>>t},okMJL:function(s,t){return s&t},YNrST:function(s,t){return s>>>t},LzLBW:function(s,t){return s+t},EmiFN:function(s,t){return s+t},HLKUv:function(s,t){return s&t},QOWrl:n(460)+n(1764)+"|1|4|11|0",SWkCt:function(s,t){return s>>>t},oFfSQ:function(s,t){return s|t},AwbOK:function(s,t){return s|t},cVSXj:function(s,t){return s<<t},xJXSp:function(s,t){return s<t},rxyRg:function(s,t){return s>>>t},wQbqZ:function(s,t){return s|t},KNOKX:function(s,t){return s<<t},lrEzA:function(s,t){return s&t},FWjHj:function(s,t){return s&t},jAJPP:function(s,t){return s&t},GKskB:function(s,t){return s<t},wwhIX:function(s,t){return s|t},sLUfV:function(s,t){return s>t},xWfah:function(s,t,r){return s(t,r)},RrDSO:n(1242),eexqd:n(1377),MKpKn:"4|5|1|3|"+n(464)+n(1261),pzlpN:n(1706),vLiSk:n(798),vBaRh:function(s,t,r,o){return s(t,r,o)},bxZlL:function(s,t,r,o){return s(t,r,o)},BmXRb:n(1047),Phuri:n(974),tLBLy:function(s,t){return s(t)},EePWc:n(635)+"ile_name",GOJdO:function(s){return s()},Gwtep:n(880),yxnVe:function(s,t,r){return s(t,r)},DntpC:function(s,t,r){return s(t,r)},ttGHA:function(s,t){return s+t},Kixiu:n(1720),qokVf:"FILE_NOT"+n(492),oQSyQ:n(1796)+n(1112),jJBea:n(1622)+"rValues",KaWqv:n(564),EiZZY:n(554),YWawt:n(1725),knYzb:function(s){return s()},bOTQy:function(s,t){return s===t},HScbu:n(1001),JJjXL:n(1694),WpDaU:function(s,t){return s(t)},mhxex:"setcursor",NIufC:n(1356),ttjiP:n(1783),cbXQZ:function(s,t){return s(t)},FhHCk:n(1754)+"or",bdlen:n(626),tyTWX:function(s,t){return s||t},Szstw:function(s,t){return s!==t},aLuog:n(708),XHGrG:n(951),USCyC:function(s,t,r,o){return s(t,r,o)},JbAcn:n(1330),ElhgN:function(s,t,r,o){return s(t,r,o)},wlPNa:function(s,t,r){return s(t,r)},Ldxwo:"x_fronti"+n(410),snFpN:n(1287)+n(1236),VDRle:function(s,t,r){return s(t,r)},glzNl:"x-msg-cursor_value",bTRcl:function(s,t){return s===t},nRnEW:n(1084),XQWqN:function(s,t){return s!==t},EPNoV:n(1145),COAwM:n(1224),PfXqL:function(s){return s()},SIksO:function(s){return s()},RbTwa:function(s,t){return s===t},YCBwT:function(s,t){return s===t},xggdL:function(s){return s()},llATk:function(s,t,r){return s(t,r)},xnIYN:n(641),ZgIuz:function(s,t){return s<t},exglI:function(s,t){return s===t},TbRfw:function(s,t){return s===t},AKaCZ:n(1341),ynXvX:"IoLKw",SYrrZ:function(s,t,r){return s(t,r)},HLbDF:"bye",Xanlu:function(s,t){return s!==t},aNdrG:function(s,t){return s===t},TsCag:n(522),xzHGS:"always",ZfsXs:n(904),eFrIa:"ping_once_success",EcOaj:function(s,t){return s===t},PIapV:function(s,t,r){return s(t,r)},GnOpS:"arraybuf"+n(1530),GrXad:function(s,t){return s(t)},pxDtA:n(1456)+"rovide ws params, WebSoc"+n(493)+n(1513)+n(615)+n(1656),PFHtJ:n(1337)+"t",kNZqj:n(801)+n(1229)+n(875)+"ct",JpdnM:"pageshow",mEPcG:function(s,t){return s<<t},YBnmS:n(925),ctWTX:function(s,t){return s!==t},ONidC:"urnjV",dBJHO:n(885),kGVFK:n(1585),rTUoY:n(1343),aftnG:n(1672),MxUVf:n(943),iNmlL:function(s,t){return s||t},iRRId:n(1456)+n(787)+n(1138)+n(1322)+n(1009),zSqok:function(s,t){return s==t},mqjid:n(1405),zvJSL:function(s,t,r){return s(t,r)},RjhsE:n(676),wjWVR:function(s,t,r){return s(t,r)},LkXOE:function(s,t){return s!==t},CUyXU:n(1233),cOhbm:n(1621),faesx:function(s,t,r){return s(t,r)},NeUWX:function(s,t,r){return s(t,r)},KCXFE:function(s,t){return s||t},WoLFK:n(544),yqdup:function(s,t){return s>t},ZrmFt:function(s,t){return s<<t},oIzto:n(403),eQsDu:function(s,t,r){return s(t,r)},XRSsI:function(s,t,r){return s(t,r)},SMVjx:function(s,t){return s===t},ACcxY:n(963),zAxnN:n(1492),qfuyc:function(s,t){return s(t)},ByczE:function(s,t){return s(t)},Xiuzt:n(519)+">",YinYV:"going away, try reconnec"+n(805)+n(886),jbCuu:n(1445)+n(906)+"onnecting",sgAtm:n(1277),vNqIE:n(1577),PhkgP:function(s,t){return s>t},NydcM:function(s,t){return s!==t},qQtEq:n(1037),Teior:n(751),MYoXa:function(s,t,r){return s(t,r)},FbakX:function(s,t,r){return s(t,r)},QHRXZ:function(s,t,r){return s(t,r)},nXYye:n(1413)+n(511)+n(582)+n(985),hAiPW:"ack",Eolvk:n(1132),gMWyA:function(s,t){return s+t},AyLPz:n(1673)+n(1402)+n(779)+n(1317)+"ed",DDYZk:n(1673)+n(570)+n(1696),ueiKt:function(s,t){return s==t},sdnQc:"please p"+n(767)+n(465)+n(1225)+n(852)+n(853)+n(1309)+n(837)+n(1575),pJobB:function(s,t){return s instanceof t},jyeCR:function(s,t){return s(t)},ozLrL:function(s,t){return s||t},GmCId:function(s,t){return s instanceof t},CDyft:function(s,t){return s(t)},HsTop:"sent",JZAss:n(1030),sxJoh:function(s,t){return s||t},pImEd:n(721)+"econnect"+n(828),mgQbl:function(s,t,r){return s(t,r)},XaSeK:function(s,t){return s(t)},QXMAx:n(1548),SPRnq:function(s,t){return s(t)},RyZbX:n(1437),PhyvH:n(1308),FzTIe:function(s,t){return s!=t},vfHkw:function(s,t){return s===t},onJWl:n(575),KoDQY:function(s,t){return s!=t},Gzsjj:function(s,t){return s!=t},uHBmR:"Object",UBVWA:function(s,t){return s===t},eJcmP:n(977)+n(1396)+n(1183)+"pe",GKBYt:function(s,t){return s===t},XrWXn:function(s,t){return s===t},WNwHc:function(s,t){return s===t},POffE:"ServiceW"+n(397)+n(1531),TJgZS:function(s,t){return s!=t},aNQPx:function(s,t){return s===t},WmGmA:function(s,t){return s!=t},sMVSk:function(s,t){return s===t},RsGyu:function(s,t){return s!=t},qLowm:function(s,t){return s!=t},Bakeo:n(1065)+"qos__"};ke.r(X),ke.d(X,{FWS:()=>P0,CustomErrorEvent:()=>Ss,createCloseEvent:()=>pe,ReconnectEvent:()=>vs,createErrorEvent:()=>de,decodedFrame:()=>ms,createOpenEvent:()=>Is,CustomCloseEvent:()=>Es,createReconnectEvent:()=>ur,FrontierMessageEvent:()=>As,encodeFrame:()=>xr,createMessageEvent:()=>Ps,OpenEvent:()=>ks,ErrorCode:()=>Ge,Event:()=>at,MessageEvent:()=>Cs});let i="";function a(s=""){let t=n,r="02",o=""+Date.now(),x=i||(i=e[t(649)](p,s)),h=Math[t(1089)]().toString(16)[t(1733)](-6);return e.rJxLI(e.HMYFY(r,o),x)+h}function c(){let s=n;return e[s(691)](1e4,Date[s(1549)]())+Math[s(1773)](e[s(691)](1e4,Math[s(1089)]()))}function u(s){let t=n;return e[t(772)](e[t(1303)](Array,8)[t(874)]("0"),parseInt(s,10)[t(1398)](2))[t(1733)](-8)}function f(s){let t=n;return e[t(893)](e[t(1303)](Array,4)[t(874)]("0"),e[t(1269)](parseInt,s,2).toString(16)).slice(-4)}function l(s){let t=n,r=s[t(542)](/\./)[t(1360)](h=>u(h)),o=[];return o[0]=e.czVNz(f,r[0]+r[1]),o[1]=e[t(1093)](f,e[t(772)](r[2],r[3])),[e[t(981)],"0000",e[t(981)],e[t(981)],t(1448),e[t(1339)],o[0],o[1]][t(874)]("")}function p(s){let t=n,r=/(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(541)](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(541)](s);return r?e[t(1768)](l,s):o?e.MdwIJ(w,s):e[t(950)]}function w(s){let t=n,r={NqUUO:function(b,E){return e[D(1159)](b,E)},bfyFd:e.nWwLF},o="",x=[],h=0,m=0,g=!0,d=e[t(981)];if(e[t(1565)](s[t(1528)]("::"),-1))if(e[t(425)](e.GfmGL,t(1365))){let b=s.split("::");for(let v=0;e[t(818)](v,b[t(1131)]);v++){let L=b[v];if(L[t(1528)](":")>0){let N=L[t(542)](":");g&&(h=N.length),m+=N[t(1131)];for(let z=0;e[t(455)](z,N[t(1131)]);z++)if(N[z][t(1131)]!==4){let me=d[t(1271)+"g"](0,4-N[z].length),j=me[t(741)](N[z]);x[t(1381)](j)}else x[t(1381)](N[z]);g=!1}else{if(e.Hzylu(4,L[t(1131)])){let N=d[t(1271)+"g"](0,e[t(539)](4,L[t(1131)])),z=N[t(741)](L);x.push(z)}else x[t(1381)](L);g&&(h+=1),m+=1,g=!1}}let E="";for(let v=0;e[t(818)](v,8-m);v++)E=E.concat(d);for(let v=0;v<x[t(1131)];v++)e[t(425)](v,h)?(o=o.concat(E),o=o.concat(x[v])):o=o[t(741)](x[v]);return o}else{let b=/(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(541)](_0x2c1a98),E=/(([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(_0x50f12b);return b?_0x3b4460(_0x555e5e):E?whEqOY[t(1652)](_0x2645a3,_0x15c8b4):whEqOY.bfyFd}{let b=s[t(542)](":");for(let E=0;e[t(736)](E,b[t(1131)]);E++){let v=b[E];if(e[t(786)](4,b[E][t(1131)])){let L=d[t(1271)+"g"](0,e[t(1226)](4,b[E][t(1131)])),N=L[t(741)](v);o=o[t(741)](N)}else o=o[t(741)](v)}return o}}function y(s,t){let r=n,o={ecTKl:r(633),fyGeU:e[r(700)],UbRgw:e.Jjlrg},x=s.key;e[r(699)](void 0,x)&&(e.xhPmz(V,t,10),e[r(1327)](be,t,x));let h=s[r(752)];h!==void 0&&(e.kBuYj!==r(1370)?(V(t,18),be(t,h)):(this[r(526)+"er"]&&_0x389449[r(1257)+"Listener"](o[r(1605)],this[r(971)+"nLine"]),this[r(526)+"er"]&&_0x1f3683[r(1257)+r(1682)](o[r(947)],this[r(971)+r(839)]),this[r(526)+"er"]&&_0x1edf1e.addEventListener(o.UbRgw,this[r(876)+r(856)]),this._isBrowser&&_0x192e6e[r(1257)+r(1682)](r(793),this[r(876)+r(650)])))}function _(s){let t=n,r={};e:for(;!e[t(467)](De,s);){let o=M(s);switch(e[t(1172)](o,3)){case 0:break e;case 1:r[t(1080)]=e[t(1426)](ye,s,e[t(1175)](M,s));break;case 2:r[t(752)]=e.WdCef(ye,s,e[t(761)](M,s));break;default:e[t(1426)](Y,s,e[t(671)](7,o))}}if(r[t(1080)]===void 0)throw new Error(e[t(944)]);if(e[t(1329)](void 0,r.value))throw new Error(e[t(961)]);return r}function C(s){let t=n,r=e[t(929)](Z);return e.xhPmz(P,s,r),e[t(1159)](W,r)}function P(s,t){let r=n,o=s[r(457)];e[r(699)](void 0,o)&&(e[r(545)](V,t,8),Pt(t,o));let x=s[r(916)];e[r(699)](void 0,x)&&(e.xOzPb(V,t,16),e[r(1562)](Pt,t,x));let h=s.service;e[r(786)](void 0,h)&&(e[r(1426)](V,t,24),Pt(t,e[r(667)](re,h)));let m=s.method;m!==void 0&&(e[r(473)](V,t,32),e.WdCef(Pt,t,e.qHLjj(re,m)));let g=s[r(1313)];if(g!==void 0)for(let me of g){e[r(747)](V,t,42);let j=e[r(929)](Z);y(me,j),e[r(1707)](V,t,j[r(478)]),e.okhcn(Yt,t,j),e[r(1159)](k,j)}let d=s["payloadE"+r(922)];e[r(786)](void 0,d)&&(e[r(747)](V,t,50),e[r(1510)](be,t,d));let b=s[r(1004)+r(972)];if(e[r(699)](void 0,b)){if(e.XGtqM(r(855),r(855)))return _0x3a0902||(_0x1350b0=[_0x4318ab,_0x4089b9,_0x23120d,_0x475b51,_0x574c33]);V(t,58),e[r(840)](be,t,b)}let E=s[r(687)];e[r(699)](void 0,E)&&(e[r(766)](V,t,66),e[r(1562)](V,t,E[r(1131)]),Xt(t,E));let v=s.LogIDNew;e.yKywI(void 0,v)&&(e[r(747)](V,t,74),e[r(1426)](be,t,v));let L=s["serverTi"+r(1207)];e[r(399)](void 0,L)&&(e[r(747)](V,t,82),e[r(766)](be,t,L));let N=s.msgID;e[r(786)](void 0,N)&&(e[r(888)](V,t,90),e[r(888)](be,t,N));let z=s[r(1054)+"e"];z!==void 0&&(e.QlbVb(V,t,96),e[r(1378)](Pt,t,e[r(1175)](re,z)))}function I(s){let t=n,r={LpVVA:function(o,x){return e.OgqsL(o,x)}};return e[t(1537)](e.ZCJJz,e[t(1355)])?r.LpVVA(_0x5d35f0,_0x235428):e[t(1159)](R,e[t(1175)](H,s))}function R(s){let t=n,r={};e:for(;!De(s);){let o=e[t(761)](M,s);switch(e[t(1772)](o,3)){case 0:break e;case 1:r[t(457)]=e.xqMCx(Te,s,!0);break;case 2:r[t(916)]=e.NJwpg(Te,s,!0);break;case 3:r.service=e.mTcHf(M,s);break;case 4:r[t(1479)]=e.szZvX(M,s);break;case 5:{let x=e.czVNz(U,s);(r.headers||(r.headers=[]))[t(1381)](e.NoDif(_,s)),s.limit=x;break}case 6:r[t(619)+"ncoding"]=e[t(1510)](ye,s,e[t(1303)](M,s));break;case 7:r[t(1004)+t(972)]=ye(s,e.qHLjj(M,s));break;case 8:r.payload=e[t(766)](kt,s,e[t(1159)](M,s));break;case 9:r[t(703)]=e[t(1104)](ye,s,e[t(749)](M,s));break;case 10:r[t(1649)+t(1207)]=e[t(1378)](ye,s,e[t(1159)](M,s));break;case 11:r.msgID=e[t(1104)](ye,s,e[t(1175)](M,s));break;case 12:r.frameType=M(s);break;default:Y(s,e[t(671)](7,o))}}if(e[t(1048)](void 0,r[t(457)]))throw new Error(e.NmEVp);if(e[t(1329)](void 0,r[t(916)]))throw new Error("Missing "+t(556)+t(1126)+t(916));if(e.TsJUV(void 0,r[t(974)]))throw new Error(t(1726)+t(556)+t(1126)+t(974));if(e[t(1048)](void 0,r[t(1479)]))throw new Error("Missing "+t(556)+t(1126)+t(1479));return r}function U(s){let t=n,r=e[t(1354)](M,s),o=s.limit;return s[t(478)]=s[t(1775)]+r,o}function Y(s,t){let r=n,o={ssDxV:e.EshMr};if(e.FUMNq!==e.tTBIH)switch(t){case 0:for(;e[r(1769)](128,e.mTcHf(ae,s)););break;case 2:se(s,M(s));break;case 5:e[r(1327)](se,s,4);break;case 1:e[r(1e3)](se,s,8);break;default:throw new Error(e[r(1353)]+t)}else this.emit(o[r(1167)],_0x3afe6c),this[r(905)]&&this[r(905)](_0x3414b8)}function re(s){let t=n;if(e[t(549)]("QrHpR","QrHpR"))return s|=0,{low:s,high:e[t(432)](s,31),unsigned:e[t(1267)](s,0)};_0x38c9a4[t(634)+t(920)]=void 0,_0x5c1d24(e[t(1518)])}let ee=[];function Z(){let s=n,t={FRveU:function(r,o){return e.fWAxV(r,o)},wsFdA:e[s(776)],uFOjB:function(r,o){return e[s(1586)](r,o)},aWvTr:function(r,o,x,h){return e.XjRUQ(r,o,x,h)},KmUcz:function(r,o){return r instanceof o}};if(e[s(1133)](s(616),s(616))){if(t[s(1052)](t[s(629)],typeof _0x31f615)){let r=new _0x304fb3(t[s(1606)](_0x93a05,_0x2f5b9e));return t[s(1215)](_0x36d5b4,_0x4a8c6b,r,0),r}return t[s(1284)](_0x229049,_0x3dddc1)?new _0x44e653(_0x26e193):new _0x5b534a(_0xd854ac.buffer,_0x817199[s(1700)+"et"],_0x22cbd6[s(1685)+"th"])}else{let r=ee[s(1521)]();return r?(r.offset=r[s(478)]=0,r):{bytes:new Uint8Array(64),offset:0,limit:0}}}function k(s){ee[n(1381)](s)}function H(s){return{bytes:s,offset:0,limit:s.length}}function W(s){let t=n,r=s[t(1038)],o=s[t(478)];return r.length===o?r:r[t(983)](0,o)}function se(s,t){let r=n;if(e.blTTI(e.yVVYV(s.offset,t),s.limit))throw new Error(r(1249)+"t limit");s.offset+=t}function De(s){let t=n;return e[t(685)](s[t(1775)],s.limit)}function ge(s,t){let r=n,o=s.bytes,x=s[r(1775)],h=s[r(478)],m=e[r(661)](x,t);if(e[r(1565)](m,o[r(1131)])){let g=new Uint8Array(e[r(483)](2,m));g[r(1043)](o),s[r(1038)]=g}return s[r(1775)]=m,e[r(1053)](m,h)&&(s[r(478)]=m),x}function Ye(s,t){let r=n,o=s[r(1775)];if(e[r(1565)](e.yVVYV(o,t),s[r(478)]))throw new Error(e.hYIxH);return s[r(1775)]+=t,o}function kt(s,t){let r=n,o=Ye(s,t);return s[r(1038)][r(983)](o,e[r(1348)](o,t))}function Xt(s,t){let r=n,o=e[r(1378)](ge,s,t[r(1131)]);s[r(1038)][r(1043)](t,o)}function ye(s,t){let r=n,o=e[r(383)](Ye,s,t),x=String[r(1075)+r(935)],h=s[r(1038)],m="\uFFFD",g="";for(let d=0;e[r(736)](d,t);d++){let b=h[e.nHNjn(d,o)],E,v,L,N;if(e[r(549)](e.ZoQCx(128,b),0))g+=e[r(1795)](x,b);else if(e[r(1272)](224,b)===192)if(e.rmVtt(d,1)>=t)g+=m;else if(e.bvgyn(e[r(669)],e.HPFWO))_0x2c727e=_0x542490.concat(_0x27e9e9),_0x254723=_0x475677[r(741)](_0x27b1fa[_0x13f8cd]);else if(E=h[e[r(1705)](e.jRqdu(d,o),1)],e[r(699)](e[r(1272)](192,E),128))g+=m;else if(N=e[r(1449)](e[r(937)](e[r(1769)](31,b),6),e[r(1181)](63,E)),N<128)g+=m;else if(e.FNPSu(r(1123),e[r(479)]))g+=e[r(1424)](x,N),d++;else{let z={cGGXh:QPEWYD[r(1611)],NMVtN:QPEWYD.zXenh,PpdcU:QPEWYD[r(1788)]};_0x1a0ef9.r=me=>{let j=r;z[j(1451)]!=typeof _0x1142dc&&_0x1441bb[j(1398)+j(1747)]&&_0x2c7fc5[j(1608)+j(1727)](me,_0x51024c[j(1398)+j(1747)],{value:z[j(603)]}),_0x295aec[j(1608)+"operty"](me,z.PpdcU,{value:!0})}}else if(e[r(1205)](e[r(1091)](240,b),224))if(e[r(685)](e[r(1383)](d,2),t))g+=m;else if(E=h[e.ilZAX(e.cotqg(d,o),1)],v=h[e.aXXnC(d,o)+2],e[r(1792)](e[r(1272)](E|e.LzEWx(v,8),49344),32896))g+=m;else if(e[r(812)](e.lzwMR,r(1247)))N=e[r(1449)](e[r(1449)](e.qPHRQ(15&b,12),e[r(679)](e[r(1769)](63,E),6)),e[r(471)](63,v)),e[r(1096)](N,2048)||e.jMPdx(N,55296)&&e.AvDHH(N,57343)?g+=m:(g+=x(N),d+=2);else return _0x5ba2bb?this[r(780)+"E"]():this.toBytesBE();else e[r(901)](248&b,240)?e[r(1514)](e[r(661)](d,3),t)?g+=m:(E=h[e[r(1171)](d,o)+1],v=h[e[r(1086)](e[r(1502)](d,o),2)],L=h[d+o+3],e.cnOxV(e[r(1021)](e[r(1449)](E,e[r(686)](v,8)),e.NEVvS(L,16))&12632256,8421504)?g+=m:(N=e[r(909)](e[r(1519)](e[r(715)](7,b),18)|e[r(686)](e[r(903)](63,E),12)|e[r(1769)](63,v)<<6,e[r(599)](63,L)),e[r(1404)](N,65536)||e[r(1053)](N,1114111)?g+=m:(N-=65536,g+=x(e[r(772)](e.ETkje(N,10),55296),e[r(1218)](1023,N)+56320),d+=3))):g+=m}return g}function be(s,t){let r=n,o=t[r(1131)],x=0;for(let g=0;e.NbBAO(g,o);g++){let d=t[r(960)+"At"](g);e[r(1267)](d,55296)&&d<=56319&&e[r(824)](e[r(898)](g,1),o)&&(d=e[r(1617)](e[r(990)](d<<10,t[r(960)+"At"](++g)),56613888)),x+=e[r(740)](d,128)?1:e[r(740)](d,2048)?2:e[r(1301)](d,65536)?3:4}e[r(1767)](V,s,x);let h=ge(s,x),m=s[r(1038)];for(let g=0;e[r(831)](g,o);g++)if(e.PhbGV(e[r(1082)],r(1326))){let d=t[r(960)+"At"](g);e[r(685)](d,55296)&&d<=56319&&e[r(1195)](e[r(1155)](g,1),o)&&(d=e[r(990)](e[r(937)](d,10),t[r(960)+"At"](++g))-56613888),e[r(1195)](d,128)?m[h++]=d:(e[r(1404)](d,2048)?m[h++]=e.OklqS(e[r(1391)](e[r(432)](d,6),31),192):(d<65536?m[h++]=e[r(1412)](e[r(903)](e[r(432)](d,12),15),224):(m[h++]=e[r(1736)](e[r(599)](d>>18,7),240),m[h++]=e[r(832)](e[r(967)](d,12)&63,128)),m[h++]=e[r(1088)](e.FfoNc(e[r(967)](d,6),63),128)),m[h++]=e.ducCV(63,d)|128)}else this[r(1120)]&&this._ws[r(1529)](_0x12bebf,_0x4f37a9)}function Yt(s,t){let r=n,o=ge(s,t[r(478)]),x=s[r(1038)],h=t.bytes;for(let m=0,g=t[r(478)];e[r(1723)](m,g);m++)x[e.RZhqi(m,o)]=h[m]}function ae(s){return s[n(1038)][Ye(s,1)]}function Zt(s,t){let r=n,o=e.rzDsZ(ge,s,1);s[r(1038)][o]=t}function M(s){let t=n,r=0,o=0,x;do x=e[t(797)](ae,s),e[t(1078)](r,32)&&(o|=e[t(1176)](e[t(927)](127,x),r)),r+=7;while(128&x);return o}function V(s,t){let r=n;for(t>>>=0;e[r(1267)](t,128);)e[r(747)](Zt,s,e[r(677)](e[r(1699)](127,t),128)),t>>>=7;Zt(s,t)}function Te(s,t){let r=n,o={kDPeO:e[r(771)],XqeDa:r(1437)};if(e[r(1408)]===e[r(1408)]){let x=0,h=0,m=0,g;if(g=e[r(1768)](ae,s),x=127&g,128&g&&(g=e[r(1159)](ae,s),x|=e.IREtk(e[r(1272)](127,g),7),e.ducCV(128,g)&&(g=e.IXGHE(ae,s),x|=e[r(398)](e[r(471)](127,g),14),e[r(1699)](128,g)&&(g=e[r(1392)](ae,s),x|=e[r(1008)](127&g,21),e.XwwCb(128,g))))){if(e[r(396)](r(606),e[r(1011)]))return this[r(638)][r(897)+"pe"];g=e[r(1768)](ae,s),h=e[r(671)](127,g),e[r(1570)](128,g)&&(g=e[r(1375)](ae,s),h|=e[r(1008)](127&g,7),e[r(1324)](128,g)&&(g=e.HNUtz(ae,s),h|=e[r(869)](e.BjyzZ(127,g),14),128&g&&(g=e[r(1159)](ae,s),h|=e[r(398)](127&g,21),e.XwwCb(128,g)&&(g=ae(s),m=e.KKHao(127,g),128&g&&(g=ae(s),m|=e.wdcPn(127,g)<<7)))))}return{low:e[r(909)](x,e.ymNAV(h,28)),high:e[r(1088)](e[r(1172)](h,4),e[r(1128)](m,24)),unsigned:t}}else this["_pingLos"+r(696)]?.[r(1802)](),this[r(863)](o[r(887)],o[r(870)]),this[r(469)+r(696)]?.[r(1095)+"chMaxCount"]()?this[r(1294)+"econnect"]():this[r(1102)]()}function Pt(s,t){let r=n,o={gRKVD:function(x,h,m,g,d){return e[D(698)](x,h,m,g,d)},OLsRl:function(x,h){return e[D(458)](x,h)}};if(e[r(695)](e[r(449)],e[r(1777)])){let x=e[r(1772)](t.low,0),h=e[r(914)](e[r(1160)](e[r(914)](t[r(1299)],28),e[r(679)](t[r(1069)],4)),0),m=e[r(914)](t.high,24),g=e[r(1329)](0,m)?e[r(549)](0,h)?e[r(666)](x,16384)?e[r(1096)](x,128)?1:2:e[r(831)](x,2097152)?3:4:e.oPXTX(h,16384)?h<128?5:6:e[r(1301)](h,2097152)?7:8:e.TdhWQ(m,128)?9:10,d=e[r(710)](ge,s,g),b=s.bytes;switch(g){case 10:b[e[r(1589)](d,9)]=e[r(1184)](m>>>7,1);case 9:b[e[r(1480)](d,8)]=e[r(1792)](9,g)?e[r(1558)](128,m):e.KRXRz(127,m);case 8:b[e.iuBTV(d,7)]=e[r(699)](8,g)?e[r(1455)](h>>>21,128):e[r(1219)](e[r(1243)](h,21),127);case 7:b[e[r(1388)](d,6)]=g!==7?h>>>14|128:e[r(1391)](e[r(1278)](h,14),127);case 6:b[e.hHjfV(d,5)]=g!==6?e[r(968)](e[r(1640)](h,7),128):e[r(999)](e[r(1278)](h,7),127);case 5:b[e[r(1501)](d,4)]=e[r(1537)](5,g)?e[r(968)](128,h):e[r(1150)](127,h);case 4:b[e[r(772)](d,3)]=g!==4?e[r(1282)](e[r(914)](x,21),128):e[r(1755)](x>>>21,127);case 3:b[e.DjumR(d,2)]=e.aWDOC(3,g)?e[r(500)](x,14)|128:e.thGwE(x,14)&127;case 2:b[d+1]=g!==2?e[r(1455)](e[r(954)](x,7),128):e[r(1755)](x>>>7,127);case 1:b[d]=g!==1?128|x:e.KSeos(127,x)}}else _0x23ee53[r(1257)+r(1682)](QPEWYD.dIuvs,x=>{let h=r;wOTQfJ[h(890)](_0x249b74,_0x189262(_0x29b97b[h(1275)]),x[h(1556)+"on"],x[h(809)+"on"],wOTQfJ.OLsRl(_0x59db8c,_0x47a30c[h(1055)+"ion"]))})}function ms(s){let t=n,r={PDRfm:function(o,x){return e[D(1221)](o,x)},AKLLI:function(o,x){return e[D(918)](o,x)},lfRBD:function(o,x){return e[D(458)](o,x)},nOehB:function(o,x){return o<<x}};if(e[t(812)](e[t(555)],e.EjCLZ))_0x35a70e=_0x57c0f0(_0x5743fe),_0x1baeaf=BXWhJO.PDRfm(127,_0x10edc7),BXWhJO[t(1295)](128,_0x4142b7)&&(_0x2c80fc=BXWhJO[t(979)](_0x428aa9,_0x503f58),_0x157098|=BXWhJO[t(558)](127&_0x143c0e,7));else return e[t(571)](I,s)}function xr(s){return e[n(1140)](C,s)}let ws=65536,qa=e[n(690)],ot=e[n(483)](ws,ws),_s=e[n(691)](ot,ot),ys=_s/2,He=String[n(408)+"e"][n(960)+"At"];class q{constructor(t,r,o){let x=n;this[x(1574)]=!0,this[x(1299)]=e[x(1412)](0,t),this.high=e[x(677)](0,r),this[x(1046)]=!!o}static[n(1574)](t){let r=n;return t&&e[r(549)](!0,t[r(1574)])}static fromBits(t,r,o){return new q(t,r,o)}static[n(1687)+"s"](t,r,o){let x=n;return o?q[x(1687)+x(819)](t,r):q[x(1687)+x(1763)](t,r)}static fromBytesLE(t,r){let o=n;return new q(e[o(1088)](e[o(535)](t[0]|t[1]<<8,e[o(424)](t[2],16)),e[o(1618)](t[3],24)),e[o(535)](e[o(1246)](e.FYygo(t[4],e[o(424)](t[5],8)),e[o(587)](t[6],16)),t[7]<<24),r)}static[n(1687)+n(1763)](t,r){let o=n;return new q(e[o(1282)](e[o(504)](e[o(1650)](t[4],24)|t[5]<<16,e[o(476)](t[6],8)),t[7]),e[o(505)](e.dbFOe(e.dbFOe(e[o(1599)](t[0],24),e[o(686)](t[1],16)),t[2]<<8),t[3]),r)}static[n(1713)](t){let r=n;return e[r(1427)](t,qa)?bs:new q(e.vDfje(e[r(1736)](He[r(491)](t,0),e[r(476)](He[r(491)](t,1),8))|e[r(1400)](He.call(t,2),16)|He[r(491)](t,3)<<24,0),(He[r(491)](t,4)|e[r(941)](He.call(t,5),8)|e[r(1650)](He[r(491)](t,6),16)|e[r(476)](He.call(t,7),24))>>>0,!0)}[n(1423)](){let t=n;return String[t(1075)+"Code"](255&this[t(1299)],e[t(1200)](this.low>>>8,255),e[t(918)](e[t(1772)](this[t(1299)],16),255),e[t(498)](this[t(1299)],24),e[t(1272)](255,this[t(1069)]),e[t(509)](e.kKaVX(this.high,8),255),this.high>>>16&255,e[t(1729)](this.high,24))}static[n(1584)+"er"](t,r=!0){let o=n,x={ojbqT:function(h,m,g,d){return e[D(376)](h,m,g,d)},Cvycx:function(h,m,g){return e[D(768)](h,m,g)},bZszF:o(421)};if(e[o(749)](isNaN,t))return r?Fa:bs;if(r){if(t>=_s)return Ha}else if(e[o(786)]("VVgHq",o(722)))try{x[o(374)](_0x463110,this,_0xc7778c,[_0x2c9781,_0x14c241,_0x395ff9])}catch(h){let m=x[o(1012)](_0x1e2d23,x.bZszF,{message:h[o(1460)],code:_0x56abef[o(889)+"OR"],error:h});this[o(1028)+o(674)+o(604)](m)}else{if(t<=-ys)return Ga;if(e[o(573)](e[o(521)](t,1),ys))return Ua}return q[o(1386)](e.USXrC(e[o(1101)](t,ot),0),e[o(909)](e[o(1717)](t,ot),0),r)}[n(1270)](){let t=n;return this[t(1046)]?e.EBbGy(e[t(691)](e.ddPep(this.high,0),ot),e[t(1243)](this[t(1299)],0)):e[t(1085)](this[t(1069)]*ot,e[t(1551)](this[t(1299)],0))}[n(385)](){let t=n;if(e.AqFyD(e[t(878)],e[t(878)])){if(e[t(833)](_0x257796,_0x2720f6))return _0x4f4e57?_0x20a2d7:_0x3dc945;if(_0x207ee2){if(e.OigdD(_0x120aa7,_0x2510c8))return _0x4eb473}else{if(e[t(1248)](_0x4e9a8c,-_0x36e333))return _0x2ea4d3;if(e[t(1800)](_0x539b27+1,_0x5f49d6))return _0x20b906}return _0x4d59da.fromBits(e.jAszQ(e.rPfuJ(_0x4198a5,_0x45bbc9),0),e[t(1245)](_0x19d124/_0x248ab5,0),_0x57f211)}else return e.NQVqc(0,this[t(1069)])&&e[t(812)](0,this[t(1299)])}[n(529)](t){let r=n;q[r(1574)](t)||(t=q[r(1584)+"er"](t));let o=e[r(1695)](this[r(1069)],16),x=e[r(599)](65535,this[r(1069)]),h=this[r(1299)]>>>16,m=e.WmLpU(65535,this[r(1299)]),g=e[r(727)](t[r(1069)],16),d=65535&t[r(1069)],b=t[r(1299)]>>>16,E=e[r(999)](65535,t[r(1299)]),v=0,L=0,N=0,z=0;return z+=e[r(915)](m,E),N+=e.OgFtG(z,16),z&=65535,N+=h+b,L+=e[r(498)](N,16),N&=65535,L+=e[r(1217)](x,d),v+=e.nQZXi(L,16),L&=65535,v+=e.eUuWx(o,g),v&=65535,q[r(1386)](e[r(1108)](e[r(996)](N,16),z),e[r(1160)](e.jQnzu(v,16),L),this[r(1046)])}equals(t){let r=n;return q[r(1574)](t)||(t=q[r(1584)+"er"](t)),this[r(1046)]!==t[r(1046)]&&e[r(549)](e[r(914)](this.high,31),1)&&e[r(1352)](t[r(1069)]>>>31,1)?!1:e[r(1352)](this[r(1069)],t[r(1069)])&&e[r(1497)](this[r(1299)],t[r(1299)])}addOne(){let t=n;if(e[t(1352)](t(1060),"chJYr"))this._isMiniTT?_0x45e1ec[t(475)+t(481)+t(1759)](({isConnected:r})=>{let o=t;this[o(1633)+"igatorOnline"]=r,r?this["_handleO"+o(1149)]():this[o(971)+o(839)]()}):this[t(1731)+"X"]&&_0x2a3325[t(475)+t(481)+t(1759)](({isConnected:r})=>{let o=t;this["_miniNavigatorOn"+o(1014)]=r,r?this["_handleO"+o(1149)]():this[o(971)+o(839)]()});else return e[t(1657)](-1,this[t(1299)])&&e.NQdit(-1,this.high)?q[t(1386)](0,0,this[t(1046)]):e[t(1657)](-1,this.low)?q[t(1386)](0,e[t(1752)](this[t(1069)],1),this[t(1046)]):q[t(1386)](this[t(1299)]+1,this[t(1069)],this.unsigned)}[n(1411)](t){let r=n;if(e[r(1792)](e[r(1534)],e[r(734)]))return t?this[r(780)+"E"]():this.toBytesBE();{let o=e[r(1462)](_0x2a204e,_0x25c703,_0x147b47[r(1131)]);_0x454633[r(1038)].set(_0x2c9b36,o)}}[n(780)+"E"](){let t=n,r=this[t(1069)],o=this[t(1299)];return[e[t(1487)](255,o),e[t(794)](e[t(1285)](o,8),255),e[t(1772)](o,16)&255,e[t(1331)](o,24),e.NFfRW(255,r),e[t(1688)](r>>>8,255),e[t(1239)](r>>>16,255),e[t(727)](r,24)]}[n(1019)+"E"](){let t=n,r=this[t(1069)],o=this[t(1299)];return[e[t(1774)](r,24),e.pZnKa(r>>>16,255),e[t(395)](e.qEYZR(r,8),255),e[t(1372)](255,r),o>>>24,e[t(931)](o>>>16,255),e.YhdNW(o,8)&255,e[t(927)](255,o)]}}let bs=new q(0,0,!1),Fa=new q(0,0,!0),Ua=q[n(1386)](-1,2147483647,!1),Ha=q.fromBits(-1,-1,!0),Ga=q.fromBits(0,-2147483648,!1);var Ge=(function(s){let t=n,r=e.hFUwR[t(542)]("|"),o=0;for(;;){switch(r[o++]){case"0":return s;case"1":s[s[e[t(1444)]]=5004]=e[t(1444)];continue;case"2":s[s[e[t(622)]]=5003]=e[t(622)];continue;case"3":s[s.OPEN_ERROR=5005]=e.eeLJr;continue;case"4":s[s[e[t(1144)]]=5002]=e[t(1144)];continue;case"5":s[s[e.ZbZAf]=5001]=e[t(448)];continue}break}})({});class at{constructor(t){let r=n;this[r(1432)]=t,this[r(417)]=null}}class vs extends at{constructor(t,r){let o=n;super(t),this[o(1460)]=r&&r.message||null}}class Ss extends at{constructor(t,r){let o=n,x=e[o(1291)][o(542)]("|"),h=0;for(;;){switch(x[h++]){case"0":this[o(1330)]=r&&r[o(1330)]||5001;continue;case"1":this[o(1476)]=r&&r[o(1476)]||"";continue;case"2":this[o(1477)]=r&&r[o(1477)]||0;continue;case"3":super(t);continue;case"4":this[o(998)]=r&&r[o(998)]||0;continue;case"5":this[o(421)]=r&&r[o(421)]||null;continue;case"6":this.message=r&&r[o(1460)]||"";continue}break}}}class Es extends at{constructor(t,r){let o=n;super(t),this[o(1330)]=r&&r[o(1330)]||0,this[o(1760)]=r&&r[o(1760)]||"",this.wasClean=r&&r.wasClean||!1,this[o(1336)+o(636)]=r&&r.willReconnect||!1}}class Cs extends at{constructor(t,r){let o=n;super(t),this.data=r&&r[o(1347)]||null}}class As extends Cs{constructor(t,r){let o=n;super(t),this.data=r&&r.data||null,this.message=r&&r[o(1460)]||null}}class ks extends at{constructor(t,r){let o=n;super(t),this[o(1347)]=r&&r[o(1347)]||null}}function de(s,{message:t,code:r,error:o}){return new Ss(s,{message:t,code:r,error:o})}function pe(s,{code:t,reason:r,wasClean:o,willReconnect:x}){let h=n,m={pvRoq:function(g,d,b){return e[D(1462)](g,d,b)}};if(e[h(1642)]("QTWBI",e[h(1474)]))return new Es(s,{code:t,reason:r,wasClean:o,willReconnect:x});m.pvRoq(_0x3c55be,_0x16f478,this["_getInte"+h(1632)+"e"](_0x2154f6))}function Ps(s,{data:t,message:r}){return new As(s,{data:t,message:r})}function Is(s,{data:t}){return new ks(s,{data:t})}function ur(s,{message:t}){return e.nRQVQ!==e.RkJRs?new vs(s,{message:t}):(_0x497adc[_0x11f07e]=_0x2d28ad,!0)}class Ds{constructor(t,r){let o=n;e[o(1751)](e[o(402)],o(864))?(this[o(440)+"s"]=t,this[o(1211)+"es"]=r,this["currentI"+o(1304)]=0,this[o(871)+o(1628)+o(1389)+"t"]=0):(this[o(1173)]=!0,this[o(1274)]())}[n(591)+n(550)+n(1721)](){let t=n;if(e[t(807)](e.GXYdN,e[t(978)]))this[t(1442)+t(1304)]=0,this[t(871)+"ndpointT"+t(1389)+"t"]=0;else return!!this[t(673)]}[n(1151)+"es"](){let t=n;this[t(871)+"ndpointT"+t(1389)+"t"]=0}["getCurre"+n(1124)+"nt"](){let t=n;return this[t(440)+"s"][this[t(1442)+t(1304)]]}["getCurrentEndpointTriesC"+n(429)](){let t=n;return this[t(871)+t(1628)+t(1389)+"t"]}[n(1095)+n(1188)+"es"](){let t=n;if(e[t(1399)]!==e.ClBLA)return!!(this["currentI"+t(1304)]>=this[t(440)+"s"].length||e[t(1657)](this.currentIndex,this[t(440)+"s"][t(1131)]-1)&&e[t(1048)](this[t(871)+t(1628)+t(1389)+"t"],this[t(1211)+"es"]));{let r=this[t(673)].getItem(this._prefix);return _0x4761b7[t(516)](e[t(512)](r,"{}"))[_0x2074cf]}}[n(810)+n(970)+n(1320)+n(1213)+"tries"](){let t=n;return e.MhwIh(this[t(1442)+t(1304)],this[t(440)+"s"].length)?!0:e[t(692)](this[t(871)+"ndpointT"+t(1389)+"t"],this[t(1211)+"es"])}["replaceB"+n(720)+n(1090)+n(1098)+n(409)](){let t=n;return this[t(871)+t(1628)+"riesCount"]=1,this[t(1442)+t(1304)]++,this.endpoints[this[t(1442)+"ndex"]]}["getCurre"+n(1124)+n(1187)+n(910)](){let t=n;return this[t(871)+"ndpointT"+t(1389)+"t"]++,this[t(1471)+"ntEndpoint"]()}}let ct=(e.FzTIe(n(1662)+"d",typeof globalThis)&&e[n(873)]("Window",globalThis[n(534)+n(502)].name)||e[n(1611)]!=typeof window&&e[n(895)](e[n(697)],window[n(534)+n(502)].name))&&e.KoDQY("undefined",typeof document),Ze=e[n(1439)]("undefined",typeof globalThis)&&(e.uHBmR===globalThis["construc"+n(502)][n(798)]||e[n(1552)](e[n(1576)],globalThis[n(534)+n(502)][n(798)]))&&e[n(1635)](n(1662)+"d",typeof tt),It=(typeof globalThis<"u"&&e.GKBYt(e[n(991)],globalThis["construc"+n(502)].name)||e[n(1578)](e.MdhBG,typeof globalThis)||e[n(644)](e[n(1611)],typeof globalThis)&&!!globalThis["WeixinJS"+n(627)])&&e[n(1611)]!=typeof wx,Dt=e.MdhBG!=typeof globalThis&&(e[n(537)](e[n(1576)],globalThis[n(534)+n(502)][n(798)])||e[n(760)](n(1338)+n(1403)+n(704),globalThis[n(534)+n(502)].name)||e[n(495)](e.POffE,globalThis[n(534)+n(502)][n(798)]))&&e[n(581)](e[n(1611)],typeof self),ja=e[n(1611)]!=typeof globalThis&&e[n(1401)](e[n(991)],globalThis[n(534)+n(502)][n(798)])&&e[n(377)]("undefined",typeof global)&&e[n(659)](e[n(991)],global[n(534)+n(502)][n(798)])&&e[n(1146)](n(1662)+"d",typeof process)&&!!process[n(1457)];class fr{constructor(){let t=n,r={ztfsO:function(o,x){return e[D(549)](o,x)}};if(e[t(396)](t(1655),e[t(1740)]))this[t(1191)+"rs"]={};else return ljGlps.ztfsO(0,this[t(1069)])&&ljGlps[t(1568)](0,this[t(1299)])}emit(t,...r){let o=n,x=this._listeners[t];if(x)x.slice().forEach(h=>h.fn[o(1222)](h.ctx,r));else if(e[o(1582)]("error",t)&&!this[o(905)]){let h=r[o(1131)]&&r[0];if(h instanceof Error)throw h;let m=new Error(e[o(1171)](e.FtgzH,h?e[o(1786)](e[o(1250)](" (",h.message),")"):""));throw m.context=h,h}return this}[n(1130)](t,r){let o=n;if(e.uzfYy(void 0,t))this[o(1191)+"rs"]={};else if(e.FNPSu(void 0,r))this[o(1191)+"rs"][t]=null;else{let x=this._listeners[t];if(x)for(let h=0;e[o(455)](h,x[o(1131)]);)e.NftMx(x[h].fn,r)?x[o(660)](h,1):++h}return this}on(t,r,o){let x=n;return(this._listeners[t]||(this[x(1191)+"rs"][t]=[]))[x(1381)]({fn:r,ctx:o||this}),this}}class Ka extends fr{[n(430)+n(789)+n(1627)](t){let r=n;return t.errMsg||t[r(388)]?("message: "+(t.errMsg||"")+r(1252)+(t[r(388)]||""))[r(588)]():JSON[r(1342)+"y"](t)}constructor(t,r,o){let x=n;super(),this[x(638)]=null,It&&wx[x(1643)+"ocket"]&&(this[x(638)]=wx[x(1643)+"ocket"]({url:t,protocols:r,header:o,fail:this[x(1395)+x(613)+x(1686)][x(1545)](this),success:this[x(1395)+x(1600)+x(777)+"ler"][x(1545)](this)})),Ze&&tt[x(1643)+x(484)]&&(this[x(638)]=tt[x(1643)+"ocket"]({url:t,protocols:r,header:o,fail:this[x(1395)+x(613)+x(1686)][x(1545)](this),success:this[x(1395)+x(1600)+x(777)+x(656)][x(1545)](this)}))}[n(1395)+"ocketSuc"+n(777)+n(656)](){let t=n;Promise[t(1129)]()[t(415)](()=>{this[t(1790)+"steners"]()})}[n(1395)+n(613)+n(1686)](t){let r=n;Promise[r(1129)]()[r(415)](()=>{let o=r,x=de(e.EshMr,{message:this[o(430)+o(789)+o(1627)](t)});this[o(863)](e[o(598)],x);let h=pe(o(1529),{reason:this[o(430)+o(789)+o(1627)](t)});this.emit("close",h)})}[n(1790)+"steners"](){let t=n,r={UBllP:function(o,x,h){return e[D(1269)](o,x,h)},OTDGe:e[t(598)]};if(e[t(426)](e[t(757)],e[t(757)]))return this[t(1046)]?e[t(772)](e[t(691)](e.kKaVX(this[t(1069)],0),_0x160b7b),e.yyFGd(this[t(1299)],0)):e[t(1059)](e.iWNrp(this[t(1069)],_0x497b1c),e[t(1715)](this[t(1299)],0));this[t(638)][t(962)](o=>{let x=t;this[x(863)](x(1577),e[x(1767)](Is,x(1577),{...o,data:o[x(487)]||""}))}),this._socket[t(1654)](o=>{let x=t;if(e[x(532)](x(494),x(1136)))return this._ws?this[x(1120)][x(897)+"pe"]:this[x(1280)+x(972)];this[x(863)](e[x(719)],e[x(1193)](pe,e[x(719)],{...o}))}),this[t(638)].onMessage(o=>{let x=t;this[x(863)](x(1460),e[x(768)](Ps,e[x(994)],{...o}))}),this._socket[t(1340)](o=>{let x=t;this[x(863)](x(421),r[x(1384)](de,r[x(654)],{...o,message:o.errMsg||""}))})}[n(1639)](t){let r=n,o={ONIfO:e[r(598)]};if(e[r(1416)](t,Uint8Array)){if(e.XGtqM(e.sGVvq,e.sGVvq))return this[r(1299)]===-1&&e[r(756)](-1,this.high)?_0x1d08f2[r(1386)](0,0,this.unsigned):e[r(1421)](-1,this[r(1299)])?_0x26bf35[r(1386)](0,e[r(1022)](this.high,1),this[r(1046)]):_0x433692[r(1386)](e[r(1217)](this[r(1299)],1),this[r(1069)],this[r(1046)]);{let x=t[r(400)][r(1733)](t.byteOffset,e.kenGQ(t.byteLength,t[r(1700)+"et"]));this[r(638)]&&this[r(638)][r(1639)]({data:x,fail:h=>{let m=r;this.emit(e[m(598)],e[m(466)](de,e.EshMr,{message:this[m(430)+m(789)+"age"](h)}))}})}}else this[r(638)]&&this[r(638)][r(1639)]({data:t,fail:x=>{let h=r;this[h(863)](o[h(924)],de(o[h(924)],{message:this[h(430)+h(789)+"age"](x)}))}})}[n(1529)](t,r){let o=n;if(e[o(786)](e[o(1141)],e.rpxCE))return _0xa4b1c9[o(1730)+"oreNames"][1]?void 0:_0x5ecfaf[o(1730)+o(743)](_0x392870.objectStoreNames[0]);this[o(638)]&&this[o(638)].close({code:t,reason:r})}[n(1257)+n(1682)](t,r){this.on(t,r)}[n(611)+n(1121)+n(647)](t,r){let o=n,x={vGWJW:function(h,m){return e[D(399)](h,m)},Ijyzz:e[o(1478)],yImMk:e[o(700)]};e[o(532)](e[o(1620)],e[o(1470)])?(this[o(861)+o(664)]()&&(!this._ws||x[o(958)](this._ws[o(1625)+"te"],this[o(1074)])||this._ws.readyState!==this.CONNECTING)&&this[o(971)+o(1149)](),this[o(526)+"er"]&&_0x27554d[o(1257)+"Listener"](x[o(942)],this[o(971)+o(1149)]),this[o(526)+"er"]&&_0x5514e7[o(1257)+o(1682)](x[o(892)],this[o(971)+"ffLine"])):this.off(t,r)}get[n(1625)+"te"](){return this[n(638)].readyState}get binaryType(){let t=n,r={bEkKl:function(o,x){return e[D(1272)](o,x)},qpSku:function(o,x,h,m){return e[D(1507)](o,x,h,m)}};if(e[t(812)]("WLOBz",e.GerJI)){let o=r[t(1593)](255,_0x32860f);r[t(1253)](_0x2971c6,o,_0x306d12,_0x3b25e0+_0x27132c),_0x4e31a5>>>=8,_0xe68d11--}else return this._socket.binaryType}set[n(897)+"pe"](t){}get[n(1450)](){let t=n,r={KPwpP:function(o,x){return e[D(1248)](o,x)},crKle:t(565)+"alled mu"+t(1186)+t(877)+"process",TeTXU:function(o,x){return o+x}};return e[t(1515)]("NcZKz",t(1334))?r.KPwpP(_0x5ebf35,_0x5ed6c5)?_0x3d7eca[t(1114)](new _0x31da90(r[t(1801)])):(_0x47e6eb=_0x459368,_0x2bfd7f===_0x41fa88.length?_0x544410[t(1129)]():_0x51638c[_0x4ef17e][t(1545)](_0x26b1db)(_0x4a0609,_0x4e2ab4[t(1545)](null,r[t(1581)](_0x4e0b6e,1)))):this[t(638)].url}get protocol(){return this[n(638)].protocol}get[n(1265)+"ns"](){return this[n(638)].extensions}get bufferedAmount(){return 0}}function Wa(s,t){let r=n;if(t)return new t(s[r(1450)],s.protocol);if(It||Ze)return new Ka(s.url,s[r(763)],s[r(1313)]);if((ct||Dt)&&e[r(1051)](e[r(1611)],typeof WebSocket)&&WebSocket)return new WebSocket(s[r(1450)],s[r(763)+"s"])}function Ja(s){let t=n,r=e[t(1527)][t(542)]("|"),o=0;for(;;){switch(r[o++]){case"0":if(e[t(512)](ct,Dt)&&e[t(1051)](e.MdhBG,typeof WebSocket)&&WebSocket)return!0;continue;case"1":if(s)return!0;continue;case"2":if(Ze&&tt[t(1643)+t(484)])return!0;continue;case"3":if(It&&wx[t(1643)+t(484)])return!0;continue;case"4":return!1}break}}function Ts(s,t,r){let o=-1;async function x(h){let m=D;return e[m(1293)](h,o)?Promise.reject(new Error("next() c"+m(1780)+"ltiple t"+m(877)+m(758))):(o=h,e[m(812)](h,r[m(1131)])?Promise[m(1129)]():r[h].bind(s)(t,x[m(1545)](null,h+1)))}e.HNUtz(x,0)}function Rs(s){let t=n,r=0,o=0;for(let x=0;e.PcOgu(x,s[t(1131)]);++x)o=s.charCodeAt(x),e.xMJKa(o,128)?r+=1:e.sInvq(o,2048)?r+=2:e[t(1515)](e[t(1362)](64512,o),55296)&&(64512&s[t(960)+"At"](x+1))===56320?(++x,r+=4):r+=3;return r}function Ns(s,t,r){let o=n;if(e[o(1368)](e[o(1418)],e[o(391)])){let x=e[o(1237)](this._options[o(619)+o(922)],_0x3e1a65)?{force:!!this[o(1805)][o(619)+o(922)][o(590)],encoding:this[o(1805)][o(619)+o(922)][o(561)]?this[o(1805)][o(619)+o(922)][o(561)].replace(/\s/g,"")[o(1669)+o(640)]():""}:{force:!1,encoding:this[o(1805)][o(619)+o(922)]?this[o(1805)][o(619)+o(922)][o(1042)](/\s/g,"")[o(1669)+o(640)]():""},h=_0x689e0e.payloadEncoding?_0x5c0bca[o(619)+o(922)][o(1042)](/\s/g,"")[o(1669)+o(640)]():"",m=this[o(1805)][o(1004)+o(972)]instanceof _0x77f4c4?{force:!!this[o(1805)][o(1004)+o(972)].force,type:this[o(1805)][o(1004)+o(972)][o(1432)]?this[o(1805)][o(1004)+o(972)].type[o(1042)](/\s/g,"")[o(1669)+o(640)]():""}:{force:!1,type:this._options[o(1004)+"ype"]?this[o(1805)]["payloadT"+o(972)][o(1042)](/\s/g,"")[o(1669)+o(640)]():""},g=_0x56fe2b.payloadType?_0x1ba845[o(1004)+o(972)][o(1042)](/\s/g,"")[o(1669)+o(640)]():"",d=m[o(590)]?m[o(1432)]:g||m.type,b=x.force?x[o(561)]:h||x[o(561)],E=[e[o(1430)],e.oLZjP,e[o(1307)],e[o(776)]],v=[e[o(1661)],e[o(1027)]];this._options[o(594)+o(431)+"extPayload"]&&E[o(1062)](d)&&(!b||v.includes(b))?_0x1a614d[o(1415)+"oad"]=e.XUUZZ(_0x581b0b,_0x2c0e85[o(687)],0,_0x2b3442[o(687)][o(1685)+"th"]):_0x13e6da[o(1415)+o(683)]=""}else{if(e.kRzEk(e[o(1335)](r,t),1))return"";let x="";for(let h=t;h<r;)if(e[o(1459)]==="RLWDn"){let m=s[h++];if(e.pzcwW(m,127))x+=String["fromChar"+o(935)](m);else if(e[o(1499)](m,192)&&m<224)x+=String[o(1075)+"Code"](e[o(1614)](e[o(574)](31,m)<<6,e[o(477)](63,s[h++])));else if(e.RjSLM(m,224)&&m<240)x+=String[o(1075)+"Code"](e[o(1455)](e.tyWEs(15,m)<<12,e[o(934)](e[o(1071)](63,s[h++]),6))|63&s[h++]);else if(m>=240){let g=e[o(1244)](e[o(1245)](e[o(1449)](e[o(1143)](e[o(476)](7&m,18),e[o(1440)](e.tyWEs(63,s[h++]),12)),e[o(1127)](e[o(639)](63,s[h++]),6)),e.BDVfH(63,s[h++])),65536);x+=String[o(1075)+o(935)](e.jlLUs(55296,e[o(967)](g,10))),x+=String[o(1075)+o(935)](e[o(1567)](56320,e[o(1570)](1023,g)))}}else _0x4407ac.o=(m,g)=>_0x5510be.prototype[o(1206)+o(1727)].call(m,g);return x}}function dr(s,t,r){let o=n,x=r,h,m;for(let g=0;e[o(392)](g,s.length);++g)h=s[o(960)+"At"](g),h<128?t[r++]=h:e.Qvuzd(h,2048)?(t[r++]=e.RXttS(e[o(432)](h,6),192),t[r++]=e[o(930)](63,h)|128):e.vZlQM(e[o(1221)](64512,h),55296)&&e[o(1067)](e[o(1184)](64512,m=s.charCodeAt(e[o(1473)](g,1))),56320)?(h=e.ilZAX(e[o(1678)](65536,e.pKcGk(e[o(1119)](1023,h),10)),e[o(678)](1023,m)),++g,t[r++]=e[o(1143)](e[o(967)](h,18),240),t[r++]=e[o(1407)](e[o(1588)](h,12)&63,128),t[r++]=e[o(860)](e[o(432)](h,6),63)|128,t[r++]=e[o(930)](63,h)|128):(t[r++]=e[o(1558)](e.ETkje(h,12),224),t[r++]=e[o(1088)](e[o(1570)](e.ETkje(h,6),63),128),t[r++]=e[o(964)](63,h)|128);return e.ucnYk(r,x)}async function Ls(s){let t=n,r={sgDih:function(o,x){return e[D(1467)](o,x)},aolkL:function(o,x){return e[D(401)](o,x)},YOilI:function(o,x){return e[D(1127)](o,x)},FcRgc:function(o,x){return e.kRZim(o,x)},rwNbY:function(o,x){return e[D(968)](o,x)},iOqQb:function(o,x){return o|x},fgyef:function(o,x){return e[D(398)](o,x)}};if(e[t(1578)](e[t(776)],typeof s))if(e.EfaRb!==e[t(1778)]){let o=new Uint8Array(e.ZPNNC(Rs,s));return e[t(1507)](dr,s,o,0),o}else return new _0x246436(NwZfCF.sgDih(NwZfCF[t(952)](_0xd57a76[0]|NwZfCF[t(894)](_0x410282[1],8),NwZfCF[t(1453)](_0x18cde4[2],16)),NwZfCF[t(894)](_0x5f3d15[3],24)),NwZfCF[t(387)](NwZfCF[t(1693)](NwZfCF[t(528)](_0x2a4651[4],NwZfCF[t(1039)](_0x46f832[5],8)),_0x3573c7[6]<<16),_0x39091e[7]<<24),_0x320501);return e[t(1237)](s,ArrayBuffer)?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s[t(1685)+"th"])}function Va(s){let t=n;try{return e[t(776)]!=typeof s&&(e[t(849)](s,ArrayBuffer)||s[t(400)]&&e[t(1475)](s.buffer,ArrayBuffer))||e[t(644)](t(1561),typeof s)?"":(JSON.parse(s),t(1743)+t(1648))}catch{if(e[t(1162)]!==e[t(1162)]){if(e[t(685)](_0x3ffbf0,_0x450241))return _0x21537f}else return e[t(776)]==typeof s?e[t(1430)]:""}}let $a=(s,t)=>{let r=n;switch(s){case e[r(1465)]:case e[r(589)]:return{[r(651)+s]:1,"x-tt-env":t};default:return{}}};class Xa{constructor(t){let r=n;this[r(811)+"ount"]=t,this[r(694)]=0}[n(1802)](){let t=n;this[t(694)]++}[n(1095)+n(953)+"nt"](){let t=n;return e[t(764)](this[t(694)],this[t(811)+t(429)])}[n(1793)+n(1540)](t=0){let r=n;this[r(811)+r(429)]=t,this[r(694)]=0}}async function Ya(s){let t=n,r={MSIJJ:function(o,x){return o(x)},tqzUd:e.awfyP,XhMKK:function(o,x){return e[D(1226)](o,x)},BSxER:function(o,x){return e[D(1741)](o,x)},sRtBq:e[t(443)],fOzdS:e[t(1680)],qYTLs:function(o,x){return e[t(1022)](o,x)},gUtAp:e[t(1099)],OJFzU:e[t(1495)]};return new Promise(o=>{let x=t,h={OJBgG:function(m,g){return r.XhMKK(m,g)}};if(!ct)return r.MSIJJ(o,x(438)+x(1760));try{if(r[x(1328)](x(1547),r[x(560)])){let m=document.createElement(r[x(420)]);window[x(634)+x(920)]=g=>{let d=x;document[d(1709)][d(829)+d(488)](m),window[d(634)+d(920)]=void 0,r[d(1158)](o,g&&g[d(1472)]||r[d(1161)])},m.type=x(1770)+x(959),m[x(423)]=r[x(1002)](s[x(1042)](/^ws/,r[x(1168)]),x(1708)+x(1737)+"tierJSONP");try{x(1541)!==x(1180)?document[x(1709)][x(1109)+x(488)](m):!this[x(1274)+x(1273)]&&(this[x(987)+x(454)]?.[x(591)+"pointCon"+x(1721)](),this[x(469)+x(696)]?.[x(1793)+x(1540)](),this[x(827)+"osed"]=!1,this._isInit=!0,this[x(1274)]())}catch{if(r[x(995)]===r[x(995)])document[x(1709)][x(829)+"ild"](m);else{let g=_0x1b4a95[_0x272ea9];if(_0x3e5168[_0x11de59][x(1131)]!==4){let d=_0x4c99c2[x(1271)+"g"](0,PnnrNu[x(1666)](4,_0x1bb80f[_0x5d2258][x(1131)])),b=d.concat(g);_0x2855a6=_0x17cd0a[x(741)](b)}else _0x1ac6a9=_0x3289a9[x(741)](g)}}}else _0x7b1f61[x(681)](_0x5d5846)}catch{window[x(634)+x(920)]=void 0,r.MSIJJ(o,r.tqzUd)}})}function je(s,t,r){let o=n;return!!s?.find(x=>x[o(1080)]===t&&x.value===r)}function xt(s,t){let r=n;return s?.[r(1198)](o=>o.key===t)?.[r(752)]}let lr=null;async function Za(){let s=n;return lr||(lr=Promise[s(1129)]()[s(415)](ke[s(1545)](ke,e.xSCnF))),lr}class Qa extends fr{constructor(t,r){let o=n;super(),this._dbName=t,this._keyPath=r,this[o(673)]=void 0,this._initPromise=null}async[n(437)](){let t=n;if(e.oHTnb(e[t(778)],e[t(778)])){let r={paXgR:function(o,x){return QPEWYD.gojmr(o,x)}};return function(...o){let x=t;return _0x5b60bb[x(1222)](r.paXgR(_0xa492a4,this),o),r[x(791)](_0x5ada97,_0x24e799[x(843)](this))}}else await this[t(1748)]()}async[n(1748)](){let t=n,r={SVVhh:function(o,x,h){return o(x,h)}};if(e[t(1537)](e.mVtgo,e.fSzrG)){if(this[t(673)])return;if(this[t(1504)+t(1583)])return this[t(1504)+t(1583)];try{let o=this[t(618)],x=this._keyPath;this._initPromise=(async()=>{let h=t,{openDB:m}=await e[h(1394)](Za);this[h(673)]=await e[h(376)](m,"frontier_"+o,1,{upgrade(g){let d=h;g[d(625)+d(1266)+"e"](o,{keyPath:x})}})})(),await this[t(1504)+t(1583)]}catch(o){console[t(681)](o)}finally{this[t(1504)+t(1583)]=null}}else _0x20edfe(_0x3e5b4f,90),LjQsQN[t(834)](_0x11ec74,_0x5c8db9,_0x1ffceb)}async[n(843)](t){let r=n;try{if(e.yKywI(e[r(1044)],e.lAfvb))return await this[r(1748)](),this._qosDB?.[r(843)](this[r(618)],t);_0x748fa9[r(1709)][r(829)+r(488)](_0x2b4169)}catch(o){console.log(o)}}async[n(1043)](t,r){let o=n;return await this[o(1748)](),this[o(673)]?.[o(1516)](this._dbName,t)}async[n(823)](t){let r=n;try{return await this[r(1748)](),this._qosDB?.[r(518)](this._dbName,t)}catch(o){console.log(o)}}async clear(){let t=n;try{return await this[t(1748)](),this[t(673)]?.[t(1346)](this[t(618)])}catch(r){console[t(681)](r)}}async[n(1425)](){let t=n;return await this[t(1748)](),this[t(673)]?.[t(1555)+"ys"](this[t(618)])}async getAll(){let t=n;return await this[t(1748)](),this._qosDB?.getAll(this[t(618)])}async closeDB(){let t=n;try{this[t(673)]?.[t(1529)](),this[t(673)]=void 0}catch(r){console[t(681)](r)}}get isReady(){let t=n;try{return!!this[t(673)]}catch(r){return console[t(681)](r),!1}}}class e0{constructor(t,r){let o=n;this._DBName=t,this[o(1716)]=r,this[o(673)]=localStorage}async openDB(){}get[n(648)](){return n(634)+"_"+this._DBName}async[n(843)](t){let r=n,o=this[r(673)][r(989)](this[r(648)]);return JSON[r(516)](e[r(662)](o,"{}"))[t]}async[n(1043)](t,r){let o=n,x=this._qosDB[o(989)](this._prefix),h=JSON[o(516)](e[o(1664)](x,"{}"));return h[r||t[this[o(1716)]]]=t,this[o(673)][o(1241)](this._prefix,JSON[o(1342)+"y"](h)),r||t[this[o(1716)]]}async[n(823)](t){let r=n,o=this[r(673)][r(989)](this[r(648)]),x=JSON[r(516)](e[r(1256)](o,"{}"));return x[t]=void 0,this._qosDB[r(1241)](this[r(648)],JSON[r(1342)+"y"](x))}async[n(1346)](){let t=n;if(e[t(1670)](e.nXgUi,e[t(1454)]))return this[t(673)][t(1346)]();{let r=_0x161887[t(1702)+"tabase"](_0x3476cd);return _0x190ff7&&r.addEventListener(QPEWYD[t(1118)],()=>_0x543f4c()),QPEWYD[t(728)](_0x25ec42,r).then(()=>{})}}async[n(1425)](){let t=n,r=this[t(673)][t(989)](this[t(648)]),o=JSON[t(516)](e[t(662)](r,"{}"));return Object.keys(o)}async[n(1137)](){let t=n,r={jldmH:function(o,x){return o<x},Aajkp:function(o,x){return e[D(1758)](o,x)},HFHPO:function(o,x){return e[D(1017)](o,x)},wzjcE:function(o,x){return e.CTGGZ(o,x)},fiEdY:function(o,x){return o>>x},YgoHP:function(o,x){return e[D(911)](o,x)},QoJRt:function(o,x){return e[D(1592)](o,x)}};if(e.vHBGP==="pokNV"){let o=this._qosDB.getItem(this[t(648)]),x=JSON[t(516)](e[t(662)](o,"{}"));return Object[t(593)](x)}else iVJjqz[t(1015)](_0x1530f1,65536)?_0x338235[_0x32278d++]=iVJjqz[t(1597)](iVJjqz[t(1005)](_0x478ae3>>12,15),224):(_0x56eeff[_0x1085f7++]=iVJjqz[t(1310)](iVJjqz[t(1532)](_0x21c83c,18)&7,240),_0x45dda8[_0x3f5f5d++]=iVJjqz[t(845)](iVJjqz[t(1532)](_0x4bd101,12)&63,128)),_0x2802dd[_0x582879++]=iVJjqz[t(1630)](iVJjqz[t(1532)](_0x56d869,6)&63,128)}[n(1079)](){return Promise.resolve()}get[n(1676)](){let t=n;return e[t(485)](e.IlZui,t(1107))?_0x8294c0(_0x412d6.apply(_0x565c13(this),_0x104f7f)):!!this._qosDB}}class t0{constructor(t,r){let o=n;this[o(1018)]=t,this[o(1716)]=r,this._qosDB=Ze?tt:It?wx:null}async openDB(){}get[n(648)](){let t=n;return t(634)+"_"+this[t(1018)]}async[n(843)](t){let r=n,o=this._qosDB[r(1238)+r(1690)](this[r(648)]);return JSON[r(516)](e.QiPTo(o,"{}"))[t]}async[n(1043)](t,r){let o=n,x=this[o(673)][o(1238)+o(1690)](this[o(648)]),h=JSON[o(516)](e[o(512)](x,"{}"));return h[r||t[this._pathKey]]=t,this[o(673)][o(614)+o(1690)](this[o(648)],JSON.stringify(h)),r||t[this[o(1716)]]}async del(t){let r=n,o=this[r(673)]["getStora"+r(1690)](this[r(648)]),x=JSON.parse(e.xDKUh(o,"{}"));return x[t]=void 0,this._qosDB[r(614)+r(1690)](this._prefix,JSON[r(1342)+"y"](x))}async[n(1346)](){let t=n;return this[t(673)][t(1779)+t(799)]()}async[n(1425)](){let t=n,r=this[t(673)]["getStora"+t(946)+"nc"](this[t(648)]),o=JSON[t(516)](r||"{}");return Object[t(1425)](o)}async[n(1137)](){let t=n,r=this[t(673)][t(1238)+t(946)+"nc"](this[t(648)]),o=JSON[t(516)](e[t(512)](r,"{}"));return Object.values(o)}[n(1079)](){return Promise[n(1129)]()}get[n(1676)](){return!!this._qosDB}}function Os(s,t){let r=n;if(e[r(1664)](Ze,Ze))return new t0(s,t);if(e[r(662)](ct,Dt)&&e[r(1611)]!=typeof indexedDB)return new Qa(s,t);if(e[r(1591)](ct,Dt)&&typeof localStorage<"u")return new e0(s,t);throw new Error(e[r(746)])}class n0{constructor(){let t=n;this[t(1070)+t(838)+"Id"]=null,this[t(1070)+"l"]=36e5,this[t(673)]=Os(e[t(1525)],e[t(813)])}async[n(1070)+"lFlush"](){let t=n;e[t(1586)](clearInterval,this[t(1070)+t(838)+"Id"]),this[t(1070)+t(838)+"Id"]=e.gRtqE(setInterval,()=>{this[t(1333)+"ired"]()},this[t(1070)+"l"])}async[n(437)](){let t=n;if(e.AqFyD(t(1746),e[t(835)]))return this._ws?this[t(1120)][t(1265)+"ns"]:"";await this[t(673)][t(437)]()[t(415)](()=>{let r=t;this[r(1070)+r(1668)]()})}async[n(1333)+"ired"](){let t=n;(await this[t(673)]?.[t(1137)]()||[]).filter(({timestamp:x})=>x<Date[t(1549)]())[t(1610)](x=>{let h=t;this[h(673)]?.[h(823)](x[h(1406)+"id"])})}async[n(823)](t){let r=n;return this._qosDB?.[r(823)](t)}async set(t,r){return this[n(673)]?.set({message_id:t,timestamp:r})}async[n(843)](t){let r=n;return this[r(673)]?.[r(843)](t)}async closeDB(){let t=n;e[t(1446)](clearInterval,this[t(1070)+t(838)+"Id"]),await this[t(673)]?.[t(1079)]()}get[n(1676)](){let t=n;return this._qosDB?.[t(1676)]}}function hr(s){let t=n,r=!!this[t(1805)][t(1154)+"S"];if(!r)return{enabled:r,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=e[t(1631)](je,s.message[t(1313)],"x_frontier_qos","2"),x=o&&je(s[t(1460)][t(1313)],e[t(1369)],"1"),h=o&&e.musMi(je,s.message[t(1313)],"x_frontier_is_ack","1"),m=h?e.QOnkd(xt,s[t(1460)][t(1313)],t(1287)+t(461)+t(1776))?.[t(542)](",")[t(1745)](Boolean)||[]:[];return{enabled:r,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:h,ackMsgIds:m}}async function Bs(){let s=n;return this[s(1147)+s(688)]||(this["_QoSMana"+s(688)]=new n0),this["_QoSMana"+s(688)][s(1676)]||await this._QoSManager.openDB(),this[s(1147)+s(688)]}async function r0(s,t){let r=n,{enableAutoAck:o}=this[r(1805)],x=je(s[r(1460)].headers,e[r(744)],"1"),h=e[r(1507)](je,s.message.headers,e[r(783)],"1"),m=hr.call(this,s);if(e.SBBWz(o,x)){let{SeqID:g,LogID:d,service:b,LogIDNew:E,method:v}=s[r(1460)];this._sendAck({SeqID:g,LogID:d,LogIDNew:E,service:b,method:v,headers:[{key:e[r(783)],value:"1"},{key:e.TAIxb,value:e[r(1664)](E,"")},{key:e[r(938)],value:"0"}]})}h&&!m.isQoSAck&&this[r(1028)+r(1742)+"ageEvent"](s),e[r(1553)](t)}async function s0(s,t){let r=n;this[r(729)](e.SmuKx,s[r(1460)]),e.jibGN(t)}async function i0(s,t){let r=n,o=e[r(375)](ms,await e[r(1490)](Ls,s[r(1347)]));try{if(o[r(687)]instanceof Uint8Array){let x=e.PCvVp(this[r(1805)][r(619)+r(922)],Object)?{force:!!this[r(1805)][r(619)+"ncoding"].force,encoding:this[r(1805)][r(619)+"ncoding"][r(561)]?this._options[r(619)+"ncoding"][r(561)][r(1042)](/\s/g,"")[r(1669)+r(640)]():""}:{force:!1,encoding:this[r(1805)][r(619)+r(922)]?this[r(1805)][r(619)+"ncoding"][r(1042)](/\s/g,"")[r(1669)+r(640)]():""},h=o[r(619)+r(922)]?o["payloadE"+r(922)].replace(/\s/g,"")["toLowerC"+r(640)]():"",m=e[r(559)](this[r(1805)]["payloadT"+r(972)],Object)?{force:!!this._options[r(1004)+"ype"][r(590)],type:this._options[r(1004)+r(972)][r(1432)]?this._options["payloadT"+r(972)][r(1432)][r(1042)](/\s/g,"")[r(1669)+"ase"]():""}:{force:!1,type:this[r(1805)].payloadType?this[r(1805)][r(1004)+"ype"].replace(/\s/g,"")[r(1669)+r(640)]():""},g=o[r(1004)+"ype"]?o[r(1004)+r(972)][r(1042)](/\s/g,"")[r(1669)+"ase"]():"",d=m.force?m[r(1432)]:g||m[r(1432)],b=x.force?x[r(561)]:h||x[r(561)],E=[e[r(1430)],e[r(1671)],e[r(1307)],e[r(776)]],v=[e[r(1661)],e[r(1027)]];this[r(1805)]["enableTr"+r(431)+r(1268)+"ad"]&&E[r(1062)](d)&&(!b||v[r(1062)](b))?o["textPayl"+r(683)]=e.Hqimn(Ns,o[r(687)],0,o[r(687)][r(1685)+"th"]):o["textPayl"+r(683)]=""}else o[r(1415)+"oad"]=""}catch(x){o["textPayl"+r(683)]="",console[r(681)](x)}s[r(1460)]=o,e[r(1323)](t)}function o0(s,t,r){let o=n;if(e[o(1041)](e[o(1615)],e.lpqVo))this["_message"+o(675)][o(1381)](_0x4c40a8),this._debug("enqueue",_0x86ef47);else{let x=r||8192,h=e[o(1153)](x,1),m=null,g=x;return function(d){let b=o;if(e[b(392)](d,1)||e[b(1565)](d,h))return e[b(1573)](s,d);e[b(1053)](e.pNgNP(g,d),x)&&(m=s(x),g=0);let E=t[b(491)](m,g,g+=d);return e.acxuC(7,g)&&(g=e[b(737)](e[b(1464)](7,g),1)),E}}}let a0=4294967295;function c0(s,t,r){let o=n;return RangeError(e[o(936)](e[o(1567)](e[o(1594)](e[o(893)](e[o(1679)](o(1414)+o(605)+o(1629),s),o(1057)),t||1),e.YteMY),r))}function x0(s,t,r){let o=n;if(r>a0)throw new Error(o(1753)+o(1653)+"e");let x=3;for(;e.iCKpg(x,0);){let h=e[o(931)](255,r);e[o(376)](pr,h,s,e[o(772)](t,x)),r>>>=8,x--}return e[o(382)](t,4)}function u0(s,t){let r=n,o=0,x=t,h=e.cotqg(t,4);for(;x<h;){let{value:m,offset:g}=e[r(383)](gr,s,x);x=g,o=e[r(1483)](o<<8,0),o+=m}return{value:o,offset:h}}function f0(s,t,r){let o=n,x=e[o(1658)][o(542)]("|"),h=0;for(;;){switch(x[h++]){case"0":if(t[o(1203)+"e"])return e.evpGf(t[o(1203)+"e"](s,r),r);continue;case"1":if(t[o(470)])return e[o(1349)](t[o(470)](s,r),r);continue;case"2":if(s[o(1131)]<40)return dr(s,t,r)+r;continue;case"3":return e[o(842)](dr(s,t,r),r);case"4":if(!s)return r;continue}break}}function d0(s,t){let r=n,o=new q(e[r(1245)](e[r(1503)](s[t+4]<<24|e[r(1010)](s[e[r(1276)](t,5)],16),s[t+6]<<8),s[e[r(1567)](t,7)]),e[r(1412)](e[r(1289)](s[e[r(1217)](t,0)]<<24,e[r(1127)](s[e[r(382)](t,1)],16)),e[r(1010)](s[e[r(1316)](t,2)],8))|s[e[r(1059)](t,3)],!0);return t+=8,{value:o,offset:e[r(1719)](t,8)}}function l0(s,t,r){let o=n;if(e[o(1006)](e[o(940)],e.krehw)){let x=s[o(1299)],h=s[o(1069)];return t[r]=h>>>24,t[e[o(568)](r,1)]=e[o(1164)](h,16)&255,t[r+2]=e.oOkaS(e[o(668)](h,8),255),t[r+3]=e.wdqCu(255,h),t[e[o(893)](r,4)]=e[o(1772)](x,24),t[r+5]=e[o(705)](e[o(1100)](x,16),255),t[e[o(755)](r,6)]=e[o(1219)](x>>>8,255),t[e[o(1013)](r,7)]=e[o(548)](255,x),r+=8,r}else{if(e[o(1067)](void 0,_0x6a6b95))this[o(1191)+"rs"]={};else if(e[o(1515)](void 0,_0x5df6c8))this[o(1191)+"rs"][_0x281858]=null;else{let x=this[o(1191)+"rs"][_0x4912b5];if(x)for(let h=0;e[o(859)](h,x.length);)x[h].fn===_0x553e6a?x[o(660)](h,1):++h}return this}}function gr(s,t){let r=n;return s[r(1438)+"8"]?{value:s[r(1438)+"8"](t),offset:t+1}:{value:255&s[t],offset:t+1}}function pr(s,t,r){let o=n;return t.writeUint8?t[o(1498)+"t8"](s,r):t[r]=e.acxuC(255,s),e[o(1594)](r,1)}let h0=function(s){return new Uint8Array(s)},g0=e[n(851)](e[n(1611)],typeof Buffer)?Buffer["allocUns"+n(552)]:e.PpUlh(o0,h0,Uint8Array[n(408)+"e"].subarray),p0=16,mr=32;function m0(s){let t=n,r={fCieM:function(h,m,g){return e[D(418)](h,m,g)}},o=0,x={};for(let h=0;e.RPONd(h,s[t(1131)]);h++)e[t(812)](e.RrDSO,e[t(497)])?(_0x56569a(_0xcffd1d,58),oJkMVw[t(1134)](_0x12cf0f,_0x563c92,_0xf79f39)):(x[s[h].cursor_name]=e[t(1424)](Rs,s[h][t(1796)+"ame"]),o+=e[t(1155)](14,x[s[h][t(1796)+t(1112)]]));return[o,x]}function Ms(s,t,r){let o=n,[x,h]=m0(s),m=e[o(1601)](g0,x),g=0;return s[o(1610)](d=>{let b=o,E=e[b(602)][b(542)]("|"),v=0;for(;;){switch(E[v++]){case"0":g=e[b(1507)](l0,q[b(1584)+"er"](d.cursor||t),m,g);continue;case"1":console[b(681)](e[b(1115)],g);continue;case"2":console[b(681)](e[b(714)],g);continue;case"3":g=e[b(969)](x0,m,g,d.service||0);continue;case"4":console[b(681)](b(1364)+b(1738),d,d[b(974)]);continue;case"5":g=e[b(1507)](pr,0,m,g);continue;case"6":g=e[b(1433)](pr,h[d[b(1796)+"ame"]],m,g);continue;case"7":g=e.bxZlL(f0,d["cursor_n"+b(1112)],m,g);continue;case"8":console[b(681)](e[b(1482)],g);continue;case"9":console[b(681)](b(1749)+"name",g);continue;case"10":console[b(681)](e[b(1803)],g);continue}break}}),{frameType:mr,headers:[{key:e[o(1332)],value:r}],payload:m}}function w0(s){let t=n,r={oORyg:function(h){return e[D(1506)](h)}},o=0,x=[];for(;e[t(392)](o,s[t(1685)+"th"]);){if(e[t(785)](e.Gwtep,e[t(1785)]))return this[t(1028)+t(601)+"Event"](_0x3af727),r[t(1698)](_0x5ded72);{let{offset:h}=e[t(413)](gr,s,o);o=h;let m={cursor_name:"",cursor:0,service:0},{value:g,offset:d}=e.oagiL(u0,s,o);m.service=g,o=d;let{value:b,offset:E}=e[t(1032)](gr,s,o);o=E,m[t(1796)+"ame"]=Ns(s,o,e.ttGHA(o,b)),o+=b;let{value:v,offset:L}=e[t(413)](d0,s,o);m.cursor=v[t(1270)](),o=L,x.push(m)}}return x}function _0(){let s=n;if(e[s(695)](s(1283),e[s(1040)]))return{frameType:mr,headers:[{key:e.EePWc,value:e.qokVf}],payload:void 0};_0x5aaabb&&_0x5d7691[s(1257)+s(1682)](s(1529),()=>_0x37ed8a()),_0x51d1e2&&_0x142e10[s(1257)+s(1682)]("versionc"+s(1759),()=>_0x48c4f0())}class y0{constructor(t,r,o){let x=n;this[x(1646)+x(503)]=t,this["_cursorF"+x(706)]=r,this[x(1520)+x(1234)]=o,this[x(673)]=e[x(1533)](Os,this[x(1646)+"ameSpace"],e[x(748)])}async openDB(){let t=n;await this[t(673)][t(437)]()}async getCursors(){let t=n;if(!this._qosDB[t(1676)])return;let r=this[t(1520)+t(1234)],o=await this._qosDB[t(1137)]();switch(console[t(681)](e[t(1766)],o),r){case e[t(1063)]:return o&&o[t(1131)]?Ms(o,0,this[t(821)+"ileName"]):void 0;case e.EiZZY:return;case e[t(1297)]:return o&&o[t(1131)]?e[t(765)](Ms,o,0,this[t(821)+t(706)]):e.knYzb(_0)}}async[n(1043)](t,r,o){let x=n,h={qSliW:e[x(380)]};return e[x(1441)](e[x(1616)],e.HScbu)?(console[x(681)](e[x(726)],t,r,o),this[x(673)][x(1043)]({cursor_name:t,cursor:r,service:o})):(_0x469e92||(_0x187363=_0x3a10f1[x(1129)]()[x(415)](_0x67ec99[x(1545)](_0x2bbc8a,CjHJXY[x(1264)]))),_0x354d71)}async[n(567)+"rs"](t){let r=n,o=e[r(1563)](w0,t);for(let x of o)console[r(681)](e[r(1511)],o),await this[r(673)][r(1043)](x)}async[n(843)](t){let r=n;return(await this[r(673)].get(t))?.[r(948)]}async[n(1079)](){let t=n;await this[t(673)][t(1079)]()}["updateCu"+n(411)+"Name"](t){let r=n,o={jWORc:function(x,h,m){return x(h,m)}};e.NIufC!==r(1092)?this["_cursorF"+r(706)]=t:(this[r(1646)+r(503)]=_0xea7c30,this[r(821)+"ileName"]=_0x47347a,this[r(1520)+r(1234)]=_0x334f79,this[r(673)]=Oayxek[r(808)](_0x543121,this["_cursorN"+r(503)],r(1796)+r(1112)))}get[n(1676)](){let t=n;return this._qosDB[t(1676)]}}let b0=e.Bakeo;async function zs(s){let t=n,r={OMRrp:function(g){return g()}};if(!this[t(1805)][t(1154)+"S"])return null;let{aID:o,fpID:x,messageStrategy:h}=this[t(1805)],m=e[t(790)](s,b0);try{if(e[t(1035)](e.aLuog,e.XHGrG))return this[t(1190)+t(836)]?s&&this[t(1190)+t(836)][t(1613)+"rsorFile"+t(1559)](s):this["_cursorM"+t(836)]=new y0(x+"_"+o+"_"+m,m,h),this[t(1190)+t(836)][t(1676)]||await this[t(1190)+t(836)][t(437)](),this["_cursorM"+t(836)];{let g={cCJUb:t(421),vlMxt:QPEWYD.ttjiP,NyByf:function(v,L){let N=t;return QPEWYD[N(1436)](v,L)},ryNoo:QPEWYD[t(770)],ZtAqt:function(v){let L=t;return QPEWYD[L(1036)](v)}},d=()=>{let v=t;_0x370488[v(611)+v(1121)+v(647)](v(626),b),_0xa33c39[v(611)+"entListe"+v(647)](g[v(1025)],E),_0x19e2bb["removeEv"+v(1121)+v(647)](g[v(1344)],E)},b=()=>{let v=t;HSNPaD[v(1068)](_0x5784ad),HSNPaD.OMRrp(d)},E=()=>{let v=t;g.NyByf(_0x1b9d9a,_0x263838[v(421)]||new _0x3eebdb(g[v(750)],g[v(750)])),g[v(1692)](d)};_0x1e5c05[t(1257)+t(1682)](QPEWYD[t(547)],b),_0x3636b1[t(1257)+t(1682)](QPEWYD.EshMr,E),_0x260eb7.addEventListener(t(1783),E)}}catch{return null}}async function v0(s,t){let r=n,o=e[r(1094)](je,s[r(1460)][r(1313)],e[r(1697)],"-1"),x=e.ElhgN(je,s[r(1460)][r(1313)],e[r(783)],"1"),h=e[r(932)](xt,s[r(1460)].headers,e[r(655)]),m=e[r(1175)](Number,e.vjRee(xt,s[r(1460)].headers,e[r(1447)]))||0,g=hr[r(491)](this,s),d=je(s[r(1460)].headers,"x-msg-qos","2"),b=e[r(413)](xt,s[r(1460)].headers,r(1566)+r(1214)+"e"),E=Number(e.VDRle(xt,s[r(1460)][r(1313)],e[r(1007)]));if(g[r(386)])return e.IyIdp(t);let v=g[r(506)+r(563)]?await Bs[r(491)](this):null;if(e[r(692)](s[r(1460)].service,0)&&x&&!o||e.blTTI(s[r(1460)][r(974)],0)){if(h&&g[r(506)+"sage"]&&v)return!!!await v[r(843)](h)&&(this[r(1028)+r(601)+r(712)](s),await v[r(1043)](h,e[r(1752)](Date.now(),m))),t();if(d){let L=await zs.call(this);if(!L){if(e[r(1434)](e[r(848)],e[r(848)]))return this[r(1028)+r(601)+"Event"](s),t();this[r(440)+"s"]=_0x2399b9,this[r(1211)+"es"]=_0x573690,this[r(1442)+r(1304)]=0,this[r(871)+r(1628)+r(1389)+"t"]=0}let N=await L[r(843)](b)??-1;if(N<E)this["_dispatc"+r(601)+r(712)](s),L[r(1043)](b,E,s[r(1460)][r(974)]);else throw new Error(r(381)+r(653)+r(1560)+E+(" larger than loc"+r(596)+"r ")+N);return t()}return this[r(1028)+r(601)+r(712)](s),e.FwqtL(t)}}async function S0(s,t){let r=n;if(e.XQWqN(e.EPNoV,e.COAwM)){let o=hr[r(491)](this,s);if(!o[r(506)+"sage"])return e.PfXqL(t);let x=await Bs[r(491)](this);if(o.isAckCleanupMessage&&o[r(1637)+"s"][r(1131)])for(let h of o[r(1637)+"s"])await x.del(h);e.SIksO(t)}else{let o=this[r(987)+r(454)]?.[r(1471)+r(1124)+"nt"](),x=this._options[r(1337)+"tInterce"+r(1228)](_0x400af4.code,_0x4051dc[r(1760)]);this[r(1028)+"hCloseEv"+r(604)](e[r(1032)](_0x5129d5,"close",{code:1006,reason:_0x35dc5e[r(1760)]||r(1761)+r(1255)+r(578)+r(543)+"n, hostn"+r(1491)+o,willReconnect:x})),x&&this[r(1274)]();return}}async function E0(s,t){let r=n,o=e[r(508)](s[r(1460)][r(1054)+"e"],p0),x=e.YCBwT(s[r(1460)][r(1054)+"e"],mr);if(e[r(628)](!o,!x))return e[r(1512)](t);let h=e[r(551)](xt,s[r(1460)][r(1313)],"cursor_f"+r(1024));if(!h)return t();let m=await zs[r(491)](this,h);if(!m)return t();if(o){let g=await m[r(1318)+"rs"](),d={frameType:g?.[r(1054)+"e"],SeqID:q[r(1584)+"er"](this[r(1734)]++),LogID:q[r(1584)+"er"](this[r(1805)]["logIDGen"+r(623)]()),service:9e3,method:5,headers:g?.headers,payload:g?.[r(687)]},b=e[r(797)](C,d);this[r(1120)]&&this[r(1120)][r(1625)+"te"]&&this._ws.send(b)}if(x){let g=s[r(1460)][r(687)];g&&m[r(567)+"rs"](g)}}let C0=async function(s,t){let r=n;if(e[r(928)]===e.xnIYN)this[r(1173)]=!1,e[r(797)](clearTimeout,this[r(1274)+"ionTimeo"+r(773)]),t();else{let o=this[r(673)][r(989)](this._prefix),x=_0x9814c2.parse(o||"{}");return _0x37cf19[r(593)](x)}},A0=async function(s,t){let r=n;if(!this._ws||e[r(1409)](this._ws[r(1625)+"te"],this[r(1074)]))return e[r(1789)](t);let{pingInterval:o}=this._options;this[r(987)+r(454)]?.[r(591)+r(550)+r(1721)]();for(let h=0;e[r(595)](h,this[r(1520)+"Queue"][r(1131)]);h++){let m=this[r(1520)+r(675)][h];if(e.exglI(this[r(1120)][r(1625)+"te"],this[r(1074)])&&e.Szstw(null,m))this[r(1120)]&&this[r(1120)][r(1639)](m),this["_message"+r(675)][h]=null;else break}this[r(1520)+r(675)]=this[r(1520)+r(675)][r(1745)](h=>!!h),this[r(921)+r(1634)+"Id"]=e[r(1378)](setTimeout,()=>this[r(1102)](),o),this._dispatchOpenEvent(s),this._isBrowser&&this[r(1120)]&&(this[r(1120)][r(897)+"pe"]=this["_binaryT"+r(972)]);let x=this[r(987)+r(454)]?.[r(1471)+r(1124)+"nt"]();this[r(729)](r(474)+x+" success"),t()},k0=async function(s,t){let r=n;if(e[r(507)]("dpYSp",r(1522))){let o=this[r(987)+r(454)]?.[r(1471)+r(1124)+"nt"]();this[r(729)]("open "+o),t()}else{if(this[r(1805)][r(1135)+r(1799)+r(850)]||this[r(827)+r(1489)])return;this._handleReconnect()}};class P0 extends fr{constructor(t){let r=n,o={iUBbK:r(1208),mIqFf:function(g,d){return g===d},hYsXW:function(g,d){return e[r(425)](g,d)},AEVOf:e.xzHGS,uKNLh:e[r(439)],FiHUU:e[r(896)],yusop:function(g,d){return e[r(1765)](g,d)},emZLk:function(g,d,b,E){return g(d,b,E)},tnnqB:function(g,d,b){return e[r(820)](g,d,b)},CLTXH:r(421)};super(),this[r(1633)+"igatorOn"+r(1014)]=!0,this._isBrowser=ct,this[r(1103)]=ja,this[r(1797)+"T"]=Ze,this[r(1731)+"X"]=It,this[r(1345)+"r"]=Dt,this[r(1520)+r(675)]=[],this[r(987)+r(454)]=null,this[r(827)+r(1489)]=!1,this[r(1280)+r(972)]=e[r(378)],this[r(1274)+"Lock"]=!1,this[r(1274)+"ionTimeoutId"]=null,this[r(1223)+r(1315)+r(1598)]=null,this[r(921)+r(1634)+"Id"]=null,this._seqId=0,this[r(1173)]=!1,this[r(525)]="",this["_QoSMana"+r(688)]=null,this._cursorManager=null,this["_pingLos"+r(696)]=null,this[r(1227)+"ls"]=r(908),this[r(733)]=3,this.CONNECTING=0,this[r(1074)]=1,this[r(693)]=2,this[r(1626)]=g=>{let d=r;try{if(e[d(422)](e[d(1469)],e.ynXvX))Ts(this,g,[C0,A0,k0]);else return this._socket[d(1625)+"te"]}catch(b){let E=e[d(545)](de,d(421),{message:b[d(1460)],code:Ge[d(889)+"OR"],error:b});this["_dispatc"+d(674)+"ent"](E)}},this[r(1443)+"ge"]=async g=>{let d=r;if(o[d(1029)]===o.iUBbK){let{pingInterval:b,pingFrequency:E}=this[d(1805)];if((o[d(1321)]("hi",g[d(1347)])&&o.hYsXW(o[d(1393)],E)||o[d(1481)](o.uKNLh,E))&&(this[d(553)+d(1524)](),this[d(863)](o[d(672)],d(1020)),this[d(921)+d(1634)+"Id"]=setTimeout(this[d(1102)][d(1545)](this),b)),o[d(517)]("hi",g.data))return;try{o[d(1757)](Ts,this,g,[i0,r0,S0,E0,v0,s0])}catch(v){let L=o.tnnqB(de,o[d(800)],{message:v.message,code:Ge["MESSAGE_"+d(1319)],error:v});this[d(1028)+d(674)+d(604)](L)}}else{let b=this[d(673)][d(1238)+d(1690)](this._prefix);return _0x5d7817[d(516)](b||"{}")[_0x10cddf]}},this[r(630)]=g=>{let d=r,b=this._endpointManager?.[d(1095)+d(1188)+"es"](),E=this[d(987)+d(454)]?.["getCurre"+d(1124)+"nt"]();if(b&&!g.message){let v=d(689)+E+(d(1111)+"ax retri"+d(1485)+"ed");this._dispatchErrorEvent(e[d(1659)](de,d(421),{message:v,code:Ge[d(419)+d(862)+"R"],error:g}));return}this[d(1120)]&&this[d(1120)][d(1625)+"te"]===this.OPEN&&this["_disconn"+d(900)](),this[d(1028)+d(674)+"ent"](de(d(421),{message:g[d(1460)],code:Ge["NATIVE_E"+d(1156)],error:g}))},this[r(1784)]=async g=>{let d=r;this._clearTimer(),this[d(553)+d(1524)](),this["_removeW"+d(945)+"rs"](),this[d(1120)]=null,this["_connect"+d(1273)]=!1;let b=this[d(987)+d(454)]?.[d(1095)+d(1188)+"es"]();if(!b&&this[d(861)+d(664)]()&&!this[d(827)+d(1489)]){let E=this[d(987)+"tManager"]?.[d(1471)+d(1124)+"nt"](),v=this._options[d(1337)+"tInterce"+d(1228)](g[d(1330)],g[d(1760)]);this[d(1028)+d(579)+d(604)](pe(e[d(719)],{code:1006,reason:g[d(1760)]||"connecti"+d(1255)+d(578)+d(543)+d(775)+d(1491)+E,willReconnect:v})),v&&this._connect();return}if(e.PwJOT(1e3,g[d(1330)])&&this[d(827)+d(1489)]){this[d(1028)+"hCloseEv"+d(604)](pe(d(1529),{code:1e3,reason:e[d(586)]})),this[d(987)+d(454)]?.[d(591)+d(550)+d(1721)](),this[d(469)+d(696)]?.["resetCou"+d(1540)]();return}if(e[d(540)](1e3,g[d(1330)])&&b)if(e[d(446)](e[d(815)],e.TsCag)){let E=this["_endpoin"+d(454)]?.[d(1471)+d(1124)+"nt"](),v=g.reason;v||(v=await e.ozaqm(Ya,this[d(525)])),v="connecti"+d(1255)+d(1791)+v+(d(702)+d(882))+E+(", max retries re"+d(913)),this[d(1028)+d(579)+"ent"](e[d(383)](pe,d(1529),{code:g.code,reason:v}));let L="connect "+E+(" fail, m"+d(557)+"es reached");this[d(1028)+d(674)+d(604)](e[d(383)](de,"error",{message:L,code:Ge[d(419)+"IES_ERROR"]})),this[d(987)+"tManager"]?.[d(591)+d(550)+d(1721)](),this[d(469)+d(696)]?.[d(1793)+"nter"]();return}else return _0x68cc76&&_0x1dc3f0[d(1574)]===!0;if(e[d(1642)](1e3,g[d(1330)])&&!g[d(1760)])if(d(739)!==d(739))this[d(863)](d(1460),_0x500c1e),this[d(1314)+"e"]&&this[d(1314)+"e"](_0x17a44b);else{let E=this["_endpoin"+d(454)]?.getCurrentEndpoint();this[d(1028)+"hCloseEvent"](pe(e[d(719)],{code:g.code,reason:d(1761)+d(1255)+"d, unkno"+d(543)+d(775)+"ame: "+E})),this._endpointManager?.[d(591)+d(550)+d(1721)](),this[d(469)+d(696)]?.[d(1793)+d(1540)]();return}this[d(1028)+d(579)+d(604)](g),this[d(987)+"tManager"]?.[d(591)+d(550)+d(1721)](),this[d(469)+"sCounter"]?.["resetCou"+d(1540)]()},this[r(1684)]=null,this[r(905)]=null,this[r(1314)+"e"]=null,this[r(1390)]=null,this[r(1254)+r(453)]=null,this["onReceiv"+r(713)]=null,this["onStopIm"+r(645)+"yReconnect"]=null,this._handleOnLine=this[r(971)+r(1149)][r(1545)](this),this[r(971)+r(839)]=this[r(971)+r(839)][r(1545)](this),this["_handleP"+r(856)]=this["_handleP"+r(856)][r(1545)](this),this[r(876)+r(650)]=this[r(876)+r(650)][r(1545)](this),this[r(1805)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[r(1717)](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[r(439)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[r(1297)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:h}=t,m=Array[r(1762)](x)?x:r(1561)==typeof x?[x]:[];if(!m||e.arXFZ(0,m[r(1131)]))throw new Error("please provide v"+r(643));if(!e[r(1366)](Ja,h))throw new Error(e[r(1496)]);Object[r(412)](this[r(1805)],t),this._endpointManager=new Ds(m,this[r(1805)][r(1211)+"es"]),this[r(469)+"sCounter"]=new Xa(this[r(1805)][r(1580)+r(1572)]),this[r(1805)].automaticOpen&&(this[r(1173)]=!0,this[r(1274)]()),this[r(1805)][r(759)+r(1058)+r(428)]&&(this[r(1797)+"T"]||this[r(1731)+"X"]?this[r(1463)+r(407)+r(716)]():this[r(526)+"er"]&&this[r(1554)+r(1435)+r(1682)]())}["_handleO"+n(1149)](){let t=n;this[t(1805)]["disableA"+t(1799)+t(850)]||this[t(827)+t(1489)]||this["_handleR"+t(453)]()}[n(971)+n(839)](){let t=n;this[t(1619)+"WebSocket"]();let r=e[t(413)](ur,e[t(1302)],{message:e.kNZqj});this["onStopIm"+t(645)+t(450)+"ct"]&&this[t(1380)+"mediatel"+t(450)+"ct"](r)}[n(1554)+n(1435)+"Listener"](){let t=n;this[t(526)+"er"]&&window.addEventListener(e[t(1478)],this._handleOnLine),this[t(526)+"er"]&&window["addEvent"+t(1682)](e[t(700)],this["_handleO"+t(839)]),this[t(526)+"er"]&&window[t(1257)+t(1682)](e[t(1651)],this[t(876)+t(856)]),this[t(526)+"er"]&&window["addEvent"+t(1682)](e[t(1072)],this[t(876)+t(650)])}[n(1196)+n(1435)+n(1682)](){let t=n,r={khNBC:function(o,x){return o(x)},mtKtK:function(o,x){return e[D(723)](o,x)},HgwsE:function(o,x){return e[D(931)](o,x)}};e.exglI(e[t(1564)],e[t(1564)])?(this[t(526)+"er"]&&window[t(611)+t(1121)+"ner"](e[t(1478)],this[t(971)+t(1149)]),this[t(526)+"er"]&&window[t(611)+t(1121)+t(647)](t(670),this[t(971)+t(839)]),this[t(526)+"er"]&&window["removeEventListe"+t(647)](e.Jjlrg,this[t(876)+t(856)]),this[t(526)+"er"]&&window[t(611)+t(1121)+"ner"](e.JpdnM,this[t(876)+t(650)])):(_0x4341b2=PLUYxt[t(1486)](_0x191811,_0x4deff9),_0x4f0a03|=PLUYxt[t(523)](PLUYxt.HgwsE(127,_0x1b08ef),7))}[n(876)+n(856)](t){let r=n;!t[r(1722)+"d"]&&(this[r(526)+"er"]&&window[r(611)+r(1121)+r(647)]("pagehide",this[r(876)+"ageHide"]),this[r(526)+"er"]&&window["removeEv"+r(1121)+r(647)](e[r(1072)],this[r(876)+r(650)]),this[r(1529)]()),this[r(526)+"er"]&&window["removeEv"+r(1121)+r(647)](e.TkPFi,this["_handleO"+r(1149)]),this[r(526)+"er"]&&window[r(611)+"entListe"+r(647)](e[r(700)],this[r(971)+"ffLine"])}[n(876)+n(650)](t){let r=n;t.persisted&&(this[r(861)+r(664)]()&&(!this._ws||this[r(1120)][r(1625)+"te"]!==this[r(1074)]||e[r(1701)](this[r(1120)][r(1625)+"te"],this[r(1542)+"NG"]))&&this[r(971)+r(1149)](),this[r(526)+"er"]&&window[r(1257)+"Listener"](e.TkPFi,this[r(971)+"nLine"]),this[r(526)+"er"]&&window[r(1257)+r(1682)](r(670),this["_handleO"+r(839)]))}async[n(997)+"eUrl"](t){let r=n,o={mtVUF:function(Re,Ne,Us){return Re(Ne,Us)},lBJZH:function(Re,Ne){return e[D(405)](Re,Ne)}},{fpID:x,deviceID:h,bddID:m,ttwID:g,accessKey:d,aID:b,customParams:E={},enableAutoAck:v,enableQoS:L,QoSLevel:N,env:z}=this[r(1805)],me,j,wr;if(this[r(526)+"er"]||this[r(1731)+"X"]||this[r(1797)+"T"])if(e[r(532)](e[r(652)],e[r(414)])){let{value:Re,offset:Ne}=xADmOt[r(1603)](_0x56cfa9,_0xe9ef8c,_0x38cb2b);_0x11d94f=Ne,_0x44de01=xADmOt.lBJZH(_0x40505a<<8,0),_0x33375a+=Re}else me=location&&e[r(1205)](e[r(844)],location.protocol)?e[r(1033)]:e[r(1298)],j=t[r(1042)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),wr=/^wss(.*:\/\/)/.test(t)?t:""+me+j;else me=e[r(1033)],j=t.replace(/(^http)((?:[s]*:\/\/))/,""),wr=/(^ws)((?:[s]*:\/\/))/[r(541)](j)?j:""+me+j;let qs=m?e[r(1201)]:g?r(1419):"device_id",Fs=m||g||h;if(e[r(1379)](!Fs,!qs))throw new Error(e.iRRId);let I0=e[r(881)](e[r(612)],typeof E)?await E():E,D0=z?e.zvJSL($a,z[r(980)],z[r(1374)]):{},_r=Object[r(412)]({device_platform:e[r(866)],version_code:"fws_1.0.0",access_key:d,fpid:x,aid:b,[qs]:Fs,xsack:v?1:0,xaack:v?1:0,xsqos:L?1:0,qos_level:L?N:void 0,qos_sdk_version:2,...D0},I0),T0=Object[r(1425)](_r)[r(1385)]((Re,Ne)=>_r[Ne]!==void 0?""+Re+(Re?"&":"?")+Ne+"="+_r[Ne]:Re,"");return wr+r(1500)+T0}async[n(1274)](){let t=n,r={wkwOm:function(o,x,h){return e[D(1306)](o,x,h)},REuml:e[t(1302)],KlOLD:e.kNZqj};if(e[t(718)](t(1233),e[t(637)]))return this[t(673)]["clearSto"+t(799)]();if(this[t(1274)+"Lock"]||this._readyClosed)return;this[t(1274)+t(1273)]=!0;try{let o=this[t(987)+t(454)]?.[t(810)+t(970)+t(1320)+t(1213)+"tries"](),{timeoutInterval:x}=this[t(1805)];if(o)if(t(1621)!==e.cOhbm){this[t(1619)+t(384)+"t"]();let m=kcflcC[t(1675)](_0x19e441,kcflcC[t(711)],{message:kcflcC[t(1647)]});this[t(1380)+t(645)+t(450)+"ct"]&&this["onStopIm"+t(645)+t(450)+"ct"](m)}else{let m=this[t(987)+t(454)]?.[t(1471)+t(1124)+"nt"](),g=this["_endpoin"+t(454)]?.[t(680)+t(720)+t(1090)+t(1098)+t(409)](),d=this[t(987)+t(454)]?.[t(1471)+t(1124)+t(1232)+t(429)]();if(g){let b=t(689)+m+(t(1300)+t(472)+t(1645)+"ached, w"+t(1429)+t(632)+t(788))+g+(t(1105)+"y"),E=e.faesx(de,"error",{message:b,code:Ge[t(419)+t(862)+"R"]});this._debug(b),this[t(1028)+t(674)+t(604)](E),this[t(525)]=await this[t(997)+t(1260)](g),this[t(729)](t(689)+g+" "+d+t(1367)),this[t(609)+t(945)+"rs"]()}else{let b=t(689)+m+(t(1300)+t(472)+t(1645)+t(913));this[t(729)](b),this[t(1028)+t(674)+t(604)](e[t(724)](de,e[t(598)],{message:b,code:Ge["MAX_RETR"+t(862)+"R"]}));return}}else{let m=this[t(987)+t(454)]?.[t(1471)+t(1124)+t(1187)+t(910)](),g=this[t(987)+t(454)]?.[t(1471)+t(1124)+"ntTriesC"+t(429)]();this[t(525)]=await this[t(997)+"eUrl"](e[t(1724)](m,"")),this._debug("connect "+m+" "+g+t(1367)),this["_removeW"+t(945)+"rs"]()}if(this._isInit)this[t(1173)]=!1;else{let m=e[t(932)](ur,t(1337)+"t",{message:e[t(393)]});this["onStartR"+t(453)]&&this.onStartReconnect(m)}let h=this["_endpoin"+t(454)]?.[t(1471)+"ntEndpoi"+t(1232)+t(429)]()||0;e[t(1711)](h,1)&&await this[t(1667)](e[t(1335)](h,1)),this[t(729)]("connecti"+t(1097)+this[t(525)]+(t(1596)+t(816))+this[t(1227)+"ls"]),this._ws=e[t(1707)](Wa,{url:this[t(525)],protocols:[this._protocols],headers:this[t(1805)][t(774)+t(1361)+"s"]["customHt"+t(883)]},this[t(1805)].ws),(this[t(526)+"er"]||this[t(1345)+"r"])&&this[t(1120)]&&(this[t(1120)][t(897)+"pe"]=this[t(1280)+"ype"]),this[t(1790)+t(1066)](),this[t(1274)+t(1174)+t(773)]=e.xOzPb(setTimeout,this[t(1305)+"ut"][t(1545)](this),x)}catch(o){throw this[t(1274)+t(1273)]=!1,o}}[n(1189)+n(1357)](){let t=n,r={uwIzV:function(o,x){return e[D(1768)](o,x)},rIGVt:function(o,x){return e[D(884)](o,x)}};if(e[t(1798)]===e[t(1798)])clearTimeout(this["_connect"+t(1174)+t(773)]),this[t(1274)+t(1174)+"utId"]=null;else{let o=0,x=0,h;do h=ApwiNW.uwIzV(_0x5dca98,_0x58b6b4),o<32&&(x|=ApwiNW[t(592)](127&h,o)),o+=7;while(128&h);return x}}[n(553)+n(1524)](){let t=n;if(e[t(520)](e[t(451)],e[t(1350)])){e[t(1292)](_0x5a4676,_0x126e62,42);let r=e[t(427)](_0x59430f);e[t(489)](_0x58057a,_0x376f68,r),e[t(899)](_0x2d4489,_0x261471,r.limit),_0x3b2f81(_0x462365,r),e[t(1573)](_0x239871,r)}else e[t(857)](clearTimeout,this[t(921)+t(1634)+"Id"]),e.ByczE(clearTimeout,this[t(1223)+t(1315)+t(1598)]),this["_pingPon"+t(1634)+"Id"]=null,this[t(1223)+t(1315)+t(1598)]=null}[n(729)](...t){let r=n;this[r(1805)][r(657)]&&console.log[r(1222)](console,[e[r(846)],...t])}[n(879)+n(1632)+"e"](t){let r=n,{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:h}=this[r(1805)],m=o*Math.pow(h,e[r(1226)](t,1));return m>x?x:m}[n(1102)](){let t=n;if(this[t(1120)]&&e[t(873)](this[t(1120)].readyState,this.CONNECTING)){this._clearPingTimer(),this["_pingPon"+t(1634)+"Id"]=e.NJwpg(setTimeout,this[t(1102)][t(1545)](this),this._options[t(580)+t(1579)]);return}if(!this[t(1120)]||e[t(785)](this[t(1120)].readyState,this[t(1074)]))return void this["_handleR"+t(453)]();this[t(1120)]&&this[t(1120)].send("hi"),this[t(1223)+t(1315)+t(1598)]=setTimeout(this[t(1294)+t(453)+"Timeout"][t(1545)](this),this[t(1805)][t(1371)+t(1182)+t(1544)])}[n(1294)+n(453)+n(538)](){let t=n;this[t(469)+"sCounter"]?.[t(1802)](),this.emit(t(804)+t(1509)+"t",t(1437)),this[t(469)+t(696)]?.[t(1095)+t(953)+"nt"]()?this[t(1294)+t(453)]():this[t(1102)]()}[n(861)+n(664)](){let t=n;return this[t(1797)+"T"]||this._isMiniWX?this[t(1633)+t(1177)+t(1014)]:(this[t(526)+"er"]||this[t(1345)+"r"])&&this[t(1805)][t(759)+"tworkChanged"]?navigator[t(1045)]:!0}[n(1294)+"econnect"](){let t=n;!this[t(861)+t(664)]()||this["_readyCl"+t(1489)]||(this[t(987)+t(454)]?.[t(591)+t(550)+t(1721)](),this[t(469)+t(696)]?.[t(1793)+t(1540)](),this._ws?this[t(955)+t(900)](1001,e[t(576)],!0):this[t(1274)]())}["_onPageN"+n(407)+n(716)](){let t=n;this[t(1797)+"T"]?tt["onNetwor"+t(481)+"hange"](({isConnected:r})=>{let o=t;this["_miniNav"+o(1177)+o(1014)]=r,r?this[o(971)+"nLine"]():this[o(971)+o(839)]()}):this._isMiniWX&&wx[t(475)+t(481)+"hange"](({isConnected:r})=>{let o=t;this[o(1633)+o(1177)+o(1014)]=r,r?this[o(971)+o(1149)]():this[o(971)+"ffLine"]()})}[n(1667)](t){let r={LuCAm:function(o,x,h){return e[D(1104)](o,x,h)}};return new Promise(o=>{let x=D;r.LuCAm(setTimeout,o,this[x(879)+x(1632)+"e"](t))})}[n(955)+n(900)](t=1e3,r="",o=!1){let x=n;this._ws&&this[x(1619)+x(384)+"t"](t,r,o)}[n(1305)+"ut"](){let t=n,r=this[t(987)+t(454)]?.getCurrentEndpoint();this[t(729)](t(689)+r+t(1300)),this[t(955)+"ect"](1001,e[t(1417)],!0)}_sendAck(t){let r=n,o=e[r(458)](xr,t);this[r(1120)]&&this[r(1120)][r(1625)+"te"]===this.OPEN&&(this[r(1120)]&&this._ws[r(1639)](o),this[r(729)](r(1422),t))}[n(609)+n(945)+"rs"](){let t=n;if(e[t(1427)](t(1277),e.sgAtm)){if(!this[t(1120)])return;this[t(1120)][t(611)+"entListe"+t(647)](e[t(663)],this[t(1626)]),this[t(1120)][t(611)+t(1121)+t(647)](t(1529),this[t(1784)]),this[t(1120)][t(611)+t(1121)+t(647)](t(1460),this[t(1443)+"ge"]),this[t(1120)]["removeEv"+t(1121)+t(647)](e[t(598)],this[t(630)])}else this[t(871)+t(1628)+t(1389)+"t"]=0}[n(1790)+n(1066)](){let t=n;if(e[t(1428)](e.qQtEq,t(480))){if(!this[t(1120)])return;this[t(1120)][t(1257)+"Listener"](e[t(663)],this._onOpen),this[t(1120)].addEventListener(t(1529),this[t(1784)]),this[t(1120)][t(1257)+"Listener"](t(1460),this._onMessage),this._ws[t(1257)+t(1682)](e[t(598)],this._onError)}else{let{initReconnectInterval:r,maxReconnectInterval:o,reconnectIntervalGrowFactor:x}=this[t(1805)],h=e[t(691)](r,_0x2b1528[t(459)](x,_0x4a8fe8-1));return e[t(1677)](h,o)?o:h}}[n(1106)+n(956)](t=1e3,r=""){let o=n;if(e[o(1741)](e[o(1351)],e[o(1351)]))return this[o(1120)]?this._ws.url:this._url;try{this[o(1120)]&&this[o(1120)][o(1529)](t,r)}catch{}}[n(1619)+n(384)+"t"](t=1e3,r="",o=!1){let x=n;if(this[x(553)+x(1524)](),this[x(1189)+x(1357)](),this[x(609)+x(945)+"rs"](),this[x(1106)+x(956)](1e3,r),this[x(1274)+x(1273)]=!1,o&&this[x(861)+x(664)]()&&!this[x(827)+"osed"]){if(this[x(987)+x(454)]?.checkReachMaxTries()){let m=this["_endpoin"+x(454)]?.[x(1471)+x(1124)+"nt"]();this[x(1028)+x(579)+x(604)](e[x(738)](pe,x(1529),{code:1006,reason:x(689)+m+(x(1300)+x(472)+x(1645)+x(913)),wasClean:!0}))}else{let m=this._options[x(1337)+x(1142)+"ptor"](t,r);this[x(1028)+x(579)+x(604)](e[x(820)](pe,e[x(719)],{code:t,reason:r,wasClean:!0,willReconnect:m})),m&&this[x(1274)]()}return}this[x(861)+x(664)]()||this[x(827)+x(1489)]?this[x(1028)+"hCloseEv"+x(604)](e.FbakX(pe,e.pZQHG,{code:t,reason:e[x(586)]})):this["_dispatc"+x(579)+x(604)](e[x(745)](pe,e.pZQHG,{code:1006,reason:e[x(631)]})),this[x(1120)]=null,this[x(987)+x(454)]?.["resetEnd"+x(550)+x(1721)](),this[x(469)+x(696)]?.[x(1793)+x(1540)]()}[n(1028)+"hOpenEvent"](t){let r=n;this.emit(e.vNqIE,t),this.onopen&&this[r(1390)](t)}[n(1028)+"hMessage"+n(712)](t){let r=n;this[r(863)](e[r(994)],t),this[r(1314)+"e"]&&this[r(1314)+"e"](t)}[n(1028)+n(1742)+n(1216)](t){let r=n;this.emit(e[r(621)],t),this[r(966)+"eAck"]&&this["onReceiv"+r(713)](t)}[n(1028)+n(674)+n(604)](t){let r=n;this[r(863)](e[r(598)],t),this[r(905)]&&this[r(905)](t)}[n(1028)+"hCloseEv"+n(604)](t){let r=n;this.emit(e[r(719)],t),this[r(1684)]&&this[r(1684)](t)}get binaryType(){let t=n;return this[t(1120)]?this[t(1120)].binaryType:this[t(1280)+"ype"]}set[n(897)+"pe"](t){let r=n;this._binaryType=t,this[r(1120)]&&(this._ws[r(897)+"pe"]=t)}get[n(1031)+"nt"](){let t=n;return this[t(987)+"tManager"]?.["getCurrentEndpointTriesC"+t(429)]()||0}get[n(1050)+"Amount"](){let t=n,r=this[t(1520)+"Queue"].reduce((o,x)=>{let h=t;return e[h(1035)](e.Eolvk,e[h(1663)])?(this[h(871)+h(1628)+h(1389)+"t"]++,this[h(1471)+h(1124)+"nt"]()):(o+=x&&x[h(1685)+"th"]||0,o)},0);return e[t(795)](r,this[t(1120)]?this[t(1120)][t(1050)+t(1387)]:0)}get[n(1265)+"ns"](){let t=n;return this[t(1120)]?this[t(1120)][t(1265)+"ns"]:""}get[n(763)](){let t=n;return this[t(1120)]?this[t(1120)].protocol:""}get[n(1625)+"te"](){let t=n;return this[t(1120)]?this[t(1120)][t(1625)+"te"]:this[t(1805)]["automati"+t(891)]?this.CONNECTING:this.CLOSED}get[n(1450)](){let t=n;return this[t(1120)]?this[t(1120)][t(1450)]:this[t(525)]}close(t=1e3,r){let o=n;if(this[o(827)+o(1489)]=!0,this[o(1189)+o(1357)](),this[o(553)+o(1524)](),this[o(1196)+o(1435)+o(1682)](),this[o(1147)+o(688)]?.[o(1079)](),!this[o(1120)])return void this[o(729)](e.AyLPz);if(e[o(520)](this[o(1120)].readyState,this.CLOSED)||e[o(508)](this._ws[o(1625)+"te"],this[o(693)]))return void this._debug(e[o(1557)]);this[o(1619)+o(384)+"t"](t,r)}async send(t,r){let o=n;if(e[o(1197)](null,t))throw new Error(e[o(762)]);o(389)==typeof t&&(t=JSON[o(1342)+"y"](t)),e[o(776)]!=typeof t&&!e[o(452)](t,ArrayBuffer)&&!(t[o(400)]&&t[o(400)]instanceof ArrayBuffer)&&(t=JSON[o(1342)+"y"](t));let x=await e[o(684)](Ls,t),h=e[o(684)](Va,t),{method:m=0,service:g=this._options[o(974)],logID:d=this[o(1805)][o(1782)+o(623)](),headers:b=this[o(1805)][o(1313)],payloadEncoding:E=this[o(1805)][o(619)+o(922)],payloadType:v=this[o(1805)][o(1004)+o(972)],logIDNew:L=this[o(1805)]["logIDNew"+o(1204)]["enableAu"+o(1508)+"teLogIDNew"]?e[o(667)](a,this[o(1805)][o(1571)+o(1204)].userIp):""}=e[o(1194)](r,{});if(!g)throw new Error(o(1456)+o(767)+o(1026)+"ervice");let N={SeqID:q[o(1584)+"er"](this[o(1734)]++),LogID:q[o(1584)+"er"](d),service:g,method:m,headers:b,payloadEncoding:e[o(510)](E,Object)?E.encoding?E[o(561)]:"":E,payloadType:e[o(1416)](v,Object)?v[o(1432)]?v[o(1432)]:h:v||h,payload:x,LogIDNew:L},z=e.CDyft(xr,N);return this[o(1120)]&&e[o(807)](this[o(1120)][o(1625)+"te"],this[o(1074)])?(this[o(1120)]&&this[o(1120)][o(1639)](z),this[o(729)](e[o(1484)],N)):this[o(1520)+o(675)].length<this[o(1805)]["maxMessa"+o(646)+"ength"]?(this[o(1520)+o(675)].push(z),this[o(729)](e.JZAss,N)):(this[o(1520)+o(675)][o(784)](),this[o(1520)+o(675)][o(1381)](z)),{seqID:this[o(1734)],logID:d,logIDNew:L}}async[n(1337)+"t"](t){let r=n,{url:o}=e[r(1452)](t,{}),x=Array[r(1762)](o)?o:e[r(776)]==typeof o?[o]:[];t&&Object[r(412)](this[r(1805)],t),x&&x[r(1131)]?this[r(987)+r(454)]=new Ds(x,this[r(1805)].maxRetries):this["_endpoin"+r(454)]?.[r(591)+r(550)+"fig"](),this["_pingLos"+r(696)]?.["resetCou"+r(1540)](this[r(1805)][r(1580)+"Count"]),this[r(827)+"osed"]=!1,this[r(1120)]&&e.PwJOT(this[r(1120)].readyState,this[r(733)])?this[r(955)+r(900)](1e3,e[r(501)],!0):(this[r(1173)]=!0,this[r(1274)]())}async[n(1612)](){let t=n;if(!this[t(1274)+t(1273)]){let r="2|0|1|4|3"[t(542)]("|"),o=0;for(;;){switch(r[o++]){case"0":this[t(469)+t(696)]?.resetCounter();continue;case"1":this[t(827)+t(1489)]=!1;continue;case"2":this._endpointManager?.["resetEnd"+t(550)+"fig"]();continue;case"3":this[t(1274)]();continue;case"4":this[t(1173)]=!0;continue}break}}}[n(1257)+n(1682)](t,r){this.on(t,r)}["dispatch"+n(712)](t){let r=n,{type:o}=t;this[r(863)](o,t)}[n(611)+n(1121)+"ner"](t,r){this[n(1130)](t,r)}[n(1279)](){let t=n,r={fLrRU:function(o,x){return e[D(825)](o,x)},EWpAg:function(o,x){return e[D(1085)](o,x)},UGCGk:"0000",RBveG:t(1718),RXPNr:function(o,x){return e[t(1352)](o,x)},PatYX:e.QXMAx,kRSnc:"success",vfTJX:e[t(896)],rbepU:t(804)+"e_timeout",GviBQ:function(o,x){return e[t(569)](o,x)},gjhaJ:e[t(546)]};return new Promise((o,x)=>{let h=t;this[h(553)+h(1524)](),this[h(921)+"gTimeoutId"]=e[h(1073)](setTimeout,this[h(1102)][h(1545)](this),this[h(1805)]["pingInte"+h(1579)]);let m=()=>{let d=h,b={qDvWq:function(E,v){return r[D(988)](E,v)},mleXY:function(E,v){return r.EWpAg(E,v)},Xasnf:r[d(1034)],GVGzW:r[d(1728)]};if(r[d(524)](r.PatYX,r[d(1420)]))o(r[d(782)]),this[d(1130)](r[d(1117)],m),this[d(1130)](r[d(486)],g);else{let E=_0x3b2e49[d(542)](/\./).map(N=>_0x1ecd35(N)),v=[];return v[0]=HZnkuA[d(1165)](_0x12fdbc,HZnkuA[d(1376)](E[0],E[1])),v[1]=HZnkuA[d(1165)](_0x25621a,E[2]+E[3]),[HZnkuA[d(973)],HZnkuA[d(973)],HZnkuA[d(973)],HZnkuA[d(973)],HZnkuA[d(973)],HZnkuA[d(1169)],v[0],v[1]][d(874)]("")}},g=()=>{let d=h;r.GviBQ(x,r[d(1251)]),this[d(1130)](r[d(1117)],m),this[d(1130)](r.rbepU,g)};this.on(h(804)+"e_success",m),this.on(e.UErtm,g),this[h(1102)]()})}}})(),Q[A(1230)+A(406)]=X.CustomCloseEvent,Q[A(617)+A(1061)]=X[A(617)+A(1061)],Q[A(456)+"e"]=X[A(456)+"e"],Q.Event=X[A(712)],Q[A(445)]=X[A(445)],Q[A(1804)+A(1209)+"vent"]=X[A(1804)+"MessageE"+A(707)],Q["MessageE"+A(707)]=X[A(1209)+A(707)],Q[A(1179)+"t"]=X.OpenEvent,Q["Reconnec"+A(902)]=X["Reconnec"+A(902)],Q.createCloseEvent=X[A(1704)+"oseEvent"],Q[A(1494)+A(1061)]=X["createEr"+A(1061)],Q[A(468)+A(1712)+"nt"]=X["createMe"+A(1712)+"nt"],Q.createOpenEvent=X.createOpenEvent,Q[A(1083)+"connectE"+A(707)]=X[A(1083)+"connectE"+A(707)],Q[A(1543)+"rame"]=X["decodedF"+A(717)],Q[A(912)+A(1112)]=X[A(912)+A(1112)];for(Rn in X)[A(1230)+"oseEvent",A(617)+A(1061),"ErrorCode","Event",A(445),"FrontierMessageE"+A(707),A(1209)+"vent","OpenEvent",A(1290)+A(902),A(1704)+A(406),A(1494)+A(1061),A(468)+"ssageEvent",A(867)+A(434),A(1083)+"connectE"+A(707),A(1543)+A(717),A(912)+A(1112)].indexOf(Rn)===-1&&(Q[Rn]=X[Rn]);function D(n,e){n=n-374;let i=zn(),a=i[n];if(D.gzrMot===void 0){var c=function(p){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",y="",_="";for(let C=0,P,I,R=0;I=p.charAt(R++);~I&&(P=C%4?P*64+I:I,C++%4)?y+=String.fromCharCode(255&P>>(-2*C&6)):0)I=w.indexOf(I);for(let C=0,P=y.length;C<P;C++)_+="%"+("00"+y.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(_)};D.tYuXGq=c,D.SPNteH={},D.gzrMot=!0}let u=i[0],f=n+u,l=D.SPNteH[f];return l?a=l:(a=D.tYuXGq(a),D.SPNteH[f]=a),a}var Rn;function zn(){let n=["yK9uuxK","y3vYCMvUDeK","x29UtwvZC2e","sffRwgG","DgLTzw91DcW","CgTdBgq","C25gCe4","mdaWma","Ae91sNq","DxjS","y0DhwgG","C3HkB2G","rMnsz2m","BLHNvwK","v1beCxq","CgXLyxnLiha","DMvYC2LVBG","v1jRt24","z3z2q3q","BwvZC2fNzq","Dfbmz0K","zKP5vhq","x29UugfNzu4","q1rhr1O","Dfnoqui","Dgv4Dc9WBge","A2fmyuC","DgvwEge","quTHq1O","BwDHze8","z2v0q3vYCMu","BxnN","q3j6Dum","AhbWBgy","vK1zt1e","zMLSzw5HBwu","BgLUzw5V","vgTqrMK","Bwv0Ag9K","tK5vzxq","AfLZwfC","qM1yuMi","Dgvtq28","shnuB3a","zxmGCMvHy2G","A2HoqKm","qu1JzLu","DNfizKe","B3nLza","twr3suO","yw1LoIa","DuPhsuW","CvHwBLa","y3jLyxrLrxi","s3nADge","ChHeDee","s2DJBfG","D3jPDgvvAw4","Evfctxe","l3DZl3yY","t0PeqwC","AwXAqvG","DxDqC0S","x2LUAxrqCM8","tK52qLu","r09kze8","wfvvwLO","Dg9hzw5LCMe","zv90Aw1LB3u","Ee96ugi","BwH4zxG","EgDNzeW","Dhj1y3rVCIa","qKvJteq","yNzNEw4","Chv0","x19LC01Vzhu","yxDMEva","q25NzeS","x21LC3nHz2u","Cg9W","zhbzu3a","zLr2svq","BMDuAw1LCG","DfnhDxK","z3jouw0","B0X4ru0","Aw5KzxHpzG","y2XVC2u","zMvY","yMfSu2nVCgu","zMLfzfK","CNPeC1O","Bxzovu4","mJiWmtuYohHQwxvPzG","Aw5KzxG","wNjRzM4","C2nYAxb0","r0TZA0i","BNrLCG","AwPWDw0","q09otKvdveK","zgvJB2rLzey","DMfS","yMLUza","BfzOuM0","z05It3a","qNPMzg8","BM93","nxW0Fdj8mxW","t0LkCfu","vujwv0e","zK1TAKy","x2LUAxrhBg8","z2v0qwXSs2u","B2XKvMvYC2K","rerzwMS","Bg1zDe0","tMfTzq","ign1CNnVCIa","C3rYAw5N","B2fNAuW","v3beyvu","wujUBvm","yMXuveK","Ec1TC2CTy3u","ANvJsei","ENrMC08","y0nID0m","CKfIvhm","Bg9NsurozxC","q291BNq","C0XzuNm","AxnmB25N","zMzLCG","zuPJBva","B3bLBG","u0XNBgm","CNzHBa","CgLUz0XVC3m","vgvuwfu","wxLPCwy","BwLZzq","zNjVBu51Bwi","Ahr0Chm6","tM9eAwy","B3jLtMfTzxm","rMD3t1i","u0nOq2e","nxW0","twvxteq","yM1Pz2y","yKvRs2W","BffXqvO","C29YDa","ihbYB3rVy28","qwfQA3a","DeLK","rgziEeS","B2nRzxrtDwm","DeXcthK","tgHituW","Bxrwvuy","tg1IDgS","zwnus2W","DuzpAKi","DeHIA3y","zgvMAw5Luhi","whzIAMC","zM9YrwfJAa","twrOqKC","y29UBMvJDa","DxbKyxrLq3u","zgjgt2u","B2Tey0S","sfnJyNu","C2Pdrxi","z0P1sMy","x2rLC3rYB3K","DKv2Aha","rMjrEue","ywXSq3vYC28","CuzPC2K","mtHjAur4v0K","CMvHzhLtDge","x29Ut3bLBG","ywDL","BMrWB2LUDfq","z2u6ia","uw9kuNq","rw1MquG","CNzHBfzHBhu","x21PBMLoyxy","z1rPBwvVDxq","s29euvK","C29Tzq","ywnRtxnNswq","v0DbALu","C2vUza","uMvezMO","yMTjsu4","DxbAA2G","y29UBMvJDfm","nda5ntjYvLfuu0W","DhjPzxmGCMu","x2n1CNnVCK4","s2Xpteq","Aw9Ul2PZB24","C2vYDMvYvgK","svHkrNi","sMPSCMC","tNfvvu8","Dg9VigXHCMC","B25dBg9Zzq","wKvpDKy","Aw5Lza","DMvxyuy","sKHkCMm","u1LYCLO","vwXTCeq","CurNyum","Dw5KzwzPBMu","rw9SDMS","uwLqvg8","EKPdAKS","t0Pcz0C","x3DHAxq","BezSDxnO","Dg9mB3DLCKm","yMPQuLO","B0XAALa","D3m6lY8","y2XVC2uSihC","mJq3mZu1meDrBuLyAq","D2T3t20","AxnszwfKEq","ugHRz1a","C21MwLO","rKLqEM0","DMflBgy","zcbLCNjVCI4","tgLZDgvUzxi","EKz3CfC","B25JBg9Zzq","yNL0zuXLBMC","BeHHBMrSzxi","zNjVBuj5Dgu","tKzMuLC","Aw5PDcbrB1m","z2vtEw5J","A1j6rwS","wNrbCxq","C2DeAwG","C2v0zgi","CuvzwLi","EsbJBg9Zzwq","sMjby24","B09sEwC","rMzVtMm","yNL0zu9MzNm","y3rxvfG","zgvSzxrLrge","m3WW","y3jLyxrLq2W","se1zrLK","AgvHzgvY","B2TOy24","jMPZy2fSBgi","yM9KEq","DeHmuuG","ExfKDxa","C3nHz2vfDMu","zNjVBuHHC2G","CxrkBhe","D2j4D1a","x3bHDgHlzxK","CwXIAMW","zMzMzG","zxfhs2q","CxzTwe0","zMLN","CgvYC2LZDgu","u3LXC2O","s0nyrKu","q09oveLovuu","twLZC2LUzYa","B3bLCNr5","uKj2zuC","AuHmu3G","B2jQzwn0u3q","x2LZtwLUAvC","mNWZFdf8mhW","C2XPy2u","x3nLCuLK","yMXVy2TLza","Bvzqt2m","ywnRpwzYB24","zxj2AwnL","CeXbvMG","vNjZr1i","B0HuBMi","AefJA01LC3m","yxbWBgLJyxq","B0zMu1e","zMLSDgvY","svzYtKS","vgfN","x2LUAxq","C2vYDMLJzs0","CefgwuS","tLfwCwm","yvHyBKm","Aw50zwDLCIa","qwjVCNrfCNi","quXeuKu","sxzMBLO","zw1AtgS","v1DOD04","AgfUz2u","CMvHC29U","y29UBMvJDgK","AxnbCNjHEq","C0jf","nxWYFdD8mta","rwnpywO","AKPczwe","z0H0sMi","y3PwtNO","wM9rq3G","Dgv4Dc9Qyxy","AgfZ","DgHhD0u","zMXVB3i","wwHKtLC","B2zMC2v0","C2DPza","D0Xzwvm","qLHZvuK","y2XLyxjtDg8","ywXSzwqGBxu","zg9Uzq","Bg9Nsurhzw4","ywjVCNq","x29Uq2XVC2u","r3D0zxa","rKreBfm","rM9vvgG","uLjhDfy","u0LRC08","x2fKzfDZtgK","zcWG","ve9Iq1y","CMvZzxrdB3u","rgTps3G","BvrJsgy","y3vYC29Yx24","x2LZtwLUAvq","B0L6Dg8","DxrVuMvJB24","AunlCgC","y3jlBgu","ywrKq291BNq","ugH1CMK","rNjVBNrPzxi","x29WDgLVBNm","B2PICvq","rvPLyvy","wgPsvve","v21hBue","r25pCfm","AxnFywnR","EfndBKy","CMvJzxzPzwq","v1PyAMq","tM1lBwO","v2vIu29JA2u","AxnAzxjV","AxnrB1nby2S","CNDoyLK","zxjYtM8","BNvTyMvY","u1DRq3q","vwLAqu0","A1nJCK4","v29mrKS","qK5Hse8","rNn1sg0","uxPPEMe","B3jRzxjhBg8","wefvuvy","y25pEfy","yNvMzMvY","uNvYCeq","vxjRENu","whjZu3K","DxbNCMfKzw4","BLfAwgK","B3nLrxzLBNq","zxrxB3jRq2G","ChjVDg90Exa","Dw50","zxjFBxnNAwq","CNnVCKzPBgu","yxnZAwDU","ExHUvMu","zejkse8","DgHLBG","z2LwzM4","DgfYz2v0","EfDMywG","tufyx1jfvfi","zK96zfm","zxjYB3i","wffxCu4","C3jJ","vNH6svy","AKL0swC","sLDnsxq","AMLIr04","BMDLza","B3vUDa","x2zVCM1HDeu","yw5ZzM9YBvq","rKTrDvG","sePsAvG","zw5fDMvUDa","sezSwLO","tKDFrvjst1i","B3bLBKrc","Dw5RBM93BIa","wMzZwhm","zw5KCg9PBNq","ywXS","thHOyMK","thfoDMS","mxWZFdj8mhW","rLDt","yu5KCKC","A251zNe","wMjAqwy","EMXuy1q","EvjLy29UBMu","qunJEfK","CePVyKi","zwnVBM5Ly3q","De1HBMfNzxi","v1Luq24","rxjYB3jdB2q","u2vXsuq","BgPIBxi","Cg93","oxW2FdH8m3W","zxjFywnRx20","DLjxs3q","DNHNzwu","mtb8nNW5FdC","ihzHBgLKigq","uu9UA2q","q1rMD2G","y3jLyxrLtwu","x3bPBMDmB3m","D3jPDgu","rwTdB3y","lcbTyxGGCMu","CvjmrKy","B3bLBIa","B25ozxr3B3i","qwrMB1a","u3PyEKC","BgLTAxq","BhDzt2K","tu1suxC","A1n0yxr1C0m","wLLPrfy","AgrRC0e","B2nRzxq","svzwBhe","CMjLCfu","zxjYtxnN","AwXK","wfjtC0K","Cw9Z","y2fSBa","x0vysvnu","A2v0ignVBNm","wMnyvMG","v053sgm","sgzKsvu","zwv4Cwq","ExLgr2q","v3vAD3i","DKrMAMu","CeLTrwq","Dg9Y","yw1Lu3bHy2u","uKXlvfK","AKfZELe","AxnrB1nnzxm","vgjszNC","uMjuD2e","zxLlr2y","r21dswq","yxKSig5LDhC","EerlvwG","t2Hkvui","BhjfEKe","q3rgChK","CgfYC2u","ExvZB3a","zgvSzxrL","rLjptLrjrvi","u01wANG","ALfiBeO","qxPZrhe","BxrlDeS","uLHqtNi","x3vYBa","x2LZqNjVD3m","BM9Uzv9UB24","Au9Xuwi","ywrK","A3fUq3O","Dwv0uLO","wxPhzNu","DK1oqK4","y29UC3rYDwm","wejbDKy","tNrxANq","whjxwg4","vgLTzw91Da","AMXPvLe","wgfUBhu","DgvZDa","C3bSAxq","D24GCMvHC28","C3rHCNq","C0v5Exm","uNLAyLG","yMrSzw4","seXlvxy","vNvzrwe","Cg9PBNrdB24","BgXbvgS","ywzL","x2nSzwfYugK","su5tvefova","B1fSyuC","CMvXDwLYzwq","yxGGCMv0CMK","BK9LAei","uen2vNa","C1j0qNe","zw5JB2rPBMC","Buj0AKq","C2fNzq","quXm","BMv4DcGPigm","EwTkAha","C2v0q3vYC28","uvzlr0G","u1bsBNe","CYbHBhjLywq","vfPMrxG","uMvHzcbWyxm","CNbpvw0","wLrwt1i","v2LUzg93","wwLUwvy","CffYCMK","zcWGDw5RBM8","AenSB3nLrxy","CgLUz0LUDgu","vePNwLm","B3jRig9MzMW","vw5PBxbSzw0","DNrir0y","m3WY","seXIrey","AufUsLa","DhjPBq","EenvtKG","zM9Yy2u","CMvZzxrfBMq","CKLhvNq","DMfSDwvZ","zw5HyMXLvhi","wMDjDxO","ywWGy3vYC28","tKfusvzfx0u","rxnOtxi","uLrODha","DgXVDwq","Ae1LC3nHz2u","tuTWs24","tK1wDe4","zw50","DcbVzIbYyw4","ug9quhC","B29sCeu","A3fruuW","x3jLBw92zvC","BMvLzf9Hy2S","CMvTB3zLrxy","BxfQAwq","B2nRzxrgywK","C2v0u3rVCMe","AxmGDw5Kzwy","thHzqwG","q3vZDg9Trxi","x2rItMfTzq","Cgf5Bg9Hzeu","Afjtsum","AefPufC","sKzJrvO","zxjHDg9Y","tuvtu0fhrv8","y3jLyxrLt2i","y29TCgXLDgu","qNjPzgDL","u0jcv3O","D3ngzee","x29UrxjYB3i","BLHzEwu","yMfJA3vWigu","B25SAw5L","zNjVBNrPzxi","y3vYC29Yx2y","BM5Ly3q","q1v5wfu","x3nVy2TLDa","s2fsBhO","yxnL","sxjWAhe","ywnRx2LK","ywXPzcb1CMW","Afzyy1i","BwvKAwf0zwW","z2vrDwv1zuW","BMvY","x3bYzwzPEa","qKroDLm","ywDLu2HVDW","Ec11C2uT","t05Pzem","ig1LC3nHz2u","t1rer2u","tgr4D28","BgvY","zgvIDwC","B2P5AMm","C01wu2S","C3bSAwnL","A3r6tLe","yNLevMW","DK5Xsuu","B3jpBMXPBMu","mJaYm1vtDhPoEa","r2HXwNO","t2DXC0W","DxnsC1K","B3bVu2u","B2zMBgLUzq","z1Huq2W","rMLivvu","x3fVC0rc","AevYCM9Yrxy","uxvLDwu","D2vI","q0ThsM8","s1jyuNO","thPfv3G","CMvWBgfJzui","Bg9N","id4G","B2fK","ANLLq1i","AK1qzhG","tKvwDLm","Cgf5Bg9Hza","z2vY","y29UBMvJDca","ugH5DKG","AvDoCNa","A2PlqwW","q0Xpu0LorW","y291BNq","uhDkt1q","C0nVDw50zxi","B25kv2W","txHitva","shP5Bhu","sgvXrKG","refpsMe","lcbOB3n0BMe","tg9NsurozxC","ywXty29Wzq","B2TnsKW","AwXLtMfTzq","DMvUDa","sxzmr0e","DvLWvve","y3rTruC","uKv1BwW","rxzLBNq","zufJAW","DKXPu2S","u3flAfK","yw5Nzq","CMfTzq","tgTyt0u","CfPrseC","ywnRDxbfBMq","BwfUDwfSihi","vLzNshe","Buvqy0C","tMvvv1G","tMfjque","sKPQweW","BK1cwgW","yKPgAMi","x2rLyNvN","ndHur3DcuwS","zKPTvxC","v3zqAwm","q0Xpu0ve","AwLYBxy","vKHRsfm","C0LUDNe","ue5er3m","tvLVwge","rw5Ovue","uxz1EMq","y29Uy2f0","rLDQsgO","B3jL","AuDktuO","uuHswfO","D3LNAgW","zhDXsM8","B1ftEve","zhDfr2y","CNLoB28","q3fNv1m","DMfSDwu","tw9KDwXL","Aw9U","thPmqLC","yxjyrLO","s29vDem","ChjVy2vZCW","BgLZDgvUtMu","tMz0txG","CuHmAMO","C2rUuwm","ChjVDg9JB2W","u2Ttz2u","yNHABeW","CwLkBMO","CM92AwrLige","quTXB3G","vNf3Cu0","rMHiq2S","vuvYDg0","we9qA0O","Dxrjza","BwLUAvbYB2C","BIWGAg9ZDg4","u0P5sfi","y2vZC0HHBMq","yKDAweK","y2uGBM90igK","Dg9cExrLC0W","Cgu6ia","A1jtBMm","B0jhvKW","C2HPzNq","yvDet0m","weD0Cu0","CM92AwrLigi","BMrWB2LUDca","CNjVCK1LC3m","DhLuv1G","Cgfyz1i","qKvIC0W","CgfNzxnOB3C","CerMwuy","z01xEue","D3bmBha","D25qsvu","BMfTzq","CMfNzvn5BMm","q0XuweG","C3rVCcbPBw0","tKvbrvC","Cxr3De0","CgLUz19VBMm","DgLUzYbZzxi","zw50zwqGDhK","wNnZALe","ALDpuMm","BMv3vMvYC2K","y2HLy2TdDxi","Bwf4tg9ZC0m","tMzdvKq","rfL1t2q","oda3odqWzxjMrgn3","vhndywC","Bhm6ia","ENvHCge","z01xu2m","C0Xf","ueLHCfy","x2n1CNnVCKy","v1z2DuS","zgvS","uLbptMq","wgftzuS","zxq9DxrMltG","x3jLywr5q2W","Aw5N","CMvTB3zLq2G","vu1XtNu","qKzVD20","t2TSCvm","wLbotKm","u1zwAgG","D0DbvvK","yw5Hz2vY","igfYCMf5yNu","BfrPBwvVDxq","zMzmAw5L","uhbvBgG","sKndy28","AMXmvxm","z2v0","A0DwrKS","wwDVsfa","wgL1ENq","yxveBg0","BLjUrvC","uKLyAMG","BMvJDa","CuXVD20","ysbTDxn0igi","zsbHihn0CMK","t0PRAuy","DhL4wKG","ywDLsgLKzq","Cwz1Ewm","B2LcC0S","vgrOv1e","yLvNs28","x25HDMLNyxq","suvtx0vsuK8","zw1PDa","t0Lvt04","Axfwq1m","uMPOC0u","y3jLyxrLt3a","AvLlzhG","CezOBui","whfLrge","y3vYCMvUDeu","BxHXBue","wuncD1q","AM9PBG","ihjLy29UBMu","x2HHBMrSzva","Aw1LCYbPBIa","v3PJy1u","x2DLDeLUDgu","vhDgt1i","ELnXB2S","Bwu6ia","DhbizwfKzxi","wNjTrNq","DuHIq3a","DMvY","A0rqzu8","wLjtEMu","t1bftL9fuLi","z1jlvKq","y09Wzw4","EuLTtwS","A2vUr1e","wu9PBeK","DMziA3C","zuzYswe","yMLUyxj5vhK","v2rmy0i","ENzku0W","zwn0","A2zLAgy","Dev2zw50","zhvJq1y","yxv0BW","B25LCNjVCG","ihrYEsbYzwm","q0HnqNq","CgjICdi","tuXKvMe","yxrLq291BNq","BhnoAu0","zw5JB2rLrNi","ywnOzwq","t2DgDeC","uLPOCwK","tg9Nsuq","mJeYnZG1AvHmChb0","s0Tiyw8","ywr2yw5Jzq","sLnptLa","x3bPBMDqB24","BMnVzgLUzW","AwrI","t05jzK8","EKPiAu8","qxDIt0S","y2j4tuu","Eg5jwu4","rNDXDeW","D2rJug4","z1zowu0","D2XqtMe","v1rvruu","wNnTugG","q29Kzq","EwDet2G","CvbiuLe","DgnNCKO","zwvKzwq","A3jLAhC","D2D1ywO","swP5ENO","yMrFzgLK","AgzoEgO","C0XPC3rLBMu","z2vjBMzVu3K","zNLhzvu","y3vYC29Y","y29UDgLUDwu","BLD3tey","ywLmv3m","yw9SA0W","y2HnyxHdB3u","tMnpt3y","x2rPC2nVBM4","BMnLq2XVC2u","y214BLm","DKDxsLC","yxnJCMLWDa","y2HHCKnVzgu","vuHlr3a","B25pCgvU","C0jYtLq","txfWCKm","uu9uzLi","B25szwnLAxy","rvrRAMu","rLL5z28","BxvZtwK","CMvUDevUzha","x2HHBMrSzu8","ExbL","wgfZBMy","C2vYDMLJzq","ChbL","D1fICvO","rgvKAwnHDgu","r1Hzze4","BgzsqKq","EfvZzuvUDG","D3nYANq","Ahr0Ca","C3vIyxjYyxK","y1ztwgO","Aw5L","ruTktuq","x2vUzhbVAw4","zKXYuLu","z2v0sxrLBq","ru5vAfu","DuHcBvi","ufPQCLO","wuTTy0W","s1DwBgO","t0PgELu","D3frDwq","x2DLBMvYyxq","y29SBM8","rMX0z3y","Ehfnq3G","BgLbA3u","CvLuthm","AgDWq2C","Cgf5Bg9Hzfq","seziue8","DvLTCNa","z2X6tMW","vK1UuM0","CIb0DhDjra","t0fWBhC","BuHhAeG","q3z5y3G","rw1PrK4","BgLUzq","AMXKBuG","zxHWB3j0CW","z1fqCvq","x0rctMfTzq","Dg9cExrLC0i","C3vJy2vZCW","DuvRB0m","zxzWr2y","vvnyCKm","AwXLx25HBwu","y0nkvwi","ihzHBgLKihm","EKPcrvu","x2rPC3bHDgm","AvvcyKS","zw5XDwv1zq","CMv0CNLdB3u","rg50Cem","CLrvB1K","vuDdr2S","u3PZDhC","A25zEMi","Auz6Auq","yNL0zxm","zMD5zwy","s2L4Axu","s3jzshC","CMvWBgfJzq","C2v0","rNvQDfq","B25mAw5L","Dw5ZAwDUzwq","y3vYDMfSDwu","vhnkvvy","qMLYBKG","yNvMzMvYzwq","rLfOvwG","rLj2zvu","A3zyq00","zNjHBwvuExa","DhjHBNnHy3q","t0nsu3C","icSG","DhDVCMTdAge","sK1sC3u","wMPPDhi","CM9YrxzLBNq","Aw5JBhvKzxm","s2fxCxy","EvHkAeG","x194x21Zz18","C3rLBMvYCW","AwLAqNK","t01sCNa","AgLNAa","x2LUDgvYDMe","v21mCfu","sNbKBK0","BwDryMW","t1bftG","zNjVBunOyxi","CMvHzg9UBhK","reiGzMfPBgu","swLTq2C","y2XVC2veqG","A2v5","whfVqxC","z09VAMK","y3jLyxrLuMu","yKDWCxy","CM1wDhq","D0rcEu0","EePyu3a","q0TWAMC","CMfUzg9T","Cg9PBNrbBMq","CfPUs2e","EwvfzM4","se5vDhO","vvndEum","y2HLy2Tszwe","Ee1ks2e","BMCGDxjSoIa","vxbKyxrLq28","v3v6v1y","wu5Yu1q","CLbMDuO","x3bPBMC","x2LZtM9Kzq","tKP3CgC","ihrVihjLDhi","x3DZsw5ZDge","DxvtA2y","CwH6v1q","yxbWzw5Kq2G","s05ps1G","igzHAwWSig0","yw1L","CgfNzwHPzgu","CMvQzwn0","ChPSCe4","mNW2Fda","DMzusLG","twnOBeS","ELvpD0O","x3DZ","zw50tgLZDgu","mhWYFdn8mxW","D1DwBLu","BNrfBMrWB2K","vhHAv1e","igzPzwXKoIa","DLfYz1i","EKHmzMq","CMvZB2X2zq","B2zM","BgvUz3rO","uePwtKW","ruXHC2u","zKnPzu0","zgLZywjSzue","vgnzyKm","z2v0qwXS","zgrjrcWGzgu","Egvou2q","rKvuvM0","CNb4q0u","DeLUDgvYy2u","uhbbs2u","ANfnExC","vwTJDKC","uNnhExu","x1fVu01HBMe","u1PmDu4","BKXPBMu","vK9PyLy","CMvZzxruCMK","tuLuzue","CxzgzfG","zw5HyMXLuw8","Ce5NtLa","uLjpuG","Cg9RtLy","tvnjsKO","DKPwtfi","sNDHt2K","Dhf6vwq","wKfHB3q","yMLUyxj5","DMzsAgO","Cur2v3e","turfDva","C3neEfy","z1v0qxa","r1zhELC","DvfbvMG","AeHQzLy","BKHgu0y","x2LZsw5PDa","Aw9UvgLTzw8","yLfWCgi","svjfDgS","AwDHDg9Yt24","DcbSAw1PDa","t3bLBKv2zw4","B21Mvfy","wLvSz1u","B3v0sw50zxi","Bg9IywXty28","q2juyxC","vw5Oyw5KBgu","BhrPCgXLihq","BNrbBMrvCgq","y2HnyxHuCMK","x2nSzwfYvgK","x2n1CNnVCK0","x2XPC3rLBMu","mti4otqWmtbOvg55CLC","B2vbAha","B3PmCKW","CMPQzhK","x2rYB3bhBg8","DwvPs3q","zMLUza","CMvHzhDYAxq","D2rXq3u","txHvvMy","ue5rDvG","DxrMofDYAxq","q29UzMLN","zLDbEfy","AgfZt3DUuhi","BwLUzW","CeXzyue","twvZC2fNzuu","ywnRx2nVzgu","Bwf4uMv0CMK","m3W1Fdr8mxW","AgvKtwf4uMu","CNnVCL9Uyw0","yvD2vhi","ywDLrxzLBNq","tfjwAgC","whD3q2i","qwTkC2u","mdaWmdaWmda","s1nLB3m","yxbWBhK","x3jLy29UBMu","uNf3ve4","yxrHlcbKyxq","DwnUwwS","x3bYB3rVy28","ChrVCG","zwrPyxrLBhK","q3vZDg9Tq2W","AK1wue8","BNruCMLLC0m","AMDju1a","u3rYyxrLz3K","z2v0s2v5","zxjFDhrS","CNLiqMC","z2v0u3rVCMe","u1P6C2O","z2vkAMC","C2v0sxrLBq","twLoENC","A0THvLG","uxzKuNu","Bhj5Au4","tKrLrK0","s1fjsMC","u1fkveK","u2TPCcbWyxm","qMHcBNC","z2POyuO","ignVzgu6ia","CxbtA3u","B25tDgfYDfi","BMCGzMfPBgu","uM5Jshe","ywrKrxzLBNq","y1fwrhG","BwvZ","zvvYBa","Fdj8mhW4","rvH1s2W","rhbprhu","CvnSAvC","zxH0zw5ZAw8","AMvJDfn0B3i","uMPtte0","zxH0ugf5Bg8","EgHqBxO","Dg9oDw1Izxi","C3vIC3rYAw4","yxvyt2y","tg9JAW","x2nVBM5Ly3q","CMvZDwX0","s1D4wMy","BgPJzhm","zgrqzxa","CgLUz09Uy2u","x2jPBMfYEvq","CNbwu08","AvrgCKS","AxLxuMO","s21vy3O","s0zZyMG","quzttvu","Ef9MCM9UDgK","mJu5mZG0ohvdDwPfyq","C3DXCgu","uMvJB25Uzwm","DMHAuw0","zvfZrhu","zM5oyLK","x2HHBMrSzvi","quTmteK","q0rfAg4","wvDHD3q","ywz0BKC","Bg93","ihrPBwvVDxq","DKvtrxC","ueziDeO","C3PADLG","BMrLEa","x29UvgLTzw8","D2PxvLi","CfLcBNu","aaaaaaaaaaa","BMCGB3iGyw4","D3PQy0u","BKTJuwm","y2f0y2G","AgvHzgvYCW","B25TzxnZywC","y3ruAw1LB3u","sMfVA0W","BML0AwfSAxO","z2v0q3vYC28","rvjst1i","B2LUDfjLywm","BuLXrMy","DMLJzuLeig8","Dg91Bgq","qML1wfm","sKj4AM4","uMjcELa","ExDks0u","qLn4rvi","rK5qu3u","y29Kzq","CuL4DK0","rwvqv2m","zMX1C2HfEha","rfPfqMK","vuHurfu","D2LSBfjLy28","CMvJB25Uzwm","u2HHCMvKv28","txPOrK4","B25fCNjVCG","reHrsMi","C3rYAw5NAwy","D3nZoI8V","DMXnEhq","x2LZv29YA2u","y2XLyxi","zgf0yq","ALjXzhu","wgzoyuq","EKf4BK4","vgvPB3i","u0TQuwe","DMr0DNe","ENfdqM0","wKnksNO","sLjXtuS","BwvY","uuXQu3i","nhWYFdb8mxW","BwfW","CMfTugfYyw0","DLjoAhK","rMPjExi","y3vYC29YlNm","vg9LB2e","r3jyywq","ihrPBwvZ","B2DtAhm","BhDZBMK","zhzAv2K","CgLUz1rPBwu","uu9WB0u","CNH5uMC","Efrurw52","B3PHCw0","BwXLwfK","tvLtCgO","DMPszwu","Au5TBeW","B25tDg9Wsw0","ChvZAa","C2zLEvO","D01bywS","vujSBfa","CMvKDwnL","zNjVBujPDhm","qw1VDw50","rujIr3K","CMLLC0nVDw4","B25VCgvU","rKXeEfq","CKTQqNu","quvwt2y","sxLjzha","x2nYzwf0zvm","zfDVCMTLCKC","AfvjsLO","Dg9tDhjPBMC","ChrJCNO","vK9wq1y","yu5ruhG","CYbPBNn0yw4","CMTLCKDSB2i","tej2rfy","zNvUy3rPB24","BwvZC2fNzv8","D2f6ALe","s0XIBhm","qxfgEuq","vNPVz2m","Dg9cExrLCW","veLkr2K","z29PBMCGyxC","Aw5KzxGGB3u","Dgv4DfbHEwW","ugHuAMS","AMjdDxu","BhPIruS","Dhr3Awq","ugf0wvG","rKzbANa","C2vUzf9Hy2S","Dg9iyxnO","EgTKu0y","A2v5CW","v2rdzwy","rLrsse8","tNLKy00","AwXSihvZzsa","B2HergG","C3rVCMu","DhLWzq","DKjHuMG","yLrsy2W","yMfSrxzLBNq","y2jyuvO","DgLTzw91Da","CMvHzfvjBNq","r3PZAMO","Ew1oqvy"];return zn=function(){return n},zn()}Object[A(1608)+A(1727)](Q,A(1517)+"le",{value:!0})});var ze=ce((Bg,fo)=>{"use strict";var xo=["nodebuffer","arraybuffer","fragments"],uo=typeof Blob<"u";uo&&xo.push("blob");fo.exports={BINARY_TYPES:xo,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:uo,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ht=ce((Mg,qn)=>{"use strict";var{EMPTY_BUFFER:iu}=ze(),Mr=Buffer[Symbol.species];function ou(n,e){if(n.length===0)return iu;if(n.length===1)return n[0];let i=Buffer.allocUnsafe(e),a=0;for(let c=0;c<n.length;c++){let u=n[c];i.set(u,a),a+=u.length}return a<e?new Mr(i.buffer,i.byteOffset,a):i}function lo(n,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=n[u]^e[u&3]}function ho(n,e){for(let i=0;i<n.length;i++)n[i]^=e[i&3]}function au(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function zr(n){if(zr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Mr(n):ArrayBuffer.isView(n)?e=new Mr(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),zr.readOnly=!1),e}qn.exports={concat:ou,mask:lo,toArrayBuffer:au,toBuffer:zr,unmask:ho};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=$("bufferutil");qn.exports.mask=function(e,i,a,c,u){u<48?lo(e,i,a,c,u):n.mask(e,i,a,c,u)},qn.exports.unmask=function(e,i){e.length<32?ho(e,i):n.unmask(e,i)}}catch{}});var mo=ce((zg,po)=>{"use strict";var go=Symbol("kDone"),qr=Symbol("kRun"),Fr=class{constructor(e){this[go]=()=>{this.pending--,this[qr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[qr]()}[qr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[go])}}};po.exports=Fr});var yt=ce((qg,bo)=>{"use strict";var Gt=$("zlib"),wo=Ht(),cu=mo(),{kStatusCode:_o}=ze(),xu=Buffer[Symbol.species],uu=Buffer.from([0,0,255,255]),Un=Symbol("permessage-deflate"),qe=Symbol("total-length"),wt=Symbol("callback"),Ve=Symbol("buffers"),_t=Symbol("error"),Fn,Ur=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,!Fn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Fn=new cu(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[wt];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){Fn.add(c=>{this._decompress(e,i,(u,f)=>{c(),a(u,f)})})}compress(e,i,a){Fn.add(c=>{this._compress(e,i,(u,f)=>{c(),a(u,f)})})}_decompress(e,i,a){let c=this._isServer?"client":"server";if(!this._inflate){let u=`${c}_max_window_bits`,f=typeof this.params[u]!="number"?Gt.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Gt.createInflateRaw({...this._options.zlibInflateOptions,windowBits:f}),this._inflate[Un]=this,this._inflate[qe]=0,this._inflate[Ve]=[],this._inflate.on("error",du),this._inflate.on("data",yo)}this._inflate[wt]=a,this._inflate.write(e),i&&this._inflate.write(uu),this._inflate.flush(()=>{let u=this._inflate[_t];if(u){this._inflate.close(),this._inflate=null,a(u);return}let f=wo.concat(this._inflate[Ve],this._inflate[qe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[qe]=0,this._inflate[Ve]=[],i&&this.params[`${c}_no_context_takeover`]&&this._inflate.reset()),a(null,f)})}_compress(e,i,a){let c=this._isServer?"server":"client";if(!this._deflate){let u=`${c}_max_window_bits`,f=typeof this.params[u]!="number"?Gt.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Gt.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:f}),this._deflate[qe]=0,this._deflate[Ve]=[],this._deflate.on("data",fu)}this._deflate[wt]=a,this._deflate.write(e),this._deflate.flush(Gt.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=wo.concat(this._deflate[Ve],this._deflate[qe]);i&&(u=new xu(u.buffer,u.byteOffset,u.length-4)),this._deflate[wt]=null,this._deflate[qe]=0,this._deflate[Ve]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};bo.exports=Ur;function fu(n){this[Ve].push(n),this[qe]+=n.length}function yo(n){if(this[qe]+=n.length,this[Un]._maxPayload<1||this[qe]<=this[Un]._maxPayload){this[Ve].push(n);return}this[_t]=new RangeError("Max payload size exceeded"),this[_t].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[_t][_o]=1009,this.removeListener("data",yo),this.reset()}function du(n){if(this[Un]._inflate=null,this[_t]){this[wt](this[_t]);return}n[_o]=1007,this[wt](n)}});var bt=ce((Fg,Hn)=>{"use strict";var{isUtf8:vo}=$("buffer"),{hasBlob:lu}=ze(),hu=[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 gu(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Hr(n){let e=n.length,i=0;for(;i<e;)if((n[i]&128)===0)i++;else if((n[i]&224)===192){if(i+1===e||(n[i+1]&192)!==128||(n[i]&254)===192)return!1;i+=2}else if((n[i]&240)===224){if(i+2>=e||(n[i+1]&192)!==128||(n[i+2]&192)!==128||n[i]===224&&(n[i+1]&224)===128||n[i]===237&&(n[i+1]&224)===160)return!1;i+=3}else if((n[i]&248)===240){if(i+3>=e||(n[i+1]&192)!==128||(n[i+2]&192)!==128||(n[i+3]&192)!==128||n[i]===240&&(n[i+1]&240)===128||n[i]===244&&n[i+1]>143||n[i]>244)return!1;i+=4}else return!1;return!0}function pu(n){return lu&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Hn.exports={isBlob:pu,isValidStatusCode:gu,isValidUTF8:Hr,tokenChars:hu};if(vo)Hn.exports.isValidUTF8=function(n){return n.length<24?Hr(n):vo(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=$("utf-8-validate");Hn.exports.isValidUTF8=function(e){return e.length<32?Hr(e):n(e)}}catch{}});var Jr=ce((Ug,Io)=>{"use strict";var{Writable:mu}=$("stream"),So=yt(),{BINARY_TYPES:wu,EMPTY_BUFFER:Eo,kStatusCode:_u,kWebSocket:yu}=ze(),{concat:Gr,toArrayBuffer:bu,unmask:vu}=Ht(),{isValidStatusCode:Su,isValidUTF8:Co}=bt(),Gn=Buffer[Symbol.species],le=0,Ao=1,ko=2,Po=3,jr=4,Kr=5,jn=6,Wr=class extends mu{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||wu[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[yu]=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=le}_write(e,i,a){if(this._opcode===8&&this._state==le)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 Gn(a.buffer,a.byteOffset+e,a.length-e),new Gn(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 Gn(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 le:this.getInfo(e);break;case Ao:this.getPayloadLength16(e);break;case ko:this.getPayloadLength64(e);break;case Po:this.getMask();break;case jr:this.getData(e);break;case Kr:case jn:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let i=this.consume(2);if((i[0]&48)!==0){let c=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(c);return}let a=(i[0]&64)===64;if(a&&!this._extensions[So.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=Ao:this._payloadLength===127?this._state=ko: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=Po:this._state=jr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=jr}getData(e){let i=Eo;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&&vu(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Kr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[So.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 f=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(f);return}this._fragments.push(u)}this.dataMessage(i),this._state===le&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=le;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=Gr(a,i):this._binaryType==="arraybuffer"?c=bu(Gr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=le):(this._state=jn,setImmediate(()=>{this.emit("message",c,!0),this._state=le,this.startLoop(e)}))}else{let c=Gr(a,i);if(!this._skipUTF8Validation&&!Co(c)){let u=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(u);return}this._state===Kr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=le):(this._state=jn,setImmediate(()=>{this.emit("message",c,!1),this._state=le,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Eo),this.end();else{let a=e.readUInt16BE(0);if(!Su(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new Gn(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Co(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=le;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=le):(this._state=jn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=le,this.startLoop(i)}))}createError(e,i,a,c,u){this._loop=!1,this._errored=!0;let f=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(f,this.createError),f.code=u,f[_u]=c,f}};Io.exports=Wr});var Xr=ce((Gg,Ro)=>{"use strict";var{Duplex:Hg}=$("stream"),{randomFillSync:Eu}=$("crypto"),Do=yt(),{EMPTY_BUFFER:Cu,kWebSocket:Au,NOOP:ku}=ze(),{isBlob:vt,isValidStatusCode:Pu}=bt(),{mask:To,toBuffer:et}=Ht(),he=Symbol("kByteLength"),Iu=Buffer.alloc(4),Kn=8*1024,nt,St=Kn,_e=0,Du=1,Tu=2,Vr=class n{constructor(e,i,a){this._extensions=i||{},a&&(this._generateMask=a,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=_e,this.onerror=ku,this[Au]=void 0}static frame(e,i){let a,c=!1,u=2,f=!1;i.mask&&(a=i.maskBuffer||Iu,i.generateMask?i.generateMask(a):(St===Kn&&(nt===void 0&&(nt=Buffer.alloc(Kn)),Eu(nt,0,Kn),St=0),a[0]=nt[St++],a[1]=nt[St++],a[2]=nt[St++],a[3]=nt[St++]),f=(a[0]|a[1]|a[2]|a[3])===0,u=6);let l;typeof e=="string"?(!i.mask||f)&&i[he]!==void 0?l=i[he]:(e=Buffer.from(e),l=e.length):(l=e.length,c=i.mask&&i.readOnly&&!f);let p=l;l>=65536?(u+=8,p=127):l>125&&(u+=2,p=126);let w=Buffer.allocUnsafe(c?l+u:u);return w[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(w[0]|=64),w[1]=p,p===126?w.writeUInt16BE(l,2):p===127&&(w[2]=w[3]=0,w.writeUIntBE(l,4,6)),i.mask?(w[1]|=128,w[u-4]=a[0],w[u-3]=a[1],w[u-2]=a[2],w[u-1]=a[3],f?[w,e]:c?(To(e,a,w,u,l),[w]):(To(e,a,e,0,l),[w,e])):[w,e]}close(e,i,a,c){let u;if(e===void 0)u=Cu;else{if(typeof e!="number"||!Pu(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 f={[he]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==_e?this.enqueue([this.dispatch,u,!1,f,c]):this.sendFrame(n.frame(u,f),c)}ping(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):vt(e)?(c=e.size,u=!1):(e=et(e),c=e.length,u=et.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let f={[he]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,f,a]):this.getBlobData(e,!1,f,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,f,a]):this.sendFrame(n.frame(e,f),a)}pong(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):vt(e)?(c=e.size,u=!1):(e=et(e),c=e.length,u=et.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let f={[he]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,!1,f,a]):this.getBlobData(e,!1,f,a):this._state!==_e?this.enqueue([this.dispatch,e,!1,f,a]):this.sendFrame(n.frame(e,f),a)}send(e,i,a){let c=this._extensions[Do.extensionName],u=i.binary?2:1,f=i.compress,l,p;typeof e=="string"?(l=Buffer.byteLength(e),p=!1):vt(e)?(l=e.size,p=!1):(e=et(e),l=e.length,p=et.readOnly),this._firstFragment?(this._firstFragment=!1,f&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(f=l>=c._threshold),this._compress=f):(f=!1,u=0),i.fin&&(this._firstFragment=!0);let w={[he]:l,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:p,rsv1:f};vt(e)?this._state!==_e?this.enqueue([this.getBlobData,e,this._compress,w,a]):this.getBlobData(e,this._compress,w,a):this._state!==_e?this.enqueue([this.dispatch,e,this._compress,w,a]):this.dispatch(e,this._compress,w,a)}getBlobData(e,i,a,c){this._bufferedBytes+=a[he],this._state=Tu,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick($r,this,l,c);return}this._bufferedBytes-=a[he];let f=et(u);i?this.dispatch(f,i,a,c):(this._state=_e,this.sendFrame(n.frame(f,a),c),this.dequeue())}).catch(u=>{process.nextTick(Ru,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(n.frame(e,a),c);return}let u=this._extensions[Do.extensionName];this._bufferedBytes+=a[he],this._state=Du,u.compress(e,a.fin,(f,l)=>{if(this._socket.destroyed){let p=new Error("The socket was closed while data was being compressed");$r(this,p,c);return}this._bufferedBytes-=a[he],this._state=_e,a.readOnly=!1,this.sendFrame(n.frame(l,a),c),this.dequeue()})}dequeue(){for(;this._state===_e&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][he],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][he],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)}};Ro.exports=Vr;function $r(n,e,i){typeof i=="function"&&i(e);for(let a=0;a<n._queue.length;a++){let c=n._queue[a],u=c[c.length-1];typeof u=="function"&&u(e)}}function Ru(n,e,i){$r(n,e,i),n.onerror(e)}});var Uo=ce((jg,Fo)=>{"use strict";var{kForOnEventAttribute:jt,kListener:Yr}=ze(),No=Symbol("kCode"),Lo=Symbol("kData"),Oo=Symbol("kError"),Bo=Symbol("kMessage"),Mo=Symbol("kReason"),Et=Symbol("kTarget"),zo=Symbol("kType"),qo=Symbol("kWasClean"),Fe=class{constructor(e){this[Et]=null,this[zo]=e}get target(){return this[Et]}get type(){return this[zo]}};Object.defineProperty(Fe.prototype,"target",{enumerable:!0});Object.defineProperty(Fe.prototype,"type",{enumerable:!0});var rt=class extends Fe{constructor(e,i={}){super(e),this[No]=i.code===void 0?0:i.code,this[Mo]=i.reason===void 0?"":i.reason,this[qo]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[No]}get reason(){return this[Mo]}get wasClean(){return this[qo]}};Object.defineProperty(rt.prototype,"code",{enumerable:!0});Object.defineProperty(rt.prototype,"reason",{enumerable:!0});Object.defineProperty(rt.prototype,"wasClean",{enumerable:!0});var Ct=class extends Fe{constructor(e,i={}){super(e),this[Oo]=i.error===void 0?null:i.error,this[Bo]=i.message===void 0?"":i.message}get error(){return this[Oo]}get message(){return this[Bo]}};Object.defineProperty(Ct.prototype,"error",{enumerable:!0});Object.defineProperty(Ct.prototype,"message",{enumerable:!0});var Kt=class extends Fe{constructor(e,i={}){super(e),this[Lo]=i.data===void 0?null:i.data}get data(){return this[Lo]}};Object.defineProperty(Kt.prototype,"data",{enumerable:!0});var Nu={addEventListener(n,e,i={}){for(let c of this.listeners(n))if(!i[jt]&&c[Yr]===e&&!c[jt])return;let a;if(n==="message")a=function(u,f){let l=new Kt("message",{data:f?u:u.toString()});l[Et]=this,Wn(e,this,l)};else if(n==="close")a=function(u,f){let l=new rt("close",{code:u,reason:f.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Et]=this,Wn(e,this,l)};else if(n==="error")a=function(u){let f=new Ct("error",{error:u,message:u.message});f[Et]=this,Wn(e,this,f)};else if(n==="open")a=function(){let u=new Fe("open");u[Et]=this,Wn(e,this,u)};else return;a[jt]=!!i[jt],a[Yr]=e,i.once?this.once(n,a):this.on(n,a)},removeEventListener(n,e){for(let i of this.listeners(n))if(i[Yr]===e&&!i[jt]){this.removeListener(n,i);break}}};Fo.exports={CloseEvent:rt,ErrorEvent:Ct,Event:Fe,EventTarget:Nu,MessageEvent:Kt};function Wn(n,e,i){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,i):n.call(e,i)}});var Jn=ce((Kg,Ho)=>{"use strict";var{tokenChars:Wt}=bt();function Ie(n,e,i){n[e]===void 0?n[e]=[i]:n[e].push(i)}function Lu(n){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,f,l,p=-1,w=-1,y=-1,_=0;for(;_<n.length;_++)if(w=n.charCodeAt(_),f===void 0)if(y===-1&&Wt[w]===1)p===-1&&(p=_);else if(_!==0&&(w===32||w===9))y===-1&&p!==-1&&(y=_);else if(w===59||w===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${_}`);y===-1&&(y=_);let P=n.slice(p,y);w===44?(Ie(e,P,i),i=Object.create(null)):f=P,p=y=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(l===void 0)if(y===-1&&Wt[w]===1)p===-1&&(p=_);else if(w===32||w===9)y===-1&&p!==-1&&(y=_);else if(w===59||w===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${_}`);y===-1&&(y=_),Ie(i,n.slice(p,y),!0),w===44&&(Ie(e,f,i),i=Object.create(null),f=void 0),p=y=-1}else if(w===61&&p!==-1&&y===-1)l=n.slice(p,_),p=y=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(c){if(Wt[w]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);p===-1?p=_:a||(a=!0),c=!1}else if(u)if(Wt[w]===1)p===-1&&(p=_);else if(w===34&&p!==-1)u=!1,y=_;else if(w===92)c=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(w===34&&n.charCodeAt(_-1)===61)u=!0;else if(y===-1&&Wt[w]===1)p===-1&&(p=_);else if(p!==-1&&(w===32||w===9))y===-1&&(y=_);else if(w===59||w===44){if(p===-1)throw new SyntaxError(`Unexpected character at index ${_}`);y===-1&&(y=_);let P=n.slice(p,y);a&&(P=P.replace(/\\/g,""),a=!1),Ie(i,l,P),w===44&&(Ie(e,f,i),i=Object.create(null),f=void 0),l=void 0,p=y=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(p===-1||u||w===32||w===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=_);let C=n.slice(p,y);return f===void 0?Ie(e,C,i):(l===void 0?Ie(i,C,!0):a?Ie(i,l,C.replace(/\\/g,"")):Ie(i,l,C),Ie(e,f,i)),e}function Ou(n){return Object.keys(n).map(e=>{let i=n[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(f=>f===!0?c:`${c}=${f}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ho.exports={format:Ou,parse:Lu}});var Yn=ce((Vg,ea)=>{"use strict";var Bu=$("events"),Mu=$("https"),zu=$("http"),Ko=$("net"),qu=$("tls"),{randomBytes:Fu,createHash:Uu}=$("crypto"),{Duplex:Wg,Readable:Jg}=$("stream"),{URL:Zr}=$("url"),$e=yt(),Hu=Jr(),Gu=Xr(),{isBlob:ju}=bt(),{BINARY_TYPES:Go,CLOSE_TIMEOUT:Ku,EMPTY_BUFFER:Vn,GUID:Wu,kForOnEventAttribute:Qr,kListener:Ju,kStatusCode:Vu,kWebSocket:te,NOOP:Wo}=ze(),{EventTarget:{addEventListener:$u,removeEventListener:Xu}}=Uo(),{format:Yu,parse:Zu}=Jn(),{toBuffer:Qu}=Ht(),Jo=Symbol("kAborted"),es=[8,13],Ue=["CONNECTING","OPEN","CLOSING","CLOSED"],ef=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,G=class n extends Bu{constructor(e,i,a){super(),this._binaryType=Go[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vn,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,i===void 0?i=[]:Array.isArray(i)||(typeof i=="object"&&i!==null?(a=i,i=[]):i=[i]),Vo(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Go.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 Hu({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new Gu(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[te]=this,u[te]=this,e[te]=this,c.on("conclude",rf),c.on("drain",sf),c.on("error",of),c.on("message",af),c.on("ping",cf),c.on("pong",xf),u.onerror=uf,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",Yo),e.on("data",Xn),e.on("end",Zo),e.on("error",Qo),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[$e.extensionName]&&this._extensions[$e.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,i){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,i,!this._isServer,a=>{a||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Xo(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,i,a){if(this.readyState===n.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!==n.OPEN){ts(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Vn,i,a)}pong(e,i,a){if(this.readyState===n.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!==n.OPEN){ts(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Vn,i,a)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,i,a){if(this.readyState===n.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!==n.OPEN){ts(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[$e.extensionName]||(c.compress=!1),this._sender.send(e||Vn,c,a)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){fe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(G,"CONNECTING",{enumerable:!0,value:Ue.indexOf("CONNECTING")});Object.defineProperty(G.prototype,"CONNECTING",{enumerable:!0,value:Ue.indexOf("CONNECTING")});Object.defineProperty(G,"OPEN",{enumerable:!0,value:Ue.indexOf("OPEN")});Object.defineProperty(G.prototype,"OPEN",{enumerable:!0,value:Ue.indexOf("OPEN")});Object.defineProperty(G,"CLOSING",{enumerable:!0,value:Ue.indexOf("CLOSING")});Object.defineProperty(G.prototype,"CLOSING",{enumerable:!0,value:Ue.indexOf("CLOSING")});Object.defineProperty(G,"CLOSED",{enumerable:!0,value:Ue.indexOf("CLOSED")});Object.defineProperty(G.prototype,"CLOSED",{enumerable:!0,value:Ue.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(G.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(G.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Qr])return e[Ju];return null},set(e){for(let i of this.listeners(n))if(i[Qr]){this.removeListener(n,i);break}typeof e=="function"&&this.addEventListener(n,e,{[Qr]:!0})}})});G.prototype.addEventListener=$u;G.prototype.removeEventListener=Xu;ea.exports=G;function Vo(n,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ku,protocolVersion:es[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(n._autoPong=c.autoPong,n._closeTimeout=c.closeTimeout,!es.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${es.join(", ")})`);let u;if(e instanceof Zr)u=e;else try{u=new Zr(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}u.protocol==="http:"?u.protocol="ws:":u.protocol==="https:"&&(u.protocol="wss:"),n._url=u.href;let f=u.protocol==="wss:",l=u.protocol==="ws+unix:",p;if(u.protocol!=="ws:"&&!f&&!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 R=new SyntaxError(p);if(n._redirects===0)throw R;$n(n,R);return}let w=f?443:80,y=Fu(16).toString("base64"),_=f?Mu.request:zu.request,C=new Set,P;if(c.createConnection=c.createConnection||(f?nf:tf),c.defaultPort=c.defaultPort||w,c.port=u.port||w,c.host=u.hostname.startsWith("[")?u.hostname.slice(1,-1):u.hostname,c.headers={...c.headers,"Sec-WebSocket-Version":c.protocolVersion,"Sec-WebSocket-Key":y,Connection:"Upgrade",Upgrade:"websocket"},c.path=u.pathname+u.search,c.timeout=c.handshakeTimeout,c.perMessageDeflate&&(P=new $e({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=Yu({[$e.extensionName]:P.offer()})),i.length){for(let R of i){if(typeof R!="string"||!ef.test(R)||C.has(R))throw new SyntaxError("An invalid or duplicated subprotocol was specified");C.add(R)}c.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(c.origin&&(c.protocolVersion<13?c.headers["Sec-WebSocket-Origin"]=c.origin:c.headers.Origin=c.origin),(u.username||u.password)&&(c.auth=`${u.username}:${u.password}`),l){let R=c.path.split(":");c.socketPath=R[0],c.path=R[1]}let I;if(c.followRedirects){if(n._redirects===0){n._originalIpc=l,n._originalSecure=f,n._originalHostOrSocketPath=l?c.socketPath:u.host;let R=a&&a.headers;if(a={...a,headers:{}},R)for(let[U,Y]of Object.entries(R))a.headers[U.toLowerCase()]=Y}else if(n.listenerCount("redirect")===0){let R=l?n._originalIpc?c.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:u.host===n._originalHostOrSocketPath;(!R||n._originalSecure&&!f)&&(delete c.headers.authorization,delete c.headers.cookie,R||delete c.headers.host,c.auth=void 0)}c.auth&&!a.headers.authorization&&(a.headers.authorization="Basic "+Buffer.from(c.auth).toString("base64")),I=n._req=_(c),n._redirects&&n.emit("redirect",n.url,I)}else I=n._req=_(c);c.timeout&&I.on("timeout",()=>{fe(n,I,"Opening handshake has timed out")}),I.on("error",R=>{I===null||I[Jo]||(I=n._req=null,$n(n,R))}),I.on("response",R=>{let U=R.headers.location,Y=R.statusCode;if(U&&c.followRedirects&&Y>=300&&Y<400){if(++n._redirects>c.maxRedirects){fe(n,I,"Maximum redirects exceeded");return}I.abort();let re;try{re=new Zr(U,e)}catch{let Z=new SyntaxError(`Invalid URL: ${U}`);$n(n,Z);return}Vo(n,re,i,a)}else n.emit("unexpected-response",I,R)||fe(n,I,`Unexpected server response: ${R.statusCode}`)}),I.on("upgrade",(R,U,Y)=>{if(n.emit("upgrade",R),n.readyState!==G.CONNECTING)return;I=n._req=null;let re=R.headers.upgrade;if(re===void 0||re.toLowerCase()!=="websocket"){fe(n,U,"Invalid Upgrade header");return}let ee=Uu("sha1").update(y+Wu).digest("base64");if(R.headers["sec-websocket-accept"]!==ee){fe(n,U,"Invalid Sec-WebSocket-Accept header");return}let Z=R.headers["sec-websocket-protocol"],k;if(Z!==void 0?C.size?C.has(Z)||(k="Server sent an invalid subprotocol"):k="Server sent a subprotocol but none was requested":C.size&&(k="Server sent no subprotocol"),k){fe(n,U,k);return}Z&&(n._protocol=Z);let H=R.headers["sec-websocket-extensions"];if(H!==void 0){if(!P){fe(n,U,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let W;try{W=Zu(H)}catch{fe(n,U,"Invalid Sec-WebSocket-Extensions header");return}let se=Object.keys(W);if(se.length!==1||se[0]!==$e.extensionName){fe(n,U,"Server indicated an extension that was not requested");return}try{P.accept(W[$e.extensionName])}catch{fe(n,U,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[$e.extensionName]=P}n.setSocket(U,Y,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(I,n):I.end()}function $n(n,e){n._readyState=G.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function tf(n){return n.path=n.socketPath,Ko.connect(n)}function nf(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Ko.isIP(n.host)?"":n.host),qu.connect(n)}function fe(n,e,i){n._readyState=G.CLOSING;let a=new Error(i);Error.captureStackTrace(a,fe),e.setHeader?(e[Jo]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick($n,n,a)):(e.destroy(a),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function ts(n,e,i){if(e){let a=ju(e)?e.size:Qu(e).length;n._socket?n._sender._bufferedBytes+=a:n._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${n.readyState} (${Ue[n.readyState]})`);process.nextTick(i,a)}}function rf(n,e){let i=this[te];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=n,i._socket[te]!==void 0&&(i._socket.removeListener("data",Xn),process.nextTick($o,i._socket),n===1005?i.close():i.close(n,e))}function sf(){let n=this[te];n.isPaused||n._socket.resume()}function of(n){let e=this[te];e._socket[te]!==void 0&&(e._socket.removeListener("data",Xn),process.nextTick($o,e._socket),e.close(n[Vu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function jo(){this[te].emitClose()}function af(n,e){this[te].emit("message",n,e)}function cf(n){let e=this[te];e._autoPong&&e.pong(n,!this._isServer,Wo),e.emit("ping",n)}function xf(n){this[te].emit("pong",n)}function $o(n){n.resume()}function uf(n){let e=this[te];e.readyState!==G.CLOSED&&(e.readyState===G.OPEN&&(e._readyState=G.CLOSING,Xo(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function Xo(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Yo(){let n=this[te];if(this.removeListener("close",Yo),this.removeListener("data",Xn),this.removeListener("end",Zo),n._readyState=G.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[te]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",jo),n._receiver.on("finish",jo))}function Xn(n){this[te]._receiver.write(n)||this.pause()}function Zo(){let n=this[te];n._readyState=G.CLOSING,n._receiver.end(),this.end()}function Qo(){let n=this[te];this.removeListener("error",Qo),this.on("error",Wo),n&&(n._readyState=G.CLOSING,this.destroy())}});var sa=ce((Xg,ra)=>{"use strict";var $g=Yn(),{Duplex:ff}=$("stream");function ta(n){n.emit("close")}function df(){!this.destroyed&&this._writableState.finished&&this.destroy()}function na(n){this.removeListener("error",na),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function lf(n,e){let i=!0,a=new ff({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(u,f){let l=!f&&a._readableState.objectMode?u.toString():u;a.push(l)||n.pause()}),n.once("error",function(u){a.destroyed||(i=!1,a.destroy(u))}),n.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(c,u){if(n.readyState===n.CLOSED){u(c),process.nextTick(ta,a);return}let f=!1;n.once("error",function(p){f=!0,u(p)}),n.once("close",function(){f||u(c),process.nextTick(ta,a)}),i&&n.terminate()},a._final=function(c){if(n.readyState===n.CONNECTING){n.once("open",function(){a._final(c)});return}n._socket!==null&&(n._socket._writableState.finished?(c(),a._readableState.endEmitted&&a.destroy()):(n._socket.once("finish",function(){c()}),n.close()))},a._read=function(){n.isPaused&&n.resume()},a._write=function(c,u,f){if(n.readyState===n.CONNECTING){n.once("open",function(){a._write(c,u,f)});return}n.send(c,f)},a.on("end",df),a.on("error",na),a}ra.exports=lf});var ns=ce((Yg,ia)=>{"use strict";var{tokenChars:hf}=bt();function gf(n){let e=new Set,i=-1,a=-1,c=0;for(c;c<n.length;c++){let f=n.charCodeAt(c);if(a===-1&&hf[f]===1)i===-1&&(i=c);else if(c!==0&&(f===32||f===9))a===-1&&i!==-1&&(a=c);else if(f===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);let l=n.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=n.slice(i,c);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);return e.add(u),e}ia.exports={parse:gf}});var da=ce((Qg,fa)=>{"use strict";var pf=$("events"),Zn=$("http"),{Duplex:Zg}=$("stream"),{createHash:mf}=$("crypto"),oa=Jn(),st=yt(),wf=ns(),_f=Yn(),{CLOSE_TIMEOUT:yf,GUID:bf,kWebSocket:vf}=ze(),Sf=/^[+/0-9A-Za-z]{22}==$/,aa=0,ca=1,ua=2,rs=class extends pf{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:yf,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:_f,...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=Zn.createServer((a,c)=>{let u=Zn.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=Ef(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(c,u,f)=>{this.handleUpgrade(c,u,f,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=aa}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===ua){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!==ca)if(this._state=ca,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",xa);let u=e.headers["sec-websocket-key"],f=e.headers.upgrade,l=+e.headers["sec-websocket-version"];if(e.method!=="GET"){it(this,e,i,405,"Invalid HTTP method");return}if(f===void 0||f.toLowerCase()!=="websocket"){it(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!Sf.test(u)){it(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){it(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Vt(i,400);return}let p=e.headers["sec-websocket-protocol"],w=new Set;if(p!==void 0)try{w=wf.parse(p)}catch{it(this,e,i,400,"Invalid Sec-WebSocket-Protocol header");return}let y=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&y!==void 0){let C=new st({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let P=oa.parse(y);P[st.extensionName]&&(C.accept(P[st.extensionName]),_[st.extensionName]=C)}catch{it(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,I,R,U)=>{if(!P)return Vt(i,I||401,R,U);this.completeUpgrade(_,u,w,e,i,a,c)});return}if(!this.options.verifyClient(C))return Vt(i,401)}this.completeUpgrade(_,u,w,e,i,a,c)}completeUpgrade(e,i,a,c,u,f,l){if(!u.readable||!u.writable)return u.destroy();if(u[vf])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>aa)return Vt(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${mf("sha1").update(i+bf).digest("base64")}`],y=new this.options.WebSocket(null,void 0,this.options);if(a.size){let _=this.options.handleProtocols?this.options.handleProtocols(a,c):a.values().next().value;_&&(w.push(`Sec-WebSocket-Protocol: ${_}`),y._protocol=_)}if(e[st.extensionName]){let _=e[st.extensionName].params,C=oa.format({[st.extensionName]:[_]});w.push(`Sec-WebSocket-Extensions: ${C}`),y._extensions=e}this.emit("headers",w,c),u.write(w.concat(`\r
|
|
12
12
|
`).join(`\r
|
|
13
|
-
`)),
|
|
14
|
-
`+Object.keys(
|
|
13
|
+
`)),u.removeListener("error",xa),y.setSocket(u,f,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(y),y.on("close",()=>{this.clients.delete(y),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Jt,this)})),l(y,c)}};fa.exports=rs;function Ef(n,e){for(let i of Object.keys(e))n.on(i,e[i]);return function(){for(let a of Object.keys(e))n.removeListener(a,e[a])}}function Jt(n){n._state=ua,n.emit("close")}function xa(){this.destroy()}function Vt(n,e,i,a){i=i||Zn.STATUS_CODES[e],a={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(i),...a},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Zn.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 it(n,e,i,a,c,u){if(n.listenerCount("wsClientError")){let f=new Error(c);Error.captureStackTrace(f,it),n.emit("wsClientError",f,i,e)}else Vt(i,a,c,u)}});import{spawn as Wf}from"node:child_process";import{existsSync as Jf,openSync as Vf}from"node:fs";import{mkdir as $f}from"node:fs/promises";import{dirname as Xf}from"node:path";import{fileURLToPath as Yf}from"node:url";function os(n=K()){return Jf(n.libEntry)?n.libEntry:Yf(new URL("../index.ts",import.meta.url))}async function ka(n={}){let e=n.paths??K(),i=n.entryOverride??os(e);await $f(Xf(e.logFile),{recursive:!0});let a=Vf(e.logFile,"a"),u=i.endsWith(".ts")?["--import","tsx/esm",i,"--daemon"]:[i,"--daemon"],f=Wf(process.execPath,u,{detached:!0,stdio:["ignore",a,a],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(f.unref(),typeof f.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Zf.info("daemon spawned",{pid:f.pid,entry:i}),{pid:f.pid,entry:i}}var Zf,as=Le(()=>{"use strict";F();xe();Zf=T("spawn-daemon")});import{spawn as od}from"node:child_process";import{mkdir as ad,unlink as cd,writeFile as xd}from"node:fs/promises";import{dirname as ud,join as fd}from"node:path";function sr(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Ra(n,e){return new Promise((i,a)=>{let c=od(n,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",f=>{u+=f.toString("utf8")}),c.on("error",a),c.on("close",f=>{f===0?i():a(new Error(`${n} ${e.join(" ")} exited ${f}: ${u.trim()}`))})})}var rr,us,fs,Na=Le(()=>{"use strict";F();rr=T("supervisor.launchd"),us="ai.coze.bridge",fs={platform:"darwin",renderConfig(n){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
18
18
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
19
19
|
<plist version="1.0">
|
|
20
20
|
<dict>
|
|
21
21
|
<key>Label</key>
|
|
22
|
-
<string>${
|
|
22
|
+
<string>${us}</string>
|
|
23
23
|
<key>ProgramArguments</key>
|
|
24
24
|
<array>
|
|
25
|
-
<string>${
|
|
26
|
-
<string>${
|
|
25
|
+
<string>${sr(n.nodeBin)}</string>
|
|
26
|
+
<string>${sr(n.entry)}</string>
|
|
27
27
|
<string>--daemon</string>
|
|
28
28
|
</array>
|
|
29
29
|
<key>RunAtLoad</key>
|
|
@@ -33,12 +33,12 @@ var va=Object.create;var Ln=Object.defineProperty;var ka=Object.getOwnPropertyDe
|
|
|
33
33
|
<key>ThrottleInterval</key>
|
|
34
34
|
<integer>10</integer>
|
|
35
35
|
<key>StandardOutPath</key>
|
|
36
|
-
<string>${
|
|
36
|
+
<string>${sr(n.logFile)}</string>
|
|
37
37
|
<key>StandardErrorPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${sr(n.logFile)}</string>
|
|
39
39
|
</dict>
|
|
40
40
|
</plist>
|
|
41
|
-
`},configPath(n){return
|
|
41
|
+
`},configPath(n){return fd(n.homeDir,"Library","LaunchAgents",`${us}.plist`)},async install(n){let e=this.configPath(n);await ad(ud(e),{recursive:!0}),await xd(e,this.renderConfig(n),"utf8"),rr.info("plist written",{plistPath:e}),await Ra("launchctl",["load","-w",e]),rr.info("launchd job loaded",{label:us})},async uninstall(n){let e=this.configPath(n);await Ra("launchctl",["unload","-w",e]).catch(i=>rr.warn("launchctl unload failed (ignored)",{err:String(i)})),await cd(e).catch(i=>{if(i.code!=="ENOENT")throw i}),rr.info("launchd job removed",{plistPath:e})}}});import{spawn as dd}from"node:child_process";import{mkdir as ld,unlink as hd,writeFile as gd}from"node:fs/promises";import{dirname as pd,join as md}from"node:path";function ar(n,e){return new Promise((i,a)=>{let c=dd(n,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",f=>{u+=f.toString("utf8")}),c.on("error",a),c.on("close",f=>{f===0?i():a(new Error(`${n} ${e.join(" ")} exited ${f}: ${u.trim()}`))})})}var ir,or,ds,La=Le(()=>{"use strict";F();ir=T("supervisor.systemd"),or="coze-bridge.service",ds={platform:"linux",renderConfig(n){return`[Unit]
|
|
42
42
|
Description=Coze Bridge daemon
|
|
43
43
|
After=network.target
|
|
44
44
|
|
|
@@ -52,7 +52,7 @@ StandardError=append:${n.logFile}
|
|
|
52
52
|
|
|
53
53
|
[Install]
|
|
54
54
|
WantedBy=default.target
|
|
55
|
-
`},configPath(n){return
|
|
55
|
+
`},configPath(n){return md(n.homeDir,".config","systemd","user",or)},async install(n){let e=this.configPath(n);await ld(pd(e),{recursive:!0}),await gd(e,this.renderConfig(n),"utf8"),ir.info("systemd unit written",{unitPath:e}),await ar("systemctl",["--user","daemon-reload"]),await ar("systemctl",["--user","enable","--now",or]),ir.info("systemd unit enabled",{unitName:or})},async uninstall(n){let e=this.configPath(n);await ar("systemctl",["--user","disable","--now",or]).catch(i=>ir.warn("systemctl disable failed (ignored)",{err:String(i)})),await hd(e).catch(i=>{if(i.code!=="ENOENT")throw i}),await ar("systemctl",["--user","daemon-reload"]).catch(()=>{}),ir.info("systemd unit removed",{unitPath:e})}}});import{spawn as wd}from"node:child_process";import{join as _d}from"node:path";function Oa(n,e){return new Promise((i,a)=>{let c=wd(n,e,{stdio:["ignore","pipe","pipe"],shell:!1}),u="";c.stderr?.on("data",f=>{u+=f.toString("utf8")}),c.on("error",a),c.on("close",f=>{f===0?i():a(new Error(`${n} ${e.join(" ")} exited ${f}: ${u.trim()}`))})})}var ls,cr,hs,Ba=Le(()=>{"use strict";F();ls=T("supervisor.taskscheduler"),cr="CozeBridge",hs={platform:"win32",renderConfig(n){return`<?xml version="1.0" encoding="UTF-16"?>
|
|
56
56
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
57
57
|
<RegistrationInfo>
|
|
58
58
|
<Description>Coze Bridge daemon</Description>
|
|
@@ -76,25 +76,25 @@ WantedBy=default.target
|
|
|
76
76
|
</Exec>
|
|
77
77
|
</Actions>
|
|
78
78
|
</Task>
|
|
79
|
-
`},configPath(n){return
|
|
79
|
+
`},configPath(n){return _d(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await Oa("schtasks",["/Create","/SC","ONLOGON","/TN",cr,"/TR",e,"/RU",n.userName,"/F"]),ls.info("task scheduler entry created",{task:cr})},async uninstall(n){await Oa("schtasks",["/Delete","/TN",cr,"/F"]).catch(e=>ls.warn("schtasks /Delete failed (ignored)",{err:String(e)})),ls.info("task scheduler entry removed",{task:cr})}}});var gs={};Hs(gs,{buildContext:()=>Sd,getSupervisor:()=>vd,launchdSupervisor:()=>fs,systemdSupervisor:()=>ds,taskSchedulerSupervisor:()=>hs});import{homedir as yd,userInfo as bd}from"node:os";function vd(n=process.platform){switch(n){case"darwin":return fs;case"linux":return ds;case"win32":return hs;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function Sd(){let n=K();return{nodeBin:process.execPath,entry:os(n),logFile:n.logFile,homeDir:yd(),userName:bd().username}}var ps=Le(()=>{"use strict";xe();as();Na();La();Ba()});Ke();F();import{readdir as Q0}from"node:fs/promises";import{mkdir as V0,writeFile as $0}from"node:fs/promises";import{join as X0}from"node:path";var Y0={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ft(n,e,i,a){await V0(n,{recursive:!0});let c=Y0[e],u=X0(n,c),f=Z0(e,i,a);return await $0(u,f,"utf8"),u}function Z0(n,e,i){let a=`# Coze Agent: ${e}
|
|
80
80
|
|
|
81
81
|
> framework: \`${n}\`
|
|
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 zn(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function As(n,e){if(!n.modelToken)return null;let t=n.model||ne,r=$n(e),s={baseUrl:`${Un}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:t,name:t,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(r).length>0&&(s.headers=r),s}function Cs(n,e){if(!n.modelToken)return[];let t=$n(e),r=[];for(let[s,i]of Object.entries(t))r.push("-c",`model_providers.coze.http_headers.${s}="${i}"`);return r}var M=w("agent-handlers"),bs=5*1024*1024,Za=1,ec=6,tc=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ut=class{constructor(e){this.opts=e}opts;async listSkills(e){ce(e._meta,"_agent/listSkills");let t=Be(e._meta),r=await this.loadAgentCfg(t),s=r?.workspace??ae(t).workspace,i=r?.skills??[],o=[];for(let a of i){let c=re(s,a.relPath,"SKILL.md");await Ka(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(oc(a))}return{skills:o}}async addSkills(e){ce(e._meta,"_agent/addSkills");let t=Be(e._meta),r=await this.requireAgentCfg(t),s=e.skills??[],i=[...r.skills??[]],o=new Map(i.map((c,l)=>[c.skillId,l])),a=[];for(let c of s){let l=await Gn({agentId:t,workspace:r.workspace,framework:r.framework,skill:c});Hn(i,o,l),a.push(c)}return await Nt(t,i),await this.reloadAgentSessions(t,"skills-added"),{installedSkills:a}}async removeSkills(e){ce(e._meta,"_agent/removeSkills");let t=Be(e._meta),r=await this.requireAgentCfg(t),s=new Set(e.skillIds??[]),i=r.skills??[],o=[];for(let a of i){if(!s.has(a.skillId)){o.push(a);continue}let c=re(r.workspace,a.relPath);await Qa(c,{recursive:!0,force:!0}),M.info("skill removed",{agentId:t,skillId:a.skillId,relPath:a.relPath})}return await Nt(t,o),await this.reloadAgentSessions(t,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,t){return this.reloadAgentSessions(e,t)}async reloadAgentSessions(e,t){let r=this.opts.agents.get(e);if(r&&r.framework!=="codex"){for(let[s,i]of r.sessions)if(!(!i.downstream||!i.acpSessionId)){i.loadingSession=!0;try{await i.downstream.sessionLoad({sessionId:i.acpSessionId,cwd:r.workspace}),M.info("session reloaded",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId})}catch(o){M.warn("session reload failed",{reason:t,agentId:e,framework:r.framework,cloudId:s,acpId:i.acpSessionId,err:String(o)})}finally{i.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return M.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let t=e.agentId,r=await q(t);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${t}`);return r.cozeIdentity===e.cozeIdentity?(M.info("_agent/update: cozeIdentity unchanged, noop",{agentId:t}),{ok:!0}):(r.cozeIdentity=e.cozeIdentity,await X(r),await Me(r.workspace,r.framework,t,e.cozeIdentity),M.info("_agent/update: cozeIdentity rewritten",{agentId:t,framework:r.framework}),await this.reloadAgentSessions(t,"identity-changed"),{ok:!0})}async disconnectAgent(e){let t=e.agentId;if(!t)throw new h("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let r=await q(t);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await X(r),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(ce(e._meta,"_agent/switchModel"),!e.agentId)throw new h("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let t=e.model?.trim()?e.model:ne,r=await q(e.agentId);if(!r)throw new h("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=t,await X(r),M.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:t,reason:e.reason??""});let s=this.opts.agents.get(e.agentId);if(!s)return M.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};s.model=t;let i=[];for(let[o,a]of s.allSessionQueues())i.push(a.enqueue(async()=>{let c=s.sessions.get(o);c?.downstream&&(await c.downstream.stop(`switchModel: ${t}`).catch(()=>{}),c.downstream=void 0)}));return await Promise.all(i),M.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:t,cloudSessions:i.length}),{ok:!0}}async resetAgent(e){if(ce(e._meta,te.RESET),!e.agentId)throw new h("IPC_BAD_REQUEST",`${te.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,te.RESET,e.reason),{ok:!0}}async repairAgent(e){if(ce(e._meta,te.REPAIR),!e.agentId)throw new h("IPC_BAD_REQUEST",`${te.REPAIR}: missing agentId`);let t=await this.loadAgentCfg(e.agentId);if(t&&t.framework!=="openclaw")throw new h("IPC_BAD_REQUEST",`${te.REPAIR} only allowed for openclaw, got ${t.framework}`);if(t&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,t.workspace)}catch(r){M.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,te.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,t,r){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:r,err:String(s)})}}async getFileTree(e){ce(e._meta,"_agent/getFileTree");let t=e._meta,r=Be(t),s=await this.resolveWorkspace(r),i=e.filePath??"",o=this.safeJoin(s,i),a=await qn(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=fc(e.depth);return a.isDirectory()?{tree:await Bs(s,o,i,c)}:{tree:[{name:hc(i),path:Fs(i||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){ce(e._meta,"_agent/getFileContent");let t=Be(e._meta),r=await this.resolveWorkspace(t);if(!e.filePath)throw new h("IPC_BAD_REQUEST","filePath required");let s=this.safeJoin(r,e.filePath),i=await qn(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>bs)throw new h("IPC_BAD_REQUEST",`file too large: ${i.size} bytes (max ${bs})`);let o=await Ds(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 q(e).catch(()=>null))?.workspace??ae(e).workspace}safeJoin(e,t){let r=Ya(e,t||"."),s=Ls(e,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${Ms}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}loadAgentCfg(e){return q(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 nc(n){let e=st(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new h("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function rc(n){return n==="claude-code"?re(".claude","skills"):re(".agents","skills")}var sc=3e4,ic=50*1024*1024,$t=3e4;async function Gn(n){let{agentId:e,workspace:t,framework:r,skill:s}=n;if(!s.skillName)throw new h("IPC_BAD_REQUEST","skill missing skillName");let i=typeof s.content=="string"&&s.content.length>0,o=typeof s.downloadUrl=="string"&&s.downloadUrl.length>0;if(!i&&!o)throw new h("IPC_BAD_REQUEST",`skill ${s.skillId} missing both content and downloadUrl`);let a=nc(s.skillName),c=rc(r),l=re(c,a),d=re(t,l);if(await Ja(d,{recursive:!0}),i){let u=Buffer.from(s.content,"utf8");it(u.length),await Os(re(d,"SKILL.md"),u,"utf8")}else{let u=await ac(s.downloadUrl);lc(u)?await dc(u,d):await Os(re(d,"SKILL.md"),u.toString("utf8"),"utf8")}let f={skillId:s.skillId,skillName:s.skillName,relPath:l,installedAt:Date.now(),...s.description?{description:s.description}:{},...s.icon?{icon:s.icon}:{},...s.version?{version:s.version}:{},...s.downloadUrl?{downloadUrl:s.downloadUrl}:{},...s.config?{config:s.config}:{},...s.builtin?{builtin:s.builtin}:{}};return M.info("skill installed",{agentId:e,skillId:s.skillId,skillName:s.skillName,relPath:l,source:i?"content":"downloadUrl"}),f}function Hn(n,e,t){let r=e.get(t.skillId);if(r!==void 0){n[r]=t;return}e.set(t.skillId,n.length),n.push(t)}function oc(n){return{skillId:n.skillId,skillName:n.skillName,...n.description?{description:n.description}:{},...n.icon?{icon:n.icon}:{},...n.version?{version:n.version}:{},...n.config?{config:n.config}:{},...n.builtin?{builtin:n.builtin}:{}}}async function ac(n){if(!n)throw new h("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);it(e);let t=cc(n);return it(t.length),t}if(n.startsWith("file:")){let e=new URL(n).pathname,t=await Ds(e);return it(t.length),t}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,t=setTimeout(()=>e.abort(),sc);try{let r=await fetch(n,{signal:e.signal});if(!r.ok)throw new h("IPC_BAD_REQUEST",`fetch skill failed HTTP ${r.status} ${n}`);let s=await r.arrayBuffer();return it(s.byteLength),Buffer.from(s)}finally{clearTimeout(t)}}throw new h("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function it(n){if(n>ic)throw new h("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function cc(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new h("IPC_BAD_REQUEST","bad data URL");let t=!!e[2],r=e[3]??"";return t?Buffer.from(r,"base64"):Buffer.from(decodeURIComponent(r),"utf8")}function lc(n){return n.length>=2&&n[0]===31&&n[1]===139}async function dc(n,e){await uc(n),await new Promise((t,r)=>{let s=Ns("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),i="";s.stderr?.on("data",a=>{i+=String(a)});let o=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar extract timeout (${$t}ms)`))},$t);s.on("error",a=>{clearTimeout(o),r(new h("IPC_BAD_REQUEST",`tar spawn failed: ${a.message}`,{cause:a}))}),s.on("exit",a=>{clearTimeout(o),a===0?t():r(new h("IPC_BAD_REQUEST",`tar exit ${a}${i?`: ${i.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)})}async function uc(n){let e=await new Promise((t,r)=>{let s=Ns("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),i="",o="";s.stdout?.on("data",c=>{i+=String(c)}),s.stderr?.on("data",c=>{o+=String(c)});let a=setTimeout(()=>{s.kill("SIGKILL"),r(new h("IPC_BAD_REQUEST",`tar list timeout (${$t}ms)`))},$t);s.on("error",c=>{clearTimeout(a),r(new h("IPC_BAD_REQUEST",`tar list spawn failed: ${c.message}`))}),s.on("exit",c=>{clearTimeout(a),c===0?t(i):r(new h("IPC_BAD_REQUEST",`tar list exit ${c}${o?`: ${o.trim().slice(0,200)}`:""}`))}),s.stdin?.end(n)});for(let t of e.split(`
|
|
90
|
-
`)){let
|
|
91
|
-
`)[0]?.trim()||void 0}catch{return}}async function
|
|
92
|
-
`}var
|
|
93
|
-
`);this.buffer=t.pop()??"";let r=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{r.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return r}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(t){return this.onError?.({line:e,error:t}),[]}}};var Js={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},Dg=Object.fromEntries(Object.entries(Js).map(([n,e])=>[e,n])),Ic={"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:[]},Ue=class{seq=0;next(e,t){this.seq+=1;let r=Js[e]??xc(e),s=Ic[r]??[],i=[r,String(this.seq)];if(s.length>0){let o=s.map(c=>js(t?.[c]??"")),a=Tc(o).join(":");a&&i.push(a)}else t&&Object.values(t).some(o=>o)&&i.push(Object.values(t).filter(Boolean).map(o=>js(String(o))).join(":"));return i.join("_")}reset(){this.seq=0}};function xc(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function js(n){return n.replace(/[:_\s]+/g,"-")}function Tc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}k();var Pc=3e4,Ac=50,Cc=20,Vs=500;function Oc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=Vs?n:`${e.slice(0,Vs)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Qs(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var pe=class{constructor(e){this.opts=e;this.log=w(`downstream.${this.constructor.name}`),this.decoder=new Qt({onError:t=>this.log.warn("decode line failed",{line:t.line})})}opts;child;decoder;pending=new Map;idAllocator=new Ue;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new h("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",t=Rc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=t,t.stdout?.setEncoding("utf8"),t.stdout?.on("data",r=>{for(let s of this.decoder.push(r))this.dispatch(s)}),t.stderr?.setEncoding("utf8"),t.stderr?.on("data",r=>{let s=r.trimEnd();this.stderrRing.push(s),this.stderrRing.length>Ac&&this.stderrRing.shift(),this.log.debug("stderr",{text:s})}),t.on("exit",(r,s)=>{this.stopped=!0,(r!==0||s!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:r,signal:s,recentStderr:this.stderrRing.slice(-Cc)}),this.failAllPending(new h("AGENT_PROTOCOL_ERROR",`agent exited (${r}/${s})`));for(let o of this.exitHandlers)o(r,s)}),t.on("error",r=>{this.log.error("child error",{err:String(r)}),this.failAllPending(new h("AGENT_SPAWN_FAILED",String(r),{cause:r}))}),this.log.info("downstream started",{command:this.opts.command,pid:t.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let t=this.child,r=new Promise(i=>t.once("exit",()=>i()));Qs(t.pid,"SIGTERM");let s=setTimeout(()=>{t.killed||Qs(t.pid,"SIGKILL")},5e3);try{await r}finally{clearTimeout(s)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e){return this.call("session/prompt",e,0)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(jt("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(Fe(e,t))}catch(r){this.log.warn("respondAgentRequest write failed",{id:e,err:String(r)})}}respondAgentRequestError(e,t){if(!(!this.child||this.stopped))try{this.writeFrame(ve(e,t))}catch(r){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(r)})}}onExit(e){this.exitHandlers.push(e)}call(e,t,r=Pc){if(!this.child||this.stopped)return Promise.reject(new h("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),i=ct(s,e,t),o=r>0&&Number.isFinite(r);return new Promise((a,c)=>{let l=o?setTimeout(()=>{this.pending.delete(s),c(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r):null;this.pending.set(s,{resolve:a,reject:c,timer:l,method:e});try{this.writeFrame(i)}catch(d){l&&clearTimeout(l),this.pending.delete(s),c(d)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new h("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Ws(e))}dispatch(e){if(Vt(e)){let t=e.id!==null?this.pending.get(e.id):void 0;if(!t){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),t.timer&&clearTimeout(t.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:t.method,code:e.error.code,message:e.error.message,data:e.error.data}),t.reject(Hs(e.error))):(this.log.info("downstream returned result",{id:e.id,method:t.method,result:Oc(e.result)}),t.resolve(e.result));return}if(Gs(e)){if(e.method==="session/update")for(let t of this.updateHandlers)Promise.resolve(t(e.params)).catch(r=>this.log.warn("update handler failed",{err:String(r)}));else this.log.debug("unknown notification",{method:e.method});return}if(qs(e)){let t=e;this.handleAgentRequest(t).catch(r=>this.log.error("agent request handler failed",{method:t.method,err:String(r)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(ve(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let t of this.agentRequestHandlers)try{await t(e)}catch(r){this.log.error("agentRequestHandler threw",{method:e.method,err:String(r)});try{this.writeFrame(ve(e.id,lt(r)))}catch{}}}failAllPending(e){for(let t of this.pending.values())t.timer&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}};var bc="@agentclientprotocol/claude-agent-acp@latest";function Nc(n){let e={};for(let[t,r]of Object.entries(n))r!==void 0&&(t.startsWith("CLAUDE")||t==="AI_AGENT"||t==="BAGGAGE"||(e[t]=r));return e}var Kt=class extends pe{framework="claude-code";constructor(e){let t=Wt("claude-code"),[r,s]=t?[t,[]]:["npx",["-y",bc]],i=e.command??r,o=e.args??s,a={command:i,args:o,cwd:e.cwd,...e.env?{env:e.env}:{}};super(a)}sanitizeEnv(e){return Nc(e)}};import{mkdtempSync as Dc,rmSync as Lc}from"node:fs";import{tmpdir as Mc}from"node:os";import{join as Bc}from"node:path";var Fc="@zed-industries/codex-acp@latest",Xt=class extends pe{framework="codex";authMethodId;codexHomeDir;constructor(e){let t=Wt("codex"),[r,s]=t?[t,[]]:["npx",["-y",Fc]],i=e.command??r,o=e.args??s,a=e.extraArgs?[...o,...e.extraArgs]:o,c=e.isolateCodexHome?Dc(Bc(Mc(),"coze-bridge-codex-home-")):void 0,l=c?{...e.env??{},CODEX_HOME:c}:e.env,d={command:i,args:a,cwd:e.cwd,...l?{env:l}:{}};super(d),this.authMethodId=e.authMethodId,this.codexHomeDir=c}async initialize(e){let t=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),t}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Lc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var dt=class extends pe{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let t=e.sessionName??"default",r=["acp","--session",`agent:${e.agentId}:${t}`];e.gatewayToken&&r.push("--token",e.gatewayToken);let s={command:e.command,args:r,cwd:e.cwd,...e.env?{env:e.env}:{}};super(s),this.agentId=e.agentId,this.sessionName=t,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};k();z();var $e=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((t,r)=>{this.slots.push({task:e,resolve:t,reject:r}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t)}}}finally{this.running=!1}}}};var Yt=class{agentId;framework;workspace;deployType;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local"}getSessionQueue(e){let t=this.sessionQueues.get(e);return t||(t=new $e,this.sessionQueues.set(e,t)),t}allSessionQueues(){return this.sessionQueues.entries()}async dispose(e){this.status="stopped";let t=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let r of this.sessionQueues.values())r.dispose(t);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let t=[];for(let[,r]of this.sessions)ut(r),r.downstream&&(t.push(r.downstream.stop(e).catch(()=>{})),r.downstream=void 0);await Promise.all(t),this.activeTriggers.clear()}};function ut(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Uc}from"node:child_process";import{homedir as $c}from"node:os";import{join as zc}from"node:path";At();k();async function Ys(){let n=zc($c(),".openclaw/openclaw.json");return(await Le(n))?.gateway?.auth?.token??""}var Ks=w("openclaw.config"),qc=[0,5e3,5e3],Xs="models.providers.",Zt="agents.defaults.models",en=class{command;env;retryDelaysMs;queue=new $e;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??qc}async withRetry(e,t){let r;for(let s=0;s<this.retryDelaysMs.length;s++){let i=this.retryDelaysMs[s]??0;i>0&&await new Promise(o=>setTimeout(o,i));try{return await t()}catch(o){r=o,Ks.warn("openclaw cli failed, will retry",{label:e,attempt:s+1,err:String(o)})}}throw new h("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${r?.message??"unknown"}`)}runCli(e){return new Promise((t,r)=>{let s=Uc(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`exit ${o}: ${i.trim().slice(0,500)}`))})})}async runCliTolerant(e,t){try{await this.runCli(e)}catch(r){let s=String(r);if(t.some(i=>s.includes(i)))return;throw r}}async bestEffortUnset(e,t){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",t])))}catch(r){Ks.warn(`${e} failed (best-effort)`,{configPath:t,err:String(r)})}}ensureProvider(e,t){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Xs}${e}`,JSON.stringify(t),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Xs}${e}`)}addModelToAllowlist(e,t){let r={[e]:t?{alias:t}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Zt}[${e}]`,()=>this.runCli(["config","set",Zt,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Zt}[${e}]`,`${Zt}.${e}`)}ensureAgent(e,t,r){let s=["agents","add",e,"--workspace",t,"--non-interactive"];return r&&s.push("--model",r),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(s,["already exists","already registered"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var se=w("agent-manager"),Hc=(n,e,t,r,s,i,o)=>{switch(n){case"claude-code":{let a=s?{...xs(s),...Ps(s,o)}:void 0;return new Kt({cwd:t,...a&&Object.keys(a).length>0?{env:a}:{}})}case"codex":{let a=s?[...Ts(s),...Cs(s,o)]:[],c=s?Rs(s):void 0,l=!!s;return new Xt({cwd:t,...a.length>0?{extraArgs:a}:{},...c&&Object.keys(c).length>0?{env:c}:{},...l?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new dt({command:e,cwd:t,agentId:r,...i?{sessionName:st(i)}:{}})}};function Zs(n){return n==="claude-code"||n==="codex"}var Wc={path:"",version:"cloud-deployed"},jc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Jc=6e4,tn=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??Hc,this.createTimeoutMs=e.createTimeoutMs??Jc}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new h("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new en({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new h("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new h("IPC_BAD_REQUEST","framework required");let t=rt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let r=this.registry.get(e.agentId);if(r){if(r.framework!==e.framework)throw new h("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${r.framework})`);if(r.status==="error")se.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(u=>se.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else return se.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:r.agentId,workspace:r.workspace,framework:r.framework}}if(!t&&!this.config.frameworksCache?.[e.framework])throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);t&&Zs(e.framework)&&await zs(e.framework);let i=ae(e.agentId,this.paths),o=e.workspace??i.workspace,a=rt(e._meta),c=new AbortController,l=setTimeout(()=>c.abort(new h("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),d,f=!1;try{let u=()=>{if(c.signal.aborted)throw c.signal.reason instanceof Error?c.signal.reason:new h("AGENT_TIMEOUT","_agent/create aborted")};await jn(i.root,{recursive:!0}),await jn(o,{recursive:!0}),await jn(i.logs,{recursive:!0}),u(),await Me(o,e.framework,e.agentId,e.cozeIdentity),u();let p=await q(e.agentId,this.paths).catch(()=>null),m=ks({model:e.model??p?.model});if(d=new Yt({agentId:e.agentId,framework:e.framework,workspace:o,model:m.model??ne,deployType:a}),d.status="ok",p?.sessions){for(let[F,b]of Object.entries(p.sessions))d.sessions.set(F,{acpSessionId:b.acpSessionId,modelToken:b.modelToken,tokenGeneratedAt:b.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let C=Object.keys(p.sessions).length;C>0&&se.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:C})}this.registry.register(d),f=!0;let _={agentId:e.agentId,framework:e.framework,workspace:o,cozeIdentity:e.cozeIdentity,createdAt:p?.createdAt??Date.now(),sessions:p?.sessions??{},model:m.model};a==="cloud"&&(_.deployType="cloud"),p?.skills&&(_.skills=p.skills),p?.agentName&&(_.agentName=p.agentName),p?.description&&(_.description=p.description),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,o):se.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let v=e.initialSkills??[];if(v.length>0){let C=[..._.skills??[]],F=new Map(C.map((P,g)=>[P.skillId,g])),b=0;for(let P of v)try{let g=await Gn({agentId:e.agentId,workspace:o,framework:e.framework,skill:P});Hn(C,F,g),b++}catch(g){se.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:P.skillId,skillName:P.skillName,err:String(g)})}b>0&&(_.skills=C,se.info("initialSkills installed",{agentId:e.agentId,installed:b,requested:v.length}))}return await X(_,this.paths),se.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:a}),{ok:!0,agentId:e.agentId,workspace:o,framework:e.framework}}catch(u){throw se.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),f&&d&&(await d.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Gc(i.root,{recursive:!0,force:!0}).catch(p=>se.warn("rm agent dir failed (ignored)",{err:String(p)})),u instanceof h?u:new h("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}async spawnSessionDownstream(e,t,r,s){let o=this.config.frameworksCache?.[e.framework];if(!o)if(e.deployType==="cloud"&&Zs(e.framework))o=Wc;else throw new h("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let a=e.deployType==="cloud"?{model:e.model,modelToken:t}:void 0,c;e.framework==="openclaw"?c=await this.buildOpenclawDownstream({session:e,modelConfig:a,cloudSessionId:r,cozeEnv:s,command:o.path}):c=this.factory(e.framework,o.path,e.workspace,e.agentId,a,r,s);try{return await c.start(),await c.initialize(jc),c}catch(l){throw await c.stop("spawnSessionDownstream failed").catch(()=>{}),l instanceof h?l:new h("AGENT_SPAWN_FAILED",l instanceof Error?l.message:String(l),{cause:l})}}async buildOpenclawDownstream(e){let{session:t,modelConfig:r,cloudSessionId:s,cozeEnv:i,command:o}=e,a=st(s),c=await Ys(),l=r?As(r,i):null,d;if(l){let f=zn(s),p=l.models[0]?.id??ne,m=`${f}/${p}`;if(!this.ensuredProviders.has(m)){let _=this.getOpenclawConfig();await _.ensureProvider(f,l),await _.addModelToAllowlist(m),this.ensuredProviders.add(m)}d=m}return new dt({command:o,cwd:t.workspace,agentId:t.agentId,sessionName:a,...c?{gatewayToken:c}:{},...d?{slashModelOnStart:d}:{}})}async openclawRepair(e,t){let r=this.getOpenclawConfig();await r.deleteAgent(e),await r.ensureAgent(e,t)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let t=this.openclawConfigCache;for(let r of e.sessions.keys()){let s=zn(r),i=`${s}/${e.model}`;this.ensuredProviders.delete(i),await t.removeProvider(s),await t.removeModelFromAllowlist(i)}}};k();import{execFile as Vc}from"node:child_process";import{promisify as Qc}from"node:util";var Kc=Qc(Vc),me=w("coze-cli-installer"),ei="@coze/cli@0.1.3-alpha.89c42a",ti="https://bnpm.byted.org",Xc="coze",Yc=5e3,Zc=9e4,ni=1e4,ft=null,Jn=!1;async function ri(n,e={}){if(Jn)return;if(ft)return ft;let t=e.exec??Kc;return ft=(async()=>{try{let r=await el(Xc,t);if(r){me.info("coze-cli already on PATH, skip install + config + auth",{path:r}),Jn=!0;return}me.info("coze-cli install start",{package:ei,registry:ti});try{await t("npm",["i","-g",ei,"--registry",ti],{timeout:Zc,maxBuffer:10*1024*1024}),me.info("coze-cli install ok")}catch(s){me.warn("coze-cli install failed (skip subsequent steps)",{err:String(s)});return}if(n.env)try{await t("coze",["config","set","xTTEnv",n.env],{timeout:ni}),me.info("coze config set xTTEnv ok",{env:n.env})}catch(s){me.warn("coze config set failed (continue to auth login)",{err:String(s)})}try{await t("coze",["auth","login","--token",n.patToken],{timeout:ni}),me.info("coze auth login ok")}catch(s){me.warn("coze auth login failed",{err:String(s)});return}Jn=!0}finally{ft=null}})(),ft}async function el(n,e){let t=process.platform==="win32"?"where":"which";try{let{stdout:r}=await e(t,[n],{timeout:Yc});return r.split(`
|
|
94
|
-
`)[0]?.trim()||void 0}catch{return}}
|
|
95
|
-
`),
|
|
96
|
-
`)}return li.info("fs/read_text_file ok",{path:t,size:s.length}),{content:s}}async function fi(n,e){if(typeof n!="string"||n.length===0)throw new h("IPC_BAD_REQUEST","path must be a non-empty string");let[t,r]=await Promise.all([ci(ai(e)),ci(ai(n))]),s=ml(t,r);if(s.startsWith("..")||s===".."||s.startsWith(`..${_l}`))throw new h("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return r}async function ci(n){let e=[],t=n;for(;t!==Vn(t);)try{let r=await fl(t);return e.length?pl(r,...e.reverse()):r}catch{e.push(gl(t)),t=Vn(t)}return n}ge();k();var S=w("core"),yl=3e4,Sl=3e4,rn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Ue;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=oi(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(),S.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){S.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),S.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let t of this.registerHandlers)try{t(e.agentId)}catch(r){S.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(r)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&S.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,t,r){let s=r.downstream;s&&(s.onUpdate(i=>{r.loadingSession||this.forwardUpdate(e,i)}),s.onAgentRequest(i=>{this.handleAgentRequest(e,s,i)}),s.onExit((i,o)=>{S.info("session runtime exited",{agentId:e.agentId,cloudId:t,code:i,signal:o}),ut(r),r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId)}))}async handleFrame(e){if(Vt(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let t="id"in e&&e.id!==void 0?e.id:null,r=e.params?._meta?.cozeEnv;r&&(this.currentCozeEnv=r);try{if(e.method.startsWith("_agent/")){let s=this.extensions[e.method];if(!s){t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):S.warn("drop notification: extension not registered",{method:e.method});return}let i=await s(e,this);t!==null&&await this.upstream.send(Fe(t,i));return}if(e.method.startsWith("session/")){let s=await this.routeSessionMethod(e);t!==null&&await this.upstream.send(Fe(t,s));return}if(e.method==="initialize"){t!==null&&await this.upstream.send(Fe(t,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}t!==null?await this.sendError(t,R.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):S.warn("drop unknown notification",{method:e.method})}catch(s){S.error("handleFrame failed",{method:e.method,err:String(s)}),t!==null&&await this.upstream.send(ve(t,lt(s)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new h("IPC_BAD_REQUEST",`${e.method} requires params`);let t=e.params,r=t._meta?.cozeAgentId;if(!r)throw new h("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let s=this.agents.get(r);if(!s)throw this.disconnectedAgents.has(r)?new h("AGENT_DISCONNECTED",`agent ${r} has been disconnected; cloud must _agent/create to revive`):new h("AGENT_NOT_FOUND",`agent not found: ${r}`);let i=typeof t.sessionId=="string"?t.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!i)return this.dispatchSessionCall(s,e.method,t);let o=Date.now(),a=!1;try{let c=await s.getSessionQueue(i).enqueue(()=>this.dispatchSessionCall(s,e.method,t));return a=!0,c}finally{S.info("session call done",{agentId:s.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,t,r){e.lastActiveAt=Date.now();let{stripped:s}=gs(r);switch(t){case"session/new":{let i=El();return S.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:i}),{sessionId:i}}case"session/load":{let i=s;return S.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:i.sessionId}),{}}case"session/prompt":{let i=s,o=i.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new h("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=r._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);try{let l=await a.downstream.sessionPrompt({...i,sessionId:a.acpSessionId});return a.lastActiveAt=Date.now(),l}finally{e.activeTriggers.delete(a.acpSessionId),a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=s.sessionId;if(!o)throw new h("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new h("IPC_BAD_REQUEST",`session method not supported: ${t}`)}}async ensureRuntime(e,t){let r=e.sessions.get(t);if(r)return r;let i={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,t):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(t,i),await this.persistSessionMapping(e),i}async requestSessionToken(e,t){let r={sessionId:t,_meta:{cozeAgentId:e}};try{let s=await this.sendRequest(te.GEN_MODEL_TOKEN,r,Sl);if(!s?.modelToken)throw new h("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${t})`);return s.modelToken}catch(s){throw s instanceof h&&s.code==="MODEL_TOKEN_GEN_FAILED"?s:new h("MODEL_TOKEN_GEN_FAILED",s instanceof Error?s.message:String(s),{cause:s})}}async ensureDownstream(e,t,r){if(ut(r),r.downstream?.isAlive())return;if(!this.sessionSpawner)throw new h("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let s=await this.sessionSpawner(e,r.modelToken,t,this.currentCozeEnv);if(r.downstream=s,this.attachRuntimeHooks(e,t,r),r.acpSessionId){r.loadingSession=!0;try{await s.sessionLoad({sessionId:r.acpSessionId,cwd:e.workspace}),S.info("session restored via session/load",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId})}catch(i){S.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:t,acpId:r.acpSessionId,err:String(i)}),r.acpSessionId=void 0;let o=await s.sessionNew({cwd:e.workspace});r.acpSessionId=o.sessionId,await this.persistSessionMapping(e)}finally{r.loadingSession=!1}}else{let i=await s.sessionNew({cwd:e.workspace});r.acpSessionId=i.sessionId,await this.persistSessionMapping(e)}s.afterSessionEstablished&&r.acpSessionId&&await s.afterSessionEstablished(r.acpSessionId)}armIdleTimer(e,t,r){if(ut(r),this.isRuntimeBusy(e,r)){S.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:t});return}r.idleTimer=setTimeout(()=>{if(r.idleTimer=void 0,this.isRuntimeBusy(e,r)){S.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:t}),this.armIdleTimer(e,t,r);return}S.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:t});let s=r.downstream;r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId),s&&s.stop("idle timeout").catch(i=>S.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:t,err:String(i)}))},this.sessionIdleTimeoutMs),r.idleTimer.unref?.()}isRuntimeBusy(e,t){if(t.acpSessionId&&e.activeTriggers.has(t.acpSessionId))return!0;let r=t.downstream;if(!r)return!1;for(let s of this.pendingUpstream.values())if(s.downstream===r)return!0;return!1}forwardUpdate(e,t){let r=t.sessionId,s=this.reverseSessionId(e,r);if(!s){S.debug("drop update for unknown session",{agentId:e.agentId,acpId:r});return}let i=e.sessions.get(s);if(!i){S.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:s});return}if(vl(t)){S.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:r});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++i.replySeq},a=e.activeTriggers.get(r);a&&(o.cozeTriggerMsgId=a),this.upstream.send(jt("session/update",{...t,sessionId:s,_meta:o})).catch(c=>S.warn("forward update failed",{agentId:e.agentId,err:String(c)}))}handleAgentRequest(e,t,r){if(r.method==="session/request_permission"){this.forwardPermissionRequest(e,t,r);return}if(r.method==="fs/write_text_file"||r.method==="fs/read_text_file"){this.handleFsRpcRequest(e,t,r);return}S.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:r.method}),t.respondAgentRequestError(r.id,{code:R.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${r.method}`})}async handleFsRpcRequest(e,t,r){try{let s=e.workspace;if(r.method==="fs/write_text_file"){let i=r.params??{},o=await di(i,s);t.respondAgentRequest(r.id,o)}else{let i=r.params??{},o=await ui(i,s);t.respondAgentRequest(r.id,o)}}catch(s){S.warn("fs rpc handler failed",{agentId:e.agentId,method:r.method,err:String(s)}),t.respondAgentRequestError(r.id,lt(s))}}forwardPermissionRequest(e,t,r){let s=this.upstreamIds.next("session/request_permission"),i=r.params??{},a=i.sessionId,c=a?e.activeTriggers.get(a):void 0,l={cozeAgentId:e.agentId};c&&(l.cozeTriggerMsgId=c);let d=a?this.reverseSessionId(e,a):void 0,f={...i,...d?{sessionId:d}:{},_meta:l};this.pendingUpstream.set(s,{agentRequestId:r.id,agentId:e.agentId,downstream:t,method:r.method}),S.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:s,acpSessionId:a,cloudSessionId:d,toolCallId:i.toolCall?.toolCallId,options:i.options?.map(u=>({optionId:u.optionId,kind:u.kind,name:u.name}))}),this.upstream.send(ct(s,"session/request_permission",f)).catch(u=>{this.pendingUpstream.delete(s),S.error("forward permission request failed",{agentId:e.agentId,err:String(u)}),t.respondAgentRequestError(r.id,{code:R.INTERNAL_ERROR,message:`upstream send failed: ${String(u)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let t=this.pendingUpstream.get(e.id);if(t){this.pendingUpstream.delete(e.id),e.error?(S.info("upstream \u2192 permission response (error)",{agentId:t.agentId,upstreamId:e.id,method:t.method,error:e.error}),t.downstream.respondAgentRequestError(t.agentRequestId,e.error)):(S.info("upstream \u2192 permission response (result)",{agentId:t.agentId,upstreamId:e.id,method:t.method,result:e.result}),t.downstream.respondAgentRequest(t.agentRequestId,e.result));return}let r=this.pendingBridge.get(e.id);if(r){this.pendingBridge.delete(e.id),clearTimeout(r.timer),e.error?r.reject(new Jt(e.error)):r.resolve(e.result);return}S.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,t,r=yl){let s=this.upstreamIds.next(e);return new Promise((i,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(s),o(new h("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r);this.pendingBridge.set(s,{method:e,resolve:i,reject:o,timer:a}),this.upstream.send(ct(s,e,t)).catch(c=>{let l=this.pendingBridge.get(s);l&&(clearTimeout(l.timer),this.pendingBridge.delete(s)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let t=new Map;for(let[r,s]of e.sessions){let i={modelToken:s.modelToken,tokenGeneratedAt:s.tokenGeneratedAt};s.acpSessionId&&(i.acpSessionId=s.acpSessionId),t.set(r,i)}await Fn(e.agentId,t,this.paths)}catch(t){S.warn("persist session mapping failed",{agentId:e.agentId,err:String(t)})}}reverseSessionId(e,t){for(let[r,s]of e.sessions.entries())if(s.acpSessionId===t)return r}sendError(e,t,r){return this.upstream.send(ve(e,{code:t,message:r}))}};function El(){return wl(16).toString("hex")}function vl(n){let e=n.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let t=e.content;if(!t||typeof t!="object")return!1;let r=t;return r.type!=="text"||typeof r.text!="string"?!1:r.text.startsWith("Model metadata for `")}k();z();import{randomBytes as kl}from"node:crypto";import{chmod as Il,mkdir as xl,writeFile as hi}from"node:fs/promises";import{createServer as Tl}from"node:http";import{dirname as Rl}from"node:path";var Pl=1e6,Qn=w("ipc"),sn=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(t=>[`${t.method} ${t.path}`,t])),this.paths=e.paths??T()}async start(){this.token=kl(32).toString("hex");let e=Tl((r,s)=>{this.dispatch(r,s)});this.server=e,await new Promise((r,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>r())});let t=e.address();if(!t||typeof t!="object")throw new Error("failed to obtain IPC port");return this.port=t.port,await this.persistAuthFiles(),Qn.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((t,r)=>{e.close(s=>s?r(s):t())}),this.server=null)}async persistAuthFiles(){await xl(Rl(this.paths.portFile),{recursive:!0}),await hi(this.paths.portFile,String(this.port),"utf8"),await hi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Il(this.paths.tokenFile,384)}catch(e){Qn.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,t){if(e.headers.authorization!==`Bearer ${this.token}`){ht(t,401,{error:"unauthorized"});return}let s=`${e.method} ${(e.url??"").split("?")[0]}`,i=this.routes.get(s);if(!i){ht(t,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await Al(e)}catch(a){ht(t,400,{error:"invalid json",detail:String(a)});return}try{let a=await i.handler(o,e);ht(t,200,a??{ok:!0})}catch(a){Qn.error("IPC handler failed",{key:s,err:String(a)}),ht(t,500,{error:a instanceof Error?a.message:String(a)})}}};function ht(n,e,t){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(t))}async function Al(n){let e=[],t=0;for await(let s of n){let i=s;if(t+=i.length,t>Pl)throw new Error("body too large");e.push(i)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var vi="";function zl(n=""){let t=`${Date.now()}`,r=vi||(vi=Wl(n)),s=Math.random().toString(16).slice(-6);return"02"+t+r+s}function ql(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function Gl(n){return(Array(8).join("0")+parseInt(n,10).toString(2)).slice(-8)}function ki(n){return(Array(4).join("0")+parseInt(n,2).toString(16)).slice(-4)}function Hl(n){let e=n.split(/\./).map(s=>Gl(s)),t=[];return t[0]=ki(e[0]+e[1]),t[1]=ki(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",t[0],t[1]].join("")}function Wl(n){let e=/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/.test(n),t=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(n);return e?Hl(n):t?jl(n):"00000000000000000000000000000000"}function jl(n){let e="",t=[],r=0,s=0,i=!0,o="0000";if(n.indexOf("::")>-1){let a=n.split("::");for(let l=0;l<a.length;l++){let d=a[l];if(d.indexOf(":")>0){let f=d.split(":");i&&(r=f.length),s+=f.length;for(let u=0;u<f.length;u++)if(f[u].length!==4){let m=o.substring(0,4-f[u].length).concat(f[u]);t.push(m)}else t.push(f[u]);i=!1}else{if(d.length!==4){let u=o.substring(0,4-d.length).concat(d);t.push(u)}else t.push(d);i&&(r+=1),s+=1,i=!1}}let c="";for(let l=0;l<8-s;l++)c=c.concat(o);for(let l=0;l<t.length;l++)l===r&&(e=e.concat(c)),e=e.concat(t[l]);return e}{let a=n.split(":");for(let c=0;c<a.length;c++){let l=a[c];if(a[c].length!==4){let f=o.substring(0,4-a[c].length).concat(l);e=e.concat(f)}else e=e.concat(l)}return e}}function Jl(n,e){let t=n.key;t!==void 0&&(N(e,10),xe(e,t));let r=n.value;r!==void 0&&(N(e,18),xe(e,r))}function Vl(n){let e={};e:for(;!Bi(n);){let t=B(n);switch(t>>>3){case 0:break e;case 1:e.key=Ie(n,B(n));break;case 2:e.value=Ie(n,B(n));break;default:Di(n,7&t)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function Ni(n){let e=Mi();return Ql(n,e),td(e)}function Ql(n,e){let t=n.SeqID;t!==void 0&&(N(e,8),pt(e,t));let r=n.LogID;r!==void 0&&(N(e,16),pt(e,r));let s=n.service;s!==void 0&&(N(e,24),pt(e,nr(s)));let i=n.method;i!==void 0&&(N(e,32),pt(e,nr(i)));let o=n.headers;if(o!==void 0)for(let m of o){N(e,42);let _=Mi();Jl(m,_),N(e,_.limit),sd(e,_),Zl(_)}let a=n.payloadEncoding;a!==void 0&&(N(e,50),xe(e,a));let c=n.payloadType;c!==void 0&&(N(e,58),xe(e,c));let l=n.payload;l!==void 0&&(N(e,66),N(e,l.length),rd(e,l));let d=n.LogIDNew;d!==void 0&&(N(e,74),xe(e,d));let f=n.serverTiming;f!==void 0&&(N(e,82),xe(e,f));let u=n.msgID;u!==void 0&&(N(e,90),xe(e,u));let p=n.frameType;p!==void 0&&(N(e,96),pt(e,nr(p)))}function Kl(n){return Xl(ed(n))}function Xl(n){let e={};e:for(;!Bi(n);){let t=B(n);switch(t>>>3){case 0:break e;case 1:e.SeqID=xi(n,!0);break;case 2:e.LogID=xi(n,!0);break;case 3:e.service=B(n);break;case 4:e.method=B(n);break;case 5:{let r=Yl(n);(e.headers||(e.headers=[])).push(Vl(n)),n.limit=r;break}case 6:e.payloadEncoding=Ie(n,B(n));break;case 7:e.payloadType=Ie(n,B(n));break;case 8:e.payload=nd(n,B(n));break;case 9:e.LogIDNew=Ie(n,B(n));break;case 10:e.serverTiming=Ie(n,B(n));break;case 11:e.msgID=Ie(n,B(n));break;case 12:e.frameType=B(n);break;default:Di(n,7&t)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function Yl(n){let e=B(n),t=n.limit;return n.limit=n.offset+e,t}function Di(n,e){switch(e){case 0:for(;128&j(n););break;case 2:rr(n,B(n));break;case 5:rr(n,4);break;case 1:rr(n,8);break;default:throw new Error("Unimplemented type: "+e)}}function nr(n){return n|=0,{low:n,high:n>>31,unsigned:n>=0}}var Li=[];function Mi(){let n=Li.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function Zl(n){Li.push(n)}function ed(n){return{bytes:n,offset:0,limit:n.length}}function td(n){let e=n.bytes,t=n.limit;return e.length===t?e:e.subarray(0,t)}function rr(n,e){if(n.offset+e>n.limit)throw new Error("Skip past limit");n.offset+=e}function Bi(n){return n.offset>=n.limit}function wt(n,e){let t=n.bytes,r=n.offset,s=n.limit,i=r+e;if(i>t.length){let o=new Uint8Array(2*i);o.set(t),n.bytes=o}return n.offset=i,i>s&&(n.limit=i),r}function Er(n,e){let t=n.offset;if(t+e>n.limit)throw new Error("Read past limit");return n.offset+=e,t}function nd(n,e){let t=Er(n,e);return n.bytes.subarray(t,t+e)}function rd(n,e){let t=wt(n,e.length);n.bytes.set(e,t)}function Ie(n,e){let t=Er(n,e),r=String.fromCharCode,s=n.bytes,i="\uFFFD",o="";for(let a=0;a<e;a++){let c=s[a+t],l,d,f,u;(128&c)===0?o+=r(c):(224&c)===192?a+1>=e?o+=i:(l=s[a+t+1],(192&l)!==128?o+=i:(u=(31&c)<<6|63&l,u<128?o+=i:(o+=r(u),a++))):(240&c)==224?a+2>=e?o+=i:(l=s[a+t+1],d=s[a+t+2],((l|d<<8)&49344)!==32896?o+=i:(u=(15&c)<<12|(63&l)<<6|63&d,u<2048||u>=55296&&u<=57343?o+=i:(o+=r(u),a+=2))):(248&c)==240?a+3>=e?o+=i:(l=s[a+t+1],d=s[a+t+2],f=s[a+t+3],((l|d<<8|f<<16)&12632256)!==8421504?o+=i:(u=(7&c)<<18|(63&l)<<12|(63&d)<<6|63&f,u<65536||u>1114111?o+=i:(u-=65536,o+=r((u>>10)+55296,(1023&u)+56320),a+=3))):o+=i}return o}function xe(n,e){let t=e.length,r=0;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),r+=a<128?1:a<2048?2:a<65536?3:4}N(n,r);let s=wt(n,r),i=n.bytes;for(let o=0;o<t;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<t&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?i[s++]=a:(a<2048?i[s++]=a>>6&31|192:(a<65536?i[s++]=a>>12&15|224:(i[s++]=a>>18&7|240,i[s++]=a>>12&63|128),i[s++]=a>>6&63|128),i[s++]=63&a|128)}}function sd(n,e){let t=wt(n,e.limit),r=n.bytes,s=e.bytes;for(let i=0,o=e.limit;i<o;i++)r[i+t]=s[i]}function j(n){return n.bytes[Er(n,1)]}function Ii(n,e){let t=wt(n,1);n.bytes[t]=e}function B(n){let e=0,t=0,r;do r=j(n),e<32&&(t|=(127&r)<<e),e+=7;while(128&r);return t}function N(n,e){for(e>>>=0;e>=128;)Ii(n,127&e|128),e>>>=7;Ii(n,e)}function xi(n,e){let t=0,r=0,s=0,i;return i=j(n),t=127&i,128&i&&(i=j(n),t|=(127&i)<<7,128&i&&(i=j(n),t|=(127&i)<<14,128&i&&(i=j(n),t|=(127&i)<<21,128&i&&(i=j(n),r=127&i,128&i&&(i=j(n),r|=(127&i)<<7,128&i&&(i=j(n),r|=(127&i)<<14,128&i&&(i=j(n),r|=(127&i)<<21,128&i&&(i=j(n),s=127&i,128&i&&(i=j(n),s|=(127&i)<<7))))))))),{low:t|r<<28,high:r>>>4|s<<24,unsigned:e}}function pt(n,e){let t=e.low>>>0,r=(e.low>>>28|e.high<<4)>>>0,s=e.high>>>24,i=s===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:s<128?9:10,o=wt(n,i),a=n.bytes;switch(i){case 10:a[o+9]=s>>>7&1;case 9:a[o+8]=i!==9?128|s:127&s;case 8:a[o+7]=i!==8?r>>>21|128:r>>>21&127;case 7:a[o+6]=i!==7?r>>>14|128:r>>>14&127;case 6:a[o+5]=i!==6?r>>>7|128:r>>>7&127;case 5:a[o+4]=i!==5?128|r:127&r;case 4:a[o+3]=i!==4?t>>>21|128:t>>>21&127;case 3:a[o+2]=i!==3?t>>>14|128:t>>>14&127;case 2:a[o+1]=i!==2?t>>>7|128:t>>>7&127;case 1:a[o]=i!==1?128|t:127&t}}function id(n){return Kl(n)}function Ti(n){return Ni(n)}var Ri=65536,od="\0\0\0\0\0\0\0\0",Ge=Ri*Ri,Fi=Ge*Ge,Pi=Fi/2,_e=String.prototype.charCodeAt,G=class n{constructor(e,t,r){this.isLong=!0,this.low=0|e,this.high=0|t,this.unsigned=!!r}static isLong(e){return e&&e.isLong===!0}static fromBits(e,t,r){return new n(e,t,r)}static fromBytes(e,t,r){return r?n.fromBytesLE(e,t):n.fromBytesBE(e,t)}static fromBytesLE(e,t){return new n(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)}static fromBytesBE(e,t){return new n(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}static fromHash(e){return e===od?Ai:new n((_e.call(e,0)|_e.call(e,1)<<8|_e.call(e,2)<<16|_e.call(e,3)<<24)>>>0,(_e.call(e,4)|_e.call(e,5)<<8|_e.call(e,6)<<16|_e.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?ad:Ai;if(t){if(e>=Fi)return ld}else{if(e<=-Pi)return dd;if(e+1>=Pi)return cd}return n.fromBits(e%Ge|0,e/Ge|0,t)}toNumber(){return this.unsigned?(this.high>>>0)*Ge+(this.low>>>0):this.high*Ge+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){n.isLong(e)||(e=n.fromNumber(e));let t=this.high>>>16,r=65535&this.high,s=this.low>>>16,i=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,l=65535&e.low,d=0,f=0,u=0,p=0;return p+=i+l,u+=p>>>16,p&=65535,u+=s+c,f+=u>>>16,u&=65535,f+=r+a,d+=f>>>16,f&=65535,d+=t+o,d&=65535,n.fromBits(u<<16|p,d<<16|f,this.unsigned)}equals(e){return n.isLong(e)||(e=n.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?n.fromBits(0,0,this.unsigned):this.low===-1?n.fromBits(0,this.high+1,this.unsigned):n.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]}},Ai=new G(0,0,!1),ad=new G(0,0,!0),cd=G.fromBits(-1,2147483647,!1),ld=G.fromBits(-1,-1,!0),dd=G.fromBits(0,-2147483648,!1),ke=(function(n){return n[n.NATIVE_ERROR=5001]="NATIVE_ERROR",n[n.CONNECTING_ERROR=5002]="CONNECTING_ERROR",n[n.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",n[n.MESSAGE_ERROR=5004]="MESSAGE_ERROR",n[n.OPEN_ERROR=5005]="OPEN_ERROR",n})({}),Te=class{constructor(e){this.type=e,this.target=null}},ir=class extends Te{constructor(e,t){super(e),this.message=t&&t.message||null}},or=class extends Te{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}},ar=class extends Te{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}},cr=class extends Te{constructor(e,t){super(e),this.data=t&&t.data||null}},lr=class extends cr{constructor(e,t){super(e),this.data=t&&t.data||null,this.message=t&&t.message||null}},dr=class extends Te{constructor(e,t){super(e),this.data=t&&t.data||null}};function Y(n,{message:e,code:t,error:r}){return new or(n,{message:e,code:t,error:r})}function ie(n,{code:e,reason:t,wasClean:r,willReconnect:s}){return new ar(n,{code:e,reason:t,wasClean:r,willReconnect:s})}function ud(n,{data:e,message:t}){return new lr(n,{data:e,message:t})}function fd(n,{data:e}){return new dr(n,{data:e})}function Ci(n,{message:e}){return new ir(n,{message:e})}var on=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()}},We=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",Re=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",yt=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",mt=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",hd=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,_t=class{constructor(){this._listeners={}}emit(e,...t){let r=this._listeners[e];if(r)r.slice().forEach(s=>s.fn.apply(s.ctx,t));else if(e==="error"&&!this.onerror){let s=t.length&&t[0];if(s instanceof Error)throw s;let i=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw i.context=s,s}return this}off(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=null;else{let r=this._listeners[e];if(r)for(let s=0;s<r.length;)r[s].fn===t?r.splice(s,1):++s}return this}on(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this}},ur=class extends _t{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,t,r){super(),this._socket=null,yt&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),Re&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:t,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let t=Y("error",{message:this._formatErrorMessage(e)});this.emit("error",t);let r=ie("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",fd("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",ie("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",ud("message",{...e}))}),this._socket.onError(e=>{this.emit("error",Y("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let t=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:t,fail:r=>{this.emit("error",Y("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:t=>{this.emit("error",Y("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 gd(n,e){if(e)return new e(n.url,n.protocol);if(yt||Re)return new ur(n.url,n.protocol,n.headers);if((We||mt)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(n.url,n.protocols)}function pd(n){return!!(n||yt&&wx.connectSocket||Re&&tt.connectSocket||(We||mt)&&typeof WebSocket<"u"&&WebSocket)}function Oi(n,e,t){let r=-1;async function s(i){return i<=r?Promise.reject(new Error("next() called multiple times in process")):(r=i,i===t.length?Promise.resolve():t[i].bind(n)(e,s.bind(null,i+1)))}s(0)}function Ui(n){let e=0,t=0;for(let r=0;r<n.length;++r)t=n.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(64512&t)===55296&&(64512&n.charCodeAt(r+1))===56320?(++r,e+=4):e+=3;return e}function $i(n,e,t){if(t-e<1)return"";let r="";for(let s=e;s<t;){let i=n[s++];if(i<=127)r+=String.fromCharCode(i);else if(i>=192&&i<224)r+=String.fromCharCode((31&i)<<6|63&n[s++]);else if(i>=224&&i<240)r+=String.fromCharCode((15&i)<<12|(63&n[s++])<<6|63&n[s++]);else if(i>=240){let o=((7&i)<<18|(63&n[s++])<<12|(63&n[s++])<<6|63&n[s++])-65536;r+=String.fromCharCode(55296+(o>>10)),r+=String.fromCharCode(56320+(1023&o))}}return r}function fr(n,e,t){let r=t,s,i;for(let o=0;o<n.length;++o)s=n.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=63&s|128):(64512&s)===55296&&(64512&(i=n.charCodeAt(o+1)))===56320?(s=65536+((1023&s)<<10)+(1023&i),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=63&s|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=63&s|128);return t-r}async function zi(n){if(typeof n=="string"){let e=new Uint8Array(Ui(n));return fr(n,e,0),e}return n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function md(n){try{return typeof n!="string"&&(n instanceof ArrayBuffer||n.buffer&&n.buffer instanceof ArrayBuffer)||typeof n!="string"?"":(JSON.parse(n),"application/json")}catch{return typeof n=="string"?"text/plain;charset=utf-8":""}}var _d=(n,e)=>{switch(n){case"boe":case"ppe":return{[`x-use-${n}`]:1,"x-tt-env":e};default:return{}}},hr=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 wd(n){return new Promise(e=>{if(!We)return e("unknown reason");try{let t=document.createElement("script");window.frontierJSONP=r=>{document.body.removeChild(t),window.frontierJSONP=void 0,e(r&&r.msg||"unknown reason")},t.type="text/javascript",t.src=n.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(t)}catch{document.body.removeChild(t)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function we(n,e,t){return!!n?.find(r=>r.key===e&&r.value===t)}function He(n,e){return n?.find(t=>t.key===e)?.value}var sr=null;async function yd(){return sr||(sr=Promise.resolve().then(()=>(Ei(),Si))),sr}var gr=class extends _t{constructor(e,t){super(),this._dbName=e,this._keyPath=t,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,t=this._keyPath;this._initPromise=(async()=>{let{openDB:r}=await yd();this._qosDB=await r(`frontier_${e}`,1,{upgrade(s){s.createObjectStore(e,{keyPath:t})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(t){console.log(t)}}async set(e,t){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(t){console.log(t)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},pr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getItem(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getItem(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getItem(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getItem(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},mr=class{constructor(e,t){this._DBName=e,this._pathKey=t,this._qosDB=Re?tt:yt?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let t=this._qosDB.getStorageSync(this._prefix);return JSON.parse(t||"{}")[e]}async set(e,t){let r=this._qosDB.getStorageSync(this._prefix),s=JSON.parse(r||"{}");return s[t||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(s)),t||e[this._pathKey]}async del(e){let t=this._qosDB.getStorageSync(this._prefix),r=JSON.parse(t||"{}");return r[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.keys(t)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),t=JSON.parse(e||"{}");return Object.values(t)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function qi(n,e){if(Re||Re)return new mr(n,e);if((We||mt)&&typeof indexedDB<"u")return new gr(n,e);if((We||mt)&&typeof localStorage<"u")return new pr(n,e);throw new Error("init QoSDB failed")}var _r=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=qi("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:r})=>r<Date.now()).forEach(r=>{this._qosDB?.del(r.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,t){return this._qosDB?.set({message_id:e,timestamp:t})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function vr(n){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let t=we(n.message.headers,"x_frontier_qos","2"),r=t&&we(n.message.headers,"x_frontier_qos_ack","1"),s=t&&we(n.message.headers,"x_frontier_is_ack","1"),i=s?He(n.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:t,isQoSAck:r,isAckCleanupMessage:s,ackMsgIds:i}}async function Gi(){return this._QoSManager||(this._QoSManager=new _r),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function Sd(n,e){let{enableAutoAck:t}=this._options,r=we(n.message.headers,"need_ack","1"),s=we(n.message.headers,"is_ack","1"),i=vr.call(this,n);if(t&&r){let{SeqID:o,LogID:a,service:c,LogIDNew:l,method:d}=n.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:l,service:c,method:d,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:l||""},{key:"ack_code",value:"0"}]})}s&&!i.isQoSAck&&this._dispatchAckMessageEvent(n),e()}async function Ed(n,e){this._debug("received",n.message),e()}async function vd(n,e){let t=id(await zi(n.data));try{if(t.payload instanceof Uint8Array){let r=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},s=t.payloadEncoding?t.payloadEncoding.replace(/\s/g,"").toLowerCase():"",i=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=t.payloadType?t.payloadType.replace(/\s/g,"").toLowerCase():"",a=i.force?i.type:o||i.type,c=r.force?r.encoding:s||r.encoding,l=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],d=["none_none","binary"];this._options.enableTransformTextPayload&&l.includes(a)&&(!c||d.includes(c))?t.textPayload=$i(t.payload,0,t.payload.byteLength):t.textPayload=""}else t.textPayload=""}catch(r){t.textPayload="",console.log(r)}n.message=t,e()}function kd(n,e,t){let r=t||8192,s=r>>>1,i=null,o=r;return function(a){if(a<1||a>s)return n(a);o+a>r&&(i=n(r),o=0);let c=e.call(i,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var Id=4294967295;function xd(n,e,t){if(t>Id)throw new Error("integer too large");let r=3;for(;r>=0;){let s=255&t;yr(s,n,e+r),t>>>=8,r--}return e+4}function Td(n,e){let t=0,r=e,s=e+4;for(;r<s;){let{value:i,offset:o}=wr(n,r);r=o,t=t<<8>>>0,t+=i}return{value:t,offset:s}}function Rd(n,e,t){return n?n.length<40?fr(n,e,t)+t:e.utf8Write?e.utf8Write(n,t)+t:e.write?e.write(n,t)+t:fr(n,e,t)+t:t}function Pd(n,e){let t=new G(n[e+4]<<24|n[e+5]<<16|n[e+6]<<8|n[e+7],n[e+0]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3],!0);return e+=8,{value:t,offset:e+8}}function Ad(n,e,t){let r=n.low,s=n.high;return e[t]=s>>>24,e[t+1]=s>>>16&255,e[t+2]=s>>>8&255,e[t+3]=255&s,e[t+4]=r>>>24,e[t+5]=r>>>16&255,e[t+6]=r>>>8&255,e[t+7]=255&r,t+=8,t}function wr(n,e){return n.readUInt8?{value:n.readUInt8(e),offset:e+1}:{value:255&n[e],offset:e+1}}function yr(n,e,t){return e.writeUint8?e.writeUint8(n,t):e[t]=255&n,t+1}var Cd=function(n){return new Uint8Array(n)},Od=typeof Buffer<"u"?Buffer.allocUnsafe:kd(Cd,Uint8Array.prototype.subarray),bd=16,kr=32;function Nd(n){let e=0,t={};for(let r=0;r<n.length;r++)t[n[r].cursor_name]=Ui(n[r].cursor_name),e+=14+t[n[r].cursor_name];return[e,t]}function bi(n,e,t){let[r,s]=Nd(n),i=Od(r),o=0;return n.forEach(a=>{console.log("cursor.service",a,a.service),o=yr(0,i,o),console.log("header",o),o=xd(i,o,a.service||0),console.log("service",o),o=yr(s[a.cursor_name],i,o),console.log("service-name",o),o=Rd(a.cursor_name,i,o),console.log("name",o),o=Ad(G.fromNumber(a.cursor||e),i,o),console.log("curvalue",o)}),{frameType:kr,headers:[{key:"cursor_file_name",value:t}],payload:i}}function Dd(n){let e=0,t=[];for(;e<n.byteLength;){let{offset:r}=wr(n,e);e=r;let s={cursor_name:"",cursor:0,service:0},{value:i,offset:o}=Td(n,e);s.service=i,e=o;let{value:a,offset:c}=wr(n,e);e=c,s.cursor_name=$i(n,e,e+a),e+=a;let{value:l,offset:d}=Pd(n,e);s.cursor=l.toNumber(),e=d,t.push(s)}return t}function Ld(){return{frameType:kr,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var Sr=class{constructor(e,t,r){this._cursorNameSpace=e,this._cursorFileName=t,this._messageStrategy=r,this._qosDB=qi(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?bi(t,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return t&&t.length?bi(t,0,this._cursorFileName):Ld()}}async set(e,t,r){return console.log("setdb",e,t,r),this._qosDB.set({cursor_name:e,cursor:t,service:r})}async setCursors(e){let t=Dd(e);for(let r of t)console.log("setcursor",t),await this._qosDB.set(r)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},Md="__x_msg_qos__";async function Hi(n){if(!this._options.enableQoS)return null;let{aID:e,fpID:t,messageStrategy:r}=this._options,s=n||Md;try{return this._cursorManager?n&&this._cursorManager.updateCursorFileName(n):this._cursorManager=new Sr(`${t}_${e}_${s}`,s,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function Bd(n,e){let t=we(n.message.headers,"code","-1"),r=we(n.message.headers,"is_ack","1"),s=He(n.message.headers,"x_frontier_msgid"),i=Number(He(n.message.headers,"x_frontier_ttl"))||0,o=vr.call(this,n),a=we(n.message.headers,"x-msg-qos","2"),c=He(n.message.headers,"x-msg-cursor_name"),l=Number(He(n.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Gi.call(this):null;if(n.message.service>0&&r&&!t||n.message.service>0){if(s&&o.isQoSMessage&&d)return await d.get(s)||(this._dispatchMessageEvent(n),await d.set(s,Date.now()+i)),e();if(a){let f=await Hi.call(this);if(!f)return this._dispatchMessageEvent(n),e();let u=await f.get(c)??-1;if(u<l)this._dispatchMessageEvent(n),f.set(c,l,n.message.service);else throw new Error(`recevied message cursor ${l} larger than local cursor ${u}`);return e()}return this._dispatchMessageEvent(n),e()}}async function Fd(n,e){let t=vr.call(this,n);if(!t.isQoSMessage)return e();let r=await Gi.call(this);if(t.isAckCleanupMessage&&t.ackMsgIds.length)for(let s of t.ackMsgIds)await r.del(s);e()}async function Ud(n,e){let t=n.message.frameType===bd,r=n.message.frameType===kr;if(!t&&!r)return e();let s=He(n.message.headers,"cursor_file_name");if(!s)return e();let i=await Hi.call(this,s);if(!i)return e();if(t){let o=await i.getCursors(),a={frameType:o?.frameType,SeqID:G.fromNumber(this._seqId++),LogID:G.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Ni(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=n.message.payload;o&&i.setCursors(o)}}var $d=async function(n,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},zd=async function(n,e){let t=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${t}`),e()},qd=async function(n,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:t}=this._options;this._endpointManager?.resetEndpointConfig();for(let s=0;s<this._messageQueue.length;s++){let i=this._messageQueue[s];if(this._ws.readyState===this.OPEN&&i!==null)this._ws&&this._ws.send(i),this._messageQueue[s]=null;else break}this._messageQueue=this._messageQueue.filter(s=>!!s),this._pingPongTimeoutId=setTimeout(()=>this._ping(),t),this._dispatchOpenEvent(n),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r} success`),e()},an=class extends _t{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=We,this._isNode=hd,this._isMiniTT=Re,this._isMiniWX=yt,this._isWorker=mt,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{Oi(this,i,[$d,qd,zd])}catch(o){let a=Y("error",{message:o.message,code:ke.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{Oi(this,i,[vd,Sd,Fd,Ud,Bd,Ed])}catch(c){let l=Y("error",{message:c.message,code:ke.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(l)}},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(Y("error",{message:c,code:ke.MAX_RETRIES_ERROR,error:i}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Y("error",{message:i.message,code:ke.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(ie("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(ie("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 wd(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(ie("close",{code:i.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Y("error",{message:l,code:ke.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(i.code!==1e3&&!i.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ie("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:ql,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:t,ws:r}=e,s=Array.isArray(t)?t:typeof t=="string"?[t]:[];if(!s||s.length===0)throw new Error("please provide valid url");if(!pd(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new on(s,this._options.maxRetries),this._pingLossCounter=new hr(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=Ci("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:t,deviceID:r,bddID:s,ttwID:i,accessKey:o,aID:a,customParams:c={},enableAutoAck:l,enableQoS:d,QoSLevel:f,env:u}=this._options,p,m,_;this._isBrowser||this._isMiniWX||this._isMiniTT?(p=location&&location.protocol=="https:"?"wss://":"ws://",m=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_=/^wss(.*:\/\/)/.test(e)?e:`${p}${m}`):(p="wss://",m=e.replace(/(^http)((?:[s]*:\/\/))/,""),_=/(^ws)((?:[s]*:\/\/))/.test(m)?m:`${p}${m}`);let v=s?"bd_did":i?"ttwid":"device_id",C=s||i||r;if(!C||!v)throw new Error("please provide bddID, deviceID or ttwID");let F=typeof c=="function"?await c():c,b=u?_d(u.xUseEnv,u.xTTEnv):{},P=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:t,aid:a,[v]:C,xsack:l?1:0,xaack:l?1:0,xsqos:d?1:0,qos_level:d?f:void 0,qos_sdk_version:2,...b},F),g=Object.keys(P).reduce((E,I)=>P[I]!==void 0?`${E}${E?"&":"?"}${I}=${P[I]}`: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=Y("error",{message:a,code:ke.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(Y("error",{message:a,code:ke.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=Ci("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(s)}let r=this._endpointManager?.getCurrentEndpointTriesCount()||0;r>1&&await this._wait(r-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=gd({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),t)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:t,maxReconnectInterval:r,reconnectIntervalGrowFactor:s}=this._options,i=t*Math.pow(s,e-1);return i>r?r:i}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(t=>{setTimeout(t,this._getIntervalValue(e))})}_disconnect(e=1e3,t="",r=!1){this._ws&&this._destroyWebSocket(e,t,r)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let t=Ti(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(t),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,t=""){try{this._ws&&this._ws.close(e,t)}catch{}}_destroyWebSocket(e=1e3,t="",r=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,t),this._connectLock=!1,r&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let i=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ie("close",{code:1006,reason:`connect ${i} timeout, max retries reached`,wasClean:!0}))}else{let i=this._options.reconnectInterceptor(e,t);this._dispatchCloseEvent(ie("close",{code:e,reason:t,wasClean:!0,willReconnect:i})),i&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(ie("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(ie("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((t,r)=>(t+=r&&r.byteLength||0,t),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,t){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,t)}async send(e,t){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let r=await zi(e),s=md(e),{method:i=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:l=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:f=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?zl(this._options.logIDNewConfig.userIp):""}=t||{};if(!o)throw new Error("please provide a valid service");let u={SeqID:G.fromNumber(this._seqId++),LogID:G.fromNumber(a),service:o,method:i,headers:c,payloadEncoding:l instanceof Object?l.encoding?l.encoding:"":l,payloadType:d instanceof Object?d.type?d.type:s:d||s,payload:r,LogIDNew:f},p=Ti(u);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(p),this._debug("sent",u)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(p),this._debug("enqueue",u)):(this._messageQueue.shift(),this._messageQueue.push(p)),{seqID:this._seqId,logID:a,logIDNew:f}}async reconnect(e){let{url:t}=e||{},r=Array.isArray(t)?t:typeof t=="string"?[t]:[];e&&Object.assign(this._options,e),r&&r.length?this._endpointManager=new on(r,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,t){this.on(e,t)}dispatchEvent(e){let{type:t}=e;this.emit(t,e)}removeEventListener(e,t){this.off(e,t)}pingOnce(){return new Promise((e,t)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let r=()=>{e("success"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)},s=()=>{t("timeout"),this.off("ping_once_success",r),this.off("ping_once_timeout",s)};this.on("ping_once_success",r),this.on("ping_once_timeout",s),this._ping()})}};var lf=he($o(),1),df=he(mn(),1),uf=he(Ve(),1),ff=he(Dr(),1),hf=he(Br(),1),gf=he(Gr(),1),Qo=he(Sn(),1),pf=he(Vo(),1);var Ko=Qo.default;k();var D=w("upstream.frontier"),Yo="application/json",Zo="none",vn=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:_s,...Bt(this.opts.ppeOverride)};class t extends Ko{constructor(a){super(a,ms,{headers:e})}send(a,...c){if(fs("debug"))try{let l;typeof a=="string"?l=Buffer.from(a,"utf8"):a instanceof Buffer?l=a:a instanceof ArrayBuffer?l=new Uint8Array(a):ArrayBuffer.isView(a)?l=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):l=new Uint8Array(0);let d=Buffer.from(l.slice(0,128)).toString("hex");D.debug("WS raw frame out",{bytes:l.byteLength,headHex:d})}catch(l){D.warn("WS raw frame dump failed",{err:String(l)})}super.send(a,...c)}}let r=Ss(this.opts.urlOverride),s={url:r,ws:t,fpID:ps,aID:Mt,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Yo,force:!0},payloadEncoding:{encoding:Zo,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},i=new an(s);i.onopen=()=>{this.opened=!0,this.openCount+=1;let o=this.openCount===1;D.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:o,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:o})).catch(a=>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(r){D.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let t=this.fws;if(!t)throw new h("UPSTREAM_DISCONNECTED","frontier upstream not started");let r=JSON.stringify(e),s=e;ea(s)||D.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:r.length});try{await t.send(r,{service:33555712,method:1,payloadType:Yo,payloadEncoding:Zo})}catch(o){throw D.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(o)}),new h("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(o)}`,{cause:o})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let t=e.message?.service;if(t!==33555712){D.debug("drop non-adapter frontier frame",{service:t});return}let r=yf(e);if(!r){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:r.length});return}let s;try{s=JSON.parse(r)}catch(o){D.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let i=s;ea(i)||D.info("frontier frame in",{logid:wf(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:i.id,method:i.method,body:_f(r)}),Promise.resolve(this.handler(s)).catch(o=>D.warn("frontier frame handler threw",{err:String(o)}))}};function ea(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}var ta=2e3;function _f(n){return n.length<=ta?n:`${n.slice(0,ta)}...<truncated, total ${n.length} chars>`}function wf(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function yf(n){let e=n.message;if(e?.textPayload)return e.textPayload;let t=e?.payload;if(!t)return null;try{return Buffer.from(t).toString("utf8")}catch{return null}}k();var Wr=w("upstream.switchable"),kn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,t){if(this.inner===e)return;Wr.info("swap upstream",{reason:t});let r=this.inner;this.inner=e,this.handler&&e.onFrame(this.handler),this.connectHandler&&e.onConnect&&e.onConnect(this.connectHandler);try{await e.start()}catch(s){throw Wr.error("swap target start failed, reverting",{err:String(s)}),this.inner=r,s}await r.stop(t??"swapped").catch(s=>Wr.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 jr=w("upstream"),Rt=class{handler=null;async start(){jr.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){jr.info("NoopUpstream stopped",{reason:e})}async send(e){jr.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();z();k();z();import{execSync as Sf}from"node:child_process";import{readFileSync as na,unlinkSync as Ef}from"node:fs";import{mkdir as vf,readFile as ra,unlink as sa,writeFile as kf}from"node:fs/promises";import{dirname as If}from"node:path";var xf=w("single-instance"),In=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??T().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(xf.warn("removing stale pid file",{stalePid:e}),await sa(this.pidFile).catch(()=>{})),await vf(If(this.pidFile),{recursive:!0}),await kf(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await ra(this.pidFile,"utf8")).trim()===String(process.pid)&&await sa(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await ra(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=na(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(t.includes("coze-bridge-daemon")||t.includes("lib/index.js"))}catch{}try{let t=Sf(`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{na(this.pidFile,"utf8").trim()===String(process.pid)&&Ef(this.pidFile)}catch{}})}};var y=w("daemon"),Tf="coze-bridge-daemon";async function aa(){let n=new In({processTitle:Tf}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let t=await nn(),r=t??{};Bn({pid:process.pid}),y.info(t?"loaded bridge config":"initialized bridge config");try{let g=new ze;r.frameworksCache=await g.detectAll(),y.info("refreshed frameworks_cache",{detected:Object.keys(r.frameworksCache)})}catch(g){y.warn("framework detection failed",{err:String(g)})}await qe(r);let s=new kn(new Rt),i=T(),o=null,a=new rn({upstream:s,paths:i,bridgeConfig:r,sessionSpawner:async(g,E,I,Q)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(g,E,I,Q)}});await Pf(i,a);let c=new tn({paths:i,config:r,registry:a});o=c;let l,d,f=null,u=null;a.registerExtension("_agent/create",async g=>c.createAgent(g.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let p={},m=new Ut({agents:a.agents,disposeAndMarkDisconnected:async(g,E)=>{let I=a.agents.get(g);I&&(await c.cleanupOpenclawSessionProviders(I).catch(Q=>y.warn("cleanup openclaw providers failed (ignored)",{agentId:g,err:String(Q)})),await I.dispose(`disconnect: ${E}`).catch(Q=>y.warn("dispose during disconnect failed (ignored)",{agentId:g,err:String(Q)})),I.status="disconnected",a.unregister(g)),a.disconnectedAgents.add(g)},detailSyncer:async g=>{if(!p.ref)throw new Error("agent-detail-sync not initialized yet");await p.ref.syncOne(g)},openclawRepair:async(g,E)=>{await c.openclawRepair(g,E)}});a.registerExtension("_agent/listSkills",g=>m.listSkills(g.params)),a.registerExtension("_agent/addSkills",g=>m.addSkills(g.params)),a.registerExtension("_agent/removeSkills",g=>m.removeSkills(g.params)),a.registerExtension("_agent/getFileTree",g=>m.getFileTree(g.params)),a.registerExtension("_agent/getFileContent",g=>m.getFileContent(g.params)),a.registerExtension("_agent/update",g=>m.updateAgent(g.params)),a.registerExtension("_agent/disconnect",g=>m.disconnectAgent(g.params)),a.registerExtension("_agent/switchModel",g=>m.switchModel(g.params)),a.registerExtension("_agent/reset",g=>m.resetAgent(g.params)),a.registerExtension("_agent/repair",g=>m.repairAgent(g.params));let _=new Lt({paths:i,handlers:m,sendDetail:g=>a.sendRequest("_agent/detail",g)});p.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 v=new sn({paths:i,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:f??"",frameworksCache:r.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async g=>{let E=g,I=E?.privatecode,Q=E?.pairing_code;if(!I||!Q)throw new h("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ne=Ft(E.env),nt=E.handshake_url,bn=E.frontier_url,Nn=Rf(E.env,nt,bn),ss=!!l&&l!==I,is=d!==void 0&&d!==Nn,os=ss||is;if(os){y.warn("pair config switched, resetting agents",{pcChanged:ss,envChanged:is,previousPc:l?ia(l):"",nextPc:ia(I),previousEnvKey:d??"",nextEnvKey:Nn});for(let U of[...a.agents.values()])await U.dispose("pair config switch").catch(()=>{}),a.agents.delete(U.agentId);await s.swap(new Rt,"pair switch").catch(()=>{})}let as=await vs({privatecode:I,...nt?{endpoint:nt}:{},ppeOverride:Ne});f=as.deviceId,Bn({deviceId:f,pid:process.pid}),ri({patToken:I,env:E.env}).catch(U=>y.warn("coze-cli setup error (ignored)",{err:String(U)}));let Sa=new vn({handshake:as,privatecode:I,...bn?{urlOverride:bn}:{},ppeOverride:Ne});await s.swap(Sa,"pair");try{let U=new ze;r.frameworksCache=await U.detectAll(),await qe(r),y.info("frameworks_cache refreshed before pair",{detected:Object.keys(r.frameworksCache)})}catch(U){y.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(U)})}let Ea=Object.keys(r.frameworksCache??{});try{let U=await a.sendRequest("_agent/pair",{pairCode:Q,patToken:I,frameworks:Ea,_meta:{cozeDeviceId:f}});y.info("_agent/pair ok",{pairResult:U}),l=I,d=Nn,u||(u=new qt({core:a,getDeviceId:()=>f??""})),u.start(),os&&oa(i,c).catch(De=>y.warn("post-pair-switch auto-revive error (ignored)",{err:String(De)}));let Dn;return E.agent_id&&(Dn=await Af(E.agent_id,i,c,De=>a.sendRequest("_agent/detail",De)).catch(De=>(y.error("--agent-id ensureAgent failed",{agentId:E.agent_id,err:String(De)}),{ok:!1,agentId:E.agent_id??"",note:String(De)}))),{ok:!0,note:"paired with cloud",...Dn?{agent:Dn}:{}}}catch(U){return y.error("_agent/pair failed",{err:String(U)}),{ok:!1,note:`pair failed: ${String(U)}`}}}},{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 ze;return r.frameworksCache=await g.detectAll(),await qe(r),{ok:!0,frameworks:r.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(y.info("IPC /shutdown received"),setImmediate(()=>{P.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:C,token:F}=await v.start();await a.start(),oa(i,c).catch(g=>y.warn("auto-revive top-level error (ignored)",{err:String(g)}));let b=null,P={port:C,token:F,core:a,ipc:v,shutdown(g){return b||(y.info("daemon shutdown",{reason:g}),b=(async()=>{u?.stop(),await a.stop(g),await v.stop(),await n.release()})(),b)}};for(let g of["SIGTERM","SIGINT"])process.on(g,()=>{P.shutdown(g).then(()=>process.exit(0))});return y.info("daemon ready",{port:C,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(r.frameworksCache??{}),libVersion:r.libVersion??"dev"}),P}function ia(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function Rf(n,e,t){return`${n??""}|${e??""}|${t??""}`}async function Pf(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return}let{loadAgentConfig:s,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(ge(),Dt));for(let o of r){await i(o,n).catch(a=>y.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await s(o,n);a?.disconnectedAt&&(e.disconnectedAgents.add(o),y.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){y.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function Af(n,e,t,r){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ge(),Dt)),i=await s(n,e);if(i){y.info("--agent-id: local config found, reconnecting",{agentId:n,framework:i.framework,hadDisconnect:!!i.disconnectedAt});let l={agentId:i.agentId,framework:i.framework,...i.cozeIdentity?{cozeIdentity:i.cozeIdentity}:{},...i.model?{model:i.model}:{}};return await t.createAgent(l),{ok:!0,agentId:n,note:i.disconnectedAt?"revived from local config":"connected from local config"}}y.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let o=await r({_meta:{cozeAgentId:n}});if(!o.framework)throw new h("AGENT_NOT_FOUND",`agent ${n} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let a={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...o.deployType?{_meta:{cozeDeployType:o.deployType}}:{}};await t.createAgent(a);let c=o.deployType==="cloud"&&o.framework==="openclaw";return{ok:!0,agentId:n,note:c?"cloud agent acknowledged":"created from cloud detail"}}async function oa(n,e){let{readdir:t}=await import("node:fs/promises"),r;try{r=await t(n.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(r.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:s}=await Promise.resolve().then(()=>(ge(),Dt));y.info("auto-revive: scanning local agents on startup",{count:r.length});let i=0,o=0;for(let a of r){let c;try{c=await s(a,n)}catch(l){y.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),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(l){y.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return y.info("auto-revive: done",{revived:i,skipped:o,total:r.length}),{revived:i,skipped:o,total:r.length}}Vr();z();import{readFile as la}from"node:fs/promises";var Ee=class{paths;constructor(e){this.paths=e??T()}async probe(e=1e3){let t=await this.readAuth();if(!t)return{kind:"not-running"};try{let r=await this.fetch(t,{method:"GET",path:"/status",timeoutMs:e});return r.status===200?{kind:"connected",...t}:{kind:"stale",reason:`unexpected status ${r.status}`}}catch(r){return{kind:"stale",reason:Ff(r)}}}async request(e){let t=await this.readAuth();if(!t)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(t,e)}async readAuth(){try{let[e,t]=await Promise.all([la(this.paths.portFile,"utf8"),la(this.paths.tokenFile,"utf8")]),r=Number.parseInt(e.trim(),10),s=t.trim();return!Number.isFinite(r)||r<=0||!s?null:{port:r,token:s}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,t){let r=t.body!==void 0,s={Authorization:`Bearer ${e.token}`};r&&(s["content-type"]="application/json");let i=new AbortController,o=setTimeout(()=>i.abort(),t.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${t.path}`,{method:t.method,headers:s,body:r?JSON.stringify(t.body):void 0,signal:i.signal}),c=await a.text();return{status:a.status,body:Bf(c)}}finally{clearTimeout(o)}}};function Bf(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function Ff(n){return n instanceof Error?n.message:String(n)}k();z();import{copyFile as da,mkdir as Uf,readFile as Qr,writeFile as $f}from"node:fs/promises";import{dirname as zf,resolve as Kr,sep as xn}from"node:path";import{fileURLToPath as qf}from"node:url";k();z();var ua=w("dist-install");function Gf(n){let e=qf(n),t=zf(e),r=`${xn}src${xn}`;if(t.includes(r)||t.endsWith(`${xn}src${xn}cli`))return null;let s=Kr(t,"index.js"),i=Kr(t,"..","package.json");return{dist:s,pkgJson:i}}async function fa(n={}){let e=n.paths??T(),t=Gf(import.meta.url),r=n.sourceDist??t?.dist,s=n.sourcePackageJson??t?.pkgJson;if(!r||!s)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};let i;try{i=JSON.parse(await Qr(s,"utf8")).version??"unknown"}catch(f){return ua.warn("cannot read source package.json,skip dist install",{err:String(f)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(f)}`}}let o=await nn(e.configFile)??{},a=o.libVersion;if(a===i)try{return await Qr(e.libEntry),{kind:"already-current",libVersion:i}}catch{}await Uf(e.libDir,{recursive:!0}),await da(r,e.libEntry),await da(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Kr(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
-
`;return await
|
|
88
|
+
${c}`}var ve=T("agent-detail-sync"),an=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await Q0(i)}catch(c){ve.info("agents dir not found, skip detail sync",{root:i,err:String(c)});return}ve.info("starting detail sync",{reason:e,count:a.length});for(let c of a)try{await this.syncOne(c)}catch(u){ve.warn("detail sync failed for agent, skipping",{agentId:c,err:String(u)})}ve.info("detail sync done",{reason:e})}async syncOne(e){let i=await ue(e,this.opts.paths);if(!i){ve.info("detail sync: agent config missing, skip",{agentId:e});return}let a;try{a=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(f){ve.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});return}if(a.agentId&&a.agentId!==e){ve.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&&ve.info("detail.deployType",{agentId:e,deployType:a.deployType}),!c){ve.debug("detail sync: no diff",{agentId:e});return}await we(i,this.opts.paths),ve.info("detail sync: config updated",{agentId:e,identityChanged:u,agentName:i.agentName}),u&&(await ft(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ke();import{spawn as hi}from"node:child_process";import{lstat as Ar,mkdir as rc,readFile as gi,readdir as sc,rm as ic,stat as oc,writeFile as di}from"node:fs/promises";import{join as Ce,normalize as ac,relative as pi,resolve as cc,sep as mi}from"node:path";var Se={PAIR:"_agent/pair",CREATE:"_agent/create",HEALTH:"_agent/health",LIST_SKILLS:"_agent/listSkills",ADD_SKILLS:"_agent/addSkills",REMOVE_SKILLS:"_agent/removeSkills",GET_FILE_TREE:"_agent/getFileTree",GET_FILE_CONTENT:"_agent/getFileContent",DETAIL:"_agent/detail",UPDATE:"_agent/update",DISCONNECT:"_agent/disconnect",SWITCH_MODEL:"_agent/switchModel",GEN_MODEL_TOKEN:"_agent/genModelToken",RESET:"_agent/reset",REPAIR:"_agent/repair",DELETE:"_agent/delete"};function Tt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function $s(n){let{_meta:e,...i}=n;return{stripped:i,meta:e}}function dt(n){if(!n?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return n.cozeAgentId}var S=class extends Error{code;retriable;cause;constructor(e,i,a){super(i),this.name="BridgeError",this.code=e,this.retriable=a?.retriable??!1,a?.cause!==void 0&&(this.cause=a.cause)}};F();xe();function cn(n){return n.startsWith("http://")||n.startsWith("https://")}function Me(n,e){if(Tt(n)!=="cloud")throw new S("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}F();var xn="1008033",Xs="1289";var Ys="pbbp2",Zs="https://www.coze.cn",Qs="/api/coze_claw/resource/get_frontier_key",ec="https://www.coze.cn",tc="wss://frontier.coze.cn";function ei(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??ec}function ti(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??tc}function un(n){let e={},i=n?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,a=n?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return i&&(e["x-tt-env"]=i),a&&(e["x-use-ppe"]=a),e}function fn(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var ni=T("handshake");async function ri(n){let e=ei(n.endpoint),i=n.timeoutMs??1e4,a=`${nc(e)}${Qs}?aid=${encodeURIComponent(xn)}`,c={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...un(n.ppeOverride)},u=new AbortController,f=setTimeout(()=>u.abort(),i);ni.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")??"",w=l.headers.get("x-tt-trace-id")??"";if(!l.ok){let P=await l.text().catch(()=>"");throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${l.status} logid=${p}: ${P.slice(0,200)}`)}let y=await l.json();if(y.code!==void 0&&y.code!==0)throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${y.code} msg=${y.msg??"-"} logid=${p}`);let _=y.data?.access_key,C=y.data?.device_id;if(!_||!C)throw new S("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${p}: ${JSON.stringify(y)}`);return ni.info("handshake ok",{remoteDeviceId:C,logid:p,traceId:w}),{accessKey:_,deviceId:C}}catch(l){throw l instanceof S?l:l.name==="AbortError"?new S("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${i}ms)`):new S("UPSTREAM_HANDSHAKE_FAILED",String(l),{cause:l})}finally{clearTimeout(f)}}function nc(n){return n.endsWith("/")?n.slice(0,-1):n}var Sr="https://llm-gateway.coze.cn",Ee="auto";function si(n){return{model:n.model??Ee,...n.modelToken?{modelToken:n.modelToken}:{}}}function ii(n){return!n||n===Ee}function oi(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=Sr,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||Ee):ii(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function ai(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||Ee}"`):ii(n.model)||e.push("-c",`model="${n.model}"`),n.modelToken&&(e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Sr}/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 ci(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function Er(n){let{ttEnv:e,usePpe:i}=fn(n),a={};return e&&(a["x-tt-env"]=e),i&&(a["x-use-ppe"]=i),a}function xi(n,e){if(!n.modelToken)return{};let i=Er(e);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,u])=>`${c}:${u}`).join(`
|
|
89
|
+
`)}}function Cr(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ui(n,e){if(!n.modelToken)return null;let i=n.model||Ee,a=Er(e),c={baseUrl:`${Sr}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:i,name:i,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(a).length>0&&(c.headers=a),c}function fi(n,e){if(!n.modelToken)return[];let i=Er(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var oe=T("agent-handlers"),li=5*1024*1024,xc=1,uc=6,fc=new Set(["node_modules",".git",".coze","dist","build",".next"]),dn=class{constructor(e){this.opts=e}opts;async listSkills(e){Me(e._meta,"_agent/listSkills");let i=dt(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Be(i).workspace,u=a?.skills??[],f=[];for(let l of u){let p=Ce(c,l.relPath,"SKILL.md");await oc(p).then(y=>y.isFile()).catch(()=>!1)&&f.push(pc(l))}return{skills:f}}async addSkills(e){Me(e._meta,"_agent/addSkills");let i=dt(e._meta),a=await this.requireAgentCfg(i),c=e.skills??[],u=[...a.skills??[]],f=new Map(u.map((p,w)=>[p.skillId,w])),l=[];for(let p of c){let w=await kr({agentId:i,workspace:a.workspace,framework:a.framework,skill:p});Pr(u,f,w),l.push(p)}return await sn(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:l}}async removeSkills(e){Me(e._meta,"_agent/removeSkills");let i=dt(e._meta),a=await this.requireAgentCfg(i),c=new Set(e.skillIds??[]),u=a.skills??[],f=[];for(let l of u){if(!c.has(l.skillId)){f.push(l);continue}let p=Ce(a.workspace,l.relPath);await ic(p,{recursive:!0,force:!0}),oe.info("skill removed",{agentId:i,skillId:l.skillId,relPath:l.relPath})}return await sn(i,f),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}),oe.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(f){oe.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId,err:String(f)})}finally{u.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return oe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await ue(i);if(!a)throw new S("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(oe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await we(a),await ft(a.workspace,a.framework,i,e.cozeIdentity),oe.info("_agent/update: cozeIdentity rewritten",{agentId:i,framework:a.framework}),await this.reloadAgentSessions(i,"identity-changed"),{ok:!0})}async disconnectAgent(e){let i=e.agentId;if(!i)throw new S("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let a=await ue(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await we(a),oe.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}):(oe.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Me(e._meta,"_agent/switchModel"),!e.agentId)throw new S("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:Ee,a=await ue(e.agentId);if(!a)throw new S("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await we(a),oe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return oe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};c.model=i;let u=[];for(let[f,l]of c.allSessionQueues())u.push(l.enqueue(async()=>{let p=c.sessions.get(f);p?.downstream&&(await p.downstream.stop(`switchModel: ${i}`).catch(()=>{}),p.downstream=void 0)}));return await Promise.all(u),oe.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,Se.RESET),!e.agentId)throw new S("IPC_BAD_REQUEST",`${Se.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Se.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Me(e._meta,Se.REPAIR),!e.agentId)throw new S("IPC_BAD_REQUEST",`${Se.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new S("IPC_BAD_REQUEST",`${Se.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){oe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(a)})}return await this.runDetailSync(e.agentId,Se.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,i,a){if(!this.opts.detailSyncer){oe.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){oe.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=dt(i),c=await this.resolveWorkspace(a),u=e.filePath??"",f=this.safeJoin(c,u),l=await Ar(f).catch(()=>null);if(!l)throw new S("IPC_BAD_REQUEST",`path not found: ${u}`);if(l.isSymbolicLink())throw new S("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let p=vc(e.depth);return l.isDirectory()?{tree:await wi(c,f,u,p)}:{tree:[{name:Sc(u),path:_i(u||"."),isDir:!1,size:l.size,modifiedAt:Math.floor(l.mtimeMs)}]}}async getFileContent(e){Me(e._meta,"_agent/getFileContent");let i=dt(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new S("IPC_BAD_REQUEST","filePath required");let c=this.safeJoin(a,e.filePath),u=await Ar(c).catch(()=>null);if(!u||!u.isFile())throw new S("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new S("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>li)throw new S("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${li})`);let f=await gi(c);return f.includes(0)?{content:f.toString("base64"),encoding:"base64",size:u.size}:{content:f.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await ue(e).catch(()=>null))?.workspace??Be(e).workspace}safeJoin(e,i){let a=cc(e,i||"."),c=pi(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${mi}`))throw new S("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return ue(e)}async requireAgentCfg(e){let i=await this.loadAgentCfg(e);if(!i)throw new S("AGENT_NOT_FOUND",`no config for agent: ${e}`);return i}};function dc(n){let e=n.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new S("IPC_BAD_REQUEST",`invalid skill name: ${n}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new S("IPC_BAD_REQUEST",`reserved windows filename: ${n}`);return e}function lc(n){return n==="claude-code"?Ce(".claude","skills"):Ce(".agents","skills")}var hc=3e4,gc=50*1024*1024,ln=3e4;async function kr(n){let{agentId:e,workspace:i,framework:a,skill:c}=n;if(!c.skillName)throw new S("IPC_BAD_REQUEST","skill missing skillName");let u=typeof c.content=="string"&&c.content.length>0,f=typeof c.downloadUrl=="string"&&c.downloadUrl.length>0;if(!u&&!f)throw new S("IPC_BAD_REQUEST",`skill ${c.skillId} missing both content and downloadUrl`);let l=dc(c.skillName),p=lc(a),w=Ce(p,l),y=Ce(i,w);if(await rc(y,{recursive:!0}),u){let C=Buffer.from(c.content,"utf8");Rt(C.length),await di(Ce(y,"SKILL.md"),C,"utf8")}else{let C=await mc(c.downloadUrl);_c(C)?await yc(C,y):await di(Ce(y,"SKILL.md"),C.toString("utf8"),"utf8")}let _={skillId:c.skillId,skillName:c.skillName,relPath:w,installedAt:Date.now(),...c.description?{description:c.description}:{},...c.icon?{icon:c.icon}:{},...c.version?{version:c.version}:{},...c.downloadUrl?{downloadUrl:c.downloadUrl}:{},...c.config?{config:c.config}:{},...c.builtin?{builtin:c.builtin}:{}};return oe.info("skill installed",{agentId:e,skillId:c.skillId,skillName:c.skillName,relPath:w,source:u?"content":"downloadUrl"}),_}function Pr(n,e,i){let a=e.get(i.skillId);if(a!==void 0){n[a]=i;return}e.set(i.skillId,n.length),n.push(i)}function pc(n){return{skillId:n.skillId,skillName:n.skillName,...n.description?{description:n.description}:{},...n.icon?{icon:n.icon}:{},...n.version?{version:n.version}:{},...n.config?{config:n.config}:{},...n.builtin?{builtin:n.builtin}:{}}}async function mc(n){if(!n)throw new S("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);Rt(e);let i=wc(n);return Rt(i.length),i}if(n.startsWith("file:")){let e=new URL(n).pathname,i=await gi(e);return Rt(i.length),i}if(cn(n)){let e=new AbortController,i=setTimeout(()=>e.abort(),hc);try{let a=await fetch(n,{signal:e.signal});if(!a.ok)throw new S("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${n}`);let c=await a.arrayBuffer();return Rt(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new S("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function Rt(n){if(n>gc)throw new S("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function wc(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new S("IPC_BAD_REQUEST","bad data URL");let i=!!e[2],a=e[3]??"";return i?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8")}function _c(n){return n.length>=2&&n[0]===31&&n[1]===139}async function yc(n,e){await bc(n),await new Promise((i,a)=>{let c=hi("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";c.stderr?.on("data",l=>{u+=String(l)});let f=setTimeout(()=>{c.kill("SIGKILL"),a(new S("IPC_BAD_REQUEST",`tar extract timeout (${ln}ms)`))},ln);c.on("error",l=>{clearTimeout(f),a(new S("IPC_BAD_REQUEST",`tar spawn failed: ${l.message}`,{cause:l}))}),c.on("exit",l=>{clearTimeout(f),l===0?i():a(new S("IPC_BAD_REQUEST",`tar exit ${l}${u?`: ${u.trim().slice(0,200)}`:""}`))}),c.stdin?.end(n)})}async function bc(n){let e=await new Promise((i,a)=>{let c=hi("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",f="";c.stdout?.on("data",p=>{u+=String(p)}),c.stderr?.on("data",p=>{f+=String(p)});let l=setTimeout(()=>{c.kill("SIGKILL"),a(new S("IPC_BAD_REQUEST",`tar list timeout (${ln}ms)`))},ln);c.on("error",p=>{clearTimeout(l),a(new S("IPC_BAD_REQUEST",`tar list spawn failed: ${p.message}`))}),c.on("exit",p=>{clearTimeout(l),p===0?i(u):a(new S("IPC_BAD_REQUEST",`tar list exit ${p}${f?`: ${f.trim().slice(0,200)}`:""}`))}),c.stdin?.end(n)});for(let i of e.split(`
|
|
90
|
+
`)){let a=i.trim();if(!a)continue;let c=a.charCodeAt(0);if(c!==45&&c!==100)throw new S("IPC_BAD_REQUEST",`tar entry kind '${a[0]}' not allowed (symlink/hardlink/special): ${a.slice(0,100)}`);let f=(a.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!f)continue;if(f.startsWith("/"))throw new S("IPC_BAD_REQUEST",`tar entry absolute path: ${f}`);if(f.split(/[/\\]/).some(p=>p===".."))throw new S("IPC_BAD_REQUEST",`tar entry contains '..': ${f}`)}}async function wi(n,e,i,a){if(a<=0)return[];let c;try{c=await sc(e,{withFileTypes:!0})}catch{return[]}let u=[];for(let f of c){if(fc.has(f.name)||f.isSymbolicLink())continue;let l=Ce(e,f.name),p=ac(Ce(i,f.name)),w=null;try{w=await Ar(l)}catch{continue}if(w.isSymbolicLink())continue;let y={name:f.name,path:_i(pi(n,l)),isDir:w.isDirectory(),size:w.size,modifiedAt:Math.floor(w.mtimeMs)};w.isDirectory()&&a>1&&(y.children=await wi(n,l,p,a-1)),u.push(y)}return u.sort((f,l)=>f.isDir!==l.isDir?f.isDir?-1:1:f.name.localeCompare(l.name)),u}function vc(n){return!n||n<=0?xc:Math.min(n,uc)}function Sc(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function _i(n){return n.split(mi).join("/")}F();import{readFileSync as Dl}from"node:fs";import{dirname as Rl,join as Nl}from"node:path";import{fileURLToPath as Ol}from"node:url";var hn="0.1.35";var Nt=T("agent-health-reporter"),Ec=1e4,gn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??Ec}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()}),Nt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Nt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Nt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Nt.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=Cc(c);u&&i.push({agentId:c.agentId,status:u})}if(i.length===0)return;let a={agents:i,bridgeVersion:hn,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",a)}catch(c){Nt.warn("heartbeat batch send failed",{count:i.length,err:String(c)})}}finally{this.inFlight=!1}}};function Cc(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}Ke();import{mkdir as Tr,rm as Qc}from"node:fs/promises";F();import{execFile as Ac}from"node:child_process";import{promisify as kc}from"node:util";var bi=kc(Ac),Lt=T("agents.acp-installer"),Pc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},Ic=5e4,Dc=5e3,Tc=5*6e4,mn=new Map,pn=new Map,Ir=new Map;async function yi(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:i}=await bi(e,[n],{timeout:Dc});return i.split(`
|
|
91
|
+
`)[0]?.trim()||void 0}catch{return}}async function Rc(n){Lt.info("npm install -g start",{npmPackage:n}),await bi("npm",["install","-g",`${n}@latest`],{timeout:Ic,maxBuffer:10*1024*1024}),Lt.info("npm install -g done",{npmPackage:n})}async function vi(n){let e=Pc[n];if(!e)return;let i=mn.get(n);if(i)return i;let a=pn.get(n);if(a&&Date.now()-a<Tc)return;let c=Ir.get(n);if(c)return c;let u=(async()=>{let f=await yi(e.binary);if(f)return mn.set(n,f),Lt.info("acp wrapper found on PATH",{binary:e.binary,path:f}),f;try{await Rc(e.npmPackage)}catch(p){Lt.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(p)}),pn.set(n,Date.now());return}let l=await yi(e.binary);if(!l){Lt.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),pn.set(n,Date.now());return}return mn.set(n,l),pn.delete(n),l})().finally(()=>{Ir.delete(n)});return Ir.set(n,u),u}function wn(n){return mn.get(n)}import{spawn as Mc}from"node:child_process";function Ot(n,e,i){return i===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:i}}function _n(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function lt(n,e){return{jsonrpc:"2.0",id:n,result:e}}function Qe(n,e){return{jsonrpc:"2.0",id:n,error:e}}var yn=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 Si(n){return"method"in n&&"id"in n&&n.id!==void 0}function Ei(n){return"method"in n&&!("id"in n)}function bn(n){return!("method"in n)&&"id"in n}var Nc={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 Bt(n){return n instanceof S?{code:Nc[n.code]??J.INTERNAL_ERROR,message:n.message,data:{bridgeCode:n.code,retriable:n.retriable}}:{code:J.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)}}function Ci(n){let e=n.data,i=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new S(i,n.message,{retriable:e?.retriable??!1,cause:n.data})}function Ai(n){return`${JSON.stringify(n)}
|
|
92
|
+
`}var vn=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let i=this.buffer.split(`
|
|
93
|
+
`);this.buffer=i.pop()??"";let a=[];for(let c of i){let u=c.replace(/\r$/,"").trim();if(u)try{a.push(JSON.parse(u))}catch(f){this.onError?.({line:u,error:f})}}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 Pi={"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"},Xl=Object.fromEntries(Object.entries(Pi).map(([n,e])=>[e,n])),Lc={"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=Pi[e]??Oc(e),c=Lc[a]??[],u=[a,String(this.seq)];if(c.length>0){let f=c.map(p=>ki(i?.[p]??"")),l=Bc(f).join(":");l&&u.push(l)}else i&&Object.values(i).some(f=>f)&&u.push(Object.values(i).filter(Boolean).map(f=>ki(String(f))).join(":"));return u.join("_")}reset(){this.seq=0}};function Oc(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function ki(n){return n.replace(/[:_\s]+/g,"-")}function Bc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}F();var zc=3e4,qc=50,Fc=20,Ii=500;function Uc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=Ii?n:`${e.slice(0,Ii)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Di(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var We=class{constructor(e){this.opts=e;this.log=T(`downstream.${this.constructor.name}`),this.decoder=new vn({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;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new S("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=Mc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=i,i.stdout?.setEncoding("utf8"),i.stdout?.on("data",a=>{for(let c of this.decoder.push(a))this.dispatch(c)}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{let c=a.trimEnd();this.stderrRing.push(c),this.stderrRing.length>qc&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.on("exit",(a,c)=>{this.stopped=!0,(a!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:a,signal:c,recentStderr:this.stderrRing.slice(-Fc)}),this.failAllPending(new S("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${c})`));for(let f of this.exitHandlers)f(a,c)}),i.on("error",a=>{this.log.error("child error",{err:String(a)}),this.failAllPending(new S("AGENT_SPAWN_FAILED",String(a),{cause:a}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let i=this.child,a=new Promise(u=>i.once("exit",()=>u()));Di(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||Di(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(_n("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(Qe(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=zc){if(!this.child||this.stopped)return Promise.reject(new S("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=Ot(c,e,i),f=a>0&&Number.isFinite(a);return new Promise((l,p)=>{let w=f?setTimeout(()=>{this.pending.delete(c),p(new S("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(c,{resolve:l,reject:p,timer:w,method:e});try{this.writeFrame(u)}catch(y){w&&clearTimeout(w),this.pending.delete(c),p(y)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new S("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Ai(e))}dispatch(e){if(bn(e)){let i=e.id!==null?this.pending.get(e.id):void 0;if(!i){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),i.timer&&clearTimeout(i.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:i.method,code:e.error.code,message:e.error.message,data:e.error.data}),i.reject(Ci(e.error))):(this.log.info("downstream returned result",{id:e.id,method:i.method,result:Uc(e.result)}),i.resolve(e.result));return}if(Ei(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(Si(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(Qe(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(Qe(e.id,Bt(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var Hc="@agentclientprotocol/claude-agent-acp@latest";function Gc(n){let e={};for(let[i,a]of Object.entries(n))a!==void 0&&(i.startsWith("CLAUDE")||i==="AI_AGENT"||i==="BAGGAGE"||(e[i]=a));return e}var Sn=class extends We{framework="claude-code";constructor(e){let i=wn("claude-code"),[a,c]=i?[i,[]]:["npx",["-y",Hc]],u=e.command??a,f=e.args??c,l={command:u,args:f,cwd:e.cwd,...e.env?{env:e.env}:{}};super(l)}sanitizeEnv(e){return Gc(e)}};import{mkdtempSync as jc,rmSync as Kc}from"node:fs";import{tmpdir as Wc}from"node:os";import{join as Jc}from"node:path";var Vc="@zed-industries/codex-acp@latest",En=class extends We{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=wn("codex"),[a,c]=i?[i,[]]:["npx",["-y",Vc]],u=e.command??a,f=e.args??c,l=e.extraArgs?[...f,...e.extraArgs]:f,p=e.isolateCodexHome?jc(Jc(Wc(),"coze-bridge-codex-home-")):void 0,w=p?{...e.env??{},CODEX_HOME:p}:e.env,y={command:u,args:l,cwd:e.cwd,...w?{env:w}:{}};super(y),this.authMethodId=e.authMethodId,this.codexHomeDir=p}async initialize(e){let i=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),i}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Kc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var Mt=class extends We{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}};F();xe();function Dr(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}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 Cn=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)zt(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function zt(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as $c}from"node:child_process";import{homedir as Xc}from"node:os";import{join as Yc}from"node:path";en();F();async function Ni(){let n=Yc(Xc(),".openclaw/openclaw.json");return(await ut(n))?.gateway?.auth?.token??""}var Ti=T("openclaw.config"),Zc=[0,5e3,5e3],Ri="models.providers.",An="agents.defaults.models",kn=class{command;env;retryDelaysMs;queue=new gt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Zc}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(f=>setTimeout(f,u));try{return await i()}catch(f){a=f,Ti.warn("openclaw cli failed, will retry",{label:e,attempt:c+1,err:String(f)})}}throw new S("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${a?.message??"unknown"}`)}runCli(e){return new Promise((i,a)=>{let c=$c(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),u="";c.stderr?.on("data",f=>{u+=f.toString("utf8")}),c.on("error",a),c.on("close",f=>{f===0?i():a(new Error(`exit ${f}: ${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){Ti.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",`${Ri}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Ri}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${An}[${e}]`,()=>this.runCli(["config","set",An,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${An}[${e}]`,`${An}.${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 Ae=T("agent-manager"),ex=(n,e,i,a,c,u,f)=>{switch(n){case"claude-code":{let l=c?{...oi(c),...xi(c,f)}:void 0;return new Sn({cwd:i,...l&&Object.keys(l).length>0?{env:l}:{}})}case"codex":{let l=c?[...ai(c),...fi(c,f)]:[],p=c?ci(c):void 0,w=!!c;return new En({cwd:i,...l.length>0?{extraArgs:l}:{},...p&&Object.keys(p).length>0?{env:p}:{},...w?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Mt({command:e,cwd:i,agentId:a,...u?{sessionName:Dr(u)}:{}})}};function Li(n){return n==="claude-code"||n==="codex"}var tx={path:"",version:"cloud-deployed"},nx={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},rx=6e4,Pn=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??ex,this.createTimeoutMs=e.createTimeoutMs??rx}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new S("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new kn({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new S("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new S("IPC_BAD_REQUEST","framework required");let i=Tt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new S("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")Ae.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>Ae.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else return Ae.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}if(!i&&!this.config.frameworksCache?.[e.framework])throw new S("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);i&&Li(e.framework)&&await vi(e.framework);let u=Be(e.agentId,this.paths),f=e.workspace??u.workspace,l=Tt(e._meta),p=new AbortController,w=setTimeout(()=>p.abort(new S("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),y,_=!1;try{let C=()=>{if(p.signal.aborted)throw p.signal.reason instanceof Error?p.signal.reason:new S("AGENT_TIMEOUT","_agent/create aborted")};await Tr(u.root,{recursive:!0}),await Tr(f,{recursive:!0}),await Tr(u.logs,{recursive:!0}),C(),await ft(f,e.framework,e.agentId,e.cozeIdentity),C();let P=await ue(e.agentId,this.paths).catch(()=>null),I=si({model:e.model??P?.model});if(y=new Cn({agentId:e.agentId,framework:e.framework,workspace:f,model:I.model??Ee,deployType:l}),y.status="ok",P?.sessions){for(let[re,ee]of Object.entries(P.sessions))y.sessions.set(re,{acpSessionId:ee.acpSessionId,modelToken:ee.modelToken,tokenGeneratedAt:ee.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let Y=Object.keys(P.sessions).length;Y>0&&Ae.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:Y})}this.registry.register(y),_=!0;let R={agentId:e.agentId,framework:e.framework,workspace:f,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:I.model};l==="cloud"&&(R.deployType="cloud"),P?.skills&&(R.skills=P.skills),P?.agentName&&(R.agentName=P.agentName),P?.description&&(R.description=P.description),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,f):Ae.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let U=e.initialSkills??[];if(U.length>0){let Y=[...R.skills??[]],re=new Map(Y.map((Z,k)=>[Z.skillId,k])),ee=0;for(let Z of U)try{let k=await kr({agentId:e.agentId,workspace:f,framework:e.framework,skill:Z});Pr(Y,re,k),ee++}catch(k){Ae.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:Z.skillId,skillName:Z.skillName,err:String(k)})}ee>0&&(R.skills=Y,Ae.info("initialSkills installed",{agentId:e.agentId,installed:ee,requested:U.length}))}return await we(R,this.paths),Ae.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:l}),{ok:!0,agentId:e.agentId,workspace:f,framework:e.framework}}catch(C){throw Ae.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),_&&y&&(await y.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Qc(u.root,{recursive:!0,force:!0}).catch(P=>Ae.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof S?C:new S("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(w)}}async spawnSessionDownstream(e,i,a,c){let f=this.config.frameworksCache?.[e.framework];if(!f)if(e.deployType==="cloud"&&Li(e.framework))f=tx;else throw new S("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:f.path}):p=this.factory(e.framework,f.path,e.workspace,e.agentId,l,a,c);try{return await p.start(),await p.initialize(nx),p}catch(w){throw await p.stop("spawnSessionDownstream failed").catch(()=>{}),w instanceof S?w:new S("AGENT_SPAWN_FAILED",w instanceof Error?w.message:String(w),{cause:w})}}async buildOpenclawDownstream(e){let{session:i,modelConfig:a,cloudSessionId:c,cozeEnv:u,command:f}=e,l=Dr(c),p=await Ni(),w=a?ui(a,u):null,y;if(w){let _=Cr(c),P=w.models[0]?.id??Ee,I=`${_}/${P}`;if(!this.ensuredProviders.has(I)){let R=this.getOpenclawConfig();await R.ensureProvider(_,w),await R.addModelToAllowlist(I),this.ensuredProviders.add(I)}y=I}return new Mt({command:f,cwd:i.workspace,agentId:i.agentId,sessionName:l,...p?{gatewayToken:p}:{},...y?{slashModelOnStart:y}:{}})}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=Cr(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};F();import{execFile as sx}from"node:child_process";import{promisify as ix}from"node:util";var ox=ix(sx),Je=T("coze-cli-installer"),Oi="@coze/cli@0.1.3-alpha.89c42a",Bi="https://bnpm.byted.org",ax="coze",cx=5e3,xx=9e4,Mi=1e4,qt=null,Rr=!1;async function zi(n,e={}){if(Rr)return;if(qt)return qt;let i=e.exec??ox;return qt=(async()=>{try{let a=await ux(ax,i);if(a){Je.info("coze-cli already on PATH, skip install + config + auth",{path:a}),Rr=!0;return}Je.info("coze-cli install start",{package:Oi,registry:Bi});try{await i("npm",["i","-g",Oi,"--registry",Bi],{timeout:xx,maxBuffer:10*1024*1024}),Je.info("coze-cli install ok")}catch(c){Je.warn("coze-cli install failed (skip subsequent steps)",{err:String(c)});return}if(n.env)try{await i("coze",["config","set","xTTEnv",n.env],{timeout:Mi}),Je.info("coze config set xTTEnv ok",{env:n.env})}catch(c){Je.warn("coze config set failed (continue to auth login)",{err:String(c)})}try{await i("coze",["auth","login","--token",n.patToken],{timeout:Mi}),Je.info("coze auth login ok")}catch(c){Je.warn("coze auth login failed",{err:String(c)});return}Rr=!0}finally{qt=null}})(),qt}async function ux(n,e){let i=process.platform==="win32"?"where":"which";try{let{stdout:a}=await e(i,[n],{timeout:cx});return a.split(`
|
|
94
|
+
`)[0]?.trim()||void 0}catch{return}}F();import{spawn as fx}from"node:child_process";import{constants as qi,access as dx}from"node:fs/promises";import{delimiter as lx,join as hx}from"node:path";var gx=T("framework-detector"),Fi={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},px=[".exe",".cmd",".bat",".ps1"],pt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??fx,access:e.access??dx}}async detect(e){let i=Fi[e],a=await this.which(i);if(!a)return gx.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(Fi).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(lx).filter(Boolean),a=this.env.platform==="win32"?["",...px]:[""];for(let c of i)for(let u of a){let f=hx(c,e+u);if(await this.isExecutable(f))return f}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?qi.F_OK:qi.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,f=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"),f("unknown")},5e3),l.stdout?.on("data",p=>{a+=p.toString("utf8")}),l.on("error",()=>f("unknown")),l.on("close",()=>{let p=_x(a).split(/\r?\n/)[0]??"";f(p)})}catch{f("unknown")}})}},mx=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function _x(n){return n.replace(mx,"")}en();xe();var yx=10*6e4;function Ui(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?yx:e}function In(n){return ut(n??K().configFile)}function mt(n,e){return Qt(e??K().configFile,n)}import{randomBytes as Nx}from"node:crypto";import{mkdir as bx,readFile as vx,realpath as Sx,writeFile as Ex}from"node:fs/promises";import{basename as Cx,dirname as Nr,join as Ax,relative as kx,resolve as Hi,sep as Px}from"node:path";F();var ji=T("fs-rpc");async function Ki(n,e){let i=await Ji(n.path,e);return await bx(Nr(i),{recursive:!0}),await Ex(i,n.content,"utf8"),ji.info("fs/write_text_file ok",{path:i,size:n.content.length}),null}async function Wi(n,e){let i=await Ji(n.path,e),a=await vx(i,"utf8"),c=a;if(typeof n.line=="number"||typeof n.limit=="number"){let u=a.split(`
|
|
95
|
+
`),f=Math.max(0,(n.line??1)-1),l=typeof n.limit=="number"?f+n.limit:void 0;c=u.slice(f,l).join(`
|
|
96
|
+
`)}return ji.info("fs/read_text_file ok",{path:i,size:c.length}),{content:c}}async function Ji(n,e){if(typeof n!="string"||n.length===0)throw new S("IPC_BAD_REQUEST","path must be a non-empty string");let[i,a]=await Promise.all([Gi(Hi(e)),Gi(Hi(n))]),c=kx(i,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${Px}`))throw new S("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return a}async function Gi(n){let e=[],i=n;for(;i!==Nr(i);)try{let a=await Sx(i);return e.length?Ax(a,...e.reverse()):a}catch{e.push(Cx(i)),i=Nr(i)}return n}F();var Vi=T("prompt-multimodal"),$i=10*1024*1024,Ix=15e3;async function Xi(n){return Promise.all(n.map(Dx))}async function Dx(n){if(n.type!=="image")return n;let e=n;if(e.data||!e.uri||!cn(e.uri))return n;try{let{buf:i,contentType:a}=await Rx(e.uri),c=e.mimeType||Tx(a)||"application/octet-stream";return Vi.info("image uri fetched and inlined",{uri:e.uri,bytes:i.length,mimeType:c}),{type:"image",data:i.toString("base64"),mimeType:c}}catch(i){return Vi.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(i)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Tx(n){if(!n)return;let e=n.indexOf(";");return(e===-1?n:n.slice(0,e)).trim()||void 0}async function Rx(n){let e=new AbortController,i=setTimeout(()=>e.abort(),Ix);try{let a=await fetch(n,{signal:e.signal});if(!a.ok)throw new Error(`HTTP ${a.status} ${a.statusText}`);let c=await a.arrayBuffer();if(c.byteLength>$i)throw new Error(`image too large: ${c.byteLength} bytes (max ${$i})`);return{buf:Buffer.from(c),contentType:a.headers.get("content-type")??void 0}}finally{clearTimeout(i)}}Ke();F();var B=T("core"),Lx=3e4,Ox=3e4,Dn=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=Ui(e.bridgeConfig)}registerExtension(e,i){this.extensions[e]=i}getCozeEnv(){return this.currentCozeEnv}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),await this.upstream.start(),B.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){B.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(i=>i.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),B.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){B.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(a)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&B.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,i,a){let c=a.downstream;c&&(c.onUpdate(u=>{a.loadingSession||this.forwardUpdate(e,u)}),c.onAgentRequest(u=>{this.handleAgentRequest(e,c,u)}),c.onExit((u,f)=>{B.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:f}),zt(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(bn(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let i="id"in e&&e.id!==void 0?e.id:null,a=e.params?._meta?.cozeEnv;a&&(this.currentCozeEnv=a);try{if(e.method.startsWith("_agent/")){let c=this.extensions[e.method];if(!c){i!==null?await this.sendError(i,J.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):B.warn("drop notification: extension not registered",{method:e.method});return}let u=await c(e,this);i!==null&&await this.upstream.send(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}`):B.warn("drop unknown notification",{method:e.method})}catch(c){B.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send(Qe(i,Bt(c)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new S("IPC_BAD_REQUEST",`${e.method} requires params`);let i=e.params,a=i._meta?.cozeAgentId;if(!a)throw new S("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let c=this.agents.get(a);if(!c)throw this.disconnectedAgents.has(a)?new S("AGENT_DISCONNECTED",`agent ${a} has been disconnected; cloud must _agent/create to revive`):new S("AGENT_NOT_FOUND",`agent not found: ${a}`);let u=typeof i.sessionId=="string"?i.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!u)return this.dispatchSessionCall(c,e.method,i);let f=Date.now(),l=!1;try{let p=await c.getSessionQueue(u).enqueue(()=>this.dispatchSessionCall(c,e.method,i));return l=!0,p}finally{B.info("session call done",{agentId:c.agentId,method:e.method,durationMs:Date.now()-f,ok:l})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:c}=$s(a);switch(i){case"session/new":{let u=Bx();return B.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return B.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=c,f=u.sessionId;if(!f)throw new S("IPC_BAD_REQUEST","session/prompt: missing sessionId");let l=await this.ensureRuntime(e,f);if(l.replySeq=0,await this.ensureDownstream(e,f,l),!l.downstream||!l.acpSessionId)throw new S("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);let w=await Xi(u.prompt);try{let y=await l.downstream.sessionPrompt({...u,sessionId:l.acpSessionId,prompt:w});return l.lastActiveAt=Date.now(),y}finally{e.activeTriggers.delete(l.acpSessionId),l.downstream?.isAlive()&&this.armIdleTimer(e,f,l)}}case"session/cancel":{let f=c.sessionId;if(!f)throw new S("IPC_BAD_REQUEST","session/cancel: missing sessionId");let l=e.sessions.get(f);return l?.downstream?.isAlive()&&l.acpSessionId&&await l.downstream.sessionCancel({sessionId:l.acpSessionId}),{ok:!0}}default:throw new S("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(i,u),await this.persistSessionMapping(e),u}async requestSessionToken(e,i){let a={sessionId:i,_meta:{cozeAgentId:e}};try{let c=await this.sendRequest(Se.GEN_MODEL_TOKEN,a,Ox);if(!c?.modelToken)throw new S("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return c.modelToken}catch(c){throw c instanceof S&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new S("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,i,a){if(zt(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new S("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let c=await this.sessionSpawner(e,a.modelToken,i,this.currentCozeEnv);if(a.downstream=c,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await c.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),B.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){B.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(u)}),a.acpSessionId=void 0;let f=await c.sessionNew({cwd:e.workspace});a.acpSessionId=f.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let u=await c.sessionNew({cwd:e.workspace});a.acpSessionId=u.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&a.acpSessionId&&await c.afterSessionEstablished(a.acpSessionId)}armIdleTimer(e,i,a){if(zt(a),this.isRuntimeBusy(e,a)){B.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:i});return}a.idleTimer=setTimeout(()=>{if(a.idleTimer=void 0,this.isRuntimeBusy(e,a)){B.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:i}),this.armIdleTimer(e,i,a);return}B.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:i});let c=a.downstream;a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId),c&&c.stop("idle timeout").catch(u=>B.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:i,err:String(u)}))},this.sessionIdleTimeoutMs),a.idleTimer.unref?.()}isRuntimeBusy(e,i){if(i.acpSessionId&&e.activeTriggers.has(i.acpSessionId))return!0;let a=i.downstream;if(!a)return!1;for(let c of this.pendingUpstream.values())if(c.downstream===a)return!0;return!1}forwardUpdate(e,i){let a=i.sessionId,c=this.reverseSessionId(e,a);if(!c){B.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){B.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}if(Mx(i)){B.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:a});return}let f={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},l=e.activeTriggers.get(a);l&&(f.cozeTriggerMsgId=l),this.upstream.send(_n("session/update",{...i,sessionId:c,_meta:f})).catch(p=>B.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}if(a.method==="fs/write_text_file"||a.method==="fs/read_text_file"){this.handleFsRpcRequest(e,i,a);return}B.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:a.method}),i.respondAgentRequestError(a.id,{code:J.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}async handleFsRpcRequest(e,i,a){try{let c=e.workspace;if(a.method==="fs/write_text_file"){let u=a.params??{},f=await Ki(u,c);i.respondAgentRequest(a.id,f)}else{let u=a.params??{},f=await Wi(u,c);i.respondAgentRequest(a.id,f)}}catch(c){B.warn("fs rpc handler failed",{agentId:e.agentId,method:a.method,err:String(c)}),i.respondAgentRequestError(a.id,Bt(c))}}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,w={cozeAgentId:e.agentId};p&&(w.cozeTriggerMsgId=p);let y=l?this.reverseSessionId(e,l):void 0,_={...u,...y?{sessionId:y}:{},_meta:w};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),B.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:c,acpSessionId:l,cloudSessionId:y,toolCallId:u.toolCall?.toolCallId,options:u.options?.map(C=>({optionId:C.optionId,kind:C.kind,name:C.name}))}),this.upstream.send(Ot(c,"session/request_permission",_)).catch(C=>{this.pendingUpstream.delete(c),B.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?(B.info("upstream \u2192 permission response (error)",{agentId:i.agentId,upstreamId:e.id,method:i.method,error:e.error}),i.downstream.respondAgentRequestError(i.agentRequestId,e.error)):(B.info("upstream \u2192 permission response (result)",{agentId:i.agentId,upstreamId:e.id,method:i.method,result:e.result}),i.downstream.respondAgentRequest(i.agentRequestId,e.result));return}let a=this.pendingBridge.get(e.id);if(a){this.pendingBridge.delete(e.id),clearTimeout(a.timer),e.error?a.reject(new yn(e.error)):a.resolve(e.result);return}B.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=Lx){let c=this.upstreamIds.next(e);return new Promise((u,f)=>{let l=setTimeout(()=>{this.pendingBridge.delete(c),f(new S("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(c,{method:e,resolve:u,reject:f,timer:l}),this.upstream.send(Ot(c,e,i)).catch(p=>{let w=this.pendingBridge.get(c);w&&(clearTimeout(w.timer),this.pendingBridge.delete(c)),f(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 vr(e.agentId,i,this.paths)}catch(i){B.warn("persist session mapping failed",{agentId:e.agentId,err:String(i)})}}reverseSessionId(e,i){for(let[a,c]of e.sessions.entries())if(c.acpSessionId===i)return a}sendError(e,i,a){return this.upstream.send(Qe(e,{code:i,message:a}))}};function Bx(){return Nx(16).toString("hex")}function Mx(n){let e=n.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let i=e.content;if(!i||typeof i!="object")return!1;let a=i;return a.type!=="text"||typeof a.text!="string"?!1:a.text.startsWith("Model metadata for `")}F();xe();import{randomBytes as zx}from"node:crypto";import{chmod as qx,mkdir as Fx,writeFile as Yi}from"node:fs/promises";import{createServer as Ux}from"node:http";import{dirname as Hx}from"node:path";var Gx=1e6,Lr=T("ipc"),Tn=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=zx(32).toString("hex");let e=Ux((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(),Lr.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 Fx(Hx(this.paths.portFile),{recursive:!0}),await Yi(this.paths.portFile,String(this.port),"utf8"),await Yi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await qx(this.paths.tokenFile,384)}catch(e){Lr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Ft(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){Ft(i,404,{error:"not found"});return}let f=null;if(e.method==="POST")try{f=await jx(e)}catch(l){Ft(i,400,{error:"invalid json",detail:String(l)});return}try{let l=await u.handler(f,e);Ft(i,200,l??{ok:!0})}catch(l){Lr.error("IPC handler failed",{key:c,err:String(l)}),Ft(i,500,{error:l instanceof Error?l.message:String(l)})}}};function Ft(n,e,i){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(i))}async function jx(n){let e=[],i=0;for await(let c of n){let u=c;if(i+=u.length,i>Gx)throw new Error("body too large");e.push(u)}let a=Buffer.concat(e).toString("utf8");return a?JSON.parse(a):null}var ya=Oe(co(),1);var Cf=Oe(sa(),1),Af=Oe(Jn(),1),kf=Oe(yt(),1),Pf=Oe(Jr(),1),If=Oe(Xr(),1),Df=Oe(ns(),1),la=Oe(Yn(),1),Tf=Oe(da(),1);var ha=la.default;F();var ne=T("upstream.frontier"),pa="application/json",ma="none",Qn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Zs,...un(this.opts.ppeOverride)};class i extends ha{constructor(l){super(l,Ys,{headers:e})}send(l,...p){if(Js("debug"))try{let w;typeof l=="string"?w=Buffer.from(l,"utf8"):l instanceof Buffer?w=l:l instanceof ArrayBuffer?w=new Uint8Array(l):ArrayBuffer.isView(l)?w=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):w=new Uint8Array(0);let y=Buffer.from(w.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:w.byteLength,headHex:y})}catch(w){ne.warn("WS raw frame dump failed",{err:String(w)})}super.send(l,...p)}}let a=ti(this.opts.urlOverride),c={url:a,ws:i,fpID:Xs,aID:xn,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:pa,force:!0},payloadEncoding:{encoding:ma,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new ya.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let f=this.openCount===1;ne.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:f,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:f})).catch(l=>ne.warn("onConnect handler threw (ignored)",{err:String(l)}))},u.onclose=f=>{this.opened=!1,ne.info("frontier closed",{code:f.code,reason:f.reason,willReconnect:f.willReconnect})},u.onerror=f=>{ne.warn("frontier error",{code:f.code,msg:f.message})},u.onmessage=f=>this.handleMessage(f),this.fws=u,await u.connect()}async stop(e){let i=this.fws;if(i){this.fws=null,this.opened=!1;try{i.close(1e3,e??"bridge shutdown")}catch(a){ne.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new S("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),c=e;wa(c)||ne.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:pa,payloadEncoding:ma})}catch(f){throw ne.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(f)}),new S("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(f)}`,{cause:f})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){ne.debug("drop non-adapter frontier frame",{service:i});return}let a=Of(e);if(!a){ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ne.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(f){ne.warn("frontier message JSON parse failed",{err:String(f),head:a.slice(0,80)});return}let u=c;wa(u)||ne.info("frontier frame in",{logid:Lf(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:u.id,method:u.method,body:Nf(a)}),Promise.resolve(this.handler(c)).catch(f=>ne.warn("frontier frame handler threw",{err:String(f)}))}};function wa(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}var _a=2e3;function Nf(n){return n.length<=_a?n:`${n.slice(0,_a)}...<truncated, total ${n.length} chars>`}function Lf(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function Of(n){let e=n.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}}F();var ss=T("upstream.switchable"),er=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;ss.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 ss.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>ss.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()}};F();var is=T("upstream"),$t=class{handler=null;async start(){is.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){is.info("NoopUpstream stopped",{reason:e})}async send(e){is.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)}};F();xe();F();xe();import{execSync as Bf}from"node:child_process";import{readFileSync as ba,unlinkSync as Mf}from"node:fs";import{mkdir as zf,readFile as va,unlink as Sa,writeFile as qf}from"node:fs/promises";import{dirname as Ff}from"node:path";var Uf=T("single-instance"),tr=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&&(Uf.warn("removing stale pid file",{stalePid:e}),await Sa(this.pidFile).catch(()=>{})),await zf(Ff(this.pidFile),{recursive:!0}),await qf(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await va(this.pidFile,"utf8")).trim()===String(process.pid)&&await Sa(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await va(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=ba(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=Bf(`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{ba(this.pidFile,"utf8").trim()===String(process.pid)&&Mf(this.pidFile)}catch{}})}};var O=T("daemon"),Hf="coze-bridge-daemon";async function Aa(){let n=new tr({processTitle:Hf}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await In(),a=i??{};br({pid:process.pid}),O.info(i?"loaded bridge config":"initialized bridge config");try{let k=new pt;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 mt(a);let c=new er(new $t),u=K(),f=null,l=new Dn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(k,H,W,se)=>{if(!f)throw new Error("agentManager not ready");return f.spawnSessionDownstream(k,H,W,se)}});await jf(u,l);let p=new Pn({paths:u,config:a,registry:l});f=p;let w,y,_=null,C=null;l.registerExtension("_agent/create",async k=>p.createAgent(k.params)),l.registerExtension("_agent/health",async()=>({ok:!0}));let P={},I=new dn({agents:l.agents,disposeAndMarkDisconnected:async(k,H)=>{let W=l.agents.get(k);W&&(await p.cleanupOpenclawSessionProviders(W).catch(se=>O.warn("cleanup openclaw providers failed (ignored)",{agentId:k,err:String(se)})),await W.dispose(`disconnect: ${H}`).catch(se=>O.warn("dispose during disconnect failed (ignored)",{agentId:k,err:String(se)})),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,H)=>{await p.openclawRepair(k,H)}});l.registerExtension("_agent/listSkills",k=>I.listSkills(k.params)),l.registerExtension("_agent/addSkills",k=>I.addSkills(k.params)),l.registerExtension("_agent/removeSkills",k=>I.removeSkills(k.params)),l.registerExtension("_agent/getFileTree",k=>I.getFileTree(k.params)),l.registerExtension("_agent/getFileContent",k=>I.getFileContent(k.params)),l.registerExtension("_agent/update",k=>I.updateAgent(k.params)),l.registerExtension("_agent/disconnect",k=>I.disconnectAgent(k.params)),l.registerExtension("_agent/switchModel",k=>I.switchModel(k.params)),l.registerExtension("_agent/reset",k=>I.resetAgent(k.params)),l.registerExtension("_agent/repair",k=>I.repairAgent(k.params));let R=new an({paths:u,handlers:I,sendDetail:k=>l.sendRequest("_agent/detail",k)});P.ref=R,c.onConnect(({initial:k})=>{O.info("frontier upstream connected, triggering detail sync",{initial:k}),R.syncAll(k?"initial-connect":"reconnect").catch(H=>O.warn("detail sync top-level error (ignored)",{err:String(H)}))});let U=new Tn({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...l.agents.keys()],deviceId:_??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async k=>{let H=k,W=H?.privatecode,se=H?.pairing_code;if(!W||!se)throw new S("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let De=fn(H.env),ge=H.handshake_url,Ye=H.frontier_url,kt=Gf(H.env,ge,Ye),Xt=!!w&&w!==W,ye=y!==void 0&&y!==kt,be=Xt||ye;if(be){O.warn("pair config switched, resetting agents",{pcChanged:Xt,envChanged:ye,previousPc:w?Ea(w):"",nextPc:Ea(W),previousEnvKey:y??"",nextEnvKey:kt});for(let M of[...l.agents.values()])await M.dispose("pair config switch").catch(()=>{}),l.agents.delete(M.agentId);await c.swap(new $t,"pair switch").catch(()=>{})}let Yt=await ri({privatecode:W,...ge?{endpoint:ge}:{},ppeOverride:De});_=Yt.deviceId,br({deviceId:_,pid:process.pid}),zi({patToken:W,env:H.env}).catch(M=>O.warn("coze-cli setup error (ignored)",{err:String(M)}));let ae=new Qn({handshake:Yt,privatecode:W,...Ye?{urlOverride:Ye}:{},ppeOverride:De});await c.swap(ae,"pair");try{let M=new pt;a.frameworksCache=await M.detectAll(),await mt(a),O.info("frameworks_cache refreshed before pair",{detected:Object.keys(a.frameworksCache)})}catch(M){O.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(M)})}let Zt=Object.keys(a.frameworksCache??{});try{let M=await l.sendRequest("_agent/pair",{pairCode:se,patToken:W,frameworks:Zt,_meta:{cozeDeviceId:_}});O.info("_agent/pair ok",{pairResult:M}),w=W,y=kt,C||(C=new gn({core:l,getDeviceId:()=>_??""})),C.start(),be&&Ca(u,p).catch(Te=>O.warn("post-pair-switch auto-revive error (ignored)",{err:String(Te)}));let V;return H.agent_id&&(V=await Kf(H.agent_id,u,p,Te=>l.sendRequest("_agent/detail",Te)).catch(Te=>(O.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(Te)}),{ok:!1,agentId:H.agent_id??"",note:String(Te)}))),{ok:!0,note:"paired with cloud",...V?{agent:V}:{}}}catch(M){return O.error("_agent/pair failed",{err:String(M)}),{ok:!1,note:`pair failed: ${String(M)}`}}}},{method:"POST",path:"/_agent/create",handler:async k=>{let H=k;return{ok:!0,result:await p.createAgent(H)}}},{method:"POST",path:"/refresh",handler:async()=>{O.info("IPC /refresh: re-detecting frameworks");let k=new pt;return a.frameworksCache=await k.detectAll(),await mt(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(O.info("IPC /shutdown received"),setImmediate(()=>{Z.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:Y,token:re}=await U.start();await l.start(),Ca(u,p).catch(k=>O.warn("auto-revive top-level error (ignored)",{err:String(k)}));let ee=null,Z={port:Y,token:re,core:l,ipc:U,shutdown(k){return ee||(O.info("daemon shutdown",{reason:k}),ee=(async()=>{C?.stop(),await l.stop(k),await U.stop(),await n.release()})(),ee)}};for(let k of["SIGTERM","SIGINT"])process.on(k,()=>{Z.shutdown(k).then(()=>process.exit(0))});return O.info("daemon ready",{port:Y,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),Z}function Ea(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function Gf(n,e,i){return`${n??""}|${e??""}|${i??""}`}async function jf(n,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(n.agentsRoot)}catch{return}let{loadAgentConfig:c,enforceAgentConfigMode:u}=await Promise.resolve().then(()=>(Ke(),on));for(let f of a){await u(f,n).catch(l=>O.warn("enforceAgentConfigMode failed (ignored)",{agentId:f,err:String(l)}));try{let l=await c(f,n);l?.disconnectedAt&&(e.disconnectedAgents.add(f),O.info("agent marked disconnected on startup",{agentId:f,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){O.warn("failed to load agent config on startup, skipping",{agentId:f,err:String(l)})}}}async function Kf(n,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ke(),on)),u=await c(n,e);if(u){O.info("--agent-id: local config found, reconnecting",{agentId:n,framework:u.framework,hadDisconnect:!!u.disconnectedAt});let w={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{}};return await i.createAgent(w),{ok:!0,agentId:n,note:u.disconnectedAt?"revived from local config":"connected from local config"}}O.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let f=await a({_meta:{cozeAgentId:n}});if(!f.framework)throw new S("AGENT_NOT_FOUND",`agent ${n} \u4E0D\u5728\u672C\u5730; \u4E91\u7AEF _agent/detail \u54CD\u5E94\u7F3A framework \u5B57\u6BB5 (D36 \u534F\u8BAE\u6269\u5C55\u672A\u751F\u6548), \u65E0\u6CD5\u5728\u672C\u673A\u65B0\u5EFA`);let l={agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...f.deployType?{_meta:{cozeDeployType:f.deployType}}:{}};await i.createAgent(l);let p=f.deployType==="cloud"&&f.framework==="openclaw";return{ok:!0,agentId:n,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function Ca(n,e){let{readdir:i}=await import("node:fs/promises"),a;try{a=await i(n.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(a.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ke(),on));O.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,f=0;for(let l of a){let p;try{p=await c(l,n)}catch(w){O.warn("auto-revive: load config failed (skipping)",{agentId:l,err:String(w)}),f+=1;continue}if(!p){f+=1;continue}if(p.disconnectedAt){O.info("auto-revive: skip disconnected agent",{agentId:l,disconnectedAt:p.disconnectedAt}),f+=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(w){O.warn("auto-revive: createAgent failed (skipping)",{agentId:l,framework:p.framework,err:String(w)}),f+=1}}return O.info("auto-revive: done",{revived:u,skipped:f,total:a.length}),{revived:u,skipped:f,total:a.length}}as();xe();import{readFile as Pa}from"node:fs/promises";var Xe=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:ed(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([Pa(this.paths.portFile,"utf8"),Pa(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,f=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:Qf(p)}}finally{clearTimeout(f)}}};function Qf(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function ed(n){return n instanceof Error?n.message:String(n)}F();xe();import{copyFile as Ia,mkdir as td,readFile as cs,writeFile as nd}from"node:fs/promises";import{dirname as rd,resolve as xs,sep as nr}from"node:path";import{fileURLToPath as sd}from"node:url";F();xe();var Da=T("dist-install");function id(n){let e=sd(n),i=rd(e),a=`${nr}src${nr}`;if(i.includes(a)||i.endsWith(`${nr}src${nr}cli`))return null;let c=xs(i,"index.js"),u=xs(i,"..","package.json");return{dist:c,pkgJson:u}}async function Ta(n={}){let e=n.paths??K(),i=id(import.meta.url),a=n.sourceDist??i?.dist,c=n.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 cs(c,"utf8")).version??"unknown"}catch(_){return Da.warn("cannot read source package.json,skip dist install",{err:String(_)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(_)}`}}let f=await In(e.configFile)??{},l=f.libVersion;if(l===u)try{return await cs(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await td(e.libDir,{recursive:!0}),await Ia(a,e.libEntry),await Ia(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let p=xs(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
+
`;return await cs(p,"utf8").catch(()=>null)!==w&&await nd(p,w),f.libVersion=u,await mt(f,e.configFile),Da.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 Ed=T("cli");function At(n,e){let i=[],a;for(let c=0;c<n.length;c++){let u=n[c];if(u===e){a=n[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 Cd(n){let e=n.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let i=e,{value:a,rest:c}=At(i,"--pat-token");i=c;let{value:u,rest:f}=At(i,"--pair-code");i=f;let{value:l,rest:p}=At(i,"--env");i=p;let{value:w,rest:y}=At(i,"--handshake-url");i=y;let{value:_,rest:C}=At(i,"--frontier-url");i=C;let{value:P}=At(i,"--agent-id");if(!a||!u)return{mode:"help"};let I={mode:"pair",privatecode:a,pairingCode:u};return l&&(I.env=l),w&&(I.handshakeUrl=w),_&&(I.frontierUrl=_),P&&(I.agentId=P),I}var Ad=`
|
|
98
98
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
99
99
|
|
|
100
100
|
Usage:
|
|
@@ -122,36 +122,36 @@ Auto-connect agent (optional):
|
|
|
122
122
|
|
|
123
123
|
Internal:
|
|
124
124
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
125
|
-
`.trimStart();async function
|
|
126
|
-
`),0;case"daemon":{try{await
|
|
127
|
-
`),1;if(
|
|
128
|
-
`),1;let
|
|
129
|
-
${JSON.stringify(
|
|
130
|
-
`),0}async function
|
|
131
|
-
`),0;if(
|
|
132
|
-
`),0;try{return await
|
|
133
|
-
`),0}catch(
|
|
134
|
-
`),1}}async function
|
|
135
|
-
`),1;try{let
|
|
136
|
-
${JSON.stringify(
|
|
137
|
-
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(
|
|
138
|
-
`),1)}catch(
|
|
139
|
-
`),1}}async function
|
|
140
|
-
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(
|
|
141
|
-
`)}await new Promise(
|
|
142
|
-
`)}catch(
|
|
143
|
-
`)}let
|
|
144
|
-
`)}catch(
|
|
125
|
+
`.trimStart();async function Ma(n=process.argv,e={}){let i=Cd(n);switch(i.mode){case"help":return process.stdout.write(Ad),0;case"version":return process.stdout.write(`${hn}
|
|
126
|
+
`),0;case"daemon":{try{await Aa()}catch(a){return Ed.error("daemon start failed",{err:String(a)}),1}return new Promise(()=>{})}case"status":return kd(e);case"stop":return Pd(e);case"refresh":return Id(e);case"uninstall":return Dd(e);case"install-service":return Td();case"pair":{let a={};return i.env&&(a.env=i.env),i.handshakeUrl&&(a.handshakeUrl=i.handshakeUrl),i.frontierUrl&&(a.frontierUrl=i.frontierUrl),Rd(i.privatecode,i.pairingCode,e,a,i.agentId)}}}async function za(n){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(n.pidFile).catch(()=>{}),e(n.portFile).catch(()=>{}),e(n.tokenFile).catch(()=>{})])}async function kd(n){let e=n.paths??K(),i=new Xe(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
127
|
+
`),1;if(a.kind==="stale")return await za(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
128
|
+
`),1;let c=await i.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
129
|
+
${JSON.stringify(c.body,null,2)}
|
|
130
|
+
`),0}async function Pd(n){let e=n.paths??K(),i=new Xe(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
131
|
+
`),0;if(a.kind==="stale")return await za(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
132
|
+
`),0;try{return await i.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
133
|
+
`),0}catch(c){return process.stdout.write(`coze-bridge: stop failed: ${String(c)}
|
|
134
|
+
`),1}}async function Id(n){let e=new Xe(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
135
|
+
`),1;try{let a=await e.request({method:"POST",path:"/refresh"});return a.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
136
|
+
${JSON.stringify(a.body,null,2)}
|
|
137
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(a.body)}
|
|
138
|
+
`),1)}catch(a){return process.stderr.write(`coze-bridge: refresh failed: ${String(a)}
|
|
139
|
+
`),1}}async function Dd(n){let e=new Xe(n.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
140
|
+
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(u){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(u)}
|
|
141
|
+
`)}await new Promise(u=>setTimeout(u,500))}if(!n.skipSupervisor)try{let{getSupervisor:u,buildContext:f}=await Promise.resolve().then(()=>(ps(),gs)),l=u();await l.uninstall(f()),process.stdout.write(`coze-bridge: ${l.platform} supervisor unregistered
|
|
142
|
+
`)}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
|
|
143
|
+
`)}let a=n.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}
|
|
144
|
+
`)}catch(u){return process.stderr.write(`coze-bridge: remove failed: ${String(u)}
|
|
145
145
|
`),1}return process.stdout.write(`coze-bridge: uninstalled
|
|
146
|
-
`),0}async function
|
|
147
|
-
`),await
|
|
146
|
+
`),0}async function Td(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(ps(),gs)),i=n(),a=e();return process.stdout.write(`coze-bridge: installing ${i.platform} supervisor...
|
|
147
|
+
`),await i.install(a),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
148
148
|
`),0}catch(n){return process.stderr.write(`coze-bridge: --install-service failed: ${String(n)}
|
|
149
|
-
`),1}}async function
|
|
150
|
-
`),(await
|
|
151
|
-
`)}let
|
|
152
|
-
`),await
|
|
153
|
-
`),1;let
|
|
154
|
-
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(
|
|
155
|
-
`),1)}catch(
|
|
156
|
-
`),1}}async function
|
|
149
|
+
`),1}}async function Rd(n,e,i,a={},c){let u=new Xe(i.paths),f=i.spawnDaemon??ka;if(!i.skipDistInstall){let w=await Ta({paths:i.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
|
|
150
|
+
`),(await u.probe()).kind==="connected"&&(await u.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
|
|
151
|
+
`)}let l=await u.probe();if(l.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
152
|
+
`),await f({paths:i.paths}),l=await Nd(u,i.waitTimeoutMs??1e4,i.sleep??Ld),l.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${l.kind}
|
|
153
|
+
`),1;let p={privatecode:n,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 w=await u.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});return w.status===200&&w.body?.ok?(process.stdout.write(`coze-bridge: paired (${w.body.note??"ok"})
|
|
154
|
+
`),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
|
|
155
|
+
`),1)}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
|
|
156
|
+
`),1}}async function Nd(n,e,i){let a=Date.now()+e;for(;Date.now()<a;){let c=await n.probe(500);if(c.kind==="connected")return c;await i(200)}return n.probe(500)}function Ld(n){return new Promise(e=>setTimeout(e,n))}Ma(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
|
|
157
157
|
`),process.exit(1)});
|