coze-bridge 0.1.30 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +58 -57
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,25 +5,25 @@ import { dirname as __coze_dirname } from 'node:path';
5
5
  const require = __coze_createRequire(import.meta.url);
6
6
  const __filename = __coze_fileURLToPath(import.meta.url);
7
7
  const __dirname = __coze_dirname(__filename);
8
- var p0=Object.create;var _r=Object.defineProperty;var m0=Object.getOwnPropertyDescriptor;var w0=Object.getOwnPropertyNames;var _0=Object.getPrototypeOf,y0=Object.prototype.hasOwnProperty;var X=(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 De=(n,e)=>()=>(n&&(e=n(n=0)),e);var oe=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Os=(n,e)=>{for(var i in e)_r(n,i,{get:e[i],enumerable:!0})},b0=(n,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of w0(e))!y0.call(n,c)&&c!==i&&_r(n,c,{get:()=>e[c],enumerable:!(a=m0(e,c))||a.enumerable});return n};var Ie=(n,e,i)=>(i=n!=null?p0(_0(n)):{},b0(e||!n||!n.__esModule?_r(i,"default",{value:n,enumerable:!0}):i,n));import{chmod as v0,mkdir as S0,readFile as E0,rename as Bs,writeFile as Ms}from"node:fs/promises";import{dirname as C0}from"node:path";async function at(n){try{let e=await E0(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Yt(n,e,i){await S0(C0(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 Ms(c,a,{encoding:"utf8",mode:i.mode}):await Ms(c,a,"utf8"),await Bs(c,n),i?.mode!==void 0&&await v0(n,i.mode)}catch(u){await Bs(c,c).catch(()=>{});let{rm:d}=await import("node:fs/promises");throw await d(c,{force:!0}).catch(()=>{}),u}}var Zt=De(()=>{"use strict"});function Fs(n){return en[zs]<=en[n]}function yr(n){qs={...n}}function Qt(n,e,i,a){if(en[n]<en[zs])return;let c=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:i,...qs,...a});n==="error"||n==="warn"?k0.write(`${c}
10
- `):A0.write(`${c}
11
- `)}function N(n){return{debug:(e,i)=>Qt("debug",n,e,i),info:(e,i)=>Qt("info",n,e,i),warn:(e,i)=>Qt("warn",n,e,i),error:(e,i)=>Qt("error",n,e,i),child:e=>N(`${n}.${e}`)}}var en,zs,A0,k0,qs,K=De(()=>{"use strict";en={debug:10,info:20,warn:30,error:40},zs=(()=>{let n=process.env.COZE_BRIDGE_LOG_LEVEL;return n==="debug"||n==="info"||n==="warn"||n==="error"?n:"info"})(),A0=process.stdout,k0=process.stderr,qs={}});import{homedir as P0}from"node:os";import{join as ne}from"node:path";function G(n){let e=n??P0(),i=ne(e,".coze"),a=ne(i,"bridge"),c=ne(a,"lib");return{cozeRoot:i,bridgeRoot:a,libDir:c,libEntry:ne(c,"index.js"),pidFile:ne(a,"bridge.pid"),portFile:ne(a,"bridge.port"),tokenFile:ne(a,"bridge.token"),logFile:ne(a,"bridge.log"),installLock:ne(a,"install.lock"),configFile:ne(a,"config.json"),agentsRoot:ne(i,"agents")}}function Te(n,e=G()){let i=ne(e.agentsRoot,n);return{root:i,config:ne(i,"config.json"),workspace:ne(i,"workspace"),logs:ne(i,"logs")}}var ce=De(()=>{"use strict"});var rn={};Os(rn,{AGENT_CONFIG_FILE_MODE:()=>tn,enforceAgentConfigMode:()=>T0,loadAgentConfig:()=>xe,persistAgentSessions:()=>br,persistAgentSkills:()=>nn,saveAgentConfig:()=>pe});import{chmod as D0,stat as I0}from"node:fs/promises";function xe(n,e){return at(Te(n,e).config)}function pe(n,e){return Yt(Te(n.agentId,e).config,n,{mode:tn})}async function T0(n,e){if(process.platform==="win32")return;let i=Te(n,e).config;try{let a=await I0(i);if(!a.isFile())return;let c=a.mode&511;c!==tn&&(await D0(i,tn),Us.warn("agent config mode auto-corrected to 0600",{path:i,from:c.toString(8)}))}catch(a){if(a.code==="ENOENT")return;Us.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:i,err:String(a)})}}async function br(n,e,i){let a=await xe(n,i);a&&(a.sessions=Object.fromEntries(e),await pe(a,i))}async function nn(n,e,i){let a=await xe(n,i);a&&(a.skills=e,await pe(a,i))}var Us,tn,Ue=De(()=>{"use strict";Zt();K();ce();Us=N("agent-config"),tn=384});var Wi=oe(Y=>{"use strict";var S=T;(function(n,e){let i=T,a=n();for(;;)try{if(-parseInt(i(1014))/1*(-parseInt(i(1341))/2)+parseInt(i(1773))/3*(-parseInt(i(614))/4)+-parseInt(i(1166))/5+parseInt(i(696))/6+-parseInt(i(1694))/7*(-parseInt(i(1415))/8)+parseInt(i(1378))/9+-parseInt(i(1570))/10*(parseInt(i(1731))/11)===e)break;a.push(a.shift())}catch{a.push(a.shift())}})(Rn,452403);function Rn(){let n=["zNvUy3rPB24","CYbWyxjHBxm","z3jXuwG","zxjYtxnN","vhvPBNC","EMT6ANC","C3Hxr2G","x3jLy29UBMu","EePwzxe","ywr2yw5Jzq","wezlBw8","y29TCgXLDgu","Cg9PBNrbBMq","CMvTB3zLrxy","vhbHy08","EgD2D28","y3vYC29Yx2y","sLnKEge","DvD4wLK","zuXlB1q","yLv2Ehi","Ewruy3a","yKTfy3K","svf3u0e","u0XMwvC","z01ky3y","B25tDgfYDfi","zw5HyMXLvhi","zu9vA2K","A2jMr0G","Ehb1qvC","CMvHC29U","nNW4Fdb8mta","rMzgCuW","tvjnzMK","Aw9UvgLTzw8","teXkuem","AxjLza","t2nAEwC","BwvZC2fNzv8","tKLWELO","EezrwNa","vNbwBg4","wxresK4","vKjiuNK","ChPUCuS","q0TPBue","l3DZl3yY","wwzTtui","C2nYAxb0","zcWG","suLnzxi","A0foALy","CMvQzwn0","z1rAz1G","Cg9W","y2fprKy","C2v0sxrLBq","q2vkEw0","yM5gwNy","tuPusha","AfngBMW","qwP0AwS","x29UugfNzu4","suHlyum","wwXOyvy","yLjiCMy","qNHRDfi","DMvUDa","ignVzgu6ia","C2vYDMLJzs0","q291BNq","whfRDNm","zuX6rxK","vuT1BwS","qLvmzgq","vu9OAue","rhjvt08","B25VCgvU","ig1LC3nHz2u","Ae9Wzw5fDMu","BvvJAhy","ihzHBgLKihm","BKXNrMC","tNDmywO","D2fZq2XLyw4","z1vjDLm","u2jcyLe","Ae1LC3nHz2u","yKLsDM8","x3bYzwzPEa","x2vUzhbVAw4","rK1uAvy","ywnRtxnNswq","Dg9cExrLC0W","B2jQzwn0u3q","zw5NDgG","z0DsAwe","C3rYAw5NAwy","zNjHBwvuExa","DMHOteq","yMjqzfO","y29UBMvJDeu","uwXzu3m","CxDyvhC","yMnXu1O","z1fJB0q","DeLUDgvYy2u","Axnby2TdBgu","zNjVBNrPzxi","x3bPBMDmB3m","D2fiB1m","q3fVDey","x3jLBw92zvC","EvPztMm","B25LCNjVCG","zfDVCMTLCKC","mJC0odLoteLSt0q","yMLUza","DNv0Buu","uxj1zhi","EKHVvuO","whPXBha","BLv6q08","ChjVDg9JB2W","CMfTzq","C2DPza","yM9KD0u","u0XvENG","v25hA2S","CMvZzxrdB3u","CgjyvuK","rfjctK0","zxbOrem","x2LZtwLUAvC","C0Per3O","EvrHuxq","ihzHBgLKigq","q3vvEgC","u3HKA2e","igzPzwXKoIa","ywDL","mxW0","B25TzxnZywC","qwDYD28","yxrLq291BNq","DhjPzxmGCMu","vgLnsvK","ChPgD0C","yxnJCMLWDa","CKnPsxu","zxjFAxnFywm","CMfTugfYyw0","C0jf","odq1ouHtCw1qwq","B25ozxr3B3i","wNrLzMi","z1LeDhy","AMvJDfn0B3i","CNnVCL9Uyw0","u3bts3q","C1nrshG","qM1Prhe","AwrI","zgLZCgf0y2G","yw51Eey","x2jPBMfYEvq","CgLUz1rPBwu","BIWGAg9ZDg4","Bg9N","DM1SBw4","rLnXsLK","yKvABvK","y2XLyxjtDg8","zgvSzxrLrge","BuPLDLm","Bfjeu2C","rKvAy0G","y0fqC2i","zw50","tu51DuW","tfPvqM4","EKPZAhC","AgLNAa","Aw5N","BgLUzw5V","B01jtfG","CgLUz09Uy2u","BgLUzq","AevYCM9Yrxy","r05Az3e","CNPlEhy","tw9KDwXL","qMDxCuW","vMvytwS","BezSDxnO","nduYnJfZs2Hftxq","rK1Wy2W","Fdz8m3WY","BK9kAfe","AeL3Cu0","qNborwS","vwDbsLe","BKrdwuW","Aw5KzxGGB3u","vvr5veW","r2PzwxO","vK9xrKG","BgrrvNK","BxnN","rg1jEum","BvDxEgu","y1fzsfG","Aururvy","y29yCwi","ANHev0W","Au1cvNa","ywX3yxLZ","B3LVDvm","C3vIC3rYAw4","r2HftK0","zg1Azvy","B055wg8","q29UzMLN","rw5grey","De1HBMfNzxi","AgvHzgvY","yxfJEgi","ExbL","uNL1Du0","AhPyCuW","yxKSihrYEsa","ugf3u24","EfLVCge","B3L1teu","CM92AwrLigi","ChjVDg90Exa","y0nMEvK","yw5Hz2vY","zw5JB2rPBMC","vhbVyKq","y0DYs2e","DMfS","C2XVr3O","Dgv4Dc9Qyxy","zK11yNK","C3LZBva","rxrtB0W","Dvrzz1i","zvL1t2i","CgDbvfG","zgv2AwnLx2K","C0Tvrg8","sxP3sw4","Bgnrzva","zxjFBxnNAwq","qufXq3u","ChrVCG","AxnbCNjHEq","rNLIEfe","z2v0s2v5","uhjdBvG","ugfvuvO","EeTJBuG","DLnSy3i","CujrAuG","twDIy1m","Ce9HBMW","zM9YrwfJAa","o2nOyxjZzxq","CMLLC0nVDw4","zMzLCG","Dvr3uxC","B2zeD2q","B2fK","zuv2rfi","uK5zq00","y3vYCMvUDeu","yLD3A1y","y3jLyxrLt3a","Dw5RBM93BIa","Dg9cExrLCW","Bg9Nsurhzw4","ihjLy29UBMu","qLLoCfi","vMrLs1C","tvHRAhO","tfPZrwi","BMvLzf9Hy2S","D2jSt2S","Du9IBxG","qK5otLi","Bxbbr1u","zw5JB2rLrNi","Bgnlvhm","sxzxBfu","EwL4zLy","sKnsveW","swPztvq","B2rNAui","qLzItwq","rhjKvg4","CuDOENG","BNrLCG","EM5vANy","Dg9hzw5LCMe","svLhDeO","z2vjBMzVu3K","ve9fyNq","Aw1LCYbPBIa","BuHltxm","BwvZ","Bwu6ia","DgvmB2Djre4","sNLRAu0","z29PBMCGyxC","tfLHDxK","zMnmqui","ChbLy1C","BMv4DcGPigm","DK5bAKe","ruvHC2i","x3DZ","qxrRDLO","zw5HyMXLqxu","DwLTywS","twvZC2fNzuu","yvbpwNC","x29Ut3bLBG","y29JCuq","DKz3q0S","D3jPDgu","D25esgq","rwfZufq","Cg9PBNrdB24","Duz4CuG","BwLbu0C","tM9Sy1G","u29YELy","u3rYyxrLz3K","Bu9RCfa","BwfW","sgPwy2G","EfvZzuvUDG","wenvveu","v0P6sfi","yxv0B21HDgK","CYbPBNn0yw4","r0TXzMS","tuDIyue","u2vXsuq","uMfJANm","Bfn1Bhm","vu5SrMW","y3vYC29Yx24","BvPnD04","A3b5sK4","ueLVwwG","q2jRA2O","v2LUzg93","B3nLza","ihrVihjLDhi","Aw47y2HHCNm","DMfSDwu","x2nSzwfYugK","wKHSAwy","q3vczu0","CfL0yKe","y01kwM0","wgrwALC","q0Xpu0ve","Dg9mB3DLCKm","tMDcyLm","A25JChe","z3nKswe","CK9qwKS","x2TLEvbHDgG","ChjdAeG","ywXty29Wzq","x2LUDgvYDMe","yw16s0y","Dw9zz1m","BMrLEa","t0LzzgK","qMrZBee","ufnfEeu","zMLN","wuzYzfe","CYbHBhjLywq","sNrVChi","CMvTB3zLq2G","qKnzwe8","Ec1TC2CTy3u","rvjst1i","r1veBeC","BevRveu","EfvjyNq","CgHAtue","zxrxB3jRq2G","tefLB3a","swfPrey","t1bftG","t3bLBKv2zw4","wujQDhC","u2TOtgG","qNbWzfO","zeXOC3u","CeTqtxC","A25KCLO","A016s20","EhnQDhK","y2XNBMi","wgXoBwq","zcWGDw5RBM8","wvHQr2K","zgvS","zxjFDhrS","zMLlAuC","sLjtsvG","qxvNvw0","uuPeAhe","C2vUzf9Hy2S","rKf1A0i","BM93","zvnpzee","zxrsEvC","tMjfvfK","x21PBMLoyxy","t3vHquS","id4G","zgvSzxrL","B2n5Bfa","CMvZzxruCMK","wLjcELO","C3rLBMvYCW","qw5TwfG","x3nVy2TLDa","sfH2B2m","tuvtu0fhrv8","qKXoCLK","DxrMofDYAxq","BML0AwfSAxO","DhLWzq","ywrKq291BNq","uLjpuG","AgXeDwS","BxnNsuq","yMTOEKO","uMvJB25Uzwm","ywDLu2HVDW","x2fKzfDZtgK","CfnXChq","AMLiEge","t1Dmtu8","m3WXFdb8mNW","wwPcsuO","qNn3CKG","AxnrB1nnzxm","zfzivMG","zMzmAw5L","B2LUDfjLywm","B3jL","yxnZAwDU","DeL0qui","lcbxzwjtB2m","rxfuy20","C2v0u3rVCMe","qxjkrhO","vuPMyxG","sNzmCKu","v1PVzee","CLfurNO","uen3vg8","D24GCMvHC28","zLDtAu4","sKTmALu","uLHiwMO","DevOEhi","Bg9IywXty28","qNjHBgi","Bhm6ia","DxbKyxrLq3u","q2zot0W","DuDxuxe","Dhr3Awq","reP3vM4","C2fNzq","ufPND0O","x3fVC0rc","vePODhG","AvPKveC","zKXsyuO","wfLAs0W","CgLUz19VBMm","yKjtz0G","AvPyq0G","vu9YqNy","EKHtDfq","A2T2BNu","mty0EenLBKXW","ExzhAxq","B25nzxnZywC","zNjVBunOyxi","r2fWveK","svrjyK0","x2LZv29YA2u","B25dBg9Zzq","zwn0","DMXVBKC","BKnHA2K","q3jlv3e","Dw50","zg9Uzq","Cuz1rhy","uKHKC2S","EeTJAgW","rxrwA2i","yNjTCKq","veXnzxi","y29Uy2f0","uMr4uuK","t2vhqNG","tg9Nsuq","CMvZDwX0","tuLJC0C","BhLNA3O","DgHHBIbSB2m","sfzNAxy","r0ndD2q","zMX1C2HfEha","B2nRzxrtDwm","C3rVCMu","B3bLBKrc","Du1qywG","qw1VDw50","y29UDgv4Da","DKPRsfe","BwLZzq","A0Ddvhi","DhjHBNnHy3q","y3jLyxrLrxi","ywfpCfa","rhHxC0m","EgziEKK","suvtx0vsuK8","DgvZDa","qLnbENe","ywjVCNq","y3vYCMvUDeK","q0zLB0K","qMHqy3q","D1n3s08","q3vZDg9Tq2W","C3jJ","C2v0q3vYC28","q3P1Agi","wgz5uve","A21iwha","AKDJsLe","ENnkyNa","reLhENG","CNLwBwS","y2PyEKm","B2zM","m3WWFdr8mNW","yuzJq2y","uKXKzhy","AvLSENu","s2fpue4","sNrss1K","BwfUDwfSihi","y3ruAw1LB3u","zxjHDg9Y","BgvY","zxjFywnRx20","zNHnD1u","y2XLyxi","yKTPB0O","seTJyKO","x2nVBM5Ly3q","DxrVuMvJB24","nte2odq4ngPkBwjXwq","Eg9fy1G","u2HLq08","wfbgueS","r0TbrxO","ywnRDxbfBMq","qxbzr0u","x1fVu01HBMe","x3bYB3rVy28","vhjyBwu","DxnsCum","shnSy3u","vwDot24","Ef9MCM9UDgK","wLLcq2W","A014r2C","s3Ddug8","BvHLrgO","B3jRig9MzMW","qLzxEKm","ywDLsgLKzq","CLHbsem","CM92AwrLihy","B25mAw5L","Aw9Ul2PZB24","C3bSAxq","DxbNCMfKzw4","Dhj1y3rVCIa","z2v0sxrLBq","CufiC2K","x3nLBMrby2S","CMfNzvn5BMm","DMvY","B0LTr1m","CfzXDeW","x2n1CNnVCK0","ihrPBwvZ","y291BNq","t2Hkqvu","Dw9qDeK","zfv2u2y","x2nYzwf0zvm","vhLHsxu","EwPOzxi","zxjYB3i","tg9JAW","wKTMs04","wfjqrgS","B25SAw5L","zxmGCMvHy2G","sg92ywO","CgXLyxnLiha","C0fWuue","D1LdAhm","s2TjqwW","t1PQvxq","DxjS","BwvKAwf0zwW","DhjcvLa","Dhfbu0K","vgLTzw91Da","rNnLBwu","BgLktue","mhWXFdv8nW","AM9PBG","q0vRBhm","y29UBMvJDca","BNziAe8","CMvJzxzPzwq","sgDhu1a","DgfIyxnL","AenSB3nLrxy","BKjcCuC","A2v5","BfLJtvu","x2DLBMvYyxq","thbVBxC","Ahr0Chm6","sufZv08","tMfTzq","rKHAwu4","EMH0wLq","y2XVC2veqG","yLvwCuC","AKj0yM4","qKTbtKq","x0rctMfTzq","x2nSzwfYvgK","zgPUrum","Dgv4DfbHEwW","vNDHA3a","Aw5KzxG","CMvWBgfJzq","ufrxCKe","swX3rw4","AgLnAMy","ihrYEsbYzwm","EMrts2m","C0PSCNe","z2vQqMu","rfbcvg4","x3bPBMDqB24","Dg9Y","y0rtBLa","BfH3tLa","yw1Lu3bHy2u","BM9Uzv9UB24","zvr1yMu","x2LZtM9Kzq","q09oveLovuu","x19LC01Vzhu","sLnptLa","yvnMswy","sKj4zK4","x2DLDeLUDgu","rfHfzge","Dev2zw50","ENzbvfa","ruTyDhe","uezvugS","zg1lv3K","AwXK","vxj2wvm","r2HwDuW","uKreALK","qMvdv20","zMLSDgvY","rxHkDu0","u21ZyuO","Bwf4tg9ZC0m","qufAC04","y3jLyxrLt2i","C29YDa","BMnVzgLUzW","seT2BfC","DvrVDvi","B0DqEu8","quXm","DgzcBxC","CvPWzwi","yMfJA3vWigu","t3nzBu4","CwHrvLi","zxzkvfC","wuPpAvm","AKHWyvG","DfLdsfa","v0fLDxC","vvfqDvu","CgLUz0LUDgu","zw5XDwv1zq","DwvqDuC","DgHLBG","C0Xf","y2f0y2G","tvf0yNe","CeL2yNe","yw9Hrvi","uuveD3O","qLnerMK","tM5lqNC","zxf1ywXZ","EMrsv1a","AwDHDg9Yt24","CffWDMe","DLbiue0","CM9WzfK","z1v2DMK","y2HLy2TdDxi","A2zKtMG","BMvY","CMvZzxrfBMq","t0Tgtei","rKjqz1K","zxjYtM8","AxfVCwK","y2HHCKnVzgu","v1nWt1q","reiGzMfPBgu","zMLSzw5HBwu","x2rLyNvN","BfPLquW","ANHYAu0","y2HLy2Tszwe","Aw5PDcbrB1m","AgfUz2u","Bwf4uMv0CMK","s0nPDfy","y29UBMvJDa","wKfus1C","BwjdBxO","vurVC2e","s1zkzfq","C2vYDMLJzq","whjAqM8","DKXNC3m","ywnR","ruPKvMC","s3DwyMC","qNjPzgDL","BMrWB2LUDfq","CfnkvM8","B2nRzxrgywK","C2vUza","x2rItMfTzq","uLDZA3C","tKXhBvi","B2zMBgLUzq","rxjYB3jdB2q","CNnVCL92ywW","Bg9NsurozxC","r290ywm","qNHZufq","zwvKzwq","ihn1y2nLC3m","yKXUrhi","yvboDhu","AKDosMS","CM92AwrLihC","uuzeAwS","z2v0qwXS","uhjPBwfYEuS","Ewj2Eu8","CNH1Bvi","suz5CeW","zvvYBa","CMvJB25Uzwm","B2nRzxq","zwHTCxO","rLPUrui","x3bPBMC","D2z3rKG","y0XXuhi","yu15s3e","vhnKzuG","zNjVBu51Bwi","u2Hsvvi","BhrPCgXLihq","x2LZqNjVD3m","AMPUzuO","Du9YC0G","B25tDg9Wsw0","vNDjyLG","uevlquC","yNL0zuXLBMC","rvrPyNe","igXHCMDLCIa","x25HDMLNyxq","A25MEhm","C2vUDa","tfjmswS","z2vY","BM5xyxm","Dg9oDw1Izxi","q3vZDg9Trxi","y3jLyxrLtwu","D1PYue8","yw1LoIa","rgfHAu0","rNjVBNrPzxi","AK10qvi","EKvwA04","CgLUz0XVC3m","BKvvsxO","D1Ppq2i","BgLTAxq","yxbWzw5Kq2G","rNzrr2C","tgjVEg4","m3WYFdr8mxW","x3vYBa","y3bqrfu","Aw9U","AwzyzxG","rfjZEuW","yMfSrxzLBNq","tgnMte8","t1rgsMe","EsbJBg9Zzwq","BLzyDhC","C3LkEva","rLjZsfq","vLnPC2W","CM92AwrLige","u3DzEfm","D2zeBe4","EuXHuvi","x3nLCuLK","r0zhz3C","Cvfhwu0","u2HHCMvKv28","B25pCgvU","rwzJEem","Cvzot00","r1HJuuK","CNnVCKzPBgu","Cgf5Bg9Hza","uNbIsha","ywrK","tvfKsfC","z1rPBwvVDxq","y29ADK8","zuX4uNC","zw5HyMXLuw8","BMDuwLy","x3DHAxq","s0PXB0S","s05qChq","BNrfBMrWB2K","x3bHDgHlzxK","yM9L","q09otKvdveK","x2n1CNnVCKy","tLr2vuS","ruLsA0S","s1bSwei","CMv0CNLdB3u","zLvgzLi","mvrYu1HmAG","z2u6ia","wKLpvNK","yxnL","weTfv3q","s1v3wwK","CKXjzuq","CMvHzhDYAxq","wgHjsvK","DxfisKq","BLDsreW","yMrFzgLK","yLrJqwW","uxzODKG","C3bSAwnL","C3rYAw5N","yKrzy1a","x2LUAxrqCM8","BwLUzW","zwPrueO","vNzhCwy","AxnFywnR","Cu9oCvi","vxbKyxrLq28","ChbL","vMfQBgi","uwXpwKu","DujNzge","whvntMq","z2v0qwXSs2u","mdaWmdaWmda","x29UtwvZC2e","BLbpvg8","B3vUDa","EK52rw8","BwPrq1K","rwvnq2K","wLr2Agy","DhDVCMTdAge","AxnszwfKEq","BKXPBMu","AKfgqMm","mNWWFdr8nNW","A2juEwK","zKPKyMW","x21LC3nHz2u","zMLUza","BLvWCxm","y3jLyxrLq2W","ENvIvLC","yxjJtLa","CLHlzMm","B1bcu3i","DLvYzvO","DxnLCKLW","A0jvs0m","BNrlz2q","Dg9cExrLC0i","rwfjELe","EvzRt1e","y1P2uee","vffRCMi","y2XVC2u","B2zcrg8","yNvMzMvY","BgrfC3q","Bg93","zxrcwKC","uerZBuW","uLjezvm","ru5mD2S","yw5ZzM9YBvq","ywzL","z2v0q3vYCMu","ufrWzhy","yw51Ce1LC3m","ufzwvuy","Efrurw52","vfnJzfe","B2DzwMq","x2zVCM1HDeu","EMnJwxi","CMvHzg9UBhK","BgjosNi","Be9MvMG","A0rzv00","AwDfBxq","t3vRCe4","zvjqqxe","Cw9Zx18","CvbWCe4","Dg9VigXHCMC","AwziExy","qwjVCNrfCNi","tez2rui","AefJA01LC3m","zuDYsxe","CgfYC2u","yMXVy2TLza","y3vYC29Y","vgnjC28","zLjHA24","yxbWBgLJyxq","BMCGzMfPBgu","x3jLywr5q2W","AgvHzgvYCW","s0LQteG","z2v0q3vYC28","Eu5it3y","rgH4qxy","CwfAu1O","B25JBg9Zzq","yMLUyxj5","igzHAwWSig0","Ec11C2uT","Aw5KzxHpzG","tgLZDgvUzxi","CgPRAgG","rgjeuNm","DcbSAw1PDa","z3juEhy","AgvKtwf4uMu","su5tvefova","B0nUC3i","B3jpBMXPBMu","zMXVB3i","vgLJuhi","x3DZsw5ZDge","DKjLuM4","A1rMvwO","AhHTAuS","Dxrjza","ywnRx2nVzgu","y2fSBa","v2XlyLe","ALPvDhC","qwL0ExO","u0XArMe","tufyx1jfvfi","z2v0u3rVCMe","zNjVBuHHC2G","ChjVy2vZCW","CMvXDwLYzwq","B2D0ruS","AwXLtMfTzq","ELbWDeK","C3nHz2vfDMu","ywrKt25L","ywWGy3vYC28","yxbWBhK","B3bLBIa","AuLStM8","otmXmJyWywXUEM1R","zxHWB3j0CW","u2vRwKi","wgjgrMi","y0D4tw0","x2rYB3bhBg8","rxLirKy","y25Aswy","v2vPEgLUsLm","A1zvCei","ALroBeK","zwrPyxrLBhK","rLjptLrjrvi","sfzvsu8","BMDLza","B25szwnLAxy","AuL4zgm","yMLUyxj5vhK","A2Tkuxa","zw5KCg9PBNq","zKPgv20","vw5Oyw5KBgu","CMvHzfvjBNq","ENfIueq","DMvYC2LVBMm","tLDbuLC","CMvZB2X2zq","Cgu6ia","DKTVDNm","yw1L","zhLzteq","zgvMAw5Luhi","Cgf5Bg9Hzfq","DgLTzw91Da","nxWXmhWWFdK","shnMA3e","x2LZsw5PDa","y0riExm","D2LSBfjLy28","y29SBM8","uLjwufK","Bujlrha","z2v0","s0j3zfu","C2v0y3vYC28","yM9KEq","s2X4z3C","uu5ezfG","CgjICdi","zxH0zw5ZAw8","uuTlwwu","BNruCMLLC0m","A09uuxm","Dg5sDvu","EMnMBLO","jMPZy2fSBgi","x2HHBMrSzu8","wLP3rvK","z09uENy","qw5Uv3C","rhHKAKu","r0PnEKi","BuPTtuK","y21fDvq","D2rHAgu","whbUwei","DgfYz2v0","Cg93","u2TPCcbWyxm","CwTetxe","quf5BLm","tg9NsurozxC","zM1XAvO","CKHXr0q","Cvnprhe","txzbD1C","vhzfyMe","A0rkzfO","yNLus1m","tgnxvKW","rLHzqvC","v2vIu29JA2u","yvDRyKO","t1L0DNa","Cwzur0O","DMLJzuLeig8","D2rcs04","v29uyxa","r3LsD1e","A1vtBxu","uMDXANy","zMn4zM4","DMLXqxO","C0nVDw50zxi","x2rPC2nVBM4","A3Heuve","ugL2D2q","EMD1Aei","x2rPC3bHDgm","z1b0AhC","vKLuC0G","x2XPC3rLBMu","ruz1s3u","reL3EKO","A1n0yxr1C0m","qM9ZB0y","x2n1CNnVCK4","wwvZz2K","swPWu3y","C3vMv2S","BMv3vMvYC2K","zNjVBuj5Dgu","DwjnuNy","D1Deu1a","yLLNuwW","BMfTzq","BwvZC2fNztO","DfHSqxa","BwvZC2fNzq","yMT2uKC","y2HtBvK","zvL5qxa","C2L1DLK","sw9OwMO","t0rYrgy","q3HNu0G","zv9ZDwnJzxm","DeLK","Dg9tDhjPBMC","r0r1AMK","BxnNuw8","sfvxvuC","yMfiBMu","Dg9iyxnO","B3jRzxjhBg8","Bwv0Ag9K","zNjIsxG","tM1cvuO","t2jQzwn0","tLHYExa","uLLzBNa","wMXJD1u","rhHczvy","C3rHCNq","s21LExy","y3r4","whbUrva","Aw1xwNO","ugvwAMe","BuHZreq","wLHjrLi","zgXLCve","x2LZtwLUAvq","vhbWvhm","uMPIBuS","BgLZDgvUtMu","Dgv4Dc9WBge","yNLL","y29UDgLUDwu","z3bruw8","BgvUz3rO","BuLMsha","D3jPDgvvAw4","yMvxy2C","thPlvwi","yvb1sKG","rgvKAwnHDgu","rurKA2q","C3vJy2vZCW","AxnmB25N","B0npCum","rMHVCNO","zcbLCNjVCI4","zwPOr1G","Dw5KzwzPBMu","mti2mZCWnNHiuxL2Cq","vw5PBxbSzw0","m3WXFdu","vgfN","z0nZz3C","rK5SA0u","y3vYDMfSDwu","CM9YrxzLBNq","txDhA1m","BeHHBMrSzxi","sfnRqNO","y29UBMvJDfm","zfL2AgS","BwvY","q3D2ww0","yNvMzMvYzwq","uw1JsK4","DK14tfK","rvHZrMy","ChbNB3e","zwjrEeO","y3jLyxrLrwW","zM9Yy2u","z2vtEw5J","EKjVt0u","zw50tgLZDgu","AungCfK","DfndA08","AxnrB1nby2S","AwXSihvZzsa","DgXkBNC","CNzHBa","C3vIyxjYyxK","r01qtKC","tg9uBwy","u3jWCg0","CMvWBgfJzui","mJqZota5C1LIDgTQ","sxzmr28","tuvMr2m","zgvJB2rLzey","x2LUAxq","q29Kzq","BfrPBwvVDxq","lcbTyxGGCMu","rvvyt1m","BMLgr3i","BMvJDa","B3jLtMfTzxm","B3vvtxq","BxD5s1q","z1j0yxO","zKrxzNK","mhW1Fdn8mNW","B2Dqvhi","s3bqq0i","vwXYyvO","zxj2AwnL","ywfLrg4","CgfNzxnOB3C","zgf0yq","sNLbDLK","uvjMugW","t1bftL9fuLi","yNL0zxm","rxzLBNq","zef6sLC","DvHLBKK","zxjFCw9Zx2e","zufJAW","q1j0vNm","B2XKvMvYC2K","zxjFCw9Z","ChvZAa","mtmZnKnKDhjxrG","C2v0","rxvvqw8","u0H5Auy","y3jLyxrLuMu","Cgf5Bg9Hzeu","wK91BMi","AvznCuS","AKzOBgm","DfjtD3e","Der0Agi","yw5Nzq","EvjLy29UBMu","B3jutey","CfHLvgW","BNrbBMrvCgq","sMftv2O","uM12rMO","s0L3BKS","t3bcEg4","D1DJDgC","zxH0ugf5Bg8","zLHNwuW","CNjVCK1LC3m","yxGGCMv0CMK","uuLgAuG","t0zHAKO","qxPNrgK","ywXSzwqGBxu","CxHbtg4","BMDuAw1LCG","CMvKDwnL","x29WDgLVBNm","tMrUEg8","zgXTEgu","wurhB2C","zv90Aw1LB3u","Aw5HEKW","uLrZz3m","x29UrxjYB3i","zwnVBM5Ly3q","AffXBKO","DgLTzw91DcW","CLvStwu","zxq9DxrMltG","A2v5CW","q0Xpu0LorW","BxHIzKm","ywnOzwq","wuvyvNu","z2vrDwv1zuW","vfDOy20","tKrtD1G","zMzMzG","sNLqvfu","BLv0D1m","x2HHBMrSzvi","rLHWrwK","yxv0BW","ywDLrxzLBNq","tKDnDLK","ELLTBK8","vgHAvfG","BxbKDNm","y2vZC0HHBMq","Bw1Vuuy","C0Xpu2S","CgfNzwHPzgu","s1jZvvi","txL5uge","ywrKrxzLBNq","vLH2EgK","DMvYC2LVBG","B2zMC2v0","Aw5JBhvKzxm","wMjqwwy","CMvJzwL2zwq","CMTLCKDSB2i","x2HHBMrSzva","BMCGDxjSoIa","y2HnyxHdB3u","y29UC3rYDwm","AgfZ","Bwf4twvZC2e","Dw5ZAwDUzwq","y214BwS","y29UBMvJDgK","ihrPBwvVDxq","twLZC2LUzYa","zw1PDa","EM9SwMS","yxjYyxLIDwy","uvvHuuy","B3nLrxzLBNq","vunyDwm","CMvHzhLtDge","Aw5Lza","yKPnzM4","y29Kzq","uxvLDwu","B3bLBG","yNvUBgC","rLDQrKW","yxDquMu","zgLZywjSzue","BMrWB2LUDca","DLv6zwW","yNL0zu9MzNm","tKzRv04","tKfusvzfx0u","BePMB0e","C2XPy2u","D3nZoI8V","x2rLC3rYB3K","yuHAB2O","lcbOB3n0BMe","uNjcy0C","zNjVBujPDhm","ywXS","BwPLBwy","CNzHBfzHBhu","AxDNAxu","AgfZt3DUuhi","vfn1rvG","mhW0Fdn8mNW","B25Uzwn0Aw4","B3bLCNr5","EuDMA00","D2vI","CKTos2m","y2XVC2uSihC","t0Lwtvu","r0LVDK8","DhjPBq","C0XPC3rLBMu","rLDt","ywnOzwqSihC","DhjPzxm","z09srgi","rvDuquO","CxHpAgy","ruTYwe8","tMDjB08","ELzOuKq","D0HRtMm","tvH3quG","y2HnyxHuCMK","Fdv8nhWY","zLz0q20","zw5fDMvUDa","tfjgwNy","tg9bAe4","BMnLq2XVC2u","x2LUAxrhBg8","C0r3quu","mte5ntbIyLLoBuG","r2T6u3O","uMjqEMy","mhWZFdr8mNW","y3nXrLO","x29Uq2XVC2u","Bwvmt20"];return Rn=function(){return n},Rn()}var mx=Object[S(1197)+S(1541)],_x=Object["getOwnPropertyNa"+S(1888)],Ui=(n,e)=>function(){return n&&(e=(0,n[{XOrfJ:function(c,u){return c(u)}}.XOrfJ(_x,n)[0]])(n=0)),e},yx=(n,e)=>{let i={mgzTF:function(c,u,d,h){return c(u,d,h)}};for(var a in e)i.mgzTF(mx,n,a,{get:e[a],enumerable:!0})};function bx(){return Bi||(Bi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function vx(){let n=S;return Mi||(Mi=[IDBCursor[n(1813)+"e"][n(1586)],IDBCursor[n(1813)+"e"][n(1324)],IDBCursor[n(1813)+"e"][n(1324)+n(917)+"ey"]])}function Sx(n){let e=S,i={JSdxa:e(1334),fRakn:e(740),aWkbJ:function(c,u){return c(u)},BVbMd:function(c,u){return c===u},ODrDf:function(c,u){return c instanceof u},KaOPN:e(1700),JyPTU:e(984)},a=new Promise((c,u)=>{let d=e,h={OLjse:function(_,C){return i[T(1248)](_,C)},TScdQ:function(_,C){return _(C)},eLzEy:function(_){return _()}},p=()=>{let _=T;n[_(1590)+_(1366)+"ner"](i[_(1594)],w),n[_(1590)+"entListener"](i[_(1115)],y)},w=()=>{let _=T;h.OLjse(c,h[_(1092)](Ce,n.result)),h[_(1650)](p)},y=()=>{let _=T;i[_(1248)](u,n[_(740)]),p()};n.addEventListener(i[d(1594)],w),n[d(1485)+"Listener"](i[d(1115)],y)});return a[e(848)](c=>{let u=e,d={zpakw:function(h,p){return i.BVbMd(h,p)},IjpSv:function(h,p){return i[T(1877)](h,p)},KjgJo:function(h,p){return i.BVbMd(h,p)},mmoQF:function(h,p){return h+p}};if(i[u(1290)](c,IDBCursor)){if(i[u(1877)](i[u(683)],i[u(1469)]))return d.zpakw(-1,this[u(1080)])&&d[u(1274)](-1,this[u(1760)])?_0x421abb[u(1532)](0,0,this[u(1499)]):d.KjgJo(-1,this[u(1080)])?_0x5a9dec[u(1532)](0,d[u(1480)](this[u(1760)],1),this.unsigned):_0x36114e[u(1532)](d.mmoQF(this[u(1080)],1),this[u(1760)],this[u(1499)]);Tr[u(1416)](c,n)}})[e(850)](()=>{}),On[e(1416)](a,n),a}function Ex(n){let e=S,i={GCCwd:function(c,u){return c(u)},yWGAI:e(1107)+"or",ofDwd:e(740)};if(Nn[e(1497)](n))return;let a=new Promise((c,u)=>{let d=e,h={GXtIV:function(p){return p()},xgiCm:function(p){return p()},jdamF:function(p,w){return i[T(643)](p,w)},tkmHS:i.yWGAI,xYopa:function(p){return p()}};if(d(765)!==d(1712)){let p=()=>{let _=d;n[_(1590)+_(1366)+_(866)](_(1588),w),n[_(1590)+_(1366)+_(866)](_(740),y),n["removeEventListe"+_(866)](_(662),y)},w=()=>{h.GXtIV(c),h.xgiCm(p)},y=()=>{let _=d;h.jdamF(u,n[_(740)]||new DOMException(h.tkmHS,_(1107)+"or")),h[_(1810)](p)};n[d(1485)+d(1130)](d(1588),w),n["addEvent"+d(1130)](i[d(1850)],y),n["addEvent"+d(1130)](d(662),y)}else return new _0xc3c0b7(_0x493639,{data:_0x3fe959,message:_0x3ab2f8})});Nn[e(1416)](n,a)}function Cx(n){Bn={IohZj:function(a,c){return a(c)}}[S(1289)](n,Bn)}function Ax(n){let e=S,i={qAHsi:function(a,c){return a(c)},mpAGU:function(a,c){return a(c)},MvAwW:function(a,c){return a(c)},gPlmI:function(a,c){return a>=c},bkhzJ:function(a,c){return a(c)},LmngG:function(a,c){return a in c},fcxfn:function(a){return a()},MXkhz:function(a,c){return a===c}};return n===IDBDatabase[e(1813)+"e"]["transact"+e(968)]&&!i.LmngG(e(1672)+e(1389),IDBTransaction[e(1813)+"e"])?function(a,...c){let u=e,d=n[u(1147)](i[u(725)](zt,this),a,...c);return Ir[u(1416)](d,a.sort?a[u(828)]():[a]),i[u(1869)](Ce,d)}:i[e(1257)](vx)[e(1489)](n)?i[e(1863)](e(1227),e(1227))?function(...a){let c=e;return n[c(1163)](i.MvAwW(zt,this),a),i[c(725)](Ce,Tr.get(this))}:i.gPlmI(_0x2d93b9[e(1488)],_0xf9b409[e(961)]):function(...a){let c=e;return i[c(562)](Ce,n[c(1163)](i[c(1241)](zt,this),a))}}function kx(n){let e=S,i={SwYxS:function(a,c){return a===c},ABEzx:e(1577),fDWfy:function(a,c){return a instanceof c},pznqK:function(a,c){return a(c)},NbETY:function(a,c,u){return a(c,u)},pyrjZ:function(a){return a()}};return i[e(980)](typeof n,i.ABEzx)?Ax(n):(i[e(1393)](n,IDBTransaction)&&i[e(1622)](Ex,n),i[e(541)](Hi,n,i.pyrjZ(bx))?new Proxy(n,Bn):n)}function Ce(n){let e=S,i={JYNia:e(740),ACgSl:function(c,u,d){return c(u,d)},HHnMS:function(c,u){return c instanceof u},IjYMT:function(c,u){return c(u)},Ztefb:function(c,u){return c!==u},HKcbJ:e(624)};if(i.HHnMS(n,IDBRequest))return i[e(1875)](Sx,n);if(Tn.has(n))return Tn.get(n);let a=kx(n);return i[e(1733)](a,n)&&(i[e(1733)](i[e(693)],i[e(693)])?this[e(1504)](i.JYNia,i.ACgSl(_0x43abc3,i.JYNia,{..._0x4ebf04,message:_0x538d71.errMsg||""})):(Tn[e(1416)](n,a),On[e(1416)](a,n))),a}var Hi,Bi,Mi,Tr,Nn,Ir,Tn,On,Bn,zt,zi=Ui({"node_modules/idb/build/wrap-idb-value.js"(){let n=S,e={FBPgY:n(1029),vNAjA:n(1322)+"in;chars"+n(1459),eRPAq:function(i,a){return i===a},PZgwJ:n(1849),BNNNR:function(i,a){return i instanceof a},EuUAo:n(627),QmcJN:function(i,a){return i===a},XrZBo:"objectSt"+n(1389),aPOZw:n(646),wcOdn:function(i,a){return i(a)},uOrsH:function(i,a){return i===a},pSqpt:function(i,a){return i in a}};Hi=(i,a)=>a.some(c=>i instanceof c),Tr=new WeakMap,Nn=new WeakMap,Ir=new WeakMap,Tn=new WeakMap,On=new WeakMap,Bn={get(i,a,c){let u=n;if(e.eRPAq(e[u(602)],e[u(602)])){if(e[u(1868)](i,IDBTransaction)){if(e[u(1102)](a,e.EuUAo))return Nn[u(1208)](i);if(e[u(1357)](a,e[u(890)]))return i[u(1672)+u(1389)]||Ir[u(1208)](i);if(a===e[u(1904)])return c["objectSt"+u(1389)][1]?void 0:c[u(1672)+"ore"](c[u(1672)+u(1389)][0])}return e.wcOdn(Ce,i[a])}else return e[u(869)]==typeof _0x149efd?e[u(1897)]:""},set(i,a,c){let u=n;return i[a]=c,!0},has(i,a){let c=n;return e.BNNNR(i,IDBTransaction)&&(a===e[c(1417)]||e[c(936)](a,e[c(1904)]))?!0:e[c(566)](a,i)}},zt=i=>On[n(1208)](i)}}),Ki={};function T(n,e){n=n-455;let i=Rn(),a=i[n];if(T.CYGSpF===void 0){var c=function(p){let w="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",y="",_="";for(let C=0,I,L,R=0;L=p.charAt(R++);~L&&(I=C%4?I*64+L:L,C++%4)?y+=String.fromCharCode(255&I>>(-2*C&6)):0)L=w.indexOf(L);for(let C=0,I=y.length;C<I;C++)_+="%"+("00"+y.charCodeAt(C).toString(16)).slice(-2);return decodeURIComponent(_)};T.DQtcaJ=c,T.dnYBGa={},T.CYGSpF=!0}let u=i[0],d=n+u,h=T.dnYBGa[d];return h?a=h:(a=T.DQtcaJ(a),T.dnYBGa[d]=a),a}yx(Ki,{deleteDB:()=>Dx,openDB:()=>Px,unwrap:()=>zt,wrap:()=>Ce});function Px(n,e,{blocked:i,upgrade:a,blocking:c,terminated:u}={}){let d=S,h={KSXkC:function(y,_,C,I,L){return y(_,C,I,L)},WSpOT:function(y,_){return y(_)},pAOkR:"CneqL",MQdHW:"close",YnOjf:function(y,_){return y(_)},zYmnO:"blocked"},p=indexedDB[d(1515)](n,e),w=h.YnOjf(Ce,p);return a&&p[d(1485)+d(1130)](d(722)+d(909),y=>{let _=d;h.KSXkC(a,Ce(p[_(638)]),y[_(1412)+"on"],y[_(1276)+"on"],h[_(873)](Ce,p["transact"+_(968)]))}),i&&p[d(1485)+d(1130)](h[d(1476)],()=>i()),w[d(848)](y=>{let _=d,C={WZSDr:function(I,L,R,q){return I(L,R,q)}};if(h.pAOkR!=="CneqL")throw _0x222280=_0x38480e.length,C.WZSDr(_0x1970d8,_0x566f0a,10,_0x16466f[_(1326)]);u&&y[_(1485)+"Listener"](h[_(995)],()=>u()),c&&y[_(1485)+_(1130)](_(1190)+_(881),()=>c())})[d(850)](()=>{}),w}function Dx(n,{blocked:e}={}){let i=S,a={mbCmz:i(1112),cGrKa:function(u,d){return u(d)}},c=indexedDB[i(1751)+i(766)](n);return e&&c[i(1485)+"Listener"](a[i(886)],()=>e()),a[i(1818)](Ce,c)[i(848)](()=>{})}function qi(n,e){let i=S,a={VsjWI:i(1021)+"e",sJlrq:i(1096),mZMwN:function(p,w){return p instanceof w},ppecW:function(p,w){return p in w},pbXUI:function(p,w){return p===w},TQkrb:function(p,w){return p!==w},cDSnP:function(p,w){return p in w}};if(!(a[i(470)](n,IDBDatabase)&&!a[i(1895)](e,n)&&a[i(1708)](typeof e,i(1029))))return;if(Ln[i(1208)](e))return Ln[i(1208)](e);let c=e[i(788)](/FromIndex$/,""),u=a[i(1075)](e,c),d=Gi[i(1489)](c);if(!a[i(799)](c,(u?IDBIndex:IDBObjectStore)[i(1813)+"e"])||!(d||ji[i(1489)](c)))return;let h=async function(p,...w){let y=i,_=this[y(654)+y(968)](p,d?a.VsjWI:a[y(794)]),C=_.store;return u&&(C=C[y(787)](w.shift())),(await Promise[y(1533)]([C[c](...w),d&&_.done]))[0]};return Ln[i(1416)](e,h),h}var ji,Gi,Ln,Ix=Ui({"node_modules/idb/build/index.js"(){let n=S,e={NgBbS:n(1208),ybbAt:"count",RpbHp:"put",tCKeZ:n(994),AINFc:n(545),rQTFz:n(691),QIFiH:function(i,a){return i(a)}};zi(),zi(),ji=[e[n(487)],n(1837),n(916),n(1043)+"ys",e.ybbAt],Gi=[e[n(993)],e.tCKeZ,e.AINFc,e[n(586)]],Ln=new Map,e[n(1440)](Cx,i=>({...i,get:(a,c,u)=>qi(a,c)||i[n(1208)](a,c,u),has:(a,c)=>!!qi(a,c)||i.has(a,c)}))}}),Tx={idb:function(n){let e=S;n[e(1167)]=Promise[e(1192)]().then(()=>(Ix(),Ki))[e(848)](function(i){return i})}},Fi={};function Ee(n){let e=S,i={ThZTX:e(965)+"0",LRFZv:function(h,p){return h!==p}},a=i[e(1477)][e(721)]("|"),c=0;for(;;){switch(a[c++]){case"0":return d.exports;case"1":Tx[n](d,d.exports,Ee);continue;case"2":if(i[e(1565)](void 0,u))return u.exports;continue;case"3":var u=Fi[n];continue;case"4":var d=Fi[n]={exports:{}};continue}break}}Ee.d=(n,e)=>{let i=T;for(var a in e)Ee.o(e,a)&&!Ee.o(n,a)&&Object[i(1197)+i(1541)](n,a,{enumerable:!0,get:e[a]})},(()=>{let n=S;Ee.o=(e,i)=>Object.prototype[n(1537)+"operty"][n(1147)](e,i)})(),(()=>{let n=S,e={EtVkb:function(i,a){return i!=a},rCiIu:n(1340)+"d",CrKWq:n(1769),yKjVe:n(806)+"le"};Ee.r=i=>{let a=n;e[a(631)](e[a(1727)],typeof Symbol)&&Symbol[a(1294)+a(1344)]&&Object[a(1197)+a(1541)](i,Symbol[a(1294)+a(1344)],{value:e[a(625)]}),Object[a(1197)+a(1541)](i,e.yKjVe,{value:!0})}})();var $={};(()=>{let n=S,e={PIoYh:function(s,t){return s(t)},GQvlA:function(s,t){return s+t},GhVuL:function(s,t){return s+t},bodwE:function(s,t){return s>=t},JCRTL:function(s,t){return s===t},XYZKL:"PZfGn",vSlcr:function(s,t){return s*t},GDuji:function(s,t){return s*t},kUSmu:function(s,t){return s&t},EUXOS:function(s,t){return s>>t},nLgFg:function(s,t){return s<t},uXenI:function(s,t){return s|t},dYvhk:function(s,t){return s&t},TppTs:n(1484),iMBVp:function(s,t){return s(t)},GKAEz:function(s,t,r){return s(t,r)},EasPT:function(s,t){return s+t},hzXqL:function(s,t){return s(t)},bBSgH:function(s,t){return s(t)},kANjV:"0000",ldEst:function(s,t){return s!==t},zEVkN:function(s,t){return s!==t},GkzSz:function(s,t){return s-t},KBwdU:function(s,t){return s!==t},gsdIa:function(s,t){return s<t},DhxAv:function(s,t){return s<t},DxdjE:function(s,t){return s!==t},waHoS:function(s,t,r){return s(t,r)},SorzV:function(s,t,r){return s(t,r)},BxsPT:function(s,t){return s&t},ldQVy:function(s,t){return s===t},jBtbn:function(s){return s()},MJTHp:function(s,t){return s(t)},FXYAW:function(s,t){return s!==t},RNYCM:n(1658),uqHJD:function(s,t,r){return s(t,r)},zqbPD:function(s,t,r){return s(t,r)},uMPah:function(s,t,r){return s(t,r)},yTKyS:function(s,t){return s!==t},fKPgE:function(s,t,r){return s(t,r)},lSuls:function(s,t,r){return s(t,r)},MgbcS:function(s,t,r){return s(t,r)},LYauy:function(s,t){return s!==t},djnEC:function(s,t,r){return s(t,r)},igEmt:n(1643),mHKMs:function(s,t,r){return s(t,r)},BpNEk:function(s,t,r){return s(t,r)},ZbPYf:function(s,t){return s(t)},BULdd:function(s,t){return s(t)},nPOTo:function(s,t){return s(t)},rXKfc:function(s,t){return s===t},Hsfkq:n(1120),PAwlK:function(s,t){return s(t)},zHStT:function(s,t){return s>>>t},FUPjq:function(s,t){return s(t)},DIwzJ:function(s,t,r){return s(t,r)},VSisl:function(s,t,r){return s(t,r)},TpobD:function(s,t){return s&t},NolcX:function(s,t){return s===t},yVkOQ:"Missing "+n(1156)+" field: "+n(465),IIMer:n(1503)+n(1156)+" field: service",MXwAH:function(s,t){return s===t},yTaQt:n(1503)+n(1156)+n(1717)+"method",cmEuT:n(1554),xJVeq:function(s,t){return s+t},GjYYz:function(s,t){return s(t)},yjher:function(s,t,r){return s(t,r)},AAZsN:function(s,t){return s(t)},brmrD:function(s,t,r){return s(t,r)},Racjs:function(s,t){return s>t},GUDlG:function(s,t){return s+t},Hovaj:n(1234)+n(1133),PrCmX:function(s,t){return s>=t},kkvnu:function(s,t){return s+t},qONqR:function(s,t){return s>t},giQIH:"Read pas"+n(1133),ApqWQ:function(s,t,r){return s(t,r)},cZvPA:function(s,t){return s(t)},RDDjY:n(1593)+"ile_name",csqFZ:n(1076),yGfkM:n(1803),vKovs:function(s,t,r,o){return s(t,r,o)},vDMaf:n(889),oMILX:n(1281),npmmj:"cursor.s"+n(1398),xFQZp:function(s,t,r){return s(t,r)},SHJuX:"egfBD",cdqmL:n(790),zAMfA:function(s,t,r){return s(t,r)},yvGit:function(s,t){return s<t},nnWas:n(490),MWIPm:function(s,t){return s===t},PeVja:function(s,t){return s===t},bEZmY:function(s,t){return s&t},arcNP:function(s,t){return s===t},BeCWm:"qdQFb",pjkhh:function(s,t){return s&t},DxBeV:function(s,t){return s&t},KwCPo:function(s,t){return s&t},qwXTw:function(s,t){return s!==t},kTfUj:"ejhGX",cAPsb:function(s,t){return s==t},zdSKc:function(s,t){return s&t},gTZgX:function(s,t){return s>=t},EyHFF:function(s,t){return s+t},iIxdc:function(s,t){return s+t},bunlg:function(s,t){return s<<t},DaaiM:function(s,t){return s===t},wZOCb:n(1095),fsOdx:function(s,t){return s<<t},dBDDa:function(s,t){return s<=t},nqaOR:function(s,t){return s(t)},OsYmN:function(s,t){return s+t},zsJbp:function(s,t){return s|t},Ndnxo:function(s,t){return s<<t},jMtAR:function(s,t){return s<t},yixfV:function(s,t){return s>t},XfyQQ:function(s,t){return s+t},BdslA:function(s,t){return s+t},XpnXB:n(1515),TcIso:function(s,t){return s<t},wblOk:function(s,t){return s<=t},kbfGH:function(s,t){return s<t},pKPMw:function(s,t){return s-t},oGPyO:function(s,t){return s+t},VmlSU:function(s,t){return s<<t},HVgiv:function(s,t){return s<t},IaiDF:function(s,t){return s<t},NTvUK:function(s,t,r){return s(t,r)},clgnb:function(s,t){return s<t},CqotF:function(s,t){return s>=t},HrBJN:function(s,t){return s<=t},caOFF:function(s,t){return s+t},lRDSg:function(s,t){return s<<t},CeJym:function(s,t){return s|t},uoYgS:n(1216),EJdVg:function(s,t){return s&t},VBHRy:function(s,t){return s>>t},QRfPl:function(s,t){return s&t},kmHXp:function(s,t){return s||t},KCitV:"undefined",Fseme:n(1039),XxnKI:n(1752),EFuKu:function(s,t,r){return s(t,r)},RWskw:n(1698),mJmMI:function(s,t){return s<t},ZZwEY:function(s,t,r){return s(t,r)},JyAvY:function(s,t,r){return s(t,r)},wHkNc:function(s,t,r){return s(t,r)},qhQVR:n(758),mpdvs:function(s,t){return s&t},BKAND:function(s,t){return s&t},FuOXC:function(s,t){return s(t)},nBBqG:function(s,t){return s&t},GEPJl:function(s,t){return s(t)},RHdsk:function(s,t){return s<<t},aMyKq:function(s,t){return s&t},OuaAK:function(s,t){return s&t},CxgSH:function(s,t){return s(t)},qGhzx:function(s,t){return s&t},FfFqL:function(s,t){return s&t},QNDdX:function(s,t){return s===t},JBxfN:n(1312),Hslcu:function(s,t){return s(t)},qYVtM:function(s,t){return s&t},IYGtJ:function(s,t){return s(t)},CuUxg:function(s,t){return s&t},kMzKm:function(s,t){return s&t},gGRia:n(1625),RmvFj:n(661),pSJVo:function(s,t){return s&t},etRyW:function(s,t){return s|t},bkvRG:function(s,t){return s>>>t},BswrH:function(s,t){return s|t},MGbaA:function(s,t){return s<<t},tEhxr:function(s,t){return s>>>t},OWLMO:function(s,t){return s===t},qFuDv:function(s,t){return s<t},MRMfi:function(s,t){return s<t},jHpaX:function(s,t){return s<t},Tuinw:function(s,t){return s&t},PCwTo:function(s,t){return s!==t},xKcmH:function(s,t){return s&t},HKvlW:function(s,t){return s+t},QFDik:function(s,t){return s!==t},jOCHs:function(s,t){return s+t},bYgQl:function(s,t){return s!==t},BppdZ:function(s,t){return s&t},xoEcX:function(s,t){return s>>>t},LZsEb:function(s,t){return s&t},IvLGo:function(s,t){return s!==t},aHZoj:function(s,t){return s>>>t},aFcCf:function(s,t){return s+t},chSmY:function(s,t){return s>>>t},XuMNd:function(s,t){return s!==t},PVVUF:function(s,t){return s instanceof t},jAFBc:"done",etBZG:function(s,t){return s===t},wWrVd:n(1672)+n(1389),rzKxv:"store",Klxgw:n(1018),BxktR:function(s,t){return s|t},LFvEB:function(s,t){return s(t)},Qrudr:function(s,t){return s!==t},OTFJa:n(598),mHsDD:function(s,t){return s|t},AAynS:function(s,t){return s<<t},NnKBw:function(s,t){return s|t},RjbmK:function(s,t){return s<<t},IQwSA:function(s,t){return s<<t},sufWk:function(s,t){return s|t},tSCkO:function(s,t){return s<<t},Kmeyv:function(s,t){return s<<t},WnGkk:function(s,t){return s>>>t},xUIbt:function(s,t){return s|t},Pivwd:function(s,t){return s<<t},QUaQF:function(s,t){return s<<t},msgQo:function(s,t){return s<<t},ebQxJ:function(s,t){return s<<t},oyuLE:function(s,t){return s<<t},YFrdQ:function(s,t){return s&t},pQpva:function(s,t){return s&t},ouUMt:function(s,t){return s&t},BmiDq:function(s,t){return s>=t},WZDVN:function(s,t){return s+t},XknSY:function(s,t){return s%t},PyaLv:function(s,t){return s/t},zkmWs:function(s,t){return s+t},zROfp:function(s,t){return s*t},AugUm:function(s,t){return s>>>t},lXwNP:function(s,t){return s+t},kOTQs:function(s,t){return s*t},EKXtq:function(s,t){return s>>>t},GIovO:function(s,t){return s>>>t},sApQA:function(s,t){return s>>>t},PTWrA:function(s,t){return s+t},zNvEo:function(s,t){return s>>>t},KUwYi:function(s,t){return s+t},WAeuw:function(s,t){return s>>>t},wfwFH:function(s,t){return s!==t},tItAB:function(s,t){return s===t},PDsmL:function(s,t){return s===t},XdVjW:function(s,t){return s===t},UOhiA:function(s,t){return s===t},YXjGi:function(s,t){return s+t},FvQGg:function(s,t){return s>>>t},UDosa:function(s,t){return s&t},uimak:function(s,t){return s&t},NXimc:function(s,t){return s&t},jTNlI:function(s,t){return s&t},OmwbQ:function(s,t){return s&t},DIFQg:"2|0|3|5|"+n(1719),lbNJr:n(1007)+"NG_ERROR",kkCpA:n(1404)+"OR",WZodA:n(1524)+n(559),LLJPC:n(1152)+n(659)+"R",oWqaE:n(553)+"ERROR",SbBbQ:n(1056)+n(1343),TiMIY:n(1244),kDYWM:function(s,t){return s(t)},bUvxr:n(536),HSkBz:n(1602),BIciu:function(s,t){return s===t},fJdbl:"StAle",aqcxb:n(1794),qxALn:n(608)+n(1292)+"s",cmxmk:n(1334),rXAHC:function(s,t,r){return s(t,r)},OIYdi:n(651),XbFFb:function(s,t){return s===t},viqAz:function(s,t){return s>t},TyaIu:n(853),fVtCm:function(s,t){return s===t},RdxQI:"error",TSuEX:function(s,t){return s+t},sSQHx:function(s,t){return s+t},usRqC:function(s,t){return s===t},iwgiu:n(1327),NDSwX:n(633),fxMwU:n(1313),orTLF:function(s,t,r){return s(t,r)},tXlAp:n(1284),ZXIFR:function(s,t,r){return s(t,r)},HyYns:function(s,t){return s<<t},oCnsr:function(s,t){return s instanceof t},yNHOv:function(s,t){return s<t},MwGkS:function(s,t){return s-t},DRBNM:function(s,t){return s|t},vLgss:function(s,t){return s>>t},ppgoq:function(s,t){return s!==t},wFqEa:"IXABF",miASG:n(1601),FMTiV:function(s,t){return s!=t},hQqnJ:n(569)+"4",NGMvY:function(s,t){return s!=t},bnFZv:function(s,t){return s===t},LcfLO:n(1288),vFwCK:n(1896)+n(1443)+n(933)+n(1886)+n(1155),MEfGc:function(s,t){return s===t},wSwKO:function(s,t){return s instanceof t},xMikD:n(1187)+n(1338),YtDJN:function(s,t){return s===t},CuBeM:function(s,t){return s+t},KgXTo:function(s,t,r){return s(t,r)},qkDMq:function(s,t){return s-t},beWcg:function(s,t){return s<=t},cPjBx:function(s,t){return s<t},jxDWL:function(s,t){return s|t},kkJQp:function(s,t){return s|t},hxmiK:function(s,t){return s&t},gORDb:function(s,t){return s&t},nOJhQ:function(s,t){return s>=t},GdJgd:"KHrDU",UZwZo:n(1027),VpVln:function(s,t){return s<<t},TpacO:function(s,t){return s&t},NIpzZ:function(s,t){return s+t},Fhorz:function(s,t){return s>>t},RYYnp:function(s,t){return s+t},GhENM:function(s,t){return s&t},QJDhq:function(s,t,r){return s(t,r)},xpuAW:function(s,t){return s<t},YEoqO:"VOqaf",aQuHJ:"QTuhN",EeMCi:function(s,t){return s|t},gUIvS:function(s,t){return s>>t},NXryp:function(s,t){return s&t},fwdYN:n(1394)+"4|1",AtkvZ:function(s,t){return s+t},nUpqs:function(s,t){return s&t},jxriM:function(s,t){return s&t},SekZB:function(s,t){return s===t},qVNOM:n(1824),JaSWj:function(s,t){return s>>t},tqASI:function(s,t){return s|t},XPFPK:function(s,t){return s&t},KVJdT:function(s,t){return s-t},eSOdA:n(1325),OIVMU:n(1029),amzKF:function(s,t,r){return s(t,r)},mWWxe:function(s,t){return s!==t},sysmP:n(885),qBQiH:n(1116)+n(720),eLxRw:function(s,t){return s==t},tnRuU:n(1322)+n(477)+"et=utf-8",TRZZz:n(1006),RMXqZ:n(1038),dmZeV:function(s,t){return s===t},gRtaz:"CexUX",pzFwG:n(506),bweDN:function(s,t){return s>=t},ZlcwU:function(s,t){return s===t},VofAz:n(1587),kHpTB:n(1821)+"ascript",eLKoT:"http",dleqQ:n(1221)+"ack=frontierJSONP",EKrXO:n(1740),OpBxn:function(s,t){return s===t},TOEbt:n(990),xKchl:n(715),DMTNf:n(1040),nVXtw:n(1112),EBmKg:function(s,t){return s(t)},kndrZ:n(504),DroYa:n(851),ropdY:function(s,t){return s!==t},fWSiN:n(1240),upmIr:function(s,t){return s(t)},NHoZH:"pIvbq",bKioJ:function(s,t){return s||t},kVUpB:function(s,t){return s||t},CEkls:function(s,t){return s||t},qfTGJ:n(512),mjQCY:n(1638),NmBUJ:function(s,t){return s||t},RbPzf:n(608)+n(1451)+"t",WAJdB:n(774),sDwAE:n(656),NLGmR:"YwRXV",mxbfC:function(s,t){return s||t},uBgda:function(s,t){return s(t)},JKLjU:function(s){return s()},OZjUt:function(s,t){return s===t},ehmqz:n(772),EsLAv:function(s,t){return s||t},KIwnK:function(s,t){return s||t},aPNtu:function(s,t){return s||t},kncpq:n(880)+n(874)+"d",GlnQb:function(s,t){return s>t},Rgqjv:"xdjah",lzBnJ:function(s,t,r){return s(t,r)},XCUTE:n(1626),rLIeD:function(s,t){return s+t},vUreZ:n(1857)+n(1608),iIlNo:function(s,t){return s===t},ephDC:"biFrH",SmsaJ:n(1110),IvWlU:function(s,t){return s(t)},PSExE:function(s,t,r,o){return s(t,r,o)},cjXzC:n(709)+n(1409)+"ck",uoPtI:function(s,t,r,o){return s(t,r,o)},yncLd:n(709)+n(1728)+"k",zBoOE:n(709)+n(689)+n(1703),lOfVh:function(s,t){return s===t},ZRBzZ:n(640),hWTXt:n(1865),Ajtik:function(s,t){return s&&t},fcLAB:n(1035),zkzjw:"ack_id",NlbIw:n(1146),SHyiF:function(s){return s()},xfHzI:n(1491),jjneJ:function(s,t){return s(t)},dUvSf:function(s,t){return s(t)},qxOhf:function(s,t){return s instanceof t},AQhcJ:n(1116)+"ion/json"+n(1846)+"=utf-8",ETibq:n(1126),UgAJQ:function(s){return s()},fMuby:function(s,t){return s<t},eEvDR:function(s,t){return s(t)},aSfIf:function(s,t){return s&t},TNVQo:n(834),coZvO:"AzAme",KPlXB:function(s,t){return s>>>t},EnFDF:function(s,t){return s(t)},uWxZY:function(s,t){return s+t},nWRDL:" + ",cpPDU:n(544),ZHlif:function(s,t){return s&t},RTsgs:function(s,t,r,o){return s(t,r,o)},fmqiZ:function(s,t){return s<t},qZpeb:n(1104),ENLwk:function(s,t){return s<<t},kaleo:n(1771),bDYcP:n(1539)+"1",NwLaj:function(s,t){return s+t},lJfoA:function(s,t){return s|t},SkhLh:function(s,t){return s<<t},pYtbA:function(s,t){return s<<t},bbecr:function(s,t){return s+t},KNPpt:function(s,t){return s|t},ENICH:function(s,t){return s<<t},lcKTs:function(s,t){return s<<t},LzKUb:function(s,t){return s+t},UKumk:function(s,t){return s<<t},oCOqC:function(s,t){return s+t},InvJx:function(s,t){return s+t},jiHxa:function(s,t){return s+t},AzgDi:function(s,t){return s&t},meLOm:function(s,t){return s+t},Gotac:function(s,t,r,o){return s(t,r,o)},PEKAG:n(709)+n(1413),wWDSP:function(s,t,r,o){return s(t,r,o)},KFrbg:function(s,t,r){return s(t,r)},ITIbM:function(s,t){return s!==t},Aityz:"IFypL",WlKbQ:function(s,t){return s+t},oBTUV:function(s,t){return s+t},DmIyC:n(1346),dAzJW:n(854),jFhlc:function(s,t){return s>>>t},iZdTG:function(s,t){return s<<t},pOanl:function(s,t){return s<t},bKEcy:n(1186),inazL:n(1780),zguhB:function(s,t){return s<t},BosoF:n(1876),TicPr:function(s,t){return s+t},EXsFf:function(s,t,r,o){return s(t,r,o)},UgNOn:function(s,t,r,o){return s(t,r,o)},CwvYm:function(s,t){return s===t},KJqoK:"UBBgv",wnDHd:n(1395),gYDtv:function(s,t){return s<t},FWjFL:function(s,t,r){return s(t,r)},fLRaJ:n(1387),voxjd:"FILE_NOT_EXIST",JykiM:"cursor_n"+n(1195),oqnQf:n(833),hIwqM:n(1136),uObmx:n(805),AnnWw:function(s,t,r,o){return s(t,r,o)},EDdkd:"setdb",EaIzQ:function(s,t){return s!==t},oNYcB:"RXHZj",CfNOL:n(1513),DJPsY:function(s,t){return s(t)},gXJuH:"x_fronti"+n(531),LOCNV:"x-msg-qos",cQYHX:function(s,t,r){return s(t,r)},xxdVw:n(507)+n(1736)+"e",pcFmA:n(507)+n(905)+"ue",sloGz:function(s,t){return s>t},mOkpP:function(s,t){return s>t},JvLrE:function(s,t){return s+t},KwVbg:function(s){return s()},FEZcH:function(s,t){return s<t},ShRUR:function(s){return s()},zolZk:function(s){return s()},BYNpR:function(s,t){return s|t},rHqGD:function(s,t){return s&t},hitsc:function(s,t){return s===t},vhhLD:function(s,t){return s&&t},ryVmk:function(s){return s()},RiLLM:n(844),OhJAU:function(s,t){return s(t)},kkDVU:function(s){return s()},zubVW:function(s,t){return s!==t},cLqPr:n(570),PjxJu:function(s,t,r){return s(t,r)},sKUDo:function(s){return s()},Lboxn:function(s,t,r){return s(t,r)},dVHVh:function(s,t){return s+t},RyuuM:function(s,t){return s===t},bTcAl:n(1473),UNlFl:n(729),EIRkK:function(s,t){return s===t},iVMqK:"GSRHr",TrXme:n(1252),AAqCu:function(s,t,r){return s(t,r)},ZKfKN:function(s,t,r){return s(t,r)},CqZOI:function(s,t){return s-t},VvGqf:n(1066),wWctg:function(s,t,r){return s(t,r)},hiMjf:n(1506)+"fer",YJOiS:n(1214),ydTcp:function(s,t){return s/t},UCXuc:n(747)+n(718)+"alid url",MIcsG:function(s,t){return s(t)},wqbfs:n(747)+n(914)+n(1578)+n(579)+"ket cons"+n(723)+"is undef"+n(1511),GKqfk:n(1022),awPRe:n(922)+"t",znMqe:"stop imm"+n(1177)+n(1860)+"ct",LAeop:function(s,t){return s&t},MedzT:n(1836),KkIAl:"ObIpA",QlYSs:n(903),lEkTE:n(1482),AnmXX:n(1400),iDTEV:n(744),TWhcm:function(s,t){return s===t},zJshw:n(1077),HiWdp:n(1691),DXEda:n(776),PaUQZ:function(s,t){return s==t},eMLLA:n(773),ntKgd:n(1527),OKFLB:"ws://",UJfax:n(1025),GNZgq:n(599),wYChs:n(1828)+"d",RRDeS:n(1577),HUWUG:function(s){return s()},hKNqV:function(s,t,r){return s(t,r)},xYyvT:"fws_1.0.0",zXARR:function(s,t){return s||t},KKObW:n(1309),qaZSZ:function(s,t){return s>t},bJMfn:n(636),fkHpQ:n(1051),ocylP:function(s,t){return s(t)},OVqOz:function(s,t){return s(t)},ZYBCl:n(1178)+">",jGcJQ:function(s,t){return s*t},OYtvp:function(s,t){return s(t)},vlxGw:function(s,t){return s===t},wfDlN:"tWavJ",UTyTL:function(s,t){return s===t},pXeTl:function(s,t){return s!==t},vMxLY:function(s,t,r){return s(t,r)},PTpdv:n(1199),NgIoO:n(1033),ifXex:"going aw"+n(1808)+n(922)+"ting ser"+n(728),knfxs:n(1705),uNsNk:function(s,t){return s===t},eTube:n(1795),DRsyL:n(1157),JNIaV:n(1573)+"1",iCFpY:"0|4|5|2|1|3",YlhaV:function(s,t){return s&t},zhtZT:function(s,t){return s>>t},GyRwQ:function(s,t){return s|t},zdRWP:n(839),pNXZm:function(s,t,r){return s(t,r)},dLhsu:function(s,t,r){return s(t,r)},kupEo:function(s,t,r){return s(t,r)},uFxqH:n(1323),bcqSZ:n(1892)+"ay, netw"+n(714)+"ine",Fhthb:n(1716),IHKaC:n(892),cocqD:"XIBBK",VOWFH:function(s,t){return s+t},FXpEi:n(1831),sxWGh:"VWcUF",JtRKY:"6|2|3|4|"+n(759),vUzel:n(1545)+n(503)+n(974),dlmxe:function(s,t){return s!==t},JRSIX:n(831),DxWsC:n(1791),QBrTP:n(747)+n(979)+n(1714)+"ata, data must be a string or an arraybu"+n(1848),WoTap:"number",mjemf:function(s,t){return s instanceof t},DIGzx:function(s,t){return s(t)},pJRhg:n(747)+n(979)+n(1659)+"ervice",LoAhN:function(s,t){return s(t)},pTbfP:function(s,t){return s===t},ApYGE:n(945),ZOunb:function(s,t){return s<t},oNyXo:n(846),dLEGu:function(s,t){return s==t},eOUki:n(685)+"econnect"+n(1761),SLZFa:n(679)+"1",qQGYM:n(594),bbPdZ:n(976),gOTzv:"XEQLn",RLddv:n(1683),PXprN:"\0\0\0\0\0\0\0\0",vBeRn:function(s,t){return s/t},zPptI:function(s,t){return s!=t},aaeDn:function(s,t){return s===t},IzwIn:n(474),NFkWN:function(s,t){return s!=t},gejBe:function(s,t){return s===t},tlJnw:n(1304),BhPct:function(s,t){return s===t},YDGog:n(1332)+n(1693)+n(593)+"pe",HVUIO:function(s,t){return s!=t},Cbkkj:function(s,t){return s===t},mwyKT:function(s,t){return s==t},knMQQ:function(s,t){return s!=t},cnZIf:function(s,t){return s===t},tDthb:n(986)+n(1492)+n(493),mfhDw:function(s,t){return s===t},OxXeV:"ServiceW"+n(1300)+"balScope",wdahe:function(s,t){return s!=t},frbIx:function(s,t){return s!=t},iZXCH:"__x_msg_"+n(1103)};Ee.r($),Ee.d($,{FWS:()=>f0,CustomErrorEvent:()=>ws,createCloseEvent:()=>ge,ReconnectEvent:()=>ms,createErrorEvent:()=>de,decodedFrame:()=>fs,createOpenEvent:()=>Es,CustomCloseEvent:()=>_s,createReconnectEvent:()=>cr,FrontierMessageEvent:()=>bs,encodeFrame:()=>ar,createMessageEvent:()=>Ss,OpenEvent:()=>vs,ErrorCode:()=>qe,Event:()=>st,MessageEvent:()=>ys});let i="";function a(s=""){let t=n,r="02",o=""+Date.now(),x=i||(i=e[t(472)](p,s)),l=Math.random()[t(1294)](16)[t(1526)](-6);return e.GQvlA(e[t(819)](r,o)+x,l)}function c(){let s=n,t={kBUKC:function(r,o){return e.bodwE(r,o)}};return e[s(1874)](e[s(607)],s(1696))?t[s(1069)](this[s(733)],this[s(825)+s(1047)]):e[s(1841)](1e4,Date[s(538)]())+Math[s(1139)](e[s(1295)](1e4,Math.random()))}function u(s){let t=n,r={xAmoL:function(o,x){return o|x},SdcSx:function(o,x){return e[T(1255)](o,x)},tRSwq:function(o,x){return e[T(1386)](o,x)},nEUIz:function(o,x){return e[T(1660)](o,x)},DmdLB:function(o,x){return e[T(1408)](o,x)},QSQau:function(o,x){return e.kUSmu(o,x)},prChH:function(o,x){return e[T(1408)](o,x)},dyYLD:function(o,x){return e[T(1353)](o,x)},Sauch:function(o,x){return o>>x},ejfvM:function(o,x){return o|x}};if(e[t(1874)](e.TppTs,e[t(1319)]))return(e.iMBVp(Array,8)[t(760)]("0")+e[t(700)](parseInt,s,10)[t(1294)](2))[t(1526)](-8);_0x2cd119<2048?_0x3efede[_0x4207f1++]=r.xAmoL(r.SdcSx(r[t(1424)](_0x43b5e8,6),31),192):(r[t(959)](_0x207309,65536)?_0x409fbf[_0x4e6427++]=r.DmdLB(r[t(1424)](_0x2ec817,12)&15,224):(_0x19dce4[_0x1e90c3++]=r.QSQau(r[t(1424)](_0x508e88,18),7)|240,_0x3d9613[_0xb987fa++]=r.prChH(r.dyYLD(_0x512f3f>>12,63),128)),_0x742540[_0x58235e++]=r[t(492)](r[t(1196)](r.Sauch(_0x46bbe8,6),63),128)),_0x353306[_0x241fdc++]=r.ejfvM(r[t(1196)](63,_0xc5df75),128)}function d(s){let t=n;return e[t(1910)](e[t(1807)](Array,4)[t(760)]("0"),e[t(700)](parseInt,s,2)[t(1294)](16)).slice(-4)}function h(s){let t=n,r=s.split(/\./)[t(456)](l=>u(l)),o=[];return o[0]=e.hzXqL(d,e[t(1910)](r[0],r[1])),o[1]=e.bBSgH(d,e[t(819)](r[2],r[3])),[e[t(1629)],e[t(1629)],e.kANjV,e[t(1629)],e[t(1629)],t(1468),o[0],o[1]][t(760)]("")}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(660)](s),o=/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/.test(s);return r?e.PIoYh(h,s):o?e[t(609)](w,s):"0000000000000000"+t(1044)+t(1044)}function w(s){let t=n,r="",o=[],x=0,l=0,g=!0,m=e[t(1629)];if(s[t(1129)]("::")>-1){let f=s[t(721)]("::");for(let b=0;e[t(1660)](b,f[t(1326)]);b++)if(e.ldEst(t(518),t(1203))){let k=f[b];if(k[t(1129)](":")>0){let A=k[t(721)](":");g&&(x=A[t(1326)]),l+=A[t(1326)];for(let D=0;D<A[t(1326)];D++)if(e.zEVkN(4,A[D][t(1326)])){let O=m[t(1796)+"g"](0,e[t(1571)](4,A[D].length)),B=O.concat(A[D]);o[t(1414)](B)}else o.push(A[D]);g=!1}else{if(e[t(1209)](4,k[t(1326)])){let A=m[t(1796)+"g"](0,e[t(1571)](4,k[t(1326)])),D=A[t(634)](k);o.push(D)}else o.push(k);g&&(x+=1),l+=1,g=!1}}else this[t(1335)]=!0,this.low=0|_0x1dcfc0,this[t(1760)]=0|_0x4638ae,this[t(1499)]=!!_0x3c3634;let v="";for(let b=0;b<e[t(1571)](8,l);b++)v=v[t(634)](m);for(let b=0;e[t(489)](b,o[t(1326)]);b++)b===x&&(r=r[t(634)](v)),r=r[t(634)](o[b]);return r}{let f=s[t(721)](":");for(let v=0;e[t(1123)](v,f[t(1326)]);v++){let b=f[v];if(e[t(1209)](4,f[v].length)){let k=m[t(1796)+"g"](0,e.GkzSz(4,f[v][t(1326)])),A=k[t(634)](b);r=r[t(634)](A)}else r=r[t(634)](b)}return r}}function y(s,t){let r=n,o=s[r(769)];e[r(1226)](void 0,o)&&(V(t,10),e[r(1688)](ye,t,o));let x=s[r(478)];e[r(1226)](void 0,x)&&(V(t,18),ye(t,x))}function _(s){let t=n,r={};e:for(;!e[t(609)](ke,s);){let o=F(s);switch(o>>>3){case 0:break e;case 1:r[t(769)]=e[t(1688)](_e,s,F(s));break;case 2:r[t(478)]=e[t(1688)](_e,s,e[t(1807)](F,s));break;default:e[t(1915)](se,s,e[t(908)](7,o))}}if(e[t(1785)](void 0,r[t(769)]))throw new Error(t(1503)+t(1156)+t(1717)+t(769));if(r[t(478)]===void 0)throw new Error(t(1503)+t(1156)+t(1717)+"value");return r}function C(s){let t=n,r=e[t(780)](ae);return e[t(700)](I,s,r),e[t(1637)](J,r)}function I(s,t){let r=n,o=s.SeqID;e[r(1246)](void 0,o)&&(e[r(1853)]!==r(1658)?this[r(1031)+r(652)]=null:(V(t,8),Ct(t,o)));let x=s[r(637)];e[r(1209)](void 0,x)&&(V(t,16),e[r(1688)](Ct,t,x));let l=s[r(889)];l!==void 0&&(V(t,24),e[r(1023)](Ct,t,e[r(1637)](ee,l)));let g=s.method;e[r(1226)](void 0,g)&&(e[r(1189)](V,t,32),Ct(t,e[r(472)](ee,g)));let m=s[r(1119)];if(e[r(1246)](void 0,m))for(let B of m){e.waHoS(V,t,42);let be=ae();e[r(648)](y,B,be),e[r(1189)](V,t,be[r(961)]),Vt(t,be),e[r(1793)](P,be)}let f=s["payloadE"+r(829)];e.yTKyS(void 0,f)&&(e[r(1688)](V,t,50),e.fKPgE(ye,t,f));let v=s["payloadT"+r(1805)];e[r(957)](void 0,v)&&(e.lSuls(V,t,58),e[r(1843)](ye,t,v));let b=s.payload;e[r(1893)](void 0,b)&&(e[r(648)](V,t,66),e[r(648)](V,t,b[r(1326)]),e[r(784)](Jt,t,b));let k=s.LogIDNew;if(e[r(957)](void 0,k)){if(e[r(1100)]!==e[r(1100)])return r(1686)+"_"+this[r(782)];e[r(1887)](V,t,74),e.fKPgE(ye,t,k)}let A=s["serverTi"+r(1032)];A!==void 0&&(e.BpNEk(V,t,82),e.djnEC(ye,t,A));let D=s[r(561)];D!==void 0&&(e[r(1688)](V,t,90),e[r(700)](ye,t,D));let O=s[r(1676)+"e"];e[r(1226)](void 0,O)&&(V(t,96),Ct(t,e[r(1490)](ee,O)))}function L(s){return e[n(1490)](R,e.BULdd(H,s))}function R(s){let t=n,r={};e:for(;!e[t(1046)](ke,s);)if(e.rXKfc(e[t(1201)],e.Hsfkq)){let o=e.PAwlK(F,s);switch(e.zHStT(o,3)){case 0:break e;case 1:r[t(465)]=Pe(s,!0);break;case 2:r[t(637)]=Pe(s,!0);break;case 3:r[t(889)]=e.nPOTo(F,s);break;case 4:r[t(1301)]=e[t(1046)](F,s);break;case 5:{let x=e.hzXqL(q,s);(r[t(1119)]||(r[t(1119)]=[]))[t(1414)](e[t(1046)](_,s)),s[t(961)]=x;break}case 6:r[t(1420)+t(829)]=e.uMPah(_e,s,e[t(1652)](F,s));break;case 7:r[t(1198)+t(1805)]=_e(s,e[t(1793)](F,s));break;case 8:r.payload=e.lSuls(Et,s,F(s));break;case 9:r[t(1237)]=_e(s,e.FUPjq(F,s));break;case 10:r["serverTi"+t(1032)]=e[t(1269)](_e,s,e[t(1652)](F,s));break;case 11:r[t(561)]=e[t(978)](_e,s,F(s));break;case 12:r[t(1676)+"e"]=e[t(1793)](F,s);break;default:e[t(467)](se,s,e[t(1817)](7,o))}}else this[t(678)](_0x305671,_0x255fe6);if(e[t(1914)](void 0,r[t(465)]))throw new Error(e[t(1073)]);if(r[t(637)]===void 0)throw new Error(t(1503)+t(1156)+t(1717)+"LogID");if(e[t(1785)](void 0,r[t(889)]))throw new Error(e[t(1628)]);if(e[t(1560)](void 0,r[t(1301)]))throw new Error(e[t(1713)]);return r}function q(s){let t=n,r={hxaaN:function(o,x,l){return o(x,l)},Srppm:function(o,x,l){return e[T(1915)](o,x,l)}};if(e.zEVkN(e[t(1229)],e[t(1229)]))zwMatD.hxaaN(_0x4a0fc8,_0x5c8f3a,10),zwMatD[t(1376)](_0xbebc19,_0x95f50,_0x4d4174);else{let o=F(s),x=s.limit;return s[t(961)]=e[t(1585)](s[t(1488)],o),x}}function se(s,t){let r=n;switch(t){case 0:for(;128&e[r(1783)](ie,s););break;case 2:e[r(739)](te,s,e.AAZsN(F,s));break;case 5:e[r(632)](te,s,4);break;case 1:te(s,8);break;default:throw new Error(r(1342)+"ented ty"+r(1193)+t)}}function ee(s){let t=n;return s|=0,{low:s,high:s>>31,unsigned:e[t(1704)](s,0)}}let we=[];function ae(){let s=n,t=we[s(1632)]();return t?(t[s(1488)]=t[s(961)]=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function P(s){we[n(1414)](s)}function H(s){return{bytes:s,offset:0,limit:s[n(1326)]}}function J(s){let t=n,r=s.bytes,o=s.limit;return r[t(1326)]===o?r:r[t(1373)](0,o)}function te(s,t){let r=n;if(e[r(466)](e[r(509)](s.offset,t),s[r(961)]))throw new Error(e[r(746)]);s.offset+=t}function ke(s){let t=n;return e[t(1838)](s[t(1488)],s.limit)}function he(s,t){let r=n,o=s.bytes,x=s[r(1488)],l=s[r(961)],g=e[r(613)](x,t);if(e[r(466)](g,o[r(1326)])){let m=new Uint8Array(e.vSlcr(2,g));m[r(1416)](o),s[r(1405)]=m}return s[r(1488)]=g,e.qONqR(g,l)&&(s.limit=g),x}function Ve(s,t){let r=n,o=s[r(1488)];if(e[r(1036)](e[r(1585)](o,t),s.limit))throw new Error(e.giQIH);return s[r(1488)]+=t,o}function Et(s,t){let r=n,o=e.ApqWQ(Ve,s,t);return s[r(1405)].subarray(o,e[r(819)](o,t))}function Jt(s,t){let r=n,o=e[r(978)](he,s,t.length);s[r(1405)][r(1416)](t,o)}function _e(s,t){let r=n,o={gPthw:"8|4|1|7|"+r(1200)+r(1775),thMdx:e[r(1542)],bLnDr:r(1347),DrUOO:function(x,l,g,m){return e[r(1194)](x,l,g,m)},VdeKW:e.vDMaf,OukpN:e[r(1763)],xsjty:function(x,l,g,m){return e[r(1194)](x,l,g,m)},QmtAn:e.npmmj,yLaQR:function(x,l,g,m){return e.vKovs(x,l,g,m)},PawSn:function(x,l,g,m){return e.vKovs(x,l,g,m)},dmKWy:function(x,l,g){return e[r(1618)](x,l,g)}};if(e[r(1246)](e.SHJuX,e.cdqmL)){let x=e.zAMfA(Ve,s,t),l=String[r(617)+r(1383)],g=s.bytes,m="\uFFFD",f="";for(let v=0;e[r(615)](v,t);v++)if(e[r(1560)](r(988),e[r(948)])){let[b,k]=_0x729d6b(_0x3b9e52),A=e[r(1074)](_0x8ea406,b),D=0;return _0x838dea[r(1845)](O=>{let B=r,be=o[B(1265)][B(721)]("|"),$t=0;for(;;){switch(be[$t++]){case"0":_0x5f4209.log(B(1647)+B(1281),D);continue;case"1":_0x3752da[B(1746)](o.thMdx,D);continue;case"2":_0x1caea4[B(1746)](o[B(911)],D);continue;case"3":D=o[B(1654)](_0x3ad2b1,_0x40ea97[B(931)+"er"](O[B(1113)]||_0x56a24d),A,D);continue;case"4":D=_0x5cc91f(0,A,D);continue;case"5":_0x53bcda[B(1746)](o[B(1862)],D);continue;case"6":_0x34f739[B(1746)](o[B(1101)],D);continue;case"7":D=o[B(525)](_0x444b4e,A,D,O[B(889)]||0);continue;case"8":_0x2b1022[B(1746)](o.QmtAn,O,O.service);continue;case"9":D=o[B(982)](_0x25c90c,O.cursor_name,A,D);continue;case"10":D=o[B(1809)](_0x2b5365,k[O["cursor_n"+B(1195)]],A,D);continue}break}}),{frameType:_0x132efc,headers:[{key:e.RDDjY,value:_0x5c0a94}],payload:A}}else{let b=g[e[r(1585)](v,x)],k,A,D,O;if(e.MWIPm(128&b,0))f+=e[r(1637)](l,b);else if(e[r(1314)](e[r(1749)](224,b),192))if(v+1>=t)f+=m;else if(e[r(1064)](e[r(821)],"IZHUI")){let B=this[r(1668)+r(1802)]?.[r(1087)+r(1004)+"nt"]();this[r(1264)+"hCloseEv"+r(1756)](e[r(1688)](_0x610e95,e.csqFZ,{code:1006,reason:"connect "+B+(r(1502)+r(1385)+"tries re"+r(1463)),wasClean:!0}))}else if(k=g[v+x+1],e[r(1131)](192,k)!==128)f+=m;else if(O=e.uXenI(e[r(1308)](31,b)<<6,e.KwCPo(63,k)),O<128)f+=m;else if(e[r(1681)](r(1339),e[r(1143)])){if(e.PrCmX(_0xa26ba8,_0x42344b))return _0x5952f5}else f+=l(O),v++;else if(e[r(1755)](e[r(793)](240,b),224))if(e[r(1631)](v+2,t))f+=m;else if(k=g[e[r(1172)](v,x)+1],A=g[e.GUDlG(e.iIxdc(v,x),2)],e[r(1079)](e[r(908)](k|e[r(1516)](A,8),49344),32896))f+=m;else if(e[r(954)](e[r(960)],e.wZOCb))O=e[r(1408)](e.fsOdx(e.zdSKc(15,b),12)|e[r(1516)](e[r(1255)](63,k),6),e.dYvhk(63,A)),e.DhxAv(O,2048)||e[r(1838)](O,55296)&&e.dBDDa(O,57343)?f+=m:(f+=e.nqaOR(l,O),v+=2);else return{bytes:_0x56d6fe,offset:0,limit:_0x54af12.length};else e[r(1755)](248&b,240)?v+3>=t?f+=m:(k=g[e[r(837)](v,x)+1],A=g[e[r(509)](v,x)+2],D=g[e[r(837)](v+x,3)],e.DxBeV(e[r(674)](k,e[r(1516)](A,8))|D<<16,12632256)!==8421504?f+=m:(O=e[r(1516)](7&b,18)|e[r(1448)](e[r(1255)](63,k),12)|e.Ndnxo(e.zdSKc(63,A),6)|63&D,e[r(956)](O,65536)||e[r(1873)](O,1114111)?f+=m:(O-=65536,f+=e[r(1778)](l,e[r(671)](e[r(1386)](O,10),55296),e[r(499)](e[r(908)](1023,O),56320)),v+=3))):f+=m}return f}else return _0x283331[r(1405)][o[r(816)](_0x6339dd,_0x5c4c10,1)]}function ye(s,t){let r=n,o=t[r(1326)],x=0;for(let m=0;e[r(1114)](m,o);m++){let f=t[r(872)+"At"](m);e[r(1704)](f,55296)&&e[r(1866)](f,56319)&&e[r(1606)](e.iIxdc(m,1),o)&&(f=e[r(522)](e[r(832)](e.VmlSU(f,10),t[r(872)+"At"](++m)),56613888)),x+=e[r(642)](f,128)?1:e[r(515)](f,2048)?2:f<65536?3:4}V(s,x);let l=e[r(1009)](he,s,x),g=s[r(1405)];for(let m=0;e[r(526)](m,o);m++){let f=t[r(872)+"At"](m);e.CqotF(f,55296)&&e.HrBJN(f,56319)&&e[r(1633)](m,1)<o&&(f=e[r(1571)](e[r(1753)](f,10)+t[r(872)+"At"](++m),56613888)),e.TcIso(f,128)?g[l++]=f:(f<2048?g[l++]=e[r(1635)](e[r(1386)](f,6)&31,192):e[r(496)]!==e[r(496)]?(this[r(1504)](e[r(1231)],_0xcd7cbc),this[r(1655)]&&this[r(1655)](_0x3e52a8)):(e[r(489)](f,65536)?g[l++]=e[r(712)](f>>12,15)|224:(g[l++]=e[r(674)](e[r(893)](e[r(1621)](f,18),7),240),g[l++]=e[r(1131)](e[r(1621)](f,12),63)|128),g[l++]=e[r(1353)](e[r(1386)](f,6),63)|128),g[l++]=e.QRfPl(63,f)|128)}}function Vt(s,t){let r=n,o={ybvyO:function(x,l){return e.kmHXp(x,l)},Wkwkh:function(x,l){return e[T(672)](x,l)},kGCTr:function(x,l){return x!=l},CKimA:e[r(883)]};if(e[r(757)]===e.XxnKI){if(_0x2d8ee5)return new _0xef8ce7(_0x1404ca.url,_0x1fb80c[r(1701)]);if(o[r(918)](_0x47307f,_0x2c91cc))return new _0x10e6db(_0x397e77.url,_0x46c6a7[r(1701)],_0x31cf02[r(1119)]);if(o.Wkwkh(_0x3e5d3c,_0x3fc648)&&o[r(653)](o[r(1623)],typeof _0x3c7863)&&_0x4cd968)return new _0x10eb64(_0x5bc0b5[r(752)],_0x157d6f[r(1701)+"s"])}else{let x=e[r(1268)](he,s,t[r(961)]),l=s[r(1405)],g=t[r(1405)];for(let m=0,f=t.limit;e[r(1660)](m,f);m++)l[e[r(819)](m,x)]=g[m]}}function ie(s){return s[n(1405)][Ve(s,1)]}function Xt(s,t){let r=n,o=he(s,1);s[r(1405)][o]=t}function F(s){let t=n,r={zcfnZ:function(o,x,l){return e.SorzV(o,x,l)}};if(e[t(901)]!==e.RWskw)mBBfyc[t(1220)](_0x459498,_0x1df078,50),mBBfyc[t(1220)](_0x1ab15b,_0x44c2ce,_0x5a30e3);else{let o=0,x=0,l;do l=e[t(1074)](ie,s),e[t(1228)](o,32)&&(x|=e[t(908)](127,l)<<o),o+=7;while(e.zdSKc(128,l));return x}}function V(s,t){let r=n;for(t>>>=0;e[r(1631)](t,128);)e[r(739)](Xt,s,e[r(1353)](127,t)|128),t>>>=7;e[r(1223)](Xt,s,t)}function Pe(s,t){let r=n;if(e[r(838)]!==r(863)){let o=0,x=0,l=0,g;if(g=e[r(472)](ie,s),o=e[r(1478)](127,g),e[r(781)](128,g)&&(g=e.FuOXC(ie,s),o|=e[r(768)](127,g)<<7,e[r(1131)](128,g)&&(g=e.GEPJl(ie,s),o|=e[r(629)](e[r(929)](127,g),14),128&g&&(g=e.nqaOR(ie,s),o|=e[r(629)](127&g,21),e[r(543)](128,g)&&(g=e[r(826)](ie,s),x=127&g,e[r(1403)](128,g)&&(g=e[r(1291)](ie,s),x|=e.pjkhh(127,g)<<7,e[r(1879)](128,g)&&(g=ie(s),x|=e.VmlSU(127&g,14),e[r(1610)](128,g))))))))if(e.QNDdX(e.JBxfN,e[r(809)])){if(g=e.Hslcu(ie,s),x|=e.fsOdx(e.qYVtM(127,g),21),e.pjkhh(128,g)&&(g=e[r(1883)](ie,s),l=e[r(1715)](127,g),e[r(524)](128,g)))if(e[r(1681)](e[r(1674)],e[r(1432)]))g=ie(s),l|=e.Ndnxo(e[r(897)](127,g),7);else return this._socket.extensions}else e[r(1009)](_0x1e06cc,_0x117964,74),e[r(1402)](_0x5359da,_0x8297d6,_0x460f85);return{low:e[r(540)](o,e[r(1448)](x,28)),high:x>>>4|e.lRDSg(l,24),unsigned:t}}else e[r(1559)](_0x1284dc,_0x2c0100,16),_0x53094f(_0x187526,_0x1f7616)}function Ct(s,t){let r=n,o=e[r(612)](t[r(1080)],0),x=e[r(1285)](e[r(571)](e[r(1285)](t[r(1080)],28),e.MGbaA(t[r(1760)],4)),0),l=e[r(592)](t.high,24),g=e[r(1914)](0,l)?e[r(568)](0,x)?e[r(628)](o,16384)?o<128?1:2:e[r(1611)](o,2097152)?3:4:e[r(841)](x,16384)?e.mJmMI(x,128)?5:6:e[r(1123)](x,2097152)?7:8:e.mJmMI(l,128)?9:10,m=e.lSuls(he,s,g),f=s[r(1405)];switch(g){case 10:f[m+9]=e[r(1581)](l>>>7,1);case 9:f[e[r(1172)](m,8)]=e[r(587)](9,g)?e[r(1408)](128,l):e[r(1840)](127,l);case 8:f[e.HKvlW(m,7)]=e[r(915)](8,g)?x>>>21|128:e.mpdvs(e[r(612)](x,21),127);case 7:f[e.jOCHs(m,6)]=e[r(1280)](7,g)?e[r(612)](x,14)|128:e[r(520)](x>>>14,127);case 6:f[e[r(837)](m,5)]=e.QFDik(6,g)?e[r(571)](e[r(697)](x,7),128):e.LZsEb(x>>>7,127);case 5:f[e[r(819)](m,4)]=g!==5?128|x:127&x;case 4:f[m+3]=e[r(1379)](4,g)?e[r(1635)](e[r(592)](o,21),128):e.dYvhk(e[r(1529)](o,21),127);case 3:f[e[r(680)](m,2)]=e[r(957)](3,g)?e[r(1635)](e.aHZoj(o,14),128):e.LZsEb(o>>>14,127);case 2:f[e[r(1585)](m,1)]=g!==2?e[r(1408)](e.chSmY(o,7),128):e[r(768)](e[r(1286)](o,7),127);case 1:f[m]=e[r(1042)](1,g)?e.zsJbp(128,o):e[r(712)](127,o)}}function fs(s){return L(s)}function ar(s){return C(s)}let ls=65536,Sa=e.PXprN,rt=e.jGcJQ(ls,ls),hs=rt*rt,gs=e[n(1142)](hs,2),ze=String[n(1813)+"e"].charCodeAt;class U{constructor(t,r,o){let x=n;if(e[x(1212)]!=="XKEWt"){if(gsOVnc[x(1090)](_0x1bb8d8,_0x138334)){if(_0x598801===gsOVnc[x(1055)])return _0x4d097e[x(1208)](_0x516218);if(gsOVnc.etBZG(_0xbfe954,gsOVnc.wWrVd))return _0x4f1885[x(1672)+x(1389)]||_0x51eef1[x(1208)](_0x3f759e);if(gsOVnc[x(1213)](_0x45ff6d,gsOVnc[x(1768)]))return _0x234774["objectSt"+x(1389)][1]?void 0:_0x4beb29[x(1672)+x(576)](_0x4f0b05[x(1672)+"oreNames"][0])}return gsOVnc[x(609)](_0x5215ce,_0x50664e[_0x5a96ec])}else this[x(1335)]=!0,this[x(1080)]=e[x(1644)](0,t),this[x(1760)]=e[x(571)](0,r),this.unsigned=!!o}static isLong(t){let r=n;if(e[r(1697)](e[r(973)],e.OTFJa))_0x139906[_0x38da02[_0x134a44][r(469)+r(1195)]]=e[r(1108)](_0x1db04c,_0x4c8f96[_0x3e0460][r(469)+r(1195)]),_0x5d6207+=e[r(1910)](14,_0x95790c[_0x4683e7[_0x219ebf].cursor_name]);else return t&&e[r(1914)](!0,t[r(1335)])}static[n(1532)](t,r,o){return new U(t,r,o)}static[n(1277)+"s"](t,r,o){let x=n;return o?U["fromByte"+x(849)](t,r):U[x(1277)+x(1730)](t,r)}static["fromByte"+n(849)](t,r){let o=n;return new U(e[o(674)](e[o(1315)](e[o(1408)](t[0],e[o(1236)](t[1],8)),e[o(464)](t[2],16)),e[o(464)](t[3],24)),e[o(856)](e[o(540)](t[4],e[o(1320)](t[5],8)),e[o(1600)](t[6],16))|e[o(629)](t[7],24),r)}static[n(1277)+"sBE"](t,r){let o=n;return new U(e.mHsDD(e[o(1408)](e[o(1275)](t[4]<<24,t[5]<<16),e.Ndnxo(t[6],8)),t[7]),e[o(1275)](e.mHsDD(e[o(1368)](t[0],24),e[o(1310)](t[1],16)),t[2]<<8)|t[3],r)}static[n(1154)](t){let r=n;return t===Sa?ps:new U(e.WnGkk(e.xUIbt(e[r(1408)](ze.call(t,0),e[r(1262)](ze[r(1147)](t,1),8))|e[r(1507)](ze.call(t,2),16),e[r(1296)](ze.call(t,3),24)),0),e[r(1285)](e[r(1408)](e[r(1275)](ze[r(1147)](t,4),e[r(1361)](ze.call(t,5),8)),e[r(1811)](ze.call(t,6),16))|ze.call(t,7)<<24,0),!0)}[n(1299)](){let t=n;return String[t(617)+"Code"](e[t(502)](255,this[t(1080)]),e[t(860)](this.low>>>8,255),e[t(1749)](e.chSmY(this[t(1080)],16),255),e[t(1286)](this[t(1080)],24),e[t(929)](255,this.high),e[t(1390)](e[t(1706)](this[t(1760)],8),255),e[t(897)](e[t(1286)](this.high,16),255),this[t(1760)]>>>24)}static fromNumber(t,r=!0){let o=n;if(e[o(1652)](isNaN,t))return r?Ea:ps;if(r){if(e[o(1739)](t,hs))return Aa}else{if(e.wblOk(t,-gs))return ka;if(e.CqotF(e.WZDVN(t,1),gs))return Ca}return U[o(1532)](e[o(571)](e.XknSY(t,rt),0),e[o(1644)](e.PyaLv(t,rt),0),r)}[n(949)](){let t=n;return this[t(1499)]?e.zkmWs(e.zROfp(e[t(534)](this[t(1760)],0),rt),e[t(1529)](this[t(1080)],0)):e[t(800)](e[t(1218)](this[t(1760)],rt),e[t(814)](this[t(1080)],0))}isZero(){let t=n;return e[t(1560)](0,this.high)&&this[t(1080)]===0}[n(994)](t){let r=n;U[r(1335)](t)||(t=U[r(931)+"er"](t));let o=this.high>>>16,x=e.CuUxg(65535,this.high),l=this[r(1080)]>>>16,g=65535&this[r(1080)],m=e[r(1547)](t[r(1760)],16),f=e[r(1864)](65535,t[r(1760)]),v=e[r(748)](t[r(1080)],16),b=65535&t.low,k=0,A=0,D=0,O=0;return O+=e.PTWrA(g,b),D+=e.zNvEo(O,16),O&=65535,D+=e[r(1019)](l,v),A+=e[r(843)](D,16),D&=65535,A+=x+f,k+=e[r(612)](A,16),A&=65535,k+=e[r(832)](o,m),k&=65535,U[r(1532)](D<<16|O,e[r(540)](e[r(1368)](k,16),A),this.unsigned)}[n(857)](t){let r=n;return U[r(1335)](t)||(t=U[r(931)+"er"](t)),e.wfwFH(this[r(1499)],t[r(1499)])&&e[r(578)](e[r(1048)](this[r(1760)],31),1)&&e[r(1082)](e.EKXtq(t[r(1760)],31),1)?!1:e[r(1082)](this[r(1760)],t.high)&&e[r(484)](this.low,t[r(1080)])}[n(1161)](){let t=n;return e[t(1065)](-1,this[t(1080)])&&this[t(1760)]===-1?U[t(1532)](0,0,this[t(1499)]):e[t(1653)](-1,this[t(1080)])?U[t(1532)](0,e.zkmWs(this[t(1760)],1),this[t(1499)]):U[t(1532)](e[t(529)](this.low,1),this[t(1760)],this[t(1499)])}[n(1858)](t){let r=n;return t?this[r(1671)+"E"]():this[r(1071)+"E"]()}[n(1671)+"E"](){let t=n,r=this[t(1760)],o=this[t(1080)];return[255&o,e[t(1131)](e[t(963)](o,8),255),e[t(887)](e[t(612)](o,16),255),e.aHZoj(o,24),e[t(1255)](255,r),e[t(1902)](r>>>8,255),r>>>16&255,r>>>24]}[n(1071)+"E"](){let t=n,r=this.high,o=this[t(1080)];return[e[t(1285)](r,24),e.kMzKm(e[t(1706)](r,16),255),e.NXimc(e[t(814)](r,8),255),e[t(1176)](255,r),o>>>24,e[t(1353)](e[t(963)](o,16),255),e.OmwbQ(e[t(748)](o,8),255),255&o]}}let ps=new U(0,0,!1),Ea=new U(0,0,!0),Ca=U[n(1532)](-1,2147483647,!1),Aa=U[n(1532)](-1,-1,!0),ka=U[n(1532)](0,-2147483648,!1);var qe=(function(s){let t=n,r=e.DIFQg[t(721)]("|"),o=0;for(;;){switch(r[o++]){case"0":s[s[e[t(1097)]]=5002]=e[t(1097)];continue;case"1":s[s[e.kkCpA]=5005]=e.kkCpA;continue;case"2":s[s[e[t(585)]]=5001]="NATIVE_E"+t(559);continue;case"3":s[s[e[t(1613)]]=5003]=t(1152)+t(659)+"R";continue;case"4":return s;case"5":s[s[e.oWqaE]=5004]=t(553)+t(508);continue}break}})({});class st{constructor(t){let r=n;this[r(557)]=t,this[r(1232)]=null}}class ms extends st{constructor(t,r){let o=n;super(t),this.message=r&&r[o(1284)]||null}}class ws extends st{constructor(t,r){let o=n,x=e[o(1664)][o(721)]("|"),l=0;for(;;){switch(x[l++]){case"0":this.error=r&&r[o(740)]||null;continue;case"1":this[o(1284)]=r&&r.message||"";continue;case"2":super(t);continue;case"3":this.lineno=r&&r[o(1762)]||0;continue;case"4":this[o(1205)]=r&&r.colno||0;continue;case"5":this[o(1513)]=r&&r[o(1513)]||5001;continue;case"6":this[o(875)]=r&&r[o(875)]||"";continue}break}}}class _s extends st{constructor(t,r){let o=n;super(t),this[o(1513)]=r&&r[o(1513)]||0,this[o(1608)]=r&&r[o(1608)]||"",this[o(1662)]=r&&r[o(1662)]||!1,this[o(1204)+"nnect"]=r&&r[o(1204)+"nnect"]||!1}}class ys extends st{constructor(t,r){let o=n;super(t),this[o(1401)]=r&&r.data||null}}class bs extends ys{constructor(t,r){let o=n;super(t),this[o(1401)]=r&&r[o(1401)]||null,this[o(1284)]=r&&r[o(1284)]||null}}class vs extends st{constructor(t,r){super(t),this.data=r&&r.data||null}}function de(s,{message:t,code:r,error:o}){return new ws(s,{message:t,code:r,error:o})}function ge(s,{code:t,reason:r,wasClean:o,willReconnect:x}){let l=n;if(e[l(1724)]==="byTKS")return new _s(s,{code:t,reason:r,wasClean:o,willReconnect:x});_0x476cac[l(1192)]()[l(848)](()=>{let g=l;this[g(565)+g(549)]()})}function Ss(s,{data:t,message:r}){let o=n;if(e[o(1874)](e[o(1351)],e[o(1351)]))return new bs(s,{data:t,message:r});{let x=e[o(1099)](_0xb8085,_0xc36ff3);this[o(1899)]&&e[o(1785)](this[o(1899)].readyState,this[o(516)])&&(this._ws&&this[o(1899)][o(899)](x),this[o(876)](e[o(1597)],_0x25a97d))}}function Es(s,{data:t}){return new vs(s,{data:t})}function cr(s,{message:t}){let r=n;if(e.BIciu("StAle",e[r(1058)]))return new ms(s,{message:t});this[r(1743)+r(1805)]=_0x3834b7,this[r(1899)]&&(this._ws[r(1183)+"pe"]=_0x4a16dd)}class Cs{constructor(t,r){let o=n;this[o(1185)+"s"]=t,this[o(882)+"es"]=r,this[o(663)+"ndex"]=0,this[o(1854)+o(896)+o(1847)+"t"]=0}[n(867)+n(1911)+n(501)](){let t=n;this[t(663)+t(497)]=0,this["currentE"+t(896)+t(1847)+"t"]=0}[n(547)+"es"](){let t=n;this[t(1854)+"ndpointTriesCount"]=0}[n(1087)+"ntEndpoint"](){let t=n;return this[t(1185)+"s"][this[t(663)+"ndex"]]}[n(1087)+"ntEndpoi"+n(1217)+"ount"](){let t=n,r={ArJDz:function(o,x){return e[T(1213)](o,x)},grTxv:function(o,x){return e[T(1653)](o,x)},Yesgi:e[t(1804)],nUtwS:e[t(1444)],GapTI:e[t(1500)],OcZyg:function(o,x,l){return e[t(717)](o,x,l)},anuxF:function(o,x,l,g){return o(x,l,g)}};if(e.OIYdi!==e[t(498)]){let{pingInterval:o,pingFrequency:x}=this[t(1447)];if((r[t(582)]("hi",_0x325770[t(1401)])&&r[t(1134)](r[t(1273)],x)||t(1473)===x)&&(this[t(479)+t(1445)](),this[t(1504)](r[t(1470)],r[t(618)]),this[t(797)+t(996)+"Id"]=r[t(1615)](_0x460b87,this[t(926)][t(1695)](this),o)),r.ArJDz("hi",_0x4cbdfb[t(1401)]))return;try{r[t(1742)](_0x4cce19,this,_0x182778,[_0x18f861,_0x34d7fb,_0x54c098,_0x532d05,_0x456678,_0x3de4cd])}catch(l){let g=_0x275635(t(740),{message:l.message,code:_0x4c7e73.MESSAGE_ERROR,error:l});this[t(1264)+t(1766)+t(1756)](g)}}else return this[t(1854)+t(896)+t(1847)+"t"]}[n(879)+n(1561)+"es"](){let t=n;return!!(e[t(1631)](this["currentI"+t(497)],this[t(1185)+"s"].length)||e[t(1874)](this[t(663)+t(497)],e.GkzSz(this.endpoints[t(1326)],1))&&e.XbFFb(this[t(1854)+"ndpointT"+t(1847)+"t"],this[t(882)+"es"]))}[n(864)+"rentEndp"+n(575)+n(1135)+"tries"](){let t=n;return this[t(663)+t(497)]==this[t(1185)+"s"].length?!0:e[t(1258)](this[t(1854)+"ndpointTriesCount"],this.maxRetries)}[n(1377)+"ackupEndpointAndUpdateCo"+n(626)](){let t=n;return this[t(1854)+"ndpointT"+t(1847)+"t"]=1,this["currentI"+t(497)]++,this.endpoints[this.currentIndex]}[n(1087)+n(1004)+n(1430)+n(1722)](){let t=n;return this[t(1854)+t(896)+t(1847)+"t"]++,this[t(1087)+t(1004)+"nt"]()}}let it=(e[n(883)]!=typeof globalThis&&globalThis[n(1496)+n(798)][n(1281)]==="Window"||e[n(1159)]("undefined",typeof window)&&e[n(1399)](e[n(1830)],window["construc"+n(798)][n(1281)]))&&e[n(883)]!=typeof document,Xe=e[n(1523)](e[n(883)],typeof globalThis)&&(e[n(795)](e[n(1371)],globalThis[n(1496)+n(798)][n(1281)])||e[n(665)](e[n(1450)],globalThis[n(1496)+n(798)].name))&&e[n(1179)](e[n(883)],typeof tt),At=(e[n(883)]!=typeof globalThis&&e[n(473)](e[n(1371)],globalThis[n(1496)+n(798)].name)||e[n(1391)](e.KCitV,typeof globalThis)||e.NGMvY(e[n(883)],typeof globalThis)&&!!globalThis[n(1174)+n(895)])&&e[n(1669)](e[n(883)],typeof wx),kt=e.knMQQ(n(1340)+"d",typeof globalThis)&&(e[n(706)](e.YDGog,globalThis[n(1496)+n(798)][n(1281)])||e[n(1173)](e[n(1425)],globalThis[n(1496)+n(798)][n(1281)])||e.mfhDw(e.OxXeV,globalThis[n(1496)+n(798)][n(1281)]))&&e[n(883)]!=typeof self,Pa=e[n(1230)](e.KCitV,typeof globalThis)&&e[n(795)](e[n(1371)],globalThis["construc"+n(798)].name)&&e.frbIx(e[n(883)],typeof global)&&e[n(1371)]===global["construc"+n(798)][n(1281)]&&e[n(1302)](e[n(883)],typeof process)&&!!process[n(1487)];class xr{constructor(){let t=n,r={DrdTn:function(o,x){return o(x)}};if(e[t(738)]!==e[t(738)])return function(o,...x){let l=t,g=_0x477421[l(1147)](ShAHIF.DrdTn(_0x2930a7,this),o,...x);return _0x1da419.set(g,o[l(828)]?o[l(828)]():[o]),ShAHIF[l(1878)](_0x1c2db1,g)};this[t(1267)+"rs"]={}}[n(1504)](t,...r){let o=n,x=this[o(1267)+"rs"][t];if(x)x[o(1526)]()[o(1845)](l=>l.fn[o(1163)](l[o(1311)],r));else if(e[o(1563)](e[o(635)],t)&&!this[o(1692)]){let l=r[o(1326)]&&r[0];if(e.PVVUF(l,Error))throw l;let g=new Error(e[o(1538)]("Unhandle"+o(1338),l?e[o(830)](e[o(1738)](" (",l[o(1284)]),")"):""));throw g.context=l,l}return this}off(t,r){let o=n;if(e[o(1213)](void 0,t))this[o(1267)+"rs"]={};else if(r===void 0)this[o(1267)+"rs"][t]=null;else{let x=this[o(1267)+"rs"][t];if(x)for(let l=0;e[o(515)](l,x[o(1326)]);)e.usRqC(x[l].fn,r)?x[o(1028)](l,1):++l}return this}on(t,r,o){let x=n;return(this._listeners[t]||(this[x(1267)+"rs"][t]=[])).push({fn:r,ctx:o||this}),this}}class Da extends xr{[n(1094)+n(1438)+n(1718)](t){let r=n;return t[r(1580)]||t[r(870)]?(r(1282)+" "+(t[r(1580)]||"")+r(1646)+(t[r(870)]||""))[r(1548)]():JSON[r(1675)+"y"](t)}constructor(t,r,o){let x=n;super(),this._socket=null,At&&wx[x(1352)+x(923)]&&(this[x(551)]=wx[x(1352)+x(923)]({url:t,protocols:r,header:o,fail:this["_createS"+x(898)+x(1350)][x(1695)](this),success:this["_createS"+x(645)+x(1479)+x(688)][x(1695)](this)})),Xe&&tt[x(1352)+x(923)]&&(this[x(551)]=tt[x(1352)+x(923)]({url:t,protocols:r,header:o,fail:this["_createS"+x(898)+"lHandler"][x(1695)](this),success:this[x(737)+x(645)+x(1479)+x(688)][x(1695)](this)}))}[n(737)+n(645)+n(1479)+n(688)](){let t=n;Promise[t(1192)]()[t(848)](()=>{let r=t;this[r(565)+r(549)]()})}[n(737)+"ocketFai"+n(1350)](t){let r=n,o={eYuOb:function(x,l){return e[T(1571)](x,l)},YrFOK:e[r(1536)],vlonG:e[r(1467)],hlDuk:function(x,l,g){return e[r(1009)](x,l,g)},RRVPY:"error",lMiTz:function(x,l,g){return x(l,g)},BLNrY:e[r(1574)]};if(e[r(915)](e.fxMwU,e[r(690)])){let x=_0x2cd965[r(1796)+"g"](0,yKCLIQ[r(1826)](4,_0x14f51c[_0xce5d97][r(1326)])),l=x[r(634)](_0x169b38[_0x26f668]);_0x422470[r(1414)](l)}else Promise.resolve()[r(848)](()=>{let x=r;if(o.YrFOK===o[x(623)])return this.endpoints[this[x(663)+x(497)]];{let l=o[x(560)](de,o[x(1206)],{message:this[x(1094)+x(1438)+x(1718)](t)});this[x(1504)](x(740),l);let g=o.lMiTz(ge,o[x(554)],{reason:this["_formatE"+x(1438)+x(1718)](t)});this[x(1504)](o.BLNrY,g)}})}[n(565)+"steners"](){let t=n,r={rKNKc:function(o,x,l){return e[T(1428)](o,x,l)},KRsUR:e[t(1574)],sLOSk:e[t(1283)]};this._socket[t(987)](o=>{let x=t;this[x(1504)](x(1515),r[x(1544)](Es,"open",{...o,data:o[x(1580)]||""}))}),this[t(551)][t(621)](o=>{let x=t;this[x(1504)](r[x(1483)],ge(r.KRsUR,{...o}))}),this._socket[t(616)+"e"](o=>{let x=t;this.emit("message",r[x(1544)](Ss,r[x(1481)],{...o}))}),this[t(551)].onError(o=>{let x=t;this[x(1504)](e[x(635)],e.wHkNc(de,e.RdxQI,{...o,message:o.errMsg||""}))})}[n(899)](t){let r=n,o={vPHPM:e.RdxQI,tYCHP:function(x,l,g){return e.uMPah(x,l,g)}};if(e.oCnsr(t,Uint8Array))if(e[r(927)](r(670),r(813))){let x=t[r(1078)][r(1526)](t[r(1522)+"et"],t[r(940)+"th"]+t[r(1522)+"et"]);this._socket&&this._socket[r(899)]({data:x,fail:l=>{let g=r;this[g(1504)](o[g(861)],o[g(842)](de,o[g(861)],{message:this[g(1094)+g(1438)+"age"](l)}))}})}else{let x=0,l=_0x13e3ff,g=e[r(800)](_0x11c5e1,4);for(;l<g;){let{value:m,offset:f}=e[r(1316)](_0x3b7c57,_0xf07dd8,l);l=f,x=e.HyYns(x,8)>>>0,x+=m}return{value:x,offset:g}}else this._socket&&this[r(551)][r(899)]({data:t,fail:x=>{let l=r;this[l(1504)](e[l(635)],e[l(1915)](de,e[l(635)],{message:this[l(1094)+l(1438)+l(1718)](x)}))}})}close(t,r){let o=n;this[o(551)]&&this[o(551)].close({code:t,reason:r})}[n(1485)+n(1130)](t,r){this.on(t,r)}[n(1590)+n(1366)+n(866)](t,r){this[n(678)](t,r)}get[n(1510)+"te"](){let t=n;return this[t(551)][t(1510)+"te"]}get[n(1183)+"pe"](){let t=n;return this[t(551)][t(1183)+"pe"]}set[n(1183)+"pe"](t){}get url(){let t=n;return this[t(551)][t(752)]}get[n(1701)](){let t=n;return this[t(551)][t(1701)]}get[n(1215)+"ns"](){let t=n;return this[t(551)][t(1215)+"ns"]}get[n(1356)+n(649)](){let t=n,r={fXgYL:function(o,x){return o<=x},BSDFi:function(o,x){return e[T(1122)](o,x)},Agrwo:function(o,x){return o+x},ogYZd:function(o,x){return e[T(1349)](o,x)},vmlmn:function(o,x){return e.QUaQF(o,x)},fiKiG:function(o,x){return e[T(674)](o,x)},baHne:function(o,x){return o&x},bGmVL:function(o,x){return o>>x},JOUxS:function(o,x){return o|x},kpyJN:function(o,x){return e.kUSmu(o,x)},ubMRv:function(o,x){return e[T(1709)](o,x)},HXvoc:function(o,x){return o>>x},lUXuM:function(o,x){return o>>x},munOl:function(o,x){return e[T(891)](o,x)}};if(e[t(1360)](e.wFqEa,e[t(1913)]))return 0;{let o=_0x153426[t(872)+"At"](_0x9ee9f2);o>=55296&&lsazLn[t(1437)](o,56319)&&lsazLn[t(855)](lsazLn[t(1721)](_0x87068e,1),_0x2b593e)&&(o=lsazLn[t(1093)](lsazLn[t(1747)](o,10)+_0x56b677.charCodeAt(++_0x296597),56613888)),o<128?_0x5a3802[_0x16f1d3++]=o:(lsazLn.BSDFi(o,2048)?_0x12a91b[_0x14b0e9++]=lsazLn[t(532)](lsazLn.baHne(lsazLn.bGmVL(o,6),31),192):(lsazLn[t(855)](o,65536)?_0x25e865[_0x200c96++]=lsazLn.JOUxS(lsazLn.kpyJN(o>>12,15),224):(_0x3ae270[_0x3cca59++]=lsazLn[t(1278)](lsazLn[t(552)](o,18)&7,240),_0x171729[_0x3da76c++]=lsazLn.JOUxS(lsazLn.baHne(lsazLn.lUXuM(o,12),63),128)),_0x9ae2a0[_0x2199f0++]=lsazLn[t(1298)](lsazLn.munOl(o,6),63)|128),_0x57cf87[_0x32c367++]=lsazLn[t(471)](63,o)|128)}}}function Ia(s,t){let r=n;if(t)return new t(s[r(752)],s[r(1701)]);if(e[r(672)](At,Xe))return new Da(s[r(752)],s[r(1701)],s[r(1119)]);if((it||kt)&&e[r(1669)](e.KCitV,typeof WebSocket)&&WebSocket)return new WebSocket(s[r(752)],s[r(1701)+"s"])}function Ta(s){let t=n,r=e[t(1456)].split("|"),o=0;for(;;){switch(r[o++]){case"0":if(Xe&&tt["connectS"+t(923)])return!0;continue;case"1":if(At&&wx[t(1352)+"ocket"])return!0;continue;case"2":if((it||kt)&&e[t(1475)](t(1340)+"d",typeof WebSocket)&&WebSocket)return!0;continue;case"3":if(s)return!0;continue;case"4":return!1}break}}function As(s,t,r){let o={VXvxi:function(g,m){return e[T(666)](g,m)},EcMhy:function(g,m){return e[T(529)](g,m)},iYlzu:e.xMikD},x=-1;async function l(g){let m=T;if(e.bnFZv(e[m(972)],m(1288)))return g<=x?Promise[m(1630)](new Error(e[m(1907)])):(x=g,e.MEfGc(g,r[m(1326)])?Promise[m(1192)]():r[g].bind(s)(t,l[m(1695)](null,e[m(789)](g,1))));{let f=_0x3f4f34[m(1326)]&&_0x1d68b2[0];if(mhuWME[m(1486)](f,_0x3225ec))throw f;let v=new _0x56b24e(mhuWME.EcMhy(mhuWME[m(682)],f?mhuWME.EcMhy(" ("+f.message,")"):""));throw v[m(650)]=f,f}}l(0)}function ks(s){let t=n,r=0,o=0;for(let x=0;e[t(1606)](x,s[t(1326)]);++x)o=s[t(872)+"At"](x),o<128?r+=1:e[t(1611)](o,2048)?r+=2:e[t(1560)](e[t(1864)](64512,o),55296)&&e[t(1620)](e.mpdvs(64512,s[t(872)+"At"](e[t(481)](x,1))),56320)?(++x,r+=4):r+=3;return r}function Ps(s,t,r){let o=n;if(e.clgnb(e[o(1235)](r,t),1))return"";let x="";for(let l=t;e[o(841)](l,r);){let g=s[l++];if(e[o(1329)](g,127))x+=String[o(617)+"Code"](g);else if(g>=192&&e.cPjBx(g,224))x+=String[o(617)+o(1383)](e[o(1792)](e[o(1581)](31,g)<<6,63&s[l++]));else if(e[o(1689)](g,224)&&e[o(1114)](g,240))x+=String["fromChar"+o(1383)](e[o(1184)](e[o(1811)](e[o(1144)](15,g),12),(63&s[l++])<<6)|e.gORDb(63,s[l++]));else if(e[o(1776)](g,240))if(e[o(954)](e.GdJgd,e.UZwZo)){let m=e.KgXTo(_0x5e1e3f,_0x4865e1,_0x1d20ae[o(1326)]);_0x182587[o(1405)][o(1416)](_0x19743a,m)}else{let m=e[o(1349)](e.mHsDD(e[o(1390)](7,g)<<18|e[o(1619)](e[o(1591)](63,s[l++]),12),e.ebQxJ(e[o(1403)](63,s[l++]),6))|63&s[l++],65536);x+=String[o(617)+o(1383)](e[o(1617)](55296,e[o(1337)](m,10))),x+=String["fromChar"+o(1383)](e[o(1306)](56320,e[o(1797)](1023,m)))}}return x}function ur(s,t,r){let o=n,x={sDxHx:function(f,v,b){return e[T(535)](f,v,b)},mXeDj:e.csqFZ},l=r,g,m;for(let f=0;f<s[o(1326)];++f)if(g=s.charCodeAt(f),e[o(642)](g,128))t[r++]=g;else if(e[o(1607)](g,2048)){if(e.YEoqO===e.aQuHJ)return(this[o(1267)+"rs"][_0xa8af7e]||(this[o(1267)+"rs"][_0x2468e4]=[]))[o(1414)]({fn:_0x2626ae,ctx:_0x70adc7||this}),this;t[r++]=e[o(1050)](e[o(1663)](g,6),192),t[r++]=63&g|128}else if(e[o(1636)](e[o(1305)](64512,g),55296)&&e[o(1785)](64512&(m=s[o(872)+"At"](f+1)),56320)){let v=e.fwdYN[o(721)]("|"),b=0;for(;;){switch(v[b++]){case"0":g=e[o(1738)](e.AtkvZ(65536,e[o(1308)](1023,g)<<10),e[o(1061)](1023,m));continue;case"1":t[r++]=e[o(520)](63,g)|128;continue;case"2":t[r++]=e[o(1050)](e[o(1553)](e[o(891)](g,12),63),128);continue;case"3":t[r++]=e.Fhorz(g,18)|240;continue;case"4":t[r++]=e[o(1792)](e[o(878)](e[o(1621)](g,6),63),128);continue;case"5":++f;continue}break}}else if(e[o(1168)](e[o(989)],e[o(989)]))t[r++]=e[o(540)](e[o(1431)](g,12),224),t[r++]=e[o(755)](e[o(1879)](g>>6,63),128),t[r++]=e[o(511)](e.XPFPK(63,g),128);else{let v=wXGraV.sDxHx(_0x1610d7,"error",{message:this[o(1094)+o(1438)+"age"](_0x5ea539)});this[o(1504)](o(740),v);let b=_0x3b2861(o(1076),{reason:this[o(1094)+o(1438)+o(1718)](_0x211cd5)});this[o(1504)](wXGraV[o(713)],b)}return e[o(888)](r,l)}async function Ds(s){let t=n;if(e[t(1082)](t(1325),e[t(539)])){if(e.cAPsb(e[t(1546)],typeof s)){let r=new Uint8Array(e[t(1807)](ks,s));return e[t(1194)](ur,s,r,0),r}return s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s[t(1078)],s[t(1522)+"et"],s.byteLength)}else return _0x35c5b9[t(1192)]()}function La(s){let t=n;if(e.mWWxe(e[t(1823)],e[t(1823)]))this[t(1504)](e[t(635)],e[t(495)](_0x45fc4a,e.RdxQI,{message:this[t(1094)+t(1438)+t(1718)](_0x5c33ec)}));else try{return e.NGMvY(e.OIVMU,typeof s)&&(e[t(1090)](s,ArrayBuffer)||s[t(1078)]&&e[t(1137)](s.buffer,ArrayBuffer))||e[t(1669)](e.OIVMU,typeof s)?"":(JSON[t(1111)](s),e[t(1842)])}catch{return e[t(998)](e[t(1546)],typeof s)?e[t(1219)]:""}}let Ra=(s,t)=>{let r=n;switch(s){case e.TRZZz:case e.RMXqZ:return{[r(1128)+s]:1,"x-tt-env":t};default:return{}}};class Na{constructor(t){let r=n;if(e[r(1798)](r(537),e[r(1392)]))try{this[r(1899)]&&this[r(1899)][r(1076)](_0x4d8f8b,_0x32759a)}catch{}else this[r(825)+"ount"]=t,this[r(733)]=0}[n(558)](){let t=n;this[t(733)]++}[n(879)+n(1495)+"nt"](){let t=n,r={UlraZ:function(o,x,l){return o(x,l)}};if(e[t(1725)]!==e.pzFwG)r[t(1397)](_0x187492,_0x24826a,this[t(810)+t(1535)+"e"](_0x3bcb96));else return e.bweDN(this.count,this[t(825)+t(1047)])}[n(1707)+n(1880)](t=0){let r=n;e[r(1307)](r(847),e.VofAz)?this._addWsListeners():(this[r(825)+"ount"]=t,this.count=0)}}async function Oa(s){let t=n,r={cGxMm:t(1857)+t(1608),TvEba:function(o,x){return e.kDYWM(o,x)},LcWVL:function(o,x){return e.rXKfc(o,x)},LZUBn:t(1626),FZnEB:e.kHpTB,Xqkvs:function(o,x){return o+x},DPBTn:e.eLKoT,HjVch:e.dleqQ,rIlzd:function(o,x){return e.cZvPA(o,x)}};return new Promise(o=>{let x=t,l={sYIde:r[x(1170)]};if(!it)return r[x(1242)](o,r[x(1170)]);try{if(r[x(1245)](x(1757),x(1757))){let g=document[x(1362)+"ement"](r[x(1758)]);window[x(1686)+x(807)]=m=>{let f=x;document[f(1211)][f(505)+f(817)](g),window[f(1686)+f(807)]=void 0,o(m&&m[f(1786)]||l.sYIde)},g[x(557)]=r[x(925)],g[x(668)]=r[x(1649)](s.replace(/^ws/,r[x(796)]),r[x(457)]);try{document[x(1211)][x(962)+x(817)](g)}catch{document.body[x(505)+x(817)](g)}}else return _0x2ef570[x(1672)+x(1389)][1]?void 0:_0x31feeb[x(1672)+"ore"](_0xe4323[x(1672)+x(1389)][0])}catch{window[x(1686)+x(807)]=void 0,r.rIlzd(o,r[x(1170)])}})}function Fe(s,t,r){let o=n;return!!s?.[o(1060)](x=>x[o(769)]===t&&x.value===r)}function ot(s,t){return s?.find(r=>r.key===t)?.value}let dr=null;async function Ba(){let s=n;return dr||(dr=Promise[s(1192)]()[s(848)](Ee[s(1695)](Ee,e[s(1556)]))),dr}class Ma extends xr{constructor(t,r){let o=n;super(),this[o(900)]=t,this[o(491)]=r,this[o(603)]=void 0,this[o(1031)+o(652)]=null}async[n(647)](){await this[n(1382)]()}async[n(1382)](){let t=n,r={EqTcm:function(o){return e[T(780)](o)},DvvBx:function(o,x,l,g){return e[T(1194)](o,x,l,g)}};if(!this[t(603)]){if(this[t(1031)+t(652)])return this[t(1031)+t(652)];try{let o=this[t(900)],x=this[t(491)];this[t(1031)+t(652)]=(async()=>{let l=t,{openDB:g}=await r[l(580)](Ba);this[l(603)]=await r.DvvBx(g,l(1686)+"_"+o,1,{upgrade(m){let f=l;m[f(827)+f(1735)+"e"](o,{keyPath:x})}})})(),await this[t(1031)+t(652)]}catch(o){if(e[t(1434)](e[t(1885)],e[t(630)]))return this[t(603)][t(691)]();console[t(1746)](o)}finally{this[t(1031)+t(652)]=null}}}async get(t){let r=n;try{return await this[r(1382)](),this[r(603)]?.[r(1208)](this[r(900)],t)}catch(o){e.ldQVy(r(938),e.DMTNf)?this._cursorFileName=_0x40a67a:console[r(1746)](o)}}async[n(1416)](t,r){let o=n;return await this._init(),this[o(603)]?.put(this[o(900)],t)}async del(t){let r=n;try{return await this[r(1382)](),this[r(603)]?.[r(545)](this[r(900)],t)}catch(o){console[r(1746)](o)}}async clear(){let t=n;try{return await this[t(1382)](),this[t(603)]?.[t(691)](this[t(900)])}catch(r){console[t(1746)](r)}}async keys(){let t=n;return await this._init(),this[t(603)]?.[t(1043)+"ys"](this[t(900)])}async[n(916)](){let t=n;return await this[t(1382)](),this[t(603)]?.getAll(this[t(900)])}async[n(778)](){let t=n;if(e[t(523)]===e.DroYa){let r=_0x2bc843["deleteDa"+t(766)](_0x4a972e);return _0xcb5a0c&&r[t(1485)+t(1130)](gsOVnc[t(975)],()=>_0x271706()),gsOVnc.EBmKg(_0x4e755f,r)[t(848)](()=>{})}else try{this[t(603)]?.[t(1076)](),this[t(603)]=void 0}catch(r){if(e[t(862)](e[t(589)],"SoMUg"))console.log(r);else return new _0x5efc3f(_0x1a440f,{code:_0x10c053,reason:_0x581f0d,wasClean:_0x5d72dd,willReconnect:_0x426e71})}}get isReady(){let t=n;try{return!!this[t(603)]}catch(r){return console[t(1746)](r),!1}}}class za{constructor(t,r){let o=n;if(e[o(1169)](o(852),e.NHoZH))this._DBName=t,this._pathKey=r,this[o(603)]=localStorage;else return _0x5b1481[o(1163)](gsOVnc[o(1793)](_0x4a1e9a,this),_0x36e5cb),gsOVnc.upmIr(_0x51045c,_0x39fdef[o(1208)](this))}async[n(647)](){}get[n(1667)](){let t=n;return t(1686)+"_"+this[t(782)]}async[n(1208)](t){let r=n,o=this._qosDB.getItem(this[r(1667)]);return JSON[r(1111)](e[r(692)](o,"{}"))[t]}async set(t,r){let o=n,x=this[o(603)][o(724)](this._prefix),l=JSON[o(1111)](x||"{}");return l[r||t[this[o(1005)]]]=t,this[o(603)][o(1634)](this[o(1667)],JSON[o(1675)+"y"](l)),r||t[this._pathKey]}async del(t){let r=n,o=this._qosDB[r(724)](this._prefix),x=JSON[r(1111)](e[r(1175)](o,"{}"));return x[t]=void 0,this[r(603)][r(1634)](this[r(1667)],JSON[r(1675)+"y"](x))}async[n(691)](){let t=n;return this[t(603)][t(691)]()}async[n(1460)](){let t=n,r=this[t(603)][t(724)](this._prefix),o=JSON[t(1111)](e[t(761)](r,"{}"));return Object[t(1460)](o)}async[n(916)](){let t=n;if(e.MEfGc(e[t(1250)],e[t(1049)]))return this[t(603)]?.[t(1053)];{let r=this._qosDB[t(724)](this[t(1667)]),o=JSON.parse(e[t(1303)](r,"{}"));return Object.values(o)}}[n(778)](){let t=n,r={kDJdZ:e[t(1444)],FSqJY:e[t(1572)],bWKvR:function(o,x){return o(x)}};if(e.WAJdB==="IAsWO")return Promise[t(1192)]();{this[t(479)+t(1445)](),this[t(797)+t(996)+"Id"]=_0x4ce636(this[t(926)][t(1695)](this),this._options[t(845)+"rval"]);let o=()=>{let l=t;_0x3cf653("success"),this[l(678)](r[l(1243)],o),this[l(678)](r[l(1748)],x)},x=()=>{let l=t;r.bWKvR(_0xa0f912,"timeout"),this.off(r[l(1243)],o),this[l(678)](r[l(1748)],x)};this.on(e.qxALn,o),this.on(e[t(1572)],x),this[t(926)]()}}get[n(1053)](){return!!this[n(603)]}}class qa{constructor(t,r){let o=n;this[o(782)]=t,this._pathKey=r,this._qosDB=Xe?tt:At?wx:null}async[n(647)](){}get[n(1667)](){let t=n;return e.wfwFH(e[t(1569)],e[t(902)])?t(1686)+"_"+this._DBName:!!this[t(603)]}async[n(1208)](t){let r=n,o=this[r(603)][r(1153)+"geSync"](this[r(1667)]);return JSON[r(1111)](e.kVUpB(o,"{}"))[t]}async[n(1416)](t,r){let o=n,x=this[o(603)].getStorageSync(this[o(1667)]),l=JSON[o(1111)](e[o(1462)](x,"{}"));return l[r||t[this[o(1005)]]]=t,this[o(603)][o(581)+o(1364)](this[o(1667)],JSON[o(1675)+"y"](l)),r||t[this[o(1005)]]}async[n(530)](t){let r=n,o=this._qosDB[r(1153)+r(1364)](this._prefix),x=JSON.parse(e[r(692)](o,"{}"));return x[t]=void 0,this[r(603)][r(581)+r(1364)](this[r(1667)],JSON[r(1675)+"y"](x))}async[n(691)](){let t=n;return this[t(603)][t(1750)+t(727)]()}async[n(1460)](){let t=n,r=this[t(603)][t(1153)+t(1884)+"nc"](this[t(1667)]),o=JSON[t(1111)](r||"{}");return Object[t(1460)](o)}async getAll(){let t=n,r=this._qosDB[t(1153)+t(1884)+"nc"](this[t(1667)]),o=JSON.parse(e.mxbfC(r,"{}"));return Object.values(o)}[n(778)](){let t=n;if(e[t(751)](e[t(924)],e.ehmqz))return Promise[t(1192)]();_0x3fe309(gsOVnc[t(1041)](_0x28679e,_0x3bed96[t(638)])),gsOVnc[t(590)](_0x48583f)}get isReady(){return!!this[n(603)]}}function Is(s,t){let r=n;if(e.EsLAv(Xe,Xe))return new qa(s,t);if(e[r(1433)](it,kt)&&e.NGMvY(e.KCitV,typeof indexedDB))return new Ma(s,t);if(e.aPNtu(it,kt)&&r(1340)+"d"!=typeof localStorage)return new za(s,t);throw new Error(e[r(488)])}class Fa{constructor(){let t=n;this[t(494)+t(1384)+"Id"]=null,this[t(494)+"l"]=36e5,this[t(603)]=e.MgbcS(Is,"qos",t(1616)+"id")}async[n(494)+n(1772)](){let t=n,r={cCfyY:function(o,x){return e.GlnQb(o,x)}};if(e[t(1788)](e[t(1256)],e[t(1256)]))return this[t(663)+t(497)]==this.endpoints[t(1326)]?!0:yAWZGp[t(1814)](this["currentE"+t(896)+t(1847)+"t"],this[t(882)+"es"]);e[t(1099)](clearInterval,this[t(494)+t(1384)+"Id"]),this[t(494)+"lTimeoutId"]=e.lzBnJ(setInterval,()=>{this.flushExpired()},this._interval)}async[n(647)](){let t=n;await this[t(603)][t(647)]()[t(848)](()=>{this[t(494)+"lFlush"]()})}async[n(644)+n(1614)](){let t=n;(await this[t(603)]?.[t(916)]()||[]).filter(({timestamp:x})=>x<Date.now())[t(1845)](x=>{let l=t;this[l(603)]?.[l(530)](x[l(1616)+"id"])})}async[n(530)](t){let r=n;return this._qosDB?.[r(530)](t)}async[n(1416)](t,r){let o=n;return this[o(603)]?.[o(1416)]({message_id:t,timestamp:r})}async[n(1208)](t){let r=n;return this[r(603)]?.[r(1208)](t)}async[n(778)](){let t=n,r={rJLEL:function(o,x){return e[T(707)](o,x)},WfCsT:e[t(1067)]};if(e[t(1165)](e[t(1710)],e[t(824)])){let o=_0x32e77e[t(1362)+"ement"](e[t(459)]);_0x419099[t(1686)+t(807)]=x=>{let l=t;_0x583f4b[l(1211)][l(505)+l(817)](o),_0x105e38["frontier"+l(807)]=void 0,mnqFXb.rJLEL(_0x1c162a,x&&x[l(1786)]||mnqFXb.WfCsT)},o[t(557)]="text/jav"+t(1726),o[t(668)]=e[t(1020)](_0x71ea92[t(788)](/^ws/,e[t(1596)]),e[t(1317)]);try{_0x43c176[t(1211)][t(962)+t(817)](o)}catch{_0x27d29e[t(1211)][t(505)+t(817)](o)}}else e[t(1872)](clearInterval,this[t(494)+"lTimeoutId"]),await this[t(603)]?.closeDB()}get[n(1053)](){let t=n;return this[t(603)]?.[t(1053)]}}function fr(s){let t=n,r=!!this._options[t(999)+"S"];if(!r)return{enabled:r,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let o=Fe(s.message[t(1119)],t(709)+t(1413),"2"),x=o&&e[t(500)](Fe,s.message.headers,e.cjXzC,"1"),l=o&&e.uoPtI(Fe,s.message[t(1119)],e.yncLd,"1"),g=l?e[t(700)](ot,s[t(1284)][t(1119)],e[t(1365)])?.[t(721)](",")[t(822)](Boolean)||[]:[];return{enabled:r,isQoSMessage:o,isQoSAck:x,isAckCleanupMessage:l,ackMsgIds:g}}async function Ts(){let s=n;return this["_QoSMana"+s(947)]||(this._QoSManager=new Fa),this[s(703)+s(947)].isReady||await this["_QoSMana"+s(947)][s(647)](),this[s(703)+s(947)]}async function Ua(s,t){let r=n,o={VITsH:function(x,l){return e[T(540)](x,l)},EEasb:function(x,l){return x&l},FRsHT:function(x,l){return e[T(1663)](x,l)},XlNmd:function(x,l){return e.mHsDD(x,l)}};if(e[r(1098)](e.ZRBzZ,e[r(548)])){let{enableAutoAck:x}=this[r(1447)],l=e[r(1194)](Fe,s[r(1284)].headers,e.hWTXt,"1"),g=e.vKovs(Fe,s[r(1284)][r(1119)],r(1035),"1"),m=fr[r(1147)](this,s);if(e[r(1639)](x,l)){let{SeqID:f,LogID:v,service:b,LogIDNew:k,method:A}=s.message;this[r(726)]({SeqID:f,LogID:v,LogIDNew:k,service:b,method:A,headers:[{key:e.fcLAB,value:"1"},{key:e[r(1582)],value:e[r(1462)](k,"")},{key:e.NlbIw,value:"0"}]})}g&&!m.isQoSAck&&this[r(1264)+"hAckMess"+r(1474)](s),e[r(1418)](t)}else _0x9c4fa1[_0x15c03e++]=aAXovw[r(1266)](aAXovw.EEasb(aAXovw[r(977)](_0x150d71,18),7),240),_0x4fd285[_0x44e1cf++]=aAXovw[r(527)](aAXovw[r(1898)](aAXovw.FRsHT(_0x550082,12),63),128)}async function Ha(s,t){let r=n;this._debug(e[r(658)],s[r(1284)]),t()}async function Ka(s,t){let r=n,o=e[r(935)](fs,await e.dUvSf(Ds,s.data));try{if(e[r(1555)](o[r(992)],Uint8Array)){let x=e[r(1090)](this[r(1447)][r(1420)+"ncoding"],Object)?{force:!!this[r(1447)][r(1420)+r(829)][r(1363)],encoding:this[r(1447)][r(1420)+r(829)].encoding?this[r(1447)][r(1420)+r(829)].encoding[r(788)](/\s/g,"")[r(486)+r(1017)]():""}:{force:!1,encoding:this[r(1447)][r(1420)+r(829)]?this._options[r(1420)+r(829)][r(788)](/\s/g,"")[r(486)+r(1017)]():""},l=o[r(1420)+r(829)]?o[r(1420)+r(829)].replace(/\s/g,"")[r(486)+r(1017)]():"",g=e.qxOhf(this._options[r(1198)+r(1805)],Object)?{force:!!this[r(1447)][r(1198)+"ype"][r(1363)],type:this._options[r(1198)+r(1805)].type?this._options["payloadT"+r(1805)][r(557)][r(788)](/\s/g,"")[r(486)+r(1017)]():""}:{force:!1,type:this[r(1447)][r(1198)+r(1805)]?this._options[r(1198)+r(1805)][r(788)](/\s/g,"")[r(486)+r(1017)]():""},m=o[r(1198)+r(1805)]?o[r(1198)+"ype"][r(788)](/\s/g,"")[r(486)+r(1017)]():"",f=g[r(1363)]?g.type:m||g[r(557)],v=x[r(1363)]?x[r(1816)]:l||x[r(1816)],b=[r(1322)+r(477)+"et=utf-8",e.qBQiH,e.AQhcJ,e[r(1546)]],k=[r(802)+"e",e[r(941)]];this[r(1447)][r(1604)+r(1085)+r(1436)+"ad"]&&b[r(1489)](f)&&(!v||k[r(1489)](v))?o[r(785)+"oad"]=e[r(500)](Ps,o[r(992)],0,o[r(992)][r(940)+"th"]):o[r(785)+r(1851)]=""}else o[r(785)+r(1851)]=""}catch(x){o[r(785)+r(1851)]="",console.log(x)}s[r(1284)]=o,e[r(1779)](t)}function ja(s,t,r){let o=n;if(e.TNVQo===e[o(997)]){let x=this._listeners[_0x2a1f9e];if(x)for(let l=0;e[o(1822)](l,x[o(1326)]);)x[l].fn===_0x4b2deb?x[o(1028)](l,1):++l}else{let x=e[o(761)](r,8192),l=e[o(1011)](x,1),g=null,m=x;return function(f){let v=o;if(e.jMtAR(f,1)||f>l)return e.eEvDR(s,f);e.Racjs(e[v(819)](m,f),x)&&(g=s(x),m=0);let b=t[v(1147)](g,m,m+=f);return e[v(808)](7,m)&&(m=e[v(1644)](7,m)+1),b}}}let Ga=4294967295;function Wa(s,t,r){let o=n;return e[o(1801)](RangeError,e[o(1595)](e.aFcCf(e[o(1900)](e[o(1538)](o(1781)+"t of ran"+o(1015),s),e[o(1024)]),e[o(912)](t,1))+e[o(967)],r))}function Ja(s,t,r){let o=n;if(r>Ga)throw new Error("integer "+o(1105)+"e");let x=3;for(;e[o(1838)](x,0);){let l=e[o(480)](255,r);e[o(1453)](hr,l,s,e[o(481)](t,x)),r>>>=8,x--}return e.uWxZY(t,4)}function Va(s,t){let r=n,o=0,x=t,l=e[r(1182)](t,4);for(;e[r(1238)](x,l);)if(e[r(835)]===e.qZpeb){let{value:g,offset:m}=lr(s,x);x=m,o=e.bkvRG(e[r(1084)](o,8),0),o+=g}else _0x35c68c[r(827)+"jectStore"](_0x5af89b,{keyPath:_0x5c2f1f});return{value:o,offset:l}}function Xa(s,t,r){let o=n;if(e.kaleo!=="nVjyd"){let x=e[o(1030)][o(721)]("|"),l=0;for(;;){switch(x[l++]){case"0":if(!s)return r;continue;case"1":return e[o(1661)](ur(s,t,r),r);case"2":if(t[o(1908)])return t[o(1908)](s,r)+r;continue;case"3":if(t[o(555)+"e"])return t[o(555)+"e"](s,r)+r;continue;case"4":if(s[o(1326)]<40)return e[o(1617)](ur(s,t,r),r);continue}break}}else return new _0x3e1800(_0x92adc3,{message:_0x3b298f})}function $a(s,t){let r=n,o=new U(e[r(1525)](e[r(511)](e[r(519)](s[e[r(680)](t,4)],24),e[r(482)](s[e[r(1633)](t,5)],16))|e.fsOdx(s[e.bbecr(t,6)],8),s[e[r(1595)](t,7)]),e[r(1408)](e[r(1184)](e[r(1003)](e.ENICH(s[e[r(680)](t,0)],24),e[r(1871)](s[e[r(1330)](t,1)],16)),e[r(1651)](s[e.HKvlW(t,2)],8)),s[t+3]),!0);return t+=8,{value:o,offset:e[r(1336)](t,8)}}function Ya(s,t,r){let o=n,x=s[o(1080)],l=s.high;return t[r]=e[o(1547)](l,24),t[r+1]=e[o(1902)](e[o(612)](l,16),255),t[e.InvJx(r,2)]=e[o(520)](l>>>8,255),t[r+3]=255&l,t[r+4]=x>>>24,t[e[o(1182)](r,5)]=e[o(1011)](x,16)&255,t[e[o(567)](r,6)]=e[o(1442)](x>>>8,255),t[e[o(1576)](r,7)]=e[o(520)](255,x),r+=8,r}function lr(s,t){let r=n,o={gCsgw:function(x,l,g,m){return e[T(907)](x,l,g,m)},xgvwo:e[r(939)],rxumR:function(x,l,g,m){return e.wWDSP(x,l,g,m)},DbDRs:e[r(677)],UrvYS:function(x,l,g){return e.KFrbg(x,l,g)},jAWda:e.zBoOE};if(e[r(619)](e[r(1150)],r(920))){let x=!!this[r(1447)][r(999)+"S"];if(!x)return{enabled:x,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=iLYZOq[r(1345)](_0x343e69,_0x2551ab[r(1284)][r(1119)],iLYZOq[r(1592)],"2"),g=l&&iLYZOq[r(919)](_0x5ba075,_0x36686e[r(1284)][r(1119)],iLYZOq[r(1132)],"1"),m=l&&iLYZOq.gCsgw(_0x58085f,_0x1d05f3[r(1284)][r(1119)],r(709)+r(1728)+"k","1"),f=m?iLYZOq[r(818)](_0x11c417,_0x5ac929[r(1284)].headers,iLYZOq.jAWda)?.[r(721)](",").filter(_0x456066)||[]:[];return{enabled:x,isQoSMessage:l,isQoSAck:g,isAckCleanupMessage:m,ackMsgIds:f}}else return s[r(1188)+"8"]?{value:s.readUInt8(t),offset:e[r(1148)](t,1)}:{value:e[r(699)](255,s[t]),offset:e.oBTUV(t,1)}}function hr(s,t,r){return t[n(1328)+"t8"]?t.writeUint8(s,r):t[r]=e.EJdVg(255,s),r+1}let Za=function(s){let t=n;if(e[t(1787)]===e[t(1787)])return new Uint8Array(s);e[t(1009)](_0x360d94,_0x3c0ec0,90),_0x2169b6(_0x5856bb,_0x578f86)},Qa=e[n(1523)](e[n(883)],typeof Buffer)?Buffer["allocUns"+n(1086)]:e.mHKMs(ja,Za,Uint8Array[n(1813)+"e"][n(1373)]);(()=>{let s=n,t={mKXSo:function(o,x){return e[T(1042)](o,x)},bWwkV:e[s(1407)],uTYgR:function(o,x){return o>>>x},ifHyv:function(o,x){return e[s(1131)](o,x)},jGNJk:function(o,x){return o<x},mBKDp:function(o,x){return e[s(1050)](o,x)},pVqtL:function(o,x){return e[s(1423)](o,x)},LqLiz:function(o,x){return e[s(605)](o,x)},BgWqL:function(o,x){return e[s(612)](o,x)},trBVP:function(o,x){return o|x},CRtVs:function(o,x){return o<x},OFajJ:function(o,x){return e[s(612)](o,x)},MjAxf:function(o,x){return e[s(1844)](o,x)},BNlra:function(o,x){return e[s(1258)](o,x)},XRPDk:function(o,x,l,g){return o(x,l,g)}},r=4294967295;return function(o,x,l=!0){let g=s;if(t.mKXSo(t[g(1855)],g(1261))){if(r=t[g(1825)](t.ifHyv(127,o[x]),0),t[g(913)](o[x++],128))return{value:l?r:t[g(1207)](0,r),offset:x};if(r=t[g(730)](t[g(1207)](r,t.LqLiz(127&o[x],7)),0),t.jGNJk(o[x++],128))return{value:l?r:t[g(1207)](0,r),offset:x};if(r=t[g(1770)](r|t[g(1106)](127,o[x])<<14,0),t[g(913)](o[x++],128))return{value:l?r:0|r,offset:x};if(r=t[g(754)](r,t.LqLiz(127&o[x],21))>>>0,t[g(1411)](o[x++],128))return{value:l?r:t[g(1207)](0,r),offset:x};if(r=t[g(1441)](t[g(1207)](r,t[g(1106)](15,o[x])<<28),0),t.MjAxf(o[x++],128))return{value:l?r:t[g(1207)](0,r),offset:x};if(t.BNlra(x+=5,o[g(1326)]))throw x=o[g(1326)],t[g(743)](Wa,x,10,o[g(1326)]);return{value:l?r:0|r,offset:x}}else++_0x49654e,_0x351314+=4}})();let e0=16,gr=32;function t0(s){let t=n,r={kMxGg:function(o,x,l,g){return e.uoPtI(o,x,l,g)},PFUPk:function(o,x,l){return o(x,l)}};if(e[t(1599)]===e[t(1452)])this[t(825)+t(1047)]=_0x557041,this[t(733)]=0;else{let o=0,x={};for(let l=0;e[t(1263)](l,s[t(1326)]);l++)if(e[t(1271)]!==t(1876))try{r[t(711)](_0x293a16,this,_0x1285ed,[_0x5c5866,_0x1002e7,_0x5e85d6])}catch(g){let m=r[t(815)](_0x401066,t(740),{message:g[t(1284)],code:_0x284e3d.OPEN_ERROR,error:g});this[t(1264)+"hErrorEv"+t(1756)](m)}else x[s[l].cursor_name]=e[t(707)](ks,s[l][t(469)+t(1195)]),o+=e[t(1140)](14,x[s[l][t(469)+t(1195)]]);return[o,x]}}function Ls(s,t,r){let o=n,x={iqoqi:function(v,b,k,A){return e[T(1359)](v,b,k,A)},bIRvo:e[o(1763)],NWARW:e.npmmj,pgATX:function(v,b,k,A){return e[o(708)](v,b,k,A)},kbTyi:e.vDMaf},[l,g]=e[o(1852)](t0,s),m=Qa(l),f=0;return s[o(1845)](v=>{let b=o,k=(b(1609)+"|9|7|3|1"+b(1562))[b(721)]("|"),A=0;for(;;){switch(k[A++]){case"0":console.log(b(1803),f);continue;case"1":f=x[b(871)](Xa,v[b(469)+b(1195)],m,f);continue;case"2":console[b(1746)](b(1347),f);continue;case"3":console.log(b(1647)+b(1281),f);continue;case"4":f=Ya(U.fromNumber(v.cursor||t),m,f);continue;case"5":console[b(1746)](x[b(1666)],f);continue;case"6":console.log(x[b(1191)],v,v[b(889)]);continue;case"7":f=x[b(871)](hr,g[v[b(469)+b(1195)]],m,f);continue;case"8":f=x[b(1827)](hr,0,m,f);continue;case"9":console[b(1746)](x[b(1057)],f);continue;case"10":f=Ja(m,f,v[b(889)]||0);continue}break}}),{frameType:gr,headers:[{key:e[o(820)],value:r}],payload:m}}function n0(s){let t=n,r={GMPNG:e[t(1574)]};if(e[t(1355)](e[t(1002)],e[t(1909)])){let o=this._options[t(922)+t(1684)+t(1834)](_0x32bd4c,_0x298351);this[t(1264)+"hCloseEv"+t(1756)](_0x228757(r[t(1374)],{code:_0x3e0659,reason:_0x5dfbf7,wasClean:!0,willReconnect:o})),o&&this[t(694)]()}else{let o=0,x=[];for(;e[t(1734)](o,s[t(940)+"th"]);){let{offset:l}=e[t(1517)](lr,s,o);o=l;let g={cursor_name:"",cursor:0,service:0},{value:m,offset:f}=e[t(1223)](Va,s,o);g.service=m,o=f;let{value:v,offset:b}=e[t(495)](lr,s,o);o=b,g["cursor_n"+t(1195)]=e[t(735)](Ps,s,o,o+v),o+=v;let{value:k,offset:A}=e.lzBnJ($a,s,o);g[t(1113)]=k[t(949)](),o=A,x[t(1414)](g)}return x}}function r0(){let s=n;return e[s(957)](e[s(606)],s(600))?{frameType:gr,headers:[{key:e[s(820)],value:e.voxjd}],payload:void 0}:_0x468d43?this[s(1671)+"E"]():this[s(1071)+"E"]()}class s0{constructor(t,r,o){let x=n;this[x(1272)+x(801)]=t,this["_cursorF"+x(1158)]=r,this[x(1059)+x(1916)]=o,this[x(603)]=e[x(648)](Is,this[x(1272)+x(801)],e[x(1891)])}async openDB(){let t=n;await this._qosDB[t(647)]()}async[n(1121)+"rs"](){let t=n;if(!this[t(603)][t(1053)])return;let r=this[t(1059)+t(1916)],o=await this._qosDB.getAll();switch(console[t(1746)]("allCursorValues",o),r){case e.oqnQf:return o&&o[t(1326)]?e.vKovs(Ls,o,0,this[t(1008)+t(1158)]):void 0;case e[t(1777)]:return;case e.uObmx:return o&&o[t(1326)]?e[t(1225)](Ls,o,0,this[t(1008)+t(1158)]):r0()}}async[n(1416)](t,r,o){let x=n;return console.log(e[x(1333)],t,r,o),this[x(603)][x(1416)]({cursor_name:t,cursor:r,service:o})}async[n(669)+"rs"](t){let r=n,o=e.FUPjq(n0,t);for(let x of o)console[r(1746)](r(1210)+"r",o),await this[r(603)][r(1416)](x)}async get(t){let r=n;return(await this._qosDB[r(1208)](t))?.cursor}async[n(778)](){let t=n;await this._qosDB[t(778)]()}["updateCu"+n(991)+"Name"](t){let r=n;this[r(1008)+r(1158)]=t}get[n(1053)](){let t=n;return this[t(603)][t(1053)]}}let i0=e[n(610)];async function Rs(s){let t=n;if(!this[t(1447)][t(999)+"S"])return null;let{aID:r,fpID:o,messageStrategy:x}=this[t(1447)],l=e[t(1462)](s,i0);try{return this[t(731)+t(1815)]?s&&this["_cursorM"+t(1815)][t(596)+"rsorFile"+t(775)](s):this["_cursorM"+t(1815)]=new s0(o+"_"+r+"_"+l,l,x),this[t(731)+"anager"][t(1053)]||await this._cursorManager.openDB(),this[t(731)+t(1815)]}catch{return e[t(1072)](e.oNYcB,t(591))?this[t(1899)]?this[t(1899)].protocol:"":null}}async function o0(s,t){let r=n,o=Fe(s[r(1284)][r(1119)],e[r(597)],"-1"),x=e[r(1359)](Fe,s.message[r(1119)],e[r(1894)],"1"),l=e[r(1778)](ot,s.message[r(1119)],r(709)+r(1832)),g=e.DJPsY(Number,e[r(1688)](ot,s[r(1284)][r(1119)],e.gXJuH))||0,m=fr.call(this,s),f=e[r(708)](Fe,s.message[r(1119)],e.LOCNV,"2"),v=e[r(1789)](ot,s[r(1284)][r(1119)],e.xxdVw),b=e[r(1883)](Number,e.uqHJD(ot,s[r(1284)][r(1119)],e.pcFmA));if(m[r(1369)])return t();let k=m["isQoSMes"+r(601)]?await Ts[r(1147)](this):null;if(e[r(1820)](s[r(1284)][r(889)],0)&&x&&!o||e[r(455)](s.message[r(889)],0)){if(l&&m[r(572)+r(601)]&&k)return!!!await k[r(1208)](l)&&(this["_dispatc"+r(1665)+r(1406)](s),await k[r(1416)](l,e[r(584)](Date.now(),g))),t();if(f){let A=await Rs.call(this);if(!A)return this[r(1264)+r(1665)+r(1406)](s),e[r(894)](t);let D=await A[r(1208)](v)??-1;if(e[r(1754)](D,b))this["_dispatc"+r(1665)+r(1406)](s),A[r(1416)](v,b,s.message[r(889)]);else throw new Error(r(764)+r(1656)+" cursor "+b+(r(942)+r(641)+r(1162)+"r ")+D);return t()}return this["_dispatchMessage"+r(1406)](s),e[r(932)](t)}}async function a0(s,t){let r=n,o=fr[r(1147)](this,s);if(!o[r(572)+r(601)])return e[r(1505)](t);let x=await Ts[r(1147)](this);if(o[r(1685)+r(1089)+"age"]&&o[r(1670)+"s"].length)for(let l of o.ackMsgIds)await x.del(l);t()}async function c0(s,t){let r=n,o={bUVqG:function(f,v){return e[T(1861)](f,v)},ExJuM:function(f,v){return e[T(1239)](f,v)}},x=s[r(1284)][r(1676)+"e"]===e0,l=e.hitsc(s[r(1284)][r(1676)+"e"],gr);if(e[r(1677)](!x,!l))return e[r(676)](t);let g=e[r(467)](ot,s[r(1284)][r(1119)],e.RDDjY);if(!g)return e.ryVmk(t);let m=await Rs.call(this,g);if(!m)return t();if(x){let f=await m[r(1121)+"rs"](),v={frameType:f?.["frameType"],SeqID:U[r(931)+"er"](this[r(983)]++),LogID:U.fromNumber(this[r(1447)][r(1859)+"erator"]()),service:9e3,method:5,headers:f?.[r(1119)],payload:f?.[r(992)]},b=C(v);this[r(1899)]&&this[r(1899)].readyState&&this[r(1899)][r(899)](b)}if(l)if(e.RiLLM===e.RiLLM){let f=s.message.payload;f&&m[r(669)+"rs"](f)}else _0x479cf0[_0x1a7a74++]=zfeike[r(779)](_0x23b79d>>6,192),_0x3f037e[_0x36420b++]=zfeike[r(823)](63,_0xba8314)|128}let x0=async function(s,t){let r=n;this._isInit=!1,e[r(734)](clearTimeout,this[r(694)+r(1612)+"utId"]),e.kkDVU(t)},u0=async function(s,t){let r=n;if(!this[r(1899)]||e[r(1063)](this._ws.readyState,this[r(516)]))return e[r(780)](t);let{pingInterval:o}=this[r(1447)];this[r(1668)+r(1802)]?.[r(867)+r(1911)+r(501)]();for(let l=0;l<this[r(1059)+r(1514)][r(1326)];l++)if(e[r(928)]!==r(570)){let g=this._qosDB[r(724)](this[r(1667)]),m=_0x230f9b[r(1111)](e[r(1303)](g,"{}"));return _0x39a74f[r(1460)](m)}else{let g=this["_message"+r(1514)][l];if(e[r(1314)](this._ws.readyState,this[r(516)])&&g!==null)this[r(1899)]&&this[r(1899)][r(899)](g),this[r(1059)+"Queue"][l]=null;else break}this[r(1059)+r(1514)]=this[r(1059)+r(1514)][r(822)](l=>!!l),this[r(797)+"gTimeoutId"]=e.PjxJu(setTimeout,()=>this[r(926)](),o),this["_dispatc"+r(1657)+"nt"](s),this[r(934)+"er"]&&this[r(1899)]&&(this._ws[r(1183)+"pe"]=this[r(1743)+r(1805)]);let x=this[r(1668)+r(1802)]?.["getCurre"+r(1004)+"nt"]();this[r(876)]("open "+x+r(910)),e[r(1829)](t)},d0=async function(s,t){let r=n,o=this["_endpoin"+r(1802)]?.[r(1087)+r(1004)+"nt"]();this[r(876)](r(1164)+o),e[r(1829)](t)};class f0 extends xr{constructor(t){let r=n,o={zVhRD:function(m,f){return e[T(1010)](m,f)},eYyAp:e[r(1422)],XJHbp:e[r(705)],grqQh:function(m,f,v){return e[r(1833)](m,f,v)},TJhtx:e[r(635)],SheCO:function(m,f,v){return e.ZKfKN(m,f,v)},YEXVu:function(m,f){return e.usRqC(m,f)},ngTZV:function(m,f){return e.CqZOI(m,f)},Xzqlp:function(m,f){return e[r(957)](m,f)},lZeAL:e[r(1034)],CFeoI:e[r(1574)],aPuJH:r(1016),fUFfR:function(m,f,v){return e[r(1435)](m,f,v)},nIbZe:function(m,f,v){return m(f,v)}};super(),this[r(542)+r(859)+r(1765)]=!0,this[r(934)+"er"]=it,this[r(804)]=Pa,this._isMiniTT=Xe,this[r(1711)+"X"]=At,this[r(620)+"r"]=kt,this[r(1059)+r(1514)]=[],this[r(1668)+r(1802)]=null,this[r(1118)+r(475)]=!1,this[r(1743)+"ype"]=e[r(791)],this["_connect"+r(741)]=!1,this[r(694)+r(1612)+"utId"]=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this[r(1202)]=!1,this[r(966)]="",this[r(703)+"ger"]=null,this[r(731)+r(1815)]=null,this["_pingLos"+r(1259)]=null,this[r(704)+"ls"]=e[r(840)],this.CLOSED=3,this[r(1007)+"NG"]=0,this.OPEN=1,this.CLOSING=2,this._onOpen=m=>{let f=r;try{e[f(907)](As,this,m,[x0,u0,d0])}catch(v){let b=e[f(964)](de,e[f(635)],{message:v[f(1284)],code:qe.OPEN_ERROR,error:v});this[f(1264)+f(1766)+"ent"](b)}},this[r(1045)+"ge"]=async m=>{let f=r,v={tpOLf:function(A,D,O){return A(D,O)},wZrPO:function(A,D){return e[T(573)](A,D)},FMpcl:function(A,D){return e.vLgss(A,D)},gkkGm:function(A,D){return e[T(671)](A,D)},iyrlx:function(A,D){return e[T(712)](A,D)}},{pingInterval:b,pingFrequency:k}=this[f(1447)];if((e[f(1064)]("hi",m[f(1401)])&&k==="always"||e[f(1806)](e[f(1026)],k))&&(this[f(479)+f(1445)](),this[f(1504)]("ping_onc"+f(1292)+"s",e[f(1500)]),this[f(797)+f(996)+"Id"]=e.zqbPD(setTimeout,this[f(926)][f(1695)](this),b)),!e[f(1874)]("hi",m.data))try{e[f(1279)](As,this,m,[Ka,Ua,a0,c0,o0,Ha])}catch(A){if(e[f(1636)](e[f(468)],"ippct"))_0x4e0818-=65536,_0x1a4190+=lGdQKR.tpOLf(_0x64bc13,lGdQKR[f(952)](lGdQKR[f(1774)](_0x2b64f1,10),55296),lGdQKR.gkkGm(lGdQKR.iyrlx(1023,_0x326fc7),56320)),_0x49b760+=3;else{let D=de(f(740),{message:A[f(1284)],code:qe[f(553)+f(508)],error:A});this["_dispatc"+f(1766)+f(1756)](D)}}},this[r(1454)]=m=>{let f=r;if(o[f(1558)](o[f(1287)],o.XJHbp))_0x132db6[f(1746)](_0x5cc9a9);else{let v=this[f(1668)+f(1802)]?.[f(879)+"chMaxTries"](),b=this._endpointManager?.[f(1087)+"ntEndpoint"]();if(v&&!m[f(1284)]){let k="connect "+b+(f(1127)+f(1439)+"es reached");this["_dispatc"+f(1766)+"ent"](o[f(1579)](de,o[f(604)],{message:k,code:qe["MAX_RETR"+f(659)+"R"],error:m}));return}this._ws&&o[f(1558)](this._ws.readyState,this.OPEN)&&this[f(1260)+f(622)](),this["_dispatc"+f(1766)+f(1756)](o[f(698)](de,o[f(604)],{message:m[f(1284)],code:qe[f(1524)+f(559)],error:m}))}},this[r(1575)]=async m=>{let f=r,v={jZUtw:function(b,k){return o[T(1464)](b,k)},QHfjo:function(b,k){return o[T(1e3)](b,k)}};if(o.Xzqlp(o[f(877)],f(1066)))return!!(this[f(663)+f(497)]>=this[f(1185)+"s"][f(1326)]||ovDWQf[f(1149)](this[f(663)+f(497)],ovDWQf.QHfjo(this[f(1185)+"s"][f(1326)],1))&&this[f(1854)+f(896)+f(1847)+"t"]===this.maxRetries);{this[f(783)+f(1354)](),this[f(479)+f(1445)](),this["_removeW"+f(1549)+"rs"](),this[f(1899)]=null,this[f(694)+f(741)]=!1;let b=this[f(1668)+f(1802)]?.[f(879)+f(1561)+"es"]();if(!b&&this[f(943)+f(1138)]()&&!this[f(1118)+"osed"]){let k=this["_endpoin"+f(1802)]?.[f(1087)+f(1004)+"nt"](),A=this[f(1447)][f(922)+f(1684)+f(1834)](m[f(1513)],m[f(1608)]);this[f(1264)+"hCloseEv"+f(1756)](o[f(698)](ge,f(1076),{code:1006,reason:m[f(1608)]||f(1501)+f(1117)+"d, unkno"+f(588)+f(1745)+f(953)+k,willReconnect:A})),A&&this[f(694)]();return}if(m[f(1513)]!==1e3&&this[f(1118)+f(475)]){this[f(1264)+f(767)+f(1756)](ge(o.CFeoI,{code:1e3,reason:f(1323)})),this[f(1668)+f(1802)]?.[f(867)+"pointCon"+f(501)](),this["_pingLos"+f(1259)]?.[f(1707)+f(1880)]();return}if(o[f(1699)](1e3,m[f(1513)])&&b){if(o.Xzqlp(f(1016),o[f(1331)]))return _0x229ee5[f(1192)]();{let k=this["_endpoin"+f(1802)]?.[f(1087)+f(1004)+"nt"](),A=m[f(1608)];A||(A=await Oa(this[f(966)])),A=f(1501)+f(1117)+f(1627)+A+(f(1530)+f(1889))+k+(f(1385)+f(1723)+f(1463)),this["_dispatc"+f(767)+"ent"](o.SheCO(ge,o[f(664)],{code:m.code,reason:A}));let D=f(762)+k+(f(1127)+f(1439)+f(745)+"ed");this[f(1264)+f(1766)+f(1756)](o[f(1013)](de,o[f(604)],{message:D,code:qe[f(1152)+"IES_ERROR"]})),this[f(1668)+"tManager"]?.[f(867)+f(1911)+f(501)](),this[f(1687)+"sCounter"]?.[f(1707)+"nter"]();return}}if(m[f(1513)]!==1e3&&!m.reason){let k=this[f(1668)+"tManager"]?.[f(1087)+f(1004)+"nt"]();this["_dispatc"+f(767)+f(1756)](o.nIbZe(ge,o[f(664)],{code:m[f(1513)],reason:f(1501)+"ng failed, unkno"+f(588)+"n, hostn"+f(953)+k})),this[f(1668)+f(1802)]?.[f(867)+f(1911)+"fig"](),this[f(1687)+f(1259)]?.[f(1707)+f(1880)]();return}this["_dispatc"+f(767)+f(1756)](m),this["_endpoin"+f(1802)]?.[f(867)+f(1911)+f(501)](),this["_pingLos"+f(1259)]?.[f(1707)+f(1880)]()}},this[r(1125)]=null,this[r(1692)]=null,this[r(1720)+"e"]=null,this.onopen=null,this[r(1603)+r(1455)]=null,this["onReceiv"+r(1410)]=null,this[r(937)+r(753)+r(1427)+"ct"]=null,this[r(1222)+r(1054)]=this._handleOnLine[r(1695)](this),this[r(1222)+"ffLine"]=this[r(1222)+"ffLine"][r(1695)](this),this[r(1493)+"ageHide"]=this[r(1493)+r(716)][r(1695)](this),this["_handleP"+r(564)]=this["_handleP"+r(564)][r(1695)](this),this[r(1447)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[r(1598)](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.bTcAl,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[r(1867)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:x,ws:l}=t,g=Array[r(1835)](x)?x:e[r(1546)]==typeof x?[x]:[];if(!g||e[r(1065)](0,g[r(1326)]))throw new Error(e[r(1509)]);if(!e[r(639)](Ta,l))throw new Error(e.wqbfs);Object[r(577)](this._options,t),this[r(1668)+r(1802)]=new Cs(g,this[r(1447)][r(882)+"es"]),this[r(1687)+r(1259)]=new Na(this[r(1447)][r(958)+r(1648)]),this[r(1447)][r(461)+"cOpen"]&&(this._isInit=!0,this[r(694)]()),this[r(1447)]["listenNetworkCha"+r(1180)]&&(this._isMiniTT||this[r(1711)+"X"]?this[r(1640)+r(513)+r(1426)]():this[r(934)+"er"]&&this[r(1568)+"balEvent"+r(1130)]())}["_handleO"+n(1054)](){let t=n;this[t(1447)][t(1519)+t(695)+t(1388)]||this[t(1118)+"osed"]||this[t(1471)+t(1455)]()}["_handleO"+n(574)](){let t=n;if(e[t(587)](e[t(463)],t(1022))){let r=this[t(1668)+t(1802)]?.[t(1087)+"ntEndpoint"](),o=this[t(1447)][t(922)+t(1684)+t(1834)](_0x2e8405.code,_0x41afdf[t(1608)]);this[t(1264)+"hCloseEv"+t(1756)](e[t(495)](_0x5b7aeb,t(1076),{code:1006,reason:_0x47ea1e[t(1608)]||t(1501)+"ng faile"+t(528)+t(588)+t(1745)+"ame: "+r,willReconnect:o})),o&&this[t(694)]();return}else{this[t(1528)+t(1247)+"t"]();let r=cr(e[t(1518)],{message:e.znMqe});this["onStopIm"+t(753)+"yReconnect"]&&this[t(937)+t(753)+"yReconnect"](r)}}[n(1568)+n(971)+n(1130)](){let t=n,r={Abxmm:function(o,x){return o(x)},LRLIk:function(o,x){return o<<x},KpPCB:function(o,x){return e[T(897)](o,x)},nvHhO:function(o,x){return e[T(514)](o,x)}};if(e[t(1081)](e.MedzT,e[t(750)])){let o=0,x=0,l;do l=RwHqvT.Abxmm(_0x5c15dd,_0x8c77e1),o<32&&(x|=RwHqvT[t(946)](RwHqvT[t(1396)](127,l),o)),o+=7;while(RwHqvT[t(763)](128,l));return x}else this[t(934)+"er"]&&window["addEvent"+t(1130)](t(744),this[t(1222)+"nLine"]),this._isBrowser&&window[t(1485)+t(1130)](e.QlYSs,this["_handleO"+t(574)]),this._isBrowser&&window[t(1485)+"Listener"](e[t(510)],this["_handleP"+t(716)]),this._isBrowser&&window[t(1485)+"Listener"](e[t(550)],this[t(1493)+t(564)])}[n(1171)+n(971)+n(1130)](){let t=n;this[t(934)+"er"]&&window[t(1590)+t(1366)+t(866)](e[t(1790)],this._handleOnLine),this[t(934)+"er"]&&window[t(1590)+t(1366)+t(866)](e[t(1680)],this[t(1222)+"ffLine"]),this[t(934)+"er"]&&window[t(1590)+t(1366)+t(866)](e[t(510)],this["_handleP"+t(716)]),this[t(934)+"er"]&&window["removeEv"+t(1366)+t(866)](e[t(550)],this[t(1493)+t(564)])}[n(1493)+n(716)](t){let r=n,o={dubwX:function(x,l){return x===l}};if(!t.persisted){if(e.TWhcm(e[r(1759)],e.HiWdp))return _0x87219&&gZoSzC.dubwX(!0,_0x102038[r(1335)]);this[r(934)+"er"]&&window["removeEventListe"+r(866)](r(1482),this[r(1493)+r(716)]),this[r(934)+"er"]&&window[r(1590)+r(1366)+r(866)](e.AnmXX,this[r(1493)+r(564)]),this[r(1076)]()}this[r(934)+"er"]&&window[r(1590)+r(1366)+"ner"](e[r(1790)],this[r(1222)+r(1054)]),this[r(934)+"er"]&&window[r(1590)+r(1366)+r(866)](r(903),this[r(1222)+r(574)])}[n(1493)+n(564)](t){let r=n,o={SpSKt:"4|2|0|3|1"};if(e[r(1314)](e.DXEda,e[r(811)]))t.persisted&&(this["_navigat"+r(1138)]()&&(!this[r(1899)]||this[r(1899)].readyState!==this[r(516)]||e[r(1079)](this._ws[r(1510)+"te"],this[r(1007)+"NG"]))&&this[r(1222)+r(1054)](),this._isBrowser&&window[r(1485)+r(1130)](e[r(1790)],this[r(1222)+r(1054)]),this[r(934)+"er"]&&window[r(1485)+r(1130)](e[r(1680)],this[r(1222)+r(574)]));else if(!this[r(694)+"Lock"]){let x=o[r(1737)][r(721)]("|"),l=0;for(;;){switch(x[l++]){case"0":this[r(1118)+r(475)]=!1;continue;case"1":this[r(694)]();continue;case"2":this[r(1687)+r(1259)]?.[r(1707)+r(1880)]();continue;case"3":this[r(1202)]=!0;continue;case"4":this._endpointManager?.[r(867)+r(1911)+"fig"]();continue}break}}}async[n(771)+n(921)](t){let r=n,{fpID:o,deviceID:x,bddID:l,ttwID:g,accessKey:m,aID:f,customParams:v={},enableAutoAck:b,enableQoS:k,QoSLevel:A,env:D}=this[r(1447)],O,B,be;this._isBrowser||this[r(1711)+"X"]||this[r(1318)+"T"]?(O=location&&e[r(1839)](e.eMLLA,location[r(1701)])?e[r(1070)]:e[r(868)],B=t.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),be=/^wss(.*:\/\/)/[r(660)](t)?t:""+O+B):(O=e[r(1070)],B=t.replace(/(^http)((?:[s]*:\/\/))/,""),be=/(^ws)((?:[s]*:\/\/))/[r(660)](B)?B:""+O+B);let $t=l?e[r(583)]:g?e[r(1767)]:e[r(749)],Ns=l||g||x;if(e[r(1303)](!Ns,!$t))throw new Error(r(747)+r(1812)+"ddID, de"+r(1251)+"r ttwID");let l0=e[r(1839)](e[r(1083)],typeof v)?await e[r(1297)](v):v,h0=D?e.hKNqV(Ra,D[r(458)],D[r(1091)]):{},pr=Object[r(577)]({device_platform:r(1543),version_code:e.xYyvT,access_key:m,fpid:o,aid:f,[$t]:Ns,xsack:b?1:0,xaack:b?1:0,xsqos:k?1:0,qos_level:k?A:void 0,qos_sdk_version:2,...h0},l0),g0=Object.keys(pr)[r(1446)]((mr,wr)=>pr[wr]!==void 0?""+mr+(mr?"&":"?")+wr+"="+pr[wr]:mr,"");return be+r(1624)+g0}async[n(694)](){let t=n;if(!(this["_connect"+t(741)]||this["_readyCl"+t(475)])){this["_connect"+t(741)]=!0;try{let r=this[t(1668)+t(1802)]?.["checkCurrentEndp"+t(575)+t(1135)+t(1552)](),{timeoutInterval:o}=this[t(1447)];if(r){let l=this[t(1668)+t(1802)]?.[t(1087)+t(1004)+"nt"](),g=this[t(1668)+t(1802)]?.[t(1377)+t(701)+t(1589)+t(1037)+"unt"](),m=this[t(1668)+"tManager"]?.["getCurre"+t(1004)+t(1217)+t(1047)]();if(g){let f=t(762)+l+(t(1502)+", max re"+t(1723)+t(1551)+t(1370)+t(836)+t(1520))+g+(t(476)+"y"),v=e.BpNEk(de,e[t(635)],{message:f,code:qe[t(1152)+t(659)+"R"]});this[t(876)](f),this[t(1264)+t(1766)+"ent"](v),this[t(966)]=await this[t(771)+t(921)](g),this._debug("connect "+g+" "+m+t(732)),this[t(1690)+t(1549)+"rs"]()}else{let f=t(762)+l+(t(1502)+", max re"+t(1723)+"ached");this[t(876)](f),this[t(1264)+t(1766)+t(1756)](e[t(964)](de,e[t(635)],{message:f,code:qe["MAX_RETR"+t(659)+"R"]}));return}}else{let l=this[t(1668)+t(1802)]?.["getCurrentEndpointAndUpd"+t(1722)](),g=this[t(1668)+"tManager"]?.[t(1087)+t(1004)+t(1217)+t(1047)]();this[t(966)]=await this["_generat"+t(921)](e.zXARR(l,"")),this[t(876)](t(762)+l+" "+g+t(732)),this._removeWsListeners()}if(this[t(1202)])this[t(1202)]=!1;else{let l=e[t(1189)](cr,e[t(1518)],{message:e.KKObW});this[t(1603)+t(1455)]&&this[t(1603)+"econnect"](l)}let x=this[t(1668)+t(1802)]?.[t(1087)+"ntEndpointTriesC"+t(1047)]()||0;e[t(1124)](x,1)&&await this[t(1001)](e[t(888)](x,1)),this[t(876)](t(1501)+t(1494)+this[t(966)]+(" protoco"+t(595))+this[t(704)+"ls"]),this._ws=e[t(1402)](Ia,{url:this[t(966)],protocols:[this._protocols],headers:this[t(1447)]["miniProg"+t(1729)+"s"].customHttpHeader},this[t(1447)].ws),(this[t(934)+"er"]||this[t(620)+"r"])&&this[t(1899)]&&(this[t(1899)][t(1183)+"pe"]=this[t(1743)+t(1805)]),this[t(565)+t(549)](),this[t(694)+"ionTimeo"+t(1145)]=e[t(1009)](setTimeout,this._onTimeout[t(1695)](this),o)}catch(r){if(e[t(1653)](e[t(1512)],e.fkHpQ))_0x50f79f&&this["_cursorM"+t(1815)]["updateCursorFile"+t(775)](_0x50449d);else throw this[t(694)+t(741)]=!1,r}}}_clearTimer(){let t=n;e[t(546)](clearTimeout,this[t(694)+t(1612)+"utId"]),this["_connect"+t(1612)+"utId"]=null}["_clearPi"+n(1445)](){let t=n;e[t(1883)](clearTimeout,this[t(797)+"gTimeoutId"]),e.OVqOz(clearTimeout,this[t(1584)+t(686)+t(1293)]),this[t(797)+t(996)+"Id"]=null,this["_reconne"+t(686)+"tId"]=null}[n(876)](...t){let r=n;this._options.debug&&console[r(1746)][r(1163)](console,[e[r(710)],...t])}[n(810)+n(1535)+"e"](t){let r=n,{initReconnectInterval:o,maxReconnectInterval:x,reconnectIntervalGrowFactor:l}=this[r(1447)],g=e[r(673)](o,Math[r(1233)](l,e.CqZOI(t,1)));return e[r(455)](g,x)?x:g}[n(926)](){let t=n,r={ZsLzS:function(o,x){return e[T(1249)](o,x)}};if(e.vlxGw(e[t(981)],e.wfDlN)){if(this[t(1899)]&&e[t(1782)](this._ws[t(1510)+"te"],this.CONNECTING)){this[t(479)+t(1445)](),this["_pingPon"+t(996)+"Id"]=e[t(1316)](setTimeout,this[t(926)][t(1695)](this),this._options[t(845)+"rval"]);return}if(!this[t(1899)]||e[t(1429)](this[t(1899)][t(1510)+"te"],this.OPEN))return void this[t(1471)+"econnect"]();this[t(1899)]&&this[t(1899)][t(899)]("hi"),this[t(1584)+t(686)+t(1293)]=e[t(1358)](setTimeout,this["_handleReconnect"+t(756)][t(1695)](this),this[t(1447)][t(1744)+"outInter"+t(1819)])}else return bFROKW.ZsLzS(_0x50e8e4,_0x2d8401)}["_handleR"+n(1455)+n(756)](){let t=n;this[t(1687)+t(1259)]?.addCount(),this[t(1504)](t(608)+t(1451)+"t",e[t(1088)]),this["_pingLos"+t(1259)]?.[t(879)+t(1495)+"nt"]()?this[t(1471)+t(1455)]():this._ping()}["_navigat"+n(1138)](){let t=n;if(e[t(1557)]===e[t(1557)])return this._isMiniTT||this[t(1711)+"X"]?this[t(542)+t(859)+"line"]:(this[t(934)+"er"]||this._isWorker)&&this._options[t(1321)+t(1052)+"nged"]?navigator[t(719)]:!0;try{return!!this[t(603)]}catch(r){return _0x50584e[t(1746)](r),!1}}[n(1471)+n(1455)](){let t=n;!this[t(943)+t(1138)]()||this["_readyCl"+t(475)]||(this[t(1668)+t(1802)]?.[t(867)+t(1911)+t(501)](),this[t(1687)+t(1259)]?.[t(1707)+"nter"](),this._ws?this["_disconn"+t(622)](1001,e[t(969)],!0):this[t(694)]())}[n(1640)+"etWorkCh"+n(1426)](){let t=n,r={lYcMU:function(o,x){return o===x},kfdNh:e[t(944)]};this[t(1318)+"T"]?tt[t(1732)+t(1270)+t(881)](({isConnected:o})=>{let x=t;r[x(770)](r.kfdNh,r[x(865)])?(this[x(542)+x(859)+x(1765)]=o,o?this[x(1222)+x(1054)]():this[x(1222)+x(574)]()):this.on(_0x40c43f,_0x55f20e)}):this[t(1711)+"X"]&&wx[t(1732)+t(1270)+t(881)](({isConnected:o})=>{let x=t;this[x(542)+x(859)+x(1765)]=o,o?this[x(1222)+x(1054)]():this[x(1222)+x(574)]()})}[n(1001)](t){return new Promise(r=>{let o=T;e[o(742)](setTimeout,r,this[o(810)+o(1535)+"e"](t))})}[n(1260)+"ect"](t=1e3,r="",o=!1){let x=n;if(e.uNsNk(e[x(803)],e[x(970)]))_0x2c0b1f+=_0x5bac99(_0x2d3bbd),_0x34f21d+=2;else{if(!this[x(1899)])return;this[x(1528)+x(1247)+"t"](t,r,o)}}_onTimeout(){let t=n,r=this[t(1668)+t(1802)]?.[t(1087)+"ntEndpoint"]();this[t(876)](t(762)+r+t(1502)),this["_disconn"+t(622)](1001,t(1457)+t(792)+t(1540)+"g",!0)}[n(726)](t){let r=n,o=e[r(1852)](ar,t);this[r(1899)]&&e[r(1380)](this[r(1899)].readyState,this[r(516)])&&(this[r(1899)]&&this[r(1899)][r(899)](o),this[r(876)]("send_ack",t))}[n(1690)+n(1549)+"rs"](){let t=n;this[t(1899)]&&(this._ws["removeEv"+t(1366)+t(866)](t(1515),this[t(1905)]),this[t(1899)][t(1590)+t(1366)+t(866)](e[t(1574)],this[t(1575)]),this[t(1899)][t(1590)+t(1366)+t(866)](e[t(1283)],this[t(1045)+"ge"]),this[t(1899)][t(1590)+"entListener"](t(740),this[t(1454)]))}[n(565)+"steners"](){let t=n,r=e.JNIaV.split("|"),o=0;for(;;){switch(r[o++]){case"0":if(!this._ws)return;continue;case"1":this._ws[t(1485)+t(1130)](e[t(635)],this[t(1454)]);continue;case"2":this[t(1899)][t(1485)+t(1130)](e.tXlAp,this[t(1045)+"ge"]);continue;case"3":this._ws[t(1485)+t(1130)]("open",this[t(1905)]);continue;case"4":this[t(1899)]["addEvent"+t(1130)](t(1076),this[t(1575)]);continue}break}}[n(1141)+n(1567)](t=1e3,r=""){let o=n;try{this[o(1899)]&&this[o(1899)].close(t,r)}catch{}}[n(1528)+n(1247)+"t"](t=1e3,r="",o=!1){let x=n;if(this["_clearPi"+x(1445)](),this[x(783)+x(1354)](),this[x(1690)+x(1549)+"rs"](),this["_wsInsta"+x(1567)](1e3,r),this[x(694)+x(741)]=!1,o&&this[x(943)+x(1138)]()&&!this["_readyCl"+x(475)])if(e[x(1063)](e[x(858)],"yenUs")){if(this[x(1668)+x(1802)]?.checkReachMaxTries()){let g=this[x(1668)+x(1802)]?.["getCurre"+x(1004)+"nt"]();this[x(1264)+x(767)+x(1756)](e.pNXZm(ge,e.csqFZ,{code:1006,reason:x(762)+g+(x(1502)+", max re"+x(1723)+x(1463)),wasClean:!0}))}else{let g=this[x(1447)][x(922)+"tInterce"+x(1834)](t,r);this[x(1264)+x(767)+x(1756)](e[x(521)](ge,e.csqFZ,{code:t,reason:r,wasClean:!0,willReconnect:g})),g&&this[x(694)]()}return}else{let l=e[x(1367)][x(721)]("|"),g=0;for(;;){switch(l[g++]){case"0":_0xcaecc5=e[x(509)](65536+(e[x(1642)](1023,_0x43f2a5)<<10),1023&_0x16928a);continue;case"1":_0x544ce7[_0x55af5b++]=e[x(1184)](e[x(777)](_0x3a5adc,6)&63,128);continue;case"2":_0x24ac5a[_0x41c5cc++]=e[x(1254)](e.KwCPo(e.gUIvS(_0x3d67b3,12),63),128);continue;case"3":_0x5a8447[_0x13c671++]=e.qGhzx(63,_0x1d829)|128;continue;case"4":++_0x37ab28;continue;case"5":_0x511848[_0x4604d8++]=e[x(1275)](_0x383d4c>>18,240);continue}break}}this[x(943)+x(1138)]()||this[x(1118)+x(475)]?this["_dispatc"+x(767)+"ent"](e.kupEo(ge,e[x(1574)],{code:t,reason:e[x(1912)]})):this[x(1264)+x(767)+x(1756)](ge(x(1076),{code:1006,reason:e[x(1682)]})),this[x(1899)]=null,this["_endpoin"+x(1802)]?.["resetEnd"+x(1911)+x(501)](),this[x(1687)+x(1259)]?.[x(1707)+x(1880)]()}[n(1264)+n(1657)+"nt"](t){let r=n;if(e[r(927)](e.Fhthb,e.Fhthb))return _0x375fa2&&(_0x52ebaa=(0,_0x52afb4[_0x49dd3c(_0x4ffbba)[0]])(_0x148d0e=0)),_0x35cb69;this[r(1504)](r(1515),t),this[r(1655)]&&this[r(1655)](t)}[n(1264)+n(1665)+n(1406)](t){let r=n;this.emit(e[r(1283)],t),this[r(1720)+"e"]&&this.onmessage(t)}[n(1264)+n(1109)+n(1474)](t){let r=n;this[r(1504)](e[r(1641)],t),this[r(1181)+r(1410)]&&this[r(1181)+r(1410)](t)}[n(1264)+n(1766)+n(1756)](t){let r=n;this[r(1504)](e[r(635)],t),this[r(1692)]&&this[r(1692)](t)}["_dispatchCloseEv"+n(1756)](t){let r=n;this.emit(e[r(1574)],t),this.onclose&&this[r(1125)](t)}get binaryType(){let t=n;return this[t(1899)]?this[t(1899)][t(1183)+"pe"]:this[t(1743)+t(1805)]}set[n(1183)+"pe"](t){let r=n;if(e[r(1466)](e[r(1906)],e[r(1906)]))this[r(1743)+"ype"]=t,this[r(1899)]&&(this[r(1899)][r(1183)+"pe"]=t);else{if(!this[r(1899)])return;this[r(1899)][r(1590)+r(1366)+r(866)](r(1515),this[r(1905)]),this[r(1899)][r(1590)+"entListe"+r(866)](e[r(1574)],this[r(1575)]),this[r(1899)]["removeEv"+r(1366)+r(866)](e.tXlAp,this[r(1045)+"ge"]),this[r(1899)][r(1590)+r(1366)+r(866)](e[r(635)],this[r(1454)])}}get[n(1012)+"nt"](){let t=n;return this[t(1668)+t(1802)]?.[t(1087)+t(1004)+"ntTriesC"+t(1047)]()||0}get[n(1356)+n(649)](){let t=n,r=this[t(1059)+t(1514)][t(1446)]((o,x)=>(o+=x&&x[t(940)+"th"]||0,o),0);return e[t(1784)](r,this._ws?this[t(1899)][t(1356)+t(649)]:0)}get[n(1215)+"ns"](){let t=n;return this[t(1899)]?this[t(1899)][t(1215)+"ns"]:""}get[n(1701)](){let t=n;return this._ws?this[t(1899)].protocol:""}get[n(1510)+"te"](){let t=n,r={mLfnZ:function(o,x){return e[T(912)](o,x)}};if(e[t(1472)]===e[t(1583)]){let o=this[t(603)][t(724)](this[t(1667)]),x=_0xe35051.parse(TfPxQT.mLfnZ(o,"{}"));return x[_0xc39264||_0x4e1365[this[t(1005)]]]=_0x3b5eb4,this[t(603)][t(1634)](this[t(1667)],_0x3a0fbf.stringify(x)),_0x3a2c09||_0x182ea3[this[t(1005)]]}else return this[t(1899)]?this[t(1899)][t(1510)+"te"]:this[t(1447)][t(461)+"cOpen"]?this[t(1007)+"NG"]:this[t(485)]}get[n(752)](){let t=n;return this[t(1899)]?this[t(1899)][t(752)]:this._url}[n(1076)](t=1e3,r){let o=n,x=e[o(684)][o(721)]("|"),l=0;for(;;){switch(x[l++]){case"0":this[o(703)+"ger"]?.closeDB();continue;case"1":if(!this[o(1899)])return void this[o(876)](o(1545)+o(462)+"ce not i"+o(556)+"ed");continue;case"2":this[o(783)+o(1354)]();continue;case"3":this[o(479)+"ngTimer"]();continue;case"4":this[o(1171)+o(971)+"Listener"]();continue;case"5":if(this[o(1899)][o(1510)+"te"]===this[o(485)]||e[o(1914)](this[o(1899)][o(1510)+"te"],this[o(1461)]))return void this._debug(e[o(1521)]);continue;case"6":this[o(1118)+o(475)]=!0;continue;case"7":this[o(1528)+"WebSocket"](t,r);continue}break}}async[n(899)](t,r){let o=n;if(e[o(1449)](e[o(533)],e[o(657)])){if(t==null)throw new Error(e.QBrTP);e[o(1253)]==typeof t&&(t=JSON[o(1675)+"y"](t)),e[o(1546)]!=typeof t&&!e[o(1534)](t,ArrayBuffer)&&!(t[o(1078)]&&e[o(1555)](t[o(1078)],ArrayBuffer))&&(t=JSON[o(1675)+"y"](t));let x=await e.EBmKg(Ds,t),l=e.DIGzx(La,t),{method:g=0,service:m=this[o(1447)][o(889)],logID:f=this[o(1447)]["logIDGen"+o(687)](),headers:v=this[o(1447)].headers,payloadEncoding:b=this._options.payloadEncoding,payloadType:k=this[o(1447)]["payloadT"+o(1805)],logIDNew:A=this[o(1447)][o(906)+o(1800)][o(1901)+o(1882)+o(1890)+"ew"]?e[o(736)](a,this[o(1447)][o(906)+"Config"][o(1068)]):""}=r||{};if(!m)throw new Error(e.pJRhg);let D={SeqID:U[o(931)+"er"](this[o(983)]++),LogID:U[o(931)+"er"](f),service:m,method:g,headers:v,payloadEncoding:e.qxOhf(b,Object)?b[o(1816)]?b[o(1816)]:"":b,payloadType:e.PVVUF(k,Object)?k.type?k[o(557)]:l:k||l,payload:x,LogIDNew:A},O=e[o(1566)](ar,D);return this[o(1899)]&&e.pTbfP(this[o(1899)][o(1510)+"te"],this.OPEN)?(this[o(1899)]&&this[o(1899)].send(O),this[o(876)](e[o(702)],D)):e[o(1421)](this[o(1059)+o(1514)][o(1326)],this[o(1447)][o(1498)+o(1465)+o(1673)])?(this._messageQueue[o(1414)](O),this._debug(e[o(1799)],D)):(this[o(1059)+o(1514)].shift(),this[o(1059)+o(1514)][o(1414)](O)),{seqID:this._seqId,logID:f,logIDNew:A}}else this[o(782)]=_0x25c99e,this[o(1005)]=_0x3d7354,this[o(603)]=_0x4bd39e}async[n(922)+"t"](t){let r=n,{url:o}=e.kVUpB(t,{}),x=Array[r(1835)](o)?o:e.dLEGu(e[r(1546)],typeof o)?[o]:[];t&&Object[r(577)](this[r(1447)],t),x&&x[r(1326)]?this[r(1668)+r(1802)]=new Cs(x,this[r(1447)].maxRetries):this[r(1668)+r(1802)]?.[r(867)+r(1911)+r(501)](),this._pingLossCounter?.[r(1707)+r(1880)](this._options[r(958)+r(1648)]),this["_readyCl"+r(475)]=!1,this[r(1899)]&&this[r(1899)][r(1510)+"te"]!==this[r(485)]?this[r(1260)+"ect"](1e3,e[r(1605)],!0):(this._isInit=!0,this._connect())}async[n(884)](){let t=n;if(!this[t(694)+t(741)]){let r=e[t(1151)][t(721)]("|"),o=0;for(;;){switch(r[o++]){case"0":this["_pingLos"+t(1259)]?.[t(1707)+t(1880)]();continue;case"1":this._connect();continue;case"2":this[t(1202)]=!0;continue;case"3":this[t(1668)+t(1802)]?.["resetEnd"+t(1911)+t(501)]();continue;case"4":this["_readyCl"+t(475)]=!1;continue}break}}}[n(1485)+"Listener"](t,r){let o=n;e[o(1213)](e[o(985)],e[o(1678)])?(this[o(542)+"igatorOn"+o(1765)]=_0x3c80af,_0x51f2a6?this[o(1222)+"nLine"]():this[o(1222)+"ffLine"]()):this.on(t,r)}[n(1741)+n(1406)](t){let r=n,{type:o}=t;this[r(1504)](o,t)}["removeEv"+n(1366)+n(866)](t,r){let o=n;if(o(1531)===e[o(1224)])return new _0x2aa3de(_0x297a53,_0x49615b,_0x55b45a);this[o(678)](t,r)}[n(1764)](){let t=n,r={Vwakp:function(o,x){return e[T(499)](o,x)},WJzHR:e[t(746)],PeLWe:e[t(681)],TsdeH:e.cmxmk,cMJZm:e[t(1444)],gUrTR:function(o,x){return e[t(675)](o,x)},UOrBv:e[t(1088)],ytdzM:e[t(1572)]};return new Promise((o,x)=>{let l=t;this[l(479)+l(1445)](),this[l(797)+l(996)+"Id"]=setTimeout(this[l(926)][l(1695)](this),this[l(1447)][l(845)+l(1372)]);let g=()=>{let f=l,v={znUjv:function(b,k){return b>k},LoTmf:function(b,k){return r[T(786)](b,k)},rUlMe:r[f(460)]};if(f(1683)!==r.PeLWe){if(fOaajW[f(1881)](fOaajW[f(1375)](_0x4b7a7c[f(1488)],_0x4d6f36),_0x51c6a8[f(961)]))throw new _0x1c670b(fOaajW[f(1458)]);_0x4da488.offset+=_0x2d4128}else o(r[f(930)]),this[f(678)](r[f(483)],g),this[f(678)]("ping_onc"+f(1451)+"t",m)},m=()=>{let f=l;r.gUrTR(x,r[f(611)]),this[f(678)](r.cMJZm,g),this.off(r.ytdzM,m)};this.on(r[l(483)],g),this.on("ping_onc"+l(1451)+"t",m),this[l(926)]()})}}})(),Y[S(667)+"oseEvent"]=$[S(667)+S(1508)],Y[S(950)+"rorEvent"]=$[S(950)+S(1348)],Y[S(904)+"e"]=$.ErrorCode,Y[S(1406)]=$[S(1406)],Y[S(1550)]=$[S(1550)],Y[S(955)+S(1903)+S(1645)]=$[S(955)+S(1903)+S(1645)],Y["MessageE"+S(1645)]=$["MessageE"+S(1645)],Y[S(517)+"t"]=$.OpenEvent,Y[S(563)+S(812)]=$["Reconnec"+S(812)],Y[S(1062)+"oseEvent"]=$[S(1062)+S(1508)],Y["createEr"+S(1348)]=$[S(655)+S(1348)],Y[S(951)+S(1160)+"nt"]=$[S(951)+S(1160)+"nt"],Y["createOp"+S(1564)]=$[S(1856)+S(1564)],Y[S(1419)+S(1679)+S(1645)]=$[S(1419)+S(1679)+S(1645)],Y[S(1381)+S(1702)]=$[S(1381)+S(1702)],Y[S(1870)+S(1195)]=$[S(1870)+S(1195)];for(In in $)[S(667)+S(1508),S(950)+S(1348),S(904)+"e","Event",S(1550),S(955)+S(1903)+"vent",S(1903)+S(1645),S(517)+"t",S(563)+S(812),S(1062)+S(1508),S(655)+S(1348),"createMessageEvent",S(1856)+S(1564),S(1419)+"connectEvent","decodedFrame",S(1870)+"ame"][S(1129)](In)===-1&&(Y[In]=$[In]);var In;Object[S(1197)+S(1541)](Y,S(806)+"le",{value:!0})});var Ne=oe((Qh,Xi)=>{"use strict";var Ji=["nodebuffer","arraybuffer","fragments"],Vi=typeof Blob<"u";Vi&&Ji.push("blob");Xi.exports={BINARY_TYPES:Ji,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Vi,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qt=oe((eg,Mn)=>{"use strict";var{EMPTY_BUFFER:Lx}=Ne(),Lr=Buffer[Symbol.species];function Rx(n,e){if(n.length===0)return Lx;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 Lr(i.buffer,i.byteOffset,a):i}function $i(n,e,i,a,c){for(let u=0;u<c;u++)i[a+u]=n[u]^e[u&3]}function Yi(n,e){for(let i=0;i<n.length;i++)n[i]^=e[i&3]}function Nx(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Rr(n){if(Rr.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Lr(n):ArrayBuffer.isView(n)?e=new Lr(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Rr.readOnly=!1),e}Mn.exports={concat:Rx,mask:$i,toArrayBuffer:Nx,toBuffer:Rr,unmask:Yi};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=X("bufferutil");Mn.exports.mask=function(e,i,a,c,u){u<48?$i(e,i,a,c,u):n.mask(e,i,a,c,u)},Mn.exports.unmask=function(e,i){e.length<32?Yi(e,i):n.unmask(e,i)}}catch{}});var eo=oe((tg,Qi)=>{"use strict";var Zi=Symbol("kDone"),Nr=Symbol("kRun"),Or=class{constructor(e){this[Zi]=()=>{this.pending--,this[Nr]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Nr]()}[Nr](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Zi])}}};Qi.exports=Or});var mt=oe((ng,so)=>{"use strict";var Ft=X("zlib"),to=qt(),Ox=eo(),{kStatusCode:no}=Ne(),Bx=Buffer[Symbol.species],Mx=Buffer.from([0,0,255,255]),qn=Symbol("permessage-deflate"),Oe=Symbol("total-length"),gt=Symbol("callback"),Ge=Symbol("buffers"),pt=Symbol("error"),zn,Br=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!zn){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zn=new Ox(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[gt];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){zn.add(c=>{this._decompress(e,i,(u,d)=>{c(),a(u,d)})})}compress(e,i,a){zn.add(c=>{this._compress(e,i,(u,d)=>{c(),a(u,d)})})}_decompress(e,i,a){let c=this._isServer?"client":"server";if(!this._inflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Ft.Z_DEFAULT_WINDOWBITS:this.params[u];this._inflate=Ft.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[qn]=this,this._inflate[Oe]=0,this._inflate[Ge]=[],this._inflate.on("error",qx),this._inflate.on("data",ro)}this._inflate[gt]=a,this._inflate.write(e),i&&this._inflate.write(Mx),this._inflate.flush(()=>{let u=this._inflate[pt];if(u){this._inflate.close(),this._inflate=null,a(u);return}let d=to.concat(this._inflate[Ge],this._inflate[Oe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Oe]=0,this._inflate[Ge]=[],i&&this.params[`${c}_no_context_takeover`]&&this._inflate.reset()),a(null,d)})}_compress(e,i,a){let c=this._isServer?"server":"client";if(!this._deflate){let u=`${c}_max_window_bits`,d=typeof this.params[u]!="number"?Ft.Z_DEFAULT_WINDOWBITS:this.params[u];this._deflate=Ft.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Oe]=0,this._deflate[Ge]=[],this._deflate.on("data",zx)}this._deflate[gt]=a,this._deflate.write(e),this._deflate.flush(Ft.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let u=to.concat(this._deflate[Ge],this._deflate[Oe]);i&&(u=new Bx(u.buffer,u.byteOffset,u.length-4)),this._deflate[gt]=null,this._deflate[Oe]=0,this._deflate[Ge]=[],i&&this.params[`${c}_no_context_takeover`]&&this._deflate.reset(),a(null,u)})}};so.exports=Br;function zx(n){this[Ge].push(n),this[Oe]+=n.length}function ro(n){if(this[Oe]+=n.length,this[qn]._maxPayload<1||this[Oe]<=this[qn]._maxPayload){this[Ge].push(n);return}this[pt]=new RangeError("Max payload size exceeded"),this[pt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[pt][no]=1009,this.removeListener("data",ro),this.reset()}function qx(n){if(this[qn]._inflate=null,this[pt]){this[gt](this[pt]);return}n[no]=1007,this[gt](n)}});var wt=oe((rg,Fn)=>{"use strict";var{isUtf8:io}=X("buffer"),{hasBlob:Fx}=Ne(),Ux=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Hx(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Mr(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 Kx(n){return Fx&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Fn.exports={isBlob:Kx,isValidStatusCode:Hx,isValidUTF8:Mr,tokenChars:Ux};if(io)Fn.exports.isValidUTF8=function(n){return n.length<24?Mr(n):io(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=X("utf-8-validate");Fn.exports.isValidUTF8=function(e){return e.length<32?Mr(e):n(e)}}catch{}});var Hr=oe((sg,lo)=>{"use strict";var{Writable:jx}=X("stream"),oo=mt(),{BINARY_TYPES:Gx,EMPTY_BUFFER:ao,kStatusCode:Wx,kWebSocket:Jx}=Ne(),{concat:zr,toArrayBuffer:Vx,unmask:Xx}=qt(),{isValidStatusCode:$x,isValidUTF8:co}=wt(),Un=Buffer[Symbol.species],fe=0,xo=1,uo=2,fo=3,qr=4,Fr=5,Hn=6,Ur=class extends jx{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Gx[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Jx]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=fe}_write(e,i,a){if(this._opcode===8&&this._state==fe)return a();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(a)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let a=this._buffers[0];return this._buffers[0]=new Un(a.buffer,a.byteOffset+e,a.length-e),new Un(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 Un(a.buffer,a.byteOffset+e,a.length-e)),e-=a.length}while(e>0);return i}startLoop(e){this._loop=!0;do switch(this._state){case fe:this.getInfo(e);break;case xo:this.getPayloadLength16(e);break;case uo:this.getPayloadLength64(e);break;case fo:this.getMask();break;case qr:this.getData(e);break;case Fr:case Hn: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[oo.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=xo:this._payloadLength===127?this._state=uo: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=fo:this._state=qr}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=qr}getData(e){let i=ao;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&&Xx(i,this._mask)}if(this._opcode>7){this.controlMessage(i,e);return}if(this._compressed){this._state=Fr,this.decompress(i,e);return}i.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(i)),this.dataMessage(e)}decompress(e,i){this._extensions[oo.extensionName].decompress(e,this._fin,(c,u)=>{if(c)return i(c);if(u.length){if(this._messageLength+=u.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");i(d);return}this._fragments.push(u)}this.dataMessage(i),this._state===fe&&this.startLoop(i)})}dataMessage(e){if(!this._fin){this._state=fe;return}let i=this._messageLength,a=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let c;this._binaryType==="nodebuffer"?c=zr(a,i):this._binaryType==="arraybuffer"?c=Vx(zr(a,i)):this._binaryType==="blob"?c=new Blob(a):c=a,this._allowSynchronousEvents?(this.emit("message",c,!0),this._state=fe):(this._state=Hn,setImmediate(()=>{this.emit("message",c,!0),this._state=fe,this.startLoop(e)}))}else{let c=zr(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===Fr||this._allowSynchronousEvents?(this.emit("message",c,!1),this._state=fe):(this._state=Hn,setImmediate(()=>{this.emit("message",c,!1),this._state=fe,this.startLoop(e)}))}}controlMessage(e,i){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,ao),this.end();else{let a=e.readUInt16BE(0);if(!$x(a)){let u=this.createError(RangeError,`invalid status code ${a}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");i(u);return}let c=new Un(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=fe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=fe):(this._state=Hn,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=fe,this.startLoop(i)}))}createError(e,i,a,c,u){this._loop=!1,this._errored=!0;let d=new e(a?`Invalid WebSocket frame: ${i}`:i);return Error.captureStackTrace(d,this.createError),d.code=u,d[Wx]=c,d}};lo.exports=Ur});var Gr=oe((og,po)=>{"use strict";var{Duplex:ig}=X("stream"),{randomFillSync:Yx}=X("crypto"),ho=mt(),{EMPTY_BUFFER:Zx,kWebSocket:Qx,NOOP:eu}=Ne(),{isBlob:_t,isValidStatusCode:tu}=wt(),{mask:go,toBuffer:Ye}=qt(),le=Symbol("kByteLength"),nu=Buffer.alloc(4),Kn=8*1024,Ze,yt=Kn,me=0,ru=1,su=2,Kr=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=me,this.onerror=eu,this[Qx]=void 0}static frame(e,i){let a,c=!1,u=2,d=!1;i.mask&&(a=i.maskBuffer||nu,i.generateMask?i.generateMask(a):(yt===Kn&&(Ze===void 0&&(Ze=Buffer.alloc(Kn)),Yx(Ze,0,Kn),yt=0),a[0]=Ze[yt++],a[1]=Ze[yt++],a[2]=Ze[yt++],a[3]=Ze[yt++]),d=(a[0]|a[1]|a[2]|a[3])===0,u=6);let h;typeof e=="string"?(!i.mask||d)&&i[le]!==void 0?h=i[le]:(e=Buffer.from(e),h=e.length):(h=e.length,c=i.mask&&i.readOnly&&!d);let p=h;h>=65536?(u+=8,p=127):h>125&&(u+=2,p=126);let w=Buffer.allocUnsafe(c?h+u:u);return w[0]=i.fin?i.opcode|128:i.opcode,i.rsv1&&(w[0]|=64),w[1]=p,p===126?w.writeUInt16BE(h,2):p===127&&(w[2]=w[3]=0,w.writeUIntBE(h,4,6)),i.mask?(w[1]|=128,w[u-4]=a[0],w[u-3]=a[1],w[u-2]=a[2],w[u-1]=a[3],d?[w,e]:c?(go(e,a,w,u,h),[w]):(go(e,a,e,0,h),[w,e])):[w,e]}close(e,i,a,c){let u;if(e===void 0)u=Zx;else{if(typeof e!="number"||!tu(e))throw new TypeError("First argument must be a valid error code number");if(i===void 0||!i.length)u=Buffer.allocUnsafe(2),u.writeUInt16BE(e,0);else{let h=Buffer.byteLength(i);if(h>123)throw new RangeError("The message must not be greater than 123 bytes");u=Buffer.allocUnsafe(2+h),u.writeUInt16BE(e,0),typeof i=="string"?u.write(i,2):u.set(i,2)}}let d={[le]:u.length,fin:!0,generateMask:this._generateMask,mask:a,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==me?this.enqueue([this.dispatch,u,!1,d,c]):this.sendFrame(n.frame(u,d),c)}ping(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):_t(e)?(c=e.size,u=!1):(e=Ye(e),c=e.length,u=Ye.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[le]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:9,readOnly:u,rsv1:!1};_t(e)?this._state!==me?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==me?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(n.frame(e,d),a)}pong(e,i,a){let c,u;if(typeof e=="string"?(c=Buffer.byteLength(e),u=!1):_t(e)?(c=e.size,u=!1):(e=Ye(e),c=e.length,u=Ye.readOnly),c>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[le]:c,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:10,readOnly:u,rsv1:!1};_t(e)?this._state!==me?this.enqueue([this.getBlobData,e,!1,d,a]):this.getBlobData(e,!1,d,a):this._state!==me?this.enqueue([this.dispatch,e,!1,d,a]):this.sendFrame(n.frame(e,d),a)}send(e,i,a){let c=this._extensions[ho.extensionName],u=i.binary?2:1,d=i.compress,h,p;typeof e=="string"?(h=Buffer.byteLength(e),p=!1):_t(e)?(h=e.size,p=!1):(e=Ye(e),h=e.length,p=Ye.readOnly),this._firstFragment?(this._firstFragment=!1,d&&c&&c.params[c._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=h>=c._threshold),this._compress=d):(d=!1,u=0),i.fin&&(this._firstFragment=!0);let w={[le]:h,fin:i.fin,generateMask:this._generateMask,mask:i.mask,maskBuffer:this._maskBuffer,opcode:u,readOnly:p,rsv1:d};_t(e)?this._state!==me?this.enqueue([this.getBlobData,e,this._compress,w,a]):this.getBlobData(e,this._compress,w,a):this._state!==me?this.enqueue([this.dispatch,e,this._compress,w,a]):this.dispatch(e,this._compress,w,a)}getBlobData(e,i,a,c){this._bufferedBytes+=a[le],this._state=su,e.arrayBuffer().then(u=>{if(this._socket.destroyed){let h=new Error("The socket was closed while the blob was being read");process.nextTick(jr,this,h,c);return}this._bufferedBytes-=a[le];let d=Ye(u);i?this.dispatch(d,i,a,c):(this._state=me,this.sendFrame(n.frame(d,a),c),this.dequeue())}).catch(u=>{process.nextTick(iu,this,u,c)})}dispatch(e,i,a,c){if(!i){this.sendFrame(n.frame(e,a),c);return}let u=this._extensions[ho.extensionName];this._bufferedBytes+=a[le],this._state=ru,u.compress(e,a.fin,(d,h)=>{if(this._socket.destroyed){let p=new Error("The socket was closed while data was being compressed");jr(this,p,c);return}this._bufferedBytes-=a[le],this._state=me,a.readOnly=!1,this.sendFrame(n.frame(h,a),c),this.dequeue()})}dequeue(){for(;this._state===me&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][le],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][le],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)}};po.exports=Kr;function jr(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 iu(n,e,i){jr(n,e,i),n.onerror(e)}});var Co=oe((ag,Eo)=>{"use strict";var{kForOnEventAttribute:Ut,kListener:Wr}=Ne(),mo=Symbol("kCode"),wo=Symbol("kData"),_o=Symbol("kError"),yo=Symbol("kMessage"),bo=Symbol("kReason"),bt=Symbol("kTarget"),vo=Symbol("kType"),So=Symbol("kWasClean"),Be=class{constructor(e){this[bt]=null,this[vo]=e}get target(){return this[bt]}get type(){return this[vo]}};Object.defineProperty(Be.prototype,"target",{enumerable:!0});Object.defineProperty(Be.prototype,"type",{enumerable:!0});var Qe=class extends Be{constructor(e,i={}){super(e),this[mo]=i.code===void 0?0:i.code,this[bo]=i.reason===void 0?"":i.reason,this[So]=i.wasClean===void 0?!1:i.wasClean}get code(){return this[mo]}get reason(){return this[bo]}get wasClean(){return this[So]}};Object.defineProperty(Qe.prototype,"code",{enumerable:!0});Object.defineProperty(Qe.prototype,"reason",{enumerable:!0});Object.defineProperty(Qe.prototype,"wasClean",{enumerable:!0});var vt=class extends Be{constructor(e,i={}){super(e),this[_o]=i.error===void 0?null:i.error,this[yo]=i.message===void 0?"":i.message}get error(){return this[_o]}get message(){return this[yo]}};Object.defineProperty(vt.prototype,"error",{enumerable:!0});Object.defineProperty(vt.prototype,"message",{enumerable:!0});var Ht=class extends Be{constructor(e,i={}){super(e),this[wo]=i.data===void 0?null:i.data}get data(){return this[wo]}};Object.defineProperty(Ht.prototype,"data",{enumerable:!0});var ou={addEventListener(n,e,i={}){for(let c of this.listeners(n))if(!i[Ut]&&c[Wr]===e&&!c[Ut])return;let a;if(n==="message")a=function(u,d){let h=new Ht("message",{data:d?u:u.toString()});h[bt]=this,jn(e,this,h)};else if(n==="close")a=function(u,d){let h=new Qe("close",{code:u,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});h[bt]=this,jn(e,this,h)};else if(n==="error")a=function(u){let d=new vt("error",{error:u,message:u.message});d[bt]=this,jn(e,this,d)};else if(n==="open")a=function(){let u=new Be("open");u[bt]=this,jn(e,this,u)};else return;a[Ut]=!!i[Ut],a[Wr]=e,i.once?this.once(n,a):this.on(n,a)},removeEventListener(n,e){for(let i of this.listeners(n))if(i[Wr]===e&&!i[Ut]){this.removeListener(n,i);break}}};Eo.exports={CloseEvent:Qe,ErrorEvent:vt,Event:Be,EventTarget:ou,MessageEvent:Ht};function jn(n,e,i){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,i):n.call(e,i)}});var Gn=oe((cg,Ao)=>{"use strict";var{tokenChars:Kt}=wt();function Ae(n,e,i){n[e]===void 0?n[e]=[i]:n[e].push(i)}function au(n){let e=Object.create(null),i=Object.create(null),a=!1,c=!1,u=!1,d,h,p=-1,w=-1,y=-1,_=0;for(;_<n.length;_++)if(w=n.charCodeAt(_),d===void 0)if(y===-1&&Kt[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 I=n.slice(p,y);w===44?(Ae(e,I,i),i=Object.create(null)):d=I,p=y=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===void 0)if(y===-1&&Kt[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=_),Ae(i,n.slice(p,y),!0),w===44&&(Ae(e,d,i),i=Object.create(null),d=void 0),p=y=-1}else if(w===61&&p!==-1&&y===-1)h=n.slice(p,_),p=y=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(c){if(Kt[w]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);p===-1?p=_:a||(a=!0),c=!1}else if(u)if(Kt[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&&Kt[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 I=n.slice(p,y);a&&(I=I.replace(/\\/g,""),a=!1),Ae(i,h,I),w===44&&(Ae(e,d,i),i=Object.create(null),d=void 0),h=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 d===void 0?Ae(e,C,i):(h===void 0?Ae(i,C,!0):a?Ae(i,h,C.replace(/\\/g,"")):Ae(i,h,C),Ae(e,d,i)),e}function cu(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(d=>d===!0?c:`${c}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ao.exports={format:cu,parse:au}});var Xn=oe((dg,zo)=>{"use strict";var xu=X("events"),uu=X("https"),du=X("http"),Do=X("net"),fu=X("tls"),{randomBytes:lu,createHash:hu}=X("crypto"),{Duplex:xg,Readable:ug}=X("stream"),{URL:Jr}=X("url"),We=mt(),gu=Hr(),pu=Gr(),{isBlob:mu}=wt(),{BINARY_TYPES:ko,CLOSE_TIMEOUT:wu,EMPTY_BUFFER:Wn,GUID:_u,kForOnEventAttribute:Vr,kListener:yu,kStatusCode:bu,kWebSocket:Z,NOOP:Io}=Ne(),{EventTarget:{addEventListener:vu,removeEventListener:Su}}=Co(),{format:Eu,parse:Cu}=Gn(),{toBuffer:Au}=qt(),To=Symbol("kAborted"),Xr=[8,13],Me=["CONNECTING","OPEN","CLOSING","CLOSED"],ku=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,j=class n extends xu{constructor(e,i,a){super(),this._binaryType=ko[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wn,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]),Lo(this,e,i,a)):(this._autoPong=a.autoPong,this._closeTimeout=a.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ko.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,i,a){let c=new gu({allowSynchronousEvents:a.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:a.maxPayload,skipUTF8Validation:a.skipUTF8Validation}),u=new pu(e,this._extensions,a.generateMask);this._receiver=c,this._sender=u,this._socket=e,c[Z]=this,u[Z]=this,e[Z]=this,c.on("conclude",Iu),c.on("drain",Tu),c.on("error",Lu),c.on("message",Ru),c.on("ping",Nu),c.on("pong",Ou),u.onerror=Bu,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),i.length>0&&e.unshift(i),e.on("close",Oo),e.on("data",Vn),e.on("end",Bo),e.on("error",Mo),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[We.extensionName]&&this._extensions[We.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){ue(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())}),No(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){$r(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.ping(e||Wn,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){$r(this,e,a);return}i===void 0&&(i=!this._isServer),this._sender.pong(e||Wn,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){$r(this,e,a);return}let c={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...i};this._extensions[We.extensionName]||(c.compress=!1),this._sender.send(e||Wn,c,a)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){ue(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(j,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(j.prototype,"CONNECTING",{enumerable:!0,value:Me.indexOf("CONNECTING")});Object.defineProperty(j,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(j.prototype,"OPEN",{enumerable:!0,value:Me.indexOf("OPEN")});Object.defineProperty(j,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(j.prototype,"CLOSING",{enumerable:!0,value:Me.indexOf("CLOSING")});Object.defineProperty(j,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});Object.defineProperty(j.prototype,"CLOSED",{enumerable:!0,value:Me.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(j.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(j.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Vr])return e[yu];return null},set(e){for(let i of this.listeners(n))if(i[Vr]){this.removeListener(n,i);break}typeof e=="function"&&this.addEventListener(n,e,{[Vr]:!0})}})});j.prototype.addEventListener=vu;j.prototype.removeEventListener=Su;zo.exports=j;function Lo(n,e,i,a){let c={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:wu,protocolVersion:Xr[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,!Xr.includes(c.protocolVersion))throw new RangeError(`Unsupported protocol version: ${c.protocolVersion} (supported versions: ${Xr.join(", ")})`);let u;if(e instanceof Jr)u=e;else try{u=new Jr(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 d=u.protocol==="wss:",h=u.protocol==="ws+unix:",p;if(u.protocol!=="ws:"&&!d&&!h?p=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:h&&!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;Jn(n,R);return}let w=d?443:80,y=lu(16).toString("base64"),_=d?uu.request:du.request,C=new Set,I;if(c.createConnection=c.createConnection||(d?Du:Pu),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&&(I=new We({...c.perMessageDeflate,isServer:!1,maxPayload:c.maxPayload}),c.headers["Sec-WebSocket-Extensions"]=Eu({[We.extensionName]:I.offer()})),i.length){for(let R of i){if(typeof R!="string"||!ku.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}`),h){let R=c.path.split(":");c.socketPath=R[0],c.path=R[1]}let L;if(c.followRedirects){if(n._redirects===0){n._originalIpc=h,n._originalSecure=d,n._originalHostOrSocketPath=h?c.socketPath:u.host;let R=a&&a.headers;if(a={...a,headers:{}},R)for(let[q,se]of Object.entries(R))a.headers[q.toLowerCase()]=se}else if(n.listenerCount("redirect")===0){let R=h?n._originalIpc?c.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:u.host===n._originalHostOrSocketPath;(!R||n._originalSecure&&!d)&&(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")),L=n._req=_(c),n._redirects&&n.emit("redirect",n.url,L)}else L=n._req=_(c);c.timeout&&L.on("timeout",()=>{ue(n,L,"Opening handshake has timed out")}),L.on("error",R=>{L===null||L[To]||(L=n._req=null,Jn(n,R))}),L.on("response",R=>{let q=R.headers.location,se=R.statusCode;if(q&&c.followRedirects&&se>=300&&se<400){if(++n._redirects>c.maxRedirects){ue(n,L,"Maximum redirects exceeded");return}L.abort();let ee;try{ee=new Jr(q,e)}catch{let ae=new SyntaxError(`Invalid URL: ${q}`);Jn(n,ae);return}Lo(n,ee,i,a)}else n.emit("unexpected-response",L,R)||ue(n,L,`Unexpected server response: ${R.statusCode}`)}),L.on("upgrade",(R,q,se)=>{if(n.emit("upgrade",R),n.readyState!==j.CONNECTING)return;L=n._req=null;let ee=R.headers.upgrade;if(ee===void 0||ee.toLowerCase()!=="websocket"){ue(n,q,"Invalid Upgrade header");return}let we=hu("sha1").update(y+_u).digest("base64");if(R.headers["sec-websocket-accept"]!==we){ue(n,q,"Invalid Sec-WebSocket-Accept header");return}let ae=R.headers["sec-websocket-protocol"],P;if(ae!==void 0?C.size?C.has(ae)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":C.size&&(P="Server sent no subprotocol"),P){ue(n,q,P);return}ae&&(n._protocol=ae);let H=R.headers["sec-websocket-extensions"];if(H!==void 0){if(!I){ue(n,q,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let J;try{J=Cu(H)}catch{ue(n,q,"Invalid Sec-WebSocket-Extensions header");return}let te=Object.keys(J);if(te.length!==1||te[0]!==We.extensionName){ue(n,q,"Server indicated an extension that was not requested");return}try{I.accept(J[We.extensionName])}catch{ue(n,q,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[We.extensionName]=I}n.setSocket(q,se,{allowSynchronousEvents:c.allowSynchronousEvents,generateMask:c.generateMask,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation})}),c.finishRequest?c.finishRequest(L,n):L.end()}function Jn(n,e){n._readyState=j.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Pu(n){return n.path=n.socketPath,Do.connect(n)}function Du(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Do.isIP(n.host)?"":n.host),fu.connect(n)}function ue(n,e,i){n._readyState=j.CLOSING;let a=new Error(i);Error.captureStackTrace(a,ue),e.setHeader?(e[To]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Jn,n,a)):(e.destroy(a),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function $r(n,e,i){if(e){let a=mu(e)?e.size:Au(e).length;n._socket?n._sender._bufferedBytes+=a:n._bufferedAmount+=a}if(i){let a=new Error(`WebSocket is not open: readyState ${n.readyState} (${Me[n.readyState]})`);process.nextTick(i,a)}}function Iu(n,e){let i=this[Z];i._closeFrameReceived=!0,i._closeMessage=e,i._closeCode=n,i._socket[Z]!==void 0&&(i._socket.removeListener("data",Vn),process.nextTick(Ro,i._socket),n===1005?i.close():i.close(n,e))}function Tu(){let n=this[Z];n.isPaused||n._socket.resume()}function Lu(n){let e=this[Z];e._socket[Z]!==void 0&&(e._socket.removeListener("data",Vn),process.nextTick(Ro,e._socket),e.close(n[bu])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Po(){this[Z].emitClose()}function Ru(n,e){this[Z].emit("message",n,e)}function Nu(n){let e=this[Z];e._autoPong&&e.pong(n,!this._isServer,Io),e.emit("ping",n)}function Ou(n){this[Z].emit("pong",n)}function Ro(n){n.resume()}function Bu(n){let e=this[Z];e.readyState!==j.CLOSED&&(e.readyState===j.OPEN&&(e._readyState=j.CLOSING,No(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function No(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Oo(){let n=this[Z];if(this.removeListener("close",Oo),this.removeListener("data",Vn),this.removeListener("end",Bo),n._readyState=j.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[Z]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Po),n._receiver.on("finish",Po))}function Vn(n){this[Z]._receiver.write(n)||this.pause()}function Bo(){let n=this[Z];n._readyState=j.CLOSING,n._receiver.end(),this.end()}function Mo(){let n=this[Z];this.removeListener("error",Mo),this.on("error",Io),n&&(n._readyState=j.CLOSING,this.destroy())}});var Ho=oe((lg,Uo)=>{"use strict";var fg=Xn(),{Duplex:Mu}=X("stream");function qo(n){n.emit("close")}function zu(){!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 qu(n,e){let i=!0,a=new Mu({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(u,d){let h=!d&&a._readableState.objectMode?u.toString():u;a.push(h)||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(qo,a);return}let d=!1;n.once("error",function(p){d=!0,u(p)}),n.once("close",function(){d||u(c),process.nextTick(qo,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,d){if(n.readyState===n.CONNECTING){n.once("open",function(){a._write(c,u,d)});return}n.send(c,d)},a.on("end",zu),a.on("error",Fo),a}Uo.exports=qu});var Yr=oe((hg,Ko)=>{"use strict";var{tokenChars:Fu}=wt();function Uu(n){let e=new Set,i=-1,a=-1,c=0;for(c;c<n.length;c++){let d=n.charCodeAt(c);if(a===-1&&Fu[d]===1)i===-1&&(i=c);else if(c!==0&&(d===32||d===9))a===-1&&i!==-1&&(a=c);else if(d===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);let h=n.slice(i,a);if(e.has(h))throw new SyntaxError(`The "${h}" subprotocol is duplicated`);e.add(h),i=a=-1}else throw new SyntaxError(`Unexpected character at index ${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}Ko.exports={parse:Uu}});var $o=oe((pg,Xo)=>{"use strict";var Hu=X("events"),$n=X("http"),{Duplex:gg}=X("stream"),{createHash:Ku}=X("crypto"),jo=Gn(),et=mt(),ju=Yr(),Gu=Xn(),{CLOSE_TIMEOUT:Wu,GUID:Ju,kWebSocket:Vu}=Ne(),Xu=/^[+/0-9A-Za-z]{22}==$/,Go=0,Wo=1,Vo=2,Zr=class extends Hu{constructor(e,i){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Wu,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Gu,...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=$n.createServer((a,c)=>{let u=$n.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=$u(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(c,u,d)=>{this.handleUpgrade(c,u,d,a)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=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===Vo){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!==Wo)if(this._state=Wo,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",Jo);let u=e.headers["sec-websocket-key"],d=e.headers.upgrade,h=+e.headers["sec-websocket-version"];if(e.method!=="GET"){nt(this,e,i,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){nt(this,e,i,400,"Invalid Upgrade header");return}if(u===void 0||!Xu.test(u)){nt(this,e,i,400,"Missing or invalid Sec-WebSocket-Key header");return}if(h!==13&&h!==8){nt(this,e,i,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Gt(i,400);return}let p=e.headers["sec-websocket-protocol"],w=new Set;if(p!==void 0)try{w=ju.parse(p)}catch{nt(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 et({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let I=jo.parse(y);I[et.extensionName]&&(C.accept(I[et.extensionName]),_[et.extensionName]=C)}catch{nt(this,e,i,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let C={origin:e.headers[`${h===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(C,(I,L,R,q)=>{if(!I)return Gt(i,L||401,R,q);this.completeUpgrade(_,u,w,e,i,a,c)});return}if(!this.options.verifyClient(C))return Gt(i,401)}this.completeUpgrade(_,u,w,e,i,a,c)}completeUpgrade(e,i,a,c,u,d,h){if(!u.readable||!u.writable)return u.destroy();if(u[Vu])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Go)return Gt(u,503);let w=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ku("sha1").update(i+Ju).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[et.extensionName]){let _=e[et.extensionName].params,C=jo.format({[et.extensionName]:[_]});w.push(`Sec-WebSocket-Extensions: ${C}`),y._extensions=e}this.emit("headers",w,c),u.write(w.concat(`\r
8
+ var va=Object.create;var Ln=Object.defineProperty;var ka=Object.getOwnPropertyDescriptor;var Ia=Object.getOwnPropertyNames;var xa=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var A=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var K=(n,e)=>()=>(n&&(e=n(n=0)),e);var $=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Mn=(n,e)=>{for(var t in e)Ln(n,t,{get:e[t],enumerable:!0})},Ra=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ia(e))!Ta.call(n,s)&&s!==t&&Ln(n,s,{get:()=>e[s],enumerable:!(r=ka(e,s))||r.enumerable});return n};var he=(n,e,t)=>(t=n!=null?va(xa(n)):{},Ra(e||!n||!n.__esModule?Ln(t,"default",{value:n,enumerable:!0}):t,n));import{chmod as Pa,mkdir as Aa,readFile as Ca,rename as cs,writeFile as ls}from"node:fs/promises";import{dirname as Oa}from"node:path";async function Le(n){try{let e=await Ca(n,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Pt(n,e,t){await Aa(Oa(n),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
9
+ `,s=`${n}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{t?.mode!==void 0?await ls(s,r,{encoding:"utf8",mode:t.mode}):await ls(s,r,"utf8"),await cs(s,n),t?.mode!==void 0&&await Pa(n,t.mode)}catch(i){await cs(s,s).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(s,{force:!0}).catch(()=>{}),i}}var At=K(()=>{"use strict"});function fs(n){return Ot[ds]<=Ot[n]}function Bn(n){us={...n}}function Ct(n,e,t,r){if(Ot[n]<Ot[ds])return;let s=JSON.stringify({ts:new Date().toISOString(),level:n,module:e,msg:t,...us,...r});n==="error"||n==="warn"?Na.write(`${s}
10
+ `):ba.write(`${s}
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
12
12
  `).join(`\r
13
- `)),u.removeListener("error",Jo),y.setSocket(u,d,{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)})),h(y,c)}};Xo.exports=Zr;function $u(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=Vo,n.emit("close")}function Jo(){this.destroy()}function Gt(n,e,i,a){i=i||$n.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} ${$n.STATUS_CODES[e]}\r
14
- `+Object.keys(a).map(c=>`${c}: ${a[c]}`).join(`\r
13
+ `)),i.removeListener("error",Wo),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(xt,this)})),a(d,s)}};Jo.exports=Hr;function cf(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function xt(n){n._state=jo,n.emit("close")}function Wo(){this.destroy()}function Tt(n,e,t,r){t=t||En.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${En.STATUS_CODES[e]}\r
14
+ `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
15
15
  `)+`\r
16
16
  \r
17
- `+i)}function nt(n,e,i,a,c,u){if(n.listenerCount("wsClientError")){let d=new Error(c);Error.captureStackTrace(d,nt),n.emit("wsClientError",d,i,e)}else Gt(i,a,c,u)}});import{spawn as wd}from"node:child_process";import{existsSync as _d,openSync as yd}from"node:fs";import{mkdir as bd}from"node:fs/promises";import{dirname as vd}from"node:path";import{fileURLToPath as Sd}from"node:url";function ts(n=G()){return _d(n.libEntry)?n.libEntry:Sd(new URL("../index.ts",import.meta.url))}async function da(n={}){let e=n.paths??G(),i=n.entryOverride??ts(e);await bd(vd(e.logFile),{recursive:!0});let a=yd(e.logFile,"a"),u=i.endsWith(".ts")?["--import","tsx/esm",i,"--daemon"]:[i,"--daemon"],d=wd(process.execPath,u,{detached:!0,stdio:["ignore",a,a],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(d.unref(),typeof d.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Ed.info("daemon spawned",{pid:d.pid,entry:i}),{pid:d.pid,entry:i}}var Ed,ns=De(()=>{"use strict";K();ce();Ed=N("spawn-daemon")});import{spawn as Ld}from"node:child_process";import{mkdir as Rd,unlink as Nd,writeFile as Od}from"node:fs/promises";import{dirname as Bd,join as Md}from"node:path";function nr(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function pa(n,e){return new Promise((i,a)=>{let c=Ld(n,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${n} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var tr,is,os,ma=De(()=>{"use strict";K();tr=N("supervisor.launchd"),is="ai.coze.bridge",os={platform:"darwin",renderConfig(n){return`<?xml version="1.0" encoding="UTF-8"?>
17
+ `+t)}function be(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,be),n.emit("wsClientError",o,t,e)}else Tt(t,r,s,i)}});import{spawn as Cf}from"node:child_process";import{existsSync as Of,openSync as bf}from"node:fs";import{mkdir as Nf}from"node:fs/promises";import{dirname as Df}from"node:path";import{fileURLToPath as Lf}from"node:url";function Jr(n=T()){return Of(n.libEntry)?n.libEntry:Lf(new URL("../index.ts",import.meta.url))}async function ca(n={}){let e=n.paths??T(),t=n.entryOverride??Jr(e);await Nf(Df(e.logFile),{recursive:!0});let r=bf(e.logFile,"a"),i=t.endsWith(".ts")?["--import","tsx/esm",t,"--daemon"]:[t,"--daemon"],o=Cf(process.execPath,i,{detached:!0,stdio:["ignore",r,r],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return Mf.info("daemon spawned",{pid:o.pid,entry:t}),{pid:o.pid,entry:t}}var Mf,Vr=K(()=>{"use strict";k();z();Mf=w("spawn-daemon")});import{spawn as Hf}from"node:child_process";import{mkdir as Wf,unlink as jf,writeFile as Jf}from"node:fs/promises";import{dirname as Vf,join as Qf}from"node:path";function Rn(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ha(n,e){return new Promise((t,r)=>{let s=Hf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Tn,Xr,Yr,ga=K(()=>{"use strict";k();Tn=w("supervisor.launchd"),Xr="ai.coze.bridge",Yr={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>${is}</string>
22
+ <string>${Xr}</string>
23
23
  <key>ProgramArguments</key>
24
24
  <array>
25
- <string>${nr(n.nodeBin)}</string>
26
- <string>${nr(n.entry)}</string>
25
+ <string>${Rn(n.nodeBin)}</string>
26
+ <string>${Rn(n.entry)}</string>
27
27
  <string>--daemon</string>
28
28
  </array>
29
29
  <key>RunAtLoad</key>
@@ -33,12 +33,12 @@ var p0=Object.create;var _r=Object.defineProperty;var m0=Object.getOwnPropertyDe
33
33
  <key>ThrottleInterval</key>
34
34
  <integer>10</integer>
35
35
  <key>StandardOutPath</key>
36
- <string>${nr(n.logFile)}</string>
36
+ <string>${Rn(n.logFile)}</string>
37
37
  <key>StandardErrorPath</key>
38
- <string>${nr(n.logFile)}</string>
38
+ <string>${Rn(n.logFile)}</string>
39
39
  </dict>
40
40
  </plist>
41
- `},configPath(n){return Md(n.homeDir,"Library","LaunchAgents",`${is}.plist`)},async install(n){let e=this.configPath(n);await Rd(Bd(e),{recursive:!0}),await Od(e,this.renderConfig(n),"utf8"),tr.info("plist written",{plistPath:e}),await pa("launchctl",["load","-w",e]),tr.info("launchd job loaded",{label:is})},async uninstall(n){let e=this.configPath(n);await pa("launchctl",["unload","-w",e]).catch(i=>tr.warn("launchctl unload failed (ignored)",{err:String(i)})),await Nd(e).catch(i=>{if(i.code!=="ENOENT")throw i}),tr.info("launchd job removed",{plistPath:e})}}});import{spawn as zd}from"node:child_process";import{mkdir as qd,unlink as Fd,writeFile as Ud}from"node:fs/promises";import{dirname as Hd,join as Kd}from"node:path";function ir(n,e){return new Promise((i,a)=>{let c=zd(n,e,{stdio:["ignore","pipe","pipe"]}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${n} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var rr,sr,as,wa=De(()=>{"use strict";K();rr=N("supervisor.systemd"),sr="coze-bridge.service",as={platform:"linux",renderConfig(n){return`[Unit]
41
+ `},configPath(n){return Qf(n.homeDir,"Library","LaunchAgents",`${Xr}.plist`)},async install(n){let e=this.configPath(n);await Wf(Vf(e),{recursive:!0}),await Jf(e,this.renderConfig(n),"utf8"),Tn.info("plist written",{plistPath:e}),await ha("launchctl",["load","-w",e]),Tn.info("launchd job loaded",{label:Xr})},async uninstall(n){let e=this.configPath(n);await ha("launchctl",["unload","-w",e]).catch(t=>Tn.warn("launchctl unload failed (ignored)",{err:String(t)})),await jf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),Tn.info("launchd job removed",{plistPath:e})}}});import{spawn as Kf}from"node:child_process";import{mkdir as Xf,unlink as Yf,writeFile as Zf}from"node:fs/promises";import{dirname as eh,join as th}from"node:path";function Cn(n,e){return new Promise((t,r)=>{let s=Kf(n,e,{stdio:["ignore","pipe","pipe"]}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var Pn,An,Zr,pa=K(()=>{"use strict";k();Pn=w("supervisor.systemd"),An="coze-bridge.service",Zr={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 Kd(n.homeDir,".config","systemd","user",sr)},async install(n){let e=this.configPath(n);await qd(Hd(e),{recursive:!0}),await Ud(e,this.renderConfig(n),"utf8"),rr.info("systemd unit written",{unitPath:e}),await ir("systemctl",["--user","daemon-reload"]),await ir("systemctl",["--user","enable","--now",sr]),rr.info("systemd unit enabled",{unitName:sr})},async uninstall(n){let e=this.configPath(n);await ir("systemctl",["--user","disable","--now",sr]).catch(i=>rr.warn("systemctl disable failed (ignored)",{err:String(i)})),await Fd(e).catch(i=>{if(i.code!=="ENOENT")throw i}),await ir("systemctl",["--user","daemon-reload"]).catch(()=>{}),rr.info("systemd unit removed",{unitPath:e})}}});import{spawn as jd}from"node:child_process";import{join as Gd}from"node:path";function _a(n,e){return new Promise((i,a)=>{let c=jd(n,e,{stdio:["ignore","pipe","pipe"],shell:!1}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`${n} ${e.join(" ")} exited ${d}: ${u.trim()}`))})})}var cs,or,xs,ya=De(()=>{"use strict";K();cs=N("supervisor.taskscheduler"),or="CozeBridge",xs={platform:"win32",renderConfig(n){return`<?xml version="1.0" encoding="UTF-16"?>
55
+ `},configPath(n){return th(n.homeDir,".config","systemd","user",An)},async install(n){let e=this.configPath(n);await Xf(eh(e),{recursive:!0}),await Zf(e,this.renderConfig(n),"utf8"),Pn.info("systemd unit written",{unitPath:e}),await Cn("systemctl",["--user","daemon-reload"]),await Cn("systemctl",["--user","enable","--now",An]),Pn.info("systemd unit enabled",{unitName:An})},async uninstall(n){let e=this.configPath(n);await Cn("systemctl",["--user","disable","--now",An]).catch(t=>Pn.warn("systemctl disable failed (ignored)",{err:String(t)})),await Yf(e).catch(t=>{if(t.code!=="ENOENT")throw t}),await Cn("systemctl",["--user","daemon-reload"]).catch(()=>{}),Pn.info("systemd unit removed",{unitPath:e})}}});import{spawn as nh}from"node:child_process";import{join as rh}from"node:path";function ma(n,e){return new Promise((t,r)=>{let s=nh(n,e,{stdio:["ignore","pipe","pipe"],shell:!1}),i="";s.stderr?.on("data",o=>{i+=o.toString("utf8")}),s.on("error",r),s.on("close",o=>{o===0?t():r(new Error(`${n} ${e.join(" ")} exited ${o}: ${i.trim()}`))})})}var es,On,ts,_a=K(()=>{"use strict";k();es=w("supervisor.taskscheduler"),On="CozeBridge",ts={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,24 +76,25 @@ WantedBy=default.target
76
76
  </Exec>
77
77
  </Actions>
78
78
  </Task>
79
- `},configPath(n){return Gd(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await _a("schtasks",["/Create","/SC","ONLOGON","/TN",or,"/TR",e,"/RU",n.userName,"/F"]),cs.info("task scheduler entry created",{task:or})},async uninstall(n){await _a("schtasks",["/Delete","/TN",or,"/F"]).catch(e=>cs.warn("schtasks /Delete failed (ignored)",{err:String(e)})),cs.info("task scheduler entry removed",{task:or})}}});var us={};Os(us,{buildContext:()=>Xd,getSupervisor:()=>Vd,launchdSupervisor:()=>os,systemdSupervisor:()=>as,taskSchedulerSupervisor:()=>xs});import{homedir as Wd,userInfo as Jd}from"node:os";function Vd(n=process.platform){switch(n){case"darwin":return os;case"linux":return as;case"win32":return xs;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function Xd(){let n=G();return{nodeBin:process.execPath,entry:ts(n),logFile:n.logFile,homeDir:Wd(),userName:Jd().username}}var ds=De(()=>{"use strict";ce();ns();ma();wa();ya()});Ue();K();import{readdir as M0}from"node:fs/promises";import{mkdir as L0,writeFile as R0}from"node:fs/promises";import{join as N0}from"node:path";var O0={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function ct(n,e,i,a){await L0(n,{recursive:!0});let c=O0[e],u=N0(n,c),d=B0(e,i,a);return await R0(u,d,"utf8"),u}function B0(n,e,i){let a=`# Coze Agent: ${e}
79
+ `},configPath(n){return rh(n.homeDir,".coze","bridge","task.xml")},async install(n){let e=`"${n.nodeBin}" "${n.entry}" --daemon`;await ma("schtasks",["/Create","/SC","ONLOGON","/TN",On,"/TR",e,"/RU",n.userName,"/F"]),es.info("task scheduler entry created",{task:On})},async uninstall(n){await ma("schtasks",["/Delete","/TN",On,"/F"]).catch(e=>es.warn("schtasks /Delete failed (ignored)",{err:String(e)})),es.info("task scheduler entry removed",{task:On})}}});var ns={};Mn(ns,{buildContext:()=>ah,getSupervisor:()=>oh,launchdSupervisor:()=>Yr,systemdSupervisor:()=>Zr,taskSchedulerSupervisor:()=>ts});import{homedir as sh,userInfo as ih}from"node:os";function oh(n=process.platform){switch(n){case"darwin":return Yr;case"linux":return Zr;case"win32":return ts;default:throw new Error(`unsupported platform for OS supervisor: ${n}`)}}function ah(){let n=T();return{nodeBin:process.execPath,entry:Jr(n),logFile:n.logFile,homeDir:sh(),userName:ih().username}}var rs=K(()=>{"use strict";z();Vr();ga();pa();_a()});ge();k();import{readdir as Ga}from"node:fs/promises";import{mkdir as Fa,writeFile as Ua}from"node:fs/promises";import{join as $a}from"node:path";var za={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Me(n,e,t,r){await Fa(n,{recursive:!0});let s=za[e],i=$a(n,s),o=qa(e,t,r);return await Ua(i,o,"utf8"),i}function qa(n,e,t){let r=`# Coze Agent: ${e}
80
80
 
81
81
  > framework: \`${n}\`
82
82
 
83
- `,c=i?.trim()?i.endsWith(`
84
- `)?i:`${i}
83
+ `,s=t?.trim()?t.endsWith(`
84
+ `)?t:`${t}
85
85
  `:`_No instructions provided._
86
- `;return`${a}---
86
+ `;return`${r}---
87
87
 
88
- ${c}`}var ve=N("agent-detail-sync"),sn=class{constructor(e){this.opts=e}opts;async syncAll(e){let i=this.opts.paths.agentsRoot,a;try{a=await M0(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 xe(e,this.opts.paths);if(!i){ve.info("detail sync: agent config missing, skip",{agentId:e});return}let a;try{a=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(d){ve.warn("detail RPC failed, using local data",{agentId:e,err:String(d)});return}if(a.agentId&&a.agentId!==e){ve.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:a.agentId});return}let 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 pe(i,this.opts.paths),ve.info("detail sync: config updated",{agentId:e,identityChanged:u,agentName:i.agentName}),u&&(await ct(i.workspace,i.framework,e,i.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};Ue();import{spawn as ii}from"node:child_process";import{lstat as Cr,mkdir as U0,readFile as oi,readdir as H0,rm as K0,stat as j0,writeFile as G0}from"node:fs/promises";import{join as Re,normalize as W0,relative as ai,resolve as J0,sep as ci}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 Pt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function Hs(n){let{_meta:e,...i}=n;return{stripped:i,meta:e}}function xt(n){if(!n?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return n.cozeAgentId}var E=class extends Error{code;retriable;cause;constructor(e,i,a){super(i),this.name="BridgeError",this.code=e,this.retriable=a?.retriable??!1,a?.cause!==void 0&&(this.cause=a.cause)}};K();ce();function Le(n,e){if(Pt(n)!=="cloud")throw new E("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Dt(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}K();var on="1008033",Ks="1289";var js="pbbp2",Gs="https://www.coze.cn",Ws="/api/coze_claw/resource/get_frontier_key",z0="https://www.coze.cn",q0="wss://frontier.coze.cn";function Js(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??z0}function Vs(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??q0}function an(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 cn(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var Xs=N("handshake");async function $s(n){let e=Js(n.endpoint),i=n.timeoutMs??1e4,a=`${F0(e)}${Ws}?aid=${encodeURIComponent(on)}`,c={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...an(n.ppeOverride)},u=new AbortController,d=setTimeout(()=>u.abort(),i);Xs.info("frontier key handshake",{base:e});try{let h=await fetch(a,{method:"GET",headers:c,signal:u.signal}),p=h.headers.get("x-tt-logid")??"",w=h.headers.get("x-tt-trace-id")??"";if(!h.ok){let I=await h.text().catch(()=>"");throw new E("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${h.status} logid=${p}: ${I.slice(0,200)}`)}let y=await h.json();if(y.code!==void 0&&y.code!==0)throw new E("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 E("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${p}: ${JSON.stringify(y)}`);return Xs.info("handshake ok",{remoteDeviceId:C,logid:p,traceId:w}),{accessKey:_,deviceId:C}}catch(h){throw h instanceof E?h:h.name==="AbortError"?new E("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${i}ms)`):new E("UPSTREAM_HANDSHAKE_FAILED",String(h),{cause:h})}finally{clearTimeout(d)}}function F0(n){return n.endsWith("/")?n.slice(0,-1):n}var vr="https://llm-gateway.coze.cn",He="auto";function Ys(n){return{model:n.model??He,...n.modelToken?{modelToken:n.modelToken}:{}}}function It(n){return!n||n===He}function Zs(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=vr,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||He):It(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function Qs(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||He}"`):It(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="${vr}/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 ei(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function Sr(n){let{ttEnv:e,usePpe:i}=cn(n),a={};return e&&(a["x-tt-env"]=e),i&&(a["x-use-ppe"]=i),a}function ti(n,e){if(!n.modelToken)return{};let i=Sr(e);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,u])=>`${c}:${u}`).join(`
89
- `)}}function Er(n){return`coze-session-${n.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function ni(n,e){if(!n.modelToken||It(n.model))return null;let i=Sr(e),a={baseUrl:`${vr}/v1`,api:"openai-completions",apiKey:n.modelToken,models:[{id:n.model,name:n.model,reasoning:!1,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(a.headers=i),a}function ri(n,e){if(!n.modelToken)return[];let i=Sr(e),a=[];for(let[c,u]of Object.entries(i))a.push("-c",`model_providers.coze.http_headers.${c}="${u}"`);return a}var re=N("agent-handlers"),si=5*1024*1024,V0=1,X0=6,$0=new Set(["node_modules",".git",".coze","dist","build",".next"]),un=class{constructor(e){this.opts=e}opts;async listSkills(e){Le(e._meta,"_agent/listSkills");let i=xt(e._meta),a=await this.loadAgentCfg(i),c=a?.workspace??Te(i).workspace,u=a?.skills??[],d=[];for(let h of u){let p=Re(c,h.relPath,"SKILL.md");await j0(p).then(y=>y.isFile()).catch(()=>!1)&&d.push({skillId:h.skillId,skillName:h.skillName,downloadUrl:h.downloadUrl??"",...h.description?{description:h.description}:{},...h.version?{version:h.version}:{}})}return{skills:d}}async addSkills(e){Le(e._meta,"_agent/addSkills");let i=xt(e._meta),a=await this.requireAgentCfg(i),c=e.skills??[],u=[...a.skills??[]],d=new Map(u.map((p,w)=>[p.skillId,w])),h=[];for(let p of c){if(!p.skillName)throw new E("IPC_BAD_REQUEST","skill missing skillName");let w=Y0(p.skillName),y=Z0(a.framework),_=Re(y,w),C=Re(a.workspace,_);await U0(C,{recursive:!0});let I=await tc(p.downloadUrl);rc(I)?await sc(I,C):await G0(Re(C,"SKILL.md"),I.toString("utf8"),"utf8");let L={skillId:p.skillId,skillName:p.skillName,relPath:_,installedAt:Date.now(),...p.description?{description:p.description}:{},...p.version?{version:p.version}:{},...p.downloadUrl?{downloadUrl:p.downloadUrl}:{}},R=d.get(p.skillId);R!==void 0?u[R]=L:(d.set(p.skillId,u.length),u.push(L)),h.push(p),re.info("skill installed",{agentId:i,skillId:p.skillId,skillName:p.skillName,relPath:_})}return await nn(i,u),await this.reloadAgentSessions(i,"skills-added"),{installedSkills:h}}async removeSkills(e){Le(e._meta,"_agent/removeSkills");let i=xt(e._meta),a=await this.requireAgentCfg(i),c=new Set(e.skillIds??[]),u=a.skills??[],d=[];for(let h of u){if(!c.has(h.skillId)){d.push(h);continue}let p=Re(a.workspace,h.relPath);await K0(p,{recursive:!0,force:!0}),re.info("skill removed",{agentId:i,skillId:h.skillId,relPath:h.relPath})}return await nn(i,d),await this.reloadAgentSessions(i,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,i){return this.reloadAgentSessions(e,i)}async reloadAgentSessions(e,i){let a=this.opts.agents.get(e);if(a&&a.framework!=="codex"){for(let[c,u]of a.sessions)if(!(!u.downstream||!u.acpSessionId)){u.loadingSession=!0;try{await u.downstream.sessionLoad({sessionId:u.acpSessionId,cwd:a.workspace}),re.info("session reloaded",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId})}catch(d){re.warn("session reload failed",{reason:i,agentId:e,framework:a.framework,cloudId:c,acpId:u.acpSessionId,err:String(d)})}finally{u.loadingSession=!1}}}}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let i=e.agentId,a=await xe(i);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${i}`);return a.cozeIdentity===e.cozeIdentity?(re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:i}),{ok:!0}):(a.cozeIdentity=e.cozeIdentity,await pe(a),await ct(a.workspace,a.framework,i,e.cozeIdentity),re.info("_agent/update: cozeIdentity rewritten",{agentId:i,framework:a.framework}),await this.reloadAgentSessions(i,"identity-changed"),{ok:!0})}async disconnectAgent(e){let i=e.agentId;if(!i)throw new E("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let a=await xe(i);return a?(a.disconnectedAt=Date.now(),a.disconnectReason=e.reason??"",await pe(a),re.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}):(re.warn("_agent/disconnect: agent not found, ignoring",{agentId:i}),{ok:!0})}async switchModel(e){if(Le(e._meta,"_agent/switchModel"),!e.agentId)throw new E("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let i=e.model?.trim()?e.model:He,a=await xe(e.agentId);if(!a)throw new E("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);a.model=i,await pe(a),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:i,reason:e.reason??""});let c=this.opts.agents.get(e.agentId);if(!c)return re.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};c.model=i;let u=[];for(let[d,h]of c.allSessionQueues())u.push(h.enqueue(async()=>{let p=c.sessions.get(d);p?.downstream&&(await p.downstream.stop(`switchModel: ${i}`).catch(()=>{}),p.downstream=void 0)}));return await Promise.all(u),re.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:i,cloudSessions:u.length}),{ok:!0}}async resetAgent(e){if(Le(e._meta,Se.RESET),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.RESET}: missing agentId`);return await this.runDetailSync(e.agentId,Se.RESET,e.reason),{ok:!0}}async repairAgent(e){if(Le(e._meta,Se.REPAIR),!e.agentId)throw new E("IPC_BAD_REQUEST",`${Se.REPAIR}: missing agentId`);let i=await this.loadAgentCfg(e.agentId);if(i&&i.framework!=="openclaw")throw new E("IPC_BAD_REQUEST",`${Se.REPAIR} only allowed for openclaw, got ${i.framework}`);if(i&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,i.workspace)}catch(a){re.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){re.warn("detailSyncer not wired, skipping sync",{method:i,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(c){re.warn("detail sync failed (ignored)",{method:i,agentId:e,reason:a,err:String(c)})}}async getFileTree(e){Le(e._meta,"_agent/getFileTree");let i=e._meta,a=xt(i),c=await this.resolveWorkspace(a),u=e.filePath??"",d=this.safeJoin(c,u),h=await Cr(d).catch(()=>null);if(!h)throw new E("IPC_BAD_REQUEST",`path not found: ${u}`);if(h.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${u}`);let p=oc(e.depth);return h.isDirectory()?{tree:await xi(c,d,u,p)}:{tree:[{name:ac(u),path:ui(u||"."),isDir:!1,size:h.size,modifiedAt:Math.floor(h.mtimeMs)}]}}async getFileContent(e){Le(e._meta,"_agent/getFileContent");let i=xt(e._meta),a=await this.resolveWorkspace(i);if(!e.filePath)throw new E("IPC_BAD_REQUEST","filePath required");let c=this.safeJoin(a,e.filePath),u=await Cr(c).catch(()=>null);if(!u||!u.isFile())throw new E("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(u.isSymbolicLink())throw new E("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(u.size>si)throw new E("IPC_BAD_REQUEST",`file too large: ${u.size} bytes (max ${si})`);let d=await oi(c);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:u.size}:{content:d.toString("utf8"),encoding:"utf-8",size:u.size}}async resolveWorkspace(e){let i=this.opts.agents.get(e);return i?i.workspace:(await xe(e).catch(()=>null))?.workspace??Te(e).workspace}safeJoin(e,i){let a=J0(e,i||"."),c=ai(e,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${ci}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${i}`);return a}loadAgentCfg(e){return xe(e)}async requireAgentCfg(e){let i=await this.loadAgentCfg(e);if(!i)throw new E("AGENT_NOT_FOUND",`no config for agent: ${e}`);return i}};function Y0(n){let e=Dt(n.trim()).replace(/^-+|-+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new E("IPC_BAD_REQUEST",`invalid skill name: ${n}`);return e}function Z0(n){return n==="claude-code"?Re(".claude","skills"):Re(".agents","skills")}var Q0=3e4,ec=50*1024*1024,dn=3e4;async function tc(n){if(!n)throw new E("IPC_BAD_REQUEST","skill missing downloadUrl");if(n.startsWith("data:")){let e=Math.floor(n.length*3/4);xn(e);let i=nc(n);return xn(i.length),i}if(n.startsWith("file:")){let e=new URL(n).pathname,i=await oi(e);return xn(i.length),i}if(n.startsWith("http://")||n.startsWith("https://")){let e=new AbortController,i=setTimeout(()=>e.abort(),Q0);try{let a=await fetch(n,{signal:e.signal});if(!a.ok)throw new E("IPC_BAD_REQUEST",`fetch skill failed HTTP ${a.status} ${n}`);let c=await a.arrayBuffer();return xn(c.byteLength),Buffer.from(c)}finally{clearTimeout(i)}}throw new E("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${n.slice(0,80)}`)}function xn(n){if(n>ec)throw new E("IPC_BAD_REQUEST",`skill too large: ${n} bytes`)}function nc(n){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(n);if(!e)throw new E("IPC_BAD_REQUEST","bad data URL");let i=!!e[2],a=e[3]??"";return i?Buffer.from(a,"base64"):Buffer.from(decodeURIComponent(a),"utf8")}function rc(n){return n.length>=2&&n[0]===31&&n[1]===139}async function sc(n,e){await ic(n),await new Promise((i,a)=>{let c=ii("tar",["-xzf","-","-C",e,"--strip-components=1","--no-same-owner"],{stdio:["pipe","pipe","pipe"]}),u="";c.stderr?.on("data",h=>{u+=String(h)});let d=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar extract timeout (${dn}ms)`))},dn);c.on("error",h=>{clearTimeout(d),a(new E("IPC_BAD_REQUEST",`tar spawn failed: ${h.message}`,{cause:h}))}),c.on("exit",h=>{clearTimeout(d),h===0?i():a(new E("IPC_BAD_REQUEST",`tar exit ${h}${u?`: ${u.trim().slice(0,200)}`:""}`))}),c.stdin?.end(n)})}async function ic(n){let e=await new Promise((i,a)=>{let c=ii("tar",["-tzvf","-"],{stdio:["pipe","pipe","pipe"]}),u="",d="";c.stdout?.on("data",p=>{u+=String(p)}),c.stderr?.on("data",p=>{d+=String(p)});let h=setTimeout(()=>{c.kill("SIGKILL"),a(new E("IPC_BAD_REQUEST",`tar list timeout (${dn}ms)`))},dn);c.on("error",p=>{clearTimeout(h),a(new E("IPC_BAD_REQUEST",`tar list spawn failed: ${p.message}`))}),c.on("exit",p=>{clearTimeout(h),p===0?i(u):a(new E("IPC_BAD_REQUEST",`tar list exit ${p}${d?`: ${d.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 E("IPC_BAD_REQUEST",`tar entry kind '${a[0]}' not allowed (symlink/hardlink/special): ${a.slice(0,100)}`);let d=(a.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!d)continue;if(d.startsWith("/"))throw new E("IPC_BAD_REQUEST",`tar entry absolute path: ${d}`);if(d.split(/[/\\]/).some(p=>p===".."))throw new E("IPC_BAD_REQUEST",`tar entry contains '..': ${d}`)}}async function xi(n,e,i,a){if(a<=0)return[];let c;try{c=await H0(e,{withFileTypes:!0})}catch{return[]}let u=[];for(let d of c){if($0.has(d.name)||d.isSymbolicLink())continue;let h=Re(e,d.name),p=W0(Re(i,d.name)),w=null;try{w=await Cr(h)}catch{continue}if(w.isSymbolicLink())continue;let y={name:d.name,path:ui(ai(n,h)),isDir:w.isDirectory(),size:w.size,modifiedAt:Math.floor(w.mtimeMs)};w.isDirectory()&&a>1&&(y.children=await xi(n,h,p,a-1)),u.push(y)}return u.sort((d,h)=>d.isDir!==h.isDir?d.isDir?-1:1:d.name.localeCompare(h.name)),u}function oc(n){return!n||n<=0?V0:Math.min(n,X0)}function ac(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function ui(n){return n.split(ci).join("/")}K();import{readFileSync as rl}from"node:fs";import{dirname as il,join as ol}from"node:path";import{fileURLToPath as cl}from"node:url";var fn="0.1.30";var Tt=N("agent-health-reporter"),cc=1e4,ln=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??cc}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Tt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Tt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Tt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Tt.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let i=[];for(let c of this.opts.core.agents.values()){let u=xc(c);u&&i.push({agentId:c.agentId,status:u})}if(i.length===0)return;let a={agents:i,bridgeVersion:fn,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",a)}catch(c){Tt.warn("heartbeat batch send failed",{count:i.length,err:String(c)})}}finally{this.inFlight=!1}}};function xc(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}Ue();import{mkdir as kr,rm as Mc}from"node:fs/promises";K();import{execFile as uc}from"node:child_process";import{promisify as dc}from"node:util";var fi=dc(uc),Lt=N("agents.acp-installer"),fc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},lc=5e4,hc=5e3,gc=5*6e4,gn=new Map,hn=new Map,Ar=new Map;async function di(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:i}=await fi(e,[n],{timeout:hc});return i.split(`
91
- `)[0]?.trim()||void 0}catch{return}}async function pc(n){Lt.info("npm install -g start",{npmPackage:n}),await fi("npm",["install","-g",`${n}@latest`],{timeout:lc,maxBuffer:10*1024*1024}),Lt.info("npm install -g done",{npmPackage:n})}async function li(n){let e=fc[n];if(!e)return;let i=gn.get(n);if(i)return i;let a=hn.get(n);if(a&&Date.now()-a<gc)return;let c=Ar.get(n);if(c)return c;let u=(async()=>{let d=await di(e.binary);if(d)return gn.set(n,d),Lt.info("acp wrapper found on PATH",{binary:e.binary,path:d}),d;try{await pc(e.npmPackage)}catch(p){Lt.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(p)}),hn.set(n,Date.now());return}let h=await di(e.binary);if(!h){Lt.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),hn.set(n,Date.now());return}return gn.set(n,h),hn.delete(n),h})().finally(()=>{Ar.delete(n)});return Ar.set(n,u),u}function pn(n){return gn.get(n)}import{spawn as bc}from"node:child_process";function Rt(n,e,i){return i===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:i}}function mn(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function ut(n,e){return{jsonrpc:"2.0",id:n,result:e}}function $e(n,e){return{jsonrpc:"2.0",id:n,error:e}}var wn=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)}},W={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 hi(n){return"method"in n&&"id"in n&&n.id!==void 0}function gi(n){return"method"in n&&!("id"in n)}function _n(n){return!("method"in n)&&"id"in n}var mc={AGENT_NOT_FOUND:W.AGENT_NOT_FOUND,AGENT_BUSY:W.AGENT_BUSY,AGENT_DISCONNECTED:W.AGENT_DISCONNECTED,AGENT_TIMEOUT:W.AGENT_TIMEOUT,AGENT_SPAWN_FAILED:W.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:W.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:W.INTERNAL_ERROR,BRIDGE_INTERNAL:W.INTERNAL_ERROR,IPC_AUTH_FAILED:W.INTERNAL_ERROR,IPC_BAD_REQUEST:W.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:W.MODEL_TOKEN_GEN_FAILED,OPERATION_NOT_ALLOWED_FOR_LOCAL:W.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:W.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:W.INTERNAL_ERROR};function Nt(n){return n instanceof E?{code:mc[n.code]??W.INTERNAL_ERROR,message:n.message,data:{bridgeCode:n.code,retriable:n.retriable}}:{code:W.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)}}function pi(n){let e=n.data,i=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new E(i,n.message,{retriable:e?.retriable??!1,cause:n.data})}function mi(n){return`${JSON.stringify(n)}
92
- `}var yn=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let i=this.buffer.split(`
93
- `);this.buffer=i.pop()??"";let a=[];for(let c of i){let u=c.replace(/\r$/,"").trim();if(u)try{a.push(JSON.parse(u))}catch(d){this.onError?.({line:u,error:d})}}return a}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(i){return this.onError?.({line:e,error:i}),[]}}};var _i={"session/prompt":"session.prompt","session/cancel":"session.cancel","session/new":"session.new","session/load":"session.load","_agent/create":"agent.create","_agent/health":"agent.health","_agent/pair":"agent.pair","_agent/listSkills":"agent.listSkills","_agent/addSkills":"agent.addSkills","_agent/removeSkills":"agent.removeSkills","_agent/getFileTree":"agent.getFileTree","_agent/getFileContent":"agent.getFileContent","_agent/detail":"agent.detail","_agent/update":"agent.update","_agent/disconnect":"agent.disconnect","_agent/switchModel":"agent.switchModel","_agent/genModelToken":"agent.genModelToken","_agent/reset":"agent.reset","_agent/repair":"agent.repair","session/request_permission":"session.requestPermission",initialize:"initialize"},Sl=Object.fromEntries(Object.entries(_i).map(([n,e])=>[e,n])),wc={"session.prompt":["agentId","triggerMsgId","sessionId"],"session.cancel":["agentId","triggerMsgId","sessionId"],"session.new":["agentId"],"session.load":["agentId"],"agent.create":["agentId"],"agent.health":[],"agent.listSkills":["agentId"],"agent.addSkills":["agentId"],"agent.removeSkills":["agentId"],"agent.getFileTree":["agentId"],"agent.getFileContent":["agentId"],"agent.detail":["agentId"],"agent.update":["agentId"],"agent.disconnect":["agentId"],"agent.switchModel":["agentId"],"agent.genModelToken":["agentId","sessionId"],"agent.reset":["agentId"],"agent.repair":["agentId"],"session.requestPermission":["agentId","sessionId"],"agent.pair":[],initialize:[]},dt=class{seq=0;next(e,i){this.seq+=1;let a=_i[e]??_c(e),c=wc[a]??[],u=[a,String(this.seq)];if(c.length>0){let d=c.map(p=>wi(i?.[p]??"")),h=yc(d).join(":");h&&u.push(h)}else i&&Object.values(i).some(d=>d)&&u.push(Object.values(i).filter(Boolean).map(d=>wi(String(d))).join(":"));return u.join("_")}reset(){this.seq=0}};function _c(n){return n.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function wi(n){return n.replace(/[:_\s]+/g,"-")}function yc(n){let e=n.length;for(;e>0&&!n[e-1];)e-=1;return n.slice(0,e)}K();var vc=3e4,Sc=50,Ec=20,yi=500;function Cc(n){try{let e=JSON.stringify(n);return e===void 0||e.length<=yi?n:`${e.slice(0,yi)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function bi(n,e){if(!(typeof n!="number"||n<=0))try{process.platform==="win32"?process.kill(n,e):process.kill(-n,e)}catch{}}var Ke=class{constructor(e){this.opts=e;this.log=N(`downstream.${this.constructor.name}`),this.decoder=new yn({onError:i=>this.log.warn("decode line failed",{line:i.line})})}opts;child;decoder;pending=new Map;idAllocator=new dt;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new E("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",i=bc(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=i,i.stdout?.setEncoding("utf8"),i.stdout?.on("data",a=>{for(let c of this.decoder.push(a))this.dispatch(c)}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",a=>{let c=a.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Sc&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.on("exit",(a,c)=>{this.stopped=!0,(a!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:a,signal:c,recentStderr:this.stderrRing.slice(-Ec)}),this.failAllPending(new E("AGENT_PROTOCOL_ERROR",`agent exited (${a}/${c})`));for(let d of this.exitHandlers)d(a,c)}),i.on("error",a=>{this.log.error("child error",{err:String(a)}),this.failAllPending(new E("AGENT_SPAWN_FAILED",String(a),{cause:a}))}),this.log.info("downstream started",{command:this.opts.command,pid:i.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let i=this.child,a=new Promise(u=>i.once("exit",()=>u()));bi(i.pid,"SIGTERM");let c=setTimeout(()=>{i.killed||bi(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(mn("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(ut(e,i))}catch(a){this.log.warn("respondAgentRequest write failed",{id:e,err:String(a)})}}respondAgentRequestError(e,i){if(!(!this.child||this.stopped))try{this.writeFrame($e(e,i))}catch(a){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(a)})}}onExit(e){this.exitHandlers.push(e)}call(e,i,a=vc){if(!this.child||this.stopped)return Promise.reject(new E("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),u=Rt(c,e,i),d=a>0&&Number.isFinite(a);return new Promise((h,p)=>{let w=d?setTimeout(()=>{this.pending.delete(c),p(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a):null;this.pending.set(c,{resolve:h,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 E("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(mi(e))}dispatch(e){if(_n(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(pi(e.error))):(this.log.info("downstream returned result",{id:e.id,method:i.method,result:Cc(e.result)}),i.resolve(e.result));return}if(gi(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(hi(e)){let i=e;this.handleAgentRequest(i).catch(a=>this.log.error("agent request handler failed",{method:i.method,err:String(a)}))}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame($e(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}for(let i of this.agentRequestHandlers)try{await i(e)}catch(a){this.log.error("agentRequestHandler threw",{method:e.method,err:String(a)});try{this.writeFrame($e(e.id,Nt(a)))}catch{}}}failAllPending(e){for(let i of this.pending.values())i.timer&&clearTimeout(i.timer),i.reject(e);this.pending.clear()}};var Ac="@agentclientprotocol/claude-agent-acp@latest";function kc(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 bn=class extends Ke{framework="claude-code";constructor(e){let i=pn("claude-code"),[a,c]=i?[i,[]]:["npx",["-y",Ac]],u=e.command??a,d=e.args??c,h={command:u,args:d,cwd:e.cwd,...e.env?{env:e.env}:{}};super(h)}sanitizeEnv(e){return kc(e)}};import{mkdtempSync as Pc,rmSync as Dc}from"node:fs";import{tmpdir as Ic}from"node:os";import{join as Tc}from"node:path";var Lc="@zed-industries/codex-acp@latest",vn=class extends Ke{framework="codex";authMethodId;codexHomeDir;constructor(e){let i=pn("codex"),[a,c]=i?[i,[]]:["npx",["-y",Lc]],u=e.command??a,d=e.args??c,h=e.extraArgs?[...d,...e.extraArgs]:d,p=e.isolateCodexHome?Pc(Tc(Ic(),"coze-bridge-codex-home-")):void 0,w=p?{...e.env??{},CODEX_HOME:p}:e.env,y={command:u,args:h,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{Dc(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var Ot=class extends Ke{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let i=e.sessionName??"default",a=["acp","--session",`agent:${e.agentId}:${i}`];e.gatewayToken&&a.push("--token",e.gatewayToken);let c={command:e.command,args:a,cwd:e.cwd,...e.env?{env:e.env}:{}};super(c),this.agentId=e.agentId,this.sessionName=i,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]}))}get acpSessionName(){return this.sessionName}};K();ce();var ft=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 Sn=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 ft,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)Bt(a),a.downstream&&(i.push(a.downstream.stop(e).catch(()=>{})),a.downstream=void 0);await Promise.all(i),this.activeTriggers.clear()}};function Bt(n){n.idleTimer&&(clearTimeout(n.idleTimer),n.idleTimer=void 0)}import{spawn as Rc}from"node:child_process";import{homedir as Nc}from"node:os";import{join as Oc}from"node:path";Zt();K();async function Ei(){let n=Oc(Nc(),".openclaw/openclaw.json");return(await at(n))?.gateway?.auth?.token??""}var vi=N("openclaw.config"),Bc=[0,5e3,5e3],Si="models.providers.",En="agents.defaults.models",Cn=class{command;env;retryDelaysMs;queue=new ft;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Bc}async withRetry(e,i){let a;for(let c=0;c<this.retryDelaysMs.length;c++){let u=this.retryDelaysMs[c]??0;u>0&&await new Promise(d=>setTimeout(d,u));try{return await i()}catch(d){a=d,vi.warn("openclaw cli failed, will retry",{label:e,attempt:c+1,err:String(d)})}}throw new E("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${a?.message??"unknown"}`)}runCli(e){return new Promise((i,a)=>{let c=Rc(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),u="";c.stderr?.on("data",d=>{u+=d.toString("utf8")}),c.on("error",a),c.on("close",d=>{d===0?i():a(new Error(`exit ${d}: ${u.trim().slice(0,500)}`))})})}async runCliTolerant(e,i){try{await this.runCli(e)}catch(a){let c=String(a);if(i.some(u=>c.includes(u)))return;throw a}}async bestEffortUnset(e,i){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",i])))}catch(a){vi.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",`${Si}${e}`,JSON.stringify(i),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Si}${e}`)}addModelToAllowlist(e,i){let a={[e]:i?{alias:i}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${En}[${e}]`,()=>this.runCli(["config","set",En,JSON.stringify(a),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${En}[${e}]`,`${En}.${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 je=N("agent-manager"),zc=(n,e,i,a,c,u,d)=>{switch(n){case"claude-code":{let h=c?{...Zs(c),...ti(c,d)}:void 0;return new bn({cwd:i,...h&&Object.keys(h).length>0?{env:h}:{}})}case"codex":{let h=c?[...Qs(c),...ri(c,d)]:[],p=c?ei(c):void 0,w=!!c;return new vn({cwd:i,...h.length>0?{extraArgs:h}:{},...p&&Object.keys(p).length>0?{env:p}:{},...w?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Ot({command:e,cwd:i,agentId:a,...u?{sessionName:Dt(u)}:{}})}};function Ci(n){return n==="claude-code"||n==="codex"}var qc={path:"",version:"cloud-deployed"},Fc={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Uc=6e4,An=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??zc,this.createTimeoutMs=e.createTimeoutMs??Uc}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new E("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=new Cn({command:e.path})}return this.openclawConfigCache}async createAgent(e){if(!e.agentId)throw new E("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new E("IPC_BAD_REQUEST","framework required");let i=Pt(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let a=this.registry.get(e.agentId);if(a){if(a.framework!==e.framework)throw new E("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${a.framework})`);if(a.status==="error")je.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await a.dispose("rebuild after error").catch(C=>je.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else return je.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:a.agentId,workspace:a.workspace,framework:a.framework}}if(!i&&!this.config.frameworksCache?.[e.framework])throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);i&&Ci(e.framework)&&await li(e.framework);let u=Te(e.agentId,this.paths),d=e.workspace??u.workspace,h=Pt(e._meta),p=new AbortController,w=setTimeout(()=>p.abort(new E("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 E("AGENT_TIMEOUT","_agent/create aborted")};await kr(u.root,{recursive:!0}),await kr(d,{recursive:!0}),await kr(u.logs,{recursive:!0}),C(),await ct(d,e.framework,e.agentId,e.cozeIdentity),C();let I=await xe(e.agentId,this.paths).catch(()=>null),L=Ys({model:e.model??I?.model});if(y=new Sn({agentId:e.agentId,framework:e.framework,workspace:d,model:L.model??He,deployType:h}),y.status="ok",I?.sessions){for(let[se,ee]of Object.entries(I.sessions))y.sessions.set(se,{acpSessionId:ee.acpSessionId,modelToken:ee.modelToken,tokenGeneratedAt:ee.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let q=Object.keys(I.sessions).length;q>0&&je.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:q})}this.registry.register(y),_=!0;let R={agentId:e.agentId,framework:e.framework,workspace:d,cozeIdentity:e.cozeIdentity,createdAt:I?.createdAt??Date.now(),sessions:I?.sessions??{},model:L.model};return h==="cloud"&&(R.deployType="cloud"),I?.skills&&(R.skills=I.skills),I?.agentName&&(R.agentName=I.agentName),I?.description&&(R.description=I.description),await pe(R,this.paths),e.framework==="openclaw"&&(this.config.frameworksCache?.openclaw?.path?await this.getOpenclawConfig().ensureAgent(e.agentId,d):je.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId})),je.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:h}),{ok:!0,agentId:e.agentId,workspace:d,framework:e.framework}}catch(C){throw je.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),_&&y&&(await y.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Mc(u.root,{recursive:!0,force:!0}).catch(I=>je.warn("rm agent dir failed (ignored)",{err:String(I)})),C instanceof E?C:new E("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(w)}}async spawnSessionDownstream(e,i,a,c){let d=this.config.frameworksCache?.[e.framework];if(!d)if(e.deployType==="cloud"&&Ci(e.framework))d=qc;else throw new E("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);let h=e.deployType==="cloud"?{model:e.model,modelToken:i}:void 0,p;e.framework==="openclaw"?p=await this.buildOpenclawDownstream({session:e,modelConfig:h,cloudSessionId:a,cozeEnv:c,command:d.path}):p=this.factory(e.framework,d.path,e.workspace,e.agentId,h,a,c);try{return await p.start(),await p.initialize(Fc),p}catch(w){throw await p.stop("spawnSessionDownstream failed").catch(()=>{}),w instanceof E?w:new E("AGENT_SPAWN_FAILED",w instanceof Error?w.message:String(w),{cause:w})}}async buildOpenclawDownstream(e){let{session:i,modelConfig:a,cloudSessionId:c,cozeEnv:u,command:d}=e,h=Dt(c),p=await Ei(),w=a?.modelToken&&!It(a.model)?ni(a,u):null,y;if(w){let _=Er(c),C=`${_}/${a.model}`;if(!this.ensuredProviders.has(C)){let I=this.getOpenclawConfig();await I.ensureProvider(_,w),await I.addModelToAllowlist(C),this.ensuredProviders.add(C)}y=C}return new Ot({command:d,cwd:i.workspace,agentId:i.agentId,sessionName:h,...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=Er(a),u=`${c}/${e.model}`;this.ensuredProviders.delete(u),await i.removeProvider(c),await i.removeModelFromAllowlist(u)}}};K();import{spawn as Hc}from"node:child_process";import{constants as Ai,access as Kc}from"node:fs/promises";import{delimiter as jc,join as Gc}from"node:path";var Wc=N("framework-detector"),ki={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Jc=[".exe",".cmd",".bat",".ps1"],lt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Hc,access:e.access??Kc}}async detect(e){let i=ki[e],a=await this.which(i);if(!a)return Wc.debug("framework binary not found",{framework:e,bin:i}),null;let c=await this.probeVersion(a);return{path:a,version:c}}async detectAll(){let e=await Promise.all(Object.keys(ki).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(jc).filter(Boolean),a=this.env.platform==="win32"?["",...Jc]:[""];for(let c of i)for(let u of a){let d=Gc(c,e+u);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let i=this.env.platform==="win32"?Ai.F_OK:Ai.X_OK;return await this.env.access(e,i),!0}catch{return!1}}async probeVersion(e){return new Promise(i=>{let a="",c=!1,u,d=h=>{c||(c=!0,u&&clearTimeout(u),i(h.trim()||"unknown"))};try{let h=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});u=setTimeout(()=>{h.kill("SIGKILL"),d("unknown")},5e3),h.stdout?.on("data",p=>{a+=p.toString("utf8")}),h.on("error",()=>d("unknown")),h.on("close",()=>{let p=Xc(a).split(/\r?\n/)[0]??"";d(p)})}catch{d("unknown")}})}},Vc=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Xc(n){return n.replace(Vc,"")}Zt();ce();var $c=10*6e4;function Pi(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?$c:e}function kn(n){return at(n??G().configFile)}function ht(n,e){return Yt(e??G().configFile,n)}import{randomBytes as ix}from"node:crypto";import{mkdir as Yc,readFile as Zc,realpath as Qc,writeFile as ex}from"node:fs/promises";import{basename as tx,dirname as Pr,join as nx,relative as rx,resolve as Di,sep as sx}from"node:path";K();var Ti=N("fs-rpc");async function Li(n,e){let i=await Ni(n.path,e);return await Yc(Pr(i),{recursive:!0}),await ex(i,n.content,"utf8"),Ti.info("fs/write_text_file ok",{path:i,size:n.content.length}),null}async function Ri(n,e){let i=await Ni(n.path,e),a=await Zc(i,"utf8"),c=a;if(typeof n.line=="number"||typeof n.limit=="number"){let u=a.split(`
94
- `),d=Math.max(0,(n.line??1)-1),h=typeof n.limit=="number"?d+n.limit:void 0;c=u.slice(d,h).join(`
95
- `)}return Ti.info("fs/read_text_file ok",{path:i,size:c.length}),{content:c}}async function Ni(n,e){if(typeof n!="string"||n.length===0)throw new E("IPC_BAD_REQUEST","path must be a non-empty string");let[i,a]=await Promise.all([Ii(Di(e)),Ii(Di(n))]),c=rx(i,a);if(c.startsWith("..")||c===".."||c.startsWith(`..${sx}`))throw new E("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return a}async function Ii(n){let e=[],i=n;for(;i!==Pr(i);)try{let a=await Qc(i);return e.length?nx(a,...e.reverse()):a}catch{e.push(tx(i)),i=Pr(i)}return n}Ue();K();var M=N("core"),ox=3e4,ax=3e4,Pn=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new dt;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=Pi(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(),M.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){M.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),M.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let i of this.registerHandlers)try{i(e.agentId)}catch(a){M.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)&&M.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,i,a){let c=a.downstream;c&&(c.onUpdate(u=>{a.loadingSession||this.forwardUpdate(e,u)}),c.onAgentRequest(u=>{this.handleAgentRequest(e,c,u)}),c.onExit((u,d)=>{M.info("session runtime exited",{agentId:e.agentId,cloudId:i,code:u,signal:d}),Bt(a),a.downstream=void 0,a.acpSessionId&&e.activeTriggers.delete(a.acpSessionId)}))}async handleFrame(e){if(_n(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,W.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):M.warn("drop notification: extension not registered",{method:e.method});return}let u=await c(e,this);i!==null&&await this.upstream.send(ut(i,u));return}if(e.method.startsWith("session/")){let c=await this.routeSessionMethod(e);i!==null&&await this.upstream.send(ut(i,c));return}if(e.method==="initialize"){i!==null&&await this.upstream.send(ut(i,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}i!==null?await this.sendError(i,W.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):M.warn("drop unknown notification",{method:e.method})}catch(c){M.error("handleFrame failed",{method:e.method,err:String(c)}),i!==null&&await this.upstream.send($e(i,Nt(c)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new E("IPC_BAD_REQUEST",`${e.method} requires params`);let i=e.params,a=i._meta?.cozeAgentId;if(!a)throw new E("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let c=this.agents.get(a);if(!c)throw this.disconnectedAgents.has(a)?new E("AGENT_DISCONNECTED",`agent ${a} has been disconnected; cloud must _agent/create to revive`):new E("AGENT_NOT_FOUND",`agent not found: ${a}`);let u=typeof i.sessionId=="string"?i.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!u)return this.dispatchSessionCall(c,e.method,i);let d=Date.now(),h=!1;try{let p=await c.getSessionQueue(u).enqueue(()=>this.dispatchSessionCall(c,e.method,i));return h=!0,p}finally{M.info("session call done",{agentId:c.agentId,method:e.method,durationMs:Date.now()-d,ok:h})}}async dispatchSessionCall(e,i,a){e.lastActiveAt=Date.now();let{stripped:c}=Hs(a);switch(i){case"session/new":{let u=cx();return M.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:u}),{sessionId:u}}case"session/load":{let u=c;return M.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:u.sessionId}),{}}case"session/prompt":{let u=c,d=u.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/prompt: missing sessionId");let h=await this.ensureRuntime(e,d);if(h.replySeq=0,await this.ensureDownstream(e,d,h),!h.downstream||!h.acpSessionId)throw new E("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let p=a._meta?.cozeTriggerMsgId;p?e.activeTriggers.set(h.acpSessionId,p):e.activeTriggers.delete(h.acpSessionId);try{let w=await h.downstream.sessionPrompt({...u,sessionId:h.acpSessionId});return h.lastActiveAt=Date.now(),w}finally{e.activeTriggers.delete(h.acpSessionId),h.downstream?.isAlive()&&this.armIdleTimer(e,d,h)}}case"session/cancel":{let d=c.sessionId;if(!d)throw new E("IPC_BAD_REQUEST","session/cancel: missing sessionId");let h=e.sessions.get(d);return h?.downstream?.isAlive()&&h.acpSessionId&&await h.downstream.sessionCancel({sessionId:h.acpSessionId}),{ok:!0}}default:throw new E("IPC_BAD_REQUEST",`session method not supported: ${i}`)}}async ensureRuntime(e,i){let a=e.sessions.get(i);if(a)return a;let u={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,i):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,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,ax);if(!c?.modelToken)throw new E("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${i})`);return c.modelToken}catch(c){throw c instanceof E&&c.code==="MODEL_TOKEN_GEN_FAILED"?c:new E("MODEL_TOKEN_GEN_FAILED",c instanceof Error?c.message:String(c),{cause:c})}}async ensureDownstream(e,i,a){if(Bt(a),a.downstream?.isAlive())return;if(!this.sessionSpawner)throw new E("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let c=await this.sessionSpawner(e,a.modelToken,i,this.currentCozeEnv);if(a.downstream=c,this.attachRuntimeHooks(e,i,a),a.acpSessionId){a.loadingSession=!0;try{await c.sessionLoad({sessionId:a.acpSessionId,cwd:e.workspace}),M.info("session restored via session/load",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId})}catch(u){M.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:i,acpId:a.acpSessionId,err:String(u)}),a.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});a.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{a.loadingSession=!1}}else{let u=await c.sessionNew({cwd:e.workspace});a.acpSessionId=u.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&a.acpSessionId&&await c.afterSessionEstablished(a.acpSessionId)}armIdleTimer(e,i,a){if(Bt(a),this.isRuntimeBusy(e,a)){M.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)){M.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:i}),this.armIdleTimer(e,i,a);return}M.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=>M.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){M.debug("drop update for unknown session",{agentId:e.agentId,acpId:a});return}let u=e.sessions.get(c);if(!u){M.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:c});return}if(xx(i)){M.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:a});return}let d={cozeAgentId:e.agentId,cozeReplySeqID:++u.replySeq},h=e.activeTriggers.get(a);h&&(d.cozeTriggerMsgId=h),this.upstream.send(mn("session/update",{...i,sessionId:c,_meta:d})).catch(p=>M.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}M.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:a.method}),i.respondAgentRequestError(a.id,{code:W.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${a.method}`})}async handleFsRpcRequest(e,i,a){try{let c=e.workspace;if(a.method==="fs/write_text_file"){let u=a.params??{},d=await Li(u,c);i.respondAgentRequest(a.id,d)}else{let u=a.params??{},d=await Ri(u,c);i.respondAgentRequest(a.id,d)}}catch(c){M.warn("fs rpc handler failed",{agentId:e.agentId,method:a.method,err:String(c)}),i.respondAgentRequestError(a.id,Nt(c))}}forwardPermissionRequest(e,i,a){let c=this.upstreamIds.next("session/request_permission"),u=a.params??{},h=u.sessionId,p=h?e.activeTriggers.get(h):void 0,w={cozeAgentId:e.agentId};p&&(w.cozeTriggerMsgId=p);let y=h?this.reverseSessionId(e,h):void 0,_={...u,...y?{sessionId:y}:{},_meta:w};this.pendingUpstream.set(c,{agentRequestId:a.id,agentId:e.agentId,downstream:i,method:a.method}),M.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:c,acpSessionId:h,cloudSessionId:y,toolCallId:u.toolCall?.toolCallId,options:u.options?.map(C=>({optionId:C.optionId,kind:C.kind,name:C.name}))}),this.upstream.send(Rt(c,"session/request_permission",_)).catch(C=>{this.pendingUpstream.delete(c),M.error("forward permission request failed",{agentId:e.agentId,err:String(C)}),i.respondAgentRequestError(a.id,{code:W.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?(M.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)):(M.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 wn(e.error)):a.resolve(e.result);return}M.debug("orphan upstream response (no pending)",{id:e.id})}sendRequest(e,i,a=ox){let c=this.upstreamIds.next(e);return new Promise((u,d)=>{let h=setTimeout(()=>{this.pendingBridge.delete(c),d(new E("AGENT_TIMEOUT",`${e} timed out after ${a}ms`))},a);this.pendingBridge.set(c,{method:e,resolve:u,reject:d,timer:h}),this.upstream.send(Rt(c,e,i)).catch(p=>{let w=this.pendingBridge.get(c);w&&(clearTimeout(w.timer),this.pendingBridge.delete(c)),d(p)})})}async persistSessionMapping(e){if(this.paths)try{let i=new Map;for(let[a,c]of e.sessions){let u={modelToken:c.modelToken,tokenGeneratedAt:c.tokenGeneratedAt};c.acpSessionId&&(u.acpSessionId=c.acpSessionId),i.set(a,u)}await br(e.agentId,i,this.paths)}catch(i){M.warn("persist session mapping failed",{agentId:e.agentId,err:String(i)})}}reverseSessionId(e,i){for(let[a,c]of e.sessions.entries())if(c.acpSessionId===i)return a}sendError(e,i,a){return this.upstream.send($e(e,{code:i,message:a}))}};function cx(){return ix(16).toString("hex")}function xx(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 `")}K();ce();import{randomBytes as ux}from"node:crypto";import{chmod as dx,mkdir as fx,writeFile as Oi}from"node:fs/promises";import{createServer as lx}from"node:http";import{dirname as hx}from"node:path";var gx=1e6,Dr=N("ipc"),Dn=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??G()}async start(){this.token=ux(32).toString("hex");let e=lx((a,c)=>{this.dispatch(a,c)});this.server=e,await new Promise((a,c)=>{e.once("error",c),e.listen(0,"127.0.0.1",()=>a())});let i=e.address();if(!i||typeof i!="object")throw new Error("failed to obtain IPC port");return this.port=i.port,await this.persistAuthFiles(),Dr.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 Oi(this.paths.portFile,String(this.port),"utf8"),await Oi(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await dx(this.paths.tokenFile,384)}catch(e){Dr.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,i){if(e.headers.authorization!==`Bearer ${this.token}`){Mt(i,401,{error:"unauthorized"});return}let c=`${e.method} ${(e.url??"").split("?")[0]}`,u=this.routes.get(c);if(!u){Mt(i,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await px(e)}catch(h){Mt(i,400,{error:"invalid json",detail:String(h)});return}try{let h=await u.handler(d,e);Mt(i,200,h??{ok:!0})}catch(h){Dr.error("IPC handler failed",{key:c,err:String(h)}),Mt(i,500,{error:h instanceof Error?h.message:String(h)})}}};function Mt(n,e,i){n.statusCode=e,n.setHeader("content-type","application/json"),n.end(JSON.stringify(i))}async function px(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 sa=Ie(Wi(),1);var Yu=Ie(Ho(),1),Zu=Ie(Gn(),1),Qu=Ie(mt(),1),ed=Ie(Hr(),1),td=Ie(Gr(),1),nd=Ie(Yr(),1),Yo=Ie(Xn(),1),rd=Ie($o(),1);var Zo=Yo.default;K();var Q=N("upstream.frontier"),ea="application/json",ta="none",Yn=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandler=null;opened=!1;openCount=0;async start(){if(this.fws){Q.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Gs,...an(this.opts.ppeOverride)};class i extends Zo{constructor(h){super(h,js,{headers:e})}send(h,...p){if(Fs("debug"))try{let w;typeof h=="string"?w=Buffer.from(h,"utf8"):h instanceof Buffer?w=h:h instanceof ArrayBuffer?w=new Uint8Array(h):ArrayBuffer.isView(h)?w=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):w=new Uint8Array(0);let y=Buffer.from(w.slice(0,128)).toString("hex");Q.debug("WS raw frame out",{bytes:w.byteLength,headHex:y})}catch(w){Q.warn("WS raw frame dump failed",{err:String(w)})}super.send(h,...p)}}let a=Vs(this.opts.urlOverride),c={url:a,ws:i,fpID:Ks,aID:on,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ea,force:!0},payloadEncoding:{encoding:ta,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,debug:this.opts.debug??!1},u=new sa.FWS(c);u.onopen=()=>{this.opened=!0,this.openCount+=1;let d=this.openCount===1;Q.info("frontier opened",{url:a,remoteDeviceId:this.opts.handshake.deviceId,initial:d,openCount:this.openCount}),this.connectHandler&&Promise.resolve(this.connectHandler({initial:d})).catch(h=>Q.warn("onConnect handler threw (ignored)",{err:String(h)}))},u.onclose=d=>{this.opened=!1,Q.info("frontier closed",{code:d.code,reason:d.reason,willReconnect:d.willReconnect})},u.onerror=d=>{Q.warn("frontier error",{code:d.code,msg:d.message})},u.onmessage=d=>this.handleMessage(d),this.fws=u,await u.connect()}async stop(e){let i=this.fws;if(i){this.fws=null,this.opened=!1;try{i.close(1e3,e??"bridge shutdown")}catch(a){Q.warn("frontier close threw (ignored)",{err:String(a)})}}}async send(e){let i=this.fws;if(!i)throw new E("UPSTREAM_DISCONNECTED","frontier upstream not started");let a=JSON.stringify(e),c=e;na(c)||Q.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:a.length});try{await i.send(a,{service:33555712,method:1,payloadType:ea,payloadEncoding:ta})}catch(d){throw Q.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(d)}),new E("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(d)}`,{cause:d})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandler=e}isConnected(){return this.opened&&this.fws?.readyState===1}handleMessage(e){let i=e.message?.service;if(i!==33555712){Q.debug("drop non-adapter frontier frame",{service:i});return}let a=ad(e);if(!a){Q.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Q.debug("frame received but no onFrame handler",{size:a.length});return}let c;try{c=JSON.parse(a)}catch(d){Q.warn("frontier message JSON parse failed",{err:String(d),head:a.slice(0,80)});return}let u=c;na(u)||Q.info("frontier frame in",{logid:od(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:u.id,method:u.method,body:id(a)}),Promise.resolve(this.handler(c)).catch(d=>Q.warn("frontier frame handler threw",{err:String(d)}))}};function na(n){return n.method==="_agent/health"?!0:typeof n.id=="string"&&n.id.startsWith("agent.health_")}var ra=2e3;function id(n){return n.length<=ra?n:`${n.slice(0,ra)}...<truncated, total ${n.length} chars>`}function od(n){return n?n.high===0?String(n.low>>>0):`${n.high.toString(16)}${(n.low>>>0).toString(16).padStart(8,"0")}`:""}function ad(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}}K();var Qr=N("upstream.switchable"),Zn=class{inner;handler=null;connectHandler=null;constructor(e){this.inner=e}async swap(e,i){if(this.inner===e)return;Qr.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 Qr.error("swap target start failed, reverting",{err:String(c)}),this.inner=a,c}await a.stop(i??"swapped").catch(c=>Qr.warn("previous upstream stop threw (ignored)",{err:String(c)}))}current(){return this.inner}start(){return this.inner.start()}stop(e){return this.inner.stop(e)}send(e){return this.inner.send(e)}onFrame(e){this.handler=e,this.inner.onFrame(e)}onConnect(e){this.connectHandler=e,this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};K();var es=N("upstream"),Wt=class{handler=null;async start(){es.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){es.info("NoopUpstream stopped",{reason:e})}async send(e){es.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();ce();K();ce();import{execSync as cd}from"node:child_process";import{readFileSync as ia,unlinkSync as xd}from"node:fs";import{mkdir as ud,readFile as oa,unlink as aa,writeFile as dd}from"node:fs/promises";import{dirname as fd}from"node:path";var ld=N("single-instance"),Qn=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??G().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&&(ld.warn("removing stale pid file",{stalePid:e}),await aa(this.pidFile).catch(()=>{})),await ud(fd(this.pidFile),{recursive:!0}),await dd(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await oa(this.pidFile,"utf8")).trim()===String(process.pid)&&await aa(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await oa(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=ia(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(i.includes("coze-bridge-daemon")||i.includes("lib/index.js"))}catch{}try{let i=cd(`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{ia(this.pidFile,"utf8").trim()===String(process.pid)&&xd(this.pidFile)}catch{}})}};var z=N("daemon"),hd="coze-bridge-daemon";async function ua(){let n=new Qn({processTitle:hd}),e=await n.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let i=await kn(),a=i??{};yr({pid:process.pid}),z.info(i?"loaded bridge config":"initialized bridge config");try{let P=new lt;a.frameworksCache=await P.detectAll(),z.info("refreshed frameworks_cache",{detected:Object.keys(a.frameworksCache)})}catch(P){z.warn("framework detection failed",{err:String(P)})}await ht(a);let c=new Zn(new Wt),u=G(),d=null,h=new Pn({upstream:c,paths:u,bridgeConfig:a,sessionSpawner:async(P,H,J,te)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,H,J,te)}});await pd(u,h);let p=new An({paths:u,config:a,registry:h});d=p;let w,y,_=null,C=null;h.registerExtension("_agent/create",async P=>p.createAgent(P.params)),h.registerExtension("_agent/health",async()=>({ok:!0}));let I={},L=new un({agents:h.agents,disposeAndMarkDisconnected:async(P,H)=>{let J=h.agents.get(P);J&&(await p.cleanupOpenclawSessionProviders(J).catch(te=>z.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(te)})),await J.dispose(`disconnect: ${H}`).catch(te=>z.warn("dispose during disconnect failed (ignored)",{agentId:P,err:String(te)})),J.status="disconnected",h.unregister(P)),h.disconnectedAgents.add(P)},detailSyncer:async P=>{if(!I.ref)throw new Error("agent-detail-sync not initialized yet");await I.ref.syncOne(P)},openclawRepair:async(P,H)=>{await p.openclawRepair(P,H)}});h.registerExtension("_agent/listSkills",P=>L.listSkills(P.params)),h.registerExtension("_agent/addSkills",P=>L.addSkills(P.params)),h.registerExtension("_agent/removeSkills",P=>L.removeSkills(P.params)),h.registerExtension("_agent/getFileTree",P=>L.getFileTree(P.params)),h.registerExtension("_agent/getFileContent",P=>L.getFileContent(P.params)),h.registerExtension("_agent/update",P=>L.updateAgent(P.params)),h.registerExtension("_agent/disconnect",P=>L.disconnectAgent(P.params)),h.registerExtension("_agent/switchModel",P=>L.switchModel(P.params)),h.registerExtension("_agent/reset",P=>L.resetAgent(P.params)),h.registerExtension("_agent/repair",P=>L.repairAgent(P.params));let R=new sn({paths:u,handlers:L,sendDetail:P=>h.sendRequest("_agent/detail",P)});I.ref=R,c.onConnect(({initial:P})=>{z.info("frontier upstream connected, triggering detail sync",{initial:P}),R.syncAll(P?"initial-connect":"reconnect").catch(H=>z.warn("detail sync top-level error (ignored)",{err:String(H)}))});let q=new Dn({paths:u,routes:[{method:"GET",path:"/status",handler:async()=>({running:!0,pid:process.pid,agents:[...h.agents.keys()],deviceId:_??"",frameworksCache:a.frameworksCache??{}})},{method:"POST",path:"/pair",handler:async P=>{let H=P,J=H?.privatecode,te=H?.pairing_code;if(!J||!te)throw new E("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let ke=cn(H.env),he=H.handshake_url,Ve=H.frontier_url,Et=gd(H.env,he,Ve),Jt=!!w&&w!==J,_e=y!==void 0&&y!==Et,ye=Jt||_e;if(ye){z.warn("pair config switched, resetting agents",{pcChanged:Jt,envChanged:_e,previousPc:w?ca(w):"",nextPc:ca(J),previousEnvKey:y??"",nextEnvKey:Et});for(let F of[...h.agents.values()])await F.dispose("pair config switch").catch(()=>{}),h.agents.delete(F.agentId);await c.swap(new Wt,"pair switch").catch(()=>{})}let Vt=await $s({privatecode:J,...he?{endpoint:he}:{},ppeOverride:ke});_=Vt.deviceId,yr({deviceId:_,pid:process.pid});let ie=new Yn({handshake:Vt,privatecode:J,...Ve?{urlOverride:Ve}:{},ppeOverride:ke});await c.swap(ie,"pair");try{let F=new lt;a.frameworksCache=await F.detectAll(),await ht(a),z.info("frameworks_cache refreshed before pair",{detected:Object.keys(a.frameworksCache)})}catch(F){z.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(F)})}let Xt=Object.keys(a.frameworksCache??{});try{let F=await h.sendRequest("_agent/pair",{pairCode:te,patToken:J,frameworks:Xt,_meta:{cozeDeviceId:_}});z.info("_agent/pair ok",{pairResult:F}),w=J,y=Et,C||(C=new ln({core:h,getDeviceId:()=>_??""})),C.start(),ye&&xa(u,p).catch(Pe=>z.warn("post-pair-switch auto-revive error (ignored)",{err:String(Pe)}));let V;return H.agent_id&&(V=await md(H.agent_id,u,p,Pe=>h.sendRequest("_agent/detail",Pe)).catch(Pe=>(z.error("--agent-id ensureAgent failed",{agentId:H.agent_id,err:String(Pe)}),{ok:!1,agentId:H.agent_id??"",note:String(Pe)}))),{ok:!0,note:"paired with cloud",...V?{agent:V}:{}}}catch(F){return z.error("_agent/pair failed",{err:String(F)}),{ok:!1,note:`pair failed: ${String(F)}`}}}},{method:"POST",path:"/_agent/create",handler:async P=>{let H=P;return{ok:!0,result:await p.createAgent(H)}}},{method:"POST",path:"/refresh",handler:async()=>{z.info("IPC /refresh: re-detecting frameworks");let P=new lt;return a.frameworksCache=await P.detectAll(),await ht(a),{ok:!0,frameworks:a.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(z.info("IPC /shutdown received"),setImmediate(()=>{ae.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:se,token:ee}=await q.start();await h.start(),xa(u,p).catch(P=>z.warn("auto-revive top-level error (ignored)",{err:String(P)}));let we=null,ae={port:se,token:ee,core:h,ipc:q,shutdown(P){return we||(z.info("daemon shutdown",{reason:P}),we=(async()=>{C?.stop(),await h.stop(P),await q.stop(),await n.release()})(),we)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{ae.shutdown(P).then(()=>process.exit(0))});return z.info("daemon ready",{port:se,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(a.frameworksCache??{}),libVersion:a.libVersion??"dev"}),ae}function ca(n){return n.length<=8?"***":`${n.slice(0,4)}***${n.slice(-4)}`}function gd(n,e,i){return`${n??""}|${e??""}|${i??""}`}async function pd(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(()=>(Ue(),rn));for(let d of a){await u(d,n).catch(h=>z.warn("enforceAgentConfigMode failed (ignored)",{agentId:d,err:String(h)}));try{let h=await c(d,n);h?.disconnectedAt&&(e.disconnectedAgents.add(d),z.info("agent marked disconnected on startup",{agentId:d,disconnectedAt:h.disconnectedAt,reason:h.disconnectReason??""}))}catch(h){z.warn("failed to load agent config on startup, skipping",{agentId:d,err:String(h)})}}}async function md(n,e,i,a){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(Ue(),rn)),u=await c(n,e);if(u){z.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"}}z.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:n});let d=await a({_meta:{cozeAgentId:n}});if(!d.framework)throw new E("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 h={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...d.deployType?{_meta:{cozeDeployType:d.deployType}}:{}};await i.createAgent(h);let p=d.deployType==="cloud"&&d.framework==="openclaw";return{ok:!0,agentId:n,note:p?"cloud agent acknowledged":"created from cloud detail"}}async function xa(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(()=>(Ue(),rn));z.info("auto-revive: scanning local agents on startup",{count:a.length});let u=0,d=0;for(let h of a){let p;try{p=await c(h,n)}catch(w){z.warn("auto-revive: load config failed (skipping)",{agentId:h,err:String(w)}),d+=1;continue}if(!p){d+=1;continue}if(p.disconnectedAt){z.info("auto-revive: skip disconnected agent",{agentId:h,disconnectedAt:p.disconnectedAt}),d+=1;continue}try{z.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:h,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){z.warn("auto-revive: createAgent failed (skipping)",{agentId:h,framework:p.framework,err:String(w)}),d+=1}}return z.info("auto-revive: done",{revived:u,skipped:d,total:a.length}),{revived:u,skipped:d,total:a.length}}ns();ce();import{readFile as fa}from"node:fs/promises";var Je=class{paths;constructor(e){this.paths=e??G()}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:Ad(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([fa(this.paths.portFile,"utf8"),fa(this.paths.tokenFile,"utf8")]),a=Number.parseInt(e.trim(),10),c=i.trim();return!Number.isFinite(a)||a<=0||!c?null:{port:a,token:c}}catch(e){if(e.code==="ENOENT")return null;throw e}}async fetch(e,i){let a=i.body!==void 0,c={Authorization:`Bearer ${e.token}`};a&&(c["content-type"]="application/json");let u=new AbortController,d=setTimeout(()=>u.abort(),i.timeoutMs??5e3);try{let h=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 h.text();return{status:h.status,body:Cd(p)}}finally{clearTimeout(d)}}};function Cd(n){if(!n)return null;try{return JSON.parse(n)}catch{return n}}function Ad(n){return n instanceof Error?n.message:String(n)}K();ce();import{copyFile as la,mkdir as kd,readFile as rs,writeFile as Pd}from"node:fs/promises";import{dirname as Dd,resolve as ss,sep as er}from"node:path";import{fileURLToPath as Id}from"node:url";K();ce();var ha=N("dist-install");function Td(n){let e=Id(n),i=Dd(e),a=`${er}src${er}`;if(i.includes(a)||i.endsWith(`${er}src${er}cli`))return null;let c=ss(i,"index.js"),u=ss(i,"..","package.json");return{dist:c,pkgJson:u}}async function ga(n={}){let e=n.paths??G(),i=Td(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 rs(c,"utf8")).version??"unknown"}catch(_){return ha.warn("cannot read source package.json,skip dist install",{err:String(_)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(_)}`}}let d=await kn(e.configFile)??{},h=d.libVersion;if(h===u)try{return await rs(e.libEntry),{kind:"already-current",libVersion:u}}catch{}await kd(e.libDir,{recursive:!0}),await la(a,e.libEntry),await la(`${a}.map`,`${e.libEntry}.map`).catch(()=>{});let p=ss(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
96
- `;return await rs(p,"utf8").catch(()=>null)!==w&&await Pd(p,w),d.libVersion=u,await ht(d,e.configFile),ha.info("dist installed",{libEntry:e.libEntry,fromVersion:h,toVersion:u}),h?{kind:"version-changed",fromVersion:h,toVersion:u,libEntry:e.libEntry}:{kind:"first-install",libVersion:u,libEntry:e.libEntry}}var $d=N("cli");function St(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 Yd(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}=St(i,"--pat-token");i=c;let{value:u,rest:d}=St(i,"--pair-code");i=d;let{value:h,rest:p}=St(i,"--env");i=p;let{value:w,rest:y}=St(i,"--handshake-url");i=y;let{value:_,rest:C}=St(i,"--frontier-url");i=C;let{value:I}=St(i,"--agent-id");if(!a||!u)return{mode:"help"};let L={mode:"pair",privatecode:a,pairingCode:u};return h&&(L.env=h),w&&(L.handshakeUrl=w),_&&(L.frontierUrl=_),I&&(L.agentId=I),L}var Zd=`
88
+ ${s}`}var ee=w("agent-detail-sync"),Lt=class{constructor(e){this.opts=e}opts;async syncAll(e){let t=this.opts.paths.agentsRoot,r;try{r=await Ga(t)}catch(s){ee.info("agents dir not found, skip detail sync",{root:t,err:String(s)});return}ee.info("starting detail sync",{reason:e,count:r.length});for(let s of r)try{await this.syncOne(s)}catch(i){ee.warn("detail sync failed for agent, skipping",{agentId:s,err:String(i)})}ee.info("detail sync done",{reason:e})}async syncOne(e){let t=await q(e,this.opts.paths);if(!t){ee.info("detail sync: agent config missing, skip",{agentId:e});return}let r;try{r=await this.opts.sendDetail({_meta:{cozeAgentId:e}})}catch(o){ee.warn("detail RPC failed, using local data",{agentId:e,err:String(o)});return}if(r.agentId&&r.agentId!==e){ee.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:r.agentId});return}let s=!1,i=!1;if(r.agentName&&r.agentName!==t.agentName&&(t.agentName=r.agentName,s=!0),r.description!==void 0&&r.description!==t.description&&(t.description=r.description,s=!0),r.cozeIdentity&&r.cozeIdentity!==t.cozeIdentity&&(t.cozeIdentity=r.cozeIdentity,s=!0,i=!0),r.deployType&&ee.info("detail.deployType",{agentId:e,deployType:r.deployType}),!s){ee.debug("detail sync: no diff",{agentId:e});return}await X(t,this.opts.paths),ee.info("detail sync: config updated",{agentId:e,identityChanged:i,agentName:t.agentName}),i&&(await Me(t.workspace,t.framework,e,t.cozeIdentity),await this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};ge();import{spawn as Ns}from"node:child_process";import{lstat as qn,mkdir as Ja,readFile as Ds,readdir as Va,rm as Qa,stat as Ka,writeFile as Os}from"node:fs/promises";import{join as re,normalize as Xa,relative as Ls,resolve as Ya,sep as Ms}from"node:path";var te={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 rt(n){return n?.cozeDeployType==="cloud"?"cloud":"local"}function gs(n){let{_meta:e,...t}=n;return{stripped:t,meta:e}}function Be(n){if(!n?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return n.cozeAgentId}var h=class extends Error{code;retriable;cause;constructor(e,t,r){super(t),this.name="BridgeError",this.code=e,this.retriable=r?.retriable??!1,r?.cause!==void 0&&(this.cause=r.cause)}};k();z();function ce(n,e){if(rt(n)!=="cloud")throw new h("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function st(n){return n.replace(/[^A-Za-z0-9._-]+/g,"-")}k();var Mt="1008033",ps="1289";var ms="pbbp2",_s="https://www.coze.cn",ws="/api/coze_claw/resource/get_frontier_key",Ha="https://www.coze.cn",Wa="wss://frontier.coze.cn";function ys(n){return n??process.env.COZE_BRIDGE_HANDSHAKE_URL??Ha}function Ss(n){return n??process.env.COZE_BRIDGE_FRONTIER_URL??Wa}function Bt(n){let e={},t=n?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,r=n?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return t&&(e["x-tt-env"]=t),r&&(e["x-use-ppe"]=r),e}function Ft(n){return n?n.startsWith("boe_")?{ttEnv:n}:{ttEnv:n,usePpe:"1"}:{}}var Es=w("handshake");async function vs(n){let e=ys(n.endpoint),t=n.timeoutMs??1e4,r=`${ja(e)}${ws}?aid=${encodeURIComponent(Mt)}`,s={Authorization:`Bearer ${n.privatecode}`,Accept:"application/json",...Bt(n.ppeOverride)},i=new AbortController,o=setTimeout(()=>i.abort(),t);Es.info("frontier key handshake",{base:e});try{let a=await fetch(r,{method:"GET",headers:s,signal:i.signal}),c=a.headers.get("x-tt-logid")??"",l=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let p=await a.text().catch(()=>"");throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${p.slice(0,200)}`)}let d=await a.json();if(d.code!==void 0&&d.code!==0)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${d.code} msg=${d.msg??"-"} logid=${c}`);let f=d.data?.access_key,u=d.data?.device_id;if(!f||!u)throw new h("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id logid=${c}: ${JSON.stringify(d)}`);return Es.info("handshake ok",{remoteDeviceId:u,logid:c,traceId:l}),{accessKey:f,deviceId:u}}catch(a){throw a instanceof h?a:a.name==="AbortError"?new h("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${t}ms)`):new h("UPSTREAM_HANDSHAKE_FAILED",String(a),{cause:a})}finally{clearTimeout(o)}}function ja(n){return n.endsWith("/")?n.slice(0,-1):n}var Un="https://llm-gateway.coze.cn",ne="auto";function ks(n){return{model:n.model??ne,...n.modelToken?{modelToken:n.modelToken}:{}}}function Is(n){return!n||n===ne}function xs(n){let e={};return n.modelToken?(e.ANTHROPIC_BASE_URL=Un,e.ANTHROPIC_AUTH_TOKEN=n.modelToken,e.ANTHROPIC_MODEL=n.model||ne):Is(n.model)||(e.ANTHROPIC_MODEL=n.model),e}function Ts(n){let e=[];return n.modelToken?e.push("-c",`model="${n.model||ne}"`):Is(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="${Un}/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 Rs(n){return n.modelToken?{OPENAI_API_KEY:n.modelToken}:{}}function $n(n){let{ttEnv:e,usePpe:t}=Ft(n),r={};return e&&(r["x-tt-env"]=e),t&&(r["x-use-ppe"]=t),r}function Ps(n,e){if(!n.modelToken)return{};let t=$n(e);return Object.keys(t).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(t).map(([s,i])=>`${s}:${i}`).join(`
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 r=t.trim();if(!r)continue;let s=r.charCodeAt(0);if(s!==45&&s!==100)throw new h("IPC_BAD_REQUEST",`tar entry kind '${r[0]}' not allowed (symlink/hardlink/special): ${r.slice(0,100)}`);let o=(r.match(/\s(\S.*)$/)?.[1]??"").split(" -> ")[0]?.trim()??"";if(!o)continue;if(o.startsWith("/"))throw new h("IPC_BAD_REQUEST",`tar entry absolute path: ${o}`);if(o.split(/[/\\]/).some(c=>c===".."))throw new h("IPC_BAD_REQUEST",`tar entry contains '..': ${o}`)}}async function Bs(n,e,t,r){if(r<=0)return[];let s;try{s=await Va(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(tc.has(o.name)||o.isSymbolicLink())continue;let a=re(e,o.name),c=Xa(re(t,o.name)),l=null;try{l=await qn(a)}catch{continue}if(l.isSymbolicLink())continue;let d={name:o.name,path:Fs(Ls(n,a)),isDir:l.isDirectory(),size:l.size,modifiedAt:Math.floor(l.mtimeMs)};l.isDirectory()&&r>1&&(d.children=await Bs(n,a,c,r-1)),i.push(d)}return i.sort((o,a)=>o.isDir!==a.isDir?o.isDir?-1:1:o.name.localeCompare(a.name)),i}function fc(n){return!n||n<=0?Za:Math.min(n,ec)}function hc(n){if(!n||n==="."||n==="/")return".";let e=n.split(/[/\\]/);return e[e.length-1]||"."}function Fs(n){return n.split(Ms).join("/")}k();import{readFileSync as gg}from"node:fs";import{dirname as mg,join as _g}from"node:path";import{fileURLToPath as yg}from"node:url";var zt="0.1.33";var ot=w("agent-health-reporter"),gc=1e4,qt=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??gc}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()}),ot.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),ot.info("heartbeat stopped"))}async tick(){if(this.inFlight){ot.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){ot.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let t=[];for(let s of this.opts.core.agents.values()){let i=pc(s);i&&t.push({agentId:s.agentId,status:i})}if(t.length===0)return;let r={agents:t,bridgeVersion:zt,_meta:{cozeDeviceId:e}};try{await this.opts.core.sendRequest("_agent/health",r)}catch(s){ot.warn("heartbeat batch send failed",{count:t.length,err:String(s)})}}finally{this.inFlight=!1}}};function pc(n){return n.status==="error"?"error":n.activeTriggers.size>0?"busy":n.status==="ok"?"online":null}ge();import{mkdir as jn,rm as Gc}from"node:fs/promises";k();import{execFile as mc}from"node:child_process";import{promisify as _c}from"node:util";var $s=_c(mc),at=w("agents.acp-installer"),wc={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp"}},yc=5e4,Sc=5e3,Ec=5*6e4,Ht=new Map,Gt=new Map,Wn=new Map;async function Us(n){let e=process.platform==="win32"?"where":"which";try{let{stdout:t}=await $s(e,[n],{timeout:Sc});return t.split(`
91
+ `)[0]?.trim()||void 0}catch{return}}async function vc(n){at.info("npm install -g start",{npmPackage:n}),await $s("npm",["install","-g",`${n}@latest`],{timeout:yc,maxBuffer:10*1024*1024}),at.info("npm install -g done",{npmPackage:n})}async function zs(n){let e=wc[n];if(!e)return;let t=Ht.get(n);if(t)return t;let r=Gt.get(n);if(r&&Date.now()-r<Ec)return;let s=Wn.get(n);if(s)return s;let i=(async()=>{let o=await Us(e.binary);if(o)return Ht.set(n,o),at.info("acp wrapper found on PATH",{binary:e.binary,path:o}),o;try{await vc(e.npmPackage)}catch(c){at.warn("acp wrapper install failed (will fallback to npx)",{npmPackage:e.npmPackage,err:String(c)}),Gt.set(n,Date.now());return}let a=await Us(e.binary);if(!a){at.warn("acp wrapper installed but binary not found on PATH",{binary:e.binary}),Gt.set(n,Date.now());return}return Ht.set(n,a),Gt.delete(n),a})().finally(()=>{Wn.delete(n)});return Wn.set(n,i),i}function Wt(n){return Ht.get(n)}import{spawn as Rc}from"node:child_process";function ct(n,e,t){return t===void 0?{jsonrpc:"2.0",id:n,method:e}:{jsonrpc:"2.0",id:n,method:e,params:t}}function jt(n,e){return e===void 0?{jsonrpc:"2.0",method:n}:{jsonrpc:"2.0",method:n,params:e}}function Fe(n,e){return{jsonrpc:"2.0",id:n,result:e}}function ve(n,e){return{jsonrpc:"2.0",id:n,error:e}}var Jt=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},R={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009};function qs(n){return"method"in n&&"id"in n&&n.id!==void 0}function Gs(n){return"method"in n&&!("id"in n)}function Vt(n){return!("method"in n)&&"id"in n}var kc={AGENT_NOT_FOUND:R.AGENT_NOT_FOUND,AGENT_BUSY:R.AGENT_BUSY,AGENT_DISCONNECTED:R.AGENT_DISCONNECTED,AGENT_TIMEOUT:R.AGENT_TIMEOUT,AGENT_SPAWN_FAILED:R.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:R.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:R.INTERNAL_ERROR,BRIDGE_INTERNAL:R.INTERNAL_ERROR,IPC_AUTH_FAILED:R.INTERNAL_ERROR,IPC_BAD_REQUEST:R.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:R.MODEL_TOKEN_GEN_FAILED,OPERATION_NOT_ALLOWED_FOR_LOCAL:R.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:R.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:R.INTERNAL_ERROR};function lt(n){return n instanceof h?{code:kc[n.code]??R.INTERNAL_ERROR,message:n.message,data:{bridgeCode:n.code,retriable:n.retriable}}:{code:R.INTERNAL_ERROR,message:n instanceof Error?n.message:String(n)}}function Hs(n){let e=n.data,t=e?.bridgeCode??"AGENT_PROTOCOL_ERROR";return new h(t,n.message,{retriable:e?.retriable??!1,cause:n.data})}function Ws(n){return`${JSON.stringify(n)}
92
+ `}var Qt=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){this.buffer+=typeof e=="string"?e:e.toString("utf8");let t=this.buffer.split(`
93
+ `);this.buffer=t.pop()??"";let r=[];for(let s of t){let i=s.replace(/\r$/,"").trim();if(i)try{r.push(JSON.parse(i))}catch(o){this.onError?.({line:i,error:o})}}return r}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(t){return this.onError?.({line:e,error:t}),[]}}};var 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}}k();import{spawn as tl}from"node:child_process";import{constants as si,access as nl}from"node:fs/promises";import{delimiter as rl,join as sl}from"node:path";var il=w("framework-detector"),ii={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},ol=[".exe",".cmd",".bat",".ps1"],ze=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??tl,access:e.access??nl}}async detect(e){let t=ii[e],r=await this.which(t);if(!r)return il.debug("framework binary not found",{framework:e,bin:t}),null;let s=await this.probeVersion(r);return{path:r,version:s}}async detectAll(){let e=await Promise.all(Object.keys(ii).map(async r=>[r,await this.detect(r)])),t={};for(let[r,s]of e)s&&(t[r]=s);return t}async which(e){let t=this.env.pathEnv.split(rl).filter(Boolean),r=this.env.platform==="win32"?["",...ol]:[""];for(let s of t)for(let i of r){let o=sl(s,e+i);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let t=this.env.platform==="win32"?si.F_OK:si.X_OK;return await this.env.access(e,t),!0}catch{return!1}}async probeVersion(e){return new Promise(t=>{let r="",s=!1,i,o=a=>{s||(s=!0,i&&clearTimeout(i),t(a.trim()||"unknown"))};try{let a=this.env.spawn(e,["--version"],{stdio:["ignore","pipe","pipe"]});i=setTimeout(()=>{a.kill("SIGKILL"),o("unknown")},5e3),a.stdout?.on("data",c=>{r+=c.toString("utf8")}),a.on("error",()=>o("unknown")),a.on("close",()=>{let c=cl(r).split(/\r?\n/)[0]??"";o(c)})}catch{o("unknown")}})}},al=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function cl(n){return n.replace(al,"")}At();z();var ll=10*6e4;function oi(n){let e=n?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?ll:e}function nn(n){return Le(n??T().configFile)}function qe(n,e){return Pt(e??T().configFile,n)}import{randomBytes as wl}from"node:crypto";import{mkdir as dl,readFile as ul,realpath as fl,writeFile as hl}from"node:fs/promises";import{basename as gl,dirname as Vn,join as pl,relative as ml,resolve as ai,sep as _l}from"node:path";k();var li=w("fs-rpc");async function di(n,e){let t=await fi(n.path,e);return await dl(Vn(t),{recursive:!0}),await hl(t,n.content,"utf8"),li.info("fs/write_text_file ok",{path:t,size:n.content.length}),null}async function ui(n,e){let t=await fi(n.path,e),r=await ul(t,"utf8"),s=r;if(typeof n.line=="number"||typeof n.limit=="number"){let i=r.split(`
95
+ `),o=Math.max(0,(n.line??1)-1),a=typeof n.limit=="number"?o+n.limit:void 0;s=i.slice(o,a).join(`
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 Qr(c,"utf8").catch(()=>null)!==l&&await $f(c,l),o.libVersion=i,await qe(o,e.configFile),ua.info("dist installed",{libEntry:e.libEntry,fromVersion:a,toVersion:i}),a?{kind:"version-changed",fromVersion:a,toVersion:i,libEntry:e.libEntry}:{kind:"first-install",libVersion:i,libEntry:e.libEntry}}var ch=w("cli");function et(n,e){let t=[],r;for(let s=0;s<n.length;s++){let i=n[s];if(i===e){r=n[s+1],s+=1;continue}if(i.startsWith(`${e}=`)){r=i.slice(e.length+1);continue}t.push(i)}return{value:r,rest:t}}function lh(n){let e=n.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e.includes("--status"))return{mode:"status"};if(e.includes("--stop"))return{mode:"stop"};if(e.includes("--refresh"))return{mode:"refresh"};if(e.includes("--uninstall"))return{mode:"uninstall"};if(e.includes("--install-service"))return{mode:"install-service"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let t=e,{value:r,rest:s}=et(t,"--pat-token");t=s;let{value:i,rest:o}=et(t,"--pair-code");t=o;let{value:a,rest:c}=et(t,"--env");t=c;let{value:l,rest:d}=et(t,"--handshake-url");t=d;let{value:f,rest:u}=et(t,"--frontier-url");t=u;let{value:p}=et(t,"--agent-id");if(!r||!i)return{mode:"help"};let m={mode:"pair",privatecode:r,pairingCode:i};return a&&(m.env=a),l&&(m.handshakeUrl=l),f&&(m.frontierUrl=f),p&&(m.agentId=p),m}var dh=`
97
98
  coze-bridge - local bridge daemon for cloud Agent Service
98
99
 
99
100
  Usage:
@@ -121,36 +122,36 @@ Auto-connect agent (optional):
121
122
 
122
123
  Internal:
123
124
  <node> <entry> --daemon daemon mode (OS supervisor only)
124
- `.trimStart();async function ba(n=process.argv,e={}){let i=Yd(n);switch(i.mode){case"help":return process.stdout.write(Zd),0;case"version":return process.stdout.write(`${fn}
125
- `),0;case"daemon":{try{await ua()}catch(a){return $d.error("daemon start failed",{err:String(a)}),1}return new Promise(()=>{})}case"status":return Qd(e);case"stop":return ef(e);case"refresh":return tf(e);case"uninstall":return nf(e);case"install-service":return rf();case"pair":{let a={};return i.env&&(a.env=i.env),i.handshakeUrl&&(a.handshakeUrl=i.handshakeUrl),i.frontierUrl&&(a.frontierUrl=i.frontierUrl),sf(i.privatecode,i.pairingCode,e,a,i.agentId)}}}async function va(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 Qd(n){let e=n.paths??G(),i=new Je(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
126
- `),1;if(a.kind==="stale")return await va(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
127
- `),1;let c=await i.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
128
- ${JSON.stringify(c.body,null,2)}
129
- `),0}async function ef(n){let e=n.paths??G(),i=new Je(e),a=await i.probe();if(a.kind==="not-running")return process.stdout.write(`coze-bridge: not running
130
- `),0;if(a.kind==="stale")return await va(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
131
- `),0;try{return await i.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
132
- `),0}catch(c){return process.stdout.write(`coze-bridge: stop failed: ${String(c)}
133
- `),1}}async function tf(n){let e=new Je(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
134
- `),1;try{let a=await e.request({method:"POST",path:"/refresh"});return a.status===200?(process.stdout.write(`coze-bridge: refreshed
135
- ${JSON.stringify(a.body,null,2)}
136
- `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(a.body)}
137
- `),1)}catch(a){return process.stderr.write(`coze-bridge: refresh failed: ${String(a)}
138
- `),1}}async function nf(n){let e=new Je(n.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
139
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(u){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(u)}
140
- `)}await new Promise(u=>setTimeout(u,500))}if(!n.skipSupervisor)try{let{getSupervisor:u,buildContext:d}=await Promise.resolve().then(()=>(ds(),us)),h=u();await h.uninstall(d()),process.stdout.write(`coze-bridge: ${h.platform} supervisor unregistered
141
- `)}catch(u){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(u)}
142
- `)}let a=n.paths??G(),{rm:c}=await import("node:fs/promises");try{await c(a.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${a.cozeRoot}
143
- `)}catch(u){return process.stderr.write(`coze-bridge: remove failed: ${String(u)}
125
+ `.trimStart();async function wa(n=process.argv,e={}){let t=lh(n);switch(t.mode){case"help":return process.stdout.write(dh),0;case"version":return process.stdout.write(`${zt}
126
+ `),0;case"daemon":{try{await aa()}catch(r){return ch.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return uh(e);case"stop":return fh(e);case"refresh":return hh(e);case"uninstall":return gh(e);case"install-service":return ph();case"pair":{let r={};return t.env&&(r.env=t.env),t.handshakeUrl&&(r.handshakeUrl=t.handshakeUrl),t.frontierUrl&&(r.frontierUrl=t.frontierUrl),mh(t.privatecode,t.pairingCode,e,r,t.agentId)}}}async function ya(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 uh(n){let e=n.paths??T(),t=new Ee(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
127
+ `),1;if(r.kind==="stale")return await ya(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
128
+ `),1;let s=await t.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
129
+ ${JSON.stringify(s.body,null,2)}
130
+ `),0}async function fh(n){let e=n.paths??T(),t=new Ee(e),r=await t.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
131
+ `),0;if(r.kind==="stale")return await ya(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
132
+ `),0;try{return await t.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
133
+ `),0}catch(s){return process.stdout.write(`coze-bridge: stop failed: ${String(s)}
134
+ `),1}}async function hh(n){let e=new Ee(n.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
135
+ `),1;try{let r=await e.request({method:"POST",path:"/refresh"});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
136
+ ${JSON.stringify(r.body,null,2)}
137
+ `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
138
+ `),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
139
+ `),1}}async function gh(n){let e=new Ee(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(i){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(i)}
141
+ `)}await new Promise(i=>setTimeout(i,500))}if(!n.skipSupervisor)try{let{getSupervisor:i,buildContext:o}=await Promise.resolve().then(()=>(rs(),ns)),a=i();await a.uninstall(o()),process.stdout.write(`coze-bridge: ${a.platform} supervisor unregistered
142
+ `)}catch(i){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(i)}
143
+ `)}let r=n.paths??T(),{rm:s}=await import("node:fs/promises");try{await s(r.cozeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${r.cozeRoot}
144
+ `)}catch(i){return process.stderr.write(`coze-bridge: remove failed: ${String(i)}
144
145
  `),1}return process.stdout.write(`coze-bridge: uninstalled
145
- `),0}async function rf(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(ds(),us)),i=n(),a=e();return process.stdout.write(`coze-bridge: installing ${i.platform} supervisor...
146
- `),await i.install(a),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
146
+ `),0}async function ph(){try{let{getSupervisor:n,buildContext:e}=await Promise.resolve().then(()=>(rs(),ns)),t=n(),r=e();return process.stdout.write(`coze-bridge: installing ${t.platform} supervisor...
147
+ `),await t.install(r),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
147
148
  `),0}catch(n){return process.stderr.write(`coze-bridge: --install-service failed: ${String(n)}
148
- `),1}}async function sf(n,e,i,a={},c){let u=new Je(i.paths),d=i.spawnDaemon??da;if(!i.skipDistInstall){let w=await ga({paths:i.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
149
- `),(await u.probe()).kind==="connected"&&(await u.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(_=>setTimeout(_,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
150
- `)}let h=await u.probe();if(h.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
151
- `),await d({paths:i.paths}),h=await of(u,i.waitTimeoutMs??1e4,i.sleep??af),h.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
152
- `),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"})
153
- `),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(w.body)}
154
- `),1)}catch(w){return process.stderr.write(`coze-bridge: pair failed: ${String(w)}
155
- `),1}}async function of(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 af(n){return new Promise(e=>setTimeout(e,n))}ba(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
149
+ `),1}}async function mh(n,e,t,r={},s){let i=new Ee(t.paths),o=t.spawnDaemon??ca;if(!t.skipDistInstall){let l=await fa({paths:t.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
150
+ `),(await i.probe()).kind==="connected"&&(await i.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(f=>setTimeout(f,500)))):l.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${l.libVersion}
151
+ `)}let a=await i.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
152
+ `),await o({paths:t.paths}),a=await _h(i,t.waitTimeoutMs??1e4,t.sleep??wh),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
153
+ `),1;let c={privatecode:n,pairing_code:e};r.env&&(c.env=r.env),r.handshakeUrl&&(c.handshake_url=r.handshakeUrl),r.frontierUrl&&(c.frontier_url=r.frontierUrl),s&&(c.agent_id=s);try{let l=await i.request({method:"POST",path:"/pair",body:c,timeoutMs:35e3});return l.status===200&&l.body?.ok?(process.stdout.write(`coze-bridge: paired (${l.body.note??"ok"})
154
+ `),0):(process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(l.body)}
155
+ `),1)}catch(l){return process.stderr.write(`coze-bridge: pair failed: ${String(l)}
156
+ `),1}}async function _h(n,e,t){let r=Date.now()+e;for(;Date.now()<r;){let s=await n.probe(500);if(s.kind==="connected")return s;await t(200)}return n.probe(500)}function wh(n){return new Promise(e=>setTimeout(e,n))}wa(process.argv).then(n=>process.exit(n),n=>{process.stderr.write(`fatal: ${n instanceof Error?n.stack??n.message:String(n)}
156
157
  `),process.exit(1)});