coze-bridge 0.1.104-beta.1 → 0.2.0-alpha.0

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 +85 -83
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,34 +5,34 @@ 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 eg=Object.create;var _a=Object.defineProperty;var tg=Object.getOwnPropertyDescriptor;var ng=Object.getOwnPropertyNames;var rg=Object.getPrototypeOf,ig=Object.prototype.hasOwnProperty;var ue=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Je=(t,e)=>()=>(t&&(e=t(t=0)),e);var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ya=(t,e)=>{for(var r in e)_a(t,r,{get:e[r],enumerable:!0})},sg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ng(e))!ig.call(t,o)&&o!==r&&_a(t,o,{get:()=>e[o],enumerable:!(i=tg(e,o))||i.enumerable});return t};var zt=(t,e,r)=>(r=t!=null?eg(rg(t)):{},sg(e||!t||!t.__esModule?_a(r,"default",{value:t,enumerable:!0}):r,t));function qe(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var nr=Je(()=>{"use strict"});import{createWriteStream as og,mkdirSync as ag,readdirSync as cg,unlinkSync as dg}from"node:fs";import{join as dl}from"node:path";function kn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function rr(t,e){return`${t}-${e}.log`}function ba(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function lg(t,e,r){let i=c=>{let[l,u,x]=c.split("-").map(Number);return Date.UTC(l??0,(u??1)-1,x??1)};return Math.floor((i(e)-i(t))/864e5)>r}function is(t,e,r,i){let o;try{o=cg(t)}catch{return}for(let c of o){let l=ba(c,e);if(l&&lg(l,r,i))try{dg(dl(t,c))}catch{}}}var Yr,Ea=Je(()=>{"use strict";Yr=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>kn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{ag(this.dir,{recursive:!0});let r=og(dl(this.dir,rr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
8
+ var mg=Object.create;var ba=Object.defineProperty;var wg=Object.getOwnPropertyDescriptor;var _g=Object.getOwnPropertyNames;var yg=Object.getPrototypeOf,bg=Object.prototype.hasOwnProperty;var le=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Qe=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ea=(t,e)=>{for(var r in e)ba(t,r,{get:e[r],enumerable:!0})},Eg=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of _g(e))!bg.call(t,o)&&o!==r&&ba(t,o,{get:()=>e[o],enumerable:!(i=wg(e,o))||i.enumerable});return t};var Ut=(t,e,r)=>(r=t!=null?mg(yg(t)):{},Eg(e||!t||!t.__esModule?ba(r,"default",{value:t,enumerable:!0}):r,t));function Ke(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var ir=Qe(()=>{"use strict"});import{createWriteStream as vg,mkdirSync as Sg,readdirSync as Ig,unlinkSync as Ag}from"node:fs";import{join as gl}from"node:path";function Pn(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function sr(t,e){return`${t}-${e}.log`}function va(t,e){let r=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!r||r[1]!==e?null:r[2]??null}function kg(t,e,r){let i=c=>{let[d,u,f]=c.split("-").map(Number);return Date.UTC(d??0,(u??1)-1,f??1)};return Math.floor((i(e)-i(t))/864e5)>r}function as(t,e,r,i){let o;try{o=Ig(t)}catch{return}for(let c of o){let d=va(c,e);if(d&&kg(d,r,i))try{Ag(gl(t,c))}catch{}}}var Qr,Sa=Qe(()=>{"use strict";Qr=class{constructor(e,r,i){this.dir=e;this.prefix=r;this.opts=i;this.clock=i.clock??(()=>Pn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let r=this.clock();r!==this.currentDate&&this.rotate(r),this.stream?.write(e)}rotate(e){this.stream?.end();try{Sg(this.dir,{recursive:!0});let r=vg(gl(this.dir,sr(this.prefix,e)),{flags:"a"});r.on("error",i=>process.stderr.write(`[log-sink] stream error: ${String(i)}
9
9
  `)),this.stream=r}catch(r){process.stderr.write(`[log-sink] rotate failed: ${String(r)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&is(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as ug,mkdirSync as fg}from"node:fs";import{join as xg}from"node:path";function ul(t){let e=t.retentionDays??gg,r=t.clock??(()=>kn(new Date));os={bridgeSink:new Yr(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new Yr(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();is(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])is(t.agentLogsDir(o),"agent",i,e)}function mg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function fl(t){va=t}function xl(t){return ir[va]<=ir[t]}function hl(t,e){let r=ir[t];return r===void 0?!0:r>=ir[e]}function as(t){ll={...t}}function pl(t){let e=(u,x=2)=>String(u).padStart(x,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),l=e(o%60);return`${kn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${l}`}function It(t,e,r,i,o){try{let c=`${JSON.stringify({ts:pl(new Date),level:e,module:r,msg:i,...o})}
11
- `;fg(t,{recursive:!0}),ug(xg(t,rr("bridge",kn(new Date))),c)}catch{}}function wg(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function ss(t,e,r,i,o){if(ir[t]<ir[va])return;let c=`${JSON.stringify({ts:pl(new Date),level:t,module:e,msg:r,...ll,...i})}
12
- `;if(os){let l=wg(o,i),u=l?mg(os,l):os.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?pg.write(c):hg.write(c)}function G(t,e){return{debug:(r,i)=>ss("debug",t,r,i,e),info:(r,i)=>ss("info",t,r,i,e),warn:(r,i)=>ss("warn",t,r,i,e),error:(r,i)=>ss("error",t,r,i,e),child:r=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var ir,va,hg,pg,ll,gg,os,ne=Je(()=>{"use strict";nr();Ea();ir={debug:10,info:20,warn:30,error:40},va=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),hg=process.stdout,pg=process.stderr,ll={},gg=qe("COZE_BRIDGE_LOG_RETENTION_DAYS",30),os=null});var T,je=Je(()=>{"use strict";T=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var _l={};ya(_l,{ACP_WRAPPER_NPM_PACKAGES:()=>Qr,_resetAcpInstallerForTests:()=>Sg,_setBinaryPathCacheForTests:()=>Ig,buildAcpSpawn:()=>ei,ensureAcpInstalled:()=>sr,getAcpBinaryPath:()=>cs,pickWhichLine:()=>Aa,probeAcpVersion:()=>vg,resolveAcpCommand:()=>wl});import{readFileSync as gl}from"node:fs";import{createRequire as _g}from"node:module";import{dirname as yg,resolve as bg}from"node:path";function Aa(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function Eg(t){let e=ml.resolve(`${t.npmPackage}/package.json`),r=yg(e),i=JSON.parse(gl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return bg(r,o)}async function sr(t,e){let r=Ia[t];if(!r)throw new T("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=Xr.get(t);if(i)return i;try{let o=Eg(r);return Xr.set(t,o),Sa.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Sa.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new T("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
- `),{cause:o})}}async function vg(t){let e=Ia[t];if(e)try{let r=ml.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(gl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Sa.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function cs(t){return Xr.get(t)}function wl(t,e){if(e)return e;let r=cs(t);if(!r)throw new T("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ei(t,e,r){if(e)return{command:e,args:[...r]};let i=wl(t);return{command:process.execPath,args:[i,...r]}}function Sg(){Xr.clear()}function Ig(t,e){Xr.set(t,e)}var Sa,Ia,Qr,ml,Xr,rn=Je(()=>{"use strict";je();ne();Sa=G("agents.acp-installer"),Ia={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},Qr=Object.values(Ia).filter(t=>t!==void 0).map(t=>t.npmPackage),ml=_g(import.meta.url),Xr=new Map});import{chmod as Tg,mkdir as Cg,readFile as Rg,rename as kg,rm as Pg,writeFile as Dg}from"node:fs/promises";import{dirname as Og}from"node:path";async function or(t){try{let e=await Rg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function sn(t,e,r){await Cg(Og(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Dg(i,e,{encoding:"utf8",mode:r?.mode}),await kg(i,t),r?.mode!==void 0&&await Tg(t,r.mode)}catch(o){throw await Pg(i,{force:!0}).catch(()=>{}),o}}async function ar(t,e,r){await sn(t,`${JSON.stringify(e,null,2)}
14
- `,r)}var on=Je(()=>{"use strict"});import{promises as El,readdirSync as Lg}from"node:fs";import{homedir as Ng}from"node:os";import{sep as Mg,join as Ae,resolve as vl}from"node:path";function Q(t){let e=t??Ng(),r=Ae(e,".coze"),i=Ae(r,"bridge"),o=Ae(i,"lib"),c=Ae(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ae(o,"index.js"),binDir:Ae(i,"bin"),pidFile:Ae(i,"bridge.pid"),portFile:Ae(i,"bridge.port"),tokenFile:Ae(i,"bridge.token"),patTokenFile:Ae(i,"pat-token"),agentEnvFile:Ae(i,"agent-env.json"),logFile:Ae(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ae(c,"daemon-stdio.log"),installLock:Ae(i,"install.lock"),configFile:Ae(i,"config.json"),agentsRoot:Ae(r,"agents")}}function Ye(t,e=Q()){let r=Ae(e.agentsRoot,t);return{root:r,config:Ae(r,"config.json"),workspace:Ae(r,"workspace"),logs:Ae(r,"logs")}}function ds(t=Q()){try{return Lg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ti(t,e){let r=await El.realpath(vl(t)).catch(()=>null);if(!r)return!1;let i=await El.realpath(vl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Mg)}var Pe=Je(()=>{"use strict"});var fs={};ya(fs,{AGENT_CONFIG_FILE_MODE:()=>ls,enforceAgentConfigMode:()=>zg,loadAgentConfig:()=>Ne,persistAgentSessions:()=>ni,persistAgentSkills:()=>us,saveAgentConfig:()=>Xe});import{chmod as Bg,stat as Fg}from"node:fs/promises";function Ne(t,e){return or(Ye(t,e).config)}function Xe(t,e){return ar(Ye(t.agentId,e).config,t,{mode:ls})}async function zg(t,e){if(process.platform==="win32")return;let r=Ye(t,e).config;try{let i=await Fg(r);if(!i.isFile())return;let o=i.mode&511;o!==ls&&(await Bg(r,ls),Sl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Sl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ni(t,e,r){let i=await Ne(t,r);i&&(i.sessions=Object.fromEntries(e),await Xe(i,r))}async function us(t,e,r){let i=await Ne(t,r);i&&(i.skills=e,await Xe(i,r))}var Sl,ls,an=Je(()=>{"use strict";on();ne();Pe();Sl=G("agent-config"),ls=384});var Ra=ae((S1,Tl)=>{Tl.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var hs=ae(Rl=>{var Cl={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function Wg(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Cl))Rl[t]=Wg(Cl[t])});var Ll=ae((A1,Ol)=>{var Kg=ue("fs"),De=ue("path"),kl=Ra(),$g=hs(),Vg=typeof process=="object"&&process.platform==="win32",Pl=t=>typeof t=="object"&&t!==null,Dl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function be(t){this.sep=De.sep,this.fs=Kg,Pl(t)&&Pl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ol.exports=be;be.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var l;try{l=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(l&&l.isFile())throw $g.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};be.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var l=De.dirname(t);o.fs.existsSync(l)||o.makeDir(l);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};be.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(l){if(l&&!r)return o(!1);c.fs.stat(t,function(u,x){if(l&&x.isDirectory())return o(!1);var h=De.dirname(t);c.fs.exists(h,function(w){w||c.makeDir(h),c.fs.open(t,"w",438,function(_,v){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(y,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};be.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let l=[];return e.fs.readdirSync(i).forEach(function(u){let x=De.join(i,u),h=e.fs.statSync(x);(!o||o.test(x))&&l.push(De.normalize(x)+(h.isDirectory()?e.sep:"")),h.isDirectory()&&c&&(l=l.concat(r(x,o,c)))}),l}return r(t,void 0,!0)};be.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let l=c.length;if(!l)return e(null,i);c.forEach(function(u){u=De.join(t,u),r.fs.stat(u,function(x,h){if(x)return e(x);h&&(i.push(De.normalize(u)+(h.isDirectory()?r.sep:"")),h.isDirectory()?r.findFilesAsync(u,function(w,_){if(w)return e(w);i=i.concat(_),--l||e(null,i)}):--l||e(null,i))})})})};be.prototype.getAttributes=function(){};be.prototype.setAttributes=function(){};be.crc32update=function(t,e){return Dl[(t^e)&255]^t>>>8};be.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=be.crc32update(r,t[i++]);return~r>>>0};be.methodToString=function(t){switch(t){case kl.STORED:return"STORED ("+t+")";case kl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};be.canonical=function(t){if(!t)return"";let e=De.posix.normalize("/"+t.split("\\").join("/"));return De.join(".",e)};be.zipnamefix=function(t){if(!t)return"";let e=De.posix.normalize("/"+t.split("\\").join("/"));return De.posix.join(".",e)};be.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};be.sanitize=function(t,e){t=De.resolve(De.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=De.normalize(De.join(t,r.slice(i,o).join(De.sep)));if(c.indexOf(t)===0)return c}return De.normalize(De.join(t,De.basename(e)))};be.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};be.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};be.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};be.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};be.isWin=Vg;be.crcTable=Dl});var Ml=ae((T1,Nl)=>{var Zg=ue("path");Nl.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=Zg.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Fl=ae((C1,Bl)=>{Bl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var lr=ae((R1,dr)=>{dr.exports=Ll();dr.exports.Constants=Ra();dr.exports.Errors=hs();dr.exports.FileAttr=Ml();dr.exports.decoder=Fl()});var Ul=ae((k1,zl)=>{var cn=lr(),H=cn.Constants;zl.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,l=0,u=0,x=0,h=0,w=0,_=0,v=0,y=0,E=0;t|=cn.isWin?2560:768,r|=H.FLG_EFS;let I={extraLen:0},A=b=>Math.max(0,b)>>>0,C=b=>Math.max(0,b)&65535,P=b=>Math.max(0,b)&255;return o=cn.fromDate2DOS(new Date),{get made(){return t},set made(b){t=b},get version(){return e},set version(b){e=b},get flags(){return r},set flags(b){r=b},get flags_efs(){return(r&H.FLG_EFS)>0},set flags_efs(b){b?r|=H.FLG_EFS:r&=~H.FLG_EFS},get flags_desc(){return(r&H.FLG_DESC)>0},set flags_desc(b){b?r|=H.FLG_DESC:r&=~H.FLG_DESC},get method(){return i},set method(b){switch(b){case H.STORED:this.version=10;case H.DEFLATED:default:this.version=20}i=b},get time(){return cn.fromDOS2Date(this.timeval)},set time(b){b=new Date(b),this.timeval=cn.fromDate2DOS(b)},get timeval(){return o},set timeval(b){o=A(b)},get timeHighByte(){return P(o>>>8)},get crc(){return c},set crc(b){c=A(b)},get compressedSize(){return l},set compressedSize(b){l=A(b)},get size(){return u},set size(b){u=A(b)},get fileNameLength(){return x},set fileNameLength(b){x=b},get extraLength(){return h},set extraLength(b){h=b},get extraLocalLength(){return I.extraLen},set extraLocalLength(b){I.extraLen=b},get commentLength(){return w},set commentLength(b){w=b},get diskNumStart(){return _},set diskNumStart(b){_=A(b)},get inAttr(){return v},set inAttr(b){v=A(b)},get attr(){return y},set attr(b){y=A(b)},get fileAttr(){return(y||0)>>16&4095},get offset(){return E},set offset(b){E=A(b)},get encrypted(){return(r&H.FLG_ENC)===H.FLG_ENC},get centralHeaderSize(){return H.CENHDR+x+h+w},get realDataOffset(){return E+H.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(b){var k=b.slice(E,E+H.LOCHDR);if(k.readUInt32LE(0)!==H.LOCSIG)throw cn.Errors.INVALID_LOC();I.version=k.readUInt16LE(H.LOCVER),I.flags=k.readUInt16LE(H.LOCFLG),I.flags_desc=(I.flags&H.FLG_DESC)>0,I.method=k.readUInt16LE(H.LOCHOW),I.time=k.readUInt32LE(H.LOCTIM),I.crc=k.readUInt32LE(H.LOCCRC),I.compressedSize=k.readUInt32LE(H.LOCSIZ),I.size=k.readUInt32LE(H.LOCLEN),I.fnameLen=k.readUInt16LE(H.LOCNAM),I.extraLen=k.readUInt16LE(H.LOCEXT);let D=E+H.LOCHDR+I.fnameLen,z=D+I.extraLen;return b.slice(D,z)},loadFromBinary:function(b){if(b.length!==H.CENHDR||b.readUInt32LE(0)!==H.CENSIG)throw cn.Errors.INVALID_CEN();t=b.readUInt16LE(H.CENVEM),e=b.readUInt16LE(H.CENVER),r=b.readUInt16LE(H.CENFLG),i=b.readUInt16LE(H.CENHOW),o=b.readUInt32LE(H.CENTIM),c=b.readUInt32LE(H.CENCRC),l=b.readUInt32LE(H.CENSIZ),u=b.readUInt32LE(H.CENLEN),x=b.readUInt16LE(H.CENNAM),h=b.readUInt16LE(H.CENEXT),w=b.readUInt16LE(H.CENCOM),_=b.readUInt16LE(H.CENDSK),v=b.readUInt16LE(H.CENATT),y=b.readUInt32LE(H.CENATX),E=b.readUInt32LE(H.CENOFF)},localHeaderToBinary:function(){var b=Buffer.alloc(H.LOCHDR);return b.writeUInt32LE(H.LOCSIG,0),b.writeUInt16LE(e,H.LOCVER),b.writeUInt16LE(r,H.LOCFLG),b.writeUInt16LE(i,H.LOCHOW),b.writeUInt32LE(o,H.LOCTIM),b.writeUInt32LE(c,H.LOCCRC),b.writeUInt32LE(l,H.LOCSIZ),b.writeUInt32LE(u,H.LOCLEN),b.writeUInt16LE(x,H.LOCNAM),b.writeUInt16LE(I.extraLen,H.LOCEXT),b},centralHeaderToBinary:function(){var b=Buffer.alloc(H.CENHDR+x+h+w);return b.writeUInt32LE(H.CENSIG,0),b.writeUInt16LE(t,H.CENVEM),b.writeUInt16LE(e,H.CENVER),b.writeUInt16LE(r,H.CENFLG),b.writeUInt16LE(i,H.CENHOW),b.writeUInt32LE(o,H.CENTIM),b.writeUInt32LE(c,H.CENCRC),b.writeUInt32LE(l,H.CENSIZ),b.writeUInt32LE(u,H.CENLEN),b.writeUInt16LE(x,H.CENNAM),b.writeUInt16LE(h,H.CENEXT),b.writeUInt16LE(w,H.CENCOM),b.writeUInt16LE(_,H.CENDSK),b.writeUInt16LE(v,H.CENATT),b.writeUInt32LE(y,H.CENATX),b.writeUInt32LE(E,H.CENOFF),b},toJSON:function(){let b=function(k){return k+" bytes"};return{made:t,version:e,flags:r,method:cn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:b(l),size:b(u),fileNameLength:b(x),extraLength:b(h),commentLength:b(w),diskNumStart:_,inAttr:v,attr:y,offset:E,centralHeaderSize:b(H.CENHDR+x+h+w)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Gl=ae((P1,Hl)=>{var ur=lr(),we=ur.Constants;Hl.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return we.ENDHDR+o},loadFromBinary:function(c){if((c.length!==we.ENDHDR||c.readUInt32LE(0)!==we.ENDSIG)&&(c.length<we.ZIP64HDR||c.readUInt32LE(0)!==we.ZIP64SIG))throw ur.Errors.INVALID_END();c.readUInt32LE(0)===we.ENDSIG?(t=c.readUInt16LE(we.ENDSUB),e=c.readUInt16LE(we.ENDTOT),r=c.readUInt32LE(we.ENDSIZ),i=c.readUInt32LE(we.ENDOFF),o=c.readUInt16LE(we.ENDCOM)):(t=ur.readBigUInt64LE(c,we.ZIP64SUB),e=ur.readBigUInt64LE(c,we.ZIP64TOT),r=ur.readBigUInt64LE(c,we.ZIP64SIZE),i=ur.readBigUInt64LE(c,we.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(we.ENDHDR+o);return c.writeUInt32LE(we.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,we.ENDSUB),c.writeUInt16LE(e,we.ENDTOT),c.writeUInt32LE(r,we.ENDSIZ),c.writeUInt32LE(i,we.ENDOFF),c.writeUInt16LE(o,we.ENDCOM),c.fill(" ",we.ENDHDR),c},toJSON:function(){let c=function(l,u){let x=l.toString(16).toUpperCase();for(;x.length<u;)x="0"+x;return"0x"+x};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Pa=ae(ka=>{ka.EntryHeader=Ul();ka.MainHeader=Gl()});var jl=ae((O1,ql)=>{ql.exports=function(t){var e=ue("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],l=0;o.on("data",function(u){c.push(u),l+=u.length}),o.on("end",function(){var u=Buffer.alloc(l),x=0;u.fill(0);for(var h=0;h<c.length;h++){var w=c[h];w.copy(u,x),x+=w.length}i&&i(u)}),o.end(t)}}}});var Kl=ae((L1,Wl)=>{var Jg=+(process.versions?process.versions.node:"").split(".")[0]||0;Wl.exports=function(t,e){var r=ue("zlib");let i=Jg>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),l=[],u=0;c.on("data",function(x){l.push(x),u+=x.length}),c.on("end",function(){var x=Buffer.alloc(u),h=0;x.fill(0);for(var w=0;w<l.length;w++){var _=l[w];_.copy(x,h),h+=_.length}o&&o(x)}),c.end(t)}}}});var Yl=ae((N1,Jl)=>{"use strict";var{randomFillSync:$l}=ue("crypto"),Yg=hs(),Xg=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Zl=(t,e)=>Math.imul(t,e)>>>0,Vl=(t,e)=>Xg[(t^e)&255]^t>>>8,ri=()=>typeof $l=="function"?$l(Buffer.alloc(12)):ri.node();ri.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ps={genSalt:ri};function gs(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}gs.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Vl(e[0],t),e[1]+=e[0]&255,e[1]=Zl(e[1],134775813)+1,e[2]=Vl(e[2],e[1]>>>24),t};gs.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Zl(t,t^1)>>8&255};function Qg(t){let e=new gs(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function em(t){let e=new gs(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let l=e.next();i[o++]=c^l,e.updateKeys(c)}return i}}function tm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=Qg(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw Yg.WRONG_PASSWORD();return i(t.slice(12))}function nm(t){Buffer.isBuffer(t)&&t.length>=12?ps.genSalt=function(){return t.slice(0,12)}:t==="node"?ps.genSalt=ri.node:ps.genSalt=ri}function rm(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=em(r),c=ps.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let l=Buffer.alloc(t.length+12);return o(c,l),o(t,l,12)}Jl.exports={decrypt:tm,encrypt:rm,_salter:nm}});var Xl=ae(ms=>{ms.Deflater=jl();ms.Inflater=Kl();ms.ZipCrypto=Yl()});var Oa=ae((B1,Ql)=>{var ce=lr(),im=Pa(),Ee=ce.Constants,Da=Xl();Ql.exports=function(t,e){var r=new im.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,l=null,u=Buffer.alloc(0),x=Buffer.alloc(0),h=!0;let w=t,_=typeof w.decoder=="object"?w.decoder:ce.decoder;h=_.hasOwnProperty("efs")?_.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(x=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function y(b){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ce.crc32(b)!==r.localHeader.crc)return!1}else{let k={},D=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(D)==Ee.LOCSIG||e.readUInt32LE(D)==Ee.CENSIG)throw ce.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(D)==Ee.EXTSIG)k.crc=e.readUInt32LE(D+Ee.EXTCRC),k.compressedSize=e.readUInt32LE(D+Ee.EXTSIZ),k.size=e.readUInt32LE(D+Ee.EXTLEN);else if(e.readUInt16LE(D+12)===19280)k.crc=e.readUInt32LE(D+Ee.EXTCRC-4),k.compressedSize=e.readUInt32LE(D+Ee.EXTSIZ-4),k.size=e.readUInt32LE(D+Ee.EXTLEN-4);else throw ce.Errors.DESCRIPTOR_UNKNOWN();if(k.compressedSize!==r.compressedSize||k.size!==r.size||k.crc!==r.crc)throw ce.Errors.DESCRIPTOR_FAULTY();if(ce.crc32(b)!==k.crc)return!1}return!0}function E(b,k,D){if(typeof k>"u"&&typeof b=="string"&&(D=b,b=void 0),c)return b&&k&&k(Buffer.alloc(0),ce.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var z=v();if(z.length===0)return b&&k&&k(z),z;if(r.encrypted){if(typeof D!="string"&&!Buffer.isBuffer(D))throw ce.Errors.INVALID_PASS_PARAM();z=Da.ZipCrypto.decrypt(z,r,D)}var M=Buffer.alloc(r.size);switch(r.method){case ce.Constants.STORED:if(z.copy(M),y(M))return b&&k&&k(M),M;throw b&&k&&k(M,ce.Errors.BAD_CRC()),ce.Errors.BAD_CRC();case ce.Constants.DEFLATED:var Z=new Da.Inflater(z,r.size);if(b)Z.inflateAsync(function(V){V.copy(V,0),k&&(y(V)?k(V):k(V,ce.Errors.BAD_CRC()))});else{if(Z.inflate(M).copy(M,0),!y(M))throw ce.Errors.BAD_CRC(`"${_.decode(i)}"`);return M}break;default:throw b&&k&&k(Buffer.alloc(0),ce.Errors.UNKNOWN_METHOD()),ce.Errors.UNKNOWN_METHOD()}}function I(b,k){if((!l||!l.length)&&Buffer.isBuffer(e))return b&&k&&k(v()),v();if(l.length&&!c){var D;switch(r.method){case ce.Constants.STORED:return r.compressedSize=r.size,D=Buffer.alloc(l.length),l.copy(D),b&&k&&k(D),D;default:case ce.Constants.DEFLATED:var z=new Da.Deflater(l);if(b)z.deflateAsync(function(Z){D=Buffer.alloc(Z.length),r.compressedSize=Z.length,Z.copy(D),k&&k(D)});else{var M=z.deflate();return r.compressedSize=M.length,M}z=null;break}}else if(b&&k)k(Buffer.alloc(0));else return Buffer.alloc(0)}function A(b,k){return ce.readBigUInt64LE(b,k)}function C(b){try{for(var k=0,D,z,M;k+4<b.length;)D=b.readUInt16LE(k),k+=2,z=b.readUInt16LE(k),k+=2,M=b.slice(k,k+z),k+=z,Ee.ID_ZIP64===D&&P(M)}catch{throw ce.Errors.EXTRA_FIELD_PARSE_ERROR()}}function P(b){var k,D,z,M;b.length>=Ee.EF_ZIP64_SCOMP&&(k=A(b,Ee.EF_ZIP64_SUNCOMP),r.size===Ee.EF_ZIP64_OR_32&&(r.size=k)),b.length>=Ee.EF_ZIP64_RHO&&(D=A(b,Ee.EF_ZIP64_SCOMP),r.compressedSize===Ee.EF_ZIP64_OR_32&&(r.compressedSize=D)),b.length>=Ee.EF_ZIP64_DSN&&(z=A(b,Ee.EF_ZIP64_RHO),r.offset===Ee.EF_ZIP64_OR_32&&(r.offset=z)),b.length>=Ee.EF_ZIP64_DSN+4&&(M=b.readUInt32LE(Ee.EF_ZIP64_DSN),r.diskNumStart===Ee.EF_ZIP64_OR_16&&(r.diskNumStart=M))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(b){i=ce.toBuffer(b,_.encode);var k=i[i.length-1];c=k===47||k===92,r.fileNameLength=i.length},get efs(){return typeof h=="function"?h(this.entryName):h},get extra(){return u},set extra(b){u=b,r.extraLength=b.length,C(b)},get comment(){return _.decode(o)},set comment(b){if(o=ce.toBuffer(b,_.encode),r.commentLength=o.length,o.length>65535)throw ce.Errors.COMMENT_TOO_LONG()},get name(){var b=_.decode(i);return c?b.substr(b.length-1).split("/").pop():b.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(b){I(!0,b)},setData:function(b){l=ce.toBuffer(b,ce.decoder.encode),!c&&l.length?(r.size=l.length,r.method=ce.Constants.DEFLATED,r.crc=ce.crc32(b),r.changed=!0):r.method=ce.Constants.STORED},getData:function(b){return r.changed?l:E(!1,null,b)},getDataAsync:function(b,k){r.changed?b(l):E(!0,b,k)},set attr(b){r.attr=b},get attr(){return r.attr},set header(b){r.loadFromBinary(b)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var b=r.centralHeaderToBinary(),k=ce.Constants.CENHDR;return i.copy(b,k),k+=i.length,u.copy(b,k),k+=r.extraLength,o.copy(b,k),b},packLocalHeader:function(){let b=0;r.flags_efs=this.efs,r.extraLocalLength=x.length;let k=r.localHeaderToBinary(),D=Buffer.alloc(k.length+i.length+r.extraLocalLength);return k.copy(D,b),b+=k.length,i.copy(D,b),b+=i.length,x.copy(D,b),b+=x.length,D},toJSON:function(){let b=function(k){return"<"+(k&&k.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:b(e),data:b(l)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var nu=ae((F1,tu)=>{var eu=Oa(),sm=Pa(),Ge=lr();tu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new sm.MainHeader,l=!1,u=null;let x=new Set,h=e,{noSort:w,decoder:_}=h;t?E(h.readEntries):l=!0;function v(){let A=new Set;for(let C of Object.keys(i)){let P=C.split("/");if(P.pop(),!!P.length)for(let b=0;b<P.length;b++){let k=P.slice(0,b+1).join("/")+"/";A.add(k)}}for(let C of A)if(!(C in i)){let P=new eu(h);P.entryName=C,P.attr=16,P.temporary=!0,r.push(P),i[P.entryName]=P,x.add(P)}}function y(){if(l=!0,i={},c.diskEntries>(t.length-c.offset)/Ge.Constants.CENHDR)throw Ge.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,C=0;C<r.length;C++){var P=A,b=new eu(h,t);b.header=t.slice(P,P+=Ge.Constants.CENHDR),b.entryName=t.slice(P,P+=b.header.fileNameLength),b.header.extraLength&&(b.extra=t.slice(P,P+=b.header.extraLength)),b.header.commentLength&&(b.comment=t.slice(P,P+b.header.commentLength)),A+=b.header.centralHeaderSize,r[C]=b,i[b.entryName]=b}x.clear(),v()}function E(A){var C=t.length-Ge.Constants.ENDHDR,P=Math.max(0,C-65535),b=P,k=t.length,D=-1,z=0;for(typeof h.trailingSpace=="boolean"&&h.trailingSpace&&(P=0),C;C>=b;C--)if(t[C]===80){if(t.readUInt32LE(C)===Ge.Constants.ENDSIG){D=C,z=C,k=C+Ge.Constants.ENDHDR,b=C-Ge.Constants.END64HDR;continue}if(t.readUInt32LE(C)===Ge.Constants.END64SIG){b=P;continue}if(t.readUInt32LE(C)===Ge.Constants.ZIP64SIG){D=C,k=C+Ge.readBigUInt64LE(t,C+Ge.Constants.ZIP64SIZE)+Ge.Constants.ZIP64LEAD;break}}if(D==-1)throw Ge.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(D,k)),c.commentLength&&(o=t.slice(z+Ge.Constants.ENDHDR)),A&&y()}function I(){r.length>1&&!w&&r.sort((A,C)=>A.entryName.toLowerCase().localeCompare(C.entryName.toLowerCase()))}return{get entries(){return l||y(),r.filter(A=>!x.has(A))},get comment(){return _.decode(o)},set comment(A){o=Ge.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return l?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return l||y(),i[A]||null},setEntry:function(A){l||y(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,C=!0){l||y();let P=i[A];this.getEntryChildren(P,C).map(k=>k.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){l||y();let C=i[A],P=r.indexOf(C);P>=0&&(r.splice(P,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,C=!0){if(l||y(),typeof A=="object")if(A.isDirectory&&C){let P=[],b=A.entryName;for(let k of r)k.entryName.startsWith(b)&&P.push(k);return P}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let C=this.getEntryChildren(A);return C.includes(A)?C.length-1:C.length}return 0},compressToBuffer:function(){l||y(),I();let A=[],C=[],P=0,b=0;c.size=0,c.offset=0;let k=0;for(let M of this.entries){let Z=M.getCompressedData();M.header.offset=b;let V=M.packLocalHeader(),te=V.length+Z.length;b+=te,A.push(V),A.push(Z);let J=M.packCentralHeader();C.push(J),c.size+=J.length,P+=te+J.length,k++}P+=c.mainHeaderSize,c.offset=b,c.totalEntries=k,b=0;let D=Buffer.alloc(P);for(let M of A)M.copy(D,b),b+=M.length;for(let M of C)M.copy(D,b),b+=M.length;let z=c.toBinary();return o&&o.copy(z,Ge.Constants.ENDHDR),z.copy(D,b),t=D,l=!1,D},toAsyncBuffer:function(A,C,P,b){try{l||y(),I();let k=[],D=[],z=0,M=0,Z=0;c.size=0,c.offset=0;let V=function(te){if(te.length>0){let J=te.shift(),ie=J.entryName+J.extra.toString();P&&P(ie),J.getCompressedDataAsync(function(oe){b&&b(ie),J.header.offset=M;let O=J.packLocalHeader(),q=O.length+oe.length;M+=q,k.push(O),k.push(oe);let K=J.packCentralHeader();D.push(K),c.size+=K.length,z+=q+K.length,Z++,V(te)})}else{z+=c.mainHeaderSize,c.offset=M,c.totalEntries=Z,M=0;let J=Buffer.alloc(z);k.forEach(function(oe){oe.copy(J,M),M+=oe.length}),D.forEach(function(oe){oe.copy(J,M),M+=oe.length});let ie=c.toBinary();o&&o.copy(ie,Ge.Constants.ENDHDR),ie.copy(J,M),t=J,l=!1,A(J)}};V(Array.from(this.entries))}catch(k){C(k)}}}}});var su=ae((z1,iu)=>{var ye=lr(),_e=ue("path"),om=Oa(),am=nu(),Pn=(...t)=>ye.findLast(t,e=>typeof e=="boolean"),ru=(...t)=>ye.findLast(t,e=>typeof e=="string"),cm=(...t)=>ye.findLast(t,e=>typeof e=="function"),dm={noSort:!1,readEntries:!1,method:ye.Constants.NONE,fs:null};iu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),dm);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=ye.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new ye(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=ye.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=ye.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw ye.Errors.INVALID_FILENAME();let c=new am(r,i),{canonical:l,sanitize:u,zipnamefix:x}=ye;function h(y){if(y&&c){var E;if(typeof y=="string"&&(E=c.getEntry(_e.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=c.getEntry(y.entryName)),E)return E}return null}function w(y){let{join:E,normalize:I,sep:A}=_e.posix;return E(_e.isAbsolute(y)?"/":".",I(A+y.split("\\").join(A)+A))}function _(y){return y instanceof RegExp?(function(E){return function(I){return E.test(I)}})(y):typeof y!="function"?()=>!0:y}let v=(y,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",_e.relative(y,E)+I};return{readFile:function(y,E){var I=h(y);return I&&I.getData(E)||null},childCount:function(y){let E=h(y);if(E)return c.getChildCount(E)},readFileAsync:function(y,E){var I=h(y);I?I.getDataAsync(E):E(null,"getEntry failed for:"+y)},readAsText:function(y,E){var I=h(y);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(y,E,I){var A=h(y);A?A.getDataAsync(function(C,P){if(P){E(C,P);return}C&&C.length?E(C.toString(I||"utf8")):E("")}):E("")},deleteFile:function(y,E=!0){var I=h(y);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(y){var E=h(y);E&&c.deleteEntry(E.entryName)},addZipComment:function(y){c.comment=y},getZipComment:function(){return c.comment||""},addZipEntryComment:function(y,E){var I=h(y);I&&(I.comment=E)},getZipEntryComment:function(y){var E=h(y);return E&&E.comment||""},updateFile:function(y,E){var I=h(y);I&&I.setData(E)},addLocalFile:function(y,E,I,A){if(o.fs.existsSync(y)){E=E?w(E):"";let C=_e.win32.basename(_e.win32.normalize(y));E+=I||C;let P=o.fs.statSync(y),b=P.isFile()?o.fs.readFileSync(y):Buffer.alloc(0);P.isDirectory()&&(E+=o.sep),this.addFile(E,b,A,P)}else throw ye.Errors.FILE_NOT_FOUND(y)},addLocalFileAsync:function(y,E){y=typeof y=="object"?y:{localPath:y};let I=_e.resolve(y.localPath),{comment:A}=y,{zipPath:C,zipName:P}=y,b=this;o.fs.stat(I,function(k,D){if(k)return E(k,!1);C=C?w(C):"";let z=_e.win32.basename(_e.win32.normalize(I));if(C+=P||z,D.isFile())o.fs.readFile(I,function(M,Z){return M?E(M,!1):(b.addFile(C,Z,A,D),setImmediate(E,void 0,!0))});else if(D.isDirectory())return C+=o.sep,b.addFile(C,Buffer.alloc(0),A,D),setImmediate(E,void 0,!0)})},addLocalFolder:function(y,E,I){if(I=_(I),E=E?w(E):"",y=_e.normalize(y),o.fs.existsSync(y)){let A=o.findFiles(y),C=this;if(A.length)for(let P of A){let b=_e.join(E,v(y,P));I(b)&&C.addLocalFile(P,_e.dirname(b))}}else throw ye.Errors.FILE_NOT_FOUND(y)},addLocalFolderAsync:function(y,E,I,A){A=_(A),I=I?w(I):"",y=_e.normalize(y);var C=this;o.fs.open(y,"r",function(P){if(P&&P.code==="ENOENT")E(void 0,ye.Errors.FILE_NOT_FOUND(y));else if(P)E(void 0,P);else{var b=o.findFiles(y),k=-1,D=function(){if(k+=1,k<b.length){var z=b[k],M=v(y,z).split("\\").join("/");M=M.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(M)?o.fs.stat(z,function(Z,V){Z&&E(void 0,Z),V.isFile()?o.fs.readFile(z,function(te,J){te?E(void 0,te):(C.addFile(I+M,J,"",V),D())}):(C.addFile(I+M+"/",Buffer.alloc(0),"",V),D())}):process.nextTick(()=>{D()})}else E(!0,void 0)};D()}})},addLocalFolderAsync2:function(y,E){let I=this;y=typeof y=="object"?y:{localPath:y},localPath=_e.resolve(w(y.localPath));let{zipPath:A,filter:C,namefix:P}=y;C instanceof RegExp?C=(function(D){return function(z){return D.test(z)}})(C):typeof C!="function"&&(C=function(){return!0}),A=A?w(A):"",P=="latin1"&&(P=D=>D.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof P!="function"&&(P=D=>D);let b=D=>_e.join(A,P(v(localPath,D))),k=D=>_e.win32.basename(_e.win32.normalize(P(D)));o.fs.open(localPath,"r",function(D){D&&D.code==="ENOENT"?E(void 0,ye.Errors.FILE_NOT_FOUND(localPath)):D?E(void 0,D):o.findFilesAsync(localPath,function(z,M){if(z)return E(z);M=M.filter(Z=>C(b(Z))),M.length||E(void 0,!1),setImmediate(M.reverse().reduce(function(Z,V){return function(te,J){if(te||J===!1)return setImmediate(Z,te,!1);I.addLocalFileAsync({localPath:V,zipPath:_e.dirname(b(V)),zipName:k(V)},Z)}},E))})})},addLocalFolderPromise:function(y,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(C,P)=>{C&&A(C),P&&I(this)})})},addFile:function(y,E,I,A){y=x(y);let C=h(y),P=C!=null;P||(C=new om(i),C.entryName=y),C.comment=I||"";let b=typeof A=="object"&&A instanceof o.fs.Stats;b&&(C.header.time=A.mtime);var k=C.isDirectory?16:0;let D=C.isDirectory?16384:32768;return b?D|=4095&A.mode:typeof A=="number"?D|=4095&A:D|=C.isDirectory?493:420,k=(k|D<<16)>>>0,C.attr=k,C.setData(E),P||c.setEntry(C),C},getEntries:function(y){return c.password=y,c?c.entries:[]},getEntry:function(y){return h(y)},getEntryCount:function(){return c.getEntryCount()},forEach:function(y){return c.forEach(y)},extractEntryTo:function(y,E,I,A,C,P){A=Pn(!1,A),C=Pn(!1,C),I=Pn(!0,I),P=ru(C,P);var b=h(y);if(!b)throw ye.Errors.NO_ENTRY();var k=l(b.entryName),D=u(E,P&&!b.isDirectory?P:I?k:_e.basename(k));if(b.isDirectory){var z=c.getEntryChildren(b);return z.forEach(function(V){if(V.isDirectory)return;var te=V.getData();if(!te)throw ye.Errors.CANT_EXTRACT_FILE();var J=l(V.entryName),ie=u(E,I?J:_e.basename(J));let oe=C?V.header.fileAttr:void 0;o.writeFileTo(ie,te,A,oe)}),!0}var M=b.getData(c.password);if(!M)throw ye.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(D)&&!A)throw ye.Errors.CANT_OVERRIDE();let Z=C?y.header.fileAttr:void 0;return o.writeFileTo(D,M,A,Z),!0},test:function(y){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(y);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(y,E,I,A){if(I=Pn(!1,I),A=ru(I,A),E=Pn(!1,E),!c)throw ye.Errors.NO_ZIP();c.entries.forEach(function(C){var P=u(y,l(C.entryName));if(C.isDirectory){o.makeDir(P);return}var b=C.getData(A);if(!b)throw ye.Errors.CANT_EXTRACT_FILE();let k=I?C.header.fileAttr:void 0;o.writeFileTo(P,b,E,k);try{o.fs.utimesSync(P,C.header.time,C.header.time)}catch{throw ye.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(y,E,I,A){if(A=cm(E,I,A),I=Pn(!1,I),E=Pn(!1,E),!A)return new Promise((D,z)=>{this.extractAllToAsync(y,E,I,function(M){M?z(M):D(this)})});if(!c){A(ye.Errors.NO_ZIP());return}y=_e.resolve(y);let C=D=>u(y,_e.normalize(l(D.entryName))),P=(D,z)=>new Error(D+': "'+z+'"'),b=[],k=[];c.entries.forEach(D=>{D.isDirectory?b.push(D):k.push(D)});for(let D of b){let z=C(D),M=I?D.header.fileAttr:void 0;try{o.makeDir(z),M&&o.fs.chmodSync(z,M),o.fs.utimesSync(z,D.header.time,D.header.time)}catch{A(P("Unable to create folder",z))}}k.reverse().reduce(function(D,z){return function(M){if(M)D(M);else{let Z=_e.normalize(l(z.entryName)),V=u(y,Z);z.getDataAsync(function(te,J){if(J)D(J);else if(!te)D(ye.Errors.CANT_EXTRACT_FILE());else{let ie=I?z.header.fileAttr:void 0;o.writeFileToAsync(V,te,E,ie,function(oe){oe||D(P("Unable to write file",V)),o.fs.utimes(V,z.header.time,z.header.time,function(O){O?D(P("Unable to set times",V)):D()})})}})}}},A)()},writeZip:function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&i.filename&&(y=i.filename),!!y){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(y,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(y,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((C,P)=>{!y&&i.filename&&(y=i.filename),y||P("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(b=>{let k=D=>D?C(D):P("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(y,b,I,A,k)},P)})},toBufferPromise:function(){return new Promise((y,E)=>{c.toAsyncBuffer(y,E)})},toBuffer:function(y,E,I,A){return typeof y=="function"?(c.toAsyncBuffer(y,E,I,A),null):c.compressToBuffer()}}}});import{execFile as p_,spawn as g_,spawnSync as rA}from"node:child_process";import{promisify as m_}from"node:util";function __(t){if(process.platform!=="win32")return!1;if(If.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(If,"").toLowerCase();return w_.has(r)}function Af(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return __(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function et(t,e=[],r={}){return g_(t,e,Af(t,r))}function Tf(t,e=[],r={}){return y_(t,e,Af(t,r))}var w_,If,y_,Kt=Je(()=>{"use strict";w_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),If=/\.(cmd|bat|ps1)$/i;y_=m_(p_)});var Vt=ae((L3,nx)=>{"use strict";var ex=["nodebuffer","arraybuffer","fragments"],tx=typeof Blob<"u";tx&&ex.push("blob");nx.exports={BINARY_TYPES:ex,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:tx,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ji=ae((N3,vo)=>{"use strict";var{EMPTY_BUFFER:Yb}=Vt(),od=Buffer[Symbol.species];function Xb(t,e){if(t.length===0)return Yb;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new od(r.buffer,r.byteOffset,i):r}function rx(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function ix(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Qb(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ad(t){if(ad.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new od(t):ArrayBuffer.isView(t)?e=new od(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ad.readOnly=!1),e}vo.exports={concat:Xb,mask:rx,toArrayBuffer:Qb,toBuffer:ad,unmask:ix};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=ue("bufferutil");vo.exports.mask=function(e,r,i,o,c){c<48?rx(e,r,i,o,c):t.mask(e,r,i,o,c)},vo.exports.unmask=function(e,r){e.length<32?ix(e,r):t.unmask(e,r)}}catch{}});var ax=ae((M3,ox)=>{"use strict";var sx=Symbol("kDone"),cd=Symbol("kRun"),dd=class{constructor(e){this[sx]=()=>{this.pending--,this[cd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[cd]()}[cd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[sx])}}};ox.exports=dd});var Br=ae((B3,ux)=>{"use strict";var Wi=ue("zlib"),cx=ji(),eE=ax(),{kStatusCode:dx}=Vt(),tE=Buffer[Symbol.species],nE=Buffer.from([0,0,255,255]),Io=Symbol("permessage-deflate"),Zt=Symbol("total-length"),Nr=Symbol("callback"),An=Symbol("buffers"),Mr=Symbol("error"),So,ld=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,!So){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;So=new eE(r)}}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[Nr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){So.add(o=>{this._decompress(e,r,(c,l)=>{o(),i(c,l)})})}compress(e,r,i){So.add(o=>{this._compress(e,r,(c,l)=>{o(),i(c,l)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Wi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Wi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:l}),this._inflate[Io]=this,this._inflate[Zt]=0,this._inflate[An]=[],this._inflate.on("error",iE),this._inflate.on("data",lx)}this._inflate[Nr]=i,this._inflate.write(e),r&&this._inflate.write(nE),this._inflate.flush(()=>{let c=this._inflate[Mr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let l=cx.concat(this._inflate[An],this._inflate[Zt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Zt]=0,this._inflate[An]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,l)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,l=typeof this.params[c]!="number"?Wi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Wi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:l}),this._deflate[Zt]=0,this._deflate[An]=[],this._deflate.on("data",rE)}this._deflate[Nr]=i,this._deflate.write(e),this._deflate.flush(Wi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=cx.concat(this._deflate[An],this._deflate[Zt]);r&&(c=new tE(c.buffer,c.byteOffset,c.length-4)),this._deflate[Nr]=null,this._deflate[Zt]=0,this._deflate[An]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};ux.exports=ld;function rE(t){this[An].push(t),this[Zt]+=t.length}function lx(t){if(this[Zt]+=t.length,this[Io]._maxPayload<1||this[Zt]<=this[Io]._maxPayload){this[An].push(t);return}this[Mr]=new RangeError("Max payload size exceeded"),this[Mr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Mr][dx]=1009,this.removeListener("data",lx),this.reset()}function iE(t){if(this[Io]._inflate=null,this[Mr]){this[Nr](this[Mr]);return}t[dx]=1007,this[Nr](t)}});var Fr=ae((F3,Ao)=>{"use strict";var{isUtf8:fx}=ue("buffer"),{hasBlob:sE}=Vt(),oE=[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 aE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ud(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function cE(t){return sE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ao.exports={isBlob:cE,isValidStatusCode:aE,isValidUTF8:ud,tokenChars:oE};if(fx)Ao.exports.isValidUTF8=function(t){return t.length<24?ud(t):fx(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=ue("utf-8-validate");Ao.exports.isValidUTF8=function(e){return e.length<32?ud(e):t(e)}}catch{}});var gd=ae((z3,yx)=>{"use strict";var{Writable:dE}=ue("stream"),xx=Br(),{BINARY_TYPES:lE,EMPTY_BUFFER:hx,kStatusCode:uE,kWebSocket:fE}=Vt(),{concat:fd,toArrayBuffer:xE,unmask:hE}=ji(),{isValidStatusCode:pE,isValidUTF8:px}=Fr(),To=Buffer[Symbol.species],ut=0,gx=1,mx=2,_x=3,xd=4,hd=5,Co=6,pd=class extends dE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||lE[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[fE]=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=ut}_write(e,r,i){if(this._opcode===8&&this._state==ut)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new To(i.buffer,i.byteOffset+e,i.length-e),new To(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new To(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ut:this.getInfo(e);break;case gx:this.getPayloadLength16(e);break;case mx:this.getPayloadLength64(e);break;case _x:this.getMask();break;case xd:this.getData(e);break;case hd:case Co:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[xx.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=gx:this._payloadLength===127?this._state=mx: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 r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=_x:this._state=xd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=xd}getData(e){let r=hx;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&hE(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=hd,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[xx.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let l=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(l);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let l=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(l);return}this._fragments.push(c)}this.dataMessage(r),this._state===ut&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ut;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=fd(i,r):this._binaryType==="arraybuffer"?o=xE(fd(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ut):(this._state=Co,setImmediate(()=>{this.emit("message",o,!0),this._state=ut,this.startLoop(e)}))}else{let o=fd(i,r);if(!this._skipUTF8Validation&&!px(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===hd||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ut):(this._state=Co,setImmediate(()=>{this.emit("message",o,!1),this._state=ut,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,hx),this.end();else{let i=e.readUInt16BE(0);if(!pE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new To(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!px(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=ut;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ut):(this._state=Co,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ut,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let l=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(l,this.createError),l.code=c,l[uE]=o,l}};yx.exports=pd});var _d=ae((H3,vx)=>{"use strict";var{Duplex:U3}=ue("stream"),{randomFillSync:gE}=ue("crypto"),{types:{isUint8Array:mE}}=ue("util"),bx=Br(),{EMPTY_BUFFER:wE,kWebSocket:_E,NOOP:yE}=Vt(),{isBlob:zr,isValidStatusCode:bE}=Fr(),{mask:Ex,toBuffer:Kn}=ji(),ft=Symbol("kByteLength"),EE=Buffer.alloc(4),Ro=8*1024,$n,Ur=Ro,vt=0,vE=1,SE=2,md=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=vt,this.onerror=yE,this[_E]=void 0}static frame(e,r){let i,o=!1,c=2,l=!1;r.mask&&(i=r.maskBuffer||EE,r.generateMask?r.generateMask(i):(Ur===Ro&&($n===void 0&&($n=Buffer.alloc(Ro)),gE($n,0,Ro),Ur=0),i[0]=$n[Ur++],i[1]=$n[Ur++],i[2]=$n[Ur++],i[3]=$n[Ur++]),l=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||l)&&r[ft]!==void 0?u=r[ft]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!l);let x=u;u>=65536?(c+=8,x=127):u>125&&(c+=2,x=126);let h=Buffer.allocUnsafe(o?u+c:c);return h[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(h[0]|=64),h[1]=x,x===126?h.writeUInt16BE(u,2):x===127&&(h[2]=h[3]=0,h.writeUIntBE(u,4,6)),r.mask?(h[1]|=128,h[c-4]=i[0],h[c-3]=i[1],h[c-2]=i[2],h[c-1]=i[3],l?[h,e]:o?(Ex(e,i,h,c,u),[h]):(Ex(e,i,e,0,u),[h,e])):[h,e]}close(e,r,i,o){let c;if(e===void 0)c=wE;else{if(typeof e!="number"||!bE(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string")c.write(r,2);else if(mE(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let l={[ft]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==vt?this.enqueue([this.dispatch,c,!1,l,o]):this.sendFrame(t.frame(c,l),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):zr(e)?(o=e.size,c=!1):(e=Kn(e),o=e.length,c=Kn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[ft]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};zr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):zr(e)?(o=e.size,c=!1):(e=Kn(e),o=e.length,c=Kn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let l={[ft]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};zr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,!1,l,i]):this.getBlobData(e,!1,l,i):this._state!==vt?this.enqueue([this.dispatch,e,!1,l,i]):this.sendFrame(t.frame(e,l),i)}send(e,r,i){let o=this._extensions[bx.extensionName],c=r.binary?2:1,l=r.compress,u,x;typeof e=="string"?(u=Buffer.byteLength(e),x=!1):zr(e)?(u=e.size,x=!1):(e=Kn(e),u=e.length,x=Kn.readOnly),this._firstFragment?(this._firstFragment=!1,l&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(l=u>=o._threshold),this._compress=l):(l=!1,c=0),r.fin&&(this._firstFragment=!0);let h={[ft]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:x,rsv1:l};zr(e)?this._state!==vt?this.enqueue([this.getBlobData,e,this._compress,h,i]):this.getBlobData(e,this._compress,h,i):this._state!==vt?this.enqueue([this.dispatch,e,this._compress,h,i]):this.dispatch(e,this._compress,h,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[ft],this._state=SE,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(wd,this,u,o);return}this._bufferedBytes-=i[ft];let l=Kn(c);r?this.dispatch(l,r,i,o):(this._state=vt,this.sendFrame(t.frame(l,i),o),this.dequeue())}).catch(c=>{process.nextTick(IE,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[bx.extensionName];this._bufferedBytes+=i[ft],this._state=vE,c.compress(e,i.fin,(l,u)=>{if(this._socket.destroyed){let x=new Error("The socket was closed while data was being compressed");wd(this,x,o);return}this._bufferedBytes-=i[ft],this._state=vt,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===vt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ft],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ft],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};vx.exports=md;function wd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function IE(t,e,r){wd(t,e,r),t.onerror(e)}});var Dx=ae((G3,Px)=>{"use strict";var{kForOnEventAttribute:Ki,kListener:yd}=Vt(),Sx=Symbol("kCode"),Ix=Symbol("kData"),Ax=Symbol("kError"),Tx=Symbol("kMessage"),Cx=Symbol("kReason"),Hr=Symbol("kTarget"),Rx=Symbol("kType"),kx=Symbol("kWasClean"),Jt=class{constructor(e){this[Hr]=null,this[Rx]=e}get target(){return this[Hr]}get type(){return this[Rx]}};Object.defineProperty(Jt.prototype,"target",{enumerable:!0});Object.defineProperty(Jt.prototype,"type",{enumerable:!0});var Vn=class extends Jt{constructor(e,r={}){super(e),this[Sx]=r.code===void 0?0:r.code,this[Cx]=r.reason===void 0?"":r.reason,this[kx]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Sx]}get reason(){return this[Cx]}get wasClean(){return this[kx]}};Object.defineProperty(Vn.prototype,"code",{enumerable:!0});Object.defineProperty(Vn.prototype,"reason",{enumerable:!0});Object.defineProperty(Vn.prototype,"wasClean",{enumerable:!0});var Gr=class extends Jt{constructor(e,r={}){super(e),this[Ax]=r.error===void 0?null:r.error,this[Tx]=r.message===void 0?"":r.message}get error(){return this[Ax]}get message(){return this[Tx]}};Object.defineProperty(Gr.prototype,"error",{enumerable:!0});Object.defineProperty(Gr.prototype,"message",{enumerable:!0});var $i=class extends Jt{constructor(e,r={}){super(e),this[Ix]=r.data===void 0?null:r.data}get data(){return this[Ix]}};Object.defineProperty($i.prototype,"data",{enumerable:!0});var AE={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ki]&&o[yd]===e&&!o[Ki])return;let i;if(t==="message")i=function(c,l){let u=new $i("message",{data:l?c:c.toString()});u[Hr]=this,ko(e,this,u)};else if(t==="close")i=function(c,l){let u=new Vn("close",{code:c,reason:l.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[Hr]=this,ko(e,this,u)};else if(t==="error")i=function(c){let l=new Gr("error",{error:c,message:c.message});l[Hr]=this,ko(e,this,l)};else if(t==="open")i=function(){let c=new Jt("open");c[Hr]=this,ko(e,this,c)};else return;i[Ki]=!!r[Ki],i[yd]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[yd]===e&&!r[Ki]){this.removeListener(t,r);break}}};Px.exports={CloseEvent:Vn,ErrorEvent:Gr,Event:Jt,EventTarget:AE,MessageEvent:$i};function ko(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Po=ae((q3,Ox)=>{"use strict";var{tokenChars:Vi}=Fr();function Nt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function TE(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,l,u,x=-1,h=-1,w=-1,_=0;for(;_<t.length;_++)if(h=t.charCodeAt(_),l===void 0)if(w===-1&&Vi[h]===1)x===-1&&(x=_);else if(_!==0&&(h===32||h===9))w===-1&&x!==-1&&(w=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);w===-1&&(w=_);let y=t.slice(x,w);h===44?(Nt(e,y,r),r=Object.create(null)):l=y,x=w=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(w===-1&&Vi[h]===1)x===-1&&(x=_);else if(h===32||h===9)w===-1&&x!==-1&&(w=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);w===-1&&(w=_),Nt(r,t.slice(x,w),!0),h===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),x=w=-1}else if(h===61&&x!==-1&&w===-1)u=t.slice(x,_),x=w=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(Vi[h]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);x===-1?x=_:i||(i=!0),o=!1}else if(c)if(Vi[h]===1)x===-1&&(x=_);else if(h===34&&x!==-1)c=!1,w=_;else if(h===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(h===34&&t.charCodeAt(_-1)===61)c=!0;else if(w===-1&&Vi[h]===1)x===-1&&(x=_);else if(x!==-1&&(h===32||h===9))w===-1&&(w=_);else if(h===59||h===44){if(x===-1)throw new SyntaxError(`Unexpected character at index ${_}`);w===-1&&(w=_);let y=t.slice(x,w);i&&(y=y.replace(/\\/g,""),i=!1),Nt(r,u,y),h===44&&(Nt(e,l,r),r=Object.create(null),l=void 0),u=void 0,x=w=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(x===-1||c||h===32||h===9)throw new SyntaxError("Unexpected end of input");w===-1&&(w=_);let v=t.slice(x,w);return l===void 0?Nt(e,v,r):(u===void 0?Nt(r,v,!0):i?Nt(r,u,v.replace(/\\/g,"")):Nt(r,u,v),Nt(e,l,r)),e}function CE(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(l=>l===!0?o:`${o}=${l}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Ox.exports={format:CE,parse:TE}});var No=ae((K3,Wx)=>{"use strict";var RE=ue("events"),kE=ue("https"),PE=ue("http"),Mx=ue("net"),DE=ue("tls"),{randomBytes:OE,createHash:LE}=ue("crypto"),{Duplex:j3,Readable:W3}=ue("stream"),{URL:bd}=ue("url"),Tn=Br(),NE=gd(),ME=_d(),{isBlob:BE}=Fr(),{BINARY_TYPES:Lx,CLOSE_TIMEOUT:FE,EMPTY_BUFFER:Do,GUID:zE,kForOnEventAttribute:Ed,kListener:UE,kStatusCode:HE,kWebSocket:Ue,NOOP:Bx}=Vt(),{EventTarget:{addEventListener:GE,removeEventListener:qE}}=Dx(),{format:jE,parse:WE}=Po(),{toBuffer:KE}=ji(),Fx=Symbol("kAborted"),vd=[8,13],Yt=["CONNECTING","OPEN","CLOSING","CLOSED"],$E=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ge=class t extends RE{constructor(e,r,i){super(),this._binaryType=Lx[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Do,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),zx(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Lx.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,r,i){let o=new NE({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new ME(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[Ue]=this,c[Ue]=this,e[Ue]=this,o.on("conclude",JE),o.on("drain",YE),o.on("error",XE),o.on("message",QE),o.on("ping",ev),o.on("pong",tv),c.onerror=nv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Gx),e.on("data",Lo),e.on("end",qx),e.on("error",jx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tn.extensionName]&&this._extensions[Tn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){st(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Hx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Do,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Do,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Sd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Tn.extensionName]||(o.compress=!1),this._sender.send(e||Do,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){st(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(ge,"CONNECTING",{enumerable:!0,value:Yt.indexOf("CONNECTING")});Object.defineProperty(ge.prototype,"CONNECTING",{enumerable:!0,value:Yt.indexOf("CONNECTING")});Object.defineProperty(ge,"OPEN",{enumerable:!0,value:Yt.indexOf("OPEN")});Object.defineProperty(ge.prototype,"OPEN",{enumerable:!0,value:Yt.indexOf("OPEN")});Object.defineProperty(ge,"CLOSING",{enumerable:!0,value:Yt.indexOf("CLOSING")});Object.defineProperty(ge.prototype,"CLOSING",{enumerable:!0,value:Yt.indexOf("CLOSING")});Object.defineProperty(ge,"CLOSED",{enumerable:!0,value:Yt.indexOf("CLOSED")});Object.defineProperty(ge.prototype,"CLOSED",{enumerable:!0,value:Yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(ge.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(ge.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ed])return e[UE];return null},set(e){for(let r of this.listeners(t))if(r[Ed]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Ed]:!0})}})});ge.prototype.addEventListener=GE;ge.prototype.removeEventListener=qE;Wx.exports=ge;function zx(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:FE,protocolVersion:vd[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!vd.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${vd.join(", ")})`);let c;if(e instanceof bd)c=e;else try{c=new bd(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let l=c.protocol==="wss:",u=c.protocol==="ws+unix:",x;if(c.protocol!=="ws:"&&!l&&!u?x=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?x="The URL's pathname is empty":c.hash&&(x="The URL contains a fragment identifier"),x){let I=new SyntaxError(x);if(t._redirects===0)throw I;Oo(t,I);return}let h=l?443:80,w=OE(16).toString("base64"),_=l?kE.request:PE.request,v=new Set,y;if(o.createConnection=o.createConnection||(l?ZE:VE),o.defaultPort=o.defaultPort||h,o.port=c.port||h,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":w,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(y=new Tn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=jE({[Tn.extensionName]:y.offer()})),r.length){for(let I of r){if(typeof I!="string"||!$E.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=l,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,C]of Object.entries(I))i.headers[A.toLowerCase()]=C}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!l)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=_(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=_(o);o.timeout&&E.on("timeout",()=>{st(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Fx]||(E=t._req=null,Oo(t,I))}),E.on("response",I=>{let A=I.headers.location,C=I.statusCode;if(A&&o.followRedirects&&C>=300&&C<400){if(++t._redirects>o.maxRedirects){st(t,E,"Maximum redirects exceeded");return}E.abort();let P;try{P=new bd(A,e)}catch{let k=new SyntaxError(`Invalid URL: ${A}`);Oo(t,k);return}zx(t,P,r,i)}else t.emit("unexpected-response",E,I)||st(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,C)=>{if(t.emit("upgrade",I),t.readyState!==ge.CONNECTING)return;E=t._req=null;let P=I.headers.upgrade;if(P===void 0||P.toLowerCase()!=="websocket"){st(t,A,"Invalid Upgrade header");return}let b=LE("sha1").update(w+zE).digest("base64");if(I.headers["sec-websocket-accept"]!==b){st(t,A,"Invalid Sec-WebSocket-Accept header");return}let k=I.headers["sec-websocket-protocol"],D;if(k!==void 0?v.size?v.has(k)||(D="Server sent an invalid subprotocol"):D="Server sent a subprotocol but none was requested":v.size&&(D="Server sent no subprotocol"),D){st(t,A,D);return}k&&(t._protocol=k);let z=I.headers["sec-websocket-extensions"];if(z!==void 0){if(!y){st(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let M;try{M=WE(z)}catch{st(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(M);if(Z.length!==1||Z[0]!==Tn.extensionName){st(t,A,"Server indicated an extension that was not requested");return}try{y.accept(M[Tn.extensionName])}catch{st(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tn.extensionName]=y}t.setSocket(A,C,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Oo(t,e){t._readyState=ge.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function VE(t){return t.path=t.socketPath,Mx.connect(t)}function ZE(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Mx.isIP(t.host)?"":t.host),DE.connect(t)}function st(t,e,r){t._readyState=ge.CLOSING;let i=new Error(r);Error.captureStackTrace(i,st),e.setHeader?(e[Fx]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Oo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Sd(t,e,r){if(e){let i=BE(e)?e.size:KE(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Yt[t.readyState]})`);process.nextTick(r,i)}}function JE(t,e){let r=this[Ue];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Ue]!==void 0&&(r._socket.removeListener("data",Lo),process.nextTick(Ux,r._socket),t===1005?r.close():r.close(t,e))}function YE(){let t=this[Ue];t.isPaused||t._socket.resume()}function XE(t){let e=this[Ue];e._socket[Ue]!==void 0&&(e._socket.removeListener("data",Lo),process.nextTick(Ux,e._socket),e.close(t[HE])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Nx(){this[Ue].emitClose()}function QE(t,e){this[Ue].emit("message",t,e)}function ev(t){let e=this[Ue];e._autoPong&&e.pong(t,!this._isServer,Bx),e.emit("ping",t)}function tv(t){this[Ue].emit("pong",t)}function Ux(t){t.resume()}function nv(t){let e=this[Ue];e.readyState!==ge.CLOSED&&(e.readyState===ge.OPEN&&(e._readyState=ge.CLOSING,Hx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Hx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Gx(){let t=this[Ue];if(this.removeListener("close",Gx),this.removeListener("data",Lo),this.removeListener("end",qx),t._readyState=ge.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ue]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Nx),t._receiver.on("finish",Nx))}function Lo(t){this[Ue]._receiver.write(t)||this.pause()}function qx(){let t=this[Ue];t._readyState=ge.CLOSING,t._receiver.end(),this.end()}function jx(){let t=this[Ue];this.removeListener("error",jx),this.on("error",Bx),t&&(t._readyState=ge.CLOSING,this.destroy())}});var Zx=ae((V3,Vx)=>{"use strict";var $3=No(),{Duplex:rv}=ue("stream");function Kx(t){t.emit("close")}function iv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function $x(t){this.removeListener("error",$x),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sv(t,e){let r=!0,i=new rv({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,l){let u=!l&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(Kx,i);return}let l=!1;t.once("error",function(x){l=!0,c(x)}),t.once("close",function(){l||c(o),process.nextTick(Kx,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,l){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,l)});return}t.send(o,l)},i.on("end",iv),i.on("error",$x),i}Vx.exports=sv});var Id=ae((Z3,Jx)=>{"use strict";var{tokenChars:ov}=Fr();function av(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let l=t.charCodeAt(o);if(i===-1&&ov[l]===1)r===-1&&(r=o);else if(o!==0&&(l===32||l===9))i===-1&&r!==-1&&(i=o);else if(l===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}Jx.exports={parse:av}});var rh=ae((Y3,nh)=>{"use strict";var cv=ue("events"),Mo=ue("http"),{Duplex:J3}=ue("stream"),{createHash:dv}=ue("crypto"),Yx=Po(),Zn=Br(),lv=Id(),uv=No(),{CLOSE_TIMEOUT:fv,GUID:xv,kWebSocket:hv}=Vt(),pv=/^[+/0-9A-Za-z]{22}==$/,Xx=0,Qx=1,th=2,Ad=class extends cv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:uv,...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=Mo.createServer((i,o)=>{let c=Mo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=gv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,l)=>{this.handleUpgrade(o,c,l,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Xx}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===th){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Zi,this);return}if(e&&this.once("close",e),this._state!==Qx)if(this._state=Qx,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(Zi,this):process.nextTick(Zi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Zi(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",eh);let c=e.headers["sec-websocket-key"],l=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Jn(this,e,r,405,"Invalid HTTP method");return}if(l===void 0||l.toLowerCase()!=="websocket"){Jn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!pv.test(c)){Jn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Jn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ji(r,400);return}let x=e.headers["sec-websocket-protocol"],h=new Set;if(x!==void 0)try{h=lv.parse(x)}catch{Jn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let w=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&w!==void 0){let v=new Zn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let y=Yx.parse(w);y[Zn.extensionName]&&(v.accept(y[Zn.extensionName]),_[Zn.extensionName]=v)}catch{Jn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(y,E,I,A)=>{if(!y)return Ji(r,E||401,I,A);this.completeUpgrade(_,c,h,e,r,i,o)});return}if(!this.options.verifyClient(v))return Ji(r,401)}this.completeUpgrade(_,c,h,e,r,i,o)}completeUpgrade(e,r,i,o,c,l,u){if(!c.readable||!c.writable)return c.destroy();if(c[hv])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Xx)return Ji(c,503);let h=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dv("sha1").update(r+xv).digest("base64")}`],w=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(h.push(`Sec-WebSocket-Protocol: ${_}`),w._protocol=_)}if(e[Zn.extensionName]){let _=e[Zn.extensionName].params,v=Yx.format({[Zn.extensionName]:[_]});h.push(`Sec-WebSocket-Extensions: ${v}`),w._extensions=e}this.emit("headers",h,o),c.write(h.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&as(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Tg,mkdirSync as Rg}from"node:fs";import{join as Cg}from"node:path";function wl(t){let e=t.retentionDays??Og,r=t.clock??(()=>Pn(new Date));ds={bridgeSink:new Qr(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:r}),agentSinks:new Map,makeAgentSink:o=>new Qr(t.agentLogsDir(o),"agent",{retentionDays:e,clock:r})};let i=r();as(t.bridgeLogsDir,"bridge",i,e);for(let o of t.listAgentIds?.()??[])as(t.agentLogsDir(o),"agent",i,e)}function Lg(t,e){let r=t.agentSinks.get(e);return r||(r=t.makeAgentSink(e),t.agentSinks.set(e,r)),r}function _l(t){Ia=t}function yl(t){return or[Ia]<=or[t]}function bl(t,e){let r=or[t];return r===void 0?!0:r>=or[e]}function ls(t){ml={...t}}function El(t){let e=(u,f=2)=>String(u).padStart(f,"0"),r=-t.getTimezoneOffset(),i=r>=0?"+":"-",o=Math.abs(r),c=e(Math.floor(o/60)),d=e(o%60);return`${Pn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${i}${c}:${d}`}function At(t,e,r,i,o){try{let c=`${JSON.stringify({ts:El(new Date),level:e,module:r,msg:i,...o})}
11
+ `;Rg(t,{recursive:!0}),Tg(Cg(t,sr("bridge",Pn(new Date))),c)}catch{}}function Ng(t,e){if(t)return t;let r=e?.agentId;return typeof r=="string"&&r.length>0?r:void 0}function cs(t,e,r,i,o){if(or[t]<or[Ia])return;let c=`${JSON.stringify({ts:El(new Date),level:t,module:e,msg:r,...ml,...i})}
12
+ `;if(ds){let d=Ng(o,i),u=d?Lg(ds,d):ds.bridgeSink;try{u.write(c)}catch{process.stderr.write(c)}return}t==="error"||t==="warn"?Dg.write(c):Pg.write(c)}function G(t,e){return{debug:(r,i)=>cs("debug",t,r,i,e),info:(r,i)=>cs("info",t,r,i,e),warn:(r,i)=>cs("warn",t,r,i,e),error:(r,i)=>cs("error",t,r,i,e),child:r=>G(`${t}.${r}`,e),forAgent:r=>G(t,r)}}var or,Ia,Pg,Dg,ml,Og,ds,te=Qe(()=>{"use strict";ir();Sa();or={debug:10,info:20,warn:30,error:40},Ia=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Pg=process.stdout,Dg=process.stderr,ml={},Og=Ke("COZE_BRIDGE_LOG_RETENTION_DAYS",30),ds=null});var k,qe=Qe(()=>{"use strict";k=class extends Error{code;retriable;cause;constructor(e,r,i){super(r),this.name="BridgeError",this.code=e,this.retriable=i?.retriable??!1,i?.cause!==void 0&&(this.cause=i.cause)}}});var Al={};Ea(Al,{ACP_WRAPPER_NPM_PACKAGES:()=>ti,_resetAcpInstallerForTests:()=>Gg,_setBinaryPathCacheForTests:()=>Hg,buildAcpSpawn:()=>ni,ensureAcpInstalled:()=>ar,getAcpBinaryPath:()=>us,pickWhichLine:()=>Ta,probeAcpVersion:()=>Ug,resolveAcpCommand:()=>Il});import{readFileSync as vl}from"node:fs";import{createRequire as Mg}from"node:module";import{dirname as Bg,resolve as Fg}from"node:path";function Ta(t){let e=t.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=i=>e.find(o=>o.toLowerCase().endsWith(i));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}function zg(t){let e=Sl.resolve(`${t.npmPackage}/package.json`),r=Bg(e),i=JSON.parse(vl(e,"utf8")),o=typeof i.bin=="string"?i.bin:i.bin?.[t.binary];if(!o)throw new Error(`${t.npmPackage} package.json \u7F3A bin[${t.binary}]`);return Fg(r,o)}async function ar(t,e){let r=ka[t];if(!r)throw new k("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let i=ei.get(t);if(i)return i;try{let o=zg(r);return ei.set(t,o),Aa.info("acp wrapper resolved",{framework:t,binary:r.binary,path:o}),o}catch(o){throw Aa.warn("acp wrapper \u89E3\u6790\u5931\u8D25 (\u672A\u968F\u5305\u56FA\u5316\u5230 lib/node_modules?)",{framework:t,npmPackage:r.npmPackage,err:String(o)}),new k("AGENT_DEPENDENCY_INSTALL_FAILED",[`ACP wrapper \u672A\u5C31\u7EEA: ${r.npmPackage} (framework=${t})`,"\u8BE5 wrapper \u968F coze-bridge \u4E00\u8D77\u5B89\u88C5 (\u56FA\u5316\u5230 ~/.coze/bridge/lib/node_modules)\u3002","\u8BF7\u91CD\u8DD1 `coze-bridge pair` / `connect` \u89E6\u53D1\u56FA\u5316\u5B89\u88C5; \u82E5\u4ECD\u5931\u8D25, \u68C0\u67E5\u7F51\u7EDC / npm \u7F13\u5B58\u3002"].join(`
13
+ `),{cause:o})}}async function Ug(t){let e=ka[t];if(e)try{let r=Sl.resolve(`${e.npmPackage}/package.json`),i=JSON.parse(vl(r,"utf8"));return typeof i.version=="string"&&i.version.length>0?i.version:void 0}catch(r){Aa.warn("acp wrapper probe: \u89E3\u6790 package.json \u5931\u8D25",{framework:t,npmPackage:e.npmPackage,err:String(r)});return}}function us(t){return ei.get(t)}function Il(t,e){if(e)return e;let r=us(t);if(!r)throw new k("BRIDGE_INTERNAL",`${t} ACP wrapper \u8DEF\u5F84\u672A\u89E3\u6790 (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function ni(t,e,r){if(e)return{command:e,args:[...r]};let i=Il(t);return{command:process.execPath,args:[i,...r]}}function Gg(){ei.clear()}function Hg(t,e){ei.set(t,e)}var Aa,ka,ti,Sl,ei,sn=Qe(()=>{"use strict";qe();te();Aa=G("agents.acp-installer"),ka={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp"},codex:{npmPackage:"@agentclientprotocol/codex-acp",binary:"codex-acp"}},ti=Object.values(ka).filter(t=>t!==void 0).map(t=>t.npmPackage),Sl=Mg(import.meta.url),ei=new Map});import{chmod as jg,mkdir as Wg,readFile as $g,rename as Kg,rm as Vg,writeFile as Zg}from"node:fs/promises";import{dirname as Jg}from"node:path";async function cr(t){try{let e=await $g(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function on(t,e,r){await Wg(Jg(t),{recursive:!0});let i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{await Zg(i,e,{encoding:"utf8",mode:r?.mode}),await Kg(i,t),r?.mode!==void 0&&await jg(t,r.mode)}catch(o){throw await Vg(i,{force:!0}).catch(()=>{}),o}}async function dr(t,e,r){await on(t,`${JSON.stringify(e,null,2)}
14
+ `,r)}var an=Qe(()=>{"use strict"});import{promises as Rl,readdirSync as Yg}from"node:fs";import{homedir as Xg}from"node:os";import{sep as Qg,join as Ae,resolve as Cl}from"node:path";function Q(t){let e=t??Xg(),r=Ae(e,".coze"),i=Ae(r,"bridge"),o=Ae(i,"lib"),c=Ae(i,"logs");return{cozeRoot:r,bridgeRoot:i,libDir:o,libEntry:Ae(o,"index.js"),binDir:Ae(i,"bin"),pidFile:Ae(i,"bridge.pid"),portFile:Ae(i,"bridge.port"),tokenFile:Ae(i,"bridge.token"),patTokenFile:Ae(i,"pat-token"),agentEnvFile:Ae(i,"agent-env.json"),logFile:Ae(i,"bridge.log"),bridgeLogsDir:c,daemonStdioLog:Ae(c,"daemon-stdio.log"),installLock:Ae(i,"install.lock"),configFile:Ae(i,"config.json"),agentsRoot:Ae(r,"agents")}}function Ve(t,e=Q()){let r=Ae(e.agentsRoot,t);return{root:r,config:Ae(r,"config.json"),workspace:Ae(r,"workspace"),logs:Ae(r,"logs")}}function fs(t=Q()){try{return Yg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function ri(t,e){let r=await Rl.realpath(Cl(t)).catch(()=>null);if(!r)return!1;let i=await Rl.realpath(Cl(e)).catch(()=>null);if(!i)return!1;let o=process.platform==="win32"?r.toLowerCase():r,c=process.platform==="win32"?i.toLowerCase():i;return o===c||o.startsWith(c+Qg)}var De=Qe(()=>{"use strict"});var xs={};Ea(xs,{AGENT_CONFIG_FILE_MODE:()=>hs,enforceAgentConfigMode:()=>nm,loadAgentConfig:()=>ke,persistAgentSessions:()=>ii,persistAgentSkills:()=>si,saveAgentConfig:()=>Me});import{chmod as em,stat as tm}from"node:fs/promises";function ke(t,e){return cr(Ve(t,e).config)}function Me(t,e){return dr(Ve(t.agentId,e).config,t,{mode:hs})}async function nm(t,e){if(process.platform==="win32")return;let r=Ve(t,e).config;try{let i=await tm(r);if(!i.isFile())return;let o=i.mode&511;o!==hs&&(await em(r,hs),Pl.warn("agent config mode auto-corrected to 0600",{path:r,from:o.toString(8)}))}catch(i){if(i.code==="ENOENT")return;Pl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(i)})}}async function ii(t,e,r){let i=await ke(t,r);i&&(i.sessions=Object.fromEntries(e),await Me(i,r))}async function si(t,e,r){let i=await ke(t,r);i&&(i.skills=e,await Me(i,r))}var Pl,hs,cn=Qe(()=>{"use strict";an();te();De();Pl=G("agent-config"),hs=384});var Pa=oe(($I,Ll)=>{Ll.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var gs=oe(Ml=>{var Nl={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function cm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,i)=>e[i]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Nl))Ml[t]=cm(Nl[t])});var Gl=oe((VI,Ul)=>{var dm=le("fs"),Oe=le("path"),Bl=Pa(),lm=gs(),um=typeof process=="object"&&process.platform==="win32",Fl=t=>typeof t=="object"&&t!==null,zl=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Ee(t){this.sep=Oe.sep,this.fs=dm,Fl(t)&&Fl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ul.exports=Ee;Ee.prototype.makeDir=function(t){let e=this;function r(i){let o=i.split(e.sep)[0];i.split(e.sep).forEach(function(c){if(!(!c||c.substr(-1,1)===":")){o+=e.sep+c;var d;try{d=e.fs.statSync(o)}catch(u){if(u.message&&u.message.startsWith("ENOENT"))e.fs.mkdirSync(o);else throw u}if(d&&d.isFile())throw lm.FILE_IN_THE_WAY(`"${o}"`)}})}r(t)};Ee.prototype.writeFileTo=function(t,e,r,i){let o=this;if(o.fs.existsSync(t)){if(!r)return!1;var c=o.fs.statSync(t);if(c.isDirectory())return!1}var d=Oe.dirname(t);o.fs.existsSync(d)||o.makeDir(d);var u;try{u=o.fs.openSync(t,"w",438)}catch{o.fs.chmodSync(t,438),u=o.fs.openSync(t,"w",438)}if(u)try{o.fs.writeSync(u,e,0,e.length,0)}finally{o.fs.closeSync(u)}return o.fs.chmodSync(t,i||438),!0};Ee.prototype.writeFileToAsync=function(t,e,r,i,o){typeof i=="function"&&(o=i,i=void 0);let c=this;c.fs.exists(t,function(d){if(d&&!r)return o(!1);c.fs.stat(t,function(u,f){if(d&&f.isDirectory())return o(!1);var x=Oe.dirname(t);c.fs.exists(x,function(p){p||c.makeDir(x),c.fs.open(t,"w",438,function(_,v){_?c.fs.chmod(t,438,function(){c.fs.open(t,"w",438,function(w,E){c.fs.write(E,e,0,e.length,0,function(){c.fs.close(E,function(){c.fs.chmod(t,i||438,function(){o(!0)})})})})}):v?c.fs.write(v,e,0,e.length,0,function(){c.fs.close(v,function(){c.fs.chmod(t,i||438,function(){o(!0)})})}):c.fs.chmod(t,i||438,function(){o(!0)})})})})})};Ee.prototype.findFiles=function(t){let e=this;function r(i,o,c){typeof o=="boolean"&&(c=o,o=void 0);let d=[];return e.fs.readdirSync(i).forEach(function(u){let f=Oe.join(i,u),x=e.fs.statSync(f);(!o||o.test(f))&&d.push(Oe.normalize(f)+(x.isDirectory()?e.sep:"")),x.isDirectory()&&c&&(d=d.concat(r(f,o,c)))}),d}return r(t,void 0,!0)};Ee.prototype.findFilesAsync=function(t,e){let r=this,i=[];r.fs.readdir(t,function(o,c){if(o)return e(o);let d=c.length;if(!d)return e(null,i);c.forEach(function(u){u=Oe.join(t,u),r.fs.stat(u,function(f,x){if(f)return e(f);x&&(i.push(Oe.normalize(u)+(x.isDirectory()?r.sep:"")),x.isDirectory()?r.findFilesAsync(u,function(p,_){if(p)return e(p);i=i.concat(_),--d||e(null,i)}):--d||e(null,i))})})})};Ee.prototype.getAttributes=function(){};Ee.prototype.setAttributes=function(){};Ee.crc32update=function(t,e){return zl[(t^e)&255]^t>>>8};Ee.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let i=0;i<e;)r=Ee.crc32update(r,t[i++]);return~r>>>0};Ee.methodToString=function(t){switch(t){case Bl.STORED:return"STORED ("+t+")";case Bl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Ee.canonical=function(t){if(!t)return"";let e=Oe.posix.normalize("/"+t.split("\\").join("/"));return Oe.join(".",e)};Ee.zipnamefix=function(t){if(!t)return"";let e=Oe.posix.normalize("/"+t.split("\\").join("/"));return Oe.posix.join(".",e)};Ee.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let i=r-1;i>=0;i--)if(e(t[i],i,t))return t[i]};Ee.sanitize=function(t,e){t=Oe.resolve(Oe.normalize(t));for(var r=e.split("/"),i=0,o=r.length;i<o;i++){var c=Oe.normalize(Oe.join(t,r.slice(i,o).join(Oe.sep)));if(c.indexOf(t)===0)return c}return Oe.normalize(Oe.join(t,Oe.basename(e)))};Ee.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Ee.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Ee.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};Ee.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Ee.isWin=um;Ee.crcTable=zl});var ql=oe((ZI,Hl)=>{var fm=le("path");Hl.exports=function(t,{fs:e}){var r=t||"",i=c(),o=null;function c(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(o=e.statSync(r),i.directory=o.isDirectory(),i.mtime=o.mtime,i.atime=o.atime,i.executable=(73&o.mode)!==0,i.readonly=(128&o.mode)===0,i.hidden=fm.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return i.directory},get readOnly(){return i.readonly},get hidden(){return i.hidden},get mtime(){return i.mtime},get atime(){return i.atime},get executable(){return i.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:i.directory,isReadOnly:i.readonly,isHidden:i.hidden,isExecutable:i.executable,mTime:i.mtime,aTime:i.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Wl=oe((JI,jl)=>{jl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var fr=oe((YI,ur)=>{ur.exports=Gl();ur.exports.Constants=Pa();ur.exports.Errors=gs();ur.exports.FileAttr=ql();ur.exports.decoder=Wl()});var Kl=oe((XI,$l)=>{var dn=fr(),z=dn.Constants;$l.exports=function(){var t=20,e=10,r=0,i=0,o=0,c=0,d=0,u=0,f=0,x=0,p=0,_=0,v=0,w=0,E=0;t|=dn.isWin?2560:768,r|=z.FLG_EFS;let I={extraLen:0},A=y=>Math.max(0,y)>>>0,T=y=>Math.max(0,y)&65535,D=y=>Math.max(0,y)&255;return o=dn.fromDate2DOS(new Date),{get made(){return t},set made(y){t=y},get version(){return e},set version(y){e=y},get flags(){return r},set flags(y){r=y},get flags_efs(){return(r&z.FLG_EFS)>0},set flags_efs(y){y?r|=z.FLG_EFS:r&=~z.FLG_EFS},get flags_desc(){return(r&z.FLG_DESC)>0},set flags_desc(y){y?r|=z.FLG_DESC:r&=~z.FLG_DESC},get method(){return i},set method(y){switch(y){case z.STORED:this.version=10;case z.DEFLATED:default:this.version=20}i=y},get time(){return dn.fromDOS2Date(this.timeval)},set time(y){y=new Date(y),this.timeval=dn.fromDate2DOS(y)},get timeval(){return o},set timeval(y){o=A(y)},get timeHighByte(){return D(o>>>8)},get crc(){return c},set crc(y){c=A(y)},get compressedSize(){return d},set compressedSize(y){d=A(y)},get size(){return u},set size(y){u=A(y)},get fileNameLength(){return f},set fileNameLength(y){f=y},get extraLength(){return x},set extraLength(y){x=y},get extraLocalLength(){return I.extraLen},set extraLocalLength(y){I.extraLen=y},get commentLength(){return p},set commentLength(y){p=y},get diskNumStart(){return _},set diskNumStart(y){_=A(y)},get inAttr(){return v},set inAttr(y){v=A(y)},get attr(){return w},set attr(y){w=A(y)},get fileAttr(){return(w||0)>>16&4095},get offset(){return E},set offset(y){E=A(y)},get encrypted(){return(r&z.FLG_ENC)===z.FLG_ENC},get centralHeaderSize(){return z.CENHDR+f+x+p},get realDataOffset(){return E+z.LOCHDR+I.fnameLen+I.extraLen},get localHeader(){return I},loadLocalHeaderFromBinary:function(y){var C=y.slice(E,E+z.LOCHDR);if(C.readUInt32LE(0)!==z.LOCSIG)throw dn.Errors.INVALID_LOC();I.version=C.readUInt16LE(z.LOCVER),I.flags=C.readUInt16LE(z.LOCFLG),I.flags_desc=(I.flags&z.FLG_DESC)>0,I.method=C.readUInt16LE(z.LOCHOW),I.time=C.readUInt32LE(z.LOCTIM),I.crc=C.readUInt32LE(z.LOCCRC),I.compressedSize=C.readUInt32LE(z.LOCSIZ),I.size=C.readUInt32LE(z.LOCLEN),I.fnameLen=C.readUInt16LE(z.LOCNAM),I.extraLen=C.readUInt16LE(z.LOCEXT);let O=E+z.LOCHDR+I.fnameLen,M=O+I.extraLen;return y.slice(O,M)},loadFromBinary:function(y){if(y.length!==z.CENHDR||y.readUInt32LE(0)!==z.CENSIG)throw dn.Errors.INVALID_CEN();t=y.readUInt16LE(z.CENVEM),e=y.readUInt16LE(z.CENVER),r=y.readUInt16LE(z.CENFLG),i=y.readUInt16LE(z.CENHOW),o=y.readUInt32LE(z.CENTIM),c=y.readUInt32LE(z.CENCRC),d=y.readUInt32LE(z.CENSIZ),u=y.readUInt32LE(z.CENLEN),f=y.readUInt16LE(z.CENNAM),x=y.readUInt16LE(z.CENEXT),p=y.readUInt16LE(z.CENCOM),_=y.readUInt16LE(z.CENDSK),v=y.readUInt16LE(z.CENATT),w=y.readUInt32LE(z.CENATX),E=y.readUInt32LE(z.CENOFF)},localHeaderToBinary:function(){var y=Buffer.alloc(z.LOCHDR);return y.writeUInt32LE(z.LOCSIG,0),y.writeUInt16LE(e,z.LOCVER),y.writeUInt16LE(r,z.LOCFLG),y.writeUInt16LE(i,z.LOCHOW),y.writeUInt32LE(o,z.LOCTIM),y.writeUInt32LE(c,z.LOCCRC),y.writeUInt32LE(d,z.LOCSIZ),y.writeUInt32LE(u,z.LOCLEN),y.writeUInt16LE(f,z.LOCNAM),y.writeUInt16LE(I.extraLen,z.LOCEXT),y},centralHeaderToBinary:function(){var y=Buffer.alloc(z.CENHDR+f+x+p);return y.writeUInt32LE(z.CENSIG,0),y.writeUInt16LE(t,z.CENVEM),y.writeUInt16LE(e,z.CENVER),y.writeUInt16LE(r,z.CENFLG),y.writeUInt16LE(i,z.CENHOW),y.writeUInt32LE(o,z.CENTIM),y.writeUInt32LE(c,z.CENCRC),y.writeUInt32LE(d,z.CENSIZ),y.writeUInt32LE(u,z.CENLEN),y.writeUInt16LE(f,z.CENNAM),y.writeUInt16LE(x,z.CENEXT),y.writeUInt16LE(p,z.CENCOM),y.writeUInt16LE(_,z.CENDSK),y.writeUInt16LE(v,z.CENATT),y.writeUInt32LE(w,z.CENATX),y.writeUInt32LE(E,z.CENOFF),y},toJSON:function(){let y=function(C){return C+" bytes"};return{made:t,version:e,flags:r,method:dn.methodToString(i),time:this.time,crc:"0x"+c.toString(16).toUpperCase(),compressedSize:y(d),size:y(u),fileNameLength:y(f),extraLength:y(x),commentLength:y(p),diskNumStart:_,inAttr:v,attr:w,offset:E,centralHeaderSize:y(z.CENHDR+f+x+p)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Zl=oe((QI,Vl)=>{var hr=fr(),_e=hr.Constants;Vl.exports=function(){var t=0,e=0,r=0,i=0,o=0;return{get diskEntries(){return t},set diskEntries(c){t=e=c},get totalEntries(){return e},set totalEntries(c){e=t=c},get size(){return r},set size(c){r=c},get offset(){return i},set offset(c){i=c},get commentLength(){return o},set commentLength(c){o=c},get mainHeaderSize(){return _e.ENDHDR+o},loadFromBinary:function(c){if((c.length!==_e.ENDHDR||c.readUInt32LE(0)!==_e.ENDSIG)&&(c.length<_e.ZIP64HDR||c.readUInt32LE(0)!==_e.ZIP64SIG))throw hr.Errors.INVALID_END();c.readUInt32LE(0)===_e.ENDSIG?(t=c.readUInt16LE(_e.ENDSUB),e=c.readUInt16LE(_e.ENDTOT),r=c.readUInt32LE(_e.ENDSIZ),i=c.readUInt32LE(_e.ENDOFF),o=c.readUInt16LE(_e.ENDCOM)):(t=hr.readBigUInt64LE(c,_e.ZIP64SUB),e=hr.readBigUInt64LE(c,_e.ZIP64TOT),r=hr.readBigUInt64LE(c,_e.ZIP64SIZE),i=hr.readBigUInt64LE(c,_e.ZIP64OFF),o=0)},toBinary:function(){var c=Buffer.alloc(_e.ENDHDR+o);return c.writeUInt32LE(_e.ENDSIG,0),c.writeUInt32LE(0,4),c.writeUInt16LE(t,_e.ENDSUB),c.writeUInt16LE(e,_e.ENDTOT),c.writeUInt32LE(r,_e.ENDSIZ),c.writeUInt32LE(i,_e.ENDOFF),c.writeUInt16LE(o,_e.ENDCOM),c.fill(" ",_e.ENDHDR),c},toJSON:function(){let c=function(d,u){let f=d.toString(16).toUpperCase();for(;f.length<u;)f="0"+f;return"0x"+f};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:c(i,4),commentLength:o}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Oa=oe(Da=>{Da.EntryHeader=Kl();Da.MainHeader=Zl()});var Yl=oe((tA,Jl)=>{Jl.exports=function(t){var e=le("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(i){var o=e.createDeflateRaw(r),c=[],d=0;o.on("data",function(u){c.push(u),d+=u.length}),o.on("end",function(){var u=Buffer.alloc(d),f=0;u.fill(0);for(var x=0;x<c.length;x++){var p=c[x];p.copy(u,f),f+=p.length}i&&i(u)}),o.end(t)}}}});var Ql=oe((nA,Xl)=>{var hm=+(process.versions?process.versions.node:"").split(".")[0]||0;Xl.exports=function(t,e){var r=le("zlib");let i=hm>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,i)},inflateAsync:function(o){var c=r.createInflateRaw(i),d=[],u=0;c.on("data",function(f){d.push(f),u+=f.length}),c.on("end",function(){var f=Buffer.alloc(u),x=0;f.fill(0);for(var p=0;p<d.length;p++){var _=d[p];_.copy(f,x),x+=_.length}o&&o(f)}),c.end(t)}}}});var iu=oe((rA,ru)=>{"use strict";var{randomFillSync:eu}=le("crypto"),xm=gs(),pm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),nu=(t,e)=>Math.imul(t,e)>>>0,tu=(t,e)=>pm[(t^e)&255]^t>>>8,oi=()=>typeof eu=="function"?eu(Buffer.alloc(12)):oi.node();oi.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ms={genSalt:oi};function ws(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}ws.prototype.updateKeys=function(t){let e=this.keys;return e[0]=tu(e[0],t),e[1]+=e[0]&255,e[1]=nu(e[1],134775813)+1,e[2]=tu(e[2],e[1]>>>24),t};ws.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return nu(t,t^1)>>8&255};function gm(t){let e=new ws(t);return function(r){let i=Buffer.alloc(r.length),o=0;for(let c of r)i[o++]=e.updateKeys(c^e.next());return i}}function mm(t){let e=new ws(t);return function(r,i,o=0){i||(i=Buffer.alloc(r.length));for(let c of r){let d=e.next();i[o++]=c^d,e.updateKeys(c)}return i}}function wm(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let i=gm(r),o=i(t.slice(0,12)),c=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(o[11]!==c)throw xm.WRONG_PASSWORD();return i(t.slice(12))}function _m(t){Buffer.isBuffer(t)&&t.length>=12?ms.genSalt=function(){return t.slice(0,12)}:t==="node"?ms.genSalt=oi.node:ms.genSalt=oi}function ym(t,e,r,i=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let o=mm(r),c=ms.genSalt();c[11]=e.crc>>>24&255,i&&(c[10]=e.crc>>>16&255);let d=Buffer.alloc(t.length+12);return o(c,d),o(t,d,12)}ru.exports={decrypt:wm,encrypt:ym,_salter:_m}});var su=oe(_s=>{_s.Deflater=Yl();_s.Inflater=Ql();_s.ZipCrypto=iu()});var Na=oe((sA,ou)=>{var ae=fr(),bm=Oa(),ve=ae.Constants,La=su();ou.exports=function(t,e){var r=new bm.EntryHeader,i=Buffer.alloc(0),o=Buffer.alloc(0),c=!1,d=null,u=Buffer.alloc(0),f=Buffer.alloc(0),x=!0;let p=t,_=typeof p.decoder=="object"?p.decoder:ae.decoder;x=_.hasOwnProperty("efs")?_.efs:!1;function v(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(f=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function w(y){if(!r.flags_desc&&!r.localHeader.flags_desc){if(ae.crc32(y)!==r.localHeader.crc)return!1}else{let C={},O=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(O)==ve.LOCSIG||e.readUInt32LE(O)==ve.CENSIG)throw ae.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(O)==ve.EXTSIG)C.crc=e.readUInt32LE(O+ve.EXTCRC),C.compressedSize=e.readUInt32LE(O+ve.EXTSIZ),C.size=e.readUInt32LE(O+ve.EXTLEN);else if(e.readUInt16LE(O+12)===19280)C.crc=e.readUInt32LE(O+ve.EXTCRC-4),C.compressedSize=e.readUInt32LE(O+ve.EXTSIZ-4),C.size=e.readUInt32LE(O+ve.EXTLEN-4);else throw ae.Errors.DESCRIPTOR_UNKNOWN();if(C.compressedSize!==r.compressedSize||C.size!==r.size||C.crc!==r.crc)throw ae.Errors.DESCRIPTOR_FAULTY();if(ae.crc32(y)!==C.crc)return!1}return!0}function E(y,C,O){if(typeof C>"u"&&typeof y=="string"&&(O=y,y=void 0),c)return y&&C&&C(Buffer.alloc(0),ae.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var M=v();if(M.length===0)return y&&C&&C(M),M;if(r.encrypted){if(typeof O!="string"&&!Buffer.isBuffer(O))throw ae.Errors.INVALID_PASS_PARAM();M=La.ZipCrypto.decrypt(M,r,O)}var N=Buffer.alloc(r.size);switch(r.method){case ae.Constants.STORED:if(M.copy(N),w(N))return y&&C&&C(N),N;throw y&&C&&C(N,ae.Errors.BAD_CRC()),ae.Errors.BAD_CRC();case ae.Constants.DEFLATED:var Z=new La.Inflater(M,r.size);if(y)Z.inflateAsync(function(K){K.copy(K,0),C&&(w(K)?C(K):C(K,ae.Errors.BAD_CRC()))});else{if(Z.inflate(N).copy(N,0),!w(N))throw ae.Errors.BAD_CRC(`"${_.decode(i)}"`);return N}break;default:throw y&&C&&C(Buffer.alloc(0),ae.Errors.UNKNOWN_METHOD()),ae.Errors.UNKNOWN_METHOD()}}function I(y,C){if((!d||!d.length)&&Buffer.isBuffer(e))return y&&C&&C(v()),v();if(d.length&&!c){var O;switch(r.method){case ae.Constants.STORED:return r.compressedSize=r.size,O=Buffer.alloc(d.length),d.copy(O),y&&C&&C(O),O;default:case ae.Constants.DEFLATED:var M=new La.Deflater(d);if(y)M.deflateAsync(function(Z){O=Buffer.alloc(Z.length),r.compressedSize=Z.length,Z.copy(O),C&&C(O)});else{var N=M.deflate();return r.compressedSize=N.length,N}M=null;break}}else if(y&&C)C(Buffer.alloc(0));else return Buffer.alloc(0)}function A(y,C){return ae.readBigUInt64LE(y,C)}function T(y){try{for(var C=0,O,M,N;C+4<y.length;)O=y.readUInt16LE(C),C+=2,M=y.readUInt16LE(C),C+=2,N=y.slice(C,C+M),C+=M,ve.ID_ZIP64===O&&D(N)}catch{throw ae.Errors.EXTRA_FIELD_PARSE_ERROR()}}function D(y){var C,O,M,N;y.length>=ve.EF_ZIP64_SCOMP&&(C=A(y,ve.EF_ZIP64_SUNCOMP),r.size===ve.EF_ZIP64_OR_32&&(r.size=C)),y.length>=ve.EF_ZIP64_RHO&&(O=A(y,ve.EF_ZIP64_SCOMP),r.compressedSize===ve.EF_ZIP64_OR_32&&(r.compressedSize=O)),y.length>=ve.EF_ZIP64_DSN&&(M=A(y,ve.EF_ZIP64_RHO),r.offset===ve.EF_ZIP64_OR_32&&(r.offset=M)),y.length>=ve.EF_ZIP64_DSN+4&&(N=y.readUInt32LE(ve.EF_ZIP64_DSN),r.diskNumStart===ve.EF_ZIP64_OR_16&&(r.diskNumStart=N))}return{get entryName(){return _.decode(i)},get rawEntryName(){return i},set entryName(y){i=ae.toBuffer(y,_.encode);var C=i[i.length-1];c=C===47||C===92,r.fileNameLength=i.length},get efs(){return typeof x=="function"?x(this.entryName):x},get extra(){return u},set extra(y){u=y,r.extraLength=y.length,T(y)},get comment(){return _.decode(o)},set comment(y){if(o=ae.toBuffer(y,_.encode),r.commentLength=o.length,o.length>65535)throw ae.Errors.COMMENT_TOO_LONG()},get name(){var y=_.decode(i);return c?y.substr(y.length-1).split("/").pop():y.split("/").pop()},get isDirectory(){return c},getCompressedData:function(){return I(!1,null)},getCompressedDataAsync:function(y){I(!0,y)},setData:function(y){d=ae.toBuffer(y,ae.decoder.encode),!c&&d.length?(r.size=d.length,r.method=ae.Constants.DEFLATED,r.crc=ae.crc32(y),r.changed=!0):r.method=ae.Constants.STORED},getData:function(y){return r.changed?d:E(!1,null,y)},getDataAsync:function(y,C){r.changed?y(d):E(!0,y,C)},set attr(y){r.attr=y},get attr(){return r.attr},set header(y){r.loadFromBinary(y)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=u.length;var y=r.centralHeaderToBinary(),C=ae.Constants.CENHDR;return i.copy(y,C),C+=i.length,u.copy(y,C),C+=r.extraLength,o.copy(y,C),y},packLocalHeader:function(){let y=0;r.flags_efs=this.efs,r.extraLocalLength=f.length;let C=r.localHeaderToBinary(),O=Buffer.alloc(C.length+i.length+r.extraLocalLength);return C.copy(O,y),y+=C.length,i.copy(O,y),y+=i.length,f.copy(O,y),y+=f.length,O},toJSON:function(){let y=function(C){return"<"+(C&&C.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:y(e),data:y(d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var du=oe((oA,cu)=>{var au=Na(),Em=Oa(),je=fr();cu.exports=function(t,e){var r=[],i={},o=Buffer.alloc(0),c=new Em.MainHeader,d=!1,u=null;let f=new Set,x=e,{noSort:p,decoder:_}=x;t?E(x.readEntries):d=!0;function v(){let A=new Set;for(let T of Object.keys(i)){let D=T.split("/");if(D.pop(),!!D.length)for(let y=0;y<D.length;y++){let C=D.slice(0,y+1).join("/")+"/";A.add(C)}}for(let T of A)if(!(T in i)){let D=new au(x);D.entryName=T,D.attr=16,D.temporary=!0,r.push(D),i[D.entryName]=D,f.add(D)}}function w(){if(d=!0,i={},c.diskEntries>(t.length-c.offset)/je.Constants.CENHDR)throw je.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(c.diskEntries);for(var A=c.offset,T=0;T<r.length;T++){var D=A,y=new au(x,t);y.header=t.slice(D,D+=je.Constants.CENHDR),y.entryName=t.slice(D,D+=y.header.fileNameLength),y.header.extraLength&&(y.extra=t.slice(D,D+=y.header.extraLength)),y.header.commentLength&&(y.comment=t.slice(D,D+y.header.commentLength)),A+=y.header.centralHeaderSize,r[T]=y,i[y.entryName]=y}f.clear(),v()}function E(A){var T=t.length-je.Constants.ENDHDR,D=Math.max(0,T-65535),y=D,C=t.length,O=-1,M=0;for(typeof x.trailingSpace=="boolean"&&x.trailingSpace&&(D=0),T;T>=y;T--)if(t[T]===80){if(t.readUInt32LE(T)===je.Constants.ENDSIG){O=T,M=T,C=T+je.Constants.ENDHDR,y=T-je.Constants.END64HDR;continue}if(t.readUInt32LE(T)===je.Constants.END64SIG){y=D;continue}if(t.readUInt32LE(T)===je.Constants.ZIP64SIG){O=T,C=T+je.readBigUInt64LE(t,T+je.Constants.ZIP64SIZE)+je.Constants.ZIP64LEAD;break}}if(O==-1)throw je.Errors.INVALID_FORMAT();c.loadFromBinary(t.slice(O,C)),c.commentLength&&(o=t.slice(M+je.Constants.ENDHDR)),A&&w()}function I(){r.length>1&&!p&&r.sort((A,T)=>A.entryName.toLowerCase().localeCompare(T.entryName.toLowerCase()))}return{get entries(){return d||w(),r.filter(A=>!f.has(A))},get comment(){return _.decode(o)},set comment(A){o=je.toBuffer(A,_.encode),c.commentLength=o.length},getEntryCount:function(){return d?r.length:c.diskEntries},forEach:function(A){this.entries.forEach(A)},getEntry:function(A){return d||w(),i[A]||null},setEntry:function(A){d||w(),r.push(A),i[A.entryName]=A,c.totalEntries=r.length},deleteFile:function(A,T=!0){d||w();let D=i[A];this.getEntryChildren(D,T).map(C=>C.entryName).forEach(this.deleteEntry)},deleteEntry:function(A){d||w();let T=i[A],D=r.indexOf(T);D>=0&&(r.splice(D,1),delete i[A],c.totalEntries=r.length)},getEntryChildren:function(A,T=!0){if(d||w(),typeof A=="object")if(A.isDirectory&&T){let D=[],y=A.entryName;for(let C of r)C.entryName.startsWith(y)&&D.push(C);return D}else return[A];return[]},getChildCount:function(A){if(A&&A.isDirectory){let T=this.getEntryChildren(A);return T.includes(A)?T.length-1:T.length}return 0},compressToBuffer:function(){d||w(),I();let A=[],T=[],D=0,y=0;c.size=0,c.offset=0;let C=0;for(let N of this.entries){let Z=N.getCompressedData();N.header.offset=y;let K=N.packLocalHeader(),ne=K.length+Z.length;y+=ne,A.push(K),A.push(Z);let Y=N.packCentralHeader();T.push(Y),c.size+=Y.length,D+=ne+Y.length,C++}D+=c.mainHeaderSize,c.offset=y,c.totalEntries=C,y=0;let O=Buffer.alloc(D);for(let N of A)N.copy(O,y),y+=N.length;for(let N of T)N.copy(O,y),y+=N.length;let M=c.toBinary();return o&&o.copy(M,je.Constants.ENDHDR),M.copy(O,y),t=O,d=!1,O},toAsyncBuffer:function(A,T,D,y){try{d||w(),I();let C=[],O=[],M=0,N=0,Z=0;c.size=0,c.offset=0;let K=function(ne){if(ne.length>0){let Y=ne.shift(),ie=Y.entryName+Y.extra.toString();D&&D(ie),Y.getCompressedDataAsync(function(se){y&&y(ie),Y.header.offset=N;let P=Y.packLocalHeader(),U=P.length+se.length;N+=U,C.push(P),C.push(se);let j=Y.packCentralHeader();O.push(j),c.size+=j.length,M+=U+j.length,Z++,K(ne)})}else{M+=c.mainHeaderSize,c.offset=N,c.totalEntries=Z,N=0;let Y=Buffer.alloc(M);C.forEach(function(se){se.copy(Y,N),N+=se.length}),O.forEach(function(se){se.copy(Y,N),N+=se.length});let ie=c.toBinary();o&&o.copy(ie,je.Constants.ENDHDR),ie.copy(Y,N),t=Y,d=!1,A(Y)}};K(Array.from(this.entries))}catch(C){T(C)}}}}});var fu=oe((aA,uu)=>{var be=fr(),ye=le("path"),vm=Na(),Sm=du(),Dn=(...t)=>be.findLast(t,e=>typeof e=="boolean"),lu=(...t)=>be.findLast(t,e=>typeof e=="string"),Im=(...t)=>be.findLast(t,e=>typeof e=="function"),Am={noSort:!1,readEntries:!1,method:be.Constants.NONE,fs:null};uu.exports=function(t,e){let r=null,i=Object.assign(Object.create(null),Am);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(i,t),t=i.input?i.input:void 0,i.input&&delete i.input),Buffer.isBuffer(t)&&(r=t,i.method=be.Constants.BUFFER,t=void 0)),Object.assign(i,e);let o=new be(i);if((typeof i.decoder!="object"||typeof i.decoder.encode!="function"||typeof i.decoder.decode!="function")&&(i.decoder=be.decoder),t&&typeof t=="string")if(o.fs.existsSync(t))i.method=be.Constants.FILE,i.filename=t,r=o.fs.readFileSync(t);else throw be.Errors.INVALID_FILENAME();let c=new Sm(r,i),{canonical:d,sanitize:u,zipnamefix:f}=be;function x(w){if(w&&c){var E;if(typeof w=="string"&&(E=c.getEntry(ye.posix.normalize(w))),typeof w=="object"&&typeof w.entryName<"u"&&typeof w.header<"u"&&(E=c.getEntry(w.entryName)),E)return E}return null}function p(w){let{join:E,normalize:I,sep:A}=ye.posix;return E(ye.isAbsolute(w)?"/":".",I(A+w.split("\\").join(A)+A))}function _(w){return w instanceof RegExp?(function(E){return function(I){return E.test(I)}})(w):typeof w!="function"?()=>!0:w}let v=(w,E)=>{let I=E.slice(-1);return I=I===o.sep?o.sep:"",ye.relative(w,E)+I};return{readFile:function(w,E){var I=x(w);return I&&I.getData(E)||null},childCount:function(w){let E=x(w);if(E)return c.getChildCount(E)},readFileAsync:function(w,E){var I=x(w);I?I.getDataAsync(E):E(null,"getEntry failed for:"+w)},readAsText:function(w,E){var I=x(w);if(I){var A=I.getData();if(A&&A.length)return A.toString(E||"utf8")}return""},readAsTextAsync:function(w,E,I){var A=x(w);A?A.getDataAsync(function(T,D){if(D){E(T,D);return}T&&T.length?E(T.toString(I||"utf8")):E("")}):E("")},deleteFile:function(w,E=!0){var I=x(w);I&&c.deleteFile(I.entryName,E)},deleteEntry:function(w){var E=x(w);E&&c.deleteEntry(E.entryName)},addZipComment:function(w){c.comment=w},getZipComment:function(){return c.comment||""},addZipEntryComment:function(w,E){var I=x(w);I&&(I.comment=E)},getZipEntryComment:function(w){var E=x(w);return E&&E.comment||""},updateFile:function(w,E){var I=x(w);I&&I.setData(E)},addLocalFile:function(w,E,I,A){if(o.fs.existsSync(w)){E=E?p(E):"";let T=ye.win32.basename(ye.win32.normalize(w));E+=I||T;let D=o.fs.statSync(w),y=D.isFile()?o.fs.readFileSync(w):Buffer.alloc(0);D.isDirectory()&&(E+=o.sep),this.addFile(E,y,A,D)}else throw be.Errors.FILE_NOT_FOUND(w)},addLocalFileAsync:function(w,E){w=typeof w=="object"?w:{localPath:w};let I=ye.resolve(w.localPath),{comment:A}=w,{zipPath:T,zipName:D}=w,y=this;o.fs.stat(I,function(C,O){if(C)return E(C,!1);T=T?p(T):"";let M=ye.win32.basename(ye.win32.normalize(I));if(T+=D||M,O.isFile())o.fs.readFile(I,function(N,Z){return N?E(N,!1):(y.addFile(T,Z,A,O),setImmediate(E,void 0,!0))});else if(O.isDirectory())return T+=o.sep,y.addFile(T,Buffer.alloc(0),A,O),setImmediate(E,void 0,!0)})},addLocalFolder:function(w,E,I){if(I=_(I),E=E?p(E):"",w=ye.normalize(w),o.fs.existsSync(w)){let A=o.findFiles(w),T=this;if(A.length)for(let D of A){let y=ye.join(E,v(w,D));I(y)&&T.addLocalFile(D,ye.dirname(y))}}else throw be.Errors.FILE_NOT_FOUND(w)},addLocalFolderAsync:function(w,E,I,A){A=_(A),I=I?p(I):"",w=ye.normalize(w);var T=this;o.fs.open(w,"r",function(D){if(D&&D.code==="ENOENT")E(void 0,be.Errors.FILE_NOT_FOUND(w));else if(D)E(void 0,D);else{var y=o.findFiles(w),C=-1,O=function(){if(C+=1,C<y.length){var M=y[C],N=v(w,M).split("\\").join("/");N=N.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),A(N)?o.fs.stat(M,function(Z,K){Z&&E(void 0,Z),K.isFile()?o.fs.readFile(M,function(ne,Y){ne?E(void 0,ne):(T.addFile(I+N,Y,"",K),O())}):(T.addFile(I+N+"/",Buffer.alloc(0),"",K),O())}):process.nextTick(()=>{O()})}else E(!0,void 0)};O()}})},addLocalFolderAsync2:function(w,E){let I=this;w=typeof w=="object"?w:{localPath:w},localPath=ye.resolve(p(w.localPath));let{zipPath:A,filter:T,namefix:D}=w;T instanceof RegExp?T=(function(O){return function(M){return O.test(M)}})(T):typeof T!="function"&&(T=function(){return!0}),A=A?p(A):"",D=="latin1"&&(D=O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof D!="function"&&(D=O=>O);let y=O=>ye.join(A,D(v(localPath,O))),C=O=>ye.win32.basename(ye.win32.normalize(D(O)));o.fs.open(localPath,"r",function(O){O&&O.code==="ENOENT"?E(void 0,be.Errors.FILE_NOT_FOUND(localPath)):O?E(void 0,O):o.findFilesAsync(localPath,function(M,N){if(M)return E(M);N=N.filter(Z=>T(y(Z))),N.length||E(void 0,!1),setImmediate(N.reverse().reduce(function(Z,K){return function(ne,Y){if(ne||Y===!1)return setImmediate(Z,ne,!1);I.addLocalFileAsync({localPath:K,zipPath:ye.dirname(y(K)),zipName:C(K)},Z)}},E))})})},addLocalFolderPromise:function(w,E){return new Promise((I,A)=>{this.addLocalFolderAsync2(Object.assign({localPath:w},E),(T,D)=>{T&&A(T),D&&I(this)})})},addFile:function(w,E,I,A){w=f(w);let T=x(w),D=T!=null;D||(T=new vm(i),T.entryName=w),T.comment=I||"";let y=typeof A=="object"&&A instanceof o.fs.Stats;y&&(T.header.time=A.mtime);var C=T.isDirectory?16:0;let O=T.isDirectory?16384:32768;return y?O|=4095&A.mode:typeof A=="number"?O|=4095&A:O|=T.isDirectory?493:420,C=(C|O<<16)>>>0,T.attr=C,T.setData(E),D||c.setEntry(T),T},getEntries:function(w){return c.password=w,c?c.entries:[]},getEntry:function(w){return x(w)},getEntryCount:function(){return c.getEntryCount()},forEach:function(w){return c.forEach(w)},extractEntryTo:function(w,E,I,A,T,D){A=Dn(!1,A),T=Dn(!1,T),I=Dn(!0,I),D=lu(T,D);var y=x(w);if(!y)throw be.Errors.NO_ENTRY();var C=d(y.entryName),O=u(E,D&&!y.isDirectory?D:I?C:ye.basename(C));if(y.isDirectory){var M=c.getEntryChildren(y);return M.forEach(function(K){if(K.isDirectory)return;var ne=K.getData();if(!ne)throw be.Errors.CANT_EXTRACT_FILE();var Y=d(K.entryName),ie=u(E,I?Y:ye.basename(Y));let se=T?K.header.fileAttr:void 0;o.writeFileTo(ie,ne,A,se)}),!0}var N=y.getData(c.password);if(!N)throw be.Errors.CANT_EXTRACT_FILE();if(o.fs.existsSync(O)&&!A)throw be.Errors.CANT_OVERRIDE();let Z=T?w.header.fileAttr:void 0;return o.writeFileTo(O,N,A,Z),!0},test:function(w){if(!c)return!1;for(var E in c.entries)try{if(E.isDirectory)continue;var I=c.entries[E].getData(w);if(!I)return!1}catch{return!1}return!0},extractAllTo:function(w,E,I,A){if(I=Dn(!1,I),A=lu(I,A),E=Dn(!1,E),!c)throw be.Errors.NO_ZIP();c.entries.forEach(function(T){var D=u(w,d(T.entryName));if(T.isDirectory){o.makeDir(D);return}var y=T.getData(A);if(!y)throw be.Errors.CANT_EXTRACT_FILE();let C=I?T.header.fileAttr:void 0;o.writeFileTo(D,y,E,C);try{o.fs.utimesSync(D,T.header.time,T.header.time)}catch{throw be.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(w,E,I,A){if(A=Im(E,I,A),I=Dn(!1,I),E=Dn(!1,E),!A)return new Promise((O,M)=>{this.extractAllToAsync(w,E,I,function(N){N?M(N):O(this)})});if(!c){A(be.Errors.NO_ZIP());return}w=ye.resolve(w);let T=O=>u(w,ye.normalize(d(O.entryName))),D=(O,M)=>new Error(O+': "'+M+'"'),y=[],C=[];c.entries.forEach(O=>{O.isDirectory?y.push(O):C.push(O)});for(let O of y){let M=T(O),N=I?O.header.fileAttr:void 0;try{o.makeDir(M),N&&o.fs.chmodSync(M,N),o.fs.utimesSync(M,O.header.time,O.header.time)}catch{A(D("Unable to create folder",M))}}C.reverse().reduce(function(O,M){return function(N){if(N)O(N);else{let Z=ye.normalize(d(M.entryName)),K=u(w,Z);M.getDataAsync(function(ne,Y){if(Y)O(Y);else if(!ne)O(be.Errors.CANT_EXTRACT_FILE());else{let ie=I?M.header.fileAttr:void 0;o.writeFileToAsync(K,ne,E,ie,function(se){se||O(D("Unable to write file",K)),o.fs.utimes(K,M.header.time,M.header.time,function(P){P?O(D("Unable to set times",K)):O()})})}})}}},A)()},writeZip:function(w,E){if(arguments.length===1&&typeof w=="function"&&(E=w,w=""),!w&&i.filename&&(w=i.filename),!!w){var I=c.compressToBuffer();if(I){var A=o.writeFileTo(w,I,!0);typeof E=="function"&&E(A?null:new Error("failed"),"")}}},writeZipPromise:function(w,E){let{overwrite:I,perm:A}=Object.assign({overwrite:!0},E);return new Promise((T,D)=>{!w&&i.filename&&(w=i.filename),w||D("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(y=>{let C=O=>O?T(O):D("ADM-ZIP: Wasn't able to write zip file");o.writeFileToAsync(w,y,I,A,C)},D)})},toBufferPromise:function(){return new Promise((w,E)=>{c.toAsyncBuffer(w,E)})},toBuffer:function(w,E,I,A){return typeof w=="function"?(c.toAsyncBuffer(w,E,I,A),null):c.compressToBuffer()}}}});import{execFile as D_,spawn as O_,spawnSync as I2}from"node:child_process";import{promisify as L_}from"node:util";function M_(t){if(process.platform!=="win32")return!1;if(Df.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(Df,"").toLowerCase();return N_.has(r)}function Of(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return M_(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function nt(t,e=[],r={}){return O_(t,e,Of(t,r))}function Lf(t,e=[],r={}){return B_(t,e,Of(t,r))}var N_,Df,B_,Kt=Qe(()=>{"use strict";N_=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Df=/\.(cmd|bat|ps1)$/i;B_=L_(D_)});var Zt=oe((fC,wh)=>{"use strict";var gh=["nodebuffer","arraybuffer","fragments"],mh=typeof Blob<"u";mh&&gh.push("blob");wh.exports={BINARY_TYPES:gh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:mh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ki=oe((hC,Ao)=>{"use strict";var{EMPTY_BUFFER:gE}=Zt(),ud=Buffer[Symbol.species];function mE(t,e){if(t.length===0)return gE;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),i=0;for(let o=0;o<t.length;o++){let c=t[o];r.set(c,i),i+=c.length}return i<e?new ud(r.buffer,r.byteOffset,i):r}function _h(t,e,r,i,o){for(let c=0;c<o;c++)r[i+c]=t[c]^e[c&3]}function yh(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function wE(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function fd(t){if(fd.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ud(t):ArrayBuffer.isView(t)?e=new ud(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),fd.readOnly=!1),e}Ao.exports={concat:mE,mask:_h,toArrayBuffer:wE,toBuffer:fd,unmask:yh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=le("bufferutil");Ao.exports.mask=function(e,r,i,o,c){c<48?_h(e,r,i,o,c):t.mask(e,r,i,o,c)},Ao.exports.unmask=function(e,r){e.length<32?yh(e,r):t.unmask(e,r)}}catch{}});var vh=oe((xC,Eh)=>{"use strict";var bh=Symbol("kDone"),hd=Symbol("kRun"),xd=class{constructor(e){this[bh]=()=>{this.pending--,this[hd]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[hd]()}[hd](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bh])}}};Eh.exports=xd});var zr=oe((pC,kh)=>{"use strict";var Vi=le("zlib"),Sh=Ki(),_E=vh(),{kStatusCode:Ih}=Zt(),yE=Buffer[Symbol.species],bE=Buffer.from([0,0,255,255]),To=Symbol("permessage-deflate"),Jt=Symbol("total-length"),Br=Symbol("callback"),kn=Symbol("buffers"),Fr=Symbol("error"),ko,pd=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,!ko){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ko=new _E(r)}}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[Br];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,i=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(i.server_no_context_takeover=!0),r.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(i.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?i.client_max_window_bits=r.clientMaxWindowBits:(i.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(i=>{let o=r[i];if(o.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(o=o[0],i==="client_max_window_bits"){if(o!==!0){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else if(i==="server_max_window_bits"){let c=+o;if(!Number.isInteger(c)||c<8||c>15)throw new TypeError(`Invalid value for parameter "${i}": ${o}`);o=c}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${o}`)}else throw new Error(`Unknown parameter "${i}"`);r[i]=o})}),e}decompress(e,r,i){ko.add(o=>{this._decompress(e,r,(c,d)=>{o(),i(c,d)})})}compress(e,r,i){ko.add(o=>{this._compress(e,r,(c,d)=>{o(),i(c,d)})})}_decompress(e,r,i){let o=this._isServer?"client":"server";if(!this._inflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._inflate=Vi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:d}),this._inflate[To]=this,this._inflate[Jt]=0,this._inflate[kn]=[],this._inflate.on("error",vE),this._inflate.on("data",Ah)}this._inflate[Br]=i,this._inflate.write(e),r&&this._inflate.write(bE),this._inflate.flush(()=>{let c=this._inflate[Fr];if(c){this._inflate.close(),this._inflate=null,i(c);return}let d=Sh.concat(this._inflate[kn],this._inflate[Jt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Jt]=0,this._inflate[kn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),i(null,d)})}_compress(e,r,i){let o=this._isServer?"server":"client";if(!this._deflate){let c=`${o}_max_window_bits`,d=typeof this.params[c]!="number"?Vi.Z_DEFAULT_WINDOWBITS:this.params[c];this._deflate=Vi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:d}),this._deflate[Jt]=0,this._deflate[kn]=[],this._deflate.on("data",EE)}this._deflate[Br]=i,this._deflate.write(e),this._deflate.flush(Vi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let c=Sh.concat(this._deflate[kn],this._deflate[Jt]);r&&(c=new yE(c.buffer,c.byteOffset,c.length-4)),this._deflate[Br]=null,this._deflate[Jt]=0,this._deflate[kn]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),i(null,c)})}};kh.exports=pd;function EE(t){this[kn].push(t),this[Jt]+=t.length}function Ah(t){if(this[Jt]+=t.length,this[To]._maxPayload<1||this[Jt]<=this[To]._maxPayload){this[kn].push(t);return}this[Fr]=new RangeError("Max payload size exceeded"),this[Fr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Fr][Ih]=1009,this.removeListener("data",Ah),this.reset()}function vE(t){if(this[To]._inflate=null,this[Fr]){this[Br](this[Fr]);return}t[Ih]=1007,this[Br](t)}});var Ur=oe((gC,Ro)=>{"use strict";var{isUtf8:Th}=le("buffer"),{hasBlob:SE}=Zt(),IE=[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 AE(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function gd(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function kE(t){return SE&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ro.exports={isBlob:kE,isValidStatusCode:AE,isValidUTF8:gd,tokenChars:IE};if(Th)Ro.exports.isValidUTF8=function(t){return t.length<24?gd(t):Th(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=le("utf-8-validate");Ro.exports.isValidUTF8=function(e){return e.length<32?gd(e):t(e)}}catch{}});var bd=oe((mC,Nh)=>{"use strict";var{Writable:TE}=le("stream"),Rh=zr(),{BINARY_TYPES:RE,EMPTY_BUFFER:Ch,kStatusCode:CE,kWebSocket:PE}=Zt(),{concat:md,toArrayBuffer:DE,unmask:OE}=Ki(),{isValidStatusCode:LE,isValidUTF8:Ph}=Ur(),Co=Buffer[Symbol.species],ht=0,Dh=1,Oh=2,Lh=3,wd=4,_d=5,Po=6,yd=class extends TE{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||RE[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[PE]=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=ht}_write(e,r,i){if(this._opcode===8&&this._state==ht)return i();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){i(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new Co(i.buffer,i.byteOffset+e,i.length-e),new Co(i.buffer,i.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let i=this._buffers[0],o=r.length-e;e>=i.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(i.buffer,i.byteOffset,e),o),this._buffers[0]=new Co(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case ht:this.getInfo(e);break;case Dh:this.getPayloadLength16(e);break;case Oh:this.getPayloadLength64(e);break;case Lh:this.getMask();break;case wd:this.getData(e);break;case _d:case Po:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let i=(r[0]&64)===64;if(i&&!this._extensions[Rh.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(i){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=Dh:this._payloadLength===127?this._state=Oh: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 r=this.consume(8),i=r.readUInt32BE(0);if(i>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=i*Math.pow(2,32)+r.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 r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=Lh:this._state=wd}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=wd}getData(e){let r=Ch;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&OE(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=_d,this.decompress(r,e);return}if(r.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let i=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(i);return}this._messageLength=this._totalPayloadLength,this._fragments.push(r)}this.dataMessage(e)}decompress(e,r){this._extensions[Rh.extensionName].decompress(e,this._fin,(o,c)=>{if(o)return r(o);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let d=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(d);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let d=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");r(d);return}this._fragments.push(c)}this.dataMessage(r),this._state===ht&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=ht;return}let r=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=md(i,r):this._binaryType==="arraybuffer"?o=DE(md(i,r)):this._binaryType==="blob"?o=new Blob(i):o=i,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=ht):(this._state=Po,setImmediate(()=>{this.emit("message",o,!0),this._state=ht,this.startLoop(e)}))}else{let o=md(i,r);if(!this._skipUTF8Validation&&!Ph(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(c);return}this._state===_d||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=ht):(this._state=Po,setImmediate(()=>{this.emit("message",o,!1),this._state=ht,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ch),this.end();else{let i=e.readUInt16BE(0);if(!LE(i)){let c=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(c);return}let o=new Co(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ph(o)){let c=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(c);return}this._loop=!1,this.emit("conclude",i,o),this.end()}this._state=ht;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ht):(this._state=Po,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ht,this.startLoop(r)}))}createError(e,r,i,o,c){this._loop=!1,this._errored=!0;let d=new e(i?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(d,this.createError),d.code=c,d[CE]=o,d}};Nh.exports=yd});var Sd=oe((_C,Fh)=>{"use strict";var{Duplex:wC}=le("stream"),{randomFillSync:NE}=le("crypto"),{types:{isUint8Array:ME}}=le("util"),Mh=zr(),{EMPTY_BUFFER:BE,kWebSocket:FE,NOOP:zE}=Zt(),{isBlob:Gr,isValidStatusCode:UE}=Ur(),{mask:Bh,toBuffer:Vn}=Ki(),xt=Symbol("kByteLength"),GE=Buffer.alloc(4),Do=8*1024,Zn,Hr=Do,St=0,HE=1,qE=2,Ed=class t{constructor(e,r,i){this._extensions=r||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=St,this.onerror=zE,this[FE]=void 0}static frame(e,r){let i,o=!1,c=2,d=!1;r.mask&&(i=r.maskBuffer||GE,r.generateMask?r.generateMask(i):(Hr===Do&&(Zn===void 0&&(Zn=Buffer.alloc(Do)),NE(Zn,0,Do),Hr=0),i[0]=Zn[Hr++],i[1]=Zn[Hr++],i[2]=Zn[Hr++],i[3]=Zn[Hr++]),d=(i[0]|i[1]|i[2]|i[3])===0,c=6);let u;typeof e=="string"?(!r.mask||d)&&r[xt]!==void 0?u=r[xt]:(e=Buffer.from(e),u=e.length):(u=e.length,o=r.mask&&r.readOnly&&!d);let f=u;u>=65536?(c+=8,f=127):u>125&&(c+=2,f=126);let x=Buffer.allocUnsafe(o?u+c:c);return x[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(x[0]|=64),x[1]=f,f===126?x.writeUInt16BE(u,2):f===127&&(x[2]=x[3]=0,x.writeUIntBE(u,4,6)),r.mask?(x[1]|=128,x[c-4]=i[0],x[c-3]=i[1],x[c-2]=i[2],x[c-1]=i[3],d?[x,e]:o?(Bh(e,i,x,c,u),[x]):(Bh(e,i,e,0,u),[x,e])):[x,e]}close(e,r,i,o){let c;if(e===void 0)c=BE;else{if(typeof e!="number"||!UE(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)c=Buffer.allocUnsafe(2),c.writeUInt16BE(e,0);else{let u=Buffer.byteLength(r);if(u>123)throw new RangeError("The message must not be greater than 123 bytes");if(c=Buffer.allocUnsafe(2+u),c.writeUInt16BE(e,0),typeof r=="string")c.write(r,2);else if(ME(r))c.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let d={[xt]:c.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==St?this.enqueue([this.dispatch,c,!1,d,o]):this.sendFrame(t.frame(c,d),o)}ping(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}pong(e,r,i){let o,c;if(typeof e=="string"?(o=Buffer.byteLength(e),c=!1):Gr(e)?(o=e.size,c=!1):(e=Vn(e),o=e.length,c=Vn.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let d={[xt]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:c,rsv1:!1};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,!1,d,i]):this.getBlobData(e,!1,d,i):this._state!==St?this.enqueue([this.dispatch,e,!1,d,i]):this.sendFrame(t.frame(e,d),i)}send(e,r,i){let o=this._extensions[Mh.extensionName],c=r.binary?2:1,d=r.compress,u,f;typeof e=="string"?(u=Buffer.byteLength(e),f=!1):Gr(e)?(u=e.size,f=!1):(e=Vn(e),u=e.length,f=Vn.readOnly),this._firstFragment?(this._firstFragment=!1,d&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(d=u>=o._threshold),this._compress=d):(d=!1,c=0),r.fin&&(this._firstFragment=!0);let x={[xt]:u,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:c,readOnly:f,rsv1:d};Gr(e)?this._state!==St?this.enqueue([this.getBlobData,e,this._compress,x,i]):this.getBlobData(e,this._compress,x,i):this._state!==St?this.enqueue([this.dispatch,e,this._compress,x,i]):this.dispatch(e,this._compress,x,i)}getBlobData(e,r,i,o){this._bufferedBytes+=i[xt],this._state=qE,e.arrayBuffer().then(c=>{if(this._socket.destroyed){let u=new Error("The socket was closed while the blob was being read");process.nextTick(vd,this,u,o);return}this._bufferedBytes-=i[xt];let d=Vn(c);r?this.dispatch(d,r,i,o):(this._state=St,this.sendFrame(t.frame(d,i),o),this.dequeue())}).catch(c=>{process.nextTick(jE,this,c,o)})}dispatch(e,r,i,o){if(!r){this.sendFrame(t.frame(e,i),o);return}let c=this._extensions[Mh.extensionName];this._bufferedBytes+=i[xt],this._state=HE,c.compress(e,i.fin,(d,u)=>{if(this._socket.destroyed){let f=new Error("The socket was closed while data was being compressed");vd(this,f,o);return}this._bufferedBytes-=i[xt],this._state=St,i.readOnly=!1,this.sendFrame(t.frame(u,i),o),this.dequeue()})}dequeue(){for(;this._state===St&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][xt],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][xt],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Fh.exports=Ed;function vd(t,e,r){typeof r=="function"&&r(e);for(let i=0;i<t._queue.length;i++){let o=t._queue[i],c=o[o.length-1];typeof c=="function"&&c(e)}}function jE(t,e,r){vd(t,e,r),t.onerror(e)}});var Kh=oe((yC,$h)=>{"use strict";var{kForOnEventAttribute:Zi,kListener:Id}=Zt(),zh=Symbol("kCode"),Uh=Symbol("kData"),Gh=Symbol("kError"),Hh=Symbol("kMessage"),qh=Symbol("kReason"),qr=Symbol("kTarget"),jh=Symbol("kType"),Wh=Symbol("kWasClean"),Yt=class{constructor(e){this[qr]=null,this[jh]=e}get target(){return this[qr]}get type(){return this[jh]}};Object.defineProperty(Yt.prototype,"target",{enumerable:!0});Object.defineProperty(Yt.prototype,"type",{enumerable:!0});var Jn=class extends Yt{constructor(e,r={}){super(e),this[zh]=r.code===void 0?0:r.code,this[qh]=r.reason===void 0?"":r.reason,this[Wh]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[zh]}get reason(){return this[qh]}get wasClean(){return this[Wh]}};Object.defineProperty(Jn.prototype,"code",{enumerable:!0});Object.defineProperty(Jn.prototype,"reason",{enumerable:!0});Object.defineProperty(Jn.prototype,"wasClean",{enumerable:!0});var jr=class extends Yt{constructor(e,r={}){super(e),this[Gh]=r.error===void 0?null:r.error,this[Hh]=r.message===void 0?"":r.message}get error(){return this[Gh]}get message(){return this[Hh]}};Object.defineProperty(jr.prototype,"error",{enumerable:!0});Object.defineProperty(jr.prototype,"message",{enumerable:!0});var Ji=class extends Yt{constructor(e,r={}){super(e),this[Uh]=r.data===void 0?null:r.data}get data(){return this[Uh]}};Object.defineProperty(Ji.prototype,"data",{enumerable:!0});var WE={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Zi]&&o[Id]===e&&!o[Zi])return;let i;if(t==="message")i=function(c,d){let u=new Ji("message",{data:d?c:c.toString()});u[qr]=this,Oo(e,this,u)};else if(t==="close")i=function(c,d){let u=new Jn("close",{code:c,reason:d.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});u[qr]=this,Oo(e,this,u)};else if(t==="error")i=function(c){let d=new jr("error",{error:c,message:c.message});d[qr]=this,Oo(e,this,d)};else if(t==="open")i=function(){let c=new Yt("open");c[qr]=this,Oo(e,this,c)};else return;i[Zi]=!!r[Zi],i[Id]=e,r.once?this.once(t,i):this.on(t,i)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Id]===e&&!r[Zi]){this.removeListener(t,r);break}}};$h.exports={CloseEvent:Jn,ErrorEvent:jr,Event:Yt,EventTarget:WE,MessageEvent:Ji};function Oo(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Lo=oe((bC,Vh)=>{"use strict";var{tokenChars:Yi}=Ur();function Mt(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function $E(t){let e=Object.create(null),r=Object.create(null),i=!1,o=!1,c=!1,d,u,f=-1,x=-1,p=-1,_=0;for(;_<t.length;_++)if(x=t.charCodeAt(_),d===void 0)if(p===-1&&Yi[x]===1)f===-1&&(f=_);else if(_!==0&&(x===32||x===9))p===-1&&f!==-1&&(p=_);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);p===-1&&(p=_);let w=t.slice(f,p);x===44?(Mt(e,w,r),r=Object.create(null)):d=w,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);else if(u===void 0)if(p===-1&&Yi[x]===1)f===-1&&(f=_);else if(x===32||x===9)p===-1&&f!==-1&&(p=_);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);p===-1&&(p=_),Mt(r,t.slice(f,p),!0),x===44&&(Mt(e,d,r),r=Object.create(null),d=void 0),f=p=-1}else if(x===61&&f!==-1&&p===-1)u=t.slice(f,_),f=p=-1;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(o){if(Yi[x]!==1)throw new SyntaxError(`Unexpected character at index ${_}`);f===-1?f=_:i||(i=!0),o=!1}else if(c)if(Yi[x]===1)f===-1&&(f=_);else if(x===34&&f!==-1)c=!1,p=_;else if(x===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${_}`);else if(x===34&&t.charCodeAt(_-1)===61)c=!0;else if(p===-1&&Yi[x]===1)f===-1&&(f=_);else if(f!==-1&&(x===32||x===9))p===-1&&(p=_);else if(x===59||x===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${_}`);p===-1&&(p=_);let w=t.slice(f,p);i&&(w=w.replace(/\\/g,""),i=!1),Mt(r,u,w),x===44&&(Mt(e,d,r),r=Object.create(null),d=void 0),u=void 0,f=p=-1}else throw new SyntaxError(`Unexpected character at index ${_}`);if(f===-1||c||x===32||x===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=_);let v=t.slice(f,p);return d===void 0?Mt(e,v,r):(u===void 0?Mt(r,v,!0):i?Mt(r,u,v.replace(/\\/g,"")):Mt(r,u,v),Mt(e,d,r)),e}function KE(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(i=>[e].concat(Object.keys(i).map(o=>{let c=i[o];return Array.isArray(c)||(c=[c]),c.map(d=>d===!0?o:`${o}=${d}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Vh.exports={format:KE,parse:$E}});var Fo=oe((SC,ox)=>{"use strict";var VE=le("events"),ZE=le("https"),JE=le("http"),Yh=le("net"),YE=le("tls"),{randomBytes:XE,createHash:QE}=le("crypto"),{Duplex:EC,Readable:vC}=le("stream"),{URL:Ad}=le("url"),Tn=zr(),ev=bd(),tv=Sd(),{isBlob:nv}=Ur(),{BINARY_TYPES:Zh,CLOSE_TIMEOUT:rv,EMPTY_BUFFER:No,GUID:iv,kForOnEventAttribute:kd,kListener:sv,kStatusCode:ov,kWebSocket:Ge,NOOP:Xh}=Zt(),{EventTarget:{addEventListener:av,removeEventListener:cv}}=Kh(),{format:dv,parse:lv}=Lo(),{toBuffer:uv}=Ki(),Qh=Symbol("kAborted"),Td=[8,13],Xt=["CONNECTING","OPEN","CLOSING","CLOSED"],fv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,me=class t extends VE{constructor(e,r,i){super(),this._binaryType=Zh[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=No,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(i=r,r=[]):r=[r]),ex(this,e,r,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Zh.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,r,i){let o=new ev({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),c=new tv(e,this._extensions,i.generateMask);this._receiver=o,this._sender=c,this._socket=e,o[Ge]=this,c[Ge]=this,e[Ge]=this,o.on("conclude",pv),o.on("drain",gv),o.on("error",mv),o.on("message",wv),o.on("ping",_v),o.on("pong",yv),c.onerror=bv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",rx),e.on("data",Bo),e.on("end",ix),e.on("error",sx),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tn.extensionName]&&this._extensions[Tn.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),nx(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Rd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||No,r,i)}pong(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=r=void 0):typeof r=="function"&&(i=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Rd(this,e,i);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||No,r,i)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,i){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(i=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Rd(this,e,i);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[Tn.extensionName]||(o.compress=!1),this._sender.send(e||No,o,i)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ct(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(me,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(me.prototype,"CONNECTING",{enumerable:!0,value:Xt.indexOf("CONNECTING")});Object.defineProperty(me,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(me.prototype,"OPEN",{enumerable:!0,value:Xt.indexOf("OPEN")});Object.defineProperty(me,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(me.prototype,"CLOSING",{enumerable:!0,value:Xt.indexOf("CLOSING")});Object.defineProperty(me,"CLOSED",{enumerable:!0,value:Xt.indexOf("CLOSED")});Object.defineProperty(me.prototype,"CLOSED",{enumerable:!0,value:Xt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(me.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(me.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[kd])return e[sv];return null},set(e){for(let r of this.listeners(t))if(r[kd]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[kd]:!0})}})});me.prototype.addEventListener=av;me.prototype.removeEventListener=cv;ox.exports=me;function ex(t,e,r,i){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:rv,protocolVersion:Td[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!Td.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${Td.join(", ")})`);let c;if(e instanceof Ad)c=e;else try{c=new Ad(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}c.protocol==="http:"?c.protocol="ws:":c.protocol==="https:"&&(c.protocol="wss:"),t._url=c.href;let d=c.protocol==="wss:",u=c.protocol==="ws+unix:",f;if(c.protocol!=="ws:"&&!d&&!u?f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:u&&!c.pathname?f="The URL's pathname is empty":c.hash&&(f="The URL contains a fragment identifier"),f){let I=new SyntaxError(f);if(t._redirects===0)throw I;Mo(t,I);return}let x=d?443:80,p=XE(16).toString("base64"),_=d?ZE.request:JE.request,v=new Set,w;if(o.createConnection=o.createConnection||(d?xv:hv),o.defaultPort=o.defaultPort||x,o.port=c.port||x,o.host=c.hostname.startsWith("[")?c.hostname.slice(1,-1):c.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},o.path=c.pathname+c.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(w=new Tn({...o.perMessageDeflate,isServer:!1,maxPayload:o.maxPayload}),o.headers["Sec-WebSocket-Extensions"]=dv({[Tn.extensionName]:w.offer()})),r.length){for(let I of r){if(typeof I!="string"||!fv.test(I)||v.has(I))throw new SyntaxError("An invalid or duplicated subprotocol was specified");v.add(I)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(c.username||c.password)&&(o.auth=`${c.username}:${c.password}`),u){let I=o.path.split(":");o.socketPath=I[0],o.path=I[1]}let E;if(o.followRedirects){if(t._redirects===0){t._originalIpc=u,t._originalSecure=d,t._originalHostOrSocketPath=u?o.socketPath:c.host;let I=i&&i.headers;if(i={...i,headers:{}},I)for(let[A,T]of Object.entries(I))i.headers[A.toLowerCase()]=T}else if(t.listenerCount("redirect")===0){let I=u?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:c.host===t._originalHostOrSocketPath;(!I||t._originalSecure&&!d)&&(delete o.headers.authorization,delete o.headers.cookie,I||delete o.headers.host,o.auth=void 0)}o.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),E=t._req=_(o),t._redirects&&t.emit("redirect",t.url,E)}else E=t._req=_(o);o.timeout&&E.on("timeout",()=>{ct(t,E,"Opening handshake has timed out")}),E.on("error",I=>{E===null||E[Qh]||(E=t._req=null,Mo(t,I))}),E.on("response",I=>{let A=I.headers.location,T=I.statusCode;if(A&&o.followRedirects&&T>=300&&T<400){if(++t._redirects>o.maxRedirects){ct(t,E,"Maximum redirects exceeded");return}E.abort();let D;try{D=new Ad(A,e)}catch{let C=new SyntaxError(`Invalid URL: ${A}`);Mo(t,C);return}ex(t,D,r,i)}else t.emit("unexpected-response",E,I)||ct(t,E,`Unexpected server response: ${I.statusCode}`)}),E.on("upgrade",(I,A,T)=>{if(t.emit("upgrade",I),t.readyState!==me.CONNECTING)return;E=t._req=null;let D=I.headers.upgrade;if(D===void 0||D.toLowerCase()!=="websocket"){ct(t,A,"Invalid Upgrade header");return}let y=QE("sha1").update(p+iv).digest("base64");if(I.headers["sec-websocket-accept"]!==y){ct(t,A,"Invalid Sec-WebSocket-Accept header");return}let C=I.headers["sec-websocket-protocol"],O;if(C!==void 0?v.size?v.has(C)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":v.size&&(O="Server sent no subprotocol"),O){ct(t,A,O);return}C&&(t._protocol=C);let M=I.headers["sec-websocket-extensions"];if(M!==void 0){if(!w){ct(t,A,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=lv(M)}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}let Z=Object.keys(N);if(Z.length!==1||Z[0]!==Tn.extensionName){ct(t,A,"Server indicated an extension that was not requested");return}try{w.accept(N[Tn.extensionName])}catch{ct(t,A,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Tn.extensionName]=w}t.setSocket(A,T,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(E,t):E.end()}function Mo(t,e){t._readyState=me.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function hv(t){return t.path=t.socketPath,Yh.connect(t)}function xv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Yh.isIP(t.host)?"":t.host),YE.connect(t)}function ct(t,e,r){t._readyState=me.CLOSING;let i=new Error(r);Error.captureStackTrace(i,ct),e.setHeader?(e[Qh]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Mo,t,i)):(e.destroy(i),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Rd(t,e,r){if(e){let i=nv(e)?e.size:uv(e).length;t._socket?t._sender._bufferedBytes+=i:t._bufferedAmount+=i}if(r){let i=new Error(`WebSocket is not open: readyState ${t.readyState} (${Xt[t.readyState]})`);process.nextTick(r,i)}}function pv(t,e){let r=this[Ge];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[Ge]!==void 0&&(r._socket.removeListener("data",Bo),process.nextTick(tx,r._socket),t===1005?r.close():r.close(t,e))}function gv(){let t=this[Ge];t.isPaused||t._socket.resume()}function mv(t){let e=this[Ge];e._socket[Ge]!==void 0&&(e._socket.removeListener("data",Bo),process.nextTick(tx,e._socket),e.close(t[ov])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Jh(){this[Ge].emitClose()}function wv(t,e){this[Ge].emit("message",t,e)}function _v(t){let e=this[Ge];e._autoPong&&e.pong(t,!this._isServer,Xh),e.emit("ping",t)}function yv(t){this[Ge].emit("pong",t)}function tx(t){t.resume()}function bv(t){let e=this[Ge];e.readyState!==me.CLOSED&&(e.readyState===me.OPEN&&(e._readyState=me.CLOSING,nx(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function nx(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function rx(){let t=this[Ge];if(this.removeListener("close",rx),this.removeListener("data",Bo),this.removeListener("end",ix),t._readyState=me.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Ge]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Jh),t._receiver.on("finish",Jh))}function Bo(t){this[Ge]._receiver.write(t)||this.pause()}function ix(){let t=this[Ge];t._readyState=me.CLOSING,t._receiver.end(),this.end()}function sx(){let t=this[Ge];this.removeListener("error",sx),this.on("error",Xh),t&&(t._readyState=me.CLOSING,this.destroy())}});var lx=oe((AC,dx)=>{"use strict";var IC=Fo(),{Duplex:Ev}=le("stream");function ax(t){t.emit("close")}function vv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function cx(t){this.removeListener("error",cx),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Sv(t,e){let r=!0,i=new Ev({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(c,d){let u=!d&&i._readableState.objectMode?c.toString():c;i.push(u)||t.pause()}),t.once("error",function(c){i.destroyed||(r=!1,i.destroy(c))}),t.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(o,c){if(t.readyState===t.CLOSED){c(o),process.nextTick(ax,i);return}let d=!1;t.once("error",function(f){d=!0,c(f)}),t.once("close",function(){d||c(o),process.nextTick(ax,i)}),r&&t.terminate()},i._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),i._readableState.endEmitted&&i.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},i._read=function(){t.isPaused&&t.resume()},i._write=function(o,c,d){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(o,c,d)});return}t.send(o,d)},i.on("end",vv),i.on("error",cx),i}dx.exports=Sv});var Cd=oe((kC,ux)=>{"use strict";var{tokenChars:Iv}=Ur();function Av(t){let e=new Set,r=-1,i=-1,o=0;for(o;o<t.length;o++){let d=t.charCodeAt(o);if(i===-1&&Iv[d]===1)r===-1&&(r=o);else if(o!==0&&(d===32||d===9))i===-1&&r!==-1&&(i=o);else if(d===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);i===-1&&(i=o);let u=t.slice(r,i);if(e.has(u))throw new SyntaxError(`The "${u}" subprotocol is duplicated`);e.add(u),r=i=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let c=t.slice(r,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);return e.add(c),e}ux.exports={parse:Av}});var _x=oe((RC,mx)=>{"use strict";var kv=le("events"),zo=le("http"),{Duplex:TC}=le("stream"),{createHash:Tv}=le("crypto"),fx=Lo(),Yn=zr(),Rv=Cd(),Cv=Fo(),{CLOSE_TIMEOUT:Pv,GUID:Dv,kWebSocket:Ov}=Zt(),Lv=/^[+/0-9A-Za-z]{22}==$/,hx=0,xx=1,gx=2,Pd=class extends kv{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Pv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Cv,...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=zo.createServer((i,o)=>{let c=zo.STATUS_CODES[426];o.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),o.end(c)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=Nv(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,c,d)=>{this.handleUpgrade(o,c,d,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=hx}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===gx){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xi,this);return}if(e&&this.once("close",e),this._state!==xx)if(this._state=xx,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(Xi,this):process.nextTick(Xi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Xi(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,i,o){r.on("error",px);let c=e.headers["sec-websocket-key"],d=e.headers.upgrade,u=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Xn(this,e,r,405,"Invalid HTTP method");return}if(d===void 0||d.toLowerCase()!=="websocket"){Xn(this,e,r,400,"Invalid Upgrade header");return}if(c===void 0||!Lv.test(c)){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(u!==13&&u!==8){Xn(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qi(r,400);return}let f=e.headers["sec-websocket-protocol"],x=new Set;if(f!==void 0)try{x=Rv.parse(f)}catch{Xn(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],_={};if(this.options.perMessageDeflate&&p!==void 0){let v=new Yn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let w=fx.parse(p);w[Yn.extensionName]&&(v.accept(w[Yn.extensionName]),_[Yn.extensionName]=v)}catch{Xn(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let v={origin:e.headers[`${u===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(v,(w,E,I,A)=>{if(!w)return Qi(r,E||401,I,A);this.completeUpgrade(_,c,x,e,r,i,o)});return}if(!this.options.verifyClient(v))return Qi(r,401)}this.completeUpgrade(_,c,x,e,r,i,o)}completeUpgrade(e,r,i,o,c,d,u){if(!c.readable||!c.writable)return c.destroy();if(c[Ov])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>hx)return Qi(c,503);let x=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Tv("sha1").update(r+Dv).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(i.size){let _=this.options.handleProtocols?this.options.handleProtocols(i,o):i.values().next().value;_&&(x.push(`Sec-WebSocket-Protocol: ${_}`),p._protocol=_)}if(e[Yn.extensionName]){let _=e[Yn.extensionName].params,v=fx.format({[Yn.extensionName]:[_]});x.push(`Sec-WebSocket-Extensions: ${v}`),p._extensions=e}this.emit("headers",x,o),c.write(x.concat(`\r
15
15
  `).join(`\r
16
- `)),c.removeListener("error",eh),w.setSocket(c,l,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(w),w.on("close",()=>{this.clients.delete(w),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Zi,this)})),u(w,o)}};nh.exports=Ad;function gv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Zi(t){t._state=th,t.emit("close")}function eh(){this.destroy()}function Ji(t,e,r,i){r=r||Mo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Mo.STATUS_CODES[e]}\r
16
+ `)),c.removeListener("error",px),p.setSocket(c,d,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Xi,this)})),u(p,o)}};mx.exports=Pd;function Nv(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let i of Object.keys(e))t.removeListener(i,e[i])}}function Xi(t){t._state=gx,t.emit("close")}function px(){this.destroy()}function Qi(t,e,r,i){r=r||zo.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${zo.STATUS_CODES[e]}\r
17
17
  `+Object.keys(i).map(o=>`${o}: ${i[o]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+r)}function Jn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let l=new Error(o);Error.captureStackTrace(l,Jn),t.emit("wsClientError",l,r,e)}else Ji(r,i,o,c)}});var gh=ae(Le=>{"use strict";var B=U;(function(t,e){let r=U,i=t();for(;;)try{if(-parseInt(r(1903))/1+parseInt(r(750))/2*(parseInt(r(1108))/3)+-parseInt(r(1255))/4+parseInt(r(962))/5+-parseInt(r(1635))/6+parseInt(r(616))/7+parseInt(r(847))/8===e)break;i.push(i.shift())}catch{i.push(i.shift())}})(qo,766304);var Sv=Object[B(1071)+"operty"],Iv=Object["getOwnPr"+B(1607)+B(1707)],uh=(t,e)=>function(){return t&&(e=(0,t[Iv(t)[0]])(t=0)),e},Av=(t,e)=>{let r=B,i={jQfKr:function(c,l,u,x){return c(l,u,x)}};for(var o in e)i[r(1015)](Sv,t,o,{get:e[o],enumerable:!0})};function Tv(){return oh||(oh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Cv(){let t=B;return ah||(ah=[IDBCursor.prototype[t(1754)],IDBCursor[t(1517)+"e"][t(756)],IDBCursor[t(1517)+"e"][t(756)+t(1634)+"ey"]])}function Rv(t){let e=B,r={ICwWT:e(1863),aUTEZ:function(o,c){return o(c)},OBBkk:function(o){return o()},NunIk:function(o,c){return o(c)},ZjOvY:"success"},i=new Promise((o,c)=>{let l=e,u={XCRor:function(_,v){return _|v},gACqn:function(_,v){return _===v},VjlRY:function(_,v){return r[U(634)](_,v)},JNbZN:function(_){return r[U(497)](_)}},x=()=>{let _=U;t["removeEventListe"+_(1062)](_(1017),h),t["removeEv"+_(870)+_(1062)](r[_(543)],w)},h=()=>{let _=U;r.aUTEZ(o,r[_(805)](Bt,t[_(1053)])),r[_(497)](x)},w=()=>{let _=U,v={mvUfP:function(y,E){return u.XCRor(y,E)}};u[_(1742)]("Ulocn",_(1420))?(u[_(717)](c,t[_(1863)]),u[_(470)](x)):(this[_(1078)]=!0,this.low=v[_(1253)](0,_0x17729a),this.high=0|_0x142397,this[_(1934)]=!!_0x25771d)};t[l(1597)+l(1574)](r.ZjOvY,h),t[l(1597)+l(1574)](r[l(543)],w)});return i.then(o=>{o instanceof IDBCursor&&Cd.set(o,t)})[e(1682)](()=>{}),Ho.set(i,t),i}function kv(t){let e=B,r={BcjAl:e(1863),PtipP:function(o){return o()},JIolA:function(o){return o()},PvZiB:function(o,c){return o||c},yUJQq:function(o,c){return o!=c},QarTJ:e(455)+"d",WHpyq:"yqlhn",daCZX:e(869),Axezo:"abort",ocwQO:function(o,c){return o(c)},xnXsZ:e(1838)+"or",MrDOj:function(o,c){return o!==c},iqmIP:e(1291)};if(Uo[e(1266)](t))return;let i=new Promise((o,c)=>{let l=e,u={DXmHD:function(x,h){return r[U(1352)](x,h)},FkrDE:function(x,h){return r.yUJQq(x,h)},DVuVm:r.QarTJ,KqEJb:r[l(1811)],xKqOk:r.daCZX,TueMv:l(1863),BkLAQ:r[l(803)],yUQbL:function(x,h){return r[l(1805)](x,h)},zZtny:r[l(1685)],KHCfQ:function(x){return r[l(761)](x)}};if(r.MrDOj(r[l(662)],r[l(662)]))_0x55e601["removeEventListe"+l(1062)]("success",_0x51b0a3),_0x47958b[l(814)+l(870)+l(1062)](kjHnUl[l(885)],_0x47f323);else{let x=()=>{let _=l,v={lRHHQ:function(y,E){return u[U(990)](y,E)},rYdlZ:function(y,E){return u[U(1300)](y,E)},WOofO:u[_(952)]};if(_(1048)!==u[_(1930)]){let y=(_(1684)+"3").split("|"),E=0;for(;;){switch(y[E++]){case"0":if(_0x1dc95f)return!0;continue;case"1":if(v[_(1548)](_0x5a075e,_0x47d576)&&v[_(1189)](v[_(967)],typeof _0x576843)&&_0x14efa3)return!0;continue;case"2":if(_0x20a4e3&&_0x21039f[_(1398)+_(1703)])return!0;continue;case"3":return!1;case"4":if(_0x190964&&_0x2f7568[_(1398)+_(1703)])return!0;continue}break}}else t[_(814)+_(870)+_(1062)](u[_(689)],h),t["removeEv"+_(870)+_(1062)](u[_(861)],w),t[_(814)+_(870)+_(1062)](u.BkLAQ,w)},h=()=>{r[l(761)](o),r.JIolA(x)},w=()=>{let _=l;u[_(1511)](c,t[_(1863)]||new DOMException(_(1838)+"or",u[_(1084)])),u[_(1040)](x)};t[l(1597)+"Listener"](r[l(1559)],h),t["addEvent"+l(1574)]("error",w),t[l(1597)+l(1574)](r[l(803)],w)}});Uo[e(1430)](t,i)}function Pv(t){Go={UqcGH:function(i,o){return i(o)}}[B(1733)](t,Go)}function U(t,e){t=t-452;let r=qo(),i=r[t];if(U.wOLGxZ===void 0){var o=function(x){let h="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",w="",_="";for(let v=0,y,E,I=0;E=x.charAt(I++);~E&&(y=v%4?y*64+E:E,v++%4)?w+=String.fromCharCode(255&y>>(-2*v&6)):0)E=h.indexOf(E);for(let v=0,y=w.length;v<y;v++)_+="%"+("00"+w.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(_)};U.nQqkhh=o,U.cWeBFL={},U.wOLGxZ=!0}let c=r[0],l=t+c,u=U.cWeBFL[l];return u?i=u:(i=U.nQqkhh(i),U.cWeBFL[l]=i),i}function Dv(t){let e=B,r={jOAbn:function(i,o){return i(o)},ofCaS:function(i,o){return i===o},GNmbx:e(1822),WMSGF:e(1925),DVcYR:function(i,o){return i(o)},JdLYN:function(i,o){return i(o)},EcIBa:function(i,o){return i===o},GRZPu:function(i,o){return i in o},RvljD:"objectSt"+e(573),gYlEI:function(i){return i()}};return r.EcIBa(t,IDBDatabase[e(1517)+"e"][e(784)+"ion"])&&!r.GRZPu(r[e(1199)],IDBTransaction.prototype)?function(i,...o){let c=e,l=t[c(941)](r.jOAbn(Yi,this),i,...o);return Td.set(l,i[c(541)]?i.sort():[i]),Bt(l)}:r.gYlEI(Cv)[e(1872)](t)?function(...i){let o=e;return r.ofCaS(r[o(727)],r[o(1483)])?this._ws?this[o(459)][o(986)]:this[o(1458)]:(t[o(772)](r[o(511)](Yi,this),i),r[o(624)](Bt,Cd.get(this)))}:function(...i){return r[e(624)](Bt,t.apply(Yi(this),i))}}function Ov(t){let e=B,r={BJSfi:function(i,o){return i===o},jeHfK:e(1504),xHvTu:function(i,o){return i instanceof o},WEXeq:function(i,o){return i(o)}};return r[e(1962)](typeof t,r.jeHfK)?Dv(t):(r[e(1797)](t,IDBTransaction)&&r[e(1628)](kv,t),fh(t,Tv())?new Proxy(t,Go):t)}function Bt(t){let e=B,r={WAPNO:function(o,c,l){return o(c,l)},kbQYf:"close",tYWaj:function(o,c){return o instanceof c},hjJMQ:function(o,c){return o(c)},SKVhP:function(o,c){return o!==c},ebOJv:function(o,c){return o!==c},upScn:e(1530)};if(r[e(1035)](t,IDBRequest))return r.hjJMQ(Rv,t);if(Fo[e(1266)](t))return Fo.get(t);let i=r[e(758)](Ov,t);if(r[e(811)](i,t))if(r[e(780)](e(1530),r.upScn)){if(this[e(1764)+e(1637)]?.[e(1144)+e(1535)+"es"]()){let c=this[e(1764)+e(1637)]?.getCurrentEndpoint();this[e(684)+"hCloseEv"+e(1342)](r[e(1874)](_0x1a7d60,"close",{code:1006,reason:e(854)+c+(e(798)+", max retries reached"),wasClean:!0}))}else{let c=this._options["reconnec"+e(1946)+e(1915)](_0x4d2437,_0x520076);this[e(684)+"hCloseEv"+e(1342)](_0x33c995(r.kbQYf,{code:_0x5c1068,reason:_0x1ebf4d,wasClean:!0,willReconnect:c})),c&&this[e(1656)]()}return}else Fo[e(1430)](t,i),Ho.set(i,t);return i}var fh,oh,ah,Cd,Uo,Td,Fo,Ho,Go,Yi,ch=uh({"node_modules/idb/build/wrap-idb-value.js"(){let t=B,e={GnMrg:function(r,i){return r(i)},REiLT:function(r,i){return r&i},reZFq:function(r,i){return r&i},AinAc:function(r,i){return r(i)},nWVqo:function(r,i){return r instanceof i},pcUfE:t(621),vEQQN:function(r,i){return r===i},FMFOI:t(1789)+t(573),IFZts:t(943),hrJwX:t(1856),WdJxN:t(1007),QaDaV:function(r,i){return r===i}};fh=(r,i)=>i[t(1561)](o=>r instanceof o),Cd=new WeakMap,Uo=new WeakMap,Td=new WeakMap,Fo=new WeakMap,Ho=new WeakMap,Go={get(r,i,o){let c=t;if(e.nWVqo(r,IDBTransaction)){if(i===e.pcUfE)return Uo.get(r);if(e[c(1646)](i,e[c(846)])){if(e.IFZts!==e[c(1148)])return r[c(1789)+"oreNames"]||Td[c(649)](r);_0x4a44d9=e[c(994)](_0x49449a,_0x486252),_0x347614=e[c(1595)](127,_0x252167),e[c(968)](128,_0x1502a1)&&(_0x44e662=e.AinAc(_0x2dac87,_0x223ff0),_0x31d98c|=e.reZFq(127,_0x5afd6c)<<7)}if(e[c(1646)](i,e[c(1497)]))return o["objectSt"+c(573)][1]?void 0:o["objectSt"+c(834)](o.objectStoreNames[0])}return e[c(865)](Bt,r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return e[o(1314)](r,IDBTransaction)&&(e[o(1646)](i,e[o(1294)])||e.QaDaV(i,e.WdJxN))?!0:i in r}},Yi=r=>Ho[t(649)](r)}}),xh={};Av(xh,{deleteDB:()=>Nv,openDB:()=>Lv,unwrap:()=>Yi,wrap:()=>Bt});function Lv(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let l=B,u={LrKaE:function(w,_,v,y,E){return w(_,v,y,E)},HtjNo:function(w,_){return w(_)},GRJQs:l(1150)+l(691),zFJwn:"upgradeneeded"},x=indexedDB[l(1496)](t,e),h=Bt(x);return i&&x["addEvent"+l(1574)](u.zFJwn,w=>{let _=l;u[_(1433)](i,u[_(1816)](Bt,x.result),w[_(1425)+"on"],w.newVersion,Bt(x[_(784)+_(738)]))}),r&&x[l(1597)+"Listener"](l(1888),()=>r()),h[l(1196)](w=>{let _=l;c&&w[_(1597)+"Listener"](_(1528),()=>c()),o&&w[_(1597)+_(1574)](u[_(1971)],()=>o())})[l(1682)](()=>{}),h}function Nv(t,{blocked:e}={}){let r=B,i={PDgQw:"blocked",lDSDL:function(c,l){return c(l)}},o=indexedDB[r(1173)+r(1406)](t);return e&&o["addEvent"+r(1574)](i[r(1969)],()=>e()),i[r(1448)](Bt,o).then(()=>{})}function dh(t,e){let r=B,i={xcsPT:r(597),IeUNi:function(x,h){return x instanceof h},JsYpC:function(x,h){return x in h},bHnGB:function(x,h){return x===h},VOOPt:"string",chSED:function(x,h){return x!==h}};if(!(i.IeUNi(t,IDBDatabase)&&!i.JsYpC(e,t)&&i.bHnGB(typeof e,i[r(654)])))return;if(zo[r(649)](e))return zo.get(e);let o=e[r(1662)](/FromIndex$/,""),c=i[r(565)](e,o),l=ph.includes(o);if(!(o in(c?IDBIndex:IDBObjectStore)[r(1517)+"e"])||!(l||hh[r(1872)](o)))return;let u=async function(x,...h){let w=r,_=this[w(784)+w(738)](x,l?w(1746)+"e":i[w(473)]),v=_.store;return c&&(v=v[w(1697)](h.shift())),(await Promise[w(1780)]([v[o](...h),l&&_.done]))[0]};return zo.set(e,u),u}var hh,ph,zo,Mv=uh({"node_modules/idb/build/index.js"(){let t=B,e={cyaNl:function(r){return r()},BfLov:t(649),TtfiI:t(1440),NNTek:"put",uWnBk:t(1794),hXhzw:t(707),ixsoY:t(748),ZkTEK:function(r,i){return r(i)}};ch(),e[t(514)](ch),hh=[e[t(1542)],e[t(787)],t(1001),t(479)+"ys","count"],ph=[e.NNTek,e[t(630)],e[t(1664)],e[t(799)]],zo=new Map,e[t(1741)](Pv,r=>({...r,get:(i,o,c)=>dh(i,o)||r[t(649)](i,o,c),has:(i,o)=>!!dh(i,o)||r[t(1266)](i,o)}))}}),Bv={idb:function(t){let e=B;t[e(1283)]=Promise.resolve()[e(1196)](()=>(Mv(),xh)).then(function(r){return r})}},lh={};function Mt(t){let e=B,r={SBpfy:function(c,l){return c!==l}};var i=lh[t];if(r[e(1919)](void 0,i))return i[e(1283)];var o=lh[t]={exports:{}};return Bv[t](o,o[e(1283)],Mt),o[e(1283)]}Mt.d=(t,e)=>{let r=U;for(var i in e)Mt.o(e,i)&&!Mt.o(t,i)&&Object[r(1071)+"operty"](t,i,{enumerable:!0,get:e[i]})},(()=>{let t=B;Mt.o=(e,r)=>Object[t(1517)+"e"][t(1723)+"operty"][t(941)](e,r)})(),(()=>{let t=B,e={jpWZO:t(1239),Gpwke:t(1246)+"le"};Mt.r=r=>{let i=t;i(455)+"d"!=typeof Symbol&&Symbol.toStringTag&&Object[i(1071)+i(1783)](r,Symbol["toString"+i(663)],{value:e.jpWZO}),Object[i(1071)+"operty"](r,e.Gpwke,{value:!0})}})();var Ce={};(()=>{let t=B,e={ZPPJC:function(a,n){return a(n)},AoZZy:function(a,n){return a+n},CJUHD:function(a,n){return a+n},Zcfpe:function(a,n){return a*n},LHFeg:function(a,n){return a(n)},xJwOr:function(a,n,s){return a(n,s)},HgQXs:function(a,n){return a(n)},zpFsP:t(1653),RNKWv:t(527),TzWrG:function(a,n){return a(n)},eNEeU:"wss://",pgmNh:t(1748),vCSxv:function(a,n){return a===n},KoWeu:t(1719),vlqFw:function(a,n){return a>n},SiuXY:function(a,n){return a<n},LofNr:function(a,n){return a!==n},iNkZk:function(a,n){return a-n},ZTBdp:function(a,n){return a!==n},kiqgV:function(a,n){return a-n},jRHme:function(a,n){return a<n},tiIOG:t(1711),SQijK:t(1863),rlQUT:function(a,n,s){return a(n,s)},xpPkz:function(a,n){return a===n},WJPNx:t(932),KqGfB:t(1219),EnhRq:function(a,n,s){return a(n,s)},UpNyX:function(a,n,s){return a(n,s)},KVdUA:function(a,n){return a>>>n},rPxrB:function(a,n){return a&n},grvbR:"Missing required"+t(1580)+t(681),HONbK:function(a,n){return a===n},rxVko:t(928)+t(1268)+t(1580)+t(1557),yMyOa:function(a){return a()},NSmxZ:function(a,n,s){return a(n,s)},kKCSx:function(a,n){return a===n},HVzSZ:function(a,n,s){return a(n,s)},MPTWb:function(a,n){return a!==n},WEuqe:function(a,n,s){return a(n,s)},cocmh:function(a,n){return a!==n},xcOFJ:function(a,n){return a!==n},EiHwA:function(a,n,s){return a(n,s)},xLNlm:function(a,n,s){return a(n,s)},rPcBl:function(a,n){return a(n)},meFTv:function(a,n){return a!==n},vOCcB:function(a,n){return a!==n},bpUrI:t(526),yYYys:function(a,n){return a!==n},JuDaU:function(a,n){return a===n},GsXoE:t(770),tbfEH:function(a,n,s){return a(n,s)},GcCKl:function(a,n){return a!==n},Qzgir:function(a,n,s){return a(n,s)},inNEj:function(a,n,s){return a(n,s)},LzPpH:function(a,n){return a!==n},phHGg:function(a,n,s){return a(n,s)},AJHuG:function(a,n,s){return a(n,s)},MQDGw:function(a,n){return a!==n},rttOF:function(a,n){return a!==n},AHUKU:function(a,n){return a(n)},PEKxc:function(a,n){return a(n)},dlijx:function(a,n,s){return a(n,s)},DldJX:function(a,n,s){return a(n,s)},mGnPA:function(a,n){return a(n)},bZbCW:function(a,n,s){return a(n,s)},JWUgM:function(a,n){return a(n)},iYCyW:function(a,n,s){return a(n,s)},OMuwU:function(a,n){return a(n)},EkkeX:t(928)+t(1268)+t(1580)+t(1835),zgtrk:t(928)+t(1268)+t(1580)+t(981),HSeeZ:"Missing "+t(1268)+" field: "+t(1444),DmKep:t(928)+t(1268)+t(1580)+t(1321),bJFey:function(a,n){return a(n)},MtEtx:function(a,n,s){return a(n,s)},bGBIF:t(1755)+t(1944)+"pe: ",EdtrC:function(a,n){return a>>n},hZeol:function(a,n){return a>=n},XQzjr:function(a,n){return a&n},zzsEk:t(983),nkJfQ:function(a,n){return a===n},bFesh:function(a,n){return a>n},YdCtn:t(781)+t(1820),OQowl:function(a,n){return a>n},zAKgc:t(1369),WISod:function(a,n){return a*n},hWQcQ:function(a,n){return a>n},NITJJ:function(a,n){return a+n},NuMqQ:function(a,n,s){return a(n,s)},dxDQR:function(a,n){return a+n},vaAbD:function(a,n,s){return a(n,s)},CKkAK:t(1761),XesKi:function(a,n,s){return a(n,s)},AAzra:function(a,n){return a<n},jLMyq:function(a,n){return a>=n},RJFTO:function(a,n){return a|n},ZmUzZ:function(a,n){return a<<n},WrsIT:function(a,n){return a&n},BPGdC:function(a,n){return a<n},ScJbW:function(a,n){return a===n},JihXa:t(1024),EEcnP:t(1907),QqrJi:function(a,n){return a+n},xWtzu:function(a,n){return a!==n},UzBnG:function(a,n){return a|n},PmTMv:function(a,n){return a|n},UTorH:function(a,n){return a&n},hxMEf:function(a,n){return a&n},WzDoN:function(a,n){return a>=n},RJFuL:function(a,n){return a<=n},zyXeJ:function(a,n){return a(n)},WVgKC:function(a,n){return a==n},qjZxK:function(a,n){return a+n},QgPuL:function(a,n){return a+n},Aagkj:function(a,n){return a+n},zmLuX:function(a,n){return a+n},gjIKJ:function(a,n){return a+n},jEESb:function(a,n){return a&n},soyNn:function(a,n){return a|n},sSyVW:function(a,n){return a|n},oNOCe:function(a,n){return a<<n},DVfEU:function(a,n){return a&n},RewbA:function(a,n){return a&n},KMZbP:function(a,n){return a&n},SrRSg:function(a,n){return a+n},TrKjP:function(a,n){return a&n},MZZxa:function(a,n){return a>=n},yWwrC:function(a,n){return a<n},doLap:function(a,n){return a<<n},daepB:function(a,n){return a<n},scezR:function(a,n){return a<n},rPWOe:function(a,n,s){return a(n,s)},fLvur:function(a,n,s){return a(n,s)},ONDHN:function(a,n){return a<n},ZZrpB:function(a,n){return a>=n},jZGxb:function(a,n){return a<=n},oOBQt:function(a,n){return a+n},TUgln:function(a,n){return a|n},czweM:function(a,n){return a<n},Daeix:function(a,n){return a&n},AJVto:function(a,n){return a|n},lSceC:function(a,n){return a|n},FqRDc:function(a,n){return a&n},IqCmd:function(a,n){return a>>n},tqXSM:function(a,n){return a&n},YqTIK:function(a,n,s){return a(n,s)},Ycaon:function(a,n,s){return a(n,s)},cmmhC:function(a,n){return a(n)},UQzIp:function(a,n){return a<n},oSlnm:function(a,n){return a(n)},SDEdJ:function(a,n,s,d){return a(n,s,d)},mKuva:t(1509),bvtjH:function(a,n){return a&n},blnIY:function(a,n,s){return a(n,s)},VwGCZ:function(a,n){return a(n)},hjFDH:function(a,n){return a&n},nQvmX:function(a,n){return a&n},ADWNi:function(a,n){return a(n)},qGRzb:function(a,n){return a<<n},XMMiO:function(a,n){return a&n},PmLXV:"ZnFYE",fxORL:function(a,n){return a(n)},duTCH:function(a,n){return a&n},bxuPB:function(a,n){return a(n)},VOLFD:function(a,n){return a<<n},cXnxV:function(a,n){return a&n},JNViv:function(a,n){return a&n},xmWBm:function(a,n){return a&n},dpgqQ:function(a,n){return a|n},RsfdU:function(a,n){return a>>>n},ZFUiP:function(a,n){return a<n},VQSIK:function(a,n){return a<n},igtdh:function(a,n){return a<n},NHGml:function(a,n,s){return a(n,s)},uJqvy:function(a,n){return a|n},FLBhT:function(a,n){return a!==n},SsnZl:function(a,n){return a>>>n},guuTe:function(a,n){return a>>>n},hfjtU:function(a,n){return a>>>n},hlLbC:function(a,n){return a!==n},TiEvG:function(a,n){return a|n},RcaON:function(a,n){return a|n},FysBF:function(a,n){return a&n},sSdUI:function(a,n){return a>>>n},uBBNF:function(a,n){return a+n},SdlOE:function(a,n){return a>>>n},WVNQZ:function(a,n){return a+n},mEUKM:function(a,n){return a&n},QREMf:function(a,n){return a&n},YiDxQ:function(a,n){return a!==n},rtxxc:t(503),bMohe:function(a,n){return a|n},HDdqR:function(a,n){return a||n},nLpVh:function(a,n){return a===n},UDzOj:t(786),uhgDG:function(a,n){return a===n},hGFVv:function(a,n){return a|n},zHMhG:function(a,n){return a|n},SZynk:function(a,n){return a|n},zYCUn:function(a,n){return a<<n},mTEaj:function(a,n){return a<<n},tsAuC:function(a,n){return a<<n},gykbT:function(a,n){return a|n},ywliH:function(a,n){return a|n},ZGTCD:function(a,n){return a<<n},ITEAG:t(1029),fyiOm:function(a,n){return a>>>n},MVACz:function(a,n){return a|n},XhkZM:function(a,n){return a<<n},bcqZR:function(a,n){return a<<n},vJFaF:function(a,n){return a|n},zBtxj:function(a,n){return a|n},HXhFL:function(a,n){return a&n},cudWT:function(a,n){return a>>>n},DFKpI:function(a,n){return a>>>n},Qrjim:function(a,n){return a>>>n},uAavt:function(a,n){return a(n)},seqjT:function(a,n){return a===n},jWCIk:"hrbkN",VHHNv:function(a,n){return a>=n},eZqSb:function(a,n){return a%n},dixHI:function(a,n){return a/n},EojjR:function(a,n){return a(n)},akCzs:t(742),MSQxe:function(a,n){return a+n},wWTBB:function(a,n){return a>>>n},PJZee:function(a,n){return a&n},RqNRx:function(a,n){return a>>>n},zSaZt:function(a,n){return a&n},ptUVa:function(a,n){return a>>>n},ecoID:function(a,n){return a+n},knnZH:function(a,n){return a>>>n},tUiQP:function(a,n){return a>>>n},mGlox:function(a,n){return a<<n},UZdip:function(a,n){return a|n},puCAk:function(a,n){return a!==n},YSuWF:function(a,n){return a>>>n},OPqGR:function(a,n){return a>>>n},eAhjk:function(a,n){return a===n},nKxRw:function(a,n){return a+n},DMjhK:"string",grZWk:function(a,n){return a!==n},rCwOi:function(a,n){return a>>>n},GOUxJ:function(a,n){return a>>>n},wNkFq:function(a,n){return a>>>n},XlQSh:function(a,n){return a>>>n},jNsla:function(a,n){return a&n},PBSYg:function(a,n){return a&n},iXwke:t(737)+"NG_ERROR",txQrs:t(1712)+t(1606),HBCjf:t(1619)+t(1111)+"R",OlNSm:t(1296)+"OR",dRpZZ:t(1940)+"RROR",frxnn:t(489)+"4",MlIns:function(a,n){return a||n},kGwSX:function(a,n,s,d,f){return a(n,s,d,f)},zqKVj:function(a,n){return a(n)},CyPDh:"ExwUH",TNTfF:t(1541),LwknP:"FNeGC",JhYWK:function(a,n){return a-n},VSrUs:function(a,n){return a===n},GTBDu:"HPrMH",JVJaw:function(a,n){return a instanceof n},bvuuE:t(741)+t(546),ioGQC:function(a,n){return a===n},bmaeZ:function(a,n){return a===n},SBehQ:function(a,n){return a===n},oyPXQ:"SNFUu",sfgZW:function(a,n){return a(n)},Nqytd:function(a,n){return a===n},dCmOt:"AztVk",jPuUW:function(a,n,s){return a(n,s)},itXhz:function(a,n,s){return a(n,s)},yqJsl:t(1528),noxks:t(1496),DBbOL:function(a,n,s){return a(n,s)},jwKDp:function(a,n,s){return a(n,s)},rbBLS:function(a,n,s){return a(n,s)},yXaqE:function(a,n,s){return a(n,s)},YWZdC:function(a,n){return a|n},Aneih:function(a,n){return a+n},cssLk:function(a,n){return a|n},BLagX:function(a,n){return a+n},KwFXe:function(a,n){return a+n},YDdBa:"kgCrv",ptjpX:"ccZjv",IZzJs:function(a,n){return a!==n},vpULJ:t(1672),uZbLf:t(455)+"d",WHOiY:t(1897)+"2",EAJjX:function(a,n){return a||n},Aayhx:function(a,n){return a!=n},AlKqz:function(a,n){return a(n)},dbryw:function(a,n){return a!==n},MyqQY:t(1643),cYnrP:function(a,n){return a<n},jAlPg:function(a,n){return a+n},UyzIT:function(a,n){return a<=n},OTOIj:function(a,n){return a&n},oCLwb:function(a,n){return a|n},OdCic:function(a,n){return a<<n},vuZNg:function(a,n){return a&n},KdQay:function(a,n){return a===n},BdsYT:t(1631),bdczq:t(1609),BUQMZ:function(a,n){return a-n},FrhSG:function(a,n){return a&n},pZLXy:function(a,n){return a<<n},fCoJj:function(a,n){return a&n},gyFnK:function(a,n){return a<<n},Yygaz:t(1494),RgdEw:function(a,n){return a<n},hRYrC:function(a,n){return a===n},QDPoQ:t(1642),rcuHS:function(a,n){return a<n},lBueO:function(a,n){return a|n},isPQl:function(a,n){return a&n},TCftt:function(a,n){return a===n},IYOaC:function(a,n){return a&n},SqMmf:function(a,n){return a===n},aCwQt:function(a,n){return a&n},RVdzF:"3|4|1|2|5|0",ebOvs:function(a,n){return a|n},KaWqj:function(a,n){return a>>n},vUEru:function(a,n){return a|n},adcMY:function(a,n){return a&n},zGgpA:function(a,n){return a+n},UXFQw:function(a,n){return a<<n},ItOmn:function(a,n){return a|n},ATWGz:function(a,n){return a>>n},VLKKX:function(a,n){return a===n},NuEku:"QpUQX",sKXst:"maUas",SHBBT:function(a,n){return a>>n},KHNFZ:function(a,n){return a|n},aMFEX:function(a,n){return a-n},axuQM:function(a,n,s,d){return a(n,s,d)},dTvlP:function(a,n){return a instanceof n},EuqOG:function(a,n){return a instanceof n},yiMvg:function(a,n){return a==n},lmwxR:t(1339),MiXSZ:t(829),iwpHh:t(1964)+t(1179),DCeEm:t(703)+t(1166),uzYly:"http",tSbEa:t(1410)+"ack=fron"+t(1762)+"P",DZwok:t(754),xeUyM:t(580),fGAiG:t(910),hMurQ:t(1307),swYYi:t(460),ZXjrc:"online",WcrQB:t(876),LGlFv:function(a,n){return a<<n},PYFcy:function(a,n,s,d){return a(n,s,d)},xHmBr:function(a,n){return a===n},rhttB:t(484),njbku:function(a,n){return a+n},bnTcy:t(1348),AlohP:t(1345),qedvn:"MakyN",emNJW:function(a,n){return a!==n},MXdEP:"eZQTt",hpqiA:t(1272),NUNBR:t(1851),ZIkyr:function(a,n,s){return a(n,s)},tqLHj:t(914),TpSMO:function(a,n){return a===n},oKJka:"uRYqS",PFSsR:function(a,n){return a||n},GyQrx:function(a,n){return a||n},veJpz:function(a,n){return a||n},EFnlr:function(a,n){return a||n},DRoPT:function(a,n){return a instanceof n},UWyls:function(a,n){return a===n},AHpTb:function(a,n){return a===n},pkcYO:"pTRWj",MOGBJ:function(a,n){return a<n},TklGE:function(a,n){return a===n},WylEy:t(1860),mJlrT:t(745),YCEiv:function(a,n){return a!==n},xwUJy:t(1439),vWhKc:t(801),YZWbT:function(a,n,s){return a(n,s)},vAORW:"message_id",CczJA:t(1368),GuigV:t(1977),wSLvs:t(918)+"_EXIST",KlAIM:function(a,n){return a===n},XinRI:"WjWTR",gPdOO:function(a,n){return a>n},crjZX:t(1818)+t(1820),dMMMs:t(1419),MkEGH:function(a,n){return a(n)},tznGB:function(a,n){return a!=n},RlQOQ:function(a,n){return a!=n},caVgg:t(824)+"ion/json",NQiAo:function(a,n){return a==n},tlSoH:t(804)+"in;chars"+t(1600),NRfjN:t(1331),mkLeO:t(1246)+"le",Qszve:function(a,n){return a!==n},EVrnF:t(579),GzHVA:"x_fronti"+t(838)+"ck",KniKC:"x_fronti"+t(1649)+"sgid",TlaKU:t(1023)+t(561),LENHX:function(a,n){return a|n},OIcdz:function(a,n){return a|n},dePXp:function(a,n){return a|n},AfhVy:function(a,n){return a>>n},DjpCo:function(a,n){return a|n},wEpnC:function(a,n){return a<<n},OObay:function(a,n){return a&n},LBVct:function(a,n){return a===n},vCGHN:t(551),WjckE:t(1382),hiZRa:function(a,n){return a&&n},SuTwV:t(1490),KlXoN:"ack_id",lRTtP:"ack_code",pWYiR:function(a,n){return a(n)},Yzoii:function(a,n){return a instanceof n},CDTDg:t(824)+t(1617)+t(647)+t(961),HXofZ:t(1879),DetqB:function(a){return a()},EMthM:function(a,n){return a(n)},iXKsK:function(a,n){return a&n},NgcCI:function(a,n){return a+n},pHblm:function(a,n){return a|n},CJkhe:function(a,n){return a>>>n},PHDSw:function(a,n){return a(n)},OyoVd:function(a,n){return a+n},EABUA:function(a,n){return a+n},JEICj:"index ou"+t(708)+"ge: ",MJfAd:t(678),KsgoG:function(a,n){return a>n},BRZqC:t(1491)+"too large",sBRVL:function(a,n,s,d){return a(n,s,d)},FMkjl:function(a,n){return a+n},nXfCP:function(a,n){return a+n},hSOFt:function(a,n){return a<n},JeEsH:function(a,n,s){return a(n,s)},uBfeU:function(a,n){return a<<n},YnmKg:function(a,n,s,d){return a(n,s,d)},bGNZv:function(a,n,s,d){return a(n,s,d)},BwkXx:function(a,n){return a|n},EcIbN:function(a,n){return a+n},kbmGf:function(a,n){return a<<n},oHURS:function(a,n){return a+n},sJNjN:function(a,n){return a<<n},ItSSD:function(a,n){return a<<n},WNLPo:function(a,n){return a<<n},wIYKF:function(a,n){return a+n},pLhjJ:function(a,n){return a+n},gSGfq:function(a,n){return a+n},lJHWy:function(a,n){return a>>>n},jjOub:function(a,n){return a&n},eHDTV:function(a,n){return a>>>n},akTVV:function(a,n){return a+n},JtHur:function(a,n){return a&n},efwQU:function(a,n){return a&n},GqVWn:function(a,n){return a+n},RxhhG:function(a,n){return a+n},VNJRY:function(a,n){return a&n},YqdLr:function(a,n){return a>>>n},tBKrQ:function(a,n){return a&n},QXNIa:function(a,n){return a&n},TBAIz:function(a,n){return a+n},AvBPn:"8|3|7|2|9|5|10|1"+t(1927)+"6",cbTyT:function(a,n){return a>>>n},aHHHb:function(a,n){return a<<n},pXteA:function(a,n){return a>n},HlgCK:function(a,n){return a|n},rOjcP:function(a,n){return a<<n},ueuCT:function(a,n){return a===n},wWlHh:"UrYoV",ZwWUa:t(564),FTRzL:t(1459)+t(789),CKfsn:t(1218)+t(958),lvCIL:"message",YRhwH:function(a,n){return a!==n},eIbzz:t(1061),ZWLVq:t(1336),amtTN:function(a,n,s,d){return a(n,s,d)},AhvhA:function(a,n){return a+n},zutNZ:function(a,n,s){return a(n,s)},vVuJB:t(954)+t(468),ozoCK:t(648),Nrxxg:function(a,n,s,d){return a(n,s,d)},DqFje:t(513),eAwdT:function(a,n){return a!==n},yDrLo:t(1845),NXHWS:t(1924),iGcTF:function(a,n){return a(n)},DIZWr:t(1364)+"r",TUhDv:function(a,n,s){return a(n,s)},FvZIh:function(a,n){return a===n},fVcuY:t(1735),YINgs:function(a,n){return a||n},NXohE:function(a,n){return a&n},NJDGq:function(a,n){return a>>>n},SjcyO:function(a,n){return a&n},FrTNU:function(a,n){return a>>>n},lfhwd:function(a,n){return a>>>n},cjrfv:function(a,n,s,d){return a(n,s,d)},DxOMd:function(a,n,s){return a(n,s)},TNCdF:t(1068)+t(1840),iaKCg:t(1068)+"er_ttl",tNkdG:t(925)+"s",HNqdn:function(a,n,s){return a(n,s)},bKjbu:"x-msg-cursor_name",RYRcQ:t(1431)+"rsor_value",aSKNT:function(a,n){return a>n},XuWzd:function(a,n){return a+n},VhHxT:"ZcybV",mlkXd:t(1049),UuDxO:function(a){return a()},fXfQm:function(a){return a()},kFoOp:t(1738),PievU:function(a){return a()},gPcto:function(a){return a()},sDhWe:function(a,n){return a(n)},WuuYt:function(a,n){return a===n},xygjz:function(a,n){return a-n},lnGqe:function(a,n){return a<n},mHWgE:function(a,n){return a===n},QOkKr:t(533),mBvAj:function(a,n,s){return a(n,s)},pZgIA:function(a,n,s){return a(n,s)},JHMBq:"rczvI",mPnIG:"always",bIIuw:t(764),ovAgX:t(493)+"e_success",VQmWp:function(a,n){return a===n},QoyVQ:function(a,n,s){return a(n,s)},TrPcV:function(a,n){return a===n},itMcs:"7|5|10|1"+t(959)+t(1826),kadXx:function(a,n,s,d){return a(n,s,d)},IaTxI:function(a,n,s){return a(n,s)},lWUmf:function(a,n){return a!==n},UaFuI:t(1612),BBKOu:"hPRCa",WHgmI:function(a,n){return a!==n},pHuYr:function(a,n){return a===n},xreww:t(1918),LUhva:t(602),BApYE:"arraybuf"+t(1361),PaMGd:function(a,n){return a/n},lZIcF:t(1690)+t(583)+t(1622),chHWr:t(1690)+t(948)+t(1224)+t(1813)+t(1457)+t(1942)+t(627)+"ined",lfRPy:function(a,n,s){return a(n,s)},QkCQC:"reconnect",sunsK:function(a){return a()},miorj:t(1149),wLDyF:"success",mJgYp:function(a,n,s){return a(n,s)},UckpU:function(a,n){return a!==n},dqZMc:"VVWjX",kjZxo:function(a,n){return a!==n},BLSqk:t(743),zfvFu:t(1136),qmUPu:t(794),Kxwdx:t(1669),lnHRT:t(525)+"d",HjYVC:"please provide b"+t(482)+t(1359)+"r ttwID",LqRfP:t(1504),JdPLY:function(a,n,s){return a(n,s)},vXQJa:t(1582),iXhur:t(976)+"0",xCYDu:t(1054)+"4",JFbih:function(a,n,s){return a(n,s)},kHuPx:t(1596),Zgfvc:t(1416),IxBZU:function(a,n,s){return a(n,s)},yLcyS:"FRONTIER>",fRsiV:function(a,n){return a===n},ZBxSQ:function(a,n,s){return a(n,s)},VTEoa:function(a,n){return a!==n},gcwaC:"ping_once_timeout",GhCOz:"timeout",woWuS:t(1027),SsBFU:t(1302),QKuFF:function(a,n,s){return a(n,s)},FnEAy:t(864),SqasA:t(936)+" try rec"+t(1013)+"g",YvEyE:function(a,n){return a(n)},oPVXc:function(a,n){return a===n},yUIWu:t(1679),KlzRz:t(1636),xeiCX:t(1787)+"0",kZxTc:t(1684)+"3",ibCaf:function(a,n,s){return a(n,s)},lweCX:"going away, netw"+t(973)+t(1786),oTpqG:t(1330),zROPA:t(1424),XwDlE:function(a,n){return a>=n},foXov:function(a,n){return a>=n},zrexj:function(a,n){return a/n},hqvIl:t(586),ZEFBt:function(a,n){return a+n},hQKku:function(a,n,s){return a(n,s)},rdemN:t(1374),XlIGA:t(636),FuXdS:t(1358),MZJrV:t(1779),UzYPv:function(a,n){return a+n},fYema:function(a,n){return a+n},ZOiSX:function(a,n){return a&n},swTsy:t(1304)+t(1629),grsHN:t(558)+t(641)+t(886)+t(1526)+"ed",YNHoP:function(a,n){return a===n},DtyPL:function(a,n){return a===n},eNppO:t(558)+t(645)+t(477),aCWbG:t(1564),GSTOp:"number",ZQoUG:function(a,n){return a!=n},BnVMJ:function(a,n){return a||n},chnja:t(1690)+t(740)+t(1776)+t(871),GhJPZ:function(a,n){return a instanceof n},gTxPp:t(1505),QiQsl:t(465),LiSBI:t(849),REKNS:t(1427)+"econnect"+t(1804),pKxkA:function(a,n){return a(n)},pJdBY:"AbortError",IBFII:function(a){return a()},OryrX:function(a,n){return a<n},yrRgQ:function(a,n){return a|n},xzbLL:function(a,n){return a>>n},Jgtrk:function(a,n){return a&n},UjDqx:function(a,n){return a>>n},OoNCF:function(a,n){return a&n},dLPld:function(a,n){return a|n},ajLPc:function(a,n){return a&n},HTIqh:function(a,n){return a>>n},nwPuB:t(1522),DkfWQ:t(538),yQusI:t(1705)+"0",yVFsf:function(a,n){return a+n},OwrXW:function(a,n){return a+n},HwJUY:function(a,n){return a+n},vQDbJ:function(a,n){return a!==n},EAMqE:function(a,n){return a&n},dOhTZ:function(a,n){return a|n},SPurV:function(a,n){return a<n},ptilx:function(a,n){return a<=n},EAqaY:t(1014),pKMuP:t(1396),qAtyL:function(a,n){return a(n)},yeqyU:"\0\0\0\0\0\0\0\0",ILsOM:function(a,n){return a!=n},caBto:function(a,n){return a===n},YLYXj:"Window",tDIkv:function(a,n){return a!=n},HWeYL:function(a,n){return a===n},GhQwy:"Object",fLUQs:function(a,n){return a!=n},OxtNU:function(a,n){return a===n},BfdZj:t(1325)+t(1168)+t(1753)+"pe",pyfho:t(1510)+t(491)+"balScope",RahEV:function(a,n){return a!=n},KBeao:function(a,n){return a!=n},QKJLe:t(1725)+t(1081)};Mt.r(Ce),Mt.d(Ce,{FWS:()=>Jp,CustomErrorEvent:()=>$d,createCloseEvent:()=>ht,ReconnectEvent:()=>Kd,createErrorEvent:()=>ot,decodedFrame:()=>Qt,createOpenEvent:()=>Qd,CustomCloseEvent:()=>Vd,createReconnectEvent:()=>aa,FrontierMessageEvent:()=>Jd,encodeFrame:()=>Ft,createMessageEvent:()=>Xd,OpenEvent:()=>Yd,ErrorCode:()=>tn,Event:()=>Qn,MessageEvent:()=>Zd});let r="";function i(a=""){let n=t,s="02",d=""+Date[n(720)](),f=r||(r=e[n(1470)](x,a)),g=Math.random().toString(16)[n(1037)](-6);return e[n(1905)](e.AoZZy(e.CJUHD(s,d),f),g)}function o(){let a=t;return e[a(1914)](1e4,Date[a(720)]())+Math[a(736)](e[a(1914)](1e4,Math.random()))}function c(a){let n=t;return e[n(1921)](e[n(554)](Array,8)[n(631)]("0"),e.xJwOr(parseInt,a,10)[n(1539)](2))[n(1037)](-8)}function l(a){let n=t;return e.CJUHD(e[n(1470)](Array,4)[n(631)]("0"),e.xJwOr(parseInt,a,2)[n(1539)](16)).slice(-4)}function u(a){let n=t,s=a[n(698)](/\./)[n(1310)](g=>c(g)),d=[];return d[0]=e.HgQXs(l,s[0]+s[1]),d[1]=e[n(554)](l,e[n(1905)](s[2],s[3])),[e.zpFsP,n(1653),e[n(550)],n(1653),e[n(550)],e[n(697)],d[0],d[1]][n(631)]("")}function x(a){let n=t,s=/(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}/[n(1611)](a),d=/(([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]))/[n(1611)](a);return s?e.LHFeg(u,a):d?e[n(1521)](h,a):n(1073)+n(1073)+n(1073)+n(1073)}function h(a){let n=t;if(e.vCSxv(e.KoWeu,e[n(921)])){let s="",d=[],f=0,g=0,m=!0,S=e[n(550)];if(e[n(1215)](a[n(979)]("::"),-1)){let p=a.split("::");for(let L=0;e[n(1152)](L,p[n(1092)]);L++){let N=p[L];if(e[n(1215)](N[n(979)](":"),0)){let F=N[n(698)](":");m&&(f=F[n(1092)]),g+=F.length;for(let $=0;e[n(1152)]($,F[n(1092)]);$++)if(e.LofNr(4,F[$][n(1092)])){let X=S[n(1627)+"g"](0,e[n(1938)](4,F[$].length)),at=X[n(592)](F[$]);d.push(at)}else d[n(539)](F[$]);m=!1}else{if(e[n(628)](4,N.length)){let F=S[n(1627)+"g"](0,e[n(1938)](4,N.length)),$=F[n(592)](N);d[n(539)]($)}else d[n(539)](N);m&&(f+=1),g+=1,m=!1}}let R="";for(let L=0;L<e[n(1532)](8,g);L++)R=R[n(592)](S);for(let L=0;e[n(1152)](L,d[n(1092)]);L++)L===f?(s=s.concat(R),s=s[n(592)](d[L])):s=s.concat(d[L]);return s}{let p=a[n(698)](":");for(let R=0;e.jRHme(R,p[n(1092)]);R++){let L=p[R];if(p[R].length!==4){if(n(472)===e[n(916)])return new _0xb8fdb2(_0x90b0fd,{data:_0x430bf0});{let N=S[n(1627)+"g"](0,4-p[R].length),F=N[n(592)](L);s=s[n(592)](F)}}else s=s.concat(L)}return s}}else _0xa5b1ac=_0x416fcc&&n(1136)==_0x5759a4[n(946)]?e[n(889)]:e[n(782)],_0x3542c0=_0x47a226.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),_0x5aba14=/^wss(.*:\/\/)/[n(1611)](_0x25758b)?_0x4bb594:""+_0x116ede+_0x480938}function w(a,n){let s=t,d={muTYr:function(m,S,p){return m(S,p)},SlyLp:e[s(1644)],pNllv:function(m,S,p){return e[s(1161)](m,S,p)},czACO:"close"},f=a.key;if(e[s(1388)](void 0,f))if(e[s(1412)](e[s(1890)],e[s(1665)])){let m=d[s(793)](_0xcefe71,d[s(1141)],{message:this[s(1560)+s(1825)+"age"](_0x115cee)});this[s(1599)](d.SlyLp,m);let S=d[s(712)](_0x526b17,d.czACO,{reason:this[s(1560)+s(1825)+s(638)](_0x209e01)});this[s(1599)](d[s(1236)],S)}else e.xJwOr(he,n,10),e.EnhRq(q,n,f);let g=a[s(1557)];g!==void 0&&(he(n,18),e[s(919)](q,n,g))}function _(a){let n=t,s={};e:for(;!V(a);){let d=xe(a);switch(e.KVdUA(d,3)){case 0:break e;case 1:s.key=O(a,e[n(1521)](xe,a));break;case 2:s[n(1557)]=e[n(901)](O,a,e[n(1470)](xe,a));break;default:e.rlQUT(C,a,e[n(963)](7,d))}}if(e[n(1954)](void 0,s[n(681)]))throw new Error(e[n(1259)]);if(e[n(1732)](void 0,s[n(1557)]))throw new Error(e[n(855)]);return s}function v(a){let n=t,s=e.yMyOa(k);return e[n(515)](y,a,s),M(s)}function y(a,n){let s=t,d={qspMg:function(ct,Ze){return e[U(1534)](ct,Ze)}},f=a[s(1835)];e[s(628)](void 0,f)&&(e[s(488)](he,n,8),xt(n,f));let g=a[s(981)];e[s(1518)](void 0,g)&&(e[s(1250)](he,n,16),e[s(901)](xt,n,g));let m=a[s(1444)];e[s(1408)](void 0,m)&&(e[s(1250)](he,n,24),xt(n,P(m)));let S=a[s(1321)];e[s(1163)](void 0,S)&&(e.rlQUT(he,n,32),xt(n,e.TzWrG(P,S)));let p=a[s(692)];if(e.ZTBdp(void 0,p))for(let ct of p){e[s(1870)](he,n,42);let Ze=e.yMyOa(k);e[s(515)](w,ct,Ze),e.UpNyX(he,n,Ze.limit),e[s(1958)](K,n,Ze),e.rPcBl(D,Ze)}let R=a[s(635)+s(1157)];if(e[s(596)](void 0,R)){if(e[s(1281)](e[s(1225)],s(526)))return{bytes:_0x261ed5,offset:0,limit:_0x12a951[s(1092)]};e[s(919)](he,n,50),q(n,R)}let L=a[s(1118)+"ype"];if(e.yYYys(void 0,L))if(e[s(1956)](e[s(1887)],"DRTYM"))e.EiHwA(he,n,58),e[s(1119)](q,n,L);else{if(_0x5b49a7===void 0)this._listeners={};else if(d[s(1277)](void 0,_0x225535))this[s(1180)+"rs"][_0x54b7d2]=null;else{let ct=this[s(1180)+"rs"][_0x3b3ead];if(ct)for(let Ze=0;Ze<ct[s(1092)];)ct[Ze].fn===_0x23b854?ct.splice(Ze,1):++Ze}return this}let N=a[s(1258)];e[s(732)](void 0,N)&&(e[s(919)](he,n,66),e[s(1070)](he,n,N.length),e[s(595)](oe,n,N));let F=a[s(1095)];e[s(1667)](void 0,F)&&(he(n,74),e[s(1654)](q,n,F));let $=a[s(1550)+s(466)];e[s(732)](void 0,$)&&(he(n,82),e.AJHuG(q,n,$));let X=a[s(1785)];e[s(496)](void 0,X)&&(he(n,90),q(n,X));let at=a[s(1827)+"e"];e[s(574)](void 0,at)&&(he(n,96),xt(n,P(at)))}function E(a){return I(e[t(857)](z,a))}function I(a){let n=t,s={};e:for(;!e[n(554)](V,a);){let d=e[n(1893)](xe,a);switch(e[n(659)](d,3)){case 0:break e;case 1:s[n(1835)]=e[n(1205)](St,a,!0);break;case 2:s.LogID=e.DldJX(St,a,!0);break;case 3:s[n(1444)]=e.rPcBl(xe,a);break;case 4:s[n(1321)]=xe(a);break;case 5:{let f=A(a);(s.headers||(s[n(692)]=[]))[n(539)](e[n(908)](_,a)),a[n(1659)]=f;break}case 6:s[n(635)+n(1157)]=e[n(771)](O,a,e.AHUKU(xe,a));break;case 7:s["payloadT"+n(1442)]=e[n(595)](O,a,e[n(908)](xe,a));break;case 8:s.payload=ie(a,e.TzWrG(xe,a));break;case 9:s[n(1095)]=O(a,e[n(1206)](xe,a));break;case 10:s[n(1550)+n(466)]=O(a,e[n(554)](xe,a));break;case 11:s[n(1785)]=e[n(1931)](O,a,e[n(554)](xe,a));break;case 12:s[n(1827)+"e"]=e[n(671)](xe,a);break;default:e.rlQUT(C,a,e[n(963)](7,d))}}if(e.kKCSx(void 0,s[n(1835)]))throw new Error(e[n(471)]);if(e[n(1954)](void 0,s[n(981)]))throw new Error(e.zgtrk);if(s.service===void 0)throw new Error(e[n(939)]);if(s[n(1321)]===void 0)throw new Error(e[n(806)]);return s}function A(a){let n=t,s=e[n(908)](xe,a),d=a[n(1659)];return a[n(1659)]=e[n(1921)](a[n(912)],s),d}function C(a,n){let s=t;switch(n){case 0:for(;e[s(963)](128,e[s(1470)](se,a)););break;case 2:Z(a,e[s(1385)](xe,a));break;case 5:e[s(1205)](Z,a,4);break;case 1:e[s(992)](Z,a,8);break;default:throw new Error(e[s(1921)](e[s(1155)],n))}}function P(a){let n=t;return a|=0,{low:a,high:e[n(1065)](a,31),unsigned:e[n(600)](a,0)}}let b=[];function k(){let a=t,n=b.pop();return n?(n.offset=n[a(1659)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function D(a){b[t(539)](a)}function z(a){let n=t,s={QuzPE:function(d,f,g){return d(f,g)},iUbgc:function(d,f){return e.XQzjr(d,f)}};if(n(983)===e.zzsEk)return{bytes:a,offset:0,limit:a.length};for(_0x3bf463>>>=0;_0x5003d2>=128;)s[n(475)](_0x88ac49,_0x144bd9,s[n(820)](127,_0x4bdf10)|128),_0x4b1f65>>>=7;s[n(475)](_0x416289,_0x3bdbd8,_0x35f2ef)}function M(a){let n=t,s=a[n(945)],d=a.limit;return e[n(1391)](s[n(1092)],d)?s:s[n(1913)](0,d)}function Z(a,n){let s=t;if(e[s(1817)](a[s(912)]+n,a.limit))throw new Error(e[s(1706)]);a.offset+=n}function V(a){let n=t;return a[n(912)]>=a[n(1659)]}function te(a,n){let s=t,d=a[s(945)],f=a[s(912)],g=a.limit,m=e.AoZZy(f,n);if(e[s(1586)](m,d[s(1092)])){if(e[s(1732)](s(1217),e[s(1322)]))return this._qosDB.clear();{let S=new Uint8Array(e[s(1019)](2,m));S.set(d),a[s(945)]=S}}return a[s(912)]=m,e[s(774)](m,g)&&(a[s(1659)]=m),f}function J(a,n){let s=t,d=a[s(912)];if(e[s(836)](d,n)>a[s(1659)])throw new Error(s(1818)+s(1820));return a[s(912)]+=n,d}function ie(a,n){let s=t,d=e.NuMqQ(J,a,n);return a[s(945)][s(1913)](d,e.dxDQR(d,n))}function oe(a,n){let s=t,d=e[s(1326)](te,a,n.length);a[s(945)][s(1430)](n,d)}function O(a,n){let s=t,d={miCAE:function(f,g){return e[U(554)](f,g)}};if(e[s(1031)]===s(1761)){let f=e.XesKi(J,a,n),g=String[s(675)+s(1546)],m=a[s(945)],S="\uFFFD",p="";for(let R=0;e.AAzra(R,n);R++){let L=m[e[s(1921)](R,f)],N,F,$,X;e[s(1732)](e[s(963)](128,L),0)?p+=g(L):e[s(1954)](224&L,192)?e[s(1256)](e[s(836)](R,1),n)?p+=S:(N=m[e[s(1303)](R,f)+1],(192&N)!==128?p+=S:(X=e[s(1743)](e[s(1833)](e[s(963)](31,L),6),e[s(1809)](63,N)),e[s(752)](X,128)?p+=S:(p+=g(X),R++))):e[s(812)](240,L)==224?R+2>=n?p+=S:e[s(1920)](e.JihXa,e[s(985)])?(_0x5e46ab+=d.miCAE(_0x167bcf,_0x14e3c2),_0x38cb3c++):(N=m[e.NITJJ(e[s(1164)](R,f),1)],F=m[e[s(1164)](R+f,2)],e[s(1110)](e[s(1743)](N,e.ZmUzZ(F,8))&49344,32896)?p+=S:(X=e.UzBnG(e[s(1400)](e[s(1833)](15&L,12),e[s(1833)](e[s(1963)](63,N),6)),e.hxMEf(63,F)),X<2048||e.WzDoN(X,55296)&&e[s(1128)](X,57343)?p+=S:(p+=e[s(1020)](g,X),R+=2))):e[s(1170)](248&L,240)?e[s(600)](R+3,n)?p+=S:(N=m[e[s(1734)](e[s(456)](R,f),1)],F=m[e[s(1531)](e[s(836)](R,f),2)],$=m[e[s(1803)](e.gjIKJ(R,f),3)],e[s(1145)](e[s(1134)](e[s(1743)](N,e[s(1833)](F,8)),e[s(1833)]($,16)),12632256)!==8421504?p+=S:(X=e[s(1474)](e[s(1329)](e[s(1335)](e[s(868)](7,L),18)|e[s(1833)](63&N,12),e.ZmUzZ(e[s(739)](63,F),6)),e.KMZbP(63,$)),X<65536||e[s(1817)](X,1114111)?p+=S:(X-=65536,p+=g(e[s(1164)](X>>10,55296),e[s(1945)](e[s(1581)](1023,X),56320)),R+=3))):p+=S}return p}else{let f={QRKWG:s(1017),LGUPG:function(p,R){let L=s;return rwmrIq[L(671)](p,R)},awNiK:function(p,R){let L=s;return rwmrIq[L(671)](p,R)},gFWYT:function(p,R){return p(R)},HKzsl:function(p){let R=s;return rwmrIq[R(922)](p)}},g=()=>{let p=s;_0x2c722b[p(814)+"entListener"](f[p(655)],m),_0x5656cd[p(814)+"entListe"+p(1062)](p(1863),S)},m=()=>{let p=s;f[p(623)](_0x4300b3,f[p(1131)](_0x5ded87,_0x530416[p(1053)])),g()},S=()=>{let p=s;f[p(828)](_0x30c4c3,_0x316444[p(1863)]),f[p(591)](g)};_0x3e6dea[s(1597)+"Listener"](s(1017),m),_0x348aa6["addEvent"+s(1574)](rwmrIq.SQijK,S)}}function q(a,n){let s=t,d=n.length,f=0;for(let S=0;e[s(752)](S,d);S++){let p=n[s(1257)+"At"](S);e.MZZxa(p,55296)&&e[s(1128)](p,56319)&&e[s(1370)](S+1,d)&&(p=e[s(1938)](e[s(1630)](p,10)+n[s(1257)+"At"](++S),56613888)),f+=e[s(642)](p,128)?1:e[s(947)](p,2048)?2:e[s(1949)](p,65536)?3:4}e[s(1366)](he,a,f);let g=e[s(905)](te,a,f),m=a[s(945)];for(let S=0;e[s(687)](S,d);S++){let p=n[s(1257)+"At"](S);e[s(1891)](p,55296)&&e.jZGxb(p,56319)&&e.AAzra(e[s(746)](S,1),d)&&(p=e[s(1945)](p<<10,n[s(1257)+"At"](++S))-56613888),e.SiuXY(p,128)?m[g++]=p:(e[s(687)](p,2048)?m[g++]=e[s(1678)](e[s(1065)](p,6)&31,192):(e.czweM(p,65536)?m[g++]=e[s(1743)](e[s(553)](e[s(1065)](p,12),15),224):(m[g++]=e[s(676)](e[s(965)](p>>18,7),240),m[g++]=e[s(1747)](e[s(722)](e[s(1233)](p,12),63),128)),m[g++]=e[s(1329)](e.tqXSM(e[s(1065)](p,6),63),128)),m[g++]=e.AJVto(e[s(868)](63,p),128))}}function K(a,n){let s=t,d=e[s(848)](te,a,n[s(1659)]),f=a.bytes,g=n[s(945)];for(let m=0,S=n[s(1659)];e[s(947)](m,S);m++)f[e[s(1945)](m,d)]=g[m]}function se(a){let n=t;return a[n(945)][e[n(1681)](J,a,1)]}function Ve(a,n){let s=t,d=e[s(515)](te,a,1);a[s(945)][d]=n}function xe(a){let n=t,s=0,d=0,f;do f=e[n(1815)](se,a),e[n(1287)](s,32)&&(d|=(127&f)<<s),s+=7;while(128&f);return d}function he(a,n){let s=t,d={MWfhf:function(f,g){return e[U(1380)](f,g)},CtzzN:function(f,g,m,S){return e[U(1689)](f,g,m,S)}};if(e.vOCcB(e[s(1849)],e[s(1849)])){let f=new _0x504e49(d[s(1601)](_0x42123e,_0x4c7078));return d.CtzzN(_0x426521,_0x4b9ac1,f,0),f}else{for(n>>>=0;n>=128;)Ve(a,e[s(1056)](127,n)|128),n>>>=7;e[s(1349)](Ve,a,n)}}function St(a,n){let s=t,d=0,f=0,g=0,m;if(m=e[s(453)](se,a),d=e[s(868)](127,m),e[s(963)](128,m)&&(m=se(a),d|=e.oNOCe(e.hjFDH(127,m),7),e[s(1005)](128,m)&&(m=se(a),d|=e[s(1833)](127&m,14),e[s(734)](128,m)&&(m=e[s(1782)](se,a),d|=e[s(1501)](e[s(1377)](127,m),21),e[s(553)](128,m)))))if(e[s(1391)]("ZnFYE",e[s(1979)]))m=e.oSlnm(se,a),f=e.XQzjr(127,m),e[s(965)](128,m)&&(m=e[s(709)](se,a),f|=e[s(571)](127,m)<<7,128&m&&(m=e[s(1515)](se,a),f|=e[s(1554)](e[s(501)](127,m),14),128&m&&(m=e[s(1815)](se,a),f|=e.doLap(e[s(1145)](127,m),21),128&m&&(m=se(a),g=e.JNViv(127,m),e[s(457)](128,m)&&(m=e.AHUKU(se,a),g|=e[s(1554)](127&m,7))))));else{let S=e[s(1205)](_0x2cedf4,e[s(1644)],{message:_0x72b591[s(924)],code:_0x470949[s(1296)+"OR"],error:_0xcbfde2});this["_dispatc"+s(625)+s(1342)](S)}return{low:e[s(1042)](d,e[s(1554)](f,28)),high:f>>>4|e[s(1833)](g,24),unsigned:n}}function xt(a,n){let s=t,d=e[s(659)](n[s(1529)],0),f=e[s(659)](e[s(1747)](e[s(874)](n[s(1529)],28),e[s(1833)](n.high,4)),0),g=e.RsfdU(n[s(572)],24),m=g===0?e[s(1956)](0,f)?e[s(1591)](d,16384)?e[s(642)](d,128)?1:2:e[s(1598)](d,2097152)?3:4:e[s(1591)](f,16384)?f<128?5:6:f<2097152?7:8:e[s(721)](g,128)?9:10,S=e.NHGml(te,a,m),p=a[s(945)];switch(m){case 10:p[S+9]=e[s(1446)](e[s(659)](g,7),1);case 9:p[S+8]=e[s(574)](9,m)?e[s(792)](128,g):127&g;case 8:p[S+7]=e.FLBhT(8,m)?e.SsnZl(f,21)|128:e[s(1230)](f,21)&127;case 7:p[e[s(836)](S,6)]=m!==7?f>>>14|128:e.hfjtU(f,14)&127;case 6:p[S+5]=e[s(1796)](6,m)?e[s(1474)](e[s(685)](f,7),128):e.guuTe(f,7)&127;case 5:p[e[s(1164)](S,4)]=e[s(1777)](5,m)?e[s(1269)](128,f):e[s(501)](127,f);case 4:p[e.gjIKJ(S,3)]=m!==4?e[s(1050)](e.guuTe(d,21),128):e[s(1200)](e[s(957)](d,21),127);case 3:p[e.uBBNF(S,2)]=m!==3?e.uJqvy(e.guuTe(d,14),128):e.SdlOE(d,14)&127;case 2:p[e[s(1718)](S,1)]=e[s(1408)](2,m)?e[s(1269)](e[s(1230)](d,7),128):e.mEUKM(e[s(696)](d,7),127);case 1:p[S]=e[s(1777)](1,m)?e[s(1743)](128,d):e[s(1756)](127,d)}}function Qt(a){return E(a)}function Ft(a){let n=t,s={CCWcy:function(d,f){return d>=f}};return e[n(1064)](e[n(944)],e.rtxxc)?s[n(1798)](this[n(1241)],this[n(1214)+n(1475)]):e[n(1521)](v,a)}let en=65536,Vr=e[t(518)],me=e[t(1914)](en,en),Ie=me*me,Xn=e[t(975)](Ie,2),ke=String[t(1517)+"e"][t(1257)+"At"];class fe{constructor(n,s,d){let f=t;this[f(1078)]=!0,this[f(1529)]=0|n,this[f(572)]=e[f(607)](0,s),this[f(1934)]=!!d}static[t(1078)](n){let s=t;if(e[s(590)](e[s(783)],"HJJfz"))return n&&e[s(1828)](!0,n.isLong);{let d=this._qosDB[s(776)](this._prefix),f=_0x781970[s(859)](e[s(1009)](d,"{}"));return f[_0x443210||_0x4702bd[this[s(791)]]]=_0x189c89,this[s(1894)].setItem(this._prefix,_0x3d702f[s(1862)+"y"](f)),_0x46b8b1||_0x481fbb[this[s(791)]]}}static[t(1480)](n,s,d){return new fe(n,s,d)}static[t(760)+"s"](n,s,d){let f=t;return d?fe[f(760)+f(1175)](n,s):fe[f(760)+"sBE"](n,s)}static[t(760)+"sLE"](n,s){let d=t;return new fe(e[d(1747)](e.sSyVW(n[0]|n[1]<<8,e[d(1501)](n[2],16)),n[3]<<24),e[d(1834)](e[d(1010)](e[d(1343)](n[4],e[d(819)](n[5],8)),e.mTEaj(n[6],16)),e[d(1554)](n[7],24)),s)}static[t(760)+t(674)](n,s){let d=t;return new fe(e.UzBnG(e[d(490)](n[4],24)|e[d(490)](n[5],16)|e[d(819)](n[6],8),n[7]),e[d(1716)](e[d(1010)](e[d(704)](e[d(1833)](n[0],24),e.ZGTCD(n[1],16)),e.qGRzb(n[2],8)),n[3]),s)}static[t(1190)](n){let s=t;if(e.yYYys("wSvtO",e[s(763)])){let d=_0x49a3f7[s(1627)+"g"](0,4-_0x3b82aa[_0xf1e409][s(1092)]),f=d.concat(_0x3c5fa4);_0x4adc2c=_0x3d1bdb[s(592)](f)}else return e[s(1828)](n,Vr)?Wd:new fe(e[s(1959)](e.dpgqQ(e.MVACz(ke[s(941)](n,0),e[s(1749)](ke[s(941)](n,1),8)),e[s(1501)](ke[s(941)](n,2),16))|e[s(1867)](ke[s(941)](n,3),24),0),e[s(957)](e[s(1400)](e[s(1829)](e[s(1004)](ke.call(n,4),ke.call(n,5)<<8),e[s(490)](ke[s(941)](n,6),16)),e.doLap(ke.call(n,7),24)),0),!0)}[t(1525)](){let n=t;return String[n(675)+"Code"](e[n(1338)](255,this[n(1529)]),e[n(957)](this[n(1529)],8)&255,e[n(1756)](this[n(1529)]>>>16,255),e[n(895)](this[n(1529)],24),255&this[n(572)],e[n(1904)](this[n(572)],8)&255,e[n(1377)](e[n(594)](this[n(572)],16),255),e[n(1481)](this.high,24))}static[t(1216)+"er"](n,s=!0){let d=t,f={CQFES:d(924),axLit:function(g,m,S){return e[d(1931)](g,m,S)}};if(e[d(610)](isNaN,n))return s?cp:Wd;if(s)if(e[d(1318)]("hrbkN",e[d(1363)])){if(e.hZeol(n,Ie))return lp}else this[d(1599)](f[d(1455)],f[d(1447)](_0x92459f,f.CQFES,{..._0x7473e6}));else{if(e[d(1067)](n,-Xn))return up;if(e.VHHNv(e.gjIKJ(n,1),Xn))return dp}return fe[d(1480)](e.SZynk(e[d(1033)](n,me),0),e.uJqvy(e[d(975)](n,me),0),s)}toNumber(){let n=t,s={gMMDh:function(d,f){return e.qjZxK(d,f)},IuVPJ:function(d,f){return e[U(529)](d,f)}};return e.GcCKl(e.akCzs,n(1658))?this[n(1934)]?e[n(1438)](e[n(1019)](e[n(895)](this[n(572)],0),me),this[n(1529)]>>>0):e[n(1303)](e[n(1019)](this.high,me),e.wWTBB(this[n(1529)],0)):beHtto[n(1632)](beHtto.IuVPJ(_0x2186e9,4)[n(631)]("0"),_0x4ed4ed(_0x24268c,2)[n(1539)](16))[n(1037)](-4)}isZero(){let n=t;return e[n(1391)](0,this.high)&&e[n(1318)](0,this.low)}[t(1794)](n){let s=t;fe[s(1078)](n)||(n=fe[s(1216)+"er"](n));let d=this[s(572)]>>>16,f=e[s(682)](65535,this[s(572)]),g=this.low>>>16,m=e[s(501)](65535,this[s(1529)]),S=e[s(1436)](n.high,16),p=e[s(1305)](65535,n.high),R=e.ptUVa(n[s(1529)],16),L=65535&n[s(1529)],N=0,F=0,$=0,X=0;return X+=e[s(1905)](m,L),$+=X>>>16,X&=65535,$+=e[s(1808)](g,R),F+=e[s(1916)]($,16),$&=65535,F+=f+p,N+=e[s(1675)](F,16),F&=65535,N+=e.ecoID(d,S),N&=65535,fe[s(1480)](e.uJqvy(e.mGlox($,16),X),e.UZdip(e[s(819)](N,16),F),this[s(1934)])}[t(1193)](n){let s=t;return fe[s(1078)](n)||(n=fe.fromNumber(n)),e[s(629)](this[s(1934)],n.unsigned)&&e.YSuWF(this[s(572)],31)===1&&e[s(1929)](n[s(572)],31)===1?!1:this[s(572)]===n.high&&this[s(1529)]===n.low}[t(1293)](){let n=t;return this[n(1529)]===-1&&e[n(1956)](-1,this[n(572)])?fe[n(1480)](0,0,this.unsigned):e[n(1120)](-1,this[n(1529)])?fe[n(1480)](0,e[n(1231)](this[n(572)],1),this[n(1934)]):fe[n(1480)](this[n(1529)]+1,this[n(572)],this[n(1934)])}toBytes(n){return n?this.toBytesLE():this[t(547)+"E"]()}[t(519)+"E"](){let n=t;if(e[n(1621)](n(643),n(1090))){let s=this.high,d=this.low;return[255&d,e[n(1476)](d,8)&255,e.rCwOi(d,16)&255,e[n(1900)](d,24),e[n(963)](255,s),e.DVfEU(s>>>8,255),e.wNkFq(s,16)&255,e[n(696)](s,24)]}else{let{url:s}=_0x55db79||{},d=_0x3fa259[n(1620)](s)?s:e[n(1170)](e[n(1222)],typeof s)?[s]:[];_0x50443b&&_0x3b36e5[n(1333)](this._options,_0x4ac7ce),d&&d.length?this[n(1764)+n(1637)]=new _0x2c3c16(d,this[n(499)][n(1951)+"es"]):this._endpointManager?.[n(1763)+n(989)+n(1673)](),this[n(1463)+n(1760)]?.[n(1003)+"nter"](this[n(499)][n(995)+n(1683)]),this[n(1751)+n(567)]=!1,this[n(459)]&&this[n(459)][n(1270)+"te"]!==this[n(1237)]?this[n(1625)+n(833)](1e3,n(1427)+n(920)+n(1804),!0):(this[n(1316)]=!0,this[n(1656)]())}}[t(547)+"E"](){let n=t,s=this[n(572)],d=this.low;return[e[n(1524)](s,24),e.XQzjr(e[n(1476)](s,16),255),e[n(1929)](s,8)&255,255&s,d>>>24,e[n(1602)](d>>>16,255),e[n(1249)](e[n(1916)](d,8),255),255&d]}}let Wd=new fe(0,0,!1),cp=new fe(0,0,!0),dp=fe[t(1480)](-1,2147483647,!1),lp=fe[t(1480)](-1,-1,!0),up=fe[t(1480)](0,-2147483648,!1);var tn=(function(a){let n=t,s=(n(766)+n(1584)).split("|"),d=0;for(;;){switch(s[d++]){case"0":return a;case"1":a[a[e[n(640)]]=5002]=n(737)+n(1926);continue;case"2":a[a[e[n(1328)]]=5004]=n(1712)+n(1606);continue;case"3":a[a[e.HBCjf]=5003]=n(1619)+n(1111)+"R";continue;case"4":a[a[e.OlNSm]=5005]=e[n(940)];continue;case"5":a[a[e[n(1147)]]=5001]=n(1940)+n(582);continue}break}})({});class Qn{constructor(n){let s=t;this[s(544)]=n,this[s(1198)]=null}}class Kd extends Qn{constructor(n,s){let d=t;super(n),this[d(924)]=s&&s[d(924)]||null}}class $d extends Qn{constructor(n,s){let d=t;super(n),this[d(1863)]=s&&s[d(1863)]||null,this.colno=s&&s.colno||0,this[d(1567)]=s&&s[d(1567)]||"",this.lineno=s&&s.lineno||0,this[d(924)]=s&&s.message||"",this[d(485)]=s&&s.code||5001}}class Vd extends Qn{constructor(n,s){let d=t,f=e.frxnn.split("|"),g=0;for(;;){switch(f[g++]){case"0":this.code=s&&s.code||0;continue;case"1":this[d(1133)]=s&&s.wasClean||!1;continue;case"2":super(n);continue;case"3":this[d(1179)]=s&&s[d(1179)]||"";continue;case"4":this[d(522)+"nnect"]=s&&s[d(522)+d(492)]||!1;continue}break}}}class Zd extends Qn{constructor(n,s){let d=t;super(n),this[d(1841)]=s&&s[d(1841)]||null}}class Jd extends Zd{constructor(n,s){let d=t;if(e.JuDaU("Mwbsn",d(1896))){let f=this._qosDB[d(1107)+d(601)+"nc"](this[d(1512)]),g=_0x1dba19.parse(e[d(1097)](f,"{}"));return _0x20a62d[d(837)](g)}else super(n),this.data=s&&s[d(1841)]||null,this[d(924)]=s&&s.message||null}}class Yd extends Qn{constructor(n,s){let d=t;super(n),this[d(1841)]=s&&s[d(1841)]||null}}function ot(a,{message:n,code:s,error:d}){return new $d(a,{message:n,code:s,error:d})}function ht(a,{code:n,reason:s,wasClean:d,willReconnect:f}){return new Vd(a,{code:n,reason:s,wasClean:d,willReconnect:f})}function Xd(a,{data:n,message:s}){return new Jd(a,{data:n,message:s})}function Qd(a,{data:n}){return new Yd(a,{data:n})}function aa(a,{message:n}){return new Kd(a,{message:n})}class el{constructor(n,s){let d=t;this[d(762)+"s"]=n,this[d(1951)+"es"]=s,this[d(487)+"ndex"]=0,this[d(1487)+d(454)+d(747)+"t"]=0}[t(1763)+t(989)+"fig"](){let n=t;this[n(487)+"ndex"]=0,this["currentE"+n(454)+n(747)+"t"]=0}resetTries(){let n=t;e[n(578)]!==e[n(578)]?rwmrIq.kGwSX(_0x4f43d6,rwmrIq[n(1213)](_0x3b1d1a,_0x144992[n(1053)]),_0x4780ac[n(1425)+"on"],_0xe8b61f[n(1855)+"on"],rwmrIq[n(554)](_0x4486d7,_0x39a77d[n(784)+"ion"])):this[n(1487)+n(454)+"riesCount"]=0}[t(1022)+"ntEndpoint"](){return this.endpoints[this.currentIndex]}[t(1022)+t(1094)+t(1593)+t(1475)](){let n=t;return this["currentE"+n(454)+n(747)+"t"]}[t(1144)+t(1535)+"es"](){let n=t,s={FSFMP:function(d,f){return e[U(1009)](d,f)}};if(e[n(1956)](e[n(1765)],e[n(461)])){let d=this._qosDB["getStora"+n(1699)](this[n(1512)]),f=_0x5ed32c[n(859)](s[n(1745)](d,"{}"));return f[_0x501dbe]=void 0,this[n(1894)][n(1242)+"geSync"](this[n(1512)],_0x4df928[n(1862)+"y"](f))}else return!!(e[n(1891)](this[n(487)+n(1418)],this.endpoints[n(1092)])||e[n(1954)](this["currentI"+n(1418)],e[n(1652)](this[n(762)+"s"][n(1092)],1))&&e.VSrUs(this[n(1487)+n(454)+"riesCount"],this[n(1951)+"es"]))}[t(1058)+t(1245)+t(1858)+t(850)+t(632)](){let n=t;return e.WVgKC(this[n(487)+n(1418)],this[n(762)+"s"].length)?!0:e[n(774)](this[n(1487)+n(454)+n(747)+"t"],this[n(1951)+"es"])}[t(1320)+"ackupEnd"+t(817)+t(877)+t(1909)](){let n=t;return e[n(1828)](e.GTBDu,e[n(1417)])?(this[n(1487)+"ndpointT"+n(747)+"t"]=1,this[n(487)+n(1418)]++,this[n(762)+"s"][this["currentI"+n(1418)]]):this._socket[n(1270)+"te"]}[t(1022)+t(1094)+t(1773)+t(464)](){let n=t;return this[n(1487)+n(454)+"riesCount"]++,this[n(1022)+n(1094)+"nt"]()}}let er=(e[t(1087)](e[t(1633)],typeof globalThis)&&e[t(1899)](e[t(1038)],globalThis[t(1502)+t(1130)][t(789)])||e[t(1002)](e[t(1633)],typeof window)&&e[t(670)](e[t(1038)],window[t(1502)+t(1130)][t(789)]))&&e[t(1516)](t(455)+"d",typeof document),Rn=e[t(1516)](e[t(1633)],typeof globalThis)&&(e.xpPkz(e[t(1452)],globalThis["construc"+t(1130)][t(789)])||e[t(790)](t(1325)+"dWorkerG"+t(1753)+"pe",globalThis[t(1502)+t(1130)][t(789)]))&&e[t(900)](t(455)+"d",typeof tt),Zr=(e[t(1240)](e[t(1633)],typeof globalThis)&&e[t(1534)](e[t(1452)],globalThis["construc"+t(1130)][t(789)])||e[t(1332)](e.uZbLf,typeof globalThis)||e[t(1516)](e.uZbLf,typeof globalThis)&&!!globalThis["WeixinJS"+t(1728)])&&e[t(1002)](e[t(1633)],typeof wx),Jr=e[t(1633)]!=typeof globalThis&&(e[t(560)](e[t(652)],globalThis[t(1502)+t(1130)].name)||t(1334)+"rkerGlob"+t(765)===globalThis[t(1502)+t(1130)][t(789)]||e.pyfho===globalThis[t(1502)+t(1130)][t(789)])&&e.RahEV(e[t(1633)],typeof self),fp=e.tznGB(e.uZbLf,typeof globalThis)&&e[t(710)]("Object",globalThis.constructor.name)&&e[t(531)](e[t(1633)],typeof global)&&e[t(1861)](e.GhQwy,global[t(1502)+"tor"].name)&&e[t(1633)]!=typeof process&&!!process[t(467)];class ca{constructor(){let n=t;this[n(1180)+"rs"]={}}[t(1599)](n,...s){let d=t,f=this[d(1180)+"rs"][n];if(f)f[d(1037)]()[d(1399)](g=>g.fn[d(772)](g[d(785)],s));else if(e[d(1920)](e[d(1644)],n)&&!this[d(690)]){let g=s[d(1092)]&&s[0];if(e.JVJaw(g,Error))throw g;let m=new Error(e[d(1303)](e[d(1486)],g?e[d(1734)](e.MSQxe(" (",g.message),")"):""));throw m[d(1702)]=g,g}return this}[t(1592)](n,s){let d=t;if(e.ioGQC(void 0,n))this._listeners={};else if(e[d(1353)](void 0,s))this[d(1180)+"rs"][n]=null;else{let f=this[d(1180)+"rs"][n];if(f)for(let g=0;g<f[d(1092)];)e[d(1032)](f[g].fn,s)?f[d(1298)](g,1):++g}return this}on(n,s,d){let f=t;return(this[f(1180)+"rs"][n]||(this._listeners[n]=[]))[f(539)]({fn:s,ctx:d||this}),this}}class xp extends ca{[t(1560)+t(1825)+t(638)](n){let s=t;return e[s(1562)]===s(1759)?(_0x2a1287[s(1449)](_0x2e0a6e),!1):n[s(1650)]||n[s(1590)]?(s(795)+" "+(n.errMsg||"")+s(1503)+(n[s(1590)]||""))[s(714)]():JSON[s(1862)+"y"](n)}constructor(n,s,d){let f=t;super(),this._socket=null,Zr&&wx[f(1398)+f(1703)]&&(this[f(1232)]=wx[f(1398)+f(1703)]({url:n,protocols:s,header:d,fail:this[f(559)+f(1203)+f(639)][f(1252)](this),success:this[f(559)+f(1484)+f(686)+"ler"].bind(this)})),Rn&&tt[f(1398)+f(1703)]&&(this[f(1232)]=tt[f(1398)+"ocket"]({url:n,protocols:s,header:d,fail:this[f(559)+"ocketFailHandler"][f(1252)](this),success:this[f(559)+f(1484)+f(686)+f(731)][f(1252)](this)}))}[t(559)+t(1484)+"cessHand"+t(731)](){let n=t,s={tArPV:function(d,f){return e.sfgZW(d,f)},owznl:function(d,f){return e.Nqytd(d,f)},kvhHm:e[n(1043)]};Promise[n(1626)]()[n(1196)](()=>{let d=n,f={hzLzz:function(g,m){return s[U(1146)](g,m)}};if(s[d(911)](s[d(866)],d(1080)))this["_addWsLi"+d(1127)]();else return _0x3cc662[d(772)](jcBePB[d(1355)](_0x265908,this),_0x3a03e5),jcBePB[d(1355)](_0x2994ec,_0x56e6f2[d(649)](this))})}[t(559)+t(1203)+t(639)](n){let s=t;Promise[s(1626)]()[s(1196)](()=>{let d=s,f=e[d(523)](ot,e[d(1644)],{message:this[d(1560)+"rrorMess"+d(638)](n)});this.emit(e[d(1644)],f);let g=e[d(835)](ht,e[d(851)],{reason:this[d(1560)+d(1825)+d(638)](n)});this[d(1599)](e[d(851)],g)})}[t(956)+"steners"](){let n=t,s={HLLKe:function(d,f,g){return e.jwKDp(d,f,g)}};this._socket[n(462)](d=>{let f=n;this.emit(e[f(1520)],e.DBbOL(Qd,e.noxks,{...d,data:d[f(1650)]||""}))}),this[n(1232)][n(759)](d=>{let f=n;this[f(1599)](f(1528),e.Qzgir(ht,e[f(851)],{...d}))}),this[n(1232)].onMessage(d=>{let f=n;this.emit(f(924),s[f(1744)](Xd,f(924),{...d}))}),this[n(1232)][n(1167)](d=>{let f=n;this[f(1599)](e[f(1644)],ot(e[f(1644)],{...d,message:d.errMsg||""}))})}[t(1708)](n){let s=t,d={kmTUu:function(f,g,m){return e[U(1933)](f,g,m)},gGPMm:e[s(1644)]};if(n instanceof Uint8Array){let f=n[s(884)][s(1037)](n.byteOffset,n[s(1192)+"th"]+n.byteOffset);this[s(1232)]&&this[s(1232)][s(1708)]({data:f,fail:g=>{let m=s;this[m(1599)](m(1863),d.kmTUu(ot,d[m(1577)],{message:this["_formatE"+m(1825)+"age"](g)}))}})}else this._socket&&this._socket[s(1708)]({data:n,fail:f=>{let g=s;this[g(1599)]("error",e[g(1204)](ot,e[g(1644)],{message:this[g(1560)+g(1825)+g(638)](f)}))}})}[t(1528)](n,s){let d=t;this[d(1232)]&&this[d(1232)][d(1528)]({code:n,reason:s})}[t(1597)+t(1574)](n,s){this.on(n,s)}[t(814)+t(870)+t(1062)](n,s){this[t(1592)](n,s)}get[t(1270)+"te"](){let n=t;return this[n(1232)][n(1270)+"te"]}get[t(1044)+"pe"](){let n=t,s={DSGlQ:function(d,f){return d|f},RAlHV:function(d,f){return e[U(840)](d,f)},KHLOP:function(d,f){return e[U(1501)](d,f)},ZxdIi:function(d,f){return e.Aneih(d,f)},nylbL:function(d,f){return e[U(456)](d,f)},aWEPE:function(d,f){return e[U(555)](d,f)},iYLsQ:function(d,f){return e[U(1371)](d,f)},xqUOA:function(d,f){return e[U(1544)](d,f)},uLQhS:function(d,f){return e[U(1905)](d,f)}};if(e.FLBhT(e[n(679)],e.ptjpX))return this._socket[n(1044)+"pe"];{let d=new _0x5d53e5(s.DSGlQ(s[n(521)](s[n(613)](s.KHLOP(_0x3e849b[s.ZxdIi(_0x46ba5e,4)],24),s[n(1859)](_0x5a0bd4[_0x2f9879+5],16)),s[n(1859)](_0x243163[s[n(1104)](_0x242c76,6)],8)),_0x2d28f4[s[n(1297)](_0x502af5,7)]),s[n(1670)](s.KHLOP(_0x63248f[s.iYLsQ(_0x3a6f24,0)],24)|s[n(1859)](_0x59b9e5[_0x1ff9c4+1],16),s.KHLOP(_0xa0ba77[s[n(879)](_0x39d86e,2)],8))|_0x326659[s.uLQhS(_0x5359cc,3)],!0);return _0x3c0dbf+=8,{value:d,offset:s[n(879)](_0xda2207,8)}}}set[t(1044)+"pe"](n){}get[t(986)](){let n=t;return this._socket[n(986)]}get[t(946)](){return this[t(1232)].protocol}get[t(1301)+"ns"](){let n=t;return this._socket[n(1301)+"ns"]}get[t(1181)+t(1736)](){let n=t;if(e[n(1974)](e[n(931)],e[n(931)]))this[n(1214)+"ount"]=_0x40968d,this[n(1241)]=0;else return 0}}function hp(a,n){let s=t;if(n)return new n(a[s(986)],a[s(946)]);if(Zr||Rn)return new xp(a[s(986)],a[s(946)],a.headers);if(e[s(1009)](er,Jr)&&e[s(1633)]!=typeof WebSocket&&WebSocket)return new WebSocket(a.url,a.protocols)}function pp(a){let n=t,s=e.WHOiY.split("|"),d=0;for(;;){switch(s[d++]){case"0":if(a)return!0;continue;case"1":if(Zr&&wx[n(1398)+n(1703)])return!0;continue;case"2":return!1;case"3":if(e[n(1908)](er,Jr)&&e[n(1516)](n(455)+"d",typeof WebSocket)&&WebSocket)return!0;continue;case"4":if(Rn&&tt[n(1398)+n(1703)])return!0;continue}break}}function tl(a,n,s){let d=t,f={XJhdp:function(S,p){return e.jZGxb(S,p)},bncZi:function(S,p){return S===p},vWwbP:function(S,p){return S+p}},g=-1;async function m(S){let p=U;return f.XJhdp(S,g)?Promise[p(1710)](new Error(p(1454)+p(1124)+p(604)+p(1729)+p(1543))):(g=S,f[p(1464)](S,s[p(1092)])?Promise.resolve():s[S].bind(a)(n,m[p(1252)](null,f.vWwbP(S,1))))}e[d(964)](m,0)}function nl(a){let n=t;if(e[n(1766)](e[n(1768)],"QtWtc")){let s=0,d=0;for(let f=0;e[n(1279)](f,a.length);++f)d=a[n(1257)+"At"](f),d<128?s+=1:e[n(892)](d,2048)?s+=2:e.DVfEU(64512,d)===55296&&e[n(1534)](e[n(1602)](64512,a[n(1257)+"At"](e.jAlPg(f,1))),56320)?(++f,s+=4):s+=3;return s}else return this[n(1894)]?.[n(649)](_0x38328c)}function rl(a,n,s){let d=t;if(s-n<1)return"";let f="";for(let g=n;e.VQSIK(g,s);){let m=a[g++];if(e[d(1086)](m,127))f+=String[d(675)+d(1546)](m);else if(m>=192&&e[d(1949)](m,224))f+=String[d(675)+d(1546)](e[d(1829)](e[d(1501)](31&m,6),e.OTOIj(63,a[g++])));else if(e[d(1892)](m,224)&&m<240)f+=String[d(675)+d(1546)](e[d(570)](e[d(1244)](e[d(899)](15,m),12)|e[d(1501)](e.jNsla(63,a[g++]),6),63&a[g++]));else if(e.hZeol(m,240)){if(e[d(816)](e[d(1799)],e[d(1570)]))return new _0x64f322(_0xb38d3e);{let S=e[d(1123)](e.soyNn(e[d(1495)](e[d(704)](e.FrhSG(7,m)<<18,e[d(1056)](63,a[g++])<<12),e[d(549)](63&a[g++],6)),e.tqXSM(63,a[g++])),65536);f+=String[d(675)+d(1546)](e[d(1803)](55296,S>>10)),f+=String[d(675)+d(1546)](e[d(1552)](56320,e[d(1103)](1023,S)))}}}return f}function da(a,n,s){let d=t,f={nAcOD:function(g,m){return e[U(1949)](g,m)},pFAGd:function(g,m){return e[U(1098)](g,m)}};if(e[d(1281)](e[d(537)],d(1494))){let g=0,m=0,S;do S=_0x5118bb(_0x1df34f),cNYQub[d(486)](g,32)&&(m|=cNYQub[d(1615)](127&S,g)),g+=7;while(128&S);return m}else{let g=s,m,S;for(let p=0;e[d(1393)](p,a.length);++p)if(e[d(927)](d(1614),e[d(1276)]))this[d(1260)+"T"]||this._isMiniWX?this[d(1790)+"etWorkCh"+d(614)]():this._isBrowser&&this["_initGlo"+d(1523)+"Listener"]();else if(m=a[d(1257)+"At"](p),e[d(1279)](m,128))n[s++]=m;else if(e.rcuHS(m,2048))n[s++]=m>>6|192,n[s++]=e[d(1191)](e[d(1955)](63,m),128);else if(e[d(1603)](e.IYOaC(64512,m),55296)&&e.SqMmf(e[d(1069)](64512,S=a[d(1257)+"At"](p+1)),56320)){let R=e[d(483)].split("|"),L=0;for(;;){switch(R[L++]){case"0":n[s++]=e.ebOvs(e[d(548)](63,m),128);continue;case"1":n[s++]=e[d(1743)](e[d(1715)](m,18),240);continue;case"2":n[s++]=e[d(1466)](e.adcMY(e[d(1715)](m,12),63),128);continue;case"3":m=e[d(1482)](65536+e[d(1844)](e[d(682)](1023,m),10),e[d(1955)](1023,S));continue;case"4":++p;continue;case"5":n[s++]=e[d(1721)](e[d(722)](e[d(666)](m,6),63),128);continue}break}}else{if(e.VLKKX(e[d(1499)],e[d(733)]))return!!this._qosDB;n[s++]=e[d(1405)](m,12)|224,n[s++]=e[d(1134)](e[d(1069)](e[d(1065)](m,6),63),128),n[s++]=e.KHNFZ(e[d(868)](63,m),128)}return e[d(984)](s,g)}}async function il(a){let n=t;if(e[n(1222)]==typeof a){let s=new Uint8Array(e[n(863)](nl,a));return e[n(1807)](da,a,s,0),s}return e[n(1547)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(884)],a[n(702)+"et"],a[n(1192)+"th"])}function gp(a){let n=t;try{return e.Aayhx(e[n(1222)],typeof a)&&(e.dTvlP(a,ArrayBuffer)||a[n(884)]&&e.EuqOG(a[n(884)],ArrayBuffer))||e[n(1516)](e.DMjhK,typeof a)?"":(JSON[n(859)](a),n(824)+n(1617))}catch{return e[n(1472)](n(856),typeof a)?n(804)+n(1275)+n(1600):""}}let mp=(a,n)=>{let s=t;switch(a){case e[s(1538)]:case e[s(1857)]:return{["x-use-"+a]:1,"x-tt-env":n};default:return{}}};class wp{constructor(n){let s=t;this[s(1214)+s(1475)]=n,this[s(1241)]=0}[t(896)](){let n=t;this[n(1241)]++}["checkRea"+t(1135)+"nt"](){let n=t;return e[n(1256)](this[n(1241)],this[n(1214)+n(1475)])}["resetCou"+t(474)](n=0){let s=t;this.maxLossCount=n,this[s(1241)]=0}}async function _p(a){let n=t,s={hsomR:function(d,f){return d(f)},WfvAZ:e[n(688)]};return new Promise(d=>{let f=n;if(!er)return d(e[f(688)]);try{let g=document[f(1169)+f(1378)](f(1583));window[f(1709)+f(1814)]=m=>{let S=f;document[S(744)][S(930)+"ild"](g),window["frontier"+S(1814)]=void 0,s.hsomR(d,m&&m[S(797)]||s[S(1299)])},g.type=e[f(589)],g[f(977)]=e[f(746)](a[f(1662)](/^ws/,e[f(1075)]),e[f(664)]);try{if(e[f(1796)](e[f(1461)],e[f(1386)]))document[f(744)][f(1185)+f(1285)](g);else return new _0x4b483d(_0x2d12f3,{message:_0x5474a7})}catch{document[f(744)][f(930)+f(1285)](g)}}catch{window[f(1709)+"JSONP"]=void 0,d(e.iwpHh)}})}function nn(a,n,s){let d=t;return!!a?.[d(1132)](f=>f.key===n&&f[d(1557)]===s)}function tr(a,n){let s=t;return e.fGAiG!==e[s(1641)]?this._qosDB?.[s(1578)](_0x47e2c8):a?.[s(1132)](d=>d[s(681)]===n)?.value}let la=null;async function yp(){let a=t;return la||(la=Promise.resolve().then(Mt.bind(Mt,e[a(545)]))),la}class bp extends ca{constructor(n,s){let d=t;super(),this[d(1414)]=n,this[d(831)]=s,this[d(1894)]=void 0,this["_initPro"+d(1183)]=null}async openDB(){await this[t(996)]()}async[t(996)](){let n=t,s={CEyNX:e.swYYi,PdzvZ:e[n(1791)],lUCGy:e[n(755)],ONFGZ:function(d,f){return e[n(555)](d,f)},qknQm:function(d,f){return e[n(532)](d,f)},HInoz:function(d,f){return d!==f},JytYE:n(1151),WIDhx:function(d){return e[n(922)](d)},bMrIn:function(d,f,g,m){return e[n(1356)](d,f,g,m)}};if(e[n(1960)](e[n(1953)],n(603)))!_0x3f63c3.persisted&&(this[n(1026)+"er"]&&_0xd9c96a["removeEv"+n(870)+"ner"](n(513),this[n(711)+n(1238)]),this[n(1026)+"er"]&&_0x2ab592["removeEventListe"+n(1062)](s[n(615)],this[n(711)+n(1063)]),this.close()),this[n(1026)+"er"]&&_0x1d0e99[n(814)+n(870)+n(1062)](s[n(860)],this[n(668)+n(1093)]),this._isBrowser&&_0x322389["removeEventListe"+n(1062)](s.lUCGy,this[n(668)+"ffLine"]);else{if(this[n(1894)])return;if(this[n(1957)+n(1183)])return this[n(1957)+n(1183)];try{let d=this._dbName,f=this[n(831)];this["_initPro"+n(1183)]=(async()=>{let g=n,m={OVsMu:function(p,R){return p|R},YAWpO:function(p,R){return s[U(1072)](p,R)},SJVKB:function(p,R){return s[U(1545)](p,R)},OpgsO:function(p,R){return s[U(701)](p,R)},VLsQe:s.JytYE},{openDB:S}=await s[g(1235)](yp);this[g(1894)]=await s[g(1677)](S,g(1709)+"_"+d,1,{upgrade(p){let R=g,L={pULsp:function(N,F){return N>>>F},hahIc:function(N,F){return m.OVsMu(N,F)},SIFOS:function(N,F){return m[U(673)](N,F)},gxGAc:function(N,F){return m[U(1752)](N,F)},fxqQq:function(N,F){return N>>>F},xhmNV:function(N,F){return N|F}};if(m[R(1387)](m.VLsQe,m[R(1536)]))return _0x5ab38a===_0x4468e7?_0x473240:new _0x4d85a8(nBuLtn[R(1740)](nBuLtn[R(1313)](nBuLtn.SIFOS(nBuLtn[R(1313)](_0x2d66fa.call(_0x5a39b6,0),nBuLtn[R(657)](_0x4dd25[R(941)](_0x399582,1),8)),_0x596a51.call(_0x3adcb3,2)<<16),nBuLtn[R(657)](_0x396c2c[R(941)](_0x157d74,3),24)),0),nBuLtn[R(1674)](nBuLtn[R(1280)](nBuLtn[R(1280)](_0x3b5095[R(941)](_0x5627f4,4),nBuLtn[R(657)](_0x251709[R(941)](_0x4d426b,5),8))|_0x3e71b4[R(941)](_0x4d1918,6)<<16,nBuLtn.gxGAc(_0x33b8b4[R(941)](_0x1828ea,7),24)),0),!0);p[R(902)+"jectStore"](d,{keyPath:f})}})})(),await this[n(1957)+n(1183)]}catch(d){console.log(d)}finally{this["_initPro"+n(1183)]=null}}}async[t(649)](n){let s=t,d={mqjQu:function(f,g,m){return f(g,m)},buOIF:e[s(1644)],CQPse:function(f,g){return e.HDdqR(f,g)}};if(e[s(715)]!==e[s(715)])if(_0x449eaa instanceof _0x20f38a){let f=_0x4a1411[s(884)][s(1037)](_0x2cbe13[s(702)+"et"],e[s(505)](_0x51a913[s(1192)+"th"],_0x2371a0[s(702)+"et"]));this._socket&&this[s(1232)][s(1708)]({data:f,fail:g=>{let m=s;this.emit("error",NXWpZq.mqjQu(_0x4ec0e8,NXWpZq[m(1085)],{message:this[m(1560)+m(1825)+m(638)](g)}))}})}else this._socket&&this[s(1232)].send({data:_0x24fc3f,fail:f=>{let g=s;this[g(1599)](g(1863),NXWpZq[g(991)](_0x5f598d,NXWpZq[g(1085)],{message:this["_formatErrorMess"+g(638)](f)}))}});else try{if(e[s(816)](s(1267),s(1267)))return await this[s(996)](),this[s(1894)]?.get(this[s(1414)],n);{let f=this[s(1894)].getItem(this[s(1512)]),g=_0xed6d70.parse(d[s(557)](f,"{}"));return _0x2b12a0[s(1608)](g)}}catch(f){console[s(1449)](f)}}async[t(1430)](n,s){let d=t,f={lpViu:function(g,m){return e[U(1586)](g,m)},EbtDQ:function(g,m){return e[U(1905)](g,m)},TXGvT:function(g,m){return g(m)},LuMVU:function(g,m){return e[U(1618)](g,m)},qHtcH:function(g,m){return e[U(1747)](g,m)}};if(e.seqjT(e[d(1415)],e.qedvn)){if(_0x418679<1||f[d(1154)](_0x5a42f4,_0x2626ec))return _0x14bb87(_0x3ae619);f[d(1540)](_0x46fb4d,_0x772263)>_0x5534c0&&(_0x48e8bd=f.TXGvT(_0x4b839,_0x1ade53),_0x84d88=0);let g=_0x21b347[d(941)](_0x60cf12,_0x5695c6,_0x107603+=_0x52a024);return f[d(974)](7,_0x533cc5)&&(_0x34f10a=f[d(1540)](f[d(1317)](7,_0x492727),1)),g}else return await this._init(),this[d(1894)]?.[d(1975)](this[d(1414)],n)}async[t(1578)](n){let s=t;try{return await this[s(996)](),this._qosDB?.[s(707)](this[s(1414)],n)}catch(d){if(e[s(1243)](e[s(1966)],e[s(504)]))console[s(1449)](d);else return!!this[s(1894)]}}async[t(748)](){let n=t;if(e[n(1032)]("qmpJs",e[n(562)]))try{return await this[n(996)](),this._qosDB?.[n(748)](this[n(1414)])}catch(s){console[n(1449)](s)}else this[n(762)+"s"]=_0x3a4a33,this[n(1951)+"es"]=_0x5d0a55,this[n(487)+n(1418)]=0,this[n(1487)+n(454)+n(747)+"t"]=0}async[t(1608)](){let n=t;return await this._init(),this[n(1894)]?.[n(479)+"ys"](this[n(1414)])}async[t(1001)](){let n=t;return await this[n(996)](),this[n(1894)]?.[n(1001)](this[n(1414)])}async[t(618)](){let n=t;try{this[n(1894)]?.[n(1528)](),this[n(1894)]=void 0}catch(s){console[n(1449)](s)}}get[t(1207)](){let n=t,s={ahsfU:function(d,f,g){return e[U(1910)](d,f,g)},EPqGz:e[n(851)],hAEDO:e.tqLHj,UnDST:function(d,f,g){return e[n(919)](d,f,g)},mjGiA:n(1610)+n(1105)+n(973)+n(1786)};try{if(e[n(1306)](e[n(1429)],e[n(1429)]))return!!this[n(1894)];if(this["_clearPi"+n(1885)](),this._clearTimer(),this[n(1880)+n(1034)+"rs"](),this["_wsInsta"+n(1774)](1e3,_0x5f55f8),this[n(1656)+"Lock"]=!1,_0x19142a&&this[n(1453)+n(1886)]()&&!this[n(1751)+"osed"]){if(this[n(1764)+n(1637)]?.[n(1144)+"chMaxTries"]()){let f=this[n(1764)+n(1637)]?.["getCurre"+n(1094)+"nt"]();this[n(684)+"hCloseEv"+n(1342)](s[n(937)](_0x2d88fa,s[n(1229)],{code:1006,reason:n(854)+f+(n(798)+", max retries reached"),wasClean:!0}))}else{let f=this[n(499)][n(718)+"tInterceptor"](_0x41dc83,_0x4eeff1);this[n(684)+n(917)+n(1342)](s[n(937)](_0x48daa5,n(1528),{code:_0x2ed780,reason:_0x33423c,wasClean:!0,willReconnect:f})),f&&this._connect()}return}this[n(1453)+n(1886)]()||this[n(1751)+"osed"]?this["_dispatc"+n(917)+n(1342)](s[n(937)](_0x361b27,s.EPqGz,{code:_0x28bc5d,reason:s[n(1312)]})):this[n(684)+"hCloseEv"+n(1342)](s[n(1906)](_0x3fdc14,s[n(1229)],{code:1006,reason:s.mjGiA})),this[n(459)]=null,this[n(1764)+n(1637)]?.["resetEnd"+n(989)+"fig"](),this[n(1463)+"sCounter"]?.[n(1003)+n(474)]()}catch(d){return console[n(1449)](d),!1}}}class Ep{constructor(n,s){let d=t;this[d(452)]=n,this._pathKey=s,this._qosDB=localStorage}async[t(882)](){}get[t(1512)](){return"frontier_"+this._DBName}async[t(649)](n){let s=t,d=this[s(1894)][s(776)](this[s(1512)]);return JSON[s(859)](e[s(1263)](d,"{}"))[n]}async[t(1430)](n,s){let d=t,f=this[d(1894)][d(776)](this._prefix),g=JSON.parse(e[d(568)](f,"{}"));return g[s||n[this[d(791)]]]=n,this._qosDB[d(517)](this._prefix,JSON[d(1862)+"y"](g)),s||n[this[d(791)]]}async[t(1578)](n){let s=t,d=this[s(1894)][s(776)](this[s(1512)]),f=JSON[s(859)](e.veJpz(d,"{}"));return f[n]=void 0,this[s(1894)][s(517)](this[s(1512)],JSON[s(1862)+"y"](f))}async[t(748)](){let n=t;return this[n(1894)][n(748)]()}async keys(){let n=t,s=this[n(1894)].getItem(this[n(1512)]),d=JSON[n(859)](s||"{}");return Object[n(1608)](d)}async[t(1001)](){let n=t,s=this._qosDB[n(776)](this._prefix),d=JSON[n(859)](e[n(1908)](s,"{}"));return Object[n(837)](d)}[t(618)](){return Promise[t(1626)]()}get[t(1207)](){return!!this._qosDB}}class vp{constructor(n,s){let d=t;this[d(452)]=n,this[d(791)]=s,this._qosDB=Rn?tt:Zr?wx:null}async[t(882)](){}get[t(1512)](){return"frontier_"+this[t(452)]}async[t(649)](n){let s=t,d=this[s(1894)][s(1107)+s(1699)](this[s(1512)]);return JSON[s(859)](d||"{}")[n]}async set(n,s){let d=t,f=this[d(1894)]["getStora"+d(1699)](this._prefix),g=JSON[d(859)](e[d(1261)](f,"{}"));return g[s||n[this[d(791)]]]=n,this[d(1894)][d(1242)+"geSync"](this._prefix,JSON[d(1862)+"y"](g)),s||n[this[d(791)]]}async[t(1578)](n){let s=t,d={McLHe:function(f,g){return e[U(1112)](f,g)},JoMOJ:function(f,g){return f===g},tpDmw:function(f,g){return e[U(1500)](f,g)},sWsXD:"store"};if(e[s(1384)](e[s(878)],e[s(878)])){let f=this[s(1894)][s(1107)+"geSync"](this[s(1512)]),g=JSON[s(859)](e[s(1009)](f,"{}"));return g[n]=void 0,this[s(1894)][s(1242)+s(1699)](this[s(1512)],JSON[s(1862)+"y"](g))}else return ycEOzM[s(1800)](_0x76fd18,_0x868d78)&&(ycEOzM.JoMOJ(_0x145bf4,s(621))||ycEOzM[s(1687)](_0x17827d,ycEOzM[s(1273)]))?!0:_0x56645c in _0x86e9bd}async[t(748)](){let n=t;return this[n(1894)]["clearSto"+n(1441)]()}async[t(1608)](){let n=t;if(e[n(1639)](e.WylEy,e[n(1251)])){let s=e[n(953)](_0x5a082f,_0x49d118,_0x4e08c3.limit),d=_0x2787f8[n(945)],f=_0x87bd0a.bytes;for(let g=0,m=_0x9b18e1[n(1659)];e[n(1772)](g,m);g++)d[e.njbku(g,s)]=f[g]}else{let s=this[n(1894)][n(1107)+n(601)+"nc"](this[n(1512)]),d=JSON[n(859)](e.PFSsR(s,"{}"));return Object[n(1608)](d)}}async[t(1001)](){let n=t,s={NImJK:function(d,f){return d|f},URxRB:function(d,f){return d>>f},OtVGl:function(d,f){return e[U(1716)](d,f)},kXtwq:function(d,f){return d|f},zrIvc:function(d,f){return e[U(1963)](d,f)}};if(e[n(1661)](e[n(705)],n(1439)))_0x645c5[_0xfe7235++]=fmRPVe[n(1726)](fmRPVe[n(1730)](_0x60975b,12),224),_0x18dbe9[_0xe7b6a6++]=fmRPVe[n(1411)](fmRPVe[n(1730)](_0x360de4,6)&63,128),_0xbbe8b2[_0x494469++]=fmRPVe[n(1188)](fmRPVe.zrIvc(63,_0x3372ed),128);else{let d=this[n(1894)][n(1107)+n(601)+"nc"](this[n(1512)]),f=JSON[n(859)](e[n(1097)](d,"{}"));return Object[n(837)](f)}}[t(618)](){return Promise.resolve()}get isReady(){return!!this[t(1894)]}}function sl(a,n){let s=t;if(e[s(1263)](Rn,Rn))return new vp(a,n);if(e[s(1263)](er,Jr)&&e.Aayhx(e[s(1633)],typeof indexedDB))return new bp(a,n);if((er||Jr)&&e[s(1516)](e[s(1633)],typeof localStorage))return new Ep(a,n);throw new Error(s(823)+s(1700)+"d")}class Sp{constructor(){let n=t,s={KouCu:function(d,f){return e[U(964)](d,f)}};if(e[n(1350)]!==n(801))return bxZJjr[n(1506)](_0x129e75,_0x255c26(_0x1884c3));this[n(1456)+n(1645)+"Id"]=null,this._interval=36e5,this[n(1894)]=e[n(651)](sl,n(1362),e[n(1012)])}async[t(1456)+t(830)](){let n=t,s={PigyN:"cursor_f"+n(958),OLnNt:e[n(1489)]};e[n(934)](n(949),e.XinRI)?(e.oSlnm(clearInterval,this[n(1456)+n(1645)+"Id"]),this[n(1456)+n(1645)+"Id"]=e[n(1931)](setInterval,()=>{let d=n;if(e[d(732)](e.CczJA,e[d(1793)]))this["flushExp"+d(581)]();else return{frameType:_0x8faeba,headers:[{key:s[d(660)],value:s[d(1289)]}],payload:void 0}},this[n(1456)+"l"])):this[n(1599)]("open",_0x418f5d("open",{..._0x45eb85,data:_0x5169e5[n(1650)]||""}))}async[t(882)](){let n=t;await this._qosDB.openDB()[n(1196)](()=>{let s=n;this[s(1456)+s(830)]()})}async[t(1701)+t(581)](){let n=t;(await this._qosDB?.getAll()||[])[n(987)](({timestamp:f})=>f<Date[n(720)]())[n(1399)](f=>{let g=n;this[g(1894)]?.[g(1578)](f[g(1869)+"id"])})}async[t(1578)](n){return this[t(1894)]?.del(n)}async[t(1430)](n,s){let d=t;if(e[d(1796)](e[d(843)],d(1831)))return this[d(1894)]?.set({message_id:n,timestamp:s});{let f=_0x44b164.offset;if(e[d(1519)](f+_0x435ec8,_0x524a7e.limit))throw new _0x42c3ce(e.crjZX);return _0x58e8e7[d(912)]+=_0x553d6e,f}}async[t(649)](n){let s=t;return this._qosDB?.[s(649)](n)}async[t(618)](){let n=t;e[n(569)](clearInterval,this["_interva"+n(1645)+"Id"]),await this[n(1894)]?.[n(618)]()}get isReady(){let n=t;if(e[n(1060)]!==e[n(1060)])try{return e[n(1240)](e[n(1222)],typeof _0x2d45e6)&&(e[n(1394)](_0x27a4a7,_0x3261b8)||_0x5c5dea.buffer&&e[n(1547)](_0x2f63fc[n(884)],_0x31f2da))||e[n(1126)](e[n(1222)],typeof _0x173108)?"":(_0x326306[n(859)](_0x170ea8),e[n(535)])}catch{return e[n(1332)](e.DMjhK,typeof _0x40627f)?e[n(1513)]:""}else return this[n(1894)]?.isReady}}function ua(a){let n=t,s={uYemM:function(d,f){return e[U(1126)](d,f)},kOryK:n(1239),znOeR:e[n(1693)]};if(e[n(1392)](e[n(1843)],"hiDCc")){let d=!!this[n(499)][n(1247)+"S"];if(!d)return{enabled:d,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let f=nn(a.message[n(692)],n(1068)+n(999),"2"),g=f&&nn(a.message[n(692)],e[n(1139)],"1"),m=f&&e.axuQM(nn,a[n(924)][n(692)],n(1068)+n(1775)+"k","1"),S=m?e[n(1186)](tr,a[n(924)].headers,e[n(611)])?.[n(698)](",").filter(Boolean)||[]:[];return{enabled:d,isQoSMessage:f,isQoSAck:g,isAckCleanupMessage:m,ackMsgIds:S}}else _0x25bea5.r=d=>{let f=n;sVeCxS[f(575)](f(455)+"d",typeof _0x447b28)&&_0x2faceb[f(1539)+"Tag"]&&_0x1c630d[f(1071)+f(1783)](d,_0x51d615[f(1539)+f(663)],{value:sVeCxS[f(1876)]}),_0x4e52cc[f(1071)+f(1783)](d,sVeCxS.znOeR,{value:!0})}}async function ol(){let a=t;return this[a(1435)+a(1935)]||(this[a(1435)+a(1935)]=new Sp),this[a(1435)+a(1935)][a(1207)]||await this[a(1435)+"ger"].openDB(),this[a(1435)+a(1935)]}async function Ip(a,n){let s=t;if(e.LBVct(s(1912),e[s(827)])){let d=e[s(1274)][s(698)]("|"),f=0;for(;;){switch(d[f++]){case"0":_0x56962e[_0x31987c++]=e[s(726)](e.tqXSM(_0x5a94a0>>6,63),128);continue;case"1":_0x53929f[_0x52a7ad++]=e.OIcdz(_0x2a0fc3>>12&63,128);continue;case"2":++_0x107e2c;continue;case"3":_0x1649f9[_0x4baf05++]=e[s(1917)](e[s(723)](_0x21ea39,18),240);continue;case"4":_0x50cb91[_0x47583b++]=e.DjpCo(e[s(734)](63,_0x1c5367),128);continue;case"5":_0x1e19cc=e.WVNQZ(65536+e[s(980)](e[s(1103)](1023,_0xb13ac1),10),e[s(463)](1023,_0x41720b));continue}break}}else{let{enableAutoAck:d}=this[s(499)],f=e[s(1807)](nn,a[s(924)][s(692)],e[s(1952)],"1"),g=e[s(1807)](nn,a.message[s(692)],s(1490),"1"),m=ua.call(this,a);if(e.hiZRa(d,f)){let{SeqID:S,LogID:p,service:R,LogIDNew:L,method:N}=a[s(924)];this[s(588)]({SeqID:S,LogID:p,LogIDNew:L,service:R,method:N,headers:[{key:e.SuTwV,value:"1"},{key:e[s(1202)],value:e[s(1263)](L,"")},{key:e.lRTtP,value:"0"}]})}g&&!m.isQoSAck&&this[s(684)+s(1465)+s(1383)](a),n()}}async function Ap(a,n){let s=t;this[s(633)]("received",a[s(924)]),n()}async function Tp(a,n){let s=t,d=e[s(1470)](Qt,await e[s(1082)](il,a[s(1841)]));try{if(d.payload instanceof Uint8Array){let f=e[s(1848)](this[s(499)][s(635)+s(1157)],Object)?{force:!!this._options[s(635)+"ncoding"][s(1102)],encoding:this[s(499)].payloadEncoding[s(1873)]?this[s(499)].payloadEncoding.encoding[s(1662)](/\s/g,"")[s(1588)+s(1692)]():""}:{force:!1,encoding:this[s(499)][s(635)+s(1157)]?this._options["payloadE"+s(1157)].replace(/\s/g,"")["toLowerC"+s(1692)]():""},g=d[s(635)+"ncoding"]?d[s(635)+s(1157)][s(1662)](/\s/g,"")[s(1588)+s(1692)]():"",m=e.DRoPT(this._options[s(1118)+s(1442)],Object)?{force:!!this[s(499)][s(1118)+s(1442)][s(1102)],type:this._options[s(1118)+s(1442)][s(544)]?this[s(499)]["payloadT"+s(1442)][s(544)][s(1662)](/\s/g,"")[s(1588)+s(1692)]():""}:{force:!1,type:this._options["payloadT"+s(1442)]?this[s(499)]["payloadT"+s(1442)][s(1662)](/\s/g,"")[s(1588)+s(1692)]():""},S=d[s(1118)+"ype"]?d[s(1118)+s(1442)][s(1662)](/\s/g,"")["toLowerC"+s(1692)]():"",p=m[s(1102)]?m[s(544)]:S||m[s(544)],R=f[s(1102)]?f[s(1873)]:g||f.encoding,L=[e[s(1513)],"applicat"+s(1617),e.CDTDg,e[s(1222)]],N=[s(469)+"e",e[s(915)]];this[s(499)][s(1117)+"ansformTextPayload"]&&L[s(1872)](p)&&(!R||N[s(1872)](R))?d["textPayl"+s(1937)]=e[s(1356)](rl,d[s(1258)],0,d[s(1258)][s(1192)+"th"]):d[s(1327)+s(1937)]=""}else d[s(1327)+"oad"]=""}catch(f){d[s(1327)+s(1937)]="",console[s(1449)](f)}a[s(924)]=d,e[s(1573)](n)}function Cp(a,n,s){let d=t,f={YMOsu:function(R,L){return R>L},pFMPd:function(R,L){return e.AoZZy(R,L)},xHHHy:function(R,L){return e[U(1390)](R,L)},nHQFn:function(R,L){return e[U(1372)](R,L)},GWkcz:function(R,L){return e[U(1360)](R,L)},FMvEG:function(R,L){return e.pHblm(R,L)}},g=s||8192,m=e[d(1651)](g,1),S=null,p=g;return function(R){let L=d;if(R<1||f[L(1074)](R,m))return a(R);f[L(1074)](f[L(1978)](p,R),g)&&(S=f.xHHHy(a,g),p=0);let N=n[L(941)](S,p,p+=R);return f[L(1401)](7,p)&&(p=f[L(768)](f[L(1143)](7,p),1)),N}}let Rp=4294967295;function kp(a,n,s){let d=t;return e.PHDSw(RangeError,e.Aneih(e[d(1902)](e[d(1878)](e[d(1808)](e[d(1114)],a),e[d(1347)]),n||1),d(893))+s)}function Pp(a,n,s){let d=t;if(e.KsgoG(s,Rp))throw new Error(e[d(1221)]);let f=3;for(;e[d(1256)](f,0);){let g=e[d(1305)](255,s);e[d(1426)](xa,g,a,e.FMkjl(n,f)),s>>>=8,f--}return e[d(1902)](n,4)}function Dp(a,n){let s=t,d=0,f=n,g=e[s(875)](n,4);for(;e[s(1397)](f,g);){let{value:m,offset:S}=e.JeEsH(fa,a,f);f=S,d=e[s(1916)](e[s(1877)](d,8),0),d+=m}return{value:d,offset:g}}function Op(a,n,s){let d=t;return a?e[d(1949)](a.length,40)?e[d(1482)](e[d(1116)](da,a,n,s),s):n[d(1853)+"e"]?e[d(1531)](n.utf8Write(a,s),s):n.write?e[d(1303)](n.write(a,s),s):e[d(1846)](da,a,n,s)+s:s}function Lp(a,n){let s=t,d=new fe(e[s(887)](e[s(704)](e.BwkXx(e[s(819)](a[e.EcIbN(n,4)],24),e[s(1657)](a[e.oHURS(n,5)],16)),e[s(1413)](a[n+6],8)),a[n+7]),e[s(840)](e[s(792)](e[s(1932)](e[s(1351)](a[n+0],24),e[s(1686)](a[e.wIYKF(n,1)],16)),a[e[s(1565)](n,2)]<<8),a[e[s(1819)](n,3)]),!0);return n+=8,{value:d,offset:e[s(1902)](n,8)}}function Np(a,n,s){let d=t,f=a[d(1529)],g=a[d(572)];return n[s]=e[d(1871)](g,24),n[e.Aagkj(s,1)]=e[d(1676)](e.eHDTV(g,16),255),n[e[d(1549)](s,2)]=e.JtHur(g>>>8,255),n[e[d(1556)](s,3)]=e[d(1174)](255,g),n[e[d(1172)](s,4)]=e.wWTBB(f,24),n[e.MSQxe(s,5)]=e[d(571)](f>>>16,255),n[e[d(852)](s,6)]=e[d(1968)](e[d(1402)](f,8),255),n[s+7]=e[d(463)](255,f),s+=8,s}function fa(a,n){let s=t;return a[s(1576)+"8"]?{value:a[s(1576)+"8"](n),offset:e[s(1878)](n,1)}:{value:e[s(1025)](255,a[n]),offset:n+1}}function xa(a,n,s){let d=t;return n[d(672)+"t8"]?n[d(672)+"t8"](a,s):n[s]=e[d(1806)](255,a),e[d(478)](s,1)}let Mp=function(a){return new Uint8Array(a)},Bp=e[t(556)](e[t(1633)],typeof Buffer)?Buffer[t(1055)+"afe"]:Cp(Mp,Uint8Array[t(1517)+"e"][t(1913)]);(()=>{let a=t,n={bgooM:e[a(1698)],MUkNa:function(d,f){return e[a(507)](d,f)},GKSWH:function(d,f){return d|f},sVdxv:function(d,f){return e[a(1911)](d,f)},pdkbd:function(d,f){return e[a(1676)](d,f)},xnEEv:function(d,f){return e[a(1451)](d,f)},ncWma:function(d,f,g,m){return d(f,g,m)},AMUuz:function(d,f){return e[a(1949)](d,f)},ZYdkq:function(d,f){return e[a(729)](d,f)},uYbvM:function(d,f){return d<f},HKNQy:function(d,f){return e[a(729)](d,f)},SCzrI:function(d,f){return e[a(1338)](d,f)},OiSkz:function(d,f){return d&f},ybWli:function(d,f){return d|f},NZoPu:function(d,f){return e[a(955)](d,f)},WUTFd:function(d,f){return d|f}},s=4294967295;return function(d,f,g=!0){let m=a,S=n[m(653)].split("|"),p=0;for(;;){switch(S[p++]){case"0":s=n[m(883)](n[m(842)](s,n[m(988)](n[m(1485)](15,d[f]),28)),0);continue;case"1":if(n[m(800)](f+=5,d[m(1092)]))throw f=d[m(1092)],n.ncWma(kp,f,10,d[m(1092)]);continue;case"2":if(n[m(1961)](d[f++],128))return{value:g?s:n[m(1176)](0,s),offset:f};continue;case"3":if(n[m(1961)](d[f++],128))return{value:g?s:n[m(842)](0,s),offset:f};continue;case"4":if(n[m(1866)](d[f++],128))return{value:g?s:n[m(842)](0,s),offset:f};continue;case"5":if(n[m(1961)](d[f++],128))return{value:g?s:n[m(1176)](0,s),offset:f};continue;case"6":return{value:g?s:n[m(1176)](0,s),offset:f};case"7":s=n.HKNQy(s,n[m(1485)](127,d[f])<<7)>>>0;continue;case"8":s=n[m(883)](n[m(1569)](127,d[f]),0);continue;case"9":s=n[m(883)](s|n[m(988)](n[m(566)](127,d[f]),14),0);continue;case"10":s=n[m(1795)](s,n.NZoPu(n[m(1569)](127,d[f]),21))>>>0;continue;case"11":if(n.AMUuz(d[f++],128))return{value:g?s:n[m(1184)](0,s),offset:f};continue}break}}})();let Fp=16,ha=32;function zp(a){let n=t,s=0,d={};for(let f=0;f<a[n(1092)];f++)if(e[n(1373)](e[n(1566)],n(563)))d[a[f]["cursor_n"+n(1282)]]=e[n(1082)](nl,a[f][n(904)+n(1282)]),s+=e[n(875)](14,d[a[f][n(904)+n(1282)]]);else return this[n(459)]?this._ws[n(1044)+"pe"]:this[n(1778)+n(1442)];return[s,d]}function al(a,n,s){let d=t,f={zVWwy:function(R,L,N,F){return e.SDEdJ(R,L,N,F)},bsNYp:e[d(1165)],cAqUj:d(789),fkrPE:e.FTRzL,yxOYu:d(1341)},[g,m]=zp(a),S=e[d(554)](Bp,g),p=0;return a[d(1399)](R=>{let L=d,N=("7|3|2|5|"+L(1284)+L(1292))[L(698)]("|"),F=0;for(;;){switch(N[F++]){case"0":p=f[L(669)](Np,fe[L(1216)+"er"](R[L(997)]||n),S,p);continue;case"1":p=f[L(669)](Op,R[L(904)+"ame"],S,p);continue;case"2":console.log(f[L(1498)],p);continue;case"3":p=f[L(669)](xa,0,S,p);continue;case"4":console[L(1449)](f[L(1527)],p);continue;case"5":p=f[L(669)](Pp,S,p,R[L(1444)]||0);continue;case"6":console.log(f[L(1437)],p);continue;case"7":console[L(1449)](L(695)+"ervice",R,R[L(1444)]);continue;case"8":p=f.zVWwy(xa,m[R[L(904)+L(1282)]],S,p);continue;case"9":console[L(1449)](f[L(1717)],p);continue;case"10":console[L(1449)](L(1444),p);continue}break}}),{frameType:ha,headers:[{key:e[d(1006)],value:s}],payload:S}}function Up(a){let n=t,s=0,d=[];for(;e[n(1370)](s,a[n(1192)+"th"]);)if(e[n(1663)](e.eIbzz,e[n(1248)])){let{offset:f}=e.NSmxZ(fa,a,s);s=f;let g={cursor_name:"",cursor:0,service:0},{value:m,offset:S}=e[n(1349)](Dp,a,s);g.service=m,s=S;let{value:p,offset:R}=e.vaAbD(fa,a,s);s=R,g[n(904)+n(1282)]=e[n(577)](rl,a,s,e[n(1140)](s,p)),s+=p;let{value:L,offset:N}=e[n(622)](Lp,a,s);g[n(997)]=L[n(1445)](),s=N,d[n(539)](g)}else this[n(1599)](e[n(528)],_0x10671f),this[n(1784)+"e"]&&this[n(1784)+"e"](_0x22ed98);return d}function Hp(){let a=t;return{frameType:ha,headers:[{key:e[a(1006)],value:e[a(1489)]}],payload:void 0}}class Gp{constructor(n,s,d){let f=t;this[f(1434)+"ameSpace"]=n,this[f(724)+"ileName"]=s,this[f(767)+"Strategy"]=d,this[f(1894)]=sl(this[f(1434)+f(1488)],f(904)+f(1282))}async[t(882)](){await this[t(1894)].openDB()}async[t(458)+"rs"](){let n=t;if(!this._qosDB[n(1207)])return;let s=this[n(767)+n(1077)],d=await this[n(1894)][n(1001)]();switch(console[n(1449)](e[n(1137)],d),s){case e.ozoCK:return d&&d.length?al(d,0,this[n(724)+n(1943)]):void 0;case"INSTANT":return;case n(769):return d&&d.length?e.Nrxxg(al,d,0,this[n(724)+n(1943)]):e[n(1573)](Hp)}}async[t(1430)](n,s,d){let f=t;if(e.eAwdT(e[f(1824)],f(1845)))this[f(1026)+"er"]&&_0x50fc4f[f(814)+"entListe"+f(1062)](e[f(1443)],this._handlePageHide),this[f(1026)+"er"]&&_0x627aed["removeEv"+f(870)+f(1062)](e[f(683)],this["_handleP"+f(1063)]),this[f(1528)]();else return console[f(1449)](e[f(1623)],n,s,d),this._qosDB[f(1430)]({cursor_name:n,cursor:s,service:d})}async[t(530)+"rs"](n){let s=t,d=e[s(832)](Up,n);for(let f of d)console[s(1449)](e[s(1011)],d),await this[s(1894)][s(1430)](f)}async[t(649)](n){let s=t;return(await this[s(1894)][s(649)](n))?.[s(997)]}async closeDB(){let n=t;await this[n(1894)][n(618)]()}[t(933)+"rsorFile"+t(1039)](n){this._cursorFileName=n}get[t(1207)](){let n=t,s={IyfaT:function(d,f,g){return e[U(972)](d,f,g)}};if(e[n(757)](e[n(894)],e[n(894)]))return this[n(1894)][n(1207)];_0x2eaa90(_0x16d7be,18),IvZIWj.IyfaT(_0x38d04a,_0x10ee20,_0x726419)}}let qp=e.QKJLe;async function cl(a){let n=t;if(!this[n(499)].enableQoS)return null;let{aID:s,fpID:d,messageStrategy:f}=this[n(499)],g=e[n(1376)](a,qp);try{return this._cursorManager?a&&this[n(951)+n(713)][n(933)+"rsorFile"+n(1039)](a):this["_cursorM"+n(713)]=new Gp(d+"_"+s+"_"+g,g,f),this[n(951)+n(713)][n(1207)]||await this[n(951)+n(713)][n(882)](),this._cursorManager}catch{return null}}async function jp(a,n){let s=t,d=e[s(1604)](nn,a.message[s(692)],s(485),"-1"),f=e.amtTN(nn,a.message[s(692)],e.SuTwV,"1"),g=e.DxOMd(tr,a.message[s(692)],e.TNCdF),m=Number(e[s(1563)](tr,a[s(924)][s(692)],e[s(1122)]))||0,S=ua.call(this,a),p=e[s(1323)](nn,a[s(924)][s(692)],e.tNkdG,"2"),R=e.HNqdn(tr,a.message[s(692)],e.bKjbu),L=e.oSlnm(Number,tr(a[s(924)][s(692)],e.RYRcQ));if(S[s(1648)])return e.DetqB(n);let N=S[s(1096)+"sage"]?await ol.call(this):null;if(e[s(966)](a[s(924)].service,0)&&f&&!d||e[s(1572)](a[s(924)][s(1444)],0)){if(g&&S["isQoSMes"+s(1460)]&&N)return!!!await N[s(649)](g)&&(this["_dispatc"+s(1638)+s(853)](a),await N[s(1430)](g,e.XuWzd(Date.now(),m))),e[s(1573)](n);if(p)if(e[s(1796)](e[s(1647)],e.mlkXd)){let F=await cl.call(this);if(!F)return this[s(684)+s(1638)+s(853)](a),e[s(1573)](n);let $=await F.get(R)??-1;if(e.SiuXY($,L))this["_dispatchMessage"+s(853)](a),F.set(R,L,a.message[s(1444)]);else throw new Error(s(1571)+" message"+s(1668)+L+(" larger than loc"+s(1375)+"r ")+$);return n()}else{let F=this[s(572)],$=this[s(1529)];return[255&$,e.nQvmX(e.eHDTV($,8),255),e[s(1106)](e[s(874)]($,16),255),e[s(982)]($,24),255&F,e[s(1059)](e.FrTNU(F,8),255),e.lfhwd(F,16)&255,F>>>24]}return this[s(684)+s(1638)+s(853)](a),e.UuDxO(n)}}async function Wp(a,n){let s=t,d=ua[s(941)](this,a);if(!d[s(1096)+"sage"])return n();let f=await ol[s(941)](this);if(d[s(1403)+s(1195)+s(638)]&&d.ackMsgIds.length)for(let g of d.ackMsgIds)await f[s(1578)](g);e[s(1178)](n)}async function Kp(a,n){let s=t;if(s(1738)===e.kFoOp){let d=e.kKCSx(a[s(924)][s(1827)+"e"],Fp),f=e[s(1847)](a[s(924)][s(1827)+"e"],ha);if(e.hiZRa(!d,!f))return e[s(1739)](n);let g=tr(a[s(924)][s(692)],e[s(1006)]);if(!g)return e.gPcto(n);let m=await cl[s(941)](this,g);if(!m)return n();if(d){let S=await m[s(458)+"rs"](),p={frameType:S?.[s(1827)+"e"],SeqID:fe[s(1216)+"er"](this._seqId++),LogID:fe.fromNumber(this[s(499)][s(1865)+s(1884)]()),service:9e3,method:5,headers:S?.[s(692)],payload:S?.[s(1258)]},R=e[s(1558)](v,p);this[s(459)]&&this[s(459)].readyState&&this[s(459)].send(R)}if(f){let S=a[s(924)][s(1258)];S&&m[s(530)+"rs"](S)}}else _0x253eec[s(1283)]=_0x4f5de9.resolve()[s(1196)](()=>(_0x481084(),_0x95c05e))[s(1196)](function(d){return d})}let $p=async function(a,n){let s=t;this[s(1316)]=!1,e[s(1390)](clearTimeout,this[s(1656)+s(1021)+s(775)]),e.DetqB(n)},Vp=async function(a,n){let s=t,d={UEVLo:function(m,S){return e[U(1892)](m,S)},hiFZQ:function(m,S){return e[U(608)](m,S)},GVjCm:function(m,S){return e[U(542)](m,S)}};if(!this._ws||e[s(1661)](this[s(459)][s(1270)+"te"],this[s(1109)]))return n();let{pingInterval:f}=this[s(499)];this["_endpoin"+s(1637)]?.[s(1763)+s(989)+"fig"]();for(let m=0;e[s(1655)](m,this[s(767)+s(620)].length);m++)if(e[s(1551)](e[s(1389)],e.QOkKr)){let S=this[s(767)+s(620)][m];if(this[s(459)][s(1270)+"te"]===this.OPEN&&e.cocmh(null,S))this[s(459)]&&this[s(459)][s(1708)](S),this[s(767)+s(620)][m]=null;else break}else return!!(mRXZpK[s(1640)](this[s(487)+s(1418)],this[s(762)+"s"][s(1092)])||mRXZpK.hiFZQ(this[s(487)+s(1418)],mRXZpK[s(1209)](this[s(762)+"s"][s(1092)],1))&&this[s(1487)+s(454)+s(747)+"t"]===this[s(1951)+"es"]);this["_message"+s(620)]=this[s(767)+"Queue"][s(987)](m=>!!m),this["_pingPon"+s(605)+"Id"]=e[s(1288)](setTimeout,()=>this[s(867)](),f),this[s(684)+s(971)+"nt"](a),this[s(1026)+"er"]&&this[s(459)]&&(this[s(459)].binaryType=this["_binaryT"+s(1442)]);let g=this[s(1764)+s(1637)]?.["getCurre"+s(1094)+"nt"]();this[s(633)](s(1821)+g+" success"),n()},Zp=async function(a,n){let s=t,d=this[s(1764)+s(1637)]?.getCurrentEndpoint();this[s(633)](s(1821)+d),e.PievU(n)};class Jp extends ca{constructor(n){let s=t,d={rulJa:function(f,g){return e.Qszve(f,g)},YghOZ:e[s(1222)],vOAMJ:function(f,g){return f instanceof g},Kfvmw:e.itMcs,HOjuL:s(789),CgSYm:function(f,g,m,S){return e.kadXx(f,g,m,S)},tnCvv:e.ZwWUa,OUYuR:function(f,g,m){return e[s(1036)](f,g,m)},LMQXe:function(f,g){return e[s(1324)](f,g)},iHCwD:e[s(1428)],oNzKC:e[s(851)],YNZmx:e[s(1810)],jHRRc:function(f,g,m){return e[s(1870)](f,g,m)},rhfFR:e.SQijK,bDNoy:function(f,g){return e.WHgmI(f,g)}};if(e.pHuYr(e[s(888)],e[s(779)]))this._intervalTimeoutId=null,this[s(1456)+"l"]=36e5,this[s(1894)]=e[s(1823)](_0x3a01bc,s(1362),e[s(1012)]);else{super(),this[s(585)+s(950)+s(1695)]=!0,this._isBrowser=er,this[s(1973)]=fp,this[s(1260)+"T"]=Rn,this[s(1537)+"X"]=Zr,this._isWorker=Jr,this[s(767)+"Queue"]=[],this._endpointManager=null,this["_readyCl"+s(567)]=!1,this[s(1778)+"ype"]=e[s(480)],this["_connect"+s(880)]=!1,this[s(1656)+s(1021)+s(775)]=null,this[s(1724)+s(1757)+s(926)]=null,this._pingPongTimeoutId=null,this[s(1271)]=0,this[s(1316)]=!1,this._url="",this[s(1435)+s(1935)]=null,this[s(951)+s(713)]=null,this[s(1463)+"sCounter"]=null,this._protocols="pbbp2",this.CLOSED=3,this[s(737)+"NG"]=0,this[s(1109)]=1,this[s(890)]=2,this[s(1018)]=S=>{let p=s;try{e[p(1051)]!==e[p(1051)]?(this[p(1453)+p(1886)]()&&(!this._ws||this._ws.readyState!==this[p(1109)]||d[p(1901)](this._ws[p(1270)+"te"],this[p(737)+"NG"]))&&this[p(668)+"nLine"](),this[p(1026)+"er"]&&_0x17bdc1[p(1597)+p(1574)](p(1467),this["_handleO"+p(1093)]),this._isBrowser&&_0x4a2a88[p(1597)+p(1574)](p(876),this[p(668)+p(1613)])):e[p(1116)](tl,this,S,[$p,Vp,Zp])}catch(R){let L=ot(p(1863),{message:R[p(924)],code:tn.OPEN_ERROR,error:R});this[p(684)+p(625)+p(1342)](L)}},this[s(644)+"ge"]=async S=>{let p=s,{pingInterval:R,pingFrequency:L}=this[p(499)];if((e.AHpTb("hi",S[p(1841)])&&e[p(1954)](e[p(1091)],L)||e[p(1391)](e[p(476)],L))&&(this["_clearPi"+p(1885)](),this[p(1599)](e[p(1125)],"success"),this[p(693)+p(605)+"Id"]=setTimeout(this._ping[p(1252)](this),R)),!e.VQmWp("hi",S[p(1841)]))try{e.cjrfv(tl,this,S,[Tp,Ip,Wp,Kp,jp,Ap])}catch(N){let F=e[p(923)](ot,e.SQijK,{message:N.message,code:tn[p(1712)+p(1606)],error:N});this[p(684)+p(625)+p(1342)](F)}},this[s(584)]=S=>{let p=s,R=this[p(1764)+p(1637)]?.checkReachMaxTries(),L=this[p(1764)+p(1637)]?.[p(1022)+p(1094)+"nt"]();if(R&&!S.message){let N="connect "+L+(" fail, max retri"+p(751)+"ed");this[p(684)+p(625)+p(1342)](e[p(1654)](ot,e.SQijK,{message:N,code:tn[p(1619)+p(1111)+"R"],error:S}));return}this[p(459)]&&e[p(716)](this[p(459)].readyState,this[p(1109)])&&this[p(1625)+p(833)](),this[p(684)+p(625)+p(1342)](ot(e[p(1644)],{message:S.message,code:tn.NATIVE_ERROR,error:S}))},this[s(1839)]=async S=>{let p=s,R={Fszoh:function(N,F){return N==F},FcJWC:d[p(1533)],zvrAs:function(N,F){return N(F)},EWsKW:function(N,F){return d[p(1928)](N,F)},ZhsSu:d[p(1864)],QnguV:p(1341),PMieb:function(N,F,$,X){return N(F,$,X)},gcmgh:p(1459)+p(789),iMdhW:p(1444),AqrGW:d[p(1197)],SDcVr:function(N,F,$,X){return d[p(1575)](N,F,$,X)},lVsGx:d.tnCvv};this._clearTimer(),this[p(1812)+"ngTimer"](),this[p(1880)+"sListeners"](),this._ws=null,this[p(1656)+p(880)]=!1;let L=this._endpointManager?.["checkRea"+p(1535)+"es"]();if(!L&&this[p(1453)+p(1886)]()&&!this[p(1751)+"osed"]){let N=this[p(1764)+p(1637)]?.["getCurre"+p(1094)+"nt"](),F=this[p(499)][p(718)+p(1946)+p(1915)](S[p(485)],S.reason);this[p(684)+"hCloseEv"+p(1342)](d[p(1594)](ht,p(1528),{code:1006,reason:S[p(1179)]||"connecti"+p(1182)+p(1311)+"wn reaso"+p(1555)+"ame: "+N,willReconnect:F})),F&&this[p(1656)]();return}if(d.LMQXe(1e3,S[p(485)])&&this[p(1751)+p(567)])if(d[p(1212)]!==d[p(1212)]){if(xHpCeQ[p(1409)](xHpCeQ[p(1121)],typeof _0x56f34f)){let N=new _0x56c5f1(xHpCeQ[p(508)](_0x1ed6ae,_0xa7d5d0));return _0x39b083(_0x4fac3d,N,0),N}return xHpCeQ[p(509)](_0x39c7d5,_0x5b92ac)?new _0x44df30(_0xf1d314):new _0x4317a0(_0x1b98c4[p(884)],_0x5d2341[p(702)+"et"],_0x4a4c9e.byteLength)}else{this["_dispatc"+p(917)+"ent"](d[p(1594)](ht,d.oNzKC,{code:1e3,reason:p(914)})),this["_endpoin"+p(1637)]?.[p(1763)+p(989)+p(1673)](),this._pingLossCounter?.[p(1003)+"nter"]();return}if(S[p(485)]!==1e3&&L)if(d.rulJa(d.YNZmx,d[p(907)])){let N=R[p(1177)][p(698)]("|"),F=0;for(;;){switch(N[F++]){case"0":_0x350a53.log(xHpCeQ.QnguV,_0xef469b);continue;case"1":_0x10b1b9=xHpCeQ[p(598)](_0x5b156e,_0x17c6a4,_0x235432,_0x4ecd36[p(1444)]||0);continue;case"2":_0x36b33c=xHpCeQ[p(598)](_0x31b5ea,_0x532f09[_0x265c93.cursor_name],_0x3e30a6,_0x49442c);continue;case"3":_0xfc554b[p(1449)](xHpCeQ[p(903)],_0xfe6d9c);continue;case"4":_0xd22178[p(1449)](xHpCeQ.iMdhW,_0x1478f8);continue;case"5":_0x161906=_0x16a67c(0,_0x5ced0b,_0x4843dc);continue;case"6":_0x5cb80c=xHpCeQ[p(598)](_0x231996,_0x11accc[p(1216)+"er"](_0x1e5bbc[p(997)]||_0x5df998),_0xf008bb,_0x490af2);continue;case"7":_0x27e48e[p(1449)](p(695)+"ervice",_0x44bc20,_0xc75d23[p(1444)]);continue;case"8":_0x38bf6b[p(1449)](xHpCeQ.AqrGW,_0x3b7d48);continue;case"9":_0x2d787c=xHpCeQ[p(1083)](_0x78b43c,_0xa2408f[p(904)+p(1282)],_0xabc785,_0x5a272);continue;case"10":_0x56083[p(1449)](xHpCeQ.lVsGx,_0x2467de);continue}break}}else{let N=this["_endpoin"+p(1637)]?.["getCurre"+p(1094)+"nt"](),F=S[p(1179)];F||(F=await _p(this[p(1458)])),F=p(1936)+p(1182)+p(1016)+F+(", hostna"+p(725))+N+(p(1422)+p(753)+p(1e3)),this[p(684)+p(917)+"ent"](d[p(1737)](ht,d[p(656)],{code:S[p(485)],reason:F}));let $="connect "+N+(" fail, m"+p(788)+"es reached");this[p(684)+"hErrorEvent"](d[p(1737)](ot,d.rhfFR,{message:$,code:tn[p(1619)+p(1111)+"R"]})),this[p(1764)+p(1637)]?.[p(1763)+p(989)+p(1673)](),this[p(1463)+p(1760)]?.["resetCou"+p(474)]();return}if(d[p(1802)](1e3,S[p(485)])&&!S[p(1179)]){let N=this[p(1764)+p(1637)]?.[p(1022)+p(1094)+"nt"]();this["_dispatc"+p(917)+p(1342)](d[p(1594)](ht,p(1528),{code:S[p(485)],reason:p(1936)+p(1182)+p(1311)+"wn reason, hostn"+p(1792)+N})),this[p(1764)+p(1637)]?.[p(1763)+p(989)+"fig"](),this[p(1463)+p(1760)]?.[p(1003)+p(474)]();return}this[p(684)+p(917)+p(1342)](S),this[p(1764)+"tManager"]?.[p(1763)+p(989)+p(1673)](),this[p(1463)+p(1760)]?.[p(1003)+p(474)]()},this[s(1830)]=null,this[s(690)]=null,this.onmessage=null,this[s(1047)]=null,this["onStartR"+s(920)]=null,this[s(665)+s(1781)]=null,this[s(524)+s(730)+"yReconnect"]=null,this[s(668)+s(1093)]=this["_handleO"+s(1093)][s(1252)](this),this[s(668)+s(1613)]=this[s(668)+s(1613)][s(1252)](this),this[s(711)+s(1238)]=this[s(711)+s(1238)][s(1252)](this),this[s(711)+s(1063)]=this[s(711)+s(1063)].bind(this),this[s(499)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e.PaMGd(1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e.bIIuw,pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:s(769),env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:f,ws:g}=n,m=Array[s(1620)](f)?f:e[s(1170)](e[s(1222)],typeof f)?[f]:[];if(!m||m.length===0)throw new Error(e[s(1265)]);if(!pp(g))throw new Error(e[s(646)]);Object[s(1333)](this[s(499)],n),this[s(1764)+"tManager"]=new el(m,this[s(499)][s(1951)+"es"]),this[s(1463)+"sCounter"]=new wp(this._options[s(995)+s(1683)]),this[s(499)][s(749)+s(815)]&&(this[s(1316)]=!0,this[s(1656)]()),this[s(499)].listenNetworkChanged&&(this[s(1260)+"T"]||this[s(1537)+"X"]?this[s(1790)+s(512)+s(614)]():this._isBrowser&&this["_initGlo"+s(1523)+s(1574)]())}}[t(668)+t(1093)](){let n=t;this[n(499)][n(1171)+n(1477)+n(1357)]||this[n(1751)+n(567)]||this[n(1226)+n(920)]()}[t(668)+t(1613)](){let n=t;this[n(1194)+n(1208)+"t"]();let s=e[n(1493)](aa,e[n(862)],{message:n(873)+n(1788)+n(841)+"ct"});this[n(524)+"mediatel"+n(1671)+"ct"]&&this[n(524)+n(730)+"yReconnect"](s)}[t(1694)+t(1523)+t(1574)](){let n=t,s={lZzCI:function(d){return e[U(1142)](d)},wKpzY:function(d,f,g){return e[U(1563)](d,f,g)}};if(e.miorj===e[n(1836)])this[n(1026)+"er"]&&window[n(1597)+n(1574)](e[n(1791)],this[n(668)+n(1093)]),this._isBrowser&&window[n(1597)+n(1574)](e[n(755)],this[n(668)+n(1613)]),this[n(1026)+"er"]&&window[n(1597)+n(1574)](e[n(1443)],this[n(711)+n(1238)]),this[n(1026)+"er"]&&window["addEvent"+n(1574)](e[n(683)],this[n(711)+n(1063)]);else{let d=QaDoot[n(1970)](_0x516e8d);return QaDoot.wKpzY(_0x10b75d,_0x739803,d),_0x59266c(d)}}[t(1696)+t(1523)+"Listener"](){let n=t;this[n(1026)+"er"]&&window[n(814)+n(870)+n(1062)](n(1467),this[n(668)+n(1093)]),this[n(1026)+"er"]&&window[n(814)+n(870)+n(1062)](e[n(755)],this[n(668)+"ffLine"]),this._isBrowser&&window[n(814)+n(870)+n(1062)](e[n(1443)],this["_handleP"+n(1238)]),this[n(1026)+"er"]&&window["removeEv"+n(870)+n(1062)](e.swYYi,this[n(711)+n(1063)])}[t(711)+"ageHide"](n){let s=t,d={ijGGg:function(f,g){return e.SBehQ(f,g)},WMTJr:function(f,g){return e[U(1318)](f,g)},cLRPl:s(1770),JhRGP:e.bIIuw,QBkFR:e[s(1125)],BOInr:e[s(872)],jswsI:function(f,g,m){return e[s(651)](f,g,m)},hzCiU:function(f,g){return e[s(1211)](f,g)},CoPCd:function(f,g,m,S){return e[s(1426)](f,g,m,S)},pvKqC:function(f,g,m){return e[s(1976)](f,g,m)},tyZxS:s(1863)};if(e[s(1057)](s(1340),e[s(609)])){let{pingInterval:f,pingFrequency:g}=this[s(499)];if((pLByNw[s(1898)]("hi",_0x1155a4.data)&&pLByNw[s(1041)](pLByNw[s(1254)],g)||pLByNw[s(1898)](pLByNw[s(1315)],g))&&(this[s(1812)+s(1885)](),this[s(1599)](pLByNw[s(1379)],pLByNw[s(1354)]),this["_pingPon"+s(605)+"Id"]=pLByNw[s(839)](_0x72db98,this[s(867)][s(1252)](this),f)),pLByNw.hzCiU("hi",_0x3ed53d.data))return;try{pLByNw[s(1688)](_0xc93f6e,this,_0x589d40,[_0x1811cc,_0x501201,_0x313e9a,_0x4bdce5,_0x58da4,_0x4e6f84])}catch(m){let S=pLByNw[s(826)](_0x4c8b82,pLByNw[s(1469)],{message:m[s(924)],code:_0x269aac["MESSAGE_"+s(1606)],error:m});this[s(684)+s(625)+s(1342)](S)}}else!n[s(913)+"d"]&&(this._isBrowser&&window[s(814)+"entListener"]("pagehide",this[s(711)+s(1238)]),this[s(1026)+"er"]&&window["removeEventListe"+s(1062)](e[s(683)],this._handlePageShow),this[s(1528)]()),this[s(1026)+"er"]&&window["removeEv"+s(870)+s(1062)]("online",this["_handleO"+s(1093)]),this[s(1026)+"er"]&&window[s(814)+s(870)+"ner"](e[s(755)],this[s(668)+s(1613)])}[t(711)+t(1063)](n){let s=t;if(e[s(1278)](e[s(978)],"FbUSt")){let{type:d}=_0x3cc804;this[s(1599)](d,_0x3c413)}else n[s(913)+"d"]&&(this[s(1453)+s(1886)]()&&(!this[s(459)]||e.LzPpH(this[s(459)][s(1270)+"te"],this.OPEN)||this._ws.readyState!==this[s(737)+"NG"])&&this[s(668)+"nLine"](),this[s(1026)+"er"]&&window["addEvent"+s(1574)](e[s(1791)],this[s(668)+s(1093)]),this[s(1026)+"er"]&&window["addEvent"+s(1574)](e.WcrQB,this["_handleO"+s(1613)]))}async[t(1407)+t(1344)](n){let s=t,{fpID:d,deviceID:f,bddID:g,ttwID:m,accessKey:S,aID:p,customParams:R={},enableAutoAck:L,enableQoS:N,QoSLevel:F,env:$}=this[s(499)],X,at,ct;this[s(1026)+"er"]||this[s(1537)+"X"]||this._isMiniTT?(X=location&&e[s(1332)](e[s(818)],location[s(946)])?s(1801):e[s(782)],at=n[s(1662)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),ct=/^wss(.*:\/\/)/[s(1611)](n)?n:""+X+at):(X=e.eNEeU,at=n[s(1662)](/(^http)((?:[s]*:\/\/))/,""),ct=/(^ws)((?:[s]*:\/\/))/[s(1611)](at)?at:""+X+at);let Ze=g?e.qmUPu:m?e[s(891)]:e[s(1160)],pa=g||m||f;if(!pa||!Ze)throw new Error(e[s(1842)]);let Yp=e[s(1170)](e[s(935)],typeof R)?await R():R,Xp=$?e[s(694)](mp,$[s(1680)],$.xTTEnv):{},ga=Object[s(1333)]({device_platform:e[s(1473)],version_code:e[s(1404)],access_key:S,fpid:d,aid:p,[Ze]:pa,xsack:L?1:0,xaack:L?1:0,xsqos:N?1:0,qos_level:N?F:void 0,qos_sdk_version:2,...Xp},Yp),Qp=Object[s(1608)](ga)[s(1076)]((ma,wa)=>ga[wa]!==void 0?""+ma+(ma?"&":"?")+wa+"="+ga[wa]:ma,"");return ct+s(1967)+Qp}async[t(1656)](){let n=t;if(!(this["_connect"+n(880)]||this[n(1751)+"osed"])){this._connectLock=!0;try{let s=this[n(1764)+"tManager"]?.[n(1058)+n(1245)+n(1858)+n(850)+n(632)](),{timeoutInterval:d}=this[n(499)];if(s){let g=this[n(1764)+n(1637)]?.[n(1022)+"ntEndpoint"](),m=this[n(1764)+n(1637)]?.[n(1320)+"ackupEnd"+n(817)+n(877)+n(1909)](),S=this[n(1764)+n(1637)]?.[n(1022)+n(1094)+"ntTriesC"+n(1475)]();if(m){let p="connect "+g+(n(798)+n(1422)+n(753)+n(1309)+n(1972)+n(1714)+n(777))+m+" to retry",R=e.JFbih(ot,"error",{message:p,code:tn[n(1619)+"IES_ERROR"]});this[n(633)](p),this["_dispatc"+n(625)+n(1342)](R),this._url=await this["_generat"+n(1344)](m),this[n(633)](n(854)+m+" "+S+n(1883)),this[n(1880)+n(1034)+"rs"]()}else{let p=n(854)+g+(n(798)+n(1422)+n(753)+"ached");this[n(633)](p),this["_dispatc"+n(625)+n(1342)](ot(e[n(1644)],{message:p,code:tn["MAX_RETR"+n(1111)+"R"]}));return}}else{let g=this[n(1764)+"tManager"]?.[n(1022)+n(1094)+n(1773)+"ateCount"](),m=this[n(1764)+n(1637)]?.[n(1022)+n(1094)+n(1593)+n(1475)]();this[n(1458)]=await this[n(1407)+n(1344)](e.YINgs(g,"")),this._debug(n(854)+g+" "+m+n(1883)),this[n(1880)+"sListeners"]()}if(this[n(1316)])this[n(1316)]=!1;else if(e.kHuPx!==e[n(1948)]){let g=e.xCYDu[n(698)]("|"),m=0;for(;;){switch(g[m++]){case"0":this._ws[n(814)+n(870)+n(1062)](e[n(1520)],this[n(1018)]);continue;case"1":if(!this[n(459)])return;continue;case"2":this._ws["removeEv"+n(870)+n(1062)](e[n(851)],this[n(1839)]);continue;case"3":this[n(459)][n(814)+n(870)+"ner"](e[n(528)],this[n(644)+"ge"]);continue;case"4":this[n(459)][n(814)+n(870)+n(1062)](e.SQijK,this._onError);continue}break}}else{let g=aa(n(718)+"t",{message:e[n(1337)]});this[n(1234)+n(920)]&&this[n(1234)+n(920)](g)}let f=this[n(1764)+n(1637)]?.[n(1022)+n(1094)+n(1593)+n(1475)]()||0;f>1&&await this[n(680)](f-1),this[n(633)]("connecti"+n(778)+this[n(1458)]+(n(1421)+n(626))+this[n(1713)+"ls"]),this[n(459)]=e[n(1750)](hp,{url:this[n(1458)],protocols:[this[n(1713)+"ls"]],headers:this[n(499)]["miniProg"+n(1089)+"s"][n(942)+n(809)]},this[n(499)].ws),(this[n(1026)+"er"]||this[n(773)+"r"])&&this._ws&&(this[n(459)][n(1044)+"pe"]=this[n(1778)+"ype"]),this[n(956)+n(1127)](),this[n(1656)+n(1021)+"utId"]=e[n(972)](setTimeout,this._onTimeout[n(1252)](this),d)}catch(s){throw this[n(1656)+"Lock"]=!1,s}}}[t(1922)+t(1868)](){let n=t;clearTimeout(this["_connect"+n(1021)+n(775)]),this[n(1656)+n(1021)+n(775)]=null}[t(1812)+"ngTimer"](){let n=t;e[n(671)](clearTimeout,this[n(693)+"gTimeoutId"]),clearTimeout(this[n(1724)+"ctTimeou"+n(926)]),this[n(693)+n(605)+"Id"]=null,this[n(1724)+n(1757)+n(926)]=null}_debug(...n){let s=t;this[s(499)][s(1227)]&&console[s(1449)][s(772)](console,[e[s(1228)],...n])}[t(606)+t(1854)+"e"](n){let s=t,{initReconnectInterval:d,maxReconnectInterval:f,reconnectIntervalGrowFactor:g}=this[s(499)],m=e[s(1019)](d,Math[s(650)](g,n-1));return m>f?f:m}_ping(){let n=t;if(this[n(459)]&&e[n(1507)](this[n(459)][n(1270)+"te"],this.CONNECTING)){this[n(1812)+n(1885)](),this[n(693)+n(605)+"Id"]=e.ZBxSQ(setTimeout,this[n(867)][n(1252)](this),this._options["pingInte"+n(1947)]);return}if(!this._ws||e[n(1479)](this._ws[n(1270)+"te"],this[n(1109)]))return void this["_handleR"+n(920)]();this[n(459)]&&this[n(459)][n(1708)]("hi"),this["_reconne"+n(1757)+n(926)]=e[n(1870)](setTimeout,this[n(1226)+n(920)+n(1046)].bind(this),this[n(499)][n(1514)+n(929)+"val"])}[t(1226)+t(920)+t(1046)](){let n=t;this["_pingLos"+n(1760)]?.[n(896)](),this[n(1599)](e[n(1767)],e[n(1264)]),this["_pingLos"+n(1760)]?.[n(1144)+n(1135)+"nt"]()?this[n(1226)+n(920)]():this[n(867)]()}[t(1453)+"orOnline"](){let n=t;return this._isMiniTT||this._isMiniWX?this[n(585)+"igatorOn"+n(1695)]:(this._isBrowser||this[n(773)+"r"])&&this[n(499)]["listenNetworkCha"+n(637)]?navigator[n(1066)]:!0}[t(1226)+t(920)](){let n=t;!this["_navigat"+n(1886)]()||this[n(1751)+n(567)]||(this[n(1764)+"tManager"]?.[n(1763)+n(989)+n(1673)](),this[n(1463)+n(1760)]?.resetCounter(),this[n(459)]?this[n(1625)+n(833)](1001,n(1610)+"ay, try "+n(718)+n(822)+"ver",!0):this[n(1656)]())}[t(1790)+t(512)+t(614)](){let n=t;if(e[n(1412)](e.woWuS,e[n(807)])){let{offset:s}=e[n(848)](_0x538c46,_0x1312aa,_0x4a2d58);_0x2dea02=s;let d={cursor_name:"",cursor:0,service:0},{value:f,offset:g}=e[n(622)](_0x2fc03a,_0x14d61e,_0x344e98);d[n(1444)]=f,_0x4c4165=g;let{value:m,offset:S}=_0x2e6654(_0x4f755d,_0x5211f3);_0x3d94b1=S,d[n(904)+n(1282)]=e[n(577)](_0x2eae63,_0x330ca3,_0x207563,_0x1ec94f+m),_0x18d5e1+=m;let{value:p,offset:R}=_0x3fed03(_0x229f9e,_0x430442);d[n(997)]=p[n(1445)](),_0x61bff6=R,_0x51e1d3[n(539)](d)}else this._isMiniTT?tt[n(536)+"kStatusC"+n(691)](({isConnected:s})=>{let d=n;this[d(585)+d(950)+d(1695)]=s,s?this[d(668)+d(1093)]():this[d(668)+d(1613)]()}):this[n(1537)+"X"]&&wx[n(536)+"kStatusC"+n(691)](({isConnected:s})=>{let d=n;this[d(585)+"igatorOn"+d(1695)]=s,s?this[d(668)+d(1093)]():this[d(668)+d(1613)]()})}_wait(n){return new Promise(s=>{let d=U;e[d(845)](setTimeout,s,this["_getInte"+d(1854)+"e"](n))})}[t(1625)+t(833)](n=1e3,s="",d=!1){let f=t;this[f(459)]&&this[f(1194)+"WebSocket"](n,s,d)}[t(619)+"ut"](){let n=t;if(e[n(1551)](n(864),e[n(658)])){let s=this["_endpoin"+n(1637)]?.[n(1022)+n(1094)+"nt"]();this._debug(n(854)+s+n(798)),this[n(1625)+n(833)](1001,e[n(593)],!0)}else return this[n(1487)+n(454)+n(747)+"t"]=1,this[n(487)+n(1418)]++,this[n(762)+"s"][this[n(487)+n(1418)]]}[t(588)](n){let s=t,d=e[s(1722)](Ft,n);this[s(459)]&&e[s(612)](this[s(459)].readyState,this[s(1109)])&&(e[s(1281)](e.yUIWu,e.yUIWu)?(this[s(1894)]?.close(),this[s(1894)]=void 0):(this[s(459)]&&this[s(459)][s(1708)](d),this._debug(e[s(677)],n)))}[t(1880)+t(1034)+"rs"](){let n=t,s=e[n(1153)][n(698)]("|"),d=0;for(;;){switch(s[d++]){case"0":this._ws[n(814)+"entListener"]("error",this[n(584)]);continue;case"1":if(!this._ws)return;continue;case"2":this._ws.removeEventListener(n(924),this._onMessage);continue;case"3":this._ws["removeEv"+n(870)+n(1062)](e[n(851)],this._onClose);continue;case"4":this[n(459)][n(814)+n(870)+n(1062)](e[n(1520)],this._onOpen);continue}break}}[t(956)+t(1127)](){let n=t,s=e[n(661)][n(698)]("|"),d=0;for(;;){switch(s[d++]){case"0":if(!this._ws)return;continue;case"1":this[n(459)]["addEvent"+n(1574)](e.lvCIL,this[n(644)+"ge"]);continue;case"2":this[n(459)][n(1597)+n(1574)](e.yqJsl,this[n(1839)]);continue;case"3":this[n(459)]["addEvent"+n(1574)](e.SQijK,this[n(584)]);continue;case"4":this[n(459)][n(1597)+"Listener"](n(1496),this._onOpen);continue}break}}["_wsInsta"+t(1774)](n=1e3,s=""){let d=t;try{this[d(459)]&&this[d(459)][d(1528)](n,s)}catch{}}["_destroy"+t(1208)+"t"](n=1e3,s="",d=!1){let f=t;if(this[f(1812)+f(1885)](),this[f(1922)+"mer"](),this[f(1880)+f(1034)+"rs"](),this["_wsInsta"+f(1774)](1e3,s),this[f(1656)+f(880)]=!1,d&&this[f(1453)+f(1886)]()&&!this[f(1751)+f(567)]){if(this["_endpoin"+f(1637)]?.[f(1144)+f(1535)+"es"]()){let m=this[f(1764)+f(1637)]?.[f(1022)+f(1094)+"nt"]();this[f(684)+"hCloseEv"+f(1342)](e[f(1186)](ht,e[f(851)],{code:1006,reason:"connect "+m+(f(798)+f(1422)+"tries re"+f(1e3)),wasClean:!0}))}else{let m=this._options[f(718)+"tInterce"+f(1915)](n,s);this["_dispatc"+f(917)+f(1342)](ht(e[f(851)],{code:n,reason:s,wasClean:!0,willReconnect:m})),m&&this[f(1656)]()}return}this[f(1453)+f(1886)]()||this[f(1751)+f(567)]?this[f(684)+f(917)+f(1342)](e[f(1624)](ht,e[f(851)],{code:n,reason:e[f(1286)]})):this[f(684)+"hCloseEv"+f(1342)](e.ibCaf(ht,e.yqJsl,{code:1006,reason:e[f(1889)]})),this[f(459)]=null,this[f(1764)+f(1637)]?.["resetEnd"+f(989)+f(1673)](),this["_pingLos"+f(1760)]?.["resetCou"+f(474)]()}[t(684)+t(971)+"nt"](n){let s=t,d={xhgKu:function(f,g){return e[U(1287)](f,g)},nIRNH:function(f,g){return f+g}};if(e[s(1324)](e[s(587)],e[s(1758)]))this[s(1599)](s(1496),n),this[s(1047)]&&this[s(1047)](n);else{let f=0,g={};for(let m=0;kFOZRK[s(998)](m,_0x2a87c4[s(1092)]);m++)g[_0x20f3ac[m][s(904)+s(1282)]]=_0x5bf6fb(_0x2df76d[m][s(904)+"ame"]),f+=kFOZRK.nIRNH(14,g[_0x2c3471[m]["cursor_n"+s(1282)]]);return[f,g]}}[t(684)+t(1638)+t(853)](n){this[t(1599)](e.lvCIL,n),this.onmessage&&this.onmessage(n)}[t(684)+t(1465)+t(1383)](n){let s=t;this[s(1599)](s(506),n),this["onReceiv"+s(1781)]&&this[s(665)+s(1781)](n)}["_dispatc"+t(625)+"ent"](n){let s=t;this[s(1599)](e[s(1644)],n),this[s(690)]&&this[s(690)](n)}[t(684)+"hCloseEvent"](n){let s=t;this[s(1599)](e[s(851)],n),this[s(1830)]&&this[s(1830)](n)}get[t(1044)+"pe"](){let n=t;return this[n(459)]?this[n(459)].binaryType:this[n(1778)+n(1442)]}set[t(1044)+"pe"](n){let s=t;this[s(1778)+s(1442)]=n,this._ws&&(this._ws[s(1044)+"pe"]=n)}get retryCount(){let n=t;return this["_endpoin"+n(1637)]?.[n(1022)+n(1094)+n(1593)+n(1475)]()||0}get[t(1181)+t(1736)](){let n=t;if(e[n(1162)]===e[n(1162)]){let s=this[n(767)+"Queue"][n(1076)]((d,f)=>(d+=f&&f[n(1192)+"th"]||0,d),0);return e.ZEFBt(s,this[n(459)]?this[n(459)].bufferedAmount:0)}else{if(e[n(964)](_0x2ce045,_0x22ade0))return _0x56c322?_0x9b2110:_0x6e33fa;if(_0xfb17e2){if(e.XwDlE(_0x45f708,_0x160a99))return _0x58056e}else{if(_0x5201e9<=-_0x431f01)return _0x5e2b94;if(e[n(825)](_0x30c776+1,_0x4920cd))return _0x4587b2}return _0x4954b1[n(1480)](e[n(1004)](_0x4fe475%_0x371e20,0),e.zrexj(_0x286138,_0x1fd27b)|0,_0x26b838)}}get[t(1301)+"ns"](){let n=t,s={LhkVG:function(d,f,g){return e[U(516)](d,f,g)},LoUfo:e[n(1337)]};if(e.TCftt(e[n(1939)],e.XlIGA)){let d=FlZzKP[n(1852)](_0x534a03,n(718)+"t",{message:FlZzKP[n(1381)]});this[n(1234)+n(920)]&&this[n(1234)+n(920)](d)}else return this[n(459)]?this._ws.extensions:""}get[t(946)](){let n=t;return this._ws?this[n(459)][n(946)]:""}get readyState(){let n=t;return this[n(459)]?this[n(459)][n(1270)+"te"]:this[n(499)][n(749)+"cOpen"]?this[n(737)+"NG"]:this[n(1237)]}get[t(986)](){let n=t,s={noSrC:function(d,f){return d||f}};if(e[n(1766)](e.FuXdS,e[n(1156)]))return this._ws?this[n(459)][n(986)]:this[n(1458)];{let d=this[n(1894)][n(776)](this._prefix);return _0x24a6e5[n(859)](kwcssZ.noSrC(d,"{}"))[_0x308a1e]}}[t(1528)](n=1e3,s){let d=t,f={cdNAY:function(g,m){return e[U(1223)](g,m)},TubbL:function(g,m){return e[U(1731)](g,m)},RGVXz:function(g,m){return e.Qszve(g,m)},xzrtc:function(g,m){return g<<m},IZwyj:function(g,m){return e[U(1769)](g,m)}};if(e[d(1408)](d(1158),"SHVDF")){let g=e.swTsy.split("|"),m=0;for(;;){switch(g[m++]){case"0":this[d(1194)+d(1208)+"t"](n,s);continue;case"1":if(!this[d(459)])return void this._debug(e[d(821)]);continue;case"2":this[d(1696)+d(1523)+d(1574)]();continue;case"3":this[d(1435)+d(1935)]?.[d(618)]();continue;case"4":this[d(1922)+d(1868)]();continue;case"5":this[d(1812)+d(1885)]();continue;case"6":if(e[d(1129)](this[d(459)][d(1270)+"te"],this[d(1237)])||e[d(710)](this._ws[d(1270)+"te"],this[d(890)]))return void this[d(633)](e.eNppO);continue;case"7":this[d(1751)+"osed"]=!0;continue}break}}else _0x19fd84=_0x35e9ed[pWBOOq[d(1308)](pWBOOq[d(1045)](_0x3d4da1,_0x5c000c),1)],pWBOOq[d(1585)](192&_0x16f385,128)?_0x51426b+=_0x4dc4e3:(_0x55662d=pWBOOq.xzrtc(pWBOOq[d(1941)](31,_0x263555),6)|63&_0x422580,_0x498f62<128?_0xb24433+=_0xbc104e:(_0xc458fb+=_0x4c8be8(_0xc465c3),_0x595bd2++))}async[t(1708)](n,s){let d=t;if(e[d(608)](e[d(1367)],e[d(1367)])){if(e[d(1170)](null,n))throw new Error("please p"+d(740)+d(1113)+"ata, dat"+d(1201)+d(1895)+d(728)+d(1882)+d(881));e[d(1965)]==typeof n&&(n=JSON[d(1862)+"y"](n)),e[d(1346)](e.DMjhK,typeof n)&&!e.JVJaw(n,ArrayBuffer)&&!(n.buffer&&e[d(1547)](n.buffer,ArrayBuffer))&&(n=JSON.stringify(n));let f=await il(n),g=e[d(1390)](gp,n),{method:m=0,service:S=this[d(499)][d(1444)],logID:p=this._options[d(1865)+"erator"](),headers:R=this[d(499)][d(692)],payloadEncoding:L=this[d(499)][d(635)+d(1157)],payloadType:N=this[d(499)][d(1118)+d(1442)],logIDNew:F=this._options["logIDNew"+d(1587)][d(858)+d(1727)+d(500)+"ew"]?e[d(1008)](i,this._options[d(844)+d(1587)][d(1159)]):""}=e.BnVMJ(s,{});if(!S)throw new Error(e[d(1704)]);let $={SeqID:fe[d(1216)+"er"](this._seqId++),LogID:fe[d(1216)+"er"](p),service:S,method:m,headers:R,payloadEncoding:e[d(534)](L,Object)?L[d(1873)]?L[d(1873)]:"":L,payloadType:N instanceof Object?N[d(544)]?N[d(544)]:g:N||g,payload:f,LogIDNew:F},X=e[d(610)](Ft,$);return this[d(459)]&&this._ws[d(1270)+"te"]===this.OPEN?(this[d(459)]&&this[d(459)][d(1708)](X),this[d(633)](d(1210),$)):this[d(767)+d(620)].length<this._options[d(993)+d(1850)+d(706)]?(this["_message"+d(620)][d(539)](X),this[d(633)](e[d(1589)],$)):(this[d(767)+d(620)][d(1099)](),this[d(767)+d(620)][d(539)](X)),{seqID:this[d(1271)],logID:p,logIDNew:F}}else return _0x48a28a||(_0x9ddc70=[_0x8b7753[d(1517)+"e"][d(1754)],_0x57f9db.prototype[d(756)],_0x33afea[d(1517)+"e"][d(756)+d(1634)+"ey"]])}async reconnect(n){let s=t;if(e.rttOF(e[s(1980)],e[s(1837)])){let{url:d}=e[s(938)](n,{}),f=Array[s(1620)](d)?d:e[s(1222)]==typeof d?[d]:[];n&&Object.assign(this._options,n),f&&f[s(1092)]?this[s(1764)+s(1637)]=new el(f,this[s(499)][s(1951)+"es"]):this["_endpoin"+s(1637)]?.[s(1763)+s(989)+s(1673)](),this[s(1463)+"sCounter"]?.[s(1003)+"nter"](this._options[s(995)+"Count"]),this[s(1751)+s(567)]=!1,this._ws&&e[s(629)](this[s(459)].readyState,this[s(1237)])?this[s(1625)+s(833)](1e3,e[s(1468)],!0):(this[s(1316)]=!0,this[s(1656)]())}else return new _0x1bfca7(_0x57a8e8,{code:_0x31a88b,reason:_0x4980c4,wasClean:_0x18ebb1,willReconnect:_0x2e7a9b})}async[t(1220)](){let n=t;if(e.GcCKl(e[n(1616)],e[n(1616)]))rwmrIq.pKxkA(_0x4aac87,_0x138536[n(1863)]||new _0x39352a(rwmrIq[n(1832)],rwmrIq.pJdBY)),rwmrIq.IBFII(_0x18b82c);else if(!this[n(1656)+n(880)])if(e[n(1828)](e[n(1365)],e[n(1365)])){let s=e[n(1187)].split("|"),d=0;for(;;){switch(s[d++]){case"0":this._connect();continue;case"1":this[n(1751)+n(567)]=!1;continue;case"2":this[n(1764)+"tManager"]?.["resetEnd"+n(989)+"fig"]();continue;case"3":this[n(1316)]=!0;continue;case"4":this[n(1463)+n(1760)]?.["resetCou"+n(474)]();continue}break}}else e.OryrX(_0x287b38,65536)?_0x27464b[_0x34f928++]=e[n(1052)](e[n(1295)](_0x23bdaa,12)&15,224):(_0x14a5c9[_0x4ffab1++]=e[n(555)](e[n(700)](e.UjDqx(_0x328fb9,18),7),240),_0x3cbaa6[_0xea0eb3++]=e[n(1508)](e[n(735)](_0x439e21>>12,63),128)),_0x357b90[_0x1183dc++]=e[n(1319)](e[n(502)](e.HTIqh(_0x44bdba,6),63),128)}[t(1597)+t(1574)](n,s){this.on(n,s)}[t(898)+t(853)](n){let s=t,d={OaNMP:function(f,g){return e[U(495)](f,g)},oNdZJ:function(f,g){return e[U(897)](f,g)},Fqtrh:function(f,g){return e[U(1115)](f,g)},TwxMo:function(f,g){return e[U(1771)](f,g)},AAHWE:function(f,g){return e[U(813)](f,g)},FAhPn:function(f,g){return e[U(1877)](f,g)},cOyph:function(f,g){return e.dOhTZ(f,g)},XeWCm:function(f,g){return f<<g},EMdHY:function(f,g){return e[U(1666)](f,g)},gzEkk:function(f,g){return e[U(1892)](f,g)},Hzljd:function(f,g){return e[U(1875)](f,g)},wabLW:function(f,g){return f(g)}};if(e[s(1412)]("TxzOB",e[s(808)])){let{type:f}=n;this[s(1599)](f,n)}else _0x38c619=_0x40adbd[NBIgae.OaNMP(NBIgae[s(1553)](_0x5993ec,_0x32e825),1)],_0x3f3806=_0x4878af[NBIgae[s(1262)](NBIgae[s(599)](_0x567e9a,_0x3f196f),2)],NBIgae[s(540)](NBIgae[s(667)](_0x38ce6b|NBIgae.FAhPn(_0xc623de,8),49344),32896)?_0x18e69f+=_0x2e9ff4:(_0x5666f1=NBIgae[s(576)](NBIgae[s(1492)](NBIgae.AAHWE(15,_0x4a6b2f),12)|NBIgae[s(1395)](NBIgae[s(667)](63,_0x584ef7),6),NBIgae[s(667)](63,_0x36931e)),NBIgae[s(1579)](_0x17e4ba,2048)||NBIgae.gzEkk(_0x496b20,55296)&&NBIgae[s(810)](_0x32ed99,57343)?_0x52f1ad+=_0x400b38:(_0x1ba70c+=NBIgae[s(1720)](_0x4534ed,_0x4e2dd7),_0x16b503+=2))}[t(814)+t(870)+t(1062)](n,s){this[t(1592)](n,s)}[t(520)](){let n=t,s={HNOsD:function(d,f,g){return e[U(1823)](d,f,g)},MmFan:function(d,f){return e[U(1663)](d,f)},NkcoS:e.pKMuP,Oxkkv:"KYjci",srSeh:function(d,f){return e[U(969)](d,f)},zcBiE:n(493)+n(1568)+"t",COKLZ:function(d,f,g){return e.TUhDv(d,f,g)},dkMGr:e.ovAgX};return new Promise((d,f)=>{let g=n,m={GMubd:g(1017),roayl:"ping_onc"+g(1138)+"s",nscXq:s[g(1450)]};this[g(1812)+g(1885)](),this[g(693)+g(605)+"Id"]=s[g(960)](setTimeout,this[g(867)][g(1252)](this),this[g(499)]["pingInte"+g(1947)]);let S=()=>{let R=g;d(m[R(1028)]),this[R(1592)](m[R(481)],S),this[R(1592)](m.nscXq,p)},p=()=>{let R=g,L={rZicw:function(N,F,$){return s[U(1471)](N,F,$)}};s[R(1100)](s.NkcoS,s[R(510)])?(s[R(1950)](f,R(796)),this[R(1592)]("ping_once_success",S),this[R(1592)](s[R(1450)],p)):(wVvyJU.rZicw(_0x38a421,_0x261b90,8),wVvyJU.rZicw(_0x239d66,_0x5c4b55,_0x2fc6b9))};this.on(s[g(1101)],S),this.on(s.zcBiE,p),this[g(867)]()})}}})(),Le[B(1462)+B(699)]=Ce.CustomCloseEvent,Le[B(1923)+B(1691)]=Ce["CustomEr"+B(1691)],Le[B(494)+"e"]=Ce[B(494)+"e"],Le[B(853)]=Ce.Event,Le[B(1432)]=Ce[B(1432)],Le[B(1290)+B(909)+B(1079)]=Ce[B(1290)+"MessageE"+B(1079)],Le[B(909)+B(1079)]=Ce["MessageE"+B(1079)],Le[B(552)+"t"]=Ce.OpenEvent,Le[B(1605)+"tEvent"]=Ce[B(1605)+B(498)],Le.createCloseEvent=Ce[B(1423)+B(699)],Le[B(1030)+"rorEvent"]=Ce.createErrorEvent,Le[B(1881)+B(719)+"nt"]=Ce[B(1881)+B(719)+"nt"],Le[B(802)+"enEvent"]=Ce[B(802)+"enEvent"],Le[B(970)+"connectE"+B(1079)]=Ce.createReconnectEvent,Le[B(1478)+B(1088)]=Ce[B(1478)+B(1088)],Le[B(1660)+B(1282)]=Ce[B(1660)+B(1282)];for(Bo in Ce)["CustomCl"+B(699),B(1923)+"rorEvent","ErrorCode",B(853),B(1432),B(1290)+B(909)+"vent",B(909)+B(1079),B(552)+"t","Reconnec"+B(498),"createCl"+B(699),"createErrorEvent",B(1881)+B(719)+"nt",B(802)+B(906),B(970)+B(617)+"vent",B(1478)+"rame",B(1660)+B(1282)][B(979)](Bo)===-1&&(Le[Bo]=Ce[Bo]);var Bo;function qo(){let t=["Dg9mB3DLCKm","z1r4uha","zxjYtM8","wKzvAva","B2zM","BNruCMLLC0m","t1vzDvi","uKvPtfq","sfzMCfG","ywrKrxzLBNq","vLftsuS","zw1PDa","zxq9DxrMltG","tvDMAgy","AK5ZBge","venMDhq","y2PYzNy","uMvJB25Uzwm","rvjst1i","B3bLCNr5tMe","A2v5CW","C2DZveC","z29PBMCGyxC","DgvZDa","uNDcA1e","zMzmAw5L","EeDhEMm","Cezbr2q","BNDqDui","Aw9Ul2PZB24","ywrJtvK","tufyx1jfvfi","AxnbCNjHEq","z3jAv2S","ywXPzcb1CMW","tLHiv1m","se5Xzg4","x2rPC2nVBM4","CMvZB2X2zq","C3vIC3rYAw4","v0vyzxe","m3WXFdz8ma","zg9myxa","sgnWqKi","z01nrgG","DvPItgy","uhjPBwfYEuS","ndq2nJa4mMfPugH0yW","C2vUzf9Hy2S","De1HBMfNzxi","Ae1LC3nHz2u","vgTSr0u","vuvwtg8","zKDbAuC","AMHly0y","vLPxDK8","u1fPAKS","BfrPBwvVDxq","DKvruu4","vMHiEfq","AxnrB1nby2S","zxjFywnRx20","zxjYtxnN","q0PRAgu","sMHzv0S","mdaWma","CgHir2C","Bg5hCwu","x2nVBM5Ly3q","A2jTr2y","C2LYs2q","BgLTAxq","zw5JB2rLrNi","wunfAxy","CMvWBgfJzq","wvjOD0G","AfHOENC","s3fhzKi","u1b1CLy","thPqCeG","ign1CNnVCIa","Dhr3Awq","yvDfueu","EvjLy29UBMu","q3PpC3O","zMLN","zNHXuxe","DfvPuva","AMPpDwi","yK1Ysw4","vfvNBg4","yLjNuKu","EfvZzuvUDG","wwnHB24","y2f0y2G","q291BNq","mhW0Fdj8mxW","Eg5yC1O","v05mug8","DhbeBxC","q29qq2q","u0rfzeO","CgXLyxnLiha","CM9YrxzLBNq","yxnL","BwTmzu8","x2LUAxrhBg8","BgLUzq","x2rYB3bhBg8","Aw5KzxG","qxzcug4","z2vtEw5J","reiGzMfPBgu","zMX1C2HfEha","y29UDgv4Da","B2nRzxq","y2HUAMe","mNW0Fdf8m3W","wwrdDg4","BwvZ","C2vUza","zNjVBNrPzxi","CMvQzwn0","qLblDNe","tuvtu0fhrv8","x3bYB3rVy28","yMfJA3vWigu","s2fxCwO","z3LRyLq","ExHpwxu","v1zouvO","u0vqDwi","D2fItfC","sxrpBw4","wxzfEuu","AgfZt3DUuhi","x3jLy29UBMu","x194x21Zz18","tKLTsKS","Dg9hzw5LCMe","qNjPzgDL","Aw1LCYbPBIa","vvj4uKi","zLLLBwe","se9oyKS","vxfJr0G","CwPAEeS","svLYtNC","qw1VDw50","AKHsuMm","EeHhtg8","ugLLDLu","CfvmC3a","wMTuruS","z0fdCw4","uKPgve8","seXms2u","rLngtva","CMvHzhDYAxq","BfnJzum","D3m6lY8","wgHRwK0","sxHcwLu","x3jLywr5q2W","u0Pws0i","Bg9IywXty28","ywr2yw5Jzq","vw5PBxbSzw0","uvjftwy","y3ruAw1LB3u","ELjpuee","yKrLy2S","C0nVDw50zxi","zxP2uu0","DgLLCKPtt04","CMvZzxrfBMq","x2vUzhbVAw4","ve5uzKy","zgjYExC","z2n3yum","txLXuvK","wK9Pu1G","ywX3yxLZ","DLfeyKO","tu9hqKO","BNrbBMrvCgq","BMnLq2XVC2u","zxjFAxnFywm","ihzHBgLKihm","AgXmyKm","x2jPBMfYEvq","uxPAvwq","ywXS","zufJAW","qurxtMK","B3bLCNr5","B25TzxnZywC","BxnNsuq","Aw5L","mxW0Fdn8mNW","zwrPyxrLBhK","B2jQzwn0u3q","x29UugfNzu4","wLHQCMm","yw1LoIa","r3vPz1y","ywrK","EwjxBgK","rKXcAfq","EeH2vhu","q0nxy3K","qMrZwvq","twnmsgu","D3nZoI8V","yKroB3K","EM1mDvG","Aw5N","B2n3uu8","uvHoswe","yxH1uu0","zwnVsuq","v3jZsvq","qKjlt3u","v0HWExe","x2nSzwfYugK","lcbxzwjtB2m","sLnptLa","y21TAem","shrQtM8","yKzLC2G","uMvHzcbWyxm","z1nhzNe","DcbSAw1PDa","B3bLBIa","AvjQChG","CfPNsue","EurYtg8","CNjVCK1LC3m","FdH8nNWW","zNjHBwvuExa","DwHNreC","DKPgyuy","B25JBg9Zzq","DLruv2K","CePKqLK","wM1vELO","AeDgvNy","u2vXsuq","BwLVCMO","tgLtqKK","qwjVCNrfCNi","x29Uq2XVC2u","zxjFBxnNAwq","zgf0yq","sgPzvKm","rvzYBKy","vvHguxC","BKDrqLe","yKDowNy","tNf5Dgq","wxPVAwK","BuT1DMe","z2vrDwv1zuW","Cw1WsNm","tgHRvKC","DxrMofDYAxq","CNzHBfzHBhu","BMv3vMvYC2K","run1BKO","twLyu1O","B2LUDfjLywm","s0Hmt1a","EMrzuxa","vKXls1G","C3rYAw5NAwy","zxjYB3i","s2z2BxC","Bg9Nsurhzw4","DvLIDK0","yMnXwLi","BwvY","BwvZC2fNzv8","rwLiD0e","BePiv3K","Aw5JBhvKzxm","zw5JB2rPBMC","v0fqtK8","ChrPBhG","A09YEuS","DujMzvu","rufcvue","yMLUyxj5","x3jLBw92zvC","y3jLyxrLtwu","igfYCMf5yNu","ihrPBwvZ","zxjHDg9Y","BMDuAw1LCG","B3jpBMXPBMu","r3nyB0u","yMXVy2TLza","BhDLq1G","v0PqtNG","wLPYCei","v3PeB04","uevlEgm","x3fVC0rc","zsbHihn0CMK","s1nnsMu","mhWXFdr8m3W","AwPhr2C","y2fcDg8","r09vEeO","CNvSsMe","t3LVvMq","mtiWnte3mwfYEe9Hsq","u3nUwMW","qw9AwNK","vw5eu1q","v0zysve","rufkALG","Dw50","wKLRExi","yuHisgi","rMzsEKS","C3vIyxjYyxK","wMnMCgu","ChrVCG","A25UwKG","zgvqwha","Dg1VBNu","u0jWzNK","u2nkyLC","q0Pvseq","x2nSzwfYvgK","q3vZDg9Trxi","C2v0zgi","v2PYCLq","tKDFrvjst1i","mxWWFdr8mxW","DK9btuO","t1bXr1i","s3ffsMi","AvLdEvC","vvPKAxa","EvHHCuu","Dw5ZAwDUzwq","z2vY","y29UBMvJDgK","B2fK","Au5RwMS","CMrLBu4","tKfusvzfx0u","svP3EwO","Dhj1y3rVCIa","AwXLtMfTzq","zw50zwqGDhK","u3jsu2C","DeLUDgvYy2u","CNzHBa","A0H1uhG","C2nLELi","C3jtzwG","Bwf4uMv0CMK","v2PJA0u","CMH0Dei","DKntEhy","AxnquwW","sNveyvu","x2LUAxrqCM8","EeXoBg0","zNLPt20","EeHTqNi","qu1vDxO","qKPtzMK","vvrVCKG","Dw5RBM93BIa","r1nut3a","tvHKrva","l3DZl3yY","vK5kuLK","uerNuxC","BfP6q0K","r1jkuxm","AwXSihvZzsa","x2LZtM9Kzq","svP6sNm","Chv0","BuPNwxa","A2PgrNK","Ceznugq","ug1mwfy","uwLrC2W","x0rctMfTzq","vNDhq1O","BMrWB2LUDfq","Dw5KzwzPBMu","uwDqDuW","Eg1xqM0","z2v0q3vYC28","x3DZ","CgfNzxnOB3C","thDRBLa","B25pCgvU","t09IyxK","yxrLq291BNq","D2nvt2u","BwLUzW","DMvYC2LVBG","CLzHBhvLCW","BM9Uzv9UB24","sK5IwK4","rwTRzvG","wLbor2q","EgnZufq","BNrLCG","uxv6ueu","yKLjDxC","EsbJBg9Zzwq","vejbsxO","z2v0qwXSs2u","qKfWwuu","CM9HEwW","zgrjrcWGzgu","uLzKEKy","BgTAsMK","y29Kzq","BKfJt0q","y3vYCMvUDeK","sfz6u1O","mNWWFdn8mxW","DhnbDum","B3jRzxjhBg8","BM5Ly3q","CgLUz19VBMm","rxjYB3jdB2q","EvzgC2y","tvfer3C","t0jcA2S","Dev2zw50","x29WDgLVBNm","DgvmB2Djre4","y1HUEfy","ywPmugm","wuvku3q","AhbXAue","BMPIA3u","ywnR","y2juEvq","ENzYqxm","rvDZs1C","t3HRA3y","rfzJwvi","zxrxB3jRq2G","CgfNzwHPzgu","y3LHtMW","tLnTEfO","AfflA3u","C2v0sxrLBq","EwvXEvu","Dg9cExrLC0W","CgLUz09Uy2u","uKfSsfy","D2LSBfjLy28","ALb1vvC","B25tDg9Wsw0","zgv2AwnLx2K","vxzLCKW","zMzMzG","BhzdsuW","rw9QALi","C2v0q3vYC28","uMfOrvy","teDSrNy","rhLuuxK","r2HkufO","y2fwz2C","B25ozxr3B3i","wxLNyxO","v1DeDui","ChvZAa","vhD4tw8","C29YDa","EhLNANO","sun3v1q","DhLWzq","Ae11CLe","zcbLCNjVCI4","Dg9cExrLC0i","Dhfyu00","CfPmwhK","ENbgC1a","y2jQs3O","t3bLBKv2zw4","rgfLAxG","teHgzwC","y3nZtgS","s0jLyw8","q1fqC2u","y2XVC2uSihC","x2nYzwf0zvm","t3H0tLu","mhW0","tLvoqLi","vxjzB1y","AgvHzgvY","y2Htruq","t2LtA3O","B3nLza","r3LrCNG","twTfr0G","B0nmD2i","zhvuq0G","AgLNAa","B3jLtMfTzxm","CNr0t0y","DvLLBu0","y095CgG","yw10ve4","q3LqrgG","BK9ivvG","tNHoEKK","AxjLza","uLjpuG","CM92AwrLihy","x29UrxjYB3i","x21PBMLoyxy","yNvXr20","B1rWCuC","x3nLBMrby2S","renLrw0","BKXWvMG","seT6C2W","y29Uy2f0","u3fHC0e","rezlCeK","Aw5orwO","Bwvgvhy","CMvHzg9UBhK","ue1Pzwi","rNf0CMG","AfPLB2W","z2vjBMzVu3K","DNn3vLq","tK5Rtw0","BhrPCgXLihq","z1rPBwvVDxq","x2DLDeLUDgu","yK1VAgu","v3v1wxq","zhfAtwm","DufHDNq","s25Ps0m","B1bwwgm","rfnhBfe","yw5Nzq","q0v5tLG","otG5mZyYnxfSvMLWAa","y29UBMvJDeu","y2XVC2veqG","x29UvgLTzw8","uxvLDwu","zg9Uzq","ENv0tLO","teDvueC","sMrmwu4","AevYCM9Yrxy","Bhm6ia","AxmGDw5Kzwy","wLrczha","ChvdqwS","DvDUqMS","AM9PBG","DhjPzxm","x2rLyNvN","tNvUswS","Cgf5Bg9Hzeu","Bg9hswe","BMDLza","ywDL","BeHHBMrSzxi","AvH3A2u","CYbPBNn0yw4","zgfLCei","ExnsAve","x29UtwvZC2e","CYbHBhjLywq","y2Hiv3i","o2nOyxjZzxq","quXm","z2v0","Cg93","wvPxyLq","qMzKwMO","yMDVB00","vK9puhq","uvjlv0C","B056s0m","z3Hhqwm","rM5fqxK","s1zKvue","ugLNEu4","A1P4vgm","AxfTsva","vgfN","DfnIrwe","B25szwnLAxy","qvrxr3O","qufiv0u","x2HHBMrSzu8","ELzxD3K","sfDLwuW","t011D1u","D3jPDgvvAw4","wufxCe8","C0jf","zNjVBunOyxi","quPwDg8","s2X6uNO","icSG","wurKqMe","x3DHAxq","A2v5","uePAzwu","C3DzwwK","x2rPC3bHDgm","AgzQDfu","y2vZC0HHBMq","t05ese4","AxDWsgG","EeTXt2S","B25LCNjVCG","AgfUz2u","AgvHzgvYCW","x3bPBMDqB24","sMrqtfK","y3vYC29YlNm","u2rSt0u","uK5lv3y","C3bSAxq","B3nLrxzLBNq","sMD0CMS","seLUB3O","yNL0zu9MzNm","Dgv4Dc9Qyxy","ExDSAuG","EhDvsNK","zw5NDgG","zgvSzxrL","DcbVzIbYyw4","zNHpuKW","rhr5ueW","x2HHBMrSzva","Ce5SBhy","yw5Hz2vY","DhjPBq","yM5uy3K","vhjqy1y","vMPSuLK","CMvJB25Uzwm","C3nHz2vfDMu","BM93","AwD0zgG","rNfsrgm","qwzOvNK","x2n1CNnVCKy","Bwu6ia","tevosfG","r05TyNG","BMCGB3iGyw4","sgXNq0S","BwvKAwf0zwW","BgvY","r2nds2W","C0TyC3q","BLf2BvG","t29oq0y","zMXVB3i","q09otKvdveK","Aw9U","uMv3yKe","CM92AwrLige","vw5Oyw5KBgu","s25wy0u","rMjvu3q","yM9KEq","v2z2q2W","B09cuxq","CMLLC0nVDw4","y2XLyxi","yxv0B21HDgK","mtHJD1r2vxa","zxmGCMvHy2G","qLbhzem","DhjPzxmGCMu","BK1PzwO","v2nYuui","y29UDgLUDwu","rNzAswG","AgPktve","B25dBg9Zzq","zNjVBuj5Dgu","uhrPCfa","zw5KCg9PBNq","svrfquC","yxv0BW","ywXty29Wzq","nxWXFdn8mNW","x21LC3nHz2u","r1DRy3O","q09oveLovuu","rfjuwu0","yLPIq1C","yxbWBhK","x2LZv29YA2u","AfDry1e","Dxrjza","z2v0sxrLBq","BMrWB2LUDca","BMCGDxjSoIa","tfvODMe","zwjpsNy","u2TPCcbWyxm","CgDTtMG","vur6t2O","DhjHBNnHy3q","y3r4","sePkzNO","vhrMAuK","yxGGCMv0CMK","BMfTzq","u3fnBwy","x3bHDgHlzxK","DuPXDNK","Bxvuwxi","yMrFzgLK","BwvZC2fNztO","DgLTzw91Da","BxnN","ihrPBwvVDxq","AxHZB1K","Eg5frxy","rg5qqw0","y3jLyxrLt3a","qxHLEM8","Dgv4Dc9WBge","yvvurvO","rg1lzxa","u3ncrLu","rufXyvK","DhbizwfKzxi","shPSAMq","u0TwAfa","wff6ANi","rufnCuu","CMvTB3zLrxy","y09Wzw4","s2rryxK","Cg9PBNrbBMq","EMz2rNu","ELLdvw4","AvvIz2m","z3jZse4","DgLUzYbZzxi","Aw5PDcbrB1m","yxbWBgLJyxq","zM9yB3y","ChzlCum","DKnhse4","z0zxwvq","ChbL","BezSDxnO","x2TLEvbHDgG","AuDJvey","zwn0","B3jL","AxryAhO","tKLusKO","DMfSDwvZ","zxjFCw9Zx2e","ANn3C0K","wvDAzem","ihjLy29UBMu","r0Ttv0G","ze1ntxm","Bg9NsurozxC","uuT1rKy","rK1gt0K","mtC1mJm0odHvyvrcCMe","wxfusuS","z3rJr1e","AgvKtwf4uMu","ExfkC2W","uNHOAeC","rxzLBNq","y29UBMvJDca","CNHwA28","C3rYAw5N","quHvs1u","zw5HyMXLqxu","CgfYC2u","ugr6DLO","vhvLtxy","uwTduum","C2zNwLC","vhrAtLy","qwLUqwm","A3zOsg0","x3bPBMC","rfzMrvu","y29TCgXLDgu","zw50tgLZDgu","zxj2AwnL","D0XeEuy","C3rVCcbPBw0","uNnMzfu","BLHMq1a","B2zMBgLUzq","vxbKyxrLq28","CgTJwu8","Ehfvt0e","tg9JAW","zMzLCG","B3bLBKrc","tvvRtMe","yNvMzMvY","qMnQqwW","y2uGBM90igK","t0LJzhO","EhjLD3C","zu5fzvu","q0Xpu0LorW","s3H3zhG","y1LUCLa","id4G","zLzJDvK","y3vKv1q","ywrKq291BNq","t3DYwfC","zgLZCgf0y2G","DNvAtMC","zKXvuxm","rw5OuNe","y3jLyxrLt2i","z2nTz2G","y3vYC29Yx24","zKX2Dxi","zw5fDMvUDa","wu5ABxG","BuDUuee","twvZC2fNzuu","s2zwwfy","B3D6BMW","B2zMC2v0","CgvYC2LZDgu","yNLL","sfHVzLO","DgLjt0C","AenSB3nLrxy","rKLmrv9ot1q","vxboEvG","zwnVBM5Ly3q","s29xzxu","Eu15t2e","uw95vLe","BwvZC2fNzq","Ec1TC2CTCw8","DeLK","AfjzCKm","twLZC2LUzYa","B3v0sw50zxi","CMvTB3zLq2G","DNbvteO","q3zbrMu","DxbKyxrLq3u","s2Xbsu0","thfszLa","DgLTzw91DcW","ywHZzLu","qM5wtuO","sfnLzvO","t2Xou20","y2fSBa","y3vZDg9Tshq","tK5sEe8","CNr4Egm","yNL0zxm","ChjVDg9JB2W","ALjiBwu","CM92AwrLihC","v2Pxvfi","AwDHDg9Yt24","x2n1CNnVCK0","rfz1vM0","wgvZs2K","ywXSq3vYC28","CK9Qy1a","x2fKzfDZtgK","C1nKvuK","AwXLx25HBwu","Fdr8mNWZFdK","q09ltfO","pxv0zI04","mtuZmdu5mfDOz3PJyq","CLb4CKi","qwXlCxO","s01AyLa","s3nNB0C","v09VzK8","CMvArNe","Cuf0EuW","y3jLyxrLuMu","Ae9Wzw5fDMu","vfvOrhy","B3jRig9MzMW","thvnvLu","zgL4seK","zNDZxZeUmc4","C3jJ","qKXtCwS","Aw5KzxHpzG","D0vWBKm","tg9Nsuq","tKPer3e","vNDHvNm","yu1grvG","ruvJBLa","DxjS","zMLSDgvY","C1zKEhy","Cg9PBNrdB24","rfHTseq","BxfQuxu","txrfDhG","Bwf4twvZC2e","r25nCMC","CgLUz0XVC3m","x2LUAxq","y3vYC29Y","EgHNs3u","zxjFCw9Z","ywnOzwq","z2v0qwXS","DerjA3y","CMvZzxrdB3u","EKj0EgO","AhHnrwy","q0TMC24","C3rVCMu","ueHeu3C","serKCvi","EKHnAeC","reLAv3i","DKfpuLC","B25Uzwn0Aw4","vhH6t0i","ALfMs3i","zcWG","C3vJy2vZCW","x29Ut3bLBG","v0LtB2q","ENLyzuO","Aw9UvgLTzw8","z2v0q3vYCMu","nxWYFdn8mxW","qLfIv0i","DejlCLe","x2LZqNjVD3m","Bu5vsKq","r011yMq","D1n2De8","y3jLyxrLrxi","q0TRquS","u0jLAfe","zvPXu2i","C0XPC3rLBMu","DfLxywO","swfuEeK","C2XPy2u","wuXzwgO","tMfTzq","s0HdzLe","v01usNi","zhbNCve","zenTt3q","yMLUyxj5vhK","vhvIyKW","vgLTzw91Da","B25VCgvU","ExfSAg4","r1r0tMe","uMnHt04","sKHnqNe","Exjsz1e","CMvZDwX0","mxWWFdj8m3W","ywXSB2nvBNm","yNz0AKG","vwnRCfu","y2HLy2TdDxi","u2PJEu8","tLjMAK4","DMzPvwW","BMvY","ywDLu2HVDW","wwLeEfe","rwr0CKm","B25mAw5L","ALPhEgi","Ef9MCM9UDgK","yun3uxq","uxPNAxi","zgvMAw5Luhi","t05gr1O","mdaWmdaWmda","wu1pC3u","DxPzBhK","CMvKDwnL","u3rYyxrLz3K","AxnmB25N","DMvUDa","qxP0vMS","Cw9Zx18","CfDzAvi","u0rJvNi","ELP0BNK","yNvpsuy","vxL6svq","suXZt00","CMfTzq","CMfTugfYyw0","D0X5tgW","BvbUsuC","BgvUz3rO","BKXPBMu","BNrfBMrWB2K","tg9NsurozxC","AxnrB1nnzxm","twXjBNm","z3LgBKS","C2HPzNq","tw1gyw4","zgTnr3i","zM9Yy2u","zKnVsMO","BNLSyKW","yxKSig5LDhC","tLHVAeu","z2v0u3rVCMe","mteWmdCZCgrZzxjg","t1bftG","EfD0ENu","suvtx0vsuK8","rfjVufq","ihzHBgLKigq","sKvjq2O","shDkvvK","ww5Ts2C","zw5HyMXLvhi","Cgf5Bg9Hzfq","DgjMruG","zufOAMS","rMnkv0m","Awflq2C","qLvrtvO","ywXSzwqGBxu","B3zbz1G","uMXrt1e","C3rLBMvYCW","uKPgDuW","wu5iB1a","Dg9Y","yxDoAuS","zMLUza","D2fZq2XLyw4","C295tM4","y2HnyxHdB3u","Ahr0Chm6","DLz1sKi","zv9ZDwnJzxm","r3PivKe","qwH2Aee","u2X5tha","C3vUC0S","rK12ruC","y2HLy2Tszwe","AKvfu2i","DefYufy","zfjWwLO","AhjkD1G","ru5VueK","DMvYC2LVBMm","y2XwB2G","u2L1wfK","EgvPq1G","BhbwAxu","yKDcsuy","tvPkCLy","BMnVzgLUzW","C0HRte4","DxnLCKLW","Bg5iuLq","CMXrvvq","Ahf2swW","EgnprKO","uxfYsMK","wNDxvwe","yxnJCMLWDa","B25fCNjVCG","zfDVCMTLCKC","y3jLyxrLrwW","v1zNs0m","zgLZywjSzue","r3fwv24","zgvSzxrLrge","zwz3uvu","C0Xf","wLLKA3e","wMHZu3u","zLHMuw0","CMvHC29U","x2XPC3rLBMu","yNvMzMvYzwq","BMCGzMfPBgu","BwLZzq","v1vurMq","yxbWzw5Kq2G","tNvnCve","Evf1C0K","A1H0D3e","CLLKBfO","zNjVBuHHC2G","Bej1zu8","yNL0zuXLBMC","zxf1ywXZ","x2rLC3rYB3K","yw51Ce1LC3m","DgHLBG","se9QDuW","DgfYz2v0","uNzSAKq","rNLZqKy","ysbTDxn0igi","s2XyB04","B2nRzxrgywK","CMjctfm","zgXPANG","sLDvz00","AxnszwfKEq","v2vIu29JA2u","r1zQq20","C2vUDa","vLnYvxm","AuHdD0q","ENflvMO","Bwf4tg9ZC0m","DMXXrNC","zNjVBu51Bwi","tKD1Auq","y3vYC29Yx2y","v3HdCLC","y29UBMvJDa","qLjACum","re1QAeS","vxPzuhy","CYbWyxjHBxm","yNbvCKK","x2HHBMrSzvi","zgvIDwC","EuXJEvm","rvbXr3O","z3v1vgu","BKT4uNC","x3nVy2TLDa","sxfdBwq","B25tDgfYDfi","v0LeAhG","y3Pbq08","q0Xpu0ve","ywDLsgLKzq","tw9KDwXL","DhPUr0i","y291BNq","C2v0u3rVCMe","zw1osLC","t2rdAwm","CMvUDevUzha","x19LC01Vzhu","zw5HyMXLuw8","wLDmvNe","uejtwwC","v0v1Cwu","BuPSCLq","yMLUza","BxzvzLa","y0XsugW","nJa5nZmWnefTAMDmsa","AKXnExe","y2HHCKnVzgu","Cgf5Bg9Hza","z3j2yLi","x2LZtwLUAvq","ruzUBhi","B05KwKO","ueztC1i","r2Hdt3O","BfPjy0y","AgfZ","uMLmEhi","CMvXDwLYzwq","vgLfDKC","CMvHzhLtDge","x3nLCuLK","wgXwrvu","C1DZweq","vgXHs1u","Aw47y2HHCNm","uurqB1e","CxnWtwC","A2PAEg8","quf6CMe","EgHTtLy","DK9dy0i","yw1L","zxHWB3j0CW","mtb8ohW2Fde","AwXK","DhfmsgO","vvf6sxa","Buj2qwO","t0XUtNq","rNjVBNrPzxi","CwvrzKS","Fdr8mhW5","ywrKt25L","CgnvzKu","EhPIteW","t1bftL9fuLi","wNHKswK","C3bSAwnL","v2z2qvO","rMTYreu","zxH0zw5ZAw8","AKTWv3i","zhHeuvi","n3W0Fdv8mNW","ELnHwNq","vhbttu8","AwrI","y2roqvK","ywnOzwqSihC","BwfW","zcWGDw5RBM8","Aeffre8","AgfOswm","BLDwCw8","sMHsr1a","x2LZsw5PDa","CuH0y0G","C2vXALq","zeXqBgq","CMvWBgfJzui","Bwv0Ag9K","EKflz2m","tNj4EgC","BfDvBwy","rgvKAwnHDgu","DMfbyKq","Dgv4DfbHEwW","DhHrCNm","C1n5vLC","D3jhAxq","tvnOEM0","tLfPqw8","yxnZAwDU","u2HHCMvKv28","B05pq2u","yxj1wgi","wMDMDMm","sfHOrKW","yM9L","vLzxALG","y3vYDMfSDwu","zw50","u1P5BMS","zvvYBa","yLHevxa","wLfVvuC","tuPMqwq","EuHrvu8","yMXUsvK","DLDOs2m","sxrtu0q","uhzAAui","yM1HzvO","qK9jBNi","AhPmENO","ufLgy3K","BMvJDa","C2DLv0C","DMLJzuLeig8","tMDJq0K","zMvY","Cw9Z","ALDdswS","C2v0y3vYC28","rgTMv1e","CLbxt2u","yunxyKC","EhvNsK8","AMjqCKC","EvD3CKm","qKXHz1G","AvHlC0S","Dwv1q1q","A05ICNi","ywWGy3vYC28","wuLoz3m","we1nAu8","zw1LBNq","uujRrLi","B1nSBM0","tg9vzM8","BMvLzf9Hy2S","ywDLrxzLBNq","quHWvgi","yKPgzxK","EgvvEu0","t3bNC08","tg9MtNi","uu9Rs3i","ru10Ae0","BMTkzLe","uxn6DMu","uMDKrxC","rxvXt0C","wgvxq20","reXuvxK","AfnprNq","y29UBMvJDfm","zM9YrwfJAa","ug1utxy","BKHrrM4","wxfKthi","Axnby2TdBgu","AvHODxi","u0HcqLq","DgfIyxnL","x2DLBMvYyxq","y29JBwG","rNn6B2G","jMPZy2fSBgi","t3rwr2W","EhbqA3O","C0PoAK4","x2rItMfTzq","qwXVAfa","C3rHCNq","r1rcrhu","BMrLEa","sw9vtMe","vwXVy24","ihbYB3rVy28","lcbTyxGGCMu","y3jLyxrLq2W","thLwrg4","B2XKvMvYC2K","C0jsvKW","BwfUDwfSihi","vwfgDuK","B0TkA2e","C2v0","Ec1TC2CTy3u","rLDt","thjlyuu","x2n1CNnVCK4","x1fVu01HBMe","uNfouNG","zMTYueu","tvnrEgu","vKHAs3C","z2v0s2v5","CMfNzvn5BMm","ExbL","rhfgAMu","C2vYDMLJzq","Dg9oDw1Izxi","sK5wAxy","yxHmAxq","BertreW","Bg9N","EMncAuu","CfH0zue","r2HrD3K","x25HDMLNyxq","BMv4DcGPigm","q1fgrvm","x2LUDgvYDMe","A2v0ignVBNm","x3vYBa","C2vYDMLJzs0","C2fNzq","rfP3B2S","q3vZDg9Tq2W","x3bPBMDmB3m","yM5JwMK","AefJA01LC3m","DLvfCNu","B25SAw5L","uKvltLm","DhLAEfm","wLbqsKm","se5pC0q","EwLnDMC","DLHrsMe","vxPcBKC","B3vUDa","D1DuqKi","DxrVuMvJB24","zgvJB2rLzey","vLrfB2e","zNjVBujPDhm","uxjQAw0","EKDNCee","v01tr0y","B2nRzxrtDwm","CgrRyMq","yNz1Duu","y3vYCMvUDeu","yw1Lu3bHy2u","D1nmDNm","AxnFywnR","Aw50zwDLCIa","rKfOug4","BgzsuhK","yuTdwLu","tvzbq3O","B3bLBG","v2rkEe4","yNnowxa","tNvfA3u","vvD5Bhm","CuDsEMi","y29UC3rYDwm","ignVzgu6ia","zNvUy3rPB24","zw5XDwv1zq","s291q3u","zLjZAvy","CeHIBg0","BhHJs0u","u2vYDMLJzvC","EvvryKW","x3bYzwzPEa","DgXtB0G","CgLUz1rPBwu","yNH1uei","qwf5AhG","ChjVDg90Exa","tvbuv2i","z1bKt08","BM94A3m","vhPxCKC","ufDVAgm","yMfSrxzLBNq","wgXru2G","Dg9iyxnO","BML0AwfSAxO","y0fXvwO","y2XVC2u","Bg93","qMPUqwC","qwfNA2O","A2LXz1y","wwDOt1O","A0Tdu3G","y2HnyxHuCMK","vKXZuwu","x2LZtwLUAvC","Bg13Efi","Dg9tDhjPBMC","rwj0rfe","wxbqEvG","qMzmB3y","ChjVy2vZCW","s3Dgwgu","CwTUuw0","q29Kzq","zfr2Bfa","Bfjisfe","ywTuvLy","C2vYDMvYvgK","BuHxz0u","AKfSugC","t2fotva","vK9mrKq","BIWGAg9ZDg4","rwnjyK4","DMfSDwu","C0rOv2u","zgfdwLG","x2zVCM1HDeu","C29Tzq","B3Lqwfe","tKHhBwW","vePZu0W","CeXOAKO","D1DSsgG","zMLSzw5HBwu","zv90Aw1LB3u","u0n6CKK","yMrJENe","CMvJzxzPzwq","yvnltLq","rgv0Cui","tgLZDgvUzxi","q2Dtww0","CMvHzfvjBNq","z0Dqtw0","zgvS","ru1KsfK","igzPzwXKoIa","vhjlALa","D2vI","C2nYAxb0","nhWW","uKDwwhO","t1fVD2W","q29UzMLN"];return qo=function(){return t},qo()}Object[B(1071)+B(1783)](Le,B(1246)+"le",{value:!0})});import{existsSync as nS,openSync as rS}from"node:fs";import{mkdir as iS}from"node:fs/promises";import{dirname as sS}from"node:path";import{fileURLToPath as oS}from"node:url";function cS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Dd(t=Q()){return nS(t.libEntry)?t.libEntry:oS(new URL("../index.ts",import.meta.url))}async function Th(t={}){let e=t.paths??Q(),r=t.entryOverride??Dd(e),i=cS(e,process.env.COZE_BRIDGE_LOG_MODE);await iS(sS(i),{recursive:!0});let o=rS(i,"a"),l=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=et(process.execPath,l,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[es]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return aS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var aS,es,Vo=Je(()=>{"use strict";Kt();ne();Pe();aS=G("spawn-daemon"),es="COZE_BRIDGE_DAEMON"});import{spawn as t2}from"node:child_process";import{mkdir as n2,unlink as r2,writeFile as i2}from"node:fs/promises";import{dirname as s2,join as o2}from"node:path";function Kr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function a2(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Kr(r)}</key>
21
- <string>${Kr(i)}</string>`).join(`
20
+ `+r)}function Xn(t,e,r,i,o,c){if(t.listenerCount("wsClientError")){let d=new Error(o);Error.captureStackTrace(d,Xn),t.emit("wsClientError",d,r,e)}else Qi(r,i,o,c)}});var Dx=oe(Ne=>{"use strict";var L=q;(function(t,e){let r=q,i=t();for(;;)try{if(-parseInt(r(1385))/1*(parseInt(r(1557))/2)+-parseInt(r(1308))/3*(parseInt(r(661))/4)+-parseInt(r(1421))/5+parseInt(r(1161))/6*(parseInt(r(330))/7)+parseInt(r(473))/8*(parseInt(r(1493))/9)+parseInt(r(752))/10+-parseInt(r(1170))/11*(-parseInt(r(1014))/12)===e)break;i.push(i.shift())}catch{i.push(i.shift())}})($o,380090);var qv=Object[L(408)+L(851)],jv=Object[L(1271)+"opertyNa"+L(449)],kx=(t,e)=>function(){return t&&(e=(0,t[{HDPRg:function(c,d){return c(d)}}[L(1722)](jv,t)[0]])(t=0)),e},Wv=(t,e)=>{let r=L,i={mBpGE:function(c,d,u,f){return c(d,u,f)}};for(var o in e)i[r(708)](qv,t,o,{get:e[o],enumerable:!0})};function $v(){return Ex||(Ex=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Kv(){let t=L;return vx||(vx=[IDBCursor[t(1443)+"e"].advance,IDBCursor[t(1443)+"e"][t(1143)],IDBCursor[t(1443)+"e"]["continue"+t(442)+"ey"]])}function Vv(t){let e=L,r={orxsW:e(514),WSChh:e(870),mvFvg:function(o){return o()},Sabcf:e(835),kwoGR:function(o,c){return o instanceof c},KdSJd:function(o,c){return o===c},MQVsI:e(1198)},i=new Promise((o,c)=>{let d=e,u={IikLY:function(x,p){return x!==p},oMCuH:d(1697),KMwRh:r[d(1361)],GZhUn:r[d(699)],tfXMz:function(x){return r[d(1118)](x)}};if(r[d(663)]==="qavKi")for(var f in _0x5b03cd)_0x43f579.o(_0x3536cd,f)&&!_0x2529f0.o(_0x424c48,f)&&_0x335fcc[d(408)+d(851)](_0x43491f,f,{enumerable:!0,get:_0x566979[f]});else{let x=()=>{let v=d;u[v(958)](u[v(1411)],u[v(1411)])?_0x493cff.log(_0x5ba4d3):(t[v(1183)+"entListener"](u.KMwRh,p),t[v(1183)+v(1467)+v(1714)](u[v(1286)],_))},p=()=>{let v=d;o(Ft(t[v(489)])),u[v(862)](x)},_=()=>{c(t[d(870)]),u.tfXMz(x)};t[d(1395)+d(1020)](d(514),p),t[d(1395)+d(1020)](d(870),_)}});return i[e(577)](o=>{let c=e;if(r[c(1238)](o,IDBCursor)){if(r[c(1158)](c(968),r[c(804)]))return new _0x4bc5a0(_0x1a20b1,{data:_0x1399df});Od[c(1744)](o,t)}})[e(1321)](()=>{}),jo[e(1744)](i,t),i}function Zv(t){let e=L,r={eUtKO:e(676),MGqFW:e(1479)+"2",rTVNT:function(o,c){return o!==c},CdnWI:e(575),PynEf:function(o,c){return o>>c},oAOcv:function(o,c){return o&c},tUanA:function(o,c){return o|c},Ttivo:function(o,c){return o(c)},oxLBi:"AbortError",XUNTw:function(o){return o()},eRzLb:"cmtlD",FsbPE:e(870),dNbiM:e(389)};if(qo.has(t))return;let i=new Promise((o,c)=>{let d=e,u={njsdg:function(p,_){return p||_},YaVRa:function(p,_){return p===_},YDMbG:r.CdnWI,mKNHw:function(p,_){return r[q(678)](p,_)},dBtqM:function(p,_){return r[q(825)](p,_)},oAoCT:function(p,_){return r[q(360)](p,_)},VecKH:function(p,_){return r[q(678)](p,_)},Idnxm:d(632),lthhj:function(p,_){return r[d(1702)](p,_)},kwAVR:r[d(868)],NIaXD:function(p){return r[d(1043)](p)}};if(r[d(886)]===r[d(886)]){let p=()=>{let w=d;t[w(1183)+w(1467)+w(1714)](r[w(1559)],_),t[w(1183)+w(1467)+w(1714)](w(870),v),t[w(1183)+w(1467)+"ner"](w(389),v)},_=()=>{let w=d;if(u[w(1211)](u.YDMbG,"pGtff")){let E=this[w(1038)][w(1244)+w(812)](this._prefix);return _0x2d149a[w(1601)](u[w(878)](E,"{}"))[_0x2c2357]}else o(),p()},v=()=>{let w=d,E={mQnSW:function(I,A){return I|A},IDexN:function(I,A){return I&A},IZBoP:function(I,A){return u[q(1547)](I,A)},gkRPQ:function(I,A){return u[q(1615)](I,A)},SVgMr:function(I,A){return u[q(1547)](I,A)},uDfhZ:function(I,A){return u[q(936)](I,A)},neWCk:function(I,A){return u[q(638)](I,A)},SBdfE:function(I,A){return u[q(936)](I,A)},rMdck:function(I,A){return u[q(1615)](I,A)},Ioyml:function(I,A){return u.mKNHw(I,A)}};u[w(1211)]("yTQMc",u[w(349)])?(_0x18192f<65536?_0x1687c[_0x92712++]=E[w(504)](E[w(1618)](E[w(1055)](_0x188dcf,12),15),224):(_0x50df9f[_0x2873e4++]=E[w(504)](E[w(938)](E[w(406)](_0x3bd328,18),7),240),_0x4c8b32[_0x9c2461++]=E[w(1276)](E.IDexN(E[w(308)](_0x360f16,12),63),128)),_0x172bd5[_0x2f66ce++]=E[w(654)](E.rMdck(E.Ioyml(_0x192aa,6),63),128)):(u[w(605)](c,t[w(870)]||new DOMException(w(333)+"or",u[w(1575)])),u[w(876)](p))};t[d(1395)+d(1020)](r.eUtKO,_),t[d(1395)+d(1020)](r[d(616)],v),t[d(1395)+d(1020)](r.dNbiM,v)}else{let p=r[d(1091)][d(732)]("|"),_=0;for(;;){switch(p[_++]){case"0":if(r[d(1232)](void 0,x))return x[d(450)];continue;case"1":var f=_0x485e01[_0xf239e8]={exports:{}};continue;case"2":return f[d(450)];case"3":var x=_0x1ebd9c[_0xfc56b9];continue;case"4":_0xcd1d93[_0x345886](f,f[d(450)],_0x12e9eb);continue}break}}});qo[e(1744)](t,i)}function Jv(t){Wo={rYnZN:function(r,i){return r(i)}}.rYnZN(t,Wo)}function Yv(t){let e=L,r={tylrs:function(i,o){return i(o)},EEugk:function(i,o){return i>o},yeImD:function(i,o){return i+o},dboiP:function(i,o){return i(o)},rOnkB:function(i,o){return i===o},pZGrZ:e(783),SiljU:e(818)};if(r.rOnkB(t,IDBDatabase.prototype[e(691)+e(983)])&&!("objectSt"+e(1416)in IDBTransaction[e(1443)+"e"]))return function(i,...o){let c=e,d=t[c(493)](es(this),i,...o);return Dd[c(1744)](d,i[c(1763)]?i[c(1763)]():[i]),Ft(d)};if(Kv().includes(t)){if(r.pZGrZ!==r[e(1397)])return function(...i){return t[e(427)](r.tylrs(es,this),i),Ft(Od.get(this))};{let i=_0x2dfdd1[e(690)];if(r[e(764)](r[e(1201)](i,_0x549f30),_0x11fd03.limit))throw new _0x13a295(e(1144)+"t limit");return _0x719467[e(690)]+=_0x30f821,i}}return function(...i){let o=e;return r[o(998)](Ft,t[o(427)](r[o(811)](es,this),i))}}function Xv(t){let e=L,r={iZhFM:function(i,o){return i===o},UkNQV:e(1352),EYroe:function(i,o){return i(o)},bxyNO:function(i,o){return i instanceof o},BDgyg:function(i,o,c){return i(o,c)}};return r[e(845)](typeof t,r[e(512)])?r[e(966)](Yv,t):(r[e(703)](t,IDBTransaction)&&r[e(966)](Zv,t),r[e(1264)](Tx,t,$v())?new Proxy(t,Wo):t)}function Ft(t){let e=L,r={XbRVm:function(o,c){return o(c)},sHUUk:function(o,c){return o!==c}};if(t instanceof IDBRequest)return r.XbRVm(Vv,t);if(Go[e(750)](t))return Go[e(915)](t);let i=r[e(1202)](Xv,t);return r[e(1309)](i,t)&&(Go[e(1744)](t,i),jo.set(i,t)),i}var Tx,Ex,vx,Od,qo,Dd,Go,jo,Wo,es,Sx=kx({"node_modules/idb/build/wrap-idb-value.js"(){let t=L,e={SWJdQ:function(r,i){return r instanceof i},kLqqv:function(r,i){return r===i},CBdhO:t(1377),kbYLa:"store",fdNzu:function(r,i){return r===i},eQSNa:function(r,i){return r===i},xOWLs:function(r,i){return r in i}};Tx=(r,i)=>i[t(1021)](o=>r instanceof o),Od=new WeakMap,qo=new WeakMap,Dd=new WeakMap,Go=new WeakMap,jo=new WeakMap,Wo={get(r,i,o){let c=t;if(e.SWJdQ(r,IDBTransaction)){if(e.kLqqv(i,e.CBdhO))return qo[c(915)](r);if(e.kLqqv(i,c(1423)+c(1416)))return r[c(1423)+"oreNames"]||Dd[c(915)](r);if(e[c(1564)](i,e[c(1662)]))return o["objectSt"+c(1416)][1]?void 0:o[c(1423)+"ore"](o[c(1423)+c(1416)][0])}return Ft(r[i])},set(r,i,o){return r[i]=o,!0},has(r,i){let o=t;return r instanceof IDBTransaction&&(e[o(682)](i,o(1377))||e[o(1694)](i,e[o(1662)]))?!0:e.xOWLs(i,r)}},es=r=>jo[t(915)](r)}}),Rx={};function $o(){let t=["B3jLtMfTzxm","Ae92yNa","wwj3vLO","mxWZFdD8nhW","zNjVBuj5Dgu","mJyXotCZnwvsDwTADa","Cg9PBNrdB24","B2jQzwn0u3q","y3vYC29Y","Cw5ZBM8","x29UvgLTzw8","BM1Qsw0","Bg9Nsurhzw4","qKHtuLu","CfLcAwC","CMv0CNLdB3u","rgL6zxy","C2v0u3rVCMe","rhLMs2O","zw5JB2rLrNi","se9MCha","v2vIu29JA2u","DgTvyKy","ywXSzwqGBxu","wM5rzei","CMvZzxrdB3u","vgX4ENi","ChjVDg90Exa","Dgv4DfbHEwW","se95seS","CNnVCL9Uyw0","wKrtsfq","EMj6A3y","x3bPBMDqB24","ywrKq291BNq","AxnFywnR","zNjwBg8","DhjWDMO","ig1LC3nHz2u","Cwvxrei","CMvTB3zLq2G","vwjWu3i","A2v5","C05zvfq","BwfUDwfSihi","wM5eAvC","vxvWBuO","CKnnuhm","EvjLy29UBMu","zMrHz1C","AKLMqNy","zw50tgLZDgu","sfHiyvG","zgTcwLK","y2HnyxHdB3u","zgLcsfC","wvn1y3e","BMnLq2XVC2u","CePjqve","q3vZDg9Trxi","ENnRu0W","D1beDMu","x2n1CNnVCK4","m3WWFdf8nhW","Ae1IyNm","ywnOzwq","BNrfBMrWB2K","n3WWFdH8oxW","aaaaaaaaaaa","lcbTyxGGCMu","uw5IDMu","ywDL","BNruugS","ywnRtxnNswq","tu9mv1u","rgT6twW","BKvjwhm","mZi4mdmXmwjZCM1UCq","BNrbBMrvCgq","u0TeCMq","zxjFAxnFywm","zxq9DxrMltG","D2LSBfjLy28","rxDWsu4","x194x21Zz18","yM9L","rgrXu1i","tNnWsgi","r2LJBgm","CNzHBfzHBhu","wfrLshG","CMvWBgfJzui","zgv2AwnLx2K","y3r2AgO","twfIu3e","uNHhyNi","ywXty29Wzq","r2rfEgK","wNLjqwK","t3jdyw0","ELfhDui","z2vrDwv1zuW","yKfNr3a","Dhzev3e","y2HLy2Tszwe","uwDHuKm","wePIALK","EwnjvKK","t05TqNm","BKndB0S","zw1LBNq","CM92AwrLigi","BMCGB3iGyw4","tePYvw0","z29PBMCGyxC","Fdj8nhWX","D0Tby2K","y3jLyxrLtwu","AfbkEfu","AefJA01LC3m","DMfSDwu","wKXIuLe","Awz0CgS","B3jL","C3rYAw5N","C1bPyuS","BLfOwNe","BKPPtKS","BenNsKW","Cgf5Bg9Hzfq","B3jRig9MzMW","BuToshC","ANfwANe","veXYtLm","uvvsAe8","C2v4r0G","DgfIyxnL","AxDWEKO","swH5y1O","B25ozxr3B3i","twjuvMO","mtGWohPZzeDerq","yMLUyxj5vhK","zvv0s08","swDsvuu","uNfstKW","rKLmrv9ot1q","mNWXFdv8nNW","A0XXCxy","tfbYCwC","zuz4Dgm","u0XHBhG","whHxvLu","vwDQwNq","yvbOsem","AenSB3nLrxy","whHqEKy","z1vlA0C","rLjptLrjrvi","A3DbvLi","r29rAwu","BIWGAg9ZDg4","x2zVCM1HDeu","D2DhqMu","rxzLBNq","B25dBg9Zzq","B3bLBG","v2jlwg8","x2HHBMrSzva","rer1yKG","shDZEK0","CgfNzwHPzgu","BNf1zfu","Ec1TC2CTy3u","ywnOzwqSihC","AevYCM9Yrxy","z2zJuM0","yNjmyNa","BwvZC2fNzv8","quzOtMq","zLbVCha","Aw5KzxGGB3u","AxLZtMm","Dw5RBM93BIa","EgvKBeW","CgfYC2u","BevJrM4","AKXPr2G","y3rmq3G","tfnIEKe","AxjLza","B25TzxnZywC","C2DPza","twLwD28","B25szwnLAxy","z2TItM4","x2LUAxrhBg8","DK1nvuC","DxrVuMvJB24","zej0Cu0","yxrHlcbKyxq","refuvwe","surLEe4","Bw5zq0y","C0TmEu4","DLv1tgS","x2LUAxrqCM8","CMvWBgfJzq","CwrtCfC","zxH0zw5ZAw8","z2u6ia","B3jRzxjhBg8","zw5HyMXLqxu","vgjPrNC","zw5fDMvUDa","C0jf","y29UDgv4Da","vxPgvLu","vLv1uNu","rwnxwNm","x25HDMLNyxq","A2v0ignVBNm","CfLkB1y","Efrurw52","z1royui","zMX1C2HfEha","zw5KCg9PBNq","vNHJBui","CMvXDwLYzwq","B1HzzKq","qw1VDw50","DgXkzNi","ChfXrLi","v29PwuC","BM13B0m","z0XAAeG","x2n1CNnVCKy","DhLWzq","BenbEMu","qLzeDMW","sNvlCNy","CLjxv0i","yMXVy2TLza","A1PhAue","Chj0q1u","x2fKzfDZtgK","A2jztge","shvks0u","yw1L","wLnWyMe","CMvHzhLtDge","BwvKAwf0zwW","su5tvefova","x29WDgLVBNm","rLjQEK4","y3jLyxrLrxi","CwDfq2y","r3Lov3O","s2DmyKe","zMTbv2y","BgHyCva","CMvHC29U","z0nOChu","D2vZshi","wfzAzu0","Au5twha","vfbHC0W","CezOBMW","vfPVCe8","y3rAugy","A0XOCfK","r0rwz1i","BM5XBxO","q3Lqvwy","CM92AwrLihy","qMvLs08","rMzvA0q","AM90sLq","zvfttMe","ChrVCG","Aw1LCYbPBIa","v0vZC3y","vxzxEe8","CMvQzwn0","EsbJBg9Zzwq","t3H3ruW","vhrPDM8","sNLMC24","rvjst1i","DffJv1C","DwLIExi","tuvtu0fhrv8","EfvZzuvUDG","DLL3DLC","zKDYrfi","Dg9cExrLC0i","A3rTr0K","igzHAwWSig0","BMvY","D25wBhe","CNnVCL92ywW","r25csg4","zw1PDa","BwvZC2fNztO","Dg9cExrLC0W","BgLUzw5V","serquMC","y3jLyxrLrwW","r0DrBNG","tKfusvzfx0u","C2v0y3vYC28","twLZC2LUzYa","y29UC3rYDwm","rxjYB3jdB2q","x29Ut3bLBG","ihzHBgLKihm","q0Xpu0LorW","Aw9UvgLTzw8","ywXPzcb1CMW","BMDLza","rxfkCeO","zNjVBuHHC2G","C1HxDLG","y2XVC2u","qxbmA3q","zNDZxZeUmc4","uxbRD0W","zxjYtxnN","C2v0","y29UBMvJDa","Dg9VigXHCMC","x21PBMLoyxy","thf0A1i","q1vUAu0","yLDuv1O","x2LUDgvYDMe","Aw5L","CLL5Cfe","zgvSzxrLrge","y29SBM8","z2v0q3vYC28","rwXyywW","Dw1NtfC","yw1Lu3bHy2u","B0HqyM0","CMvHzg9UBhK","C1zRthu","C29YDa","BMvxq2S","rNDSB0C","y3vYC29YlNm","quPesgm","vNPzzee","rxvmDgO","B3fZExG","vhHrzfO","ELLruwy","BgLTAxq","CKXXtxy","zxbAz3m","CuHcEfa","CeX4A0i","v0H1uhu","zufJAW","yMfSu2nVCgu","tvHHDNu","C0Xf","wxrmuNa","sejKC3a","Dev2zw50","n05twMzSuW","rwvOt1K","DhjPBq","qwjVCNrfCNi","uvjhsg8","x3DHAxq","Dw5KzwzPBMu","Cg1ICuy","CLnhywm","CgvYC2LZDgu","A3LZAfe","t3PjEKK","ywWGy3vYC28","tLrkAeG","wLnHqLq","t25zA0e","z2f5Dg0","AgHivha","yMLUy2y","swrUEg0","uefNsgO","DuvhuhK","ihn1y2nLC3m","Bu1ltei","BfrPBwvVDxq","B3Dmv3G","DKv2ELm","y2HlB2u","t0Dstge","B2jyy3O","DfvHBKe","CIb0DhDjra","DgvmB2Djre4","AwDHDg9Yt24","C2vYDMLJzs0","DNvpAw4","BM12zwO","AefNAhK","A1jXs1u","rwrzAw4","vhL4CwO","vwDptvy","AgfUz2u","x2rPC3bHDgm","Beritfi","yNvMzMvYzwq","ysbTDxn0igi","ywXSq3vYC28","y2LSDKS","BMCGDxjSoIa","sgPyr0e","x3jLy29UBMu","Aw5Lza","x2rLC3rYB3K","BgvY","mhW3Fdj8mhW","Ag5Nzw4","zwnQrw0","qujWseW","ywjVCNq","su5Wq3q","DMvY","v3nAuNq","B3L6EKi","u2HHCMvKv28","A2LtANq","BgzgB0i","x21LC3nHz2u","Bg9ryKC","AfHKyNa","AxnmEwG","DKrsBM0","wK9TtwW","B0vewgO","q2j0ALG","sevpvvK","u1zNtxi","CNjVCK1LC3m","zgvMAw5Luhi","wMjzuK8","ywDLu2HVDW","ywPtAve","BwLUAvbYB2C","ign1CNnVCIa","tfHrr0S","v0nzwee","tg9JAW","DhjPzxmGCMu","y2rlvvG","vxjoExq","uw1kExK","ywrKt25L","x3nLCuLK","yKvuuhG","yxnZAwDU","nNW1Fdj8ma","x2DLDeLUDgu","yxbWBhK","x29Uq2XVC2u","lcbOB3n0BMe","Cw9Z","y3HQvLO","q3Pnwgu","zeLZC3K","EMnfCMm","wgvvtha","uundq1m","y3DHCfK","Cxryseq","BM9Uzv9UB24","wfLmBem","CKnmvhO","uhjPBwfYEuS","B3nLrxzLBNq","zgf0yq","z2v0qwXS","uxrsv2y","BhrPCgXLihq","x2n1CNnVCK0","BwvZ","zxHWB3j0CW","r21Mu2u","DuTtqNm","m3W0Fda","yMfSrxzLBNq","ywrKzMq","AKvAt04","zMXVB3i","C3vIC3rYAw4","BgLUzq","BgvUz3rO","ue1xsKO","yNL0zu9MzNm","q29UzMLN","BwvZC2fNzq","BuzhEKG","q09otKvdveK","mxWZFdj8nhW","sLrrqvi","EwXcDMq","vM9Jsgi","vLLOExO","DLP1v3C","mtzPvuTHs1C","EMTuAuW","Dhj1y3rVCIa","zK5zsuK","zKP0B0O","yNbhz1a","x19LC01Vzhu","r2zTwum","zwXQthi","vgT2Bwm","EfL1wKu","DxHLuMO","x2nVBM5Ly3q","EMnMugS","x0vysvnu","zgvSzxrL","CMvZDwX0","ze94yK8","x2LZqNjVD3m","q1fLvgC","y2fSBa","B2zMBgLUzq","wML0vu8","y2XLyxi","z2vjBMzVu3K","rwHsv2C","qxbnANC","r0vntg8","uevUsxy","AevfvLq","EwDtyvm","BvfUu1C","zgvS","whfHqKG","DgLLCKPtt04","igzPzwXKoIa","yM9KEq","Bwfztvu","B3jpBMXPBMu","vwTouvy","z2vY","C3vJy2vZCW","zMjmtgC","tfnhs1G","Eejfwwq","zxjHDg9Y","D24GCMvHC28","Ewf1Awu","z1LNAhm","q0HyrhO","t1z1y24","zsbHihn0CMK","D3Pmsue","CMvHzfvjBNq","B2n1sfe","AwjlyMe","Cu5vuue","D3jPDgvvAw4","zwrPyxrLBhK","q0Xpu0ve","AvjjweW","u0HvsNa","x2HHBMrSzu8","uxnAwNK","DhDVCMTdAge","rwXMBvu","zwnVBM5Ly3q","sfLxC3e","shHJDLm","x2vUzhbVAw4","t0LcCMS","tMzrCha","AML6Dhm","rhrIB0W","yNbeqM8","EMLOwuG","zMXxvMu","yw5Hz2vY","yw1LoIa","Dg9Iwei","yKXABMK","C2vYDMLJzq","yNLL","icSG","B25Uzwn0Aw4","yK5SwKG","z0jPq2O","C3b3zK0","yKjWBNO","suvtx0vsuK8","CMfNzvn5BMm","C2v0zgi","ug5YCNG","yKXvDwW","CYbPBNn0yw4","sfPqvwu","yvn6r0G","qMjfEKO","CMLXEwu","z0v3rg0","ALHeuxG","s1PdCfi","zxnmtLK","zMPcBLq","DgHLBG","CxHgAxi","v2vPEgLUsLm","C2nYAxb0","zK9wAfO","qxbIBK0","zhzYwLu","Dg9oDw1Izxi","zMLN","zMLUza","yxjiEKC","B2nRzxrtDwm","ren3s0m","CK92yvi","x2nSzwfYvgK","mxW0Fdn8mNW","vKHltfm","r3HHBxu","yNvMzMvY","B3vUDa","sMzWqKK","tfveqM8","uKr5BhG","reTTwfO","B0Lsvue","x2nSzwfYugK","DgvZDa","x2LZsw5PDa","BhrOAgO","x29UrxjYB3i","BeHHBMrSzxi","BerXt1m","yxnL","Cgf5Bg9Hza","sLnLsfi","C3bSAwnL","x3bYzwzPEa","AgvKtwf4uMu","uMvJB25Uzwm","rNnIueu","r0jSDxe","ihrPBwvZ","rhnIqwi","shDgvuS","y0HpreS","DxbKyxrLq3u","sw5TBKS","EwfetM4","Aw5PDcbrB1m","x3nLBMrby2S","Dxv6Exm","Ae1LC3nHz2u","CMvHzhDYAxq","uxfxtKW","tfrdu0C","rMnevNe","CMfUzg9T","quPwwwy","BvvbEfq","DhbizwfKzxi","Cw96zfe","vMvJs0G","CgfNzxnOB3C","yNL0zxm","ywDLrxzLBNq","yujhwfu","u3rzwhu","D1fQzhO","tK9csfi","s2jqExa","rxbKChe","y2XVC2veqG","CMPsyLy","AhffzLi","DunUvKG","tMPdDKm","Bhb3vei","u0jKzKu","wNHmDwC","BfPmufe","u0DTqLy","A2Twr2S","x2nYzwf0zvm","weDSwhG","ndqXmda0ALzIC1zo","B2nRzxq","u2fIy2y","B3nLza","CKrnvw0","q291BNq","D2rqquS","Dfrzue0","u1HfuNu","Dw50","y3ruAw1LB3u","uhPoz3G","ywzL","zMzMzG","DunVDg0","y29TCgXLDgu","CNvdsMW","uhLUrwy","vhDVALu","sNHQCNO","yLnpy3y","zMroENu","wLnhzuC","zMvY","vfbREvO","zu1VAKW","rwPbAeK","AwXK","Ahv3s0S","B2zMC2v0","DhjHBNnHy3q","u0PKru4","BvD3BLC","ENr6y1q","tMfAqKW","tuXHuKy","BNruCMLLC0m","uLjpuG","v1ndAgG","Aw5Ky0e","rNjVBNrPzxi","C3rLBMvYCW","yNH5tK8","zw5HyMXLvhi","AMnfq3K","DfDiwuW","CYbWyxjHBxm","BujWr0u","zNjVBunOyxi","C3rYAw5NAwy","A3n5vxq","Ahr0Chm6","t3PeqxG","vxrtze4","Eg9gqKW","ugvurxa","q29WtgO","mxWWFdj8nhW","ywnR","DM5Ozei","vuvqrvO","we5qzwy","DhrbvMW","ExnRBNe","yxLst0G","y2vZC0HHBMq","thPKu3a","BMrWB2LUDfq","ywXSB2nvBNm","wxr5A2i","BMfTzq","C3bSAxq","Aw5N","D0HhAKK","suXyww4","zMLSDgvY","x2DLBMvYyxq","rg9Oq0y","AxnbCNjHEq","A1zdBKe","zMzmAw5L","o2nOyxjZzxq","zfj0vge","Cg93","tw9KDwXL","y2Lzt2u","zv9ZDwnJzxm","Ae9Wzw5fDMu","Cgu6ia","AgfZ","t1bftG","mZK4mJK2mhffEwLgqW","uNvNCgK","CMTLCKDSB2i","yxjYyxLIDwy","y2XLyxjtDg8","rxzovge","rLPPrxy","v0rMzNq","CMjPueW","C2v0sxrLBq","CwjcvNm","tLLhzMG","ruv1z2S","qMTZuLy","B25SAw5L","zhnPCg0","BM93","y2HnyxHuCMK","q09ZveW","y3r4","B3bLBIa","yxjttMi","y2XVC2uSihC","x2XPC3rLBMu","x3nVy2TLDa","CMvZB2X2zq","ExndEwe","AMH2thC","CKzOrxe","yw9JyMC","x2rYB3bhBg8","BxfOteK","DxH1wKW","u1LIyNK","ywDLsgLKzq","uwrTshK","wuL4B2C","B2nRzxrgywK","Dhn4t3O","x3jLywr5q2W","swPiAvm","nxWZFdz8mta","zMPjyvO","tuD1DfC","zfDVCMTLCKC","vKLVwhu","ywnRDxbfBMq","Bwf4uMv0CMK","u2vXsuq","DMvYC2LVBMm","l3DZl3yY","wwLbvK4","tvfwC0K","Bwf4tg9ZC0m","CM1Nzg0","A2v5CW","DMfS","y29UBMvJDca","qMDowKW","zgjVAva","z2vtEw5J","Dg9iyxnO","tg9Nsuq","BKXPBMu","D2fZq2XLyw4","zxjYtM8","BgHMwhq","quvREvK","DKz5AM8","vuTws1u","DhjPzxm","B25nzxnZywC","sfb3y1m","B0fpy3y","ExPNvLm","C0jAqLe","uKLZrfe","A1Dts00","v0rgrM4","u25iv1q","rvbfA0O","surKrLK","zfbnCLu","tNLuB1C","lcbxzwjtB2m","DMvUDa","uxvLDwu","ruffv1C","Dhvrv3i","BwfW","BuvxsNi","zMLSzw5HBwu","rwnnywG","AvPOrK0","qLPlA3y","BMrLEa","rfDMwKe","CM9YrxzLBNq","Ef9MCM9UDgK","B3bLCNr5","CgLUz0LUDgu","A2HvwwG","B25fCNjVCG","BMvLzf9Hy2S","wxnxz0q","CNnVCKzPBgu","thvmELq","svH1vhK","C2vYDMvYvgK","tKDFrvjst1i","DgzytxO","wfvzzvm","AwXLx25HBwu","C3rHCNq","jMPZy2fSBgi","sMn2zvK","B3HmqMK","tLLZs2G","zxjYB3i","uwPwv0i","wvfXwNm","DeLUDgvYy2u","Bg9IywXty28","AervAxG","tKLHweq","x2LZtM9Kzq","BMPZzgC","De1HBMfNzxi","DxrMofDYAxq","DMLJzuLeig8","y29Kzq","AxnmB25N","tg9NsurozxC","A1nOugW","zvj6tgi","zM9Yy2u","DenTEhq","wvzfA2G","vgLTzw91Da","rLDt","rxnRvu0","whH3DMC","sM5xDgG","t2jQzwn0","uurpt3i","shb2sMq","zxH0ugf5Bg8","yw5Nzq","ywrK","C2XPy2u","DgLUzYbZzxi","zgvIDwC","Dhr3Awq","we5PAgi","yxGGCMv0CMK","ywX3yxLZ","zv90Aw1LB3u","wxnur2W","DM1LAvy","DeLK","AwrI","DgLTzw91Da","D2vI","z2v0","twvZC2fNzuu","tK5tzhC","rKHyCgW","yvrZvgS","wLj4r2y","Aw9Ul2PZB24","DxjS","t1r2BxC","zwn0","B25JBg9Zzq","B2fK","sMPOv20","tMfTzq","y0zrEM0","z2vhAMS","vgf2q0e","y291BNq","x29UtwvZC2e","Evbxyxm","zgjJzuO","B0fVq1q","AgrRy1e","z2Tsufe","C09Luei","AwfTB2y","z0Ddsvm","x1fVu01HBMe","yMfJA3vWigu","Cev1ufy","x3bPBMDmB3m","sLnptLa","BwHNANq","tuHqyva","x3vYBa","BMCGzMfPBgu","zcWG","BMnVzgLUzW","zM9YrwfJAa","r3r2vgG","B2XQsg8","zxj2AwnL","x3bPBMC","swLRtfK","DLLurKm","Cgf5Bg9Hzeu","z3LXq2K","EvHnEeW","Dw5ZAwDUzwq","ExLPzKu","CNvRD3m","rvLYB2u","Aw5JBhvKzxm","re5uzLu","CuHSwhy","y3jLyxrLt3a","AM9MAwS","ALbPDwK","B2XKvMvYC2K","q2vQr3q","C0LPtfy","wMnsB0u","ywLJwgC","CMvZzxrfBMq","Aw5KzxG","r0zLB3O","zMzqEwu","CeDkue0","Aw9U","u2TPCcbWyxm","z2PRBg0","zhvqA0u","rvvNtgK","A2jrsfC","C3rVCMu","yLbsqNm","Aw50zwDLCIa","x2LZtwLUAvC","CfnptKe","CeflD1y","B2zM","x2HHBMrSzvi","sffMu0O","DhLSCNm","CfHfEgO","AeHjv2u","quXwzKm","mdaWmdaWmda","ExPQwgW","CgLUz19VBMm","Eg9KsxG","we1fCLO","rxbKAMy","x2jPBMfYEvq","CvLzzMu","CM92AwrLige","z25cyuq","CMvUDevUzha","AM9PBG","mJi0mdrhqK1ODfC","shLHweW","wwTKrxq","ChvZAa","u0PpCwO","ChjVDg9JB2W","tgLZDgvUzxi","C29Tzq","ugvmCvi","yMLUza","DLLWyu0","ELvgD1G","x3bYB3rVy28","Aen2rva","CYbHBhjLywq","CKDVwwC","AxnszwfKEq","CMrNBei","CMXJA28","x3DZ","BMfkD2y","y01jweS","BvnXzMu","sMP0ELe","x3fVC0rc","BM5Ly3q","ufvQqNe","zvfvsNy","ruTSzNm","wfvovhC","vMDcq3y","vgfN","y2HHCKnVzgu","DMfSDwvZ","yLLbAxa","qNf1EhO","x2LZv29YA2u","EMHnBLu","sgveDfO","C3rVCcbPBw0","mhWYFdr8m3W","svPcB1a","vxbKyxrLq28","x2rPC2nVBM4","q2f4yve","BwLUzW","zgvJB2rLzey","A1n0yxr1C0m","BgLZDgvUtMu","yMT1BgO","BMrWB2LUDca","swXPsw8","C3vIyxjYyxK","x3jLBw92zvC","EKrZwMi","Axnby2TdBgu","ohW0Fdv8oxW","r3rMvMy","vNDmDNe","zvPNyNK","z3rsswC","vhfjww8","t1rkEKm","CMLLC0nVDw4","rujUrKK","zwDuuw8","ExPOtwO","r1D2z2e","ywHyz2u","vhnQugC","tfD6EeC","AxnJtKW","x2rItMfTzq","EKvIC1G","AujQCva","uLvsBwy","BvDHDxm","tuDXrLC","zNjVBNrPzxi","Ec11C2uT","yxnJCMLWDa","y09Wzw4","Dxrjza","tgDhv1G","D3nZoI8V","BwvY","tu9jrgm","EfrwuwK","yNnlDNa","EhvcA2i","BML0AwfSAxO","BMDuAw1LCG","BwLZzq","CLbTAMu","Cg9W","vwDHy3C","sLLyy3m","uMXcvwi","r21kBeG","AMfbwMm","CNzHBa","ihjLy29UBMu","zgDKq1y","ExbL","BxzgDMC","wwTYDKm","Ag5fugS","u3rYyxrLz3K","qvjuBuS","CK5OreG","CMfTzq","DMvYC2LVBG","v1Lxug8","CgXLyxnLiha","x29UugfNzu4","DfLjyw4","rKfUtwK","y3vZDg9Tshq","ExH2r0i","ugDks0e","DhzhExi","q29Kzq","sM55uhm","yMfTyLe","ihzHBgLKigq","zhfZzKK","EuXsDfa","wu95vxy","shbdqui","y29UDgLUDwu","uMvHzcbWyxm","zw5HyMXLuw8","yKTJCNG","A053yxy","yxrLq291BNq","C2fNzq","CMfTugfYyw0","BhvUzuq","DcbVzIbYyw4","y29Uy2f0","AuHxsxi","BLbHAwm","A3Hjufy","zvvYBa","s2rtsMq","u3nduKG","B3v0sw50zxi","mZCWmJqZoffqs0PyDG","DvfkBLq","BxnN","Bg9N","mxWWFdn8mNW","Bg5NAgG","rgvKAwnHDgu","Dgv4Dc9WBge","zcWGDw5RBM8","mtCZoeLVwwHoqG","tennBNe","BwfRCgy","rg9Ozxa","venRvve","yxbWBgLJyxq","yuHmv2K","z2v0qwXSs2u","x2rLyNvN","zwvKzwq","BezSDxnO","zxmGCMvHy2G","zw5JB2rPBMC","CMvTB3zLrxy","zNjVBu51Bwi","B25LCNjVCG","BNrLCG","CNLqEhy","CgLUz09Uy2u","y3jLyxrLq2W","v01TswS","z2jnr3G","zunnse4","B25VCgvU","teLzzLC","EMDIrhm","tfbYBNK","qMPXzeq","Euj1sLC","B25tDgfYDfi","vw5Oyw5KBgu","EwvjBuq","wgjsvM0","BMv3vMvYC2K","CgLUz0XVC3m","sxfPwhG","AxnrB1nby2S","CgjICdi","B25pCgvU","y29UBMvJDgK","q09oveLovuu","wwfwuMe","A2rNAK4","Bw5TCvu","nxW0Fdj8mhW","uvj3CKG","qvnTB1i","uu5qsw0","EK9Wz3y","AwXSihvZzsa","DuHtCxu","y3PMzuW","ufjptgy","Chv0","qvDgvMS","yw5ZzM9YBvq","y2HLy2TdDxi","C3H4Afi","EfPhquS","B2LUDfjLywm","Eev4r2i","AMvJDfn0B3i","CLrwtLq","ywXS","tgz3t1K","vxrmt2u","s2vTCw8","ihrVihjLDhi","A3DVr1i","zw5XDwv1zq","wgHKCgq","vKXLEw4","y0X3BNy","D2Xry2u","z2v0u3rVCMe","CMH0Cgq","BxnNsuq","vMLdBeS","A1PyDLm","CMvJzxzPzwq","y3vYCMvUDeK","s1LTvMu","rg9sALO","y3vYC29Yx24","zgLZywjSzue","CMvKDwnL","y3vYDMfSDwu","CMTUDMe","Cg9PBNrbBMq","qNjPzgDL","x3DZsw5ZDge","tMTfA2m","seHnrgi","AMrkExu","qKrNEwC","D3jdrfy","C2v0q3vYC28","quTzDKO","yMLUyxj5","De9Rrui","C0nVDw50zxi","z2v0t3DUuhi","AxPgEKe","y3futeW","EKv4Dfm","Dg9tDhjPBMC","DurMAfO","wvDTyLG","Aw47y2HHCNm","vNfwCvK","z2v0sxrLBq","t1bftL9fuLi","re9Ry0q","D0Dcs00","y29UBMvJDfm","D3P4z2y","r1POvw4","BefhyxC","uvb5BgS","rwPSB2y","Dw96yxK","q3vUAxe","AgvHzgvYCW","EgTtu2i","CufmrNa","AMnhBNa","ve9MAM0","wKP2uvq","x3bHDgHlzxK","vengq3G","veXtuuC","teLzzgW","zKnUthe","rfvtrwi","runPDeG","B3nttva","D3HzCK0","CMvJB25Uzwm","mtjov0DyrMG","C0HvvwS","wfDUrfC","vhPQwgS","sw5kuxG","u3ffrKq","zxjFBxnNAwq","BKXAANq","C3nHz2vfDMu","yLP3wfO","tgnyr2C","tufyx1jfvfi","B25tDg9Wsw0","y2f0y2G","vfrerM4","C3DLB3y","Bg93","zNjHBwvuExa","sND2BKm","tMXjzKe","uLDWBwi","Dg9hzw5LCMe","Dg9mB3DLCKm","zgf5q0W","yu5su3y","q3vZDg9Tq2W","BK9wBeW","AgLNAa","x0rctMfTzq","zgLZCgf0y2G","yNL0zuXLBMC","DNbxy00","r0D1vgi","wffuwvq","zw50","u052CfK","ExroCeu","y29UBMvJDeu","y3nTuM4","BezmtMK","B3bLBKrc","uKrnuK8","AwXLtMfTzq","vujYwKm","zNvUy3rPB24","x2LUAxq","Aw5KzxHpzG","z1rPBwvVDxq","zxrxB3jRq2G","vKvOse0","DxnLCKLW","wgL0D08","AMnVB1O","B3j4C1C","Cer3q2y","B3LpD3e","yurvrNy","t2PfugC","ChbL","BwntDw0","y3vYCMvUDeu","swnAAvm","mNWWFdn8nhW","ihrPBwvVDxq","C09Ws04","yxjvC1O","rfbqwK8","DNfZEwG","CMvJzwL2zwq","zg9Uzq","y2j5DgK","ihrYEsbYzwm","D3jPDgu","zgrjrcWGzgu","uKftANy","C2vUza","x2LZtwLUAvq","nZy4rxjoEw1j","u2rjCwu","C0XPC3rLBMu","zNjVBujPDhm","CLDpvgy","Ahr0Ca","y3vYC29Yx2y","tw9sqLO","z2v0q3vYCMu","we5Zu3u","ywrKrxzLBNq","D3m6lY8","u2LSALu","y1jdzuS","tM1srMK","AhH2rfy","vfLvvem","A2X5zvC","t3PWweC","AhHcv2W","Dg9Y","z0vvEvm","sKjhCg4","ruvJsw0","r0f0tLy","AwjOyum","B01dDuG","DcbSAw1PDa","BNrfsgq","Bwv0Ag9K","y3jLyxrLuMu"];return $o=function(){return t},$o()}Wv(Rx,{deleteDB:()=>eS,openDB:()=>Qv,unwrap:()=>es,wrap:()=>Ft});function Qv(t,e,{blocked:r,upgrade:i,blocking:o,terminated:c}={}){let d=L,u={uCotm:function(p,_,v,w,E){return p(_,v,w,E)},ztzcT:function(p,_){return p(_)},hCvEP:function(p,_){return p(_)},ffPye:d(1739),hhHTp:d(801)+d(372),lfFoB:"upgraden"+d(1179),ruCJl:d(1658)},f=indexedDB[d(1582)](t,e),x=u[d(694)](Ft,f);return i&&f[d(1395)+"Listener"](u[d(396)],p=>{let _=d;u[_(675)](i,u[_(694)](Ft,f[_(489)]),p[_(973)+"on"],p[_(1203)+"on"],u[_(1027)](Ft,f["transact"+_(983)]))}),r&&f["addEvent"+d(1020)](u[d(677)],()=>r()),x[d(577)](p=>{let _=d;c&&p[_(1395)+_(1020)](u[_(981)],()=>c()),o&&p[_(1395)+_(1020)](u[_(347)],()=>o())})[d(1321)](()=>{}),x}function eS(t,{blocked:e}={}){let r=L,i={LaoDm:"blocked"},o=indexedDB[r(1754)+r(1552)](t);return e&&o["addEvent"+r(1020)](i.LaoDm,()=>e()),Ft(o)[r(577)](()=>{})}function Ix(t,e){let r=L,i={HOyHK:r(629)+"e",YsWgD:r(1761),UtLOe:function(f,x){return f in x},HtpTp:function(f,x){return f===x},ASmoR:r(1540),jotJT:function(f,x){return f!==x}};if(!(t instanceof IDBDatabase&&!i[r(1235)](e,t)&&i.HtpTp(typeof e,i[r(1216)])))return;if(Ho.get(e))return Ho[r(915)](e);let o=e[r(1623)](/FromIndex$/,""),c=i[r(1693)](e,o),d=Px[r(967)](o);if(!(o in(c?IDBIndex:IDBObjectStore).prototype)||!(d||Cx[r(967)](o)))return;let u=async function(f,...x){let p=r,_=this[p(691)+p(983)](f,d?i[p(1445)]:i[p(856)]),v=_.store;return c&&(v=v[p(979)](x.shift())),(await Promise[p(1233)]([v[o](...x),d&&_[p(1377)]]))[0]};return Ho[r(1744)](e,u),u}var Cx,Px,Ho,tS=kx({"node_modules/idb/build/index.js"(){let t=L,e={WYWPo:"4|3|5|1|0|2",bSOcv:t(1223),INpCt:t(900),wgGBe:function(o,c){return o(c)},HwszM:function(o){return o()},xZGAK:function(o){return o()},DKmXZ:"getKey",arHzG:t(445),IEaAF:t(1177)+"ys",HBYTu:t(932)},r=e[t(1126)][t(732)]("|"),i=0;for(;;){switch(r[i++]){case"0":Ho=new Map;continue;case"1":Px=[e[t(681)],e[t(390)],t(488),"clear"];continue;case"2":e[t(1579)](Jv,o=>({...o,get:(c,d,u)=>Ix(c,d)||o.get(c,d,u),has:(c,d)=>!!Ix(c,d)||o.has(c,d)}));continue;case"3":e[t(1586)](Sx);continue;case"4":e[t(1228)](Sx);continue;case"5":Cx=[t(915),e[t(600)],e[t(587)],e.IEaAF,e.HBYTu];continue}break}}}),nS={idb:function(t){let e=L;t.exports=Promise.resolve()[e(577)](()=>(tS(),Rx))[e(577)](function(r){return r})}},Ax={};function q(t,e){t=t-308;let r=$o(),i=r[t];if(q.MrbiJX===void 0){var o=function(f){let x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",p="",_="";for(let v=0,w,E,I=0;E=f.charAt(I++);~E&&(w=v%4?w*64+E:E,v++%4)?p+=String.fromCharCode(255&w>>(-2*v&6)):0)E=x.indexOf(E);for(let v=0,w=p.length;v<w;v++)_+="%"+("00"+p.charCodeAt(v).toString(16)).slice(-2);return decodeURIComponent(_)};q.swiWFE=o,q.nYaWbU={},q.MrbiJX=!0}let c=r[0],d=t+c,u=q.nYaWbU[d];return u?i=u:(i=q.swiWFE(i),q.nYaWbU[d]=i),i}function Bt(t){let e=L,r={eFxtc:e(592)+"0"},i=r[e(1566)][e(732)]("|"),o=0;for(;;){switch(i[o++]){case"0":return d[e(450)];case"1":var c=Ax[t];continue;case"2":nS[t](d,d[e(450)],Bt);continue;case"3":var d=Ax[t]={exports:{}};continue;case"4":if(c!==void 0)return c[e(450)];continue}break}}(()=>{let t=L,e={cmRyB:function(r,i){return r>>i},huwKK:function(r,i){return r|i},CejGt:function(r,i){return r!==i},mnYCF:t(929)};Bt.d=(r,i)=>{let o=t,c={UzFVU:function(u,f){return e.cmRyB(u,f)},bxGWO:function(u,f){return e[q(689)](u,f)}};if(e[o(974)](o(929),e[o(1619)]))_0x55fa95[_0x341380++]=c[o(1633)](_0x5f3941,6)|192,_0x5750cb[_0x348bd5++]=c.bxGWO(63&_0x56c084,128);else for(var d in i)Bt.o(i,d)&&!Bt.o(r,d)&&Object[o(408)+o(851)](r,d,{enumerable:!0,get:i[d]})}})(),(()=>{let t=L;Bt.o=(e,r)=>Object.prototype["hasOwnPr"+t(851)][t(493)](e,r)})(),(()=>{let t=L,e={jaAZc:function(r,i){return r!=i},QBhze:t(745),ZcRoE:t(479)+"le"};Bt.r=r=>{let i=t;e[i(1113)]("undefined",typeof Symbol)&&Symbol[i(1275)+i(1045)]&&Object[i(408)+i(851)](r,Symbol[i(1275)+"Tag"],{value:e.QBhze}),Object[i(408)+i(851)](r,e[i(976)],{value:!0})}})();var Re={};(()=>{let t=L,e={qxFir:function(a,n){return a(n)},LzdSp:function(a,n){return a+n},rPmje:function(a,n){return a+n},iHWIr:function(a,n){return a*n},LCMnq:function(a,n){return a*n},NkEkc:function(a,n){return a(n)},InmnK:function(a,n){return a+n},dqsfI:function(a,n,s){return a(n,s)},tsxOz:function(a,n){return a(n)},qeWDB:function(a,n){return a+n},yyifE:"0000",LTCSG:t(674),nCCoK:function(a,n){return a(n)},EwpIN:function(a,n){return a(n)},LSbzA:"00000000"+t(1002)+t(1002)+"00000000",YtLRp:"error",vckyb:function(a,n){return a>n},COsTL:function(a,n){return a!==n},qHlXv:t(480),iBjqP:t(1267),kdgjN:function(a,n){return a>n},Tkvmc:function(a,n){return a===n},UEPEZ:"SmJEh",YsTGl:function(a,n){return a<n},TOfjm:"oOoZh",IDdFY:function(a,n){return a-n},ZSpba:function(a,n){return a<n},riqye:function(a,n){return a-n},UtSdN:t(1401),cooCn:"ebGVk",Yhaal:function(a,n){return a!==n},GnBHn:function(a,n,s){return a(n,s)},aDUFv:function(a,n){return a(n)},ZbYRO:function(a,n){return a(n)},qHBxP:function(a,n){return a>>>n},kiSjt:function(a,n,s){return a(n,s)},RURmf:function(a,n){return a&n},InJQx:function(a,n){return a===n},sOePB:t(1727)+t(1644)+t(508)+"key",ZJvQT:function(a){return a()},lDHLR:t(430),LJrUm:t(1594)+"id",kWSKM:function(a,n){return a!==n},BksRV:function(a,n,s){return a(n,s)},HHMDb:function(a,n,s){return a(n,s)},LfwOY:function(a,n){return a!==n},PPmXn:function(a,n,s){return a(n,s)},AFhNd:function(a,n){return a(n)},cwapY:function(a,n,s){return a(n,s)},tYIan:function(a,n){return a(n)},aPhHC:function(a,n){return a!==n},LWzxG:function(a){return a()},IhycZ:function(a,n,s){return a(n,s)},XWnDW:function(a,n,s){return a(n,s)},zQGuB:function(a,n,s){return a(n,s)},uCnVH:t(683),ciYOe:t(1291),oEDXj:function(a,n,s){return a(n,s)},SnHWT:function(a,n,s){return a(n,s)},qgECf:t(1518),lAGaw:function(a,n,s){return a(n,s)},OxwEL:function(a,n){return a!==n},pLxkB:t(1583),NTJhH:"jvZmT",Kemqo:function(a,n,s){return a(n,s)},QmJyy:function(a,n){return a(n)},EcMah:function(a,n){return a(n)},Dizev:function(a,n){return a(n)},DWfZA:function(a,n,s){return a(n,s)},NjCvC:function(a,n){return a(n)},TbiFw:function(a,n,s){return a(n,s)},lsKny:function(a,n){return a(n)},ypapY:function(a,n){return a(n)},sNYTT:function(a,n,s){return a(n,s)},pFhnl:function(a,n){return a(n)},zhMnU:function(a,n,s){return a(n,s)},gaytm:function(a,n){return a&n},yzhMj:function(a,n){return a===n},bZwXZ:function(a,n){return a===n},JcveY:t(1727)+t(1644)+t(508)+t(814),jLiGh:t(1727)+t(1644)+t(508)+"service",XGlXx:"Missing required"+t(508)+t(1414),yzgVS:function(a,n){return a(n)},ysknq:function(a,n,s){return a(n,s)},tlJfr:function(a,n){return a(n)},xuBkb:function(a,n){return a>>n},XxWVU:function(a,n){return a>=n},cdKUX:function(a,n,s,l){return a(n,s,l)},YKYSt:t(1511),VWfIS:"Byggq",dRtTa:t(1130),EskUM:function(a,n){return a+n},QURhO:function(a,n){return a>n},YbwVZ:t(1144)+t(1412),ApMjw:function(a,n){return a+n},LUDBo:function(a,n){return a<n},GBluq:function(a,n){return a===n},EdYin:function(a,n){return a+n},EqJpJ:function(a,n){return a!==n},klyeW:function(a,n){return a<<n},LqtkR:function(a,n){return a&n},Tlxzr:function(a,n){return a==n},gnBaD:function(a,n){return a&n},iNSXp:function(a,n){return a>=n},SXERu:t(781),lpwTB:function(a,n){return a+n},vmeiV:function(a,n){return a+n},ZOmMl:function(a,n){return a+n},YOyUv:function(a,n){return a&n},YkrvC:function(a,n){return a|n},rGoYg:function(a,n){return a|n},rbiPL:function(a,n){return a<<n},NspHb:function(a,n){return a>=n},QNPIm:function(a,n){return a==n},RlBUb:function(a,n){return a&n},TwojU:function(a,n){return a>=n},TzjXk:function(a,n){return a+n},zihYH:function(a,n){return a+n},eljLr:function(a,n){return a+n},GtfVf:function(a,n){return a&n},HpCAB:function(a,n){return a<<n},FRjzN:function(a,n){return a|n},fjIaZ:function(a,n){return a|n},RIsDQ:function(a,n){return a&n},OzIzI:function(a,n){return a&n},SHUJp:function(a,n){return a<n},IXuTy:function(a,n){return a>n},jhvLw:function(a,n){return a+n},vFyjo:function(a,n){return a&n},hHIWe:function(a,n){return a<=n},hqEfR:function(a,n){return a<n},uuzys:function(a,n){return a<<n},mhgjt:function(a,n){return a<n},EUgLi:function(a,n){return a<n},eZgby:function(a,n,s){return a(n,s)},dOxbO:function(a,n){return a<n},IgRUE:function(a,n){return a-n},OrCam:function(a,n){return a<<n},bzwVu:function(a,n){return a<n},YiAVN:function(a,n){return a&n},vYwvW:function(a,n){return a===n},BRYOA:function(a,n){return a<n},GoQie:function(a,n){return a|n},vuOin:function(a,n){return a>>n},vZuWw:function(a,n){return a&n},Ugacw:function(a,n){return a|n},wxYrM:function(a,n){return a&n},jEZON:function(a,n){return a|n},dIssy:function(a,n,s){return a(n,s)},JjhWm:function(a,n,s){return a(n,s)},eQEtn:function(a,n,s){return a(n,s)},kxIPV:t(1075),dPMrU:function(a,n){return a(n)},LPrqg:function(a,n,s){return a(n,s)},vMMUG:function(a,n){return a|n},zExtS:t(719),QCCCS:function(a,n){return a&n},rknva:function(a,n){return a&n},vDRnm:function(a,n){return a&n},TTDFn:"QqdoY",wPDve:function(a,n){return a&n},VzYdA:function(a,n){return a&n},QtRWf:t(1417),yPWas:t(711),qNUQA:function(a,n){return a(n)},VTPJw:t(311),GWvga:function(a,n){return a&n},DDGmA:function(a,n){return a&n},Xhdpd:function(a,n){return a<<n},chKoe:function(a,n){return a(n)},SqEFD:function(a,n){return a&n},NmRFi:function(a,n){return a&n},EhRWg:function(a,n){return a<<n},pAKwV:function(a,n){return a<<n},DDubH:function(a,n){return a>>>n},NfQpp:function(a,n){return a===n},gyqCi:function(a,n){return a===n},YIxog:function(a,n){return a<n},wesHr:function(a,n){return a<n},BeeKO:function(a,n){return a+n},jofik:function(a,n){return a+n},loQbG:function(a,n){return a|n},nnqmz:function(a,n){return a>>>n},DoRjZ:function(a,n){return a|n},HXHaX:function(a,n){return a&n},izFzA:function(a,n){return a>>>n},wrCDV:function(a,n){return a!==n},gEwDm:function(a,n){return a&n},EBnFI:function(a,n){return a|n},jcooZ:function(a,n){return a&n},tTYPM:function(a,n){return a|n},QRGHo:function(a,n){return a!==n},ktmGI:function(a,n){return a|n},brLbp:function(a,n){return a&n},egTQo:function(a,n){return a&n},Giclc:function(a,n){return a|n},RWpmb:function(a,n){return a<<n},buuXq:function(a,n){return a|n},RDylx:function(a,n){return a|n},rDMUm:function(a,n){return a<<n},eQUJv:function(a,n){return a|n},tvDWq:"ViClK",SsCRH:function(a,n){return a===n},HjXGA:function(a,n){return a|n},Tyxqj:function(a,n){return a<<n},VHKLS:function(a,n){return a>>>n},HKPyU:function(a,n){return a<<n},UgOMV:function(a,n){return a<<n},QsZZy:function(a,n){return a>>>n},ibKba:function(a,n){return a&n},SLalx:function(a,n){return a&n},lFLNi:function(a,n){return a>>>n},pEuPV:"kcris",DkzMl:function(a,n){return a(n)},zcErc:function(a,n){return a===n},geGjk:t(720),arSNb:function(a,n){return a<=n},wzLIA:function(a,n){return a>=n},vpWcM:function(a,n){return a+n},bPRBs:function(a,n){return a%n},XUYeS:function(a,n){return a|n},indcA:function(a,n){return a/n},LIYdl:function(a,n){return a*n},pGJPM:function(a,n){return a>>>n},FHXpl:function(a,n){return a>>>n},sexGH:function(a,n){return a*n},OTvmw:function(a,n){return a===n},oljHo:function(a,n){return a===n},SGmBV:function(a,n){return a>>>n},oyOwq:function(a,n){return a>>>n},ygSaS:function(a,n){return a>>>n},tkUbF:function(a,n){return a&n},kbQHW:function(a,n){return a>>>n},zDsZb:function(a,n){return a>>>n},JTQAR:function(a,n){return a|n},SNvpY:function(a,n){return a|n},wdPAK:function(a,n){return a<<n},oyzzB:function(a,n){return a>>>n},fkAWf:function(a,n){return a===n},tOkEB:function(a,n){return a+n},IcZiS:function(a,n){return a&n},iamof:function(a,n){return a>>>n},MGutW:function(a,n){return a&n},qbBVs:function(a,n){return a>>>n},fGrDR:function(a,n){return a&n},rNhDH:function(a,n){return a&n},TLSQG:function(a,n){return a>>>n},PROLf:function(a,n){return a>>>n},nOVlL:function(a,n){return a&n},QgaRC:t(1214)+"3|1",BVDvl:t(1707)+t(1704),JBGpn:t(1281)+"OR",XQTYT:t(466)+t(861),yLRtP:t(1725)+t(698),xkSSb:t(1563)+t(453),kNwav:t(1370)+"1",JfpBI:t(1739),xoFBL:function(a,n){return a!==n},jIfBv:"UfYFH",Ytykb:function(a,n,s){return a(n,s)},uJFOS:"LUkJN",BgNZL:function(a,n){return a===n},hngen:function(a,n){return a===n},wQjdz:function(a,n){return a instanceof n},ibhaC:t(1200)+"d error.",ZyIAi:function(a,n){return a+n},YnIsR:function(a,n){return a>n},cilvK:function(a,n){return a*n},addfd:function(a,n){return a+n},bBpnz:function(a,n){return a===n},gjklm:t(541),nEIXs:function(a,n){return a===n},jPiui:function(a,n){return a!==n},pmbqF:t(1365),LPIyk:function(a,n){return a<n},wHGjI:function(a,n){return a===n},XitwO:t(1582),cxjVZ:function(a,n,s){return a(n,s)},TCkUQ:function(a,n,s){return a(n,s)},rukws:"message",TWMhQ:t(850)+"er_qos",LPrny:t(850)+"er_qos_ack",pDwCf:t(850)+t(1496)+"k",khUYh:function(a,n,s){return a(n,s)},gLZhH:"x_frontier_ack_m"+t(1608),fjBnT:function(a,n){return a===n},HuJKE:t(1425),zUFwX:t(642),IjHiS:"cEIGt",sPiaK:function(a,n){return a!==n},jdJyu:"ZbFkN",PeLqR:"SXBDL",LSGKX:function(a,n){return a||n},ALVfC:function(a,n){return a||n},HBdsp:function(a,n){return a!=n},EcWZs:"undefined",mFGzH:function(a,n){return a>>>n},HZPUe:function(a,n){return a+n},iwpzJ:function(a,n){return a!==n},YSucq:t(1176),QpkwL:t(467)+"0",EjAhI:function(a,n){return a||n},gYghs:"next() c"+t(1439)+t(447)+t(1696)+"process",lpZIk:function(a,n){return a===n},hMbbs:function(a,n){return a+n},LIYfW:function(a,n){return a<n},ARTmK:function(a,n){return a&n},TavCA:t(1375),SJOqj:function(a,n){return a<n},HYWsq:function(a,n){return a&n},fJtoJ:function(a,n){return a<n},fbLLg:function(a,n){return a|n},hEEVT:function(a,n){return a<<n},Jyfsn:function(a,n){return a&n},pSONA:function(a,n){return a-n},VEhHM:function(a,n){return a|n},ElfmU:function(a,n){return a|n},Bquxz:"ylBvd",dgdCV:function(a,n){return a|n},aSzGH:function(a,n){return a===n},AWFVk:function(a,n){return a+n},rhtpd:function(a,n){return a&n},naJwf:function(a,n){return a>>n},GAtNV:function(a,n){return a&n},UgjZt:function(a,n){return a|n},gTNaB:function(a,n){return a&n},NYGfh:function(a,n){return a>>n},eBrMc:function(a,n){return a|n},ApbnM:t(1540),zskSL:function(a,n,s,l){return a(n,s,l)},ZRxGf:function(a,n){return a instanceof n},BHSRU:function(a,n){return a!=n},dvrZU:t(1251),UBrZC:t(1168)+"in;chars"+t(1497),Rugpi:t(1366),ggVCV:function(a,n){return a===n},LuLzT:t(1600),QPylk:function(a,n,s){return a(n,s)},QRwrH:function(a,n){return a!==n},bETPx:function(a,n){return a>=n},CUniM:t(1599)+t(1677),SYbby:"text/jav"+t(1094),jcGnp:function(a,n){return a+n},isLyh:t(1390),ctLCx:t(866)+"ack=fron"+t(507)+"P",mvBrL:function(a,n){return a===n},hXdbp:t(611),xYuZE:function(a,n){return a(n)},rCMPs:t(1072),lEcFn:function(a,n,s){return a(n,s)},CyKjc:function(a,n){return a!==n},qleMW:t(608),rrLwJ:t(912),GtvTh:function(a,n){return a<n},byVnG:function(a,n){return a>n},oqsyx:function(a,n){return a&n},yxvGB:function(a,n){return a>>>n},kVCnA:function(a,n){return a!==n},QDOOr:t(1076),aNRSv:function(a){return a()},sDUwk:"zgbDs",nqudU:t(832),xTVQi:function(a,n){return a+n},jSZyb:"iNgDC",ZDSHT:"EeauO",jizts:function(a,n){return a&n},owDNv:function(a,n){return a>>>n},KgLbA:function(a,n){return a>>>n},DOkcD:function(a,n){return a!==n},bUpBN:t(1110),pYJoV:function(a,n){return a||n},oIRUA:function(a,n){return a===n},bLUul:"ZdysI",FfUkD:function(a,n){return a||n},YkdEt:function(a,n){return a!=n},Gxamu:t(745),luneD:"__esModule",cMIXK:function(a,n){return a===n},tkiJV:t(501),xExGb:function(a,n){return a!=n},ryPxv:t(625)+"DB failed",JjtzQ:function(a,n,s){return a(n,s)},Fhwzv:function(a,n){return a<=n},GEMLo:function(a,n){return a|n},EpQMX:function(a,n){return a&n},sxxhR:function(a,n){return a&n},kShPl:function(a,n){return a|n},uQJnT:function(a,n){return a&n},zcfPk:function(a,n){return a&n},cbyti:function(a,n){return a===n},DsbAb:t(1242),arUsZ:t(784),mMKLB:function(a,n){return a instanceof n},EehOY:t(1175)+t(921),qYYfe:t(1175)+t(921)+t(742)+"=utf-8",jXDQx:t(439)+"e",UJXFT:t(1268),OzDAx:function(a,n,s,l){return a(n,s,l)},WMmIk:"tbAPl",MHPaP:function(a,n,s,l){return a(n,s,l)},juXRq:function(a,n,s){return a(n,s)},fOVhZ:t(344),GyNWz:function(a,n,s,l){return a(n,s,l)},sBZBQ:t(1451),yIuvo:function(a,n){return a&&n},hqxEX:"ack_id",hnEPk:"ack_code",yauie:function(a){return a()},pXExj:t(1376),yzjXl:function(a,n,s){return a(n,s)},qtXHD:function(a,n){return a(n)},ukFhh:t(1524),KZCpR:t(1506),vEvzS:function(a,n){return a instanceof n},wGBKM:function(a,n){return a instanceof n},qALFp:t(840),XNPef:function(a,n){return a<n},wnVlq:function(a,n){return a(n)},kZXvS:function(a,n){return a>n},MmsoQ:function(a,n){return a&n},CopLj:function(a,n){return a|n},DBrYO:function(a,n){return a(n)},WHuPu:function(a,n){return a+n},FXUan:function(a,n){return a+n},yAOzo:t(1597)+t(1152)+t(1626),CbtjX:t(556),DdqSR:" > ",RDMRO:function(a,n){return a===n},dsipm:t(1682),jQajC:function(a,n){return a>n},DtboL:t(991)+t(1746)+"e",bpGgP:function(a,n){return a<n},uibyr:function(a,n,s){return a(n,s)},ntEHd:function(a,n){return a<<n},OnYkA:"0|2|1|4|3",aTyYp:function(a,n){return a!==n},bNlZH:t(589),XJbjY:function(a,n){return a<<n},czfeL:function(a,n){return a+n},YWmbX:function(a,n){return a|n},bambQ:function(a,n){return a|n},flWVe:function(a,n){return a<<n},PAgHj:function(a,n){return a+n},cqTLL:function(a,n){return a<<n},OGRLa:function(a,n){return a+n},NNSdw:function(a,n){return a+n},HrAyM:function(a,n){return a+n},NOBHR:function(a,n){return a>>>n},HQfSJ:function(a,n){return a+n},MoRBZ:function(a,n){return a+n},rztcT:function(a,n){return a>>>n},bpDBo:function(a,n){return a+n},EpWGx:function(a,n){return a|n},fCnLq:function(a,n){return a&n},ajSiQ:function(a,n){return a>>>n},ElXal:function(a,n){return a&n},BxfBx:function(a,n){return a|n},TCFCx:function(a,n){return a<<n},HyaXL:function(a,n){return a&n},HOfpp:function(a,n){return a|n},SKDrd:function(a,n){return a|n},TsjPg:function(a,n){return a&n},rRtoh:function(a,n){return a<<n},LcXGg:function(a,n){return a===n},FzZwe:t(780),duPkE:function(a,n,s,l){return a(n,s,l)},ntTPk:t(1256),zkTiL:"name",UvWxO:function(a,n,s,l){return a(n,s,l)},gbMGx:"service",yqzZC:t(364)+t(731),hxBWl:t(310)+t(956),jpaCz:"header",WCYXA:function(a,n){return a-n},mEWJr:function(a,n){return a<n},tWHYL:function(a,n){return a!==n},HfTfB:t(1687),mLLxI:"cursor_name",rCLTz:t(377)+"rValues",gWTzc:"ALL",ZitUO:t(1668),mWwnW:function(a,n,s,l){return a(n,s,l)},Ljqix:function(a,n){return a(n)},RqRNL:t(1726)+"r",deTMD:"MQYbm",MiVwo:function(a,n,s,l){return a(n,s,l)},IqiXx:t(882),QjVWB:function(a,n,s){return a(n,s)},hDUix:t(850)+t(1314),ysCya:function(a,n){return a(n)},wzxgf:t(850)+"er_ttl",cRCeK:function(a){return a()},pOjSC:function(a,n){return a>n},Fguop:function(a,n){return a!==n},bYAip:t(897),uozay:t(1650),CzMXe:function(a,n){return a+n},kmulL:function(a){return a()},VUuRu:function(a,n){return a<n},OIBrk:function(a){return a()},MbTVj:function(a){return a()},vYTFC:function(a,n){return a===n},OVucn:function(a,n,s){return a(n,s)},YuwPD:"XqaBH",iRIXL:function(a){return a()},ZLbRQ:function(a,n){return a!==n},hAghy:function(a,n){return a===n},PUjBq:"wCQvh",LgGWX:function(a,n,s){return a(n,s)},uWEhi:function(a){return a()},VLeyn:t(907),rmgdm:function(a,n){return a===n},mnmqU:"auto",ayROH:"ping_onc"+t(747)+"s",ODfMA:"success",OSUEB:function(a,n){return a===n},rjRbV:t(1367),VIrPT:function(a,n,s,l){return a(n,s,l)},sKLyN:function(a,n){return a===n},rWOTf:function(a,n,s){return a(n,s)},kRqKU:t(1534),Dohep:function(a,n){return a!==n},ecjEm:t(686),TZopO:function(a,n,s){return a(n,s)},rlcko:function(a,n,s){return a(n,s)},aTsTk:t(555),woCfI:function(a,n,s){return a(n,s)},VyoXa:function(a,n,s){return a(n,s)},lCgJL:t(755)+t(684),SJdEN:"CONTINUE",uKSBs:function(a,n){return a==n},PKOCt:function(a,n){return a(n)},GGuTb:t(1127)+"rovide w"+t(707)+t(836)+t(1637)+t(475)+"is undef"+t(382),ytNpE:"done",tCmxt:function(a,n){return a in n},GdExi:function(a,n){return a===n},VUSDA:t(1762),GGQnx:function(a,n,s){return a(n,s)},jqVjq:"reconnect",NYsKh:t(1053)+t(531)+t(1115)+"ct",DBzXS:"online",uxeRj:t(494),CQeTg:t(1587),WoiYG:t(639),QiNxQ:function(a,n){return a==n},DATUa:t(712),gkbNn:t(1098),uHSqu:"bd_did",DUSEb:t(904),IliIo:function(a,n){return a==n},hdkcQ:function(a){return a()},QqWNL:t(1741)+"0",vHViS:function(a,n){return a>=n},Xxwvg:function(a,n,s){return a(n,s)},ECitH:t(313),nJiNK:function(a,n,s){return a(n,s)},iftpk:function(a,n,s){return a(n,s)},uaivB:function(a,n,s){return a(n,s)},Ejlof:function(a,n){return a(n)},VqVqY:function(a,n){return a(n)},rYypQ:function(a,n){return a===n},bKcrx:t(590),RKBDS:t(680),MLaRF:t(1574)+">",HPwcS:function(a,n){return a-n},NHGjO:function(a,n){return a>n},oRNdi:function(a,n){return a===n},EvNTa:function(a,n,s){return a(n,s)},VIoXu:t(1004)+t(908)+"t",SdIqe:t(913),sXWvX:t(1530)+"ay, try reconnec"+t(902)+t(391),gEUyS:function(a,n,s){return a(n,s)},NMKyK:"timeout,"+t(1379)+t(557)+"g",epZgs:function(a,n){return a(n)},csmRn:function(a,n){return a===n},wUPXp:t(340),GmJlH:t(1659),iLUQn:function(a,n,s){return a(n,s)},MOLWU:function(a,n,s){return a(n,s)},lKzOu:function(a,n,s){return a(n,s)},zEbsX:t(1530)+"ay, netw"+t(1546)+t(1752),KDgPO:function(a,n){return a===n},QdmHy:"ZnQdB",PMWJJ:t(1134),CHXDz:t(348),ABpHL:function(a,n){return a!==n},qozdQ:t(316),PubxL:t(1419)+t(425),HEOUY:"close, w"+t(1028)+t(1700),XLWsP:t(774)+t(567)+"ce not i"+t(1104)+"ed",lnghh:t(1127)+t(1010)+t(1138)+t(1616)+t(376)+t(524)+t(1528)+" arraybuffer",diBHW:function(a,n){return a instanceof n},iscNL:function(a,n){return a(n)},UsZjk:function(a,n){return a||n},trpvj:t(1127)+t(1010)+t(1731)+t(956),rLqMv:function(a,n){return a instanceof n},KjCwm:function(a,n){return a instanceof n},cqihC:t(1239),nEZOA:function(a,n){return a!==n},sIiLV:t(735),rRWWB:function(a,n){return a(n)},PsHgU:function(a,n){return a!==n},CyPUf:function(a,n){return a===n},PvOhO:t(419),MOIDc:function(a,n){return a!==n},FwloG:"rSGac",iysNc:t(718)+"3",CaxaQ:function(a,n){return a>>>n},KbPyp:function(a,n){return a<n},NaZBL:function(a,n){return a|n},nLZjt:function(a,n){return a<n},IGbQU:function(a,n,s,l){return a(n,s,l)},DohCF:function(a,n){return a|n},YQqZs:t(527),pvINi:t(1549),hxvDV:t(1082),nmvej:t(510),LXQGK:t(1484),wlQce:function(a,n){return a*n},UbpSr:function(a,n){return a===n},zbzkv:"Window",owLWx:function(a,n){return a===n},vUuLk:"DedicatedWorkerG"+t(874)+"pe",kkVGk:function(a,n){return a!=n},spwfM:function(a,n){return a===n},TxQdZ:function(a,n){return a!=n},osSMP:function(a,n){return a===n},RKZNr:function(a,n){return a===n},fPopp:t(394)+t(754)+t(1512),SGlmJ:function(a,n){return a===n},eEurm:function(a,n){return a===n},AEkyY:function(a,n){return a===n},PeTEp:"Object",HwFUK:function(a,n,s){return a(n,s)},makpf:t(1500)+"qos__"};Bt.r(Re),Bt.d(Re,{FWS:()=>hg,CustomErrorEvent:()=>Qd,createCloseEvent:()=>gt,ReconnectEvent:()=>Xd,createErrorEvent:()=>dt,decodedFrame:()=>en,createOpenEvent:()=>sl,CustomCloseEvent:()=>el,createReconnectEvent:()=>la,FrontierMessageEvent:()=>nl,encodeFrame:()=>zt,createMessageEvent:()=>il,OpenEvent:()=>rl,ErrorCode:()=>nn,Event:()=>tr,MessageEvent:()=>tl});let r="";function i(a=""){let n=t,s="02",l=""+Date.now(),h=r||(r=e[n(578)](f,a)),g=Math[n(633)]().toString(16)[n(901)](-6);return e[n(727)](e[n(1107)](e[n(727)](s,l),h),g)}function o(){let a=t;return e[a(727)](e[a(1154)](1e4,Date[a(768)]()),Math[a(457)](e[a(1171)](1e4,Math.random())))}function c(a){let n=t;return(e[n(1261)](Array,8)[n(1013)]("0")+parseInt(a,10)[n(1275)](2)).slice(-8)}function d(a){let n=t;return e[n(623)](e[n(578)](Array,4)[n(1013)]("0"),e[n(1139)](parseInt,a,2)[n(1275)](16))[n(901)](-4)}function u(a){let n=t,s=a.split(/\./)[n(841)](g=>c(g)),l=[];return l[0]=e.tsxOz(d,e[n(623)](s[0],s[1])),l[1]=e.tsxOz(d,e[n(1455)](s[2],s[3])),[e[n(964)],e[n(964)],e[n(964)],e[n(964)],e.yyifE,e[n(631)],l[0],l[1]].join("")}function f(a){let n=t,s=/(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(a),l=/(([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(a);return s?e[n(1525)](u,a):l?e[n(1499)](x,a):e[n(1605)]}function x(a){let n=t,s={tobXB:function(l,h){return e.vckyb(l,h)},GFeoz:function(l,h){return e.rPmje(l,h)}};if(e.COsTL(e[n(969)],e[n(1088)])){let l="",h=[],g=0,S=0,b=!0,m=e[n(964)];if(e[n(1212)](a[n(1354)]("::"),-1))if(e[n(482)](e[n(721)],e[n(721)])){let R=a[n(732)]("::");for(let F=0;e[n(909)](F,R[n(460)]);F++)if(e.Tkvmc("vzyRN",e[n(1296)])){let V=e[n(1139)](_0x2518d0,e[n(327)],{message:_0x4bd495.message,code:_0xc35eb3[n(1281)+"OR"],error:_0x1f698c});this[n(373)+n(1591)+n(1342)](V)}else{let V=R[F];if(V.indexOf(":")>0){let $=V.split(":");b&&(g=$[n(460)]),S+=$.length;for(let pe=0;e[n(909)](pe,$[n(460)]);pe++)if(e[n(770)](4,$[pe][n(460)])){let rt=m[n(458)+"g"](0,e[n(833)](4,$[pe][n(460)])),$e=rt.concat($[pe]);h[n(1017)]($e)}else h[n(1017)]($[pe]);b=!1}else{if(V[n(460)]!==4){let $=m[n(458)+"g"](0,4-V.length),pe=$[n(1153)](V);h[n(1017)](pe)}else h[n(1017)](V);b&&(g+=1),S+=1,b=!1}}let B="";for(let F=0;e[n(1665)](F,e[n(571)](8,S));F++)B=B[n(1153)](m);for(let F=0;e.YsTGl(F,h[n(460)]);F++)e[n(482)](F,g)?(l=l[n(1153)](B),l=l[n(1153)](h[F])):l=l.concat(h[F]);return l}else try{return!!this[n(1038)]}catch(R){return _0x4fd47a[n(1164)](R),!1}{let R=a.split(":");for(let B=0;e[n(909)](B,R.length);B++){let F=R[B];if(e[n(770)](4,R[B][n(460)]))if(e[n(770)](e[n(714)],e.cooCn)){let V=m[n(458)+"g"](0,e[n(571)](4,R[B][n(460)])),$=V[n(1153)](F);l=l[n(1153)]($)}else return;else l=l[n(1153)](F)}return l}}else{if(s[n(552)](s[n(980)](_0x3a2f9d.offset,_0x130e89),_0x1cfcda[n(317)]))throw new _0x4e8f02(n(984)+n(1412));_0x29cdd6[n(690)]+=_0x1a818e}}function p(a,n){let s=t,l=a.key;e.Yhaal(void 0,l)&&(xe(n,10),e[s(1139)](U,n,l));let h=a[s(1536)];e[s(770)](void 0,h)&&(e[s(1139)](xe,n,18),e[s(1717)](U,n,h))}function _(a){let n=t,s={};e:for(;!e[n(1364)](K,a);){let l=e[n(409)](he,a);switch(e[n(320)](l,3)){case 0:break e;case 1:s[n(1458)]=e.dqsfI(P,a,e[n(1499)](he,a));break;case 2:s[n(1536)]=P(a,e.ZbYRO(he,a));break;default:e[n(395)](T,a,e[n(1089)](7,l))}}if(e[n(1312)](void 0,s[n(1458)]))throw new Error(e[n(939)]);if(e[n(482)](void 0,s.value))throw new Error("Missing "+n(1644)+n(508)+n(1536));return s}function v(a){let n=t,s=e[n(1297)](C);return e.GnBHn(w,a,s),e.qxFir(N,s)}function w(a,n){let s=t,l={TlITS:function($e,it){return $e-it},XNsSu:function($e,it){return $e*it}},h=a.SeqID;e[s(829)](void 0,h)&&(e.BksRV(xe,n,8),e.kiSjt(pt,n,h));let g=a[s(814)];g!==void 0&&(e[s(395)](xe,n,16),e[s(1262)](pt,n,g));let S=a.service;e[s(1234)](void 0,S)&&(e.dqsfI(xe,n,24),e.PPmXn(pt,n,e.AFhNd(D,S)));let b=a[s(1414)];e[s(770)](void 0,b)&&(e[s(395)](xe,n,32),e[s(437)](pt,n,e[s(1129)](D,b)));let m=a.headers;if(e[s(1570)](void 0,m))for(let $e of m){e[s(1139)](xe,n,42);let it=e[s(1084)](C);e[s(1554)](p,$e,it),e.XWnDW(xe,n,it[s(317)]),e[s(1516)](j,n,it),O(it)}let R=a["payloadE"+s(952)];if(R!==void 0)if(e[s(1312)](e[s(651)],e[s(746)])){if(_0x594ae1[s(460)]!==4){let $e=_0x35f03e[s(458)+"g"](0,YIMmMI.TlITS(4,_0x449c22[s(460)])),it=$e.concat(_0x556b66);_0x583eda[s(1017)](it)}else _0xcd7ab4[s(1017)](_0x62dac9);_0x41b201&&(_0xf66efb+=1),_0x2157af+=1,_0x159952=!1}else e[s(1310)](xe,n,50),e[s(403)](U,n,R);let B=a[s(1545)+"ype"];e[s(829)](void 0,B)&&(xe(n,58),e[s(831)](U,n,B));let F=a[s(610)];if(F!==void 0)if(e[s(1312)](e[s(1672)],e[s(1672)]))e[s(1287)](xe,n,66),e[s(1516)](xe,n,F[s(460)]),se(n,F);else{let $e=new _0x1c5aa5(l[s(1394)](2,_0x13fc64));$e[s(1744)](_0x56c2cb),_0x269e93[s(640)]=$e}let V=a[s(884)];e[s(1701)](void 0,V)&&(e[s(482)](e[s(321)],e[s(343)])?(this[s(1751)+s(354)+"Id"]=null,this._interval=36e5,this._qosDB=e[s(1139)](_0x2cb56c,e[s(374)],e.LJrUm)):(e[s(1236)](xe,n,74),e[s(765)](U,n,V)));let $=a["serverTi"+s(1059)];e[s(1570)](void 0,$)&&(e.dqsfI(xe,n,82),e[s(831)](U,n,$));let pe=a[s(1246)];pe!==void 0&&(e[s(1287)](xe,n,90),U(n,pe));let rt=a[s(1325)+"e"];e.OxwEL(void 0,rt)&&(e[s(437)](xe,n,96),e[s(403)](pt,n,e.EwpIN(D,rt)))}function E(a){return I(e.nCCoK(M,a))}function I(a){let n=t,s={};e:for(;!K(a);){let l=e[n(1364)](he,a);switch(e[n(320)](l,3)){case 0:break e;case 1:s[n(800)]=It(a,!0);break;case 2:s[n(814)]=e[n(1310)](It,a,!0);break;case 3:s[n(554)]=e[n(420)](he,a);break;case 4:s[n(1414)]=e[n(409)](he,a);break;case 5:{let h=e[n(844)](A,a);(s.headers||(s[n(1292)]=[]))[n(1017)](e[n(1432)](_,a)),a.limit=h;break}case 6:s["payloadE"+n(952)]=e[n(1717)](P,a,e[n(790)](he,a));break;case 7:s[n(1545)+n(1117)]=e[n(848)](P,a,e[n(652)](he,a));break;case 8:s[n(610)]=e[n(1629)](ie,a,e[n(1364)](he,a));break;case 9:s[n(884)]=e[n(1717)](P,a,e.lsKny(he,a));break;case 10:s[n(860)+n(1059)]=e[n(848)](P,a,e.ypapY(he,a));break;case 11:s.msgID=e[n(1459)](P,a,e.tsxOz(he,a));break;case 12:s.frameType=e[n(1683)](he,a);break;default:e[n(1051)](T,a,e[n(346)](7,l))}}if(e[n(1080)](void 0,s[n(800)]))throw new Error(n(1727)+"required"+n(508)+n(800));if(e[n(1317)](void 0,s[n(814)]))throw new Error(e[n(867)]);if(e[n(1080)](void 0,s[n(554)]))throw new Error(e[n(1603)]);if(e.bZwXZ(void 0,s[n(1414)]))throw new Error(e[n(660)]);return s}function A(a){let n=t,s=e[n(578)](he,a),l=a[n(317)];return a[n(317)]=e.rPmje(a.offset,s),l}function T(a,n){let s=t;switch(n){case 0:for(;e[s(346)](128,e[s(826)](ee,a)););break;case 2:e[s(724)](Z,a,e[s(1647)](he,a));break;case 5:e[s(765)](Z,a,4);break;case 1:e[s(1262)](Z,a,8);break;default:throw new Error(e[s(727)]("Unimplemented ty"+s(749),n))}}function D(a){let n=t;return a|=0,{low:a,high:e[n(1103)](a,31),unsigned:e[n(1568)](a,0)}}let y=[];function C(){let a=t,n=y[a(1108)]();return n?(n[a(690)]=n[a(317)]=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}function O(a){y[t(1017)](a)}function M(a){return{bytes:a,offset:0,limit:a.length}}function N(a){let n=t,s=a[n(640)],l=a[n(317)];return s[n(460)]===l?s:s[n(1066)](0,l)}function Z(a,n){let s=t,l={nQhZq:function(h,g,S,b){return e[q(418)](h,g,S,b)},dmIEk:"error"};if(e.yzhMj(e.YKYSt,e.VWfIS))try{l[s(1542)](_0xc4a26b,this,_0xd61d70,[_0x52c122,_0x354596,_0x5f1db0])}catch(h){let g=_0x3c7927(l.dmIEk,{message:h[s(464)],code:_0x1b36c4.OPEN_ERROR,error:h});this["_dispatc"+s(1591)+s(1342)](g)}else{if(e.kdgjN(a[s(690)]+n,a[s(317)]))throw new Error(s(984)+s(1412));a.offset+=n}}function K(a){let n=t;return a[n(690)]>=a[n(317)]}function ne(a,n){let s=t;if(e[s(743)]!==e[s(743)])return this._socket.readyState;{let l=a[s(640)],h=a[s(690)],g=a.limit,S=e[s(892)](h,n);if(e[s(1212)](S,l[s(460)])){let b=new Uint8Array(e[s(1171)](2,S));b[s(1744)](l),a.bytes=b}return a.offset=S,e[s(1550)](S,g)&&(a.limit=S),h}}function Y(a,n){let s=t,l=a[s(690)];if(e[s(1212)](e[s(1455)](l,n),a[s(317)]))throw new Error(e[s(1418)]);return a[s(690)]+=n,l}function ie(a,n){let s=t,l=e[s(1717)](Y,a,n);return a.bytes[s(1066)](l,e[s(499)](l,n))}function se(a,n){let s=t,l=ne(a,n[s(460)]);a[s(640)].set(n,l)}function P(a,n){let s=t,l=e[s(1629)](Y,a,n),h=String["fromChar"+s(1135)],g=a[s(640)],S="\uFFFD",b="";for(let m=0;e[s(598)](m,n);m++){let R=g[m+l],B,F,V,$;if(e[s(617)](128&R,0))b+=e[s(1595)](h,R);else if(e[s(1089)](224,R)===192)e[s(1568)](e[s(623)](m,1),n)?b+=S:(B=g[e[s(1455)](e[s(369)](m,l),1)],e[s(1736)](192&B,128)?b+=S:($=e[s(1402)](e.LqtkR(31,R),6)|e.RURmf(63,B),e[s(909)]($,128)?b+=S:(b+=h($),m++)));else if(e[s(1442)](e.gnBaD(240,R),224))if(e[s(1681)](m+2,n))b+=S;else{if(e[s(617)](e[s(669)],s(1645)))return this._ws?this[s(1033)][s(1019)]:"";B=g[e[s(653)](m,l)+1],F=g[e[s(910)](e[s(402)](m,l),2)],e[s(1141)](e[s(1119)](B,F<<8),49344)!==32896?b+=S:($=e[s(1029)](e[s(1029)]((15&R)<<12,e[s(760)](e[s(1748)](63,B),6)),e[s(1141)](63,F)),e[s(598)]($,2048)||e[s(1503)]($,55296)&&$<=57343?b+=S:(b+=e[s(1261)](h,$),m+=2))}else e[s(1217)](e.RlBUb(248,R),240)?e[s(679)](e[s(1311)](m,3),n)?b+=S:(B=g[e[s(402)](m,l)+1],F=g[e[s(548)](m+l,2)],V=g[e[s(481)](e[s(727)](m,l),3)],e.Yhaal(e[s(1071)](e[s(1029)](B|e[s(1402)](F,8),e.HpCAB(V,16)),12632256),8421504)?b+=S:($=e[s(1119)](e[s(1670)](e[s(794)](e[s(1111)](7,R)<<18,e[s(828)](63,B)<<12),e[s(1142)](63&F,6)),e[s(341)](63,V)),e[s(534)]($,65536)||e[s(859)]($,1114111)?b+=S:($-=65536,b+=e.HHMDb(h,e[s(727)](e[s(1103)]($,10),55296),e[s(779)](e.vFyjo(1023,$),56320)),m+=3))):b+=S}return b}function U(a,n){let s=t,l=n[s(460)],h=0;for(let b=0;b<l;b++){let m=n[s(1046)+"At"](b);e[s(1503)](m,55296)&&e[s(1e3)](m,56319)&&e[s(650)](e[s(727)](b,1),l)&&(m=e[s(833)](e[s(369)](e[s(627)](m,10),n[s(1046)+"At"](++b)),56613888)),h+=e.hqEfR(m,128)?1:e[s(947)](m,2048)?2:e[s(987)](m,65536)?3:4}e[s(1073)](xe,a,h);let g=e[s(1717)](ne,a,h),S=a[s(640)];for(let b=0;b<l;b++){let m=n[s(1046)+"At"](b);e.XxWVU(m,55296)&&m<=56319&&e[s(490)](e.jhvLw(b,1),l)&&(m=e[s(1560)](e[s(1515)](m,10)+n[s(1046)+"At"](++b),56613888)),e.bzwVu(m,128)?S[g++]=m:(e[s(534)](m,2048)?S[g++]=e[s(803)](e[s(1103)](m,6),31)|192:e[s(1709)](s(962),"yXMxL")?(e.BRYOA(m,65536)?S[g++]=e[s(1576)](e[s(365)](m,12)&15,224):(S[g++]=e.FRjzN(e[s(472)](e[s(1103)](m,18),7),240),S[g++]=e[s(1109)](e[s(1306)](e.xuBkb(m,12),63),128)),S[g++]=e[s(1029)](e[s(365)](m,6)&63,128)):!this[s(485)+"Lock"]&&(this[s(542)+s(879)]?.[s(978)+"pointCon"+s(585)](),this[s(945)+s(1270)]?.["resetCou"+s(1186)](),this[s(791)+"osed"]=!1,this[s(604)]=!0,this[s(485)]()),S[g++]=e[s(456)](e[s(341)](63,m),128))}}function j(a,n){let s=t,l=e[s(433)](ne,a,n[s(317)]),h=a.bytes,g=n[s(640)];for(let S=0,b=n[s(317)];e.LUDBo(S,b);S++)h[S+l]=g[S]}function ee(a){return a[t(640)][Y(a,1)]}function Xe(a,n){let s=t,l=e[s(437)](ne,a,1);a[s(640)][l]=n}function he(a){let n=t,s=0,l=0,h;do n(1075)!==e[n(1156)]?(e[n(927)](_0x88785d,_0x2a5514,50),e.eQEtn(_0x18e20e,_0x2f651a,_0xd01713)):(h=e[n(834)](ee,a),s<32&&(l|=(127&h)<<s),s+=7);while(e[n(346)](128,h));return l}function xe(a,n){let s=t;for(n>>>=0;e[s(1681)](n,128);)e[s(1565)](Xe,a,e[s(1613)](e[s(346)](127,n),128)),n>>>=7;e[s(1139)](Xe,a,n)}function It(a,n){let s=t,l={dkBZY:e[s(1274)],ctvhj:function(m,R){return e[s(436)](m,R)},zOpgv:function(m,R){return m&R},MXavu:function(m,R){return m>>>R},FZiEv:function(m,R){return e[s(1257)](m,R)},XYLlC:function(m,R){return e[s(320)](m,R)}},h=0,g=0,S=0,b;if(b=e[s(420)](ee,a),h=e[s(401)](127,b),128&b){if(e[s(1322)]!==e.TTDFn)this.emit(l[s(1469)],_0x352f50),this[s(1610)+"eAck"]&&this["onReceiv"+s(323)](_0x55e47b);else if(b=e[s(1499)](ee,a),h|=e[s(1142)](e[s(1477)](127,b),7),e.VzYdA(128,b))if(e[s(1317)](e[s(446)],e[s(934)])){let m=this[s(1335)],R=this[s(1324)];return[255&R,l[s(1509)](R>>>8,255),l[s(1218)](l.MXavu(R,16),255),l[s(325)](R,24),l[s(758)](255,m),l[s(1218)](l.XYLlC(m,8),255),l[s(440)](m,16)&255,m>>>24]}else b=e[s(409)](ee,a),h|=e[s(760)](127&b,14),e[s(1748)](128,b)&&(b=e[s(529)](ee,a),h|=e.HpCAB(e[s(1306)](127,b),21),e.vDRnm(128,b)&&(s(311)===e.VTPJw?(b=e[s(420)](ee,a),g=127&b,e[s(1477)](128,b)&&(b=ee(a),g|=e[s(1081)](127,b)<<7,e.DDGmA(128,b)&&(b=ee(a),g|=e[s(1240)](e[s(1141)](127,b),14),e.YiAVN(128,b)&&(b=e[s(357)](ee,a),g|=e[s(341)](127,b)<<21,e.YiAVN(128,b)&&(b=ee(a),S=e[s(1313)](127,b),e[s(1399)](128,b)&&(b=ee(a),S|=(127&b)<<7)))))):this[s(776)]&&this[s(776)].close({code:_0x34d4fd,reason:_0x56944e})))}return{low:e[s(1613)](h,e[s(498)](g,28)),high:e[s(1029)](e[s(320)](g,4),S<<24),unsigned:n}}function pt(a,n){let s=t,l=e.qHBxP(n[s(1324)],0),h=e[s(1670)](e[s(320)](n[s(1324)],28),e[s(994)](n[s(1335)],4))>>>0,g=e[s(1585)](n[s(1335)],24),S=e[s(544)](0,g)?e[s(961)](0,h)?l<16384?l<128?1:2:e.EUgLi(l,2097152)?3:4:e[s(788)](h,16384)?e[s(1679)](h,128)?5:6:e[s(1679)](h,2097152)?7:8:e[s(490)](g,128)?9:10,b=ne(a,S),m=a[s(640)];switch(S){case 10:m[e.InmnK(b,9)]=e[s(828)](e[s(1585)](g,7),1);case 9:m[e[s(1691)](b,8)]=e[s(829)](9,S)?e[s(456)](128,g):127&g;case 8:m[e[s(971)](b,7)]=e[s(829)](8,S)?e.loQbG(e[s(1688)](h,21),128):h>>>21&127;case 7:m[e[s(779)](b,6)]=S!==7?e[s(1252)](e.DDubH(h,14),128):e[s(1468)](e.izFzA(h,14),127);case 6:m[e[s(481)](b,5)]=e[s(1701)](6,S)?e[s(1670)](h>>>7,128):e[s(1468)](h>>>7,127);case 5:m[b+4]=e.wrCDV(5,S)?128|h:e.gEwDm(127,h);case 4:m[b+3]=S!==4?e[s(1078)](e[s(320)](l,21),128):e[s(1360)](e.nnqmz(l,21),127);case 3:m[b+2]=e.COsTL(3,S)?e[s(668)](e[s(1585)](l,14),128):e[s(820)](l>>>14,127);case 2:m[e[s(779)](b,1)]=e[s(334)](2,S)?e[s(1712)](l>>>7,128):e[s(1593)](e[s(1272)](l,7),127);case 1:m[b]=e.OxwEL(1,S)?e[s(668)](128,l):e[s(1079)](127,l)}}function en(a){return E(a)}function zt(a){return v(a)}let tn=65536,Jr=e[t(414)],we=e[t(1171)](tn,tn),Ie=e[t(1243)](we,we),er=e[t(700)](Ie,2),Pe=String.prototype[t(1046)+"At"];class ue{constructor(n,s,l){let h=t;this[h(883)]=!0,this[h(1324)]=0|n,this[h(1335)]=0|s,this[h(963)]=!!l}static isLong(n){let s=t;return n&&e[s(617)](!0,n[s(883)])}static[t(1388)](n,s,l){return new ue(n,s,l)}static[t(1420)+"s"](n,s,l){let h=t;return l?ue[h(1420)+h(326)](n,s):ue[h(1420)+h(1631)](n,s)}static[t(1420)+t(326)](n,s){let l=t;return new ue(e[l(1504)](n[0]|e[l(1328)](n[1],8)|e.rbiPL(n[2],16),e[l(760)](n[3],24)),e[l(398)](e.Giclc(n[4],n[5]<<8),n[6]<<16)|e[l(1142)](n[7],24),s)}static[t(1420)+t(1631)](n,s){let l=t;return new ue(e.buuXq(e[l(599)](e[l(665)](n[4],24),e[l(1515)](n[5],16))|n[6]<<8,n[7]),e[l(1576)](e[l(1041)](e[l(1328)](n[0],24),e[l(498)](n[1],16)),n[2]<<8)|n[3],s)}static[t(1737)](n){let s=t;if(e[s(1519)]===s(1247))return e[s(1159)](n,Jr)?Yd:new ue(e.DDubH(e[s(380)](e[s(1109)](e.ktmGI(Pe[s(493)](n,0),Pe.call(n,1)<<8),e[s(370)](Pe[s(493)](n,2),16)),Pe.call(n,3)<<24),0),e[s(593)](e.Ugacw(e.FRjzN(Pe[s(493)](n,4),e.HKPyU(Pe[s(493)](n,5),8)),e[s(371)](Pe[s(493)](n,6),16))|Pe[s(493)](n,7)<<24,0),!0);try{this[s(1033)]&&this[s(1033)][s(1739)](_0x55650a,_0x4a7f16)}catch{}}[t(813)](){let n=t;return String["fromChar"+n(1135)](e[n(1011)](255,this[n(1324)]),e.QsZZy(this.low,8)&255,e[n(528)](e[n(536)](this[n(1324)],16),255),e[n(1688)](this[n(1324)],24),e.HXHaX(255,this[n(1335)]),e[n(1272)](this[n(1335)],8)&255,e[n(1567)](e[n(1347)](this[n(1335)],16),255),e[n(1347)](this[n(1335)],24))}static[t(1184)+"er"](n,s=!0){let l=t;if(e[l(1317)](l(476),e[l(944)]))this._DBName=_0x13bace,this[l(1298)]=_0x405739,this[l(1038)]=_0x54f9c0?_0x254473:_0x2e67ed?_0x5dcc31:null;else{if(e[l(1491)](isNaN,n))return s?Ip:Yd;if(s){if(e.XxWVU(n,Ie))return kp}else if(e[l(434)](e[l(930)],l(1680)))_0x176527=e[l(834)](_0x574fa2,_0x4d74dd),_0x28a9f2|=e[l(1402)](e.egTQo(127,_0x59204a),7);else{if(e.arSNb(n,-er))return Tp;if(e[l(525)](e[l(1339)](n,1),er))return Ap}return ue[l(1388)](e[l(990)](n,we)|0,e.XUYeS(e[l(700)](n,we),0),s)}}[t(584)](){let n=t;return this[n(963)]?e.eljLr(e[n(1301)](e[n(982)](this[n(1335)],0),we),e[n(918)](this.low,0)):e[n(1551)](this[n(1335)],we)+e[n(1347)](this[n(1324)],0)}isZero(){let n=t;return e[n(923)](0,this[n(1335)])&&e.oljHo(0,this.low)}add(n){let s=t;ue[s(883)](n)||(n=ue[s(1184)+"er"](n));let l=e[s(982)](this[s(1335)],16),h=e[s(1141)](65535,this.high),g=e[s(657)](this.low,16),S=65535&this[s(1324)],b=e[s(1363)](n[s(1335)],16),m=65535&n[s(1335)],R=e[s(503)](n.low,16),B=e[s(1438)](65535,n[s(1324)]),F=0,V=0,$=0,pe=0;return pe+=e[s(402)](S,B),$+=e[s(988)](pe,16),pe&=65535,$+=e[s(779)](g,R),V+=e[s(536)]($,16),$&=65535,V+=h+m,F+=e[s(1068)](V,16),V&=65535,F+=e.vmeiV(l,b),F&=65535,ue[s(1388)](e[s(468)]($<<16,pe),e[s(1343)](e[s(667)](F,16),V),this.unsigned)}equals(n){let s=t;return ue.isLong(n)||(n=ue[s(1184)+"er"](n)),e[s(829)](this[s(963)],n[s(963)])&&e[s(544)](this.high>>>31,1)&&e[s(1709)](e[s(393)](n[s(1335)],31),1)?!1:this[s(1335)]===n.high&&e[s(544)](this[s(1324)],n.low)}[t(421)](){let n=t;return this[n(1324)]===-1&&e[n(1317)](-1,this[n(1335)])?ue[n(1388)](0,0,this[n(963)]):e[n(1675)](-1,this[n(1324)])?ue.fromBits(0,e[n(1269)](this[n(1335)],1),this[n(963)]):ue[n(1388)](this[n(1324)]+1,this.high,this[n(963)])}toBytes(n){let s=t;return n?this[s(1720)+"E"]():this[s(1711)+"E"]()}toBytesLE(){let n=t,s=this[n(1335)],l=this[n(1324)];return[e[n(1369)](255,l),e.VzYdA(e[n(940)](l,8),255),e[n(795)](e[n(762)](l,16),255),e[n(1363)](l,24),e[n(1313)](255,s),e[n(1710)](e[n(1347)](s,8),255),e[n(1123)](e.pGJPM(s,16),255),s>>>24]}[t(1711)+"E"](){let n=t,s=this[n(1335)],l=this[n(1324)];return[e[n(1300)](s,24),e.gaytm(s>>>16,255),e[n(1222)](s,8)&255,e[n(1334)](255,s),e[n(762)](l,24),e[n(988)](l,16)&255,e[n(1011)](e[n(320)](l,8),255),e[n(1011)](255,l)]}}let Yd=new ue(0,0,!1),Ip=new ue(0,0,!0),Ap=ue[t(1388)](-1,2147483647,!1),kp=ue[t(1388)](-1,-1,!0),Tp=ue.fromBits(0,-2147483648,!1);var nn=(function(a){let n=t,s=e[n(1521)].split("|"),l=0;for(;;){switch(s[l++]){case"0":a[a[e[n(1655)]]=5004]="MESSAGE_ERROR";continue;case"1":return a;case"2":a[a["MAX_RETR"+n(562)+"R"]=5003]=n(1319)+n(562)+"R";continue;case"3":a[a[e[n(1407)]]=5005]=e[n(1407)];continue;case"4":a[a[e[n(1341)]]=5002]=e[n(1341)];continue;case"5":a[a[e[n(1140)]]=5001]=e[n(1140)];continue}break}})({});class tr{constructor(n){let s=t;this[s(1653)]=n,this.target=null}}class Xd extends tr{constructor(n,s){let l=t;super(n),this[l(464)]=s&&s.message||null}}class Qd extends tr{constructor(n,s){let l=t,h=e[l(1293)].split("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(882)]=s&&s[l(882)]||5001;continue;case"1":this.error=s&&s[l(870)]||null;continue;case"2":super(n);continue;case"3":this[l(1721)]=s&&s.lineno||0;continue;case"4":this.message=s&&s.message||"";continue;case"5":this[l(1755)]=s&&s[l(1755)]||0;continue;case"6":this.filename=s&&s[l(843)]||"";continue}break}}}class el extends tr{constructor(n,s){let l=t,h=e[l(1147)][l(732)]("|"),g=0;for(;;){switch(h[g++]){case"0":this.code=s&&s[l(882)]||0;continue;case"1":this[l(1498)+l(1039)]=s&&s[l(1498)+l(1039)]||!1;continue;case"2":super(n);continue;case"3":this[l(1677)]=s&&s[l(1677)]||"";continue;case"4":this[l(816)]=s&&s[l(816)]||!1;continue}break}}}class tl extends tr{constructor(n,s){super(n),this.data=s&&s.data||null}}class nl extends tl{constructor(n,s){let l=t;super(n),this[l(444)]=s&&s[l(444)]||null,this.message=s&&s.message||null}}class rl extends tr{constructor(n,s){let l=t;super(n),this[l(444)]=s&&s[l(444)]||null}}function dt(a,{message:n,code:s,error:l}){return new Qd(a,{message:n,code:s,error:l})}function gt(a,{code:n,reason:s,wasClean:l,willReconnect:h}){return new el(a,{code:n,reason:s,wasClean:l,willReconnect:h})}function il(a,{data:n,message:s}){return new nl(a,{data:n,message:s})}function sl(a,{data:n}){return new rl(a,{data:n})}function la(a,{message:n}){let s=t,l={ulWRU:e[s(597)],VocHb:e.YtLRp};if(e.xoFBL(s(565),e[s(1466)]))return new Xd(a,{message:n});{let h=(s(1165)+"4")[s(732)]("|"),g=0;for(;;){switch(h[g++]){case"0":this[s(1033)][s(1183)+s(1467)+s(1714)](s(1582),this[s(1730)]);continue;case"1":if(!this._ws)return;continue;case"2":this[s(1033)][s(1183)+s(1467)+s(1714)]("message",this[s(933)+"ge"]);continue;case"3":this[s(1033)][s(1183)+s(1467)+s(1714)](l.ulWRU,this[s(428)]);continue;case"4":this._ws["removeEv"+s(1467)+s(1714)](l[s(470)],this._onError);continue}break}}}class ol{constructor(n,s){let l=t;this[l(1642)+"s"]=n,this[l(799)+"es"]=s,this[l(1250)+l(847)]=0,this[l(1368)+l(728)+l(1077)+"t"]=0}[t(978)+t(1422)+t(585)](){let n=t;this[n(1250)+n(847)]=0,this[n(1368)+n(728)+n(1077)+"t"]=0}resetTries(){let n=t;this[n(1368)+"ndpointT"+n(1077)+"t"]=0}[t(1393)+t(1482)+"nt"](){let n=t;if(e[n(617)](e.uJFOS,e.uJFOS))return this[n(1642)+"s"][this[n(1250)+n(847)]];_0x538165(_0xd50170,8),e.Ytykb(_0x11f30a,_0x3e09ed,_0x49626a)}[t(1393)+"ntEndpoi"+t(697)+t(596)](){return this["currentEndpointT"+t(1077)+"t"]}["checkRea"+t(769)+"es"](){let n=t;return!!(this[n(1250)+n(847)]>=this[n(1642)+"s"][n(460)]||e[n(810)](this.currentIndex,this.endpoints[n(460)]-1)&&e[n(386)](this[n(1368)+n(728)+n(1077)+"t"],this[n(799)+"es"]))}[t(1226)+t(1012)+t(1229)+t(614)+"tries"](){let n=t;return e[n(1217)](this[n(1250)+n(847)],this[n(1642)+"s"][n(460)])?!0:this[n(1368)+n(728)+n(1077)+"t"]>this[n(799)+"es"]}[t(1507)+t(798)+t(1258)+t(1056)+t(670)](){let n=t;return this[n(1368)+n(728)+"riesCount"]=1,this[n(1250)+n(847)]++,this[n(1642)+"s"][this[n(1250)+n(847)]]}["getCurre"+t(1482)+t(1494)+t(1148)](){let n=t;return this[n(1368)+n(728)+"riesCount"]++,this[n(1393)+n(1482)+"nt"]()}}let nr=(e.BHSRU(e[t(1635)],typeof globalThis)&&e[t(1457)](e[t(1448)],globalThis[t(1728)+t(1405)].name)||t(336)+"d"!=typeof window&&window[t(1728)+t(1405)][t(731)]==="Window")&&e.xExGb(t(336)+"d",typeof document),Cn=e[t(328)](e[t(1635)],typeof globalThis)&&(e[t(1349)]("Object",globalThis[t(1728)+t(1405)][t(731)])||e[t(355)](e[t(1621)],globalThis[t(1728)+t(1405)][t(731)]))&&e.BHSRU(t(336)+"d",typeof tt),Yr=(e.kkVGk(e[t(1635)],typeof globalThis)&&e[t(560)](t(895),globalThis[t(1728)+t(1405)].name)||e[t(1065)](e[t(1635)],typeof globalThis)||e[t(315)]("undefined",typeof globalThis)&&!!globalThis[t(579)+t(1259)])&&t(336)+"d"!=typeof wx,Xr=e[t(658)](e[t(1635)],typeof globalThis)&&(e[t(1305)](t(1167)+t(796)+t(874)+"pe",globalThis[t(1728)+"tor"][t(731)])||e.RKZNr(e[t(1596)],globalThis[t(1728)+"tor"].name)||e.SGlmJ("ServiceW"+t(1627)+t(324),globalThis[t(1728)+t(1405)][t(731)]))&&e[t(315)](t(336)+"d",typeof self),Rp=e[t(1429)](e.EcWZs,typeof globalThis)&&e.eEurm(t(895),globalThis[t(1728)+t(1405)][t(731)])&&e[t(1635)]!=typeof global&&e[t(819)](e[t(716)],global[t(1728)+"tor"][t(731)])&&e[t(1635)]!=typeof process&&!!process[t(1125)];class ua{constructor(){let n=t;this[n(775)+"rs"]={}}[t(1718)](n,...s){let l=t,h=this[l(775)+"rs"][n];if(h)h[l(901)]()[l(953)](g=>g.fn.apply(g[l(771)],s));else if(e[l(544)](e[l(327)],n)&&!this[l(1185)]){let g=s[l(460)]&&s[0];if(e[l(644)](g,Error))throw g;let S=new Error(e.qeWDB(e[l(1410)],g?e.InmnK(" ("+g[l(464)],")"):""));throw S.context=g,g}return this}off(n,s){let l=t;if(e[l(561)](e[l(985)],e[l(985)])){if(e.nEIXs(void 0,n))this[l(775)+"rs"]={};else if(s===void 0)this[l(775)+"rs"][n]=null;else if(e.jPiui(e[l(337)],l(634))){let h=this[l(775)+"rs"][n];if(h)for(let g=0;e.LPIyk(g,h[l(460)]);)e[l(734)](h[g].fn,s)?h[l(612)](g,1):++g}else{let h=_0x1eb09b[l(640)],g=_0x409f47[l(690)],S=_0x3ede0f.limit,b=e[l(1514)](g,_0x6b022d);if(e.YnIsR(b,h[l(460)])){let m=new _0x21006d(e[l(378)](2,b));m[l(1744)](h),_0x27de89[l(640)]=m}return _0x4b8622[l(690)]=b,b>S&&(_0x3cf44d[l(317)]=b),g}return this}else{let h=this[l(775)+"rs"][_0xaf39ae];if(h)h[l(901)]()[l(953)](g=>g.fn[l(427)](g.ctx,_0x7a5641));else if(e[l(386)](e.YtLRp,_0x3b54fc)&&!this[l(1185)]){let g=_0x317fe1.length&&_0x3d6877[0];if(e.wQjdz(g,_0x473d3c))throw g;let S=new _0x71461a(e.ibhaC+(g?e[l(455)](" (",g[l(464)])+")":""));throw S[l(1632)]=g,g}return this}}on(n,s,l){let h=t;return(this[h(775)+"rs"][n]||(this._listeners[n]=[]))[h(1017)]({fn:s,ctx:l||this}),this}}class Cp extends ua{["_formatE"+t(407)+t(1487)](n){let s=t;return n[s(1743)]||n[s(817)]?(s(1719)+" "+(n[s(1743)]||"")+" code: "+(n[s(817)]||""))[s(332)]():JSON[s(710)+"y"](n)}constructor(n,s,l){let h=t;super(),this[h(776)]=null,Yr&&wx["connectS"+h(662)]&&(this._socket=wx.connectSocket({url:n,protocols:s,header:l,fail:this[h(659)+"ocketFai"+h(607)][h(1023)](this),success:this[h(659)+"ocketSuccessHand"+h(384)][h(1023)](this)})),Cn&&tt["connectS"+h(662)]&&(this[h(776)]=tt.connectSocket({url:n,protocols:s,header:l,fail:this["_createS"+h(789)+"lHandler"][h(1023)](this),success:this[h(659)+h(588)+"cessHand"+h(384)][h(1023)](this)}))}["_createS"+t(588)+t(726)+t(384)](){let n=t;Promise[n(777)]()[n(577)](()=>{let s=n;this[s(1661)+s(702)]()})}[t(659)+"ocketFai"+t(607)](n){let s=t;Promise[s(777)]().then(()=>{let l=s,h=e[l(1310)](dt,l(870),{message:this[l(1578)+l(407)+"age"](n)});this.emit(e[l(327)],h);let g=e[l(395)](gt,e[l(597)],{reason:this["_formatE"+l(407)+"age"](n)});this[l(1718)](e[l(597)],g)})}[t(1661)+t(702)](){let n=t,s={Qnbve:function(l,h,g){return e[q(433)](l,h,g)},VxcmB:e.rukws};this[n(776)][n(1208)](l=>{let h=n;this[h(1718)](e[h(1359)],e[h(431)](sl,e[h(1359)],{...l,data:l.errMsg||""}))}),this._socket[n(1581)](l=>{let h=n;this[h(1718)](h(1739),s[h(1486)](gt,h(1739),{...l}))}),this[n(776)][n(823)+"e"](l=>{let h=n;this[h(1718)](s[h(1643)],il(s[h(1643)],{...l}))}),this._socket[n(854)](l=>{let h=n;this.emit(e[h(327)],e[h(1174)](dt,h(870),{...l,message:l[h(1743)]||""}))})}[t(1383)](n){let s=t,l={PzNgx:s(870)};if(n instanceof Uint8Array){let h=n.buffer.slice(n[s(462)+"et"],n[s(1338)+"th"]+n.byteOffset);this[s(776)]&&this[s(776)][s(1383)]({data:h,fail:g=>{let S=s;this.emit(e[S(327)],dt(e.YtLRp,{message:this["_formatE"+S(407)+"age"](g)}))}})}else this._socket&&this._socket[s(1383)]({data:n,fail:h=>{let g=s;this[g(1718)](l.PzNgx,dt(l[g(672)],{message:this[g(1578)+g(407)+g(1487)](h)}))}})}[t(1739)](n,s){let l=t;this[l(776)]&&this[l(776)][l(1739)]({code:n,reason:s})}[t(1395)+t(1020)](n,s){this.on(n,s)}[t(1183)+t(1467)+t(1714)](n,s){let l=t;if(e[l(576)](e[l(1663)],l(1425)))this[l(995)](n,s);else{let h=!!this[l(1669)][l(1145)+"S"];if(!h)return{enabled:h,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let g=e[l(418)](_0x2baf25,_0x44a179[l(464)][l(1292)],e.TWMhQ,"2"),S=g&&_0x2067d3(_0x46c1df[l(464)][l(1292)],e[l(1196)],"1"),b=g&&e[l(418)](_0xc81b15,_0x449371[l(464)].headers,e[l(1362)],"1"),m=b?e[l(853)](_0x25e812,_0x30e8a5[l(464)].headers,e[l(1651)])?.[l(732)](",").filter(_0x3478ca)||[]:[];return{enabled:h,isQoSMessage:g,isQoSAck:S,isAckCleanupMessage:b,ackMsgIds:m}}}get[t(1666)+"te"](){let n=t;return this[n(776)][n(1666)+"te"]}get binaryType(){let n=t;return this[n(776)][n(1558)+"pe"]}set[t(1558)+"pe"](n){}get[t(922)](){let n=t,s={mSqfe:function(l,h,g){return e.lAGaw(l,h,g)}};return e[n(482)](e[n(1025)],e[n(792)])?new _0xf25697(l=>{let h=n;s[h(1036)](_0x28f19a,l,this[h(426)+h(1505)+"e"](_0x3d59ca))}):this._socket.url}get[t(1019)](){return this._socket.protocol}get[t(1625)+"ns"](){let n=t;return this[n(776)][n(1625)+"ns"]}get[t(375)+"Amount"](){let n=t;return e[n(1541)](e[n(1263)],e[n(1022)])?0:(this[n(1368)+n(728)+n(1077)+"t"]++,this["getCurre"+n(1482)+"nt"]())}}function Pp(a,n){let s=t;if(n)return new n(a.url,a.protocol);if(e.LSGKX(Yr,Cn))return new Cp(a.url,a[s(1019)],a[s(1292)]);if(e.ALVfC(nr,Xr)&&e[s(328)](e.EcWZs,typeof WebSocket)&&WebSocket)return new WebSocket(a[s(922)],a[s(1019)+"s"])}function Dp(a){let n=t,s={WsZRt:function(l,h){return e[q(465)](l,h)},jcECy:function(l,h){return l&h},qdSpW:function(l,h){return e[q(568)](l,h)},mUAxT:function(l,h){return l+h}};if(e[n(1553)](e[n(1472)],"aHLWi")){let l=_0xd61201.low,h=_0xea0c6[n(1335)];return _0x340e94[_0x59a3c1]=s[n(392)](h,24),_0x173bff[_0xe86b5c+1]=s[n(705)](s[n(392)](h,16),255),_0x35f7fc[_0x395eaa+2]=s[n(705)](h>>>8,255),_0x21ff8f[s.qdSpW(_0x34b2e1,3)]=s[n(705)](255,h),_0x24c599[_0x3ee531+4]=s[n(392)](l,24),_0x522c76[s[n(1624)](_0x99820f,5)]=l>>>16&255,_0x5726ee[_0x4dddc4+6]=s.jcECy(l>>>8,255),_0x2129ab[s[n(635)](_0x81d2e3,7)]=s[n(705)](255,l),_0x43deb2+=8,_0x5f48e4}else{let l=e[n(1742)][n(732)]("|"),h=0;for(;;){switch(l[h++]){case"0":return!1;case"1":if(a)return!0;continue;case"2":if(Cn&&tt["connectS"+n(662)])return!0;continue;case"3":if(Yr&&wx[n(1284)+n(662)])return!0;continue;case"4":if(e.EjAhI(nr,Xr)&&typeof WebSocket<"u"&&WebSocket)return!0;continue}break}}}function al(a,n,s){let l=t,h={TRiaK:function(b,m){return e.hHIWe(b,m)},WDFFn:e[l(521)],ffeWu:function(b,m){return e.lpZIk(b,m)},BbEzJ:function(b,m){return e[l(1480)](b,m)}},g=-1;async function S(b){let m=l;return h.TRiaK(b,g)?Promise[m(1699)](new Error(h[m(830)])):(g=b,h.ffeWu(b,s.length)?Promise[m(777)]():s[b][m(1023)](a)(n,S.bind(null,h[m(570)](b,1))))}e[l(1129)](S,0)}function cl(a){let n=t,s=0,l=0;for(let h=0;e[n(909)](h,a[n(460)]);++h)l=a.charCodeAt(h),e.LIYfW(l,128)?s+=1:l<2048?s+=2:e[n(1122)](64512,l)===55296&&e.nEIXs(64512&a[n(1046)+"At"](h+1),56320)?e[n(576)](e.TavCA,e[n(931)])?(++h,s+=4):_0x55a671[n(1164)](_0x472ba9):s+=3;return s}function dl(a,n,s){let l=t;if(e[l(1018)](e[l(571)](s,n),1))return"";let h="";for(let g=n;e[l(650)](g,s);){let S=a[g++];if(e[l(773)](S,127))h+=String[l(709)+l(1135)](S);else if(e[l(525)](S,192)&&e.EUgLi(S,224))h+=String[l(709)+"Code"](e[l(1240)](31&S,6)|e[l(540)](63,a[g++]));else if(S>=224&&e[l(477)](S,240))h+=String[l(709)+l(1135)](e.buuXq(e[l(515)](e[l(502)](e[l(1567)](15,S),12),e[l(667)](63&a[g++],6)),e[l(1703)](63,a[g++])));else if(S>=240){let b=e[l(993)](e[l(1357)](e[l(538)](e[l(1142)](e.ARTmK(7,S),18)|e.hEEVT(e[l(312)](63,a[g++]),12),e[l(667)](e.tkUbF(63,a[g++]),6)),63&a[g++]),65536);h+=String["fromChar"+l(1135)](55296+(b>>10)),h+=String[l(709)+l(1135)](56320+e[l(1122)](1023,b))}}return h}function fa(a,n,s){let l=t;if(e[l(955)](l(469),e[l(1049)])){let h=s,g,S;for(let b=0;e[l(490)](b,a[l(460)]);++b)g=a[l(1046)+"At"](b),e[l(788)](g,128)?n[s++]=g:e[l(788)](g,2048)?(n[s++]=e[l(1116)](e[l(1103)](g,6),192),n[s++]=e[l(1670)](e[l(1399)](63,g),128)):e[l(569)](e[l(1477)](64512,g),55296)&&e[l(434)](e[l(1468)](64512,S=a[l(1046)+"At"](b+1)),56320)?(g=e[l(369)](e[l(1224)](65536,e[l(667)](e.rhtpd(1023,g),10)),e.vZuWw(1023,S)),++b,n[s++]=e[l(1103)](g,18)|240,n[s++]=e[l(1078)](e[l(540)](e[l(1034)](g,12),63),128),n[s++]=e[l(1409)](e[l(1103)](g,6),63)|128,n[s++]=e[l(1569)](e[l(1640)](63,g),128)):(n[s++]=e[l(863)](e[l(763)](g,12),224),n[s++]=e[l(365)](g,6)&63|128,n[s++]=e.eBrMc(e.gTNaB(63,g),128));return s-h}else this["currentI"+l(847)]=0,this[l(1368)+l(728)+l(1077)+"t"]=0}async function ll(a){let n=t;if(e[n(1442)](e[n(582)],typeof a)){let s=new Uint8Array(cl(a));return e[n(1476)](fa,a,s,0),s}return e[n(920)](a,ArrayBuffer)?new Uint8Array(a):new Uint8Array(a[n(595)],a.byteOffset,a[n(1338)+"th"])}function Op(a){let n=t;try{return e[n(328)](n(1540),typeof a)&&(a instanceof ArrayBuffer||a[n(595)]&&e[n(920)](a[n(595)],ArrayBuffer))||e.BHSRU(n(1540),typeof a)?"":(JSON.parse(a),n(1175)+n(921))}catch{return e[n(583)]!==e[n(583)]?n(1092)+"_"+this._DBName:typeof a=="string"?e[n(1351)]:""}}let Lp=(a,n)=>{let s=t;switch(a){case s(1501):case e[s(753)]:return{[s(1093)+a]:1,"x-tt-env":n};default:return{}}};class Np{constructor(n){let s=t;if(e.ggVCV(e[s(858)],"TLDvj"))return null;this.maxLossCount=n,this.count=0}addCount(){this.count++}[t(1520)+t(1470)+"nt"](){let n=t,s={sOpKN:function(l,h,g){return e[q(1288)](l,h,g)},rdglB:function(l,h){return e[q(1736)](l,h)},Epdpq:function(l,h,g){return l(h,g)}};if(e[n(1215)](n(1573),"gdWhp"))return e[n(423)](this[n(932)],this[n(805)+"ount"]);if(this[n(1033)]&&this[n(1033)][n(1666)+"te"]===this[n(466)+"NG"]){this[n(602)+n(1105)](),this[n(1449)+n(1355)+"Id"]=s[n(1372)](_0x3129f1,this._ping[n(1023)](this),this._options[n(852)+n(1114)]);return}if(!this[n(1033)]||s[n(1031)](this._ws[n(1666)+"te"],this[n(751)]))return void this[n(996)+n(539)]();this._ws&&this._ws.send("hi"),this[n(381)+n(671)+n(911)]=s[n(647)](_0x2a45ff,this[n(996)+n(539)+n(890)][n(1023)](this),this[n(1669)]["pingTime"+n(1160)+n(808)])}[t(1441)+t(1186)](n=0){let s=t;this[s(805)+s(596)]=n,this[s(932)]=0}}async function Mp(a){let n=t,s={ZxLug:function(l,h){return e.pFhnl(l,h)},EKlfs:e[n(1749)]};if(e[n(1492)](e[n(1463)],n(1072)))return new Promise(l=>{let h=n;if(!nr)return e.pFhnl(l,e[h(1749)]);try{let g=document[h(1723)+h(1526)](h(580));window[h(1092)+h(946)]=S=>{let b=h;document.body[b(1456)+b(688)](g),window[b(1092)+b(946)]=void 0,s[b(655)](l,S&&S[b(1163)]||s[b(1042)])},g[h(1653)]=e[h(785)],g.src=e[h(1295)](a[h(1623)](/^ws/,e[h(400)]),e[h(1604)]);try{if(e.mvBrL(e[h(399)],h(559)))return this[h(1038)][h(1030)];document[h(509)]["appendCh"+h(688)](g)}catch{document[h(509)][h(1456)+h(688)](g)}}catch{window[h(1092)+h(946)]=void 0,e.pFhnl(l,"unknown "+h(1677))}});e.xYuZE(_0x1875c0,this[n(485)+n(1733)+n(1096)]),this[n(485)+n(1733)+n(1096)]=null}function rn(a,n,s){let l=t,h={prtCU:function(g,S,b){return e[q(1602)](g,S,b)},XMErZ:e[l(327)]};if(e.CyKjc(e.qleMW,l(608))){let g=l(809)+_0x1ef1e8+(l(1371)+", max re"+l(417)+l(1481));this[l(1178)](g),this["_dispatc"+l(1591)+"ent"](h[l(1660)](_0x899c63,h[l(1006)],{message:g,code:_0x269f74[l(1319)+l(562)+"R"]}));return}else return!!a?.[l(586)](g=>g[l(1458)]===n&&g[l(1536)]===s)}function rr(a,n){let s=t;return a?.find(l=>l[s(1458)]===n)?.[s(1536)]}let ha=null;async function Bp(){let a=t;return ha||(ha=Promise.resolve()[a(577)](Bt.bind(Bt,e.rrLwJ))),ha}class Fp extends ua{constructor(n,s){let l=t;super(),this[l(1086)]=n,this._keyPath=s,this[l(1038)]=void 0,this[l(1622)+l(1106)]=null}async[t(1348)](){await this._init()}async[t(1353)](){let n=t,s={lhXqP:function(l,h){return l!==h},gfcRm:e.sDUwk};if(!this[n(1038)]){if(this[n(1622)+"mise"])return this[n(1622)+n(1106)];try{let l=this[n(1086)],h=this._keyPath;this[n(1622)+n(1106)]=(async()=>{let g=n,S={umgLW:function(b,m){return e[q(954)](b,m)},eCMHN:function(b,m){return e.byVnG(b,m)},EEcIm:function(b,m){return e[q(409)](b,m)},XeULp:function(b,m){return e[q(314)](b,m)},kLhpY:function(b,m){return e[q(1252)](b,m)},tQcWW:function(b,m){return b||m},cHODK:function(b,m){return e[q(1132)](b,m)}};if(e[g(740)](e[g(896)],"BHuFN")){let{openDB:b}=await e[g(1332)](Bp);this[g(1038)]=await e[g(1476)](b,g(1092)+"_"+l,1,{upgrade(m){let R=g;if(s[R(1676)](R(1195),s[R(1592)]))return this[R(776)][R(1558)+"pe"];m["createOb"+R(1231)+"e"](l,{keyPath:h})}})}else{let b=S[g(1705)](_0xec5fde,8192),m=S[g(621)](b,1),R=null,B=b;return function(F){let V=g;if(S[V(1758)](F,1)||S[V(1192)](F,m))return _0x33345a(F);S[V(1192)](B+F,b)&&(R=S[V(1408)](_0xa7600b,b),B=0);let $=_0x24c1d2[V(493)](R,B,B+=F);return S[V(435)](7,B)&&(B=S[V(1686)](7,B)+1),$}}})(),await this["_initPro"+n(1106)]}catch(l){console[n(1164)](l)}finally{this._initPromise=null}}}async[t(915)](n){let s=t;try{return await this[s(1353)](),this[s(1038)]?.[s(915)](this[s(1086)],n)}catch(l){console[s(1164)](l)}}async set(n,s){let l=t;if(e[l(1588)]!==e[l(1588)])_0x51ecaa(_0x482e04,74),_0x5e6961(_0x508852,_0x2c4c32);else return await this[l(1353)](),this[l(1038)]?.[l(1223)](this[l(1086)],n)}async[t(505)](n){let s=t,l={hQxuQ:function(h,g){return e[q(1101)](h,g)}};try{return await this[s(1353)](),this._qosDB?.[s(488)](this[s(1086)],n)}catch(h){e[s(1265)](s(846),e.jSZyb)?console[s(1164)](h):(_0x5c6619[_0x490465[_0x695474].cursor_name]=_0x4703a7(_0x2ce0e0[_0x39be8a][s(1253)+"ame"]),_0x57f9b0+=l.hQxuQ(14,_0x347a96[_0x141d69[_0x14c2f8][s(1253)+s(1664)]]))}}async[t(496)](){let n=t;try{return await this[n(1353)](),this[n(1038)]?.[n(496)](this[n(1086)])}catch(s){console[n(1164)](s)}}async keys(){let n=t;return await this[n(1353)](),this._qosDB?.[n(1177)+"ys"](this._dbName)}async[t(445)](){let n=t;return await this[n(1353)](),this._qosDB?.[n(445)](this._dbName)}async closeDB(){let n=t;try{this._qosDB?.[n(1739)](),this[n(1038)]=void 0}catch(s){console[n(1164)](s)}}get[t(1030)](){let n=t;try{return!!this[n(1038)]}catch(s){return console[n(1164)](s),!1}}}class zp{constructor(n,s){let l=t;this[l(1336)]=n,this[l(1298)]=s,this[l(1038)]=localStorage}async[t(1348)](){}get[t(613)](){let n=t;return n(1092)+"_"+this[n(1336)]}async[t(915)](n){let s=t;if(e[s(1447)]===e.ZDSHT){let l=this[s(1038)][s(1280)](this[s(613)]);return JSON[s(1601)](l||"{}")[n]}else return{bytes:_0xec1fb4,offset:0,limit:_0x22bbbf[s(460)]}}async[t(1744)](n,s){let l=t,h={VYhyz:function(g,S){return e[q(545)](g,S)},ULWIs:function(g,S){return g&S},yaDNn:function(g,S){return e.owDNv(g,S)},DyfKj:function(g,S){return g&S},MabSq:function(g,S){return e[q(1674)](g,S)},VmoSd:function(g,S){return e.rhtpd(g,S)},WDfft:function(g,S){return g>>>S}};if(e[l(1282)](e.bUpBN,l(1024))){let g=this[l(1038)].getItem(this[l(613)]),S=JSON[l(1601)](e[l(1638)](g,"{}"));return S[s||n[this[l(1298)]]]=n,this[l(1038)][l(761)](this[l(613)],JSON[l(710)+"y"](S)),s||n[this._pathKey]}else{let g=this[l(1335)],S=this[l(1324)];return[g>>>24,TAjTnB[l(471)](g>>>16,255),TAjTnB.ULWIs(TAjTnB[l(624)](g,8),255),TAjTnB[l(1434)](255,g),TAjTnB[l(624)](S,24),TAjTnB[l(471)](TAjTnB[l(1510)](S,16),255),TAjTnB.VmoSd(TAjTnB[l(759)](S,8),255),TAjTnB.VmoSd(255,S)]}}async del(n){let s=t,l=this[s(1038)][s(1280)](this[s(613)]),h=JSON[s(1601)](e.ALVfC(l,"{}"));return h[n]=void 0,this[s(1038)].setItem(this[s(613)],JSON[s(710)+"y"](h))}async[t(496)](){let n=t;return this[n(1038)][n(496)]()}async[t(807)](){let n=t,s=this._qosDB[n(1280)](this[n(613)]),l=JSON[n(1601)](e[n(516)](s,"{}"));return Object[n(807)](l)}async[t(445)](){let n=t,s=this[n(1038)][n(1280)](this._prefix),l=JSON[n(1601)](s||"{}");return Object.values(l)}[t(648)](){return Promise[t(777)]()}get[t(1030)](){return!!this._qosDB}}class Up{constructor(n,s){let l=t;e[l(601)](e[l(566)],e[l(566)])?(this[l(1336)]=n,this[l(1298)]=s,this[l(1038)]=Cn?tt:Yr?wx:null):_0x1f23c9&&this[l(448)+"anager"][l(622)+"rsorFile"+l(928)](_0x4872c8)}async[t(1348)](){}get[t(613)](){let n=t;return n(1092)+"_"+this[n(1336)]}async get(n){let s=t,l=this._qosDB[s(1244)+s(812)](this[s(613)]);return JSON[s(1601)](e.FfUkD(l,"{}"))[n]}async[t(1744)](n,s){let l=t,h=this[l(1038)][l(1244)+l(812)](this[l(613)]),g=JSON.parse(e[l(1001)](h,"{}"));return g[s||n[this._pathKey]]=n,this[l(1038)]["setStora"+l(812)](this._prefix,JSON.stringify(g)),s||n[this[l(1298)]]}async[t(505)](n){let s=t,l=this[s(1038)][s(1244)+s(812)](this._prefix),h=JSON.parse(l||"{}");return h[n]=void 0,this[s(1038)][s(1433)+"geSync"](this[s(613)],JSON[s(710)+"y"](h))}async[t(496)](){let n=t;return this._qosDB[n(756)+n(563)]()}async[t(807)](){let n=t,s=this._qosDB[n(1244)+"geInfoSync"](this[n(613)]),l=JSON[n(1601)](e[n(687)](s,"{}"));return Object[n(807)](l)}async[t(445)](){let n=t,s=this[n(1038)][n(1244)+n(497)+"nc"](this[n(613)]),l=JSON.parse(s||"{}");return Object[n(1047)](l)}[t(648)](){return Promise[t(777)]()}get[t(1030)](){let n=t;if(e[n(1035)](n(1452),e.tkiJV)){let s={XxPzF:function(l,h){return beIKsU.YkdEt(l,h)},lCAze:beIKsU[n(1635)],eSaJa:beIKsU[n(594)],NlIfA:beIKsU[n(1151)]};_0x548705.r=l=>{let h=n;s[h(1572)](s[h(1654)],typeof _0x3ff30a)&&_0x3c1dce[h(1275)+h(1045)]&&_0x2362dc[h(408)+h(851)](l,_0x124288[h(1275)+h(1045)],{value:s.eSaJa}),_0x2b93b6["definePr"+h(851)](l,s[h(1327)],{value:!0})}}else return!!this[n(1038)]}}function ul(a,n){let s=t;if(Cn||Cn)return new Up(a,n);if((nr||Xr)&&e[s(1016)](e[s(1635)],typeof indexedDB))return new Fp(a,n);if(e[s(1692)](nr,Xr)&&e[s(1230)](s(336)+"d",typeof localStorage))return new zp(a,n);throw new Error(e[s(1187)])}class Gp{constructor(){let n=t;this[n(1751)+n(354)+"Id"]=null,this[n(1751)+"l"]=36e5,this[n(1038)]=e[n(724)](ul,e[n(374)],e[n(1529)])}async["_interva"+t(1180)](){let n=t;e.pFhnl(clearInterval,this["_interva"+n(354)+"Id"]),this[n(1751)+n(354)+"Id"]=e[n(1037)](setInterval,()=>{let s=n;this[s(1641)+s(1606)]()},this._interval)}async[t(1348)](){let n=t;await this._qosDB[n(1348)]()[n(577)](()=>{let s=n;this[s(1751)+s(1180)]()})}async[t(1641)+"ired"](){let n=t,s={RASjv:function(l,h){return e.Fhwzv(l,h)},pJIAQ:function(l,h){return e[q(500)](l,h)},EAEWW:function(l,h){return l<<h},XNihb:function(l,h){return e.EpQMX(l,h)},kzxgp:function(l,h){return e[q(1399)](l,h)},pYBig:function(l,h){return l>=h},TPkyZ:function(l,h){return l<h},BjqdD:function(l,h){return l&h},DPPZO:function(l,h){return e[q(1227)](l,h)},guJPJ:function(l,h){return l-h},gGCIS:function(l,h){return e[q(885)](l,h)},GmfSe:function(l,h){return e[q(538)](l,h)},xBEYd:function(l,h){return l<<h},sweov:function(l,h){return e[q(1162)](l,h)},hNXpw:function(l,h){return e[q(486)](l,h)}};if(e[n(1378)](e[n(619)],e[n(1373)])){let l=_0x21ed1e[_0x6a69fc++];if(zqWfxU[n(1382)](l,127))_0x4ed908+=_0x283abc[n(709)+n(1135)](l);else if(l>=192&&l<224)_0x268d54+=_0x1ab6e9[n(709)+n(1135)](zqWfxU[n(1474)](zqWfxU.EAEWW(zqWfxU[n(905)](31,l),6),zqWfxU.kzxgp(63,_0x21b27c[_0x1acd79++])));else if(zqWfxU[n(1430)](l,224)&&zqWfxU[n(685)](l,240))_0x3a96bb+=_0x26f4db[n(709)+n(1135)](zqWfxU[n(1474)](zqWfxU[n(905)](15,l)<<12,zqWfxU[n(839)](zqWfxU[n(1197)](63,_0x332d79[_0xc66c76++]),6))|zqWfxU[n(1374)](63,_0x1220bf[_0x15ecae++]));else if(l>=240){let h=zqWfxU.guJPJ(zqWfxU[n(941)](zqWfxU[n(451)](zqWfxU[n(1374)](7,l)<<18,zqWfxU[n(839)](63&_0x2e57f3[_0x4203f1++],12)),zqWfxU[n(517)](zqWfxU[n(905)](63,_0x3ac290[_0x40f586++]),6))|zqWfxU[n(1323)](63,_0x5bcb4b[_0x5d915a++]),65536);_0x372266+=_0x43cfa1["fromChar"+n(1135)](55296+(h>>10)),_0x37ae0c+=_0x4be857[n(709)+n(1135)](56320+zqWfxU.hNXpw(1023,h))}}else(await this[n(1038)]?.[n(445)]()||[])[n(736)](({timestamp:g})=>g<Date.now())[n(953)](g=>{let S=n;this[S(1038)]?.[S(505)](g[S(1594)+"id"])})}async[t(505)](n){let s=t;return this[s(1038)]?.[s(505)](n)}async[t(1744)](n,s){let l=t;return this[l(1038)]?.[l(1744)]({message_id:n,timestamp:s})}async[t(915)](n){return this[t(1038)]?.get(n)}async[t(648)](){let n=t;clearInterval(this[n(1751)+"lTimeoutId"]),await this[n(1038)]?.closeDB()}get[t(1030)](){let n=t;if(e[n(1190)]===e.WMmIk)return this._qosDB?.[n(1030)];if(_0x45f251.payload instanceof _0x1a4039){let s=this[n(1669)][n(960)+"ncoding"]instanceof _0x3dd91a?{force:!!this[n(1669)][n(960)+n(952)][n(887)],encoding:this[n(1669)][n(960)+n(952)][n(1182)]?this._options[n(960)+n(952)][n(1182)][n(1623)](/\s/g,"")["toLowerC"+n(609)]():""}:{force:!1,encoding:this[n(1669)][n(960)+"ncoding"]?this[n(1669)].payloadEncoding[n(1623)](/\s/g,"")[n(1330)+n(609)]():""},l=_0x156e73["payloadE"+n(952)]?_0x5254a2[n(960)+n(952)][n(1623)](/\s/g,"")["toLowerC"+n(609)]():"",h=e.mMKLB(this[n(1669)][n(1545)+n(1117)],_0x29762e)?{force:!!this[n(1669)][n(1545)+n(1117)][n(887)],type:this._options["payloadT"+n(1117)].type?this[n(1669)][n(1545)+n(1117)][n(1653)][n(1623)](/\s/g,"")[n(1330)+n(609)]():""}:{force:!1,type:this[n(1669)]["payloadT"+n(1117)]?this[n(1669)][n(1545)+n(1117)].replace(/\s/g,"")[n(1330)+n(609)]():""},g=_0x30e126[n(1545)+n(1117)]?_0x1d6333[n(1545)+n(1117)][n(1623)](/\s/g,"")[n(1330)+n(609)]():"",S=h.force?h[n(1653)]:g||h.type,b=s[n(887)]?s.encoding:l||s[n(1182)],m=["text/pla"+n(1278)+n(1497),e[n(331)],e[n(1009)],e.ApbnM],R=[e.jXDQx,e.UJXFT];this._options[n(704)+"ansformT"+n(898)+"ad"]&&m[n(967)](S)&&(!b||R[n(967)](b))?_0x2359c4[n(1444)+n(926)]=e[n(713)](_0x4d9499,_0x1172dd[n(610)],0,_0x243de6[n(610)][n(1338)+"th"]):_0x535afa[n(1444)+n(926)]=""}else _0x1a0eea[n(1444)+n(926)]=""}}function xa(a){let n=t,s=!!this[n(1669)].enableQoS;if(!s)return{enabled:s,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let l=rn(a[n(464)][n(1292)],e.TWMhQ,"2"),h=l&&rn(a[n(464)].headers,e.LPrny,"1"),g=l&&e.MHPaP(rn,a[n(464)][n(1292)],n(850)+n(1496)+"k","1"),S=g?e.juXRq(rr,a.message[n(1292)],e[n(1651)])?.[n(732)](",")[n(736)](Boolean)||[]:[];return{enabled:s,isQoSMessage:l,isQoSAck:h,isAckCleanupMessage:g,ackMsgIds:S}}async function fl(){let a=t;return this["_QoSMana"+a(513)]||(this[a(942)+a(513)]=new Gp),this[a(942)+a(513)][a(1030)]||await this[a(942)+"ger"][a(1348)](),this[a(942)+a(513)]}async function Hp(a,n){let s=t;if(e[s(581)]==="rsGOY")this[s(604)]=!0,this._connect();else{let{enableAutoAck:l}=this[s(1669)],h=e[s(1673)](rn,a.message[s(1292)],s(855),"1"),g=rn(a[s(464)].headers,e[s(827)],"1"),S=xa.call(this,a);if(e.yIuvo(l,h)){let{SeqID:b,LogID:m,service:R,LogIDNew:B,method:F}=a[s(464)];this._sendAck({SeqID:b,LogID:m,LogIDNew:B,service:R,method:F,headers:[{key:e.sBZBQ,value:"1"},{key:e.hqxEX,value:B||""},{key:e[s(1120)],value:"0"}]})}g&&!S[s(1206)]&&this[s(373)+s(1535)+"ageEvent"](a),e[s(520)](n)}}async function qp(a,n){let s=t;this[s(1178)](e[s(999)],a[s(464)]),n()}async function jp(a,n){let s=t,l=e[s(438)](en,await ll(a.data));try{if(e[s(644)](l.payload,Uint8Array))if(e[s(972)](e.ukFhh,e[s(574)])){let h=e[s(356)](this._options[s(960)+s(952)],Object)?{force:!!this._options[s(960)+"ncoding"].force,encoding:this[s(1669)][s(960)+"ncoding"][s(1182)]?this[s(1669)][s(960)+s(952)][s(1182)].replace(/\s/g,"")["toLowerC"+s(609)]():""}:{force:!1,encoding:this[s(1669)]["payloadE"+s(952)]?this[s(1669)]["payloadE"+s(952)][s(1623)](/\s/g,"")[s(1330)+s(609)]():""},g=l[s(960)+"ncoding"]?l[s(960)+s(952)].replace(/\s/g,"")[s(1330)+"ase"]():"",S=e[s(1283)](this[s(1669)][s(1545)+"ype"],Object)?{force:!!this._options["payloadT"+s(1117)][s(887)],type:this[s(1669)][s(1545)+s(1117)][s(1653)]?this[s(1669)][s(1545)+"ype"][s(1653)][s(1623)](/\s/g,"")[s(1330)+s(609)]():""}:{force:!1,type:this._options.payloadType?this[s(1669)][s(1545)+s(1117)][s(1623)](/\s/g,"")[s(1330)+s(609)]():""},b=l[s(1545)+s(1117)]?l["payloadT"+s(1117)][s(1623)](/\s/g,"")["toLowerC"+s(609)]():"",m=S[s(887)]?S[s(1653)]:b||S.type,R=h[s(887)]?h.encoding:g||h[s(1182)],B=[e[s(1351)],e.EehOY,s(1175)+s(921)+s(742)+"=utf-8",e[s(582)]],F=[e[s(573)],e.UJXFT];this._options[s(704)+s(1225)+s(898)+"ad"]&&B.includes(m)&&(!R||F[s(967)](R))?l[s(1444)+"oad"]=dl(l[s(610)],0,l[s(610)][s(1338)+"th"]):l[s(1444)+s(926)]=""}else this[s(932)]++;else l[s(1444)+"oad"]=""}catch(h){if(e[s(1294)]!=="tuQWr"){for(_0x3618c2>>>=0;_0x2e9037>=128;)e[s(927)](_0x5205f6,_0x1ad2d4,e[s(794)](e.gnBaD(127,_0x60fd67),128)),_0x2aad15>>>=7;e[s(1003)](_0x1007c6,_0x2c8d8b,_0x34c566)}else l[s(1444)+s(926)]="",console.log(h)}a[s(464)]=l,e[s(1297)](n)}function Wp(a,n,s){let l=t,h=s||8192,g=e[l(982)](h,1),S=null,b=h;return function(m){let R=l;if(e[R(722)](m,1)||m>g)return e[R(1715)](a,m);e[R(1248)](b+m,h)&&(S=a(h),b=0);let B=n[R(493)](S,b,b+=m);return e.MmsoQ(7,b)&&(b=e[R(717)](7,b)+1),B}}let $p=4294967295;function Kp(a,n,s){let l=t;return e.DBrYO(RangeError,e[l(322)](e.BeeKO(e.rPmje(e[l(1101)](e.FXUan(e.yAOzo,a),e[l(404)]),e[l(1638)](n,1)),e[l(1502)]),s))}function Vp(a,n,s){let l=t;if(e.RDMRO(e[l(767)],l(1682))){if(e.jQajC(s,$p))throw new Error(e[l(546)]);let h=3;for(;h>=0;){let g=e[l(1703)](255,s);ga(g,a,e[l(1269)](n,h)),s>>>=8,h--}return n+4}else return 0}function Zp(a,n){let s=t,l=0,h=n,g=e[s(779)](n,4);for(;e[s(478)](h,g);){let{value:S,offset:b}=e[s(1706)](pa,a,h);h=b,l=e[s(1413)](l,8)>>>0,l+=S}return{value:l,offset:g}}function Jp(a,n,s){let l=t,h=e[l(345)].split("|"),g=0;for(;;){switch(h[g++]){case"0":if(!a)return s;continue;case"1":if(n[l(880)+"e"])return e[l(322)](n[l(880)+"e"](a,s),s);continue;case"2":if(e[l(1665)](a[l(460)],40))return e[l(1673)](fa,a,n,s)+s;continue;case"3":return e.EskUM(e[l(1673)](fa,a,n,s),s);case"4":if(n.write)return n[l(1380)](a,s)+s;continue}break}}function Yp(a,n){let s=t;if(e.aTyYp(e[s(558)],e[s(558)]))return this[s(776)].extensions;{let l=new ue(e[s(1078)](a[e.ZyIAi(n,4)]<<24|e[s(1522)](a[e[s(1221)](n,5)],16),e[s(1522)](a[n+6],8))|a[e[s(1101)](n,7)],e[s(1277)](e[s(1137)](e[s(1670)](e[s(549)](a[e.eljLr(n,0)],24),e[s(1515)](a[e[s(350)](n,1)],16)),e[s(1273)](a[e[s(358)](n,2)],8)),a[e[s(917)](n,3)]),!0);return n+=8,{value:l,offset:e.HrAyM(n,8)}}}function Xp(a,n,s){let l=t,h=a[l(1324)],g=a[l(1335)];return n[s]=g>>>24,n[s+1]=e.QCCCS(e[l(593)](g,16),255),n[e[l(1224)](s,2)]=e[l(645)](g,8)&255,n[e[l(997)](s,3)]=e[l(1640)](255,g),n[e[l(1392)](s,4)]=h>>>24,n[s+5]=e.rztcT(h,16)&255,n[e[l(1101)](s,6)]=e[l(1438)](e.QsZZy(h,8),255),n[s+7]=e[l(1313)](255,h),s+=8,s}function pa(a,n){let s=t;return a[s(526)+"8"]?{value:a[s(526)+"8"](n),offset:e.NNSdw(n,1)}:{value:e[s(1593)](255,a[n]),offset:e[s(547)](n,1)}}function ga(a,n,s){let l=t;return n[l(530)+"t8"]?n[l(530)+"t8"](a,s):n[s]=255&a,e[l(568)](s,1)}let Qp=function(a){return new Uint8Array(a)},eg=e.EcWZs!=typeof Buffer?Buffer[t(729)+t(673)]:e[t(620)](Wp,Qp,Uint8Array.prototype[t(1066)]);(()=>{let a=t;if(e[a(1318)](e.FzZwe,e.FzZwe)){let n=4294967295;return function(s,l,h=!0){let g=a,S=("1|11|3|1"+g(385)+g(1070)+"6")[g(732)]("|"),b=0;for(;;){switch(S[b++]){case"0":n=e.lFLNi(e.EpWGx(n,e[g(1302)](127,s[l])<<21),0);continue;case"1":n=e[g(411)](e[g(1757)](127,s[l]),0);continue;case"2":if(s[l++]<128)return{value:h?n:0|n,offset:l};continue;case"3":n=e.BxfBx(n,e[g(1273)](e[g(572)](127,s[l]),7))>>>0;continue;case"4":n=e[g(536)](n|e[g(1299)](e[g(1015)](15,s[l]),28),0);continue;case"5":if(s[l++]<128)return{value:h?n:e[g(1436)](0,n),offset:l};continue;case"6":return{value:h?n:e.vMMUG(0,n),offset:l};case"7":n=e[g(536)](e[g(1504)](n,e[g(1328)](127&s[l],14)),0);continue;case"8":if(e[g(954)](s[l++],128))return{value:h?n:0|n,offset:l};continue;case"9":if((l+=5)>s[g(460)])throw l=s[g(460)],Kp(l,10,s.length);continue;case"10":if(s[l++]<128)return{value:h?n:e[g(1495)](0,n),offset:l};continue;case"11":if(e[g(1194)](s[l++],128))return{value:h?n:0|n,offset:l};continue}break}}}else _0xc9f495=_0x1105d8(_0x225276),_0x1005bf=e.YiAVN(127,_0x12799a),e[a(1083)](128,_0x3c7810)&&(_0x205cd5=e[a(483)](_0x30ee6a,_0x32b73c),_0x393f22|=e.rRtoh(e[a(1162)](127,_0x3e9fbe),7))})();let tg=16,ma=32;function ng(a){let n=t,s=0,l={};for(let h=0;e[n(788)](h,a[n(460)]);h++)l[a[h][n(1253)+n(1664)]]=cl(a[h][n(1253)+n(1664)]),s+=14+l[a[h][n(1253)+n(1664)]];return[s,l]}function hl(a,n,s){let l=t,[h,g]=e[l(1499)](ng,a),S=e[l(529)](eg,h),b=0;return a[l(953)](m=>{let R=l,B=(R(1483)+R(793)+R(1531))[R(732)]("|"),F=0;for(;;){switch(B[F++]){case"0":b=e[R(986)](ga,0,S,b);continue;case"1":console[R(1164)](e[R(1488)],b);continue;case"2":console[R(1164)](e[R(474)],b);continue;case"3":b=e[R(948)](ga,g[m[R(1253)+R(1664)]],S,b);continue;case"4":b=e.UvWxO(Xp,ue[R(1184)+"er"](m[R(1424)]||n),S,b);continue;case"5":console[R(1164)](e[R(1191)],b);continue;case"6":console.log(e.yqzZC,b);continue;case"7":console[R(1164)](e[R(1404)],m,m[R(554)]);continue;case"8":console[R(1164)](e.jpaCz,b);continue;case"9":b=Vp(S,b,m.service||0);continue;case"10":b=e[R(1673)](Jp,m[R(1253)+R(1664)],S,b);continue}break}}),{frameType:ma,headers:[{key:l(1391)+"ile_name",value:s}],payload:S}}function rg(a){let n=t,s=0,l=[];for(;e[n(842)](s,a[n(1338)+"th"]);)if(e.tWHYL(n(1687),e.HfTfB)){let h=_0x3f5544.substring(0,e.WCYXA(4,_0x31feaa[_0x3968f5][n(460)])),g=h[n(1153)](_0x636101[_0x1c37a2]);_0x552a44.push(g)}else{let{offset:h}=pa(a,s);s=h;let g={cursor_name:"",cursor:0,service:0},{value:S,offset:b}=e[n(730)](Zp,a,s);g[n(554)]=S,s=b;let{value:m,offset:R}=pa(a,s);s=R,g["cursor_n"+n(1664)]=e[n(418)](dl,a,s,e[n(548)](s,m)),s+=m;let{value:B,offset:F}=Yp(a,s);g.cursor=B.toNumber(),s=F,l[n(1017)](g)}return l}function ig(){let a=t;return{frameType:ma,headers:[{key:a(1391)+"ile_name",value:a(1562)+a(487)}],payload:void 0}}class sg{constructor(n,s,l){let h=t;this[h(1478)+h(1759)]=n,this._cursorFileName=s,this[h(397)+"Strategy"]=l,this[h(1038)]=e[h(1003)](ul,this[h(1478)+"ameSpace"],e.mLLxI)}async[t(1348)](){let n=t;await this[n(1038)][n(1348)]()}async[t(1756)+"rs"](){let n=t;if(!this._qosDB[n(1030)])return;let s=this[n(397)+n(1121)],l=await this[n(1038)][n(445)]();switch(console.log(e[n(441)],l),s){case e.gWTzc:return l&&l[n(460)]?e.duPkE(hl,l,0,this["_cursorF"+n(1350)]):void 0;case e[n(495)]:return;case n(1210):return l&&l[n(460)]?e[n(693)](hl,l,0,this[n(1652)+n(1350)]):e[n(1332)](ig)}}async[t(1744)](n,s,l){let h=t;return console[h(1164)](h(564),n,s,l),this._qosDB.set({cursor_name:n,cursor:s,service:l})}async[t(1266)+"rs"](n){let s=t,l=e.Ljqix(rg,n);for(let h of l)console.log(e[s(1561)],l),await this[s(1038)][s(1744)](h)}async[t(915)](n){let s=t,l={zkqaC:function(h,g,S){return e[q(1037)](h,g,S)},OzpXG:s(1739)};if(e[s(770)](e.deTMD,s(935)))return(await this._qosDB[s(915)](n))?.[s(1424)];{let h=this[s(542)+s(879)]?.[s(1393)+"ntEndpoint"]();this[s(373)+s(1571)+"ent"](l.zkqaC(_0x5e5c1f,l[s(1403)],{code:_0x29392f[s(882)],reason:s(1209)+"ng faile"+s(1169)+s(519)+s(1577)+s(551)+h})),this[s(542)+s(879)]?.["resetEnd"+s(1422)+s(585)](),this[s(945)+s(1270)]?.resetCounter();return}}async[t(648)](){let n=t;await this._qosDB[n(648)]()}[t(622)+t(857)+t(928)](n){let s=t;this[s(1652)+"ileName"]=n}get[t(1030)](){let n=t;return this._qosDB[n(1030)]}}let og=e[t(1172)];async function xl(a){let n=t;if(!this[n(1669)][n(1145)+"S"])return null;let{aID:s,fpID:l,messageStrategy:h}=this[n(1669)],g=a||og;try{return this[n(448)+"anager"]?a&&this[n(448)+n(550)][n(622)+n(857)+n(928)](a):this[n(448)+"anager"]=new sg(l+"_"+s+"_"+g,g,h),this[n(448)+"anager"][n(1030)]||await this[n(448)+n(550)][n(1348)](),this[n(448)+n(550)]}catch{return null}}async function ag(a,n){let s=t,l=e[s(1609)](rn,a.message[s(1292)],e[s(1205)],"-1"),h=rn(a[s(464)].headers,e.sBZBQ,"1"),g=e[s(871)](rr,a[s(464)][s(1292)],e[s(875)]),S=e[s(778)](Number,rr(a[s(464)][s(1292)],e[s(1285)]))||0,b=xa.call(this,a),m=e[s(1698)](rn,a[s(464)][s(1292)],"x-msg-qos","2"),R=rr(a[s(464)][s(1292)],s(1589)+s(1446)+"e"),B=e[s(790)](Number,rr(a[s(464)][s(1292)],s(1589)+s(1716)+"ue"));if(b.isQoSAck)return e[s(1398)](n);let F=b["isQoSMes"+s(1149)]?await fl[s(493)](this):null;if(e.pOjSC(a[s(464)][s(554)],0)&&h&&!l||a[s(464)][s(554)]>0){if(g&&b["isQoSMes"+s(1149)]&&F)if(e.Fguop(s(897),e[s(1048)]))this.on(_0x2f1b31,_0x10a443);else return!!!await F[s(915)](g)&&(e[s(1290)]!==s(1760)?(this[s(373)+s(628)+s(1580)](a),await F[s(1744)](g,e[s(432)](Date[s(768)](),S))):_0x42264a[s(1164)](_0x5d548f)),e[s(520)](n);if(m){let V=await xl[s(493)](this);if(!V)return this[s(373)+"hMessage"+s(1580)](a),e.kmulL(n);let $=await V[s(915)](R)??-1;if(e[s(1634)]($,B))this[s(373)+s(628)+s(1580)](a),V[s(1744)](R,B,a.message.service);else throw new Error(s(1249)+s(1454)+s(413)+B+(" larger than loc"+s(342)+"r ")+$);return n()}return this[s(373)+s(628)+s(1580)](a),e[s(543)](n)}}async function cg(a,n){let s=t,l=xa.call(this,a);if(!l["isQoSMes"+s(1149)])return e[s(1556)](n);let h=await fl[s(493)](this);if(l[s(1069)+"anupMess"+s(1487)]&&l[s(1489)+"s"][s(460)])for(let g of l[s(1489)+"s"])await h.del(g);e[s(520)](n)}async function dg(a,n){let s=t,l=a[s(464)][s(1325)+"e"]===tg,h=e[s(959)](a[s(464)][s(1325)+"e"],ma);if(!l&&!h)return e[s(1084)](n);let g=rr(a[s(464)][s(1292)],"cursor_f"+s(864));if(!g)return n();let S=await xl[s(493)](this,g);if(!S)return n();if(l){let b=await S.getCursors(),m={frameType:b?.[s(1325)+"e"],SeqID:ue[s(1184)+"er"](this._seqId++),LogID:ue.fromNumber(this[s(1669)][s(1428)+s(518)]()),service:9e3,method:5,headers:b?.headers,payload:b?.[s(610)]},R=e[s(483)](v,m);this[s(1033)]&&this[s(1033)][s(1666)+"te"]&&this._ws.send(R)}if(h){let b=a[s(464)][s(610)];b&&S.setCursors(b)}}let lg=async function(a,n){let s=t;if(e[s(576)](s(506),e.YuwPD))this[s(604)]=!1,clearTimeout(this[s(485)+s(1733)+s(1096)]),e[s(533)](n);else{let l=e[s(523)](_0x2f5197,e[s(327)],{message:_0x153a04[s(464)],code:_0x38d81c[s(1707)+s(1704)],error:_0x855efa});this[s(373)+s(1591)+s(1342)](l)}},ug=async function(a,n){let s=t,l={mWaus:function(S,b,m){return S(b,m)},HeDtZ:e[s(597)]};if(!this[s(1033)]||e[s(1537)](this._ws[s(1666)+"te"],this[s(751)]))return e[s(1556)](n);let{pingInterval:h}=this[s(1669)];this[s(542)+s(879)]?.[s(978)+s(1422)+s(585)]();for(let S=0;S<this[s(397)+"Queue"][s(460)];S++){let b=this[s(397)+s(838)][S];if(e[s(367)](this[s(1033)][s(1666)+"te"],this[s(751)])&&e.aPhHC(null,b))if(e[s(1040)]!=="NYNra")this[s(1033)]&&this._ws[s(1383)](b),this[s(397)+"Queue"][S]=null;else{let m=this[s(1669)][s(1307)+"tInterce"+s(1695)](_0xb2d5b3,_0x143f24);this[s(373)+"hCloseEv"+s(1342)](l[s(1090)](_0x37f6b8,l[s(1052)],{code:_0x2c077c,reason:_0x4845a5,wasClean:!0,willReconnect:m})),m&&this[s(485)]()}else break}this[s(397)+s(838)]=this[s(397)+"Queue"][s(736)](S=>!!S),this[s(1449)+"gTimeoutId"]=e[s(1097)](setTimeout,()=>this[s(957)](),h),this[s(373)+s(748)+"nt"](a),this[s(491)+"er"]&&this._ws&&(this[s(1033)].binaryType=this[s(1008)+s(1117)]);let g=this["_endpoin"+s(879)]?.["getCurre"+s(1482)+"nt"]();this[s(1178)](s(772)+g+s(352)),e.uWEhi(n)},fg=async function(a,n){let s=t,l=this[s(542)+s(879)]?.[s(1393)+s(1482)+"nt"]();this[s(1178)](s(772)+l),e.cRCeK(n)};class hg extends ua{constructor(n){let s=t,l={JwvnC:function(b,m,R,B){return b(m,R,B)},uEGPy:function(b,m,R){return e.VyoXa(b,m,R)},ZqfuE:e[s(327)],FUqDJ:function(b,m){return e.jEZON(b,m)}};super(),this[s(1747)+s(363)+s(459)]=!0,this[s(491)+"er"]=nr,this[s(877)]=Rp,this._isMiniTT=Cn,this[s(992)+"X"]=Yr,this[s(1050)+"r"]=Xr,this["_message"+s(838)]=[],this[s(542)+"tManager"]=null,this[s(791)+s(664)]=!1,this[s(1008)+s(1117)]=e[s(1544)],this[s(485)+s(416)]=!1,this[s(485)+s(1733)+s(1096)]=null,this[s(381)+s(671)+s(911)]=null,this[s(1449)+"gTimeoutId"]=null,this._seqId=0,this[s(604)]=!1,this[s(949)]="",this[s(942)+s(513)]=null,this[s(448)+s(550)]=null,this[s(945)+s(1270)]=null,this._protocols=s(1207),this[s(532)]=3,this[s(466)+"NG"]=0,this[s(751)]=1,this.CLOSING=2,this[s(1730)]=b=>{let m=s;try{l[m(1326)](al,this,b,[lg,ug,fg])}catch(R){let B=l.uEGPy(dt,l.ZqfuE,{message:R[m(464)],code:nn[m(1281)+"OR"],error:R});this["_dispatc"+m(1591)+m(1342)](B)}},this[s(933)+"ge"]=async b=>{let m=s,{pingInterval:R,pingFrequency:B}=this._options;if((e.SsCRH("hi",b[m(444)])&&e[m(1241)]===B||e[m(806)](e[m(1213)],B))&&(this[m(602)+"ngTimer"](),this[m(1718)](e[m(725)],e.ODfMA),this._pingPongTimeoutId=e[m(1174)](setTimeout,this[m(957)][m(1023)](this),R)),!e.OSUEB("hi",b[m(444)]))try{e[m(706)](e[m(649)],"mcSum")?(eQczxH[m(351)](_0x4b67a3,_0x230005,82),eQczxH[m(351)](_0x567181,_0x2d5196,_0x1fac48)):e.VIrPT(al,this,b,[jp,Hp,cg,dg,ag,qp])}catch(F){let V=dt(e[m(327)],{message:F[m(464)],code:nn[m(1707)+m(1704)],error:F});this[m(373)+m(1591)+m(1342)](V)}},this._onError=b=>{let m=s,R=this[m(542)+"tManager"]?.[m(1520)+"chMaxTries"](),B=this[m(542)+"tManager"]?.["getCurre"+m(1482)+"nt"]();if(R&&!b[m(464)]){let F=m(809)+B+(" fail, m"+m(906)+m(1181)+"ed");this[m(373)+m(1591)+m(1342)](e.LgGWX(dt,e[m(327)],{message:F,code:nn[m(1319)+"IES_ERROR"],error:b}));return}this[m(1033)]&&e[m(1620)](this[m(1033)][m(1666)+"te"],this[m(751)])&&this[m(1057)+m(924)](),this[m(373)+m(1591)+m(1342)](e.rWOTf(dt,"error",{message:b.message,code:nn[m(1725)+"RROR"],error:b}))},this._onClose=async b=>{let m=s;if(e[m(961)](e[m(368)],m(1074))){let R=_0x1ca256[m(464)].payload;R&&_0xe84c45[m(1266)+"rs"](R)}else{this[m(591)+m(1099)](),this[m(602)+m(1105)](),this[m(1067)+m(1387)+"rs"](),this[m(1033)]=null,this[m(485)+m(416)]=!1;let R=this._endpointManager?.[m(1520)+"chMaxTries"]();if(!R&&this[m(1636)+m(511)]()&&!this[m(791)+m(664)])if(e[m(1173)](e[m(387)],e[m(387)]))eQczxH[m(351)](_0x100f57,_0x1b6991,eQczxH.FUqDJ(127&_0x9d12f,128)),_0x469657>>>=7;else{let B=this[m(542)+m(879)]?.[m(1393)+"ntEndpoint"](),F=this._options[m(1307)+m(873)+m(1695)](b.code,b[m(1677)]);this["_dispatc"+m(1571)+m(1342)](e[m(1684)](gt,e[m(597)],{code:1006,reason:b[m(1677)]||m(1209)+m(950)+m(1169)+m(519)+m(1577)+"ame: "+B,willReconnect:F})),F&&this[m(485)]();return}if(b[m(882)]!==1e3&&this._readyClosed){this[m(373)+m(1571)+m(1342)](e[m(1032)](gt,e[m(597)],{code:1e3,reason:e[m(919)]})),this[m(542)+"tManager"]?.[m(978)+"pointConfig"](),this[m(945)+m(1270)]?.["resetCou"+m(1186)]();return}if(e[m(770)](1e3,b[m(882)])&&R){let B=this[m(542)+m(879)]?.["getCurre"+m(1482)+"nt"](),F=b[m(1677)];F||(F=await e[m(529)](Mp,this[m(949)])),F=m(1209)+"ng faile"+m(951)+F+(m(429)+"me: ")+B+(", max retries re"+m(1481)),this["_dispatchCloseEv"+m(1342)](e[m(1389)](gt,e[m(597)],{code:b[m(882)],reason:F}));let V=m(809)+B+(m(1713)+m(906)+m(1181)+"ed");this[m(373)+m(1591)+m(1342)](e.woCfI(dt,m(870),{message:V,code:nn[m(1319)+m(562)+"R"]})),this[m(542)+m(879)]?.[m(978)+m(1422)+"fig"](),this[m(945)+m(1270)]?.["resetCou"+m(1186)]();return}if(b[m(882)]!==1e3&&!b.reason){let B=this[m(542)+m(879)]?.[m(1393)+m(1482)+"nt"]();this[m(373)+"hCloseEv"+m(1342)](e.khUYh(gt,e.JfpBI,{code:b.code,reason:"connecti"+m(950)+"d, unkno"+m(519)+m(1577)+"ame: "+B})),this[m(542)+m(879)]?.[m(978)+m(1422)+"fig"](),this[m(945)+m(1270)]?.resetCounter();return}this[m(373)+m(1571)+m(1342)](b),this._endpointManager?.["resetEnd"+m(1422)+m(585)](),this[m(945)+"sCounter"]?.["resetCou"+m(1186)]()}},this[s(925)]=null,this[s(1185)]=null,this.onmessage=null,this[s(1193)]=null,this[s(1199)+s(539)]=null,this["onReceiv"+s(323)]=null,this[s(1320)+"mediatel"+s(1464)+"ct"]=null,this[s(535)+s(815)]=this._handleOnLine[s(1023)](this),this[s(535)+s(741)]=this[s(535)+s(741)][s(1023)](this),this[s(1584)+s(786)]=this._handlePageHide[s(1023)](this),this[s(1584)+s(410)]=this._handlePageShow[s(1023)](this),this[s(1669)]={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:e[s(700)](1,0),service:0,logIDGenerator:o,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:e[s(1213)],pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:e[s(692)],env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:h,ws:g}=n,S=Array[s(739)](h)?h:e.uKSBs(e[s(582)],typeof h)?[h]:[];if(!S||e[s(1080)](0,S[s(460)]))throw new Error(s(1127)+s(1690)+s(1734));if(!e.PKOCt(Dp,g))throw new Error(e[s(1340)]);Object[s(424)](this[s(1669)],n),this["_endpoin"+s(879)]=new ol(S,this[s(1669)][s(799)+"es"]),this[s(945)+"sCounter"]=new Np(this[s(1669)][s(1204)+s(666)]),this[s(1669)].automaticOpen&&(this[s(604)]=!0,this._connect()),this[s(1669)][s(1062)+s(537)+"nged"]&&(this[s(1384)+"T"]||this[s(992)+"X"]?this[s(1128)+s(1356)+"ange"]():this[s(491)+"er"]&&this[s(1612)+"balEvent"+s(1020)]())}["_handleO"+t(815)](){let n=t;if(e[n(1513)]("sVkLu",e.VUSDA)){if(this[n(1669)][n(1254)+n(1614)+"nect"]||this[n(791)+n(664)])return;this[n(996)+n(539)]()}else return _0x4882c4 instanceof _0x38dc95&&(beIKsU.lpZIk(_0x5be302,beIKsU[n(1344)])||_0x38daaf===n(989))?!0:beIKsU[n(888)](_0x5182f8,_0x157ba1)}["_handleO"+t(741)](){let n=t;this[n(383)+n(1437)+"t"]();let s=e[n(1724)](la,e[n(1548)],{message:e[n(869)]});this[n(1320)+n(1667)+"yReconnect"]&&this[n(1320)+n(1667)+n(1464)+"ct"](s)}["_initGlo"+t(454)+t(1020)](){let n=t;this[n(491)+"er"]&&window[n(1395)+n(1020)](e.DBzXS,this["_handleO"+n(815)]),this[n(491)+"er"]&&window[n(1395)+n(1020)](e.uxeRj,this[n(535)+n(741)]),this[n(491)+"er"]&&window[n(1395)+n(1020)](e[n(492)],this[n(1584)+"ageHide"]),this._isBrowser&&window[n(1395)+n(1020)](n(639),this[n(1584)+n(410)])}[t(782)+"balEventListener"](){let n=t;this._isBrowser&&window[n(1183)+n(1467)+"ner"](e.DBzXS,this[n(535)+n(815)]),this[n(491)+"er"]&&window[n(1183)+"entListener"](e[n(484)],this["_handleO"+n(741)]),this[n(491)+"er"]&&window[n(1183)+"entListe"+n(1714)](e[n(492)],this[n(1584)+"ageHide"]),this[n(491)+"er"]&&window[n(1183)+"entListe"+n(1714)](e.WoiYG,this["_handleP"+n(410)])}["_handleP"+t(786)](n){let s=t;!n[s(339)+"d"]&&(this[s(491)+"er"]&&window[s(1183)+s(1467)+s(1714)](e[s(492)],this[s(1584)+s(786)]),this[s(491)+"er"]&&window[s(1183)+s(1467)+s(1714)](e[s(1649)],this[s(1584)+"ageShow"]),this[s(1739)]()),this[s(491)+"er"]&&window[s(1183)+"entListe"+s(1714)](s(766),this[s(535)+s(815)]),this[s(491)+"er"]&&window[s(1183)+"entListener"](e[s(484)],this[s(535)+s(741)])}[t(1584)+"ageShow"](n){let s=t;n[s(339)+"d"]&&(this["_navigat"+s(511)]()&&(!this[s(1033)]||this._ws[s(1666)+"te"]!==this[s(751)]||e[s(1265)](this._ws[s(1666)+"te"],this.CONNECTING))&&this[s(535)+"nLine"](),this[s(491)+"er"]&&window[s(1395)+s(1020)](s(766),this[s(535)+"nLine"]),this[s(491)+"er"]&&window[s(1395)+s(1020)](e[s(484)],this._handleOffLine))}async[t(737)+t(1157)](n){let s=t,{fpID:l,deviceID:h,bddID:g,ttwID:S,accessKey:b,aID:m,customParams:R={},enableAutoAck:B,enableQoS:F,QoSLevel:V,env:$}=this[s(1669)],pe,rt,$e;this[s(491)+"er"]||this[s(992)+"X"]||this[s(1384)+"T"]?(pe=location&&e.QiNxQ(e[s(1617)],location[s(1019)])?e.gkbNn:s(1396),rt=n[s(1623)](/((^ws)|(^http))((?:[s]*:\/\/))/,""),$e=/^wss(.*:\/\/)/[s(603)](n)?n:""+pe+rt):(pe=e[s(1611)],rt=n[s(1623)](/(^http)((?:[s]*:\/\/))/,""),$e=/(^ws)((?:[s]*:\/\/))/.test(rt)?rt:""+pe+rt);let it=g?e[s(1220)]:S?e[s(1303)]:s(1508)+"d",pl=g||S||h;if(!pl||!it)throw new Error(s(1127)+s(1527)+s(1381)+s(881)+s(361));let xg=e[s(1065)]("function",typeof R)?await e[s(937)](R):R,pg=$?Lp($[s(1708)],$[s(1639)]):{},wa=Object.assign({device_platform:s(914),version_code:e[s(630)],access_key:b,fpid:l,aid:m,[it]:pl,xsack:B?1:0,xaack:B?1:0,xsqos:F?1:0,qos_level:F?V:void 0,qos_sdk_version:2,...pg},xg),gg=Object[s(807)](wa)[s(1255)]((_a,ya)=>wa[ya]!==void 0?""+_a+(_a?"&":"?")+ya+"="+wa[ya]:_a,"");return $e+s(802)+gg}async[t(485)](){let n=t,s={sHzSA:function(l,h){return l<=h},wKAci:function(l,h){return e.vHViS(l,h)},gChpu:function(l,h){return l+h}};if(!(this[n(485)+n(416)]||this[n(791)+n(664)])){this[n(485)+n(416)]=!0;try{let l=this[n(542)+n(879)]?.[n(1226)+n(1012)+n(1229)+n(614)+n(822)](),{timeoutInterval:h}=this[n(1669)];if(l){let S=this["_endpoin"+n(879)]?.[n(1393)+n(1482)+"nt"](),b=this[n(542)+n(879)]?.["replaceB"+n(798)+"pointAndUpdateCount"](),m=this[n(542)+n(879)]?.[n(1393)+n(1482)+n(697)+"ount"]();if(b){let R=n(809)+S+(n(1371)+n(1485)+n(417)+n(1590)+n(1219)+n(943)+n(1064))+b+(n(1237)+"y"),B=e[n(893)](dt,"error",{message:R,code:nn[n(1319)+n(562)+"R"]});this[n(1178)](R),this[n(373)+n(1591)+n(1342)](B),this[n(949)]=await this[n(737)+n(1157)](b),this._debug(n(809)+b+" "+m+n(618)),this[n(1067)+n(1387)+"rs"]()}else{let R=n(809)+S+(n(1371)+", max re"+n(417)+n(1481));this._debug(R),this[n(373)+"hErrorEvent"](dt(n(870),{message:R,code:nn[n(1319)+"IES_ERROR"]}));return}}else{let S=this["_endpoin"+n(879)]?.[n(1393)+n(1482)+n(1494)+n(1148)](),b=this[n(542)+n(879)]?.[n(1393)+n(1482)+n(697)+n(596)]();this[n(949)]=await this[n(737)+n(1157)](S||""),this[n(1178)](n(809)+S+" "+b+n(618)),this[n(1067)+n(1387)+"rs"]()}if(this._isInit)this._isInit=!1;else if(e[n(1304)]!=="hieGt"){let S=e[n(1543)](la,n(1307)+"t",{message:n(865)});this[n(1199)+"econnect"]&&this[n(1199)+n(539)](S)}else{if(FyAknx.sHzSA(_0x1c7567,-_0x2d580a))return _0x552b4b;if(FyAknx[n(1532)](FyAknx[n(1678)](_0x88b4fb,1),_0xec017))return _0x56dd66}let g=this[n(542)+n(879)]?.["getCurre"+n(1482)+n(697)+"ount"]()||0;e[n(1248)](g,1)&&await this[n(335)](e[n(415)](g,1)),this[n(1178)](n(1209)+n(379)+this[n(949)]+" protocols: "+this[n(1026)+"ls"]),this[n(1033)]=e[n(1538)](Pp,{url:this._url,protocols:[this[n(1026)+"ls"]],headers:this[n(1669)][n(412)+n(1150)+"s"][n(1131)+n(636)]},this[n(1669)].ws),(this[n(491)+"er"]||this[n(1050)+"r"])&&this[n(1033)]&&(this[n(1033)][n(1558)+"pe"]=this[n(1008)+n(1117)]),this[n(1661)+n(702)](),this[n(485)+n(1733)+"utId"]=e.uaivB(setTimeout,this[n(1426)+"ut"][n(1023)](this),h)}catch(l){throw this["_connect"+n(416)]=!1,l}}}["_clearTi"+t(1099)](){let n=t;e[n(1289)](clearTimeout,this[n(485)+"ionTimeoutId"]),this[n(485)+n(1733)+n(1096)]=null}[t(602)+t(1105)](){let n=t;clearTimeout(this._pingPongTimeoutId),e[n(1279)](clearTimeout,this[n(381)+n(671)+"tId"]),this[n(1449)+n(1355)+"Id"]=null,this[n(381)+n(671)+n(911)]=null}[t(1178)](...n){let s=t,l={Epdjf:e[s(1341)],ctZPf:e.BVDvl,ycIVI:"MAX_RETR"+s(562)+"R",VgBCv:e.JBGpn};if(e[s(1753)](e[s(1146)],e.RKBDS)){let h=(s(1054)+"5|1")[s(732)]("|"),g=0;for(;;){switch(h[g++]){case"0":_0x26d07c[_0x50e0e0[s(1725)+s(698)]=5001]=s(1725)+s(698);continue;case"1":return _0x3682dc;case"2":_0x523f0d[_0x3fa8e3[AObZvo[s(1007)]]=5002]=AObZvo[s(1007)];continue;case"3":_0x39cc90[_0x40f2c6[AObZvo.ctZPf]=5004]=AObZvo[s(1685)];continue;case"4":_0x4e042e[_0x38733b[AObZvo[s(1523)]]=5003]=AObZvo.ycIVI;continue;case"5":_0x1f6229[_0x4aac27.OPEN_ERROR=5005]=AObZvo[s(1044)];continue}break}}else this[s(1669)][s(903)]&&console[s(1164)][s(427)](console,[e[s(696)],...n])}["_getInte"+t(1505)+"e"](n){let s=t,{initReconnectInterval:l,maxReconnectInterval:h,reconnectIntervalGrowFactor:g}=this[s(1669)],S=l*Math[s(744)](g,e[s(824)](n,1));return e.NHGjO(S,h)?h:S}[t(957)](){let n=t;if(this[n(1033)]&&e.oRNdi(this._ws[n(1666)+"te"],this[n(466)+"NG"])){this["_clearPi"+n(1105)](),this[n(1449)+"gTimeoutId"]=setTimeout(this[n(957)].bind(this),this[n(1669)][n(852)+n(1114)]);return}if(!this[n(1033)]||e.Fguop(this[n(1033)].readyState,this[n(751)]))return void this[n(996)+"econnect"]();this._ws&&this[n(1033)][n(1383)]("hi"),this["_reconne"+n(671)+"tId"]=e[n(757)](setTimeout,this[n(996)+n(539)+n(890)].bind(this),this[n(1669)]["pingTime"+n(1160)+"val"])}[t(996)+t(539)+"Timeout"](){let n=t;this._pingLossCounter?.[n(1450)](),this[n(1718)](e[n(797)],e[n(1386)]),this["_pingLos"+n(1270)]?.["checkRea"+n(1470)+"nt"]()?this[n(996)+n(539)]():this[n(957)]()}[t(1636)+t(511)](){let n=t;return this[n(1384)+"T"]||this._isMiniWX?this["_miniNav"+n(363)+"line"]:(this[n(491)+"er"]||this[n(1050)+"r"])&&this._options[n(1062)+"tworkCha"+n(1735)]?navigator.onLine:!0}[t(996)+t(539)](){let n=t;!this[n(1636)+"orOnline"]()||this[n(791)+n(664)]||(this[n(542)+"tManager"]?.[n(978)+n(1422)+"fig"](),this[n(945)+"sCounter"]?.["resetCou"+n(1186)](),this[n(1033)]?this["_disconn"+n(924)](1001,e[n(1738)],!0):this[n(485)]())}[t(1128)+"etWorkCh"+t(899)](){let n=t;this[n(1384)+"T"]?tt[n(1555)+n(1061)+n(372)](({isConnected:s})=>{let l=n;this["_miniNav"+l(363)+l(459)]=s,s?this["_handleO"+l(815)]():this[l(535)+l(741)]()}):this._isMiniWX&&wx[n(1555)+n(1061)+n(372)](({isConnected:s})=>{let l=n;this["_miniNav"+l(363)+"line"]=s,s?this[l(535)+"nLine"]():this[l(535)+l(741)]()})}_wait(n){let s={UKVKU:function(l,h,g){return e[q(1406)](l,h,g)}};return new Promise(l=>{let h=q;s[h(821)](setTimeout,l,this[h(426)+h(1505)+"e"](n))})}[t(1057)+t(924)](n=1e3,s="",l=!1){let h=t;this[h(1033)]&&this[h(383)+"WebSocket"](n,s,l)}[t(1426)+"ut"](){let n=t,s=this[n(542)+n(879)]?.[n(1393)+"ntEndpoint"]();this[n(1178)](n(809)+s+n(1371)),this[n(1057)+n(924)](1001,e.NMKyK,!0)}[t(626)](n){let s=t,l=e[s(319)](zt,n);this[s(1033)]&&e[s(1346)](this._ws[s(1666)+"te"],this[s(751)])&&(this[s(1033)]&&this[s(1033)][s(1383)](l),this[s(1178)]("send_ack",n))}["_removeW"+t(1387)+"rs"](){let n=t;this[n(1033)]&&(this[n(1033)][n(1183)+n(1467)+"ner"](e[n(1359)],this._onOpen),this[n(1033)][n(1183)+n(1467)+n(1714)](e[n(597)],this[n(428)]),this[n(1033)][n(1183)+"entListe"+n(1714)](e[n(965)],this[n(933)+"ge"]),this[n(1033)][n(1183)+n(1467)+"ner"](e[n(327)],this[n(606)]))}["_addWsLi"+t(702)](){let n=t;this[n(1033)]&&(this[n(1033)][n(1395)+n(1020)](n(1582),this[n(1730)]),this._ws[n(1395)+n(1020)](e[n(597)],this[n(428)]),this[n(1033)][n(1395)+n(1020)](e[n(965)],this[n(933)+"ge"]),this._ws[n(1395)+n(1020)](e[n(327)],this._onError))}[t(1260)+t(1473)](n=1e3,s=""){let l=t;try{e.wUPXp===e[l(1112)]?beIKsU[l(353)](_0x1a0ae3,_0x527bc2)&&_0x254a59.set(_0x18b8e9,_0x540902):this[l(1033)]&&this._ws[l(1739)](n,s)}catch{}}["_destroy"+t(1437)+"t"](n=1e3,s="",l=!1){let h=t;if(this["_clearPi"+h(1105)](),this[h(591)+h(1099)](),this[h(1067)+"sListeners"](),this["_wsInsta"+h(1473)](1e3,s),this["_connect"+h(416)]=!1,l&&this["_navigat"+h(511)]()&&!this[h(791)+h(664)]){if(this[h(542)+"tManager"]?.[h(1520)+"chMaxTries"]()){let S=this[h(542)+h(879)]?.[h(1393)+"ntEndpoint"]();this[h(373)+"hCloseEv"+h(1342)](e.iLUQn(gt,e[h(597)],{code:1006,reason:h(809)+S+(h(1371)+", max retries re"+h(1481)),wasClean:!0}))}else{let S=this[h(1669)][h(1307)+h(873)+h(1695)](n,s);this[h(373)+h(1571)+h(1342)](e[h(1490)](gt,e[h(597)],{code:n,reason:s,wasClean:!0,willReconnect:S})),S&&this[h(485)]()}return}this[h(1636)+h(511)]()||this[h(791)+h(664)]?this[h(373)+h(1571)+h(1342)](e[h(1389)](gt,h(1739),{code:n,reason:e[h(919)]})):this[h(373)+h(1571)+"ent"](e.lKzOu(gt,h(1739),{code:1006,reason:e[h(1087)]})),this[h(1033)]=null,this[h(542)+"tManager"]?.[h(978)+h(1422)+"fig"](),this[h(945)+h(1270)]?.[h(1441)+h(1186)]()}[t(373)+"hOpenEvent"](n){let s=t;this.emit(e[s(1359)],n),this[s(1193)]&&this.onopen(n)}[t(373)+t(628)+t(1580)](n){let s=t;this[s(1718)](e[s(965)],n),this[s(1607)+"e"]&&this[s(1607)+"e"](n)}[t(373)+t(1535)+t(641)](n){let s=t;this[s(1718)](e[s(1274)],n),this[s(1610)+s(323)]&&this[s(1610)+s(323)](n)}[t(373)+"hErrorEv"+t(1342)](n){let s=t;this[s(1718)](e[s(327)],n),this[s(1185)]&&this[s(1185)](n)}[t(373)+t(1571)+"ent"](n){let s=t;this[s(1718)](e[s(597)],n),this.onclose&&this[s(925)](n)}get[t(1558)+"pe"](){let n=t;return this._ws?this[n(1033)][n(1558)+"pe"]:this[n(1008)+n(1117)]}set binaryType(n){let s=t;if(e.KDgPO(s(1440),e[s(787)]))this[s(1008)+s(1117)]=n,this[s(1033)]&&(this[s(1033)][s(1558)+"pe"]=n);else return new _0x1d1baa(_0x47d2fb,{data:_0x2135ea,message:_0x321968})}get[t(1431)+"nt"](){let n=t;return this._endpointManager?.["getCurrentEndpoi"+n(697)+"ount"]()||0}get[t(375)+t(1646)](){let n=t;return this[n(397)+n(838)].reduce((l,h)=>{let g=n;return e[g(461)]!==g(1134)?this[g(1642)+"s"][this[g(1250)+g(847)]]:(l+=h&&h[g(1338)+"th"]||0,l)},0)+(this[n(1033)]?this[n(1033)][n(375)+n(1646)]:0)}get[t(1625)+"ns"](){let n=t;return this[n(1033)]?this[n(1033)].extensions:""}get[t(1019)](){let n=t;return this[n(1033)]?this[n(1033)][n(1019)]:""}get readyState(){let n=t;if(e[n(522)]===n(348))return this[n(1033)]?this[n(1033)][n(1666)+"te"]:this[n(1669)]["automati"+n(1095)]?this[n(466)+"NG"]:this.CLOSED;this[n(1661)+n(702)]()}get[t(922)](){let n=t;return this[n(1033)]?this[n(1033)][n(922)]:this._url}[t(1739)](n=1e3,s){let l=t;if(e[l(388)](e[l(637)],l(1461))){let h=e.PubxL[l(732)]("|"),g=0;for(;;){switch(h[g++]){case"0":this[l(383)+l(1437)+"t"](n,s);continue;case"1":this[l(791)+"osed"]=!0;continue;case"2":if(e.yzhMj(this[l(1033)][l(1666)+"te"],this.CLOSED)||this[l(1033)][l(1666)+"te"]===this[l(1732)])return void this[l(1178)](e[l(405)]);continue;case"3":this[l(591)+"mer"]();continue;case"4":this[l(782)+"balEvent"+l(1020)]();continue;case"5":if(!this._ws)return void this._debug(e.XLWsP);continue;case"6":this[l(942)+"ger"]?.[l(648)]();continue;case"7":this[l(602)+l(1105)]();continue}break}}else this[l(1718)](e[l(1359)],_0x3187e6),this[l(1193)]&&this[l(1193)](_0x130195)}async[t(1383)](n,s){let l=t;if(n==null)throw new Error(e[l(1166)]);e.IliIo("number",typeof n)&&(n=JSON[l(710)+"y"](n)),e[l(582)]!=typeof n&&!e[l(1283)](n,ArrayBuffer)&&!(n[l(595)]&&e[l(1471)](n[l(595)],ArrayBuffer))&&(n=JSON[l(710)+"y"](n));let h=await e[l(357)](ll,n),g=e.wnVlq(Op,n),{method:S=0,service:b=this[l(1669)][l(554)],logID:m=this._options[l(1428)+l(518)](),headers:R=this[l(1669)][l(1292)],payloadEncoding:B=this[l(1669)][l(960)+l(952)],payloadType:F=this._options[l(1545)+l(1117)],logIDNew:V=this[l(1669)]["logIDNew"+l(463)][l(1628)+l(1329)+l(362)+"ew"]?e[l(1085)](i,this[l(1669)]["logIDNew"+l(463)][l(1358)]):""}=e.UsZjk(s,{});if(!b)throw new Error(e[l(1453)]);let $={SeqID:ue[l(1184)+"er"](this[l(422)]++),LogID:ue.fromNumber(m),service:b,method:S,headers:R,payloadEncoding:e[l(318)](B,Object)?B[l(1182)]?B[l(1182)]:"":B,payloadType:e.KjCwm(F,Object)?F[l(1653)]?F[l(1653)]:g:F||g,payload:h,LogIDNew:V},pe=e.NkEkc(zt,$);if(this._ws&&e[l(601)](this[l(1033)][l(1666)+"te"],this[l(751)]))this._ws&&this._ws[l(1383)](pe),this[l(1178)]("sent",$);else if(e[l(1634)](this[l(397)+l(838)].length,this[l(1669)]["maxMessa"+l(1517)+"ength"]))this[l(397)+l(838)][l(1017)](pe),this[l(1178)](e.cqihC,$);else if(e.nEZOA(e[l(975)],e[l(975)])){let rt=_0xd6edc9(_0x3f4fb6,_0x24b756[l(460)]);_0x49ba49[l(640)][l(1744)](_0x1dc8d6,rt)}else this[l(397)+l(838)].shift(),this[l(397)+l(838)].push(pe);return{seqID:this[l(422)],logID:m,logIDNew:V}}async[t(1307)+"t"](n){let s=t,l={JnyPs:function(S,b){return e[q(1657)](S,b)},bLZni:e.SdIqe,UupmJ:s(1004)+"e_success",ttAVl:e[s(797)]},{url:h}=e[s(1001)](n,{}),g=Array[s(739)](h)?h:e[s(452)](e[s(582)],typeof h)?[h]:[];n&&Object[s(424)](this[s(1669)],n),g&&g.length?this[s(542)+"tManager"]=new ol(g,this._options.maxRetries):this["_endpoin"+s(879)]?.["resetEnd"+s(1422)+s(585)](),this[s(945)+s(1270)]?.[s(1441)+"nter"](this[s(1669)][s(1204)+s(666)]),this[s(791)+s(664)]=!1,this[s(1033)]&&e.PsHgU(this._ws[s(1666)+"te"],this[s(532)])?this[s(1057)+"ect"](1e3,s(1460)+"econnect"+s(733),!0):e[s(1689)](e.PvOhO,e.PvOhO)?(this[s(604)]=!0,this[s(485)]()):(l[s(1136)](_0x233ceb,l[s(553)]),this[s(995)](l[s(1462)],_0x4800bd),this[s(995)](l[s(723)],_0x243573))}async[t(1745)](){let n=t;if(!this[n(485)+n(416)]){if(e[n(1100)](e[n(309)],n(338)))return _0x40accb["objectSt"+n(1416)][1]?void 0:_0x2e8087[n(1423)+n(1539)](_0x37b87a[n(1423)+n(1416)][0]);{let s=e[n(1598)].split("|"),l=0;for(;;){switch(s[l++]){case"0":this[n(945)+"sCounter"]?.[n(1441)+"nter"]();continue;case"1":this[n(542)+n(879)]?.[n(978)+n(1422)+"fig"]();continue;case"2":this["_readyCl"+n(664)]=!1;continue;case"3":this[n(485)]();continue;case"4":this[n(604)]=!0;continue}break}}}}[t(1395)+t(1020)](n,s){let l=t,h={wcnLG:function(g,S){return e[q(1058)](g,S)},fdagW:function(g,S){return g&S},YVEkh:function(g,S){return e[q(646)](g,S)},dayCL:function(g,S){return e[q(695)](g,S)},JuKrv:function(g,S){return e[q(1363)](g,S)},xodIx:function(g,S){return e[q(1245)](g,S)},lZLPQ:function(g,S){return e[q(1315)](g,S)},PgJKA:function(g,S){return e.eQUJv(g,S)},StYXu:function(g,S){return e[q(1363)](g,S)},nPaic:function(g,S){return e[q(1413)](g,S)},ApLkt:function(g,S){return e[q(398)](g,S)},mlyaV:function(g,S,b,m){return e.IGbQU(g,S,b,m)},aicXg:function(g,S){return e[q(738)](g,S)}};if(e[l(715)](e[l(872)],e.pvINi))this.on(n,s);else{if(_0x2d2cbe=pZJacm.wcnLG(pZJacm[l(1465)](127,_0x38c55e[_0x23f7ba]),0),pZJacm[l(889)](_0x230a1b[_0xca5688++],128))return{value:_0x245f20?_0x373b45:pZJacm[l(1331)](0,_0x1072a4),offset:_0x28b99d};if(_0x3c5239=pZJacm[l(1656)](pZJacm.dayCL(_0x5b3b2a,pZJacm.xodIx(127,_0xfdf4c3[_0x448285])<<7),0),pZJacm.lZLPQ(_0xef4f3d[_0x3dac30++],128))return{value:_0x11bd6c?_0x34906e:pZJacm.PgJKA(0,_0xda3898),offset:_0x119a7b};if(_0x235994=pZJacm[l(643)](pZJacm[l(1331)](_0x30e6cd,pZJacm[l(1155)](pZJacm[l(1005)](127,_0x5c7c4e[_0x39cb11]),14)),0),_0x559d7c[_0x2e6a30++]<128)return{value:_0x17983e?_0x66473c:pZJacm[l(1133)](0,_0x77bf65),offset:_0x3f3775};if(_0x314163=pZJacm[l(1656)](pZJacm[l(1331)](_0x461301,pZJacm[l(1155)](pZJacm.xodIx(127,_0x143fa3[_0x13d145]),21)),0),pZJacm[l(656)](_0x521204[_0x48f4c2++],128))return{value:_0xd94009?_0x31eea8:pZJacm[l(1740)](0,_0xaf5a28),offset:_0x56c67c};if(_0x17011e=pZJacm.JuKrv(pZJacm.PgJKA(_0x163427,pZJacm[l(1465)](15,_0x4be34b[_0x13ae7d])<<28),0),pZJacm.YVEkh(_0x36092d[_0xaa1f76++],128))return{value:_0x5e92d5?_0x459a4b:pZJacm[l(1331)](0,_0x177dbb),offset:_0x52b1b4};if((_0x1d9d78+=5)>_0x56094c[l(460)])throw _0x461496=_0xa09d7d[l(460)],pZJacm.mlyaV(_0x455562,_0x1e0133,10,_0x198655[l(460)]);return{value:_0x250f39?_0x209bdb:pZJacm[l(977)](0,_0x308e1a),offset:_0x140392}}}[t(1337)+"Event"](n){let s=t,{type:l}=n;this[s(1718)](l,n)}[t(1183)+t(1467)+t(1714)](n,s){this.off(n,s)}[t(1188)](){let n=t,s={bsKvp:function(l,h){return l(h)},vmqCT:n(1004)+n(747)+"s",JnWth:function(l,h,g){return l(h,g)},bWTWZ:e[n(797)]};return e[n(961)](e[n(1400)],e[n(366)])?new _0x1fc363(_0x4499f0,_0x264adc,_0x11e15f):new Promise((l,h)=>{let g=n,S={bkulj:function(R,B){return s[q(1102)](R,B)},nmjIm:s.vmqCT,obXcz:g(1004)+g(908)+"t",pqqFR:function(R,B){return s[g(1102)](R,B)}};this[g(602)+g(1105)](),this[g(1449)+"gTimeoutId"]=s[g(894)](setTimeout,this[g(957)][g(1023)](this),this[g(1669)][g(852)+g(1114)]);let b=()=>{let R=g;S[R(1063)](l,R(514)),this[R(995)](S.nmjIm,b),this[R(995)](S[R(359)],m)},m=()=>{let R=g;S[R(1648)](h,"timeout"),this[R(995)](S[R(1427)],b),this[R(995)](S.obXcz,m)};this.on(g(1004)+g(747)+"s",b),this.on(s[g(1750)],m),this[g(957)]()})}}})(),Ne["CustomCl"+L(443)]=Re[L(1333)+"oseEvent"],Ne[L(1475)+L(849)]=Re.CustomErrorEvent,Ne[L(1729)+"e"]=Re[L(1729)+"e"],Ne.Event=Re[L(1580)],Ne[L(891)]=Re[L(891)],Ne[L(701)+L(916)+L(837)]=Re[L(701)+L(916)+L(837)],Ne[L(916)+L(837)]=Re[L(916)+"vent"],Ne.OpenEvent=Re.OpenEvent,Ne[L(615)+L(329)]=Re[L(615)+L(329)],Ne["createCl"+L(443)]=Re[L(1189)+L(443)],Ne[L(1671)+L(849)]=Re[L(1671)+L(849)],Ne[L(1533)+"ssageEvent"]=Re["createMe"+L(1316)+"nt"],Ne.createOpenEvent=Re["createOp"+L(1630)],Ne[L(1415)+L(1345)+L(837)]=Re[L(1415)+L(1345)+L(837)],Ne[L(1060)+L(1124)]=Re["decodedF"+L(1124)],Ne[L(1435)+L(1664)]=Re[L(1435)+L(1664)];for(Uo in Re)["CustomCl"+L(443),L(1475)+"rorEvent",L(1729)+"e",L(1580),"FWS",L(701)+L(916)+L(837),L(916)+L(837),"OpenEvent",L(615)+L(329),L(1189)+L(443),L(1671)+L(849),L(1533)+L(1316)+"nt",L(970)+L(1630),"createRe"+L(1345)+"vent",L(1060)+L(1124),L(1435)+L(1664)][L(1354)](Uo)===-1&&(Ne[Uo]=Re[Uo]);var Uo;Object[L(408)+L(851)](Ne,"__esModule",{value:!0})});import{existsSync as vS,openSync as SS}from"node:fs";import{mkdir as IS}from"node:fs/promises";import{dirname as AS}from"node:path";import{fileURLToPath as kS}from"node:url";function RS(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function Fd(t=Q()){return vS(t.libEntry)?t.libEntry:kS(new URL("../index.ts",import.meta.url))}async function jx(t={}){let e=t.paths??Q(),r=t.entryOverride??Fd(e),i=RS(e,process.env.COZE_BRIDGE_LOG_MODE);await IS(AS(i),{recursive:!0});let o=SS(i,"a"),d=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],u=nt(process.execPath,d,{detached:!0,stdio:["ignore",o,o],env:{...process.env,[rs]:"1"}});if(u.unref(),typeof u.pid!="number")throw new Error("failed to spawn daemon (no pid)");return TS.info("daemon spawned",{pid:u.pid,entry:r}),{pid:u.pid,entry:r}}var TS,rs,Yo=Qe(()=>{"use strict";Kt();te();De();TS=G("spawn-daemon"),rs="COZE_BRIDGE_DAEMON"});import{spawn as v1}from"node:child_process";import{mkdir as S1,unlink as I1,writeFile as A1}from"node:fs/promises";import{dirname as k1,join as T1}from"node:path";function Vr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function R1(t){if(!t)return"";let e=Object.entries(t).map(([r,i])=>` <key>${Vr(r)}</key>
21
+ <string>${Vr(i)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function c2(t,e){return new Promise((r,i)=>{let o=t2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var Wr,ns,ta,Hd,$h=Je(()=>{"use strict";ne();Wr=G("supervisor.launchd"),ns="ai.coze.bridge",ta=c2,Hd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function C1(t,e){return new Promise((r,i)=>{let o=v1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Kr,ss,ia,Kd,lp=Qe(()=>{"use strict";te();Kr=G("supervisor.launchd"),ss="ai.coze.bridge",ia=C1,Kd={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
30
30
  <key>Label</key>
31
- <string>${ns}</string>
31
+ <string>${ss}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${Kr(t.nodeBin)}</string>
35
- <string>${Kr(t.entry)}</string>
34
+ <string>${Vr(t.nodeBin)}</string>
35
+ <string>${Vr(t.entry)}</string>
36
36
  <string>--daemon</string>
37
37
  </array>
38
38
  <key>RunAtLoad</key>
@@ -42,13 +42,13 @@ ${e}
42
42
  <key>ThrottleInterval</key>
43
43
  <integer>10</integer>
44
44
  <key>StandardOutPath</key>
45
- <string>${Kr(t.logFile)}</string>
45
+ <string>${Vr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${Kr(t.logFile)}</string>${a2(t.env)}
47
+ <string>${Vr(t.logFile)}</string>${R1(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return o2(t.homeDir,"Library","LaunchAgents",`${ns}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await n2(s2(i),{recursive:!0}),await i2(i,this.renderConfig(t),"utf8"),Wr.info("plist written",{plistPath:i,activate:r}),!r)return;await ta("launchctl",["unload","-w",i]).catch(c=>Wr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ta("launchctl",["load","-w",i]),Wr.info("launchd job loaded",{label:ns});let o=process.getuid?.()??0;await ta("launchctl",["kickstart","-k",`gui/${o}/${ns}`]),Wr.info("launchd job kickstarted",{label:ns,uid:o})},async uninstall(t){let e=this.configPath(t);await ta("launchctl",["unload","-w",e]).catch(r=>Wr.warn("launchctl unload failed (ignored)",{err:String(r)})),await r2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Wr.info("launchd job removed",{plistPath:e})}}});import{spawn as d2}from"node:child_process";import{mkdir as l2,unlink as u2,writeFile as f2}from"node:fs/promises";import{dirname as x2,join as Vh}from"node:path";function ra(t,e){return t.isRoot?e:["--user",...e]}function p2(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
- `):""}function ia(t,e){return new Promise((r,i)=>{let o=d2(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var na,$r,h2,Gd,Zh=Je(()=>{"use strict";ne();na=G("supervisor.systemd"),$r="coze-bridge.service",h2="/etc/systemd/system";Gd={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return T1(t.homeDir,"Library","LaunchAgents",`${ss}.plist`)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t);if(await S1(k1(i),{recursive:!0}),await A1(i,this.renderConfig(t),"utf8"),Kr.info("plist written",{plistPath:i,activate:r}),!r)return;await ia("launchctl",["unload","-w",i]).catch(c=>Kr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(c)})),await ia("launchctl",["load","-w",i]),Kr.info("launchd job loaded",{label:ss});let o=process.getuid?.()??0;await ia("launchctl",["kickstart","-k",`gui/${o}/${ss}`]),Kr.info("launchd job kickstarted",{label:ss,uid:o})},async uninstall(t){let e=this.configPath(t);await ia("launchctl",["unload","-w",e]).catch(r=>Kr.warn("launchctl unload failed (ignored)",{err:String(r)})),await I1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),Kr.info("launchd job removed",{plistPath:e})}}});import{spawn as P1}from"node:child_process";import{mkdir as D1,unlink as O1,writeFile as L1}from"node:fs/promises";import{dirname as N1,join as up}from"node:path";function oa(t,e){return t.isRoot?e:["--user",...e]}function B1(t){return t?Object.entries(t).map(([e,r])=>{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${i}"`}).join(`
51
+ `):""}function aa(t,e){return new Promise((r,i)=>{let o=P1(t,e,{stdio:["ignore","pipe","pipe"]}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var sa,Zr,M1,Vd,fp=Qe(()=>{"use strict";te();sa=G("supervisor.systemd"),Zr="coze-bridge.service",M1="/etc/systemd/system";Vd={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
52
52
  Description=Coze Bridge daemon
53
53
  After=network.target
54
54
 
@@ -59,10 +59,10 @@ Restart=always
59
59
  RestartSec=3
60
60
  StandardOutput=append:${t.logFile}
61
61
  StandardError=append:${t.logFile}
62
- ${p2(t.env)}
62
+ ${B1(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?Vh(h2,$r):Vh(t.homeDir,".config","systemd","user",$r)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await l2(x2(i),{recursive:!0}),await f2(i,this.renderConfig(t),"utf8"),na.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await ia("systemctl",ra(t,["daemon-reload"])),await ia("systemctl",ra(t,r?["enable","--now",$r]:["enable",$r])),na.info("systemd unit enabled",{unitName:$r,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await ia("systemctl",ra(t,["disable","--now",$r])).catch(r=>na.warn("systemctl disable failed (ignored)",{err:String(r)})),await u2(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ia("systemctl",ra(t,["daemon-reload"])).catch(()=>{}),na.info("systemd unit removed",{unitPath:e})}}});import{spawn as g2}from"node:child_process";import{join as m2}from"node:path";function Jh(t,e){return new Promise((r,i)=>{let o=g2(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",l=>{c+=l.toString("utf8")}),o.on("error",i),o.on("close",l=>{l===0?r():i(new Error(`${t} ${e.join(" ")} exited ${l}: ${c.trim()}`))})})}var qd,sa,jd,Yh=Je(()=>{"use strict";ne();qd=G("supervisor.taskscheduler"),sa="CozeBridge",jd={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?up(M1,Zr):up(t.homeDir,".config","systemd","user",Zr)},async install(t,e){let r=e?.activate!==!1,i=this.configPath(t),o=t.isRoot?"system":"user";await D1(N1(i),{recursive:!0}),await L1(i,this.renderConfig(t),"utf8"),sa.info("systemd unit written",{unitPath:i,mode:o,activate:r}),await aa("systemctl",oa(t,["daemon-reload"])),await aa("systemctl",oa(t,r?["enable","--now",Zr]:["enable",Zr])),sa.info("systemd unit enabled",{unitName:Zr,mode:o,activate:r})},async uninstall(t){let e=this.configPath(t);await aa("systemctl",oa(t,["disable","--now",Zr])).catch(r=>sa.warn("systemctl disable failed (ignored)",{err:String(r)})),await O1(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await aa("systemctl",oa(t,["daemon-reload"])).catch(()=>{}),sa.info("systemd unit removed",{unitPath:e})}}});import{spawn as F1}from"node:child_process";import{join as z1}from"node:path";function hp(t,e){return new Promise((r,i)=>{let o=F1(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),c="";o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",i),o.on("close",d=>{d===0?r():i(new Error(`${t} ${e.join(" ")} exited ${d}: ${c.trim()}`))})})}var Zd,ca,Jd,xp=Qe(()=>{"use strict";te();Zd=G("supervisor.taskscheduler"),ca="CozeBridge",Jd={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
66
66
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
67
67
  <RegistrationInfo>
68
68
  <Description>Coze Bridge daemon</Description>
@@ -86,48 +86,50 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return m2(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Jh("schtasks",["/Create","/SC","ONLOGON","/TN",sa,"/TR",r,"/RU",t.userName,"/F"]),qd.info("task scheduler entry created",{task:sa,logFile:t.logFile})},async uninstall(t){await Jh("schtasks",["/Delete","/TN",sa,"/F"]).catch(e=>qd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),qd.info("task scheduler entry removed",{task:sa})}}});var Xh={};ya(Xh,{buildContext:()=>v2,getSupervisor:()=>y2,launchdSupervisor:()=>Hd,systemdSupervisor:()=>Gd,taskSchedulerSupervisor:()=>jd});import{homedir as w2,userInfo as _2}from"node:os";function y2(t=process.platform){switch(t){case"darwin":return Hd;case"linux":return Gd;case"win32":return jd;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function E2(){let t={};for(let e of b2){let r=process.env[e];r&&(t[e]=r)}return t}function v2(){let t=Q();return{nodeBin:process.execPath,entry:Dd(t),logFile:t.logFile,homeDir:w2(),userName:_2().username,isRoot:process.getuid?.()===0,env:E2()}}var b2,Qh=Je(()=>{"use strict";Pe();Vo();$h();Zh();Yh();b2=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});ne();rn();var yl=G("acp-installer-warmup"),Ag=["claude-code","codex"];async function bl(t={}){let e=t.ensure??sr,i=(await Promise.allSettled(Ag.map(async o=>{let c=await e(o);yl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&yl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}an();ne();import{readdir as Gg}from"node:fs/promises";import{mkdir as Il,readFile as Ug,writeFile as Al}from"node:fs/promises";import{join as Ta}from"node:path";var Hg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function cr(t,e,r){await Il(t,{recursive:!0});let i=Hg[e],o=Ta(t,i);return await Al(o,r??"","utf8"),o}async function Ca(t,e,r){let i=Ta(t,".claude");await Il(i,{recursive:!0});let o=Ta(i,"settings.local.json"),c={};try{let u=await Ug(o,"utf8"),x=JSON.parse(u);typeof x=="object"&&x!==null&&!Array.isArray(x)&&(c=x)}catch{}let l=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")l.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");l.defaultMode===void 0&&(l.defaultMode=r)}return c.permissions=l,await Al(o,JSON.stringify(c,null,2),"utf8"),o}var Ke=G("agent-detail-sync"),qg=6e4,jg=5*6e4,xs=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await Gg(r)}catch(o){Ke.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Ke.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await Ne(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Ke.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(l){Ke.warn("detail sync failed for agent, skipping",{agentId:o,err:String(l)})}}})),Ke.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Ke.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Ke.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await Ne(e,this.opts.paths);if(!i){Ke.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(x){Ke.warn("detail RPC failed, using local data",{agentId:e,err:String(x)});let h=this.retryQueue.get(e),w=h?Math.min(h.currentDelay*2,jg):qg;this.retryQueue.set(e,{dueAt:Date.now()+w,currentDelay:w});return}if(o.agentId&&o.agentId!==e){Ke.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,l=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,l=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Ke.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Ke.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Ke.debug("detail sync: no diff",{agentId:e});return}await Xe(i,this.opts.paths),Ke.info("detail sync: config updated",{agentId:e,identityChanged:l,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Ke.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):l&&(await cr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var $f=zt(su(),1);import{lstat as Gc,mkdir as qc,readFile as qf,readdir as S_,rm as I_,stat as A_,writeFile as jc}from"node:fs/promises";import{dirname as T_,join as Dt,normalize as C_,relative as $c,resolve as Wc,sep as jf}from"node:path";import{Readable as Wf}from"node:stream";import{pipeline as Kf}from"node:stream/promises";import fm from"events";import Qe from"fs";import{EventEmitter as Tc}from"node:events";import Uu from"node:stream";import{StringDecoder as xm}from"node:string_decoder";import qu from"node:path";import yr from"node:fs";import{dirname as Am,parse as Tm}from"path";import{EventEmitter as Nm}from"events";import cc from"assert";import{Buffer as Hn}from"buffer";import*as lu from"zlib";import Mm from"zlib";import{posix as xr}from"node:path";import{basename as dw}from"node:path";import Ws from"fs";import Rt from"fs";import mu from"path";import{win32 as bw}from"node:path";import Su from"path";import sf from"node:fs";import Fw from"node:assert";import{randomBytes as of}from"node:crypto";import re from"node:fs";import Oe from"node:path";import af from"fs";import eo from"node:fs";import bi from"node:path";import it from"node:fs";import Ww from"node:fs/promises";import Vs from"node:path";import{join as wf}from"node:path";import rt from"node:fs";import bf from"node:path";var lm=Object.defineProperty,um=(t,e)=>{for(var r in e)lm(t,r,{get:e[r],enumerable:!0})},ou=typeof process=="object"&&process?process:{stdout:null,stderr:null},hm=t=>!!t&&typeof t=="object"&&(t instanceof jn||t instanceof Uu||pm(t)||gm(t)),pm=t=>!!t&&typeof t=="object"&&t instanceof Tc&&typeof t.pipe=="function"&&t.pipe!==Uu.Writable.prototype.pipe,gm=t=>!!t&&typeof t=="object"&&t instanceof Tc&&typeof t.write=="function"&&typeof t.end=="function",Ut=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),dn=Symbol("emittedEnd"),ws=Symbol("emittingEnd"),ii=Symbol("emittedError"),_s=Symbol("closed"),au=Symbol("read"),ys=Symbol("flush"),cu=Symbol("flushChunk"),pt=Symbol("encoding"),fr=Symbol("decoder"),Me=Symbol("flowing"),si=Symbol("paused"),mr=Symbol("resume"),Be=Symbol("buffer"),$e=Symbol("pipes"),Fe=Symbol("bufferLength"),La=Symbol("bufferPush"),bs=Symbol("bufferShift"),We=Symbol("objectMode"),ve=Symbol("destroyed"),Na=Symbol("error"),Ma=Symbol("emitData"),du=Symbol("emitEnd"),Ba=Symbol("emitEnd2"),At=Symbol("async"),Fa=Symbol("abort"),Es=Symbol("aborted"),oi=Symbol("signal"),Dn=Symbol("dataListeners"),nt=Symbol("discarded"),ai=t=>Promise.resolve().then(t),mm=t=>t(),wm=t=>t==="end"||t==="finish"||t==="prefinish",_m=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,ym=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Hu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[mr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},bm=class extends Hu{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},Em=t=>!!t.objectMode,vm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",jn=class extends Tc{[Me]=!1;[si]=!1;[$e]=[];[Be]=[];[We];[pt];[At];[fr];[Ut]=!1;[dn]=!1;[ws]=!1;[_s]=!1;[ii]=null;[Fe]=0;[ve]=!1;[oi];[Es]=!1;[Dn]=0;[nt]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Em(e)?(this[We]=!0,this[pt]=null):vm(e)?(this[pt]=e.encoding,this[We]=!1):(this[We]=!1,this[pt]=null),this[At]=!!e.async,this[fr]=this[pt]?new xm(this[pt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Be]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[$e]});let{signal:r}=e;r&&(this[oi]=r,r.aborted?this[Fa]():r.addEventListener("abort",()=>this[Fa]()))}get bufferLength(){return this[Fe]}get encoding(){return this[pt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[We]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[At]}set async(t){this[At]=this[At]||!!t}[Fa](){this[Es]=!0,this.emit("abort",this[oi]?.reason),this.destroy(this[oi]?.reason)}get aborted(){return this[Es]}set aborted(t){}write(t,e,r){if(this[Es])return!1;if(this[Ut])throw new Error("write after end");if(this[ve])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[At]?ai:mm;if(!this[We]&&!Buffer.isBuffer(t)){if(ym(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(_m(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[We]?(this[Me]&&this[Fe]!==0&&this[ys](!0),this[Me]?this.emit("data",t):this[La](t),this[Fe]!==0&&this.emit("readable"),r&&i(r),this[Me]):t.length?(typeof t=="string"&&!(e===this[pt]&&!this[fr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[pt]&&(t=this[fr].write(t)),this[Me]&&this[Fe]!==0&&this[ys](!0),this[Me]?this.emit("data",t):this[La](t),this[Fe]!==0&&this.emit("readable"),r&&i(r),this[Me]):(this[Fe]!==0&&this.emit("readable"),r&&i(r),this[Me])}read(t){if(this[ve])return null;if(this[nt]=!1,this[Fe]===0||t===0||t&&t>this[Fe])return this[Ht](),null;this[We]&&(t=null),this[Be].length>1&&!this[We]&&(this[Be]=[this[pt]?this[Be].join(""):Buffer.concat(this[Be],this[Fe])]);let e=this[au](t||null,this[Be][0]);return this[Ht](),e}[au](t,e){if(this[We])this[bs]();else{let r=e;t===r.length||t===null?this[bs]():typeof r=="string"?(this[Be][0]=r.slice(t),e=r.slice(0,t),this[Fe]-=t):(this[Be][0]=r.subarray(t),e=r.subarray(0,t),this[Fe]-=t)}return this.emit("data",e),!this[Be].length&&!this[Ut]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[Ut]=!0,this.writable=!1,(this[Me]||!this[si])&&this[Ht](),this}[mr](){this[ve]||(!this[Dn]&&!this[$e].length&&(this[nt]=!0),this[si]=!1,this[Me]=!0,this.emit("resume"),this[Be].length?this[ys]():this[Ut]?this[Ht]():this.emit("drain"))}resume(){return this[mr]()}pause(){this[Me]=!1,this[si]=!0,this[nt]=!1}get destroyed(){return this[ve]}get flowing(){return this[Me]}get paused(){return this[si]}[La](t){this[We]?this[Fe]+=1:this[Fe]+=t.length,this[Be].push(t)}[bs](){return this[We]?this[Fe]-=1:this[Fe]-=this[Be][0].length,this[Be].shift()}[ys](t=!1){do;while(this[cu](this[bs]())&&this[Be].length);!t&&!this[Be].length&&!this[Ut]&&this.emit("drain")}[cu](t){return this.emit("data",t),this[Me]}pipe(t,e){if(this[ve])return t;this[nt]=!1;let r=this[dn];return e=e||{},t===ou.stdout||t===ou.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[$e].push(e.proxyErrors?new bm(this,t,e):new Hu(this,t,e)),this[At]?ai(()=>this[mr]()):this[mr]()),t}unpipe(t){let e=this[$e].find(r=>r.dest===t);e&&(this[$e].length===1?(this[Me]&&this[Dn]===0&&(this[Me]=!1),this[$e]=[]):this[$e].splice(this[$e].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[nt]=!1,this[Dn]++,!this[$e].length&&!this[Me]&&this[mr]();else if(t==="readable"&&this[Fe]!==0)super.emit("readable");else if(wm(t)&&this[dn])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ii]){let i=e;this[At]?ai(()=>i.call(this,this[ii])):i.call(this,this[ii])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Dn]=this.listeners("data").length,this[Dn]===0&&!this[nt]&&!this[$e].length&&(this[Me]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Dn]=0,!this[nt]&&!this[$e].length&&(this[Me]=!1)),e}get emittedEnd(){return this[dn]}[Ht](){!this[ws]&&!this[dn]&&!this[ve]&&this[Be].length===0&&this[Ut]&&(this[ws]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[_s]&&this.emit("close"),this[ws]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==ve&&this[ve])return!1;if(t==="data")return!this[We]&&!r?!1:this[At]?(ai(()=>this[Ma](r)),!0):this[Ma](r);if(t==="end")return this[du]();if(t==="close"){if(this[_s]=!0,!this[dn]&&!this[ve])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ii]=r,super.emit(Na,r);let o=!this[oi]||this.listeners("error").length?super.emit("error",r):!1;return this[Ht](),o}else if(t==="resume"){let o=super.emit("resume");return this[Ht](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Ht](),i}[Ma](t){for(let r of this[$e])r.dest.write(t)===!1&&this.pause();let e=this[nt]?!1:super.emit("data",t);return this[Ht](),e}[du](){return this[dn]?!1:(this[dn]=!0,this.readable=!1,this[At]?(ai(()=>this[Ba]()),!0):this[Ba]())}[Ba](){if(this[fr]){let e=this[fr].end();if(e){for(let r of this[$e])r.dest.write(e);this[nt]||super.emit("data",e)}}for(let e of this[$e])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[We]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[We]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[We])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[pt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(ve,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[nt]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Ut])return e();let i,o,c=h=>{this.off("data",l),this.off("end",u),this.off(ve,x),e(),o(h)},l=h=>{this.off("error",c),this.off("end",u),this.off(ve,x),this.pause(),i({value:h,done:!!this[Ut]})},u=()=>{this.off("error",c),this.off("data",l),this.off(ve,x),e(),i({done:!0,value:void 0})},x=()=>c(new Error("stream destroyed"));return new Promise((h,w)=>{o=w,i=h,this.once(ve,x),this.once("error",c),this.once("end",u),this.once("data",l)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[nt]=!1;let t=!1,e=()=>(this.pause(),this.off(Na,e),this.off(ve,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Na,e),this.once(ve,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[ve])return t?this.emit("error",t):this.emit(ve),this;this[ve]=!0,this[nt]=!0,this[Be].length=0,this[Fe]=0;let e=this;return typeof e.close=="function"&&!this[_s]&&e.close(),t?this.emit("error",t):this.emit(ve),this}static get isStream(){return hm}},Sm=Qe.writev,_n=Symbol("_autoClose"),_t=Symbol("_close"),ci=Symbol("_ended"),de=Symbol("_fd"),za=Symbol("_finished"),Wt=Symbol("_flags"),Ua=Symbol("_flush"),oc=Symbol("_handleChunk"),ac=Symbol("_makeBuf"),_i=Symbol("_mode"),vs=Symbol("_needDrain"),Er=Symbol("_onerror"),vr=Symbol("_onopen"),Ha=Symbol("_onread"),wr=Symbol("_onwrite"),yn=Symbol("_open"),wt=Symbol("_path"),hn=Symbol("_pos"),Tt=Symbol("_queue"),_r=Symbol("_read"),Ga=Symbol("_readSize"),jt=Symbol("_reading"),di=Symbol("_remain"),qa=Symbol("_size"),Os=Symbol("_write"),On=Symbol("_writing"),Ls=Symbol("_defaultFlag"),Un=Symbol("_errored"),Cc=class extends jn{[Un]=!1;[de];[wt];[Ga];[jt]=!1;[qa];[di];[_n];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Un]=!1,this[de]=typeof e.fd=="number"?e.fd:void 0,this[wt]=t,this[Ga]=e.readSize||16*1024*1024,this[jt]=!1,this[qa]=typeof e.size=="number"?e.size:1/0,this[di]=this[qa],this[_n]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[de]=="number"?this[_r]():this[yn]()}get fd(){return this[de]}get path(){return this[wt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[yn](){Qe.open(this[wt],"r",(t,e)=>this[vr](t,e))}[vr](t,e){t?this[Er](t):(this[de]=e,this.emit("open",e),this[_r]())}[ac](){return Buffer.allocUnsafe(Math.min(this[Ga],this[di]))}[_r](){if(!this[jt]){this[jt]=!0;let t=this[ac]();if(t.length===0)return process.nextTick(()=>this[Ha](null,0,t));Qe.read(this[de],t,0,t.length,null,(e,r,i)=>this[Ha](e,r,i))}}[Ha](t,e,r){this[jt]=!1,t?this[Er](t):this[oc](e,r)&&this[_r]()}[_t](){if(this[_n]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Er](t){this[jt]=!0,this[_t](),this.emit("error",t)}[oc](t,e){let r=!1;return this[di]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[di]<=0)&&(r=!1,this[_t](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[de]=="number"&&this[_r](),!1;case"error":return this[Un]?!1:(this[Un]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Im=class extends Cc{[yn](){let t=!0;try{this[vr](null,Qe.openSync(this[wt],"r")),t=!1}finally{t&&this[_t]()}}[_r](){let t=!0;try{if(!this[jt]){this[jt]=!0;do{let e=this[ac](),r=e.length===0?0:Qe.readSync(this[de],e,0,e.length,null);if(!this[oc](r,e))break}while(!0);this[jt]=!1}t=!1}finally{t&&this[_t]()}}[_t](){if(this[_n]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.closeSync(t),this.emit("close")}}},Zs=class extends fm{readable=!1;writable=!0;[Un]=!1;[On]=!1;[ci]=!1;[Tt]=[];[vs]=!1;[wt];[_i];[_n];[de];[Ls];[Wt];[za]=!1;[hn];constructor(t,e){e=e||{},super(e),this[wt]=t,this[de]=typeof e.fd=="number"?e.fd:void 0,this[_i]=e.mode===void 0?438:e.mode,this[hn]=typeof e.start=="number"?e.start:void 0,this[_n]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[hn]!==void 0?"r+":"w";this[Ls]=e.flags===void 0,this[Wt]=e.flags===void 0?r:e.flags,this[de]===void 0&&this[yn]()}emit(t,...e){if(t==="error"){if(this[Un])return!1;this[Un]=!0}return super.emit(t,...e)}get fd(){return this[de]}get path(){return this[wt]}[Er](t){this[_t](),this[On]=!0,this.emit("error",t)}[yn](){Qe.open(this[wt],this[Wt],this[_i],(t,e)=>this[vr](t,e))}[vr](t,e){this[Ls]&&this[Wt]==="r+"&&t&&t.code==="ENOENT"?(this[Wt]="w",this[yn]()):t?this[Er](t):(this[de]=e,this.emit("open",e),this[On]||this[Ua]())}end(t,e){return t&&this.write(t,e),this[ci]=!0,!this[On]&&!this[Tt].length&&typeof this[de]=="number"&&this[wr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ci]?(this.emit("error",new Error("write() after end()")),!1):this[de]===void 0||this[On]||this[Tt].length?(this[Tt].push(t),this[vs]=!0,!1):(this[On]=!0,this[Os](t),!0)}[Os](t){Qe.write(this[de],t,0,t.length,this[hn],(e,r)=>this[wr](e,r))}[wr](t,e){t?this[Er](t):(this[hn]!==void 0&&typeof e=="number"&&(this[hn]+=e),this[Tt].length?this[Ua]():(this[On]=!1,this[ci]&&!this[za]?(this[za]=!0,this[_t](),this.emit("finish")):this[vs]&&(this[vs]=!1,this.emit("drain"))))}[Ua](){if(this[Tt].length===0)this[ci]&&this[wr](null,0);else if(this[Tt].length===1)this[Os](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],Sm(this[de],t,this[hn],(e,r)=>this[wr](e,r))}}[_t](){if(this[_n]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Gu=class extends Zs{[yn](){let t;if(this[Ls]&&this[Wt]==="r+")try{t=Qe.openSync(this[wt],this[Wt],this[_i])}catch(e){if(e?.code==="ENOENT")return this[Wt]="w",this[yn]();throw e}else t=Qe.openSync(this[wt],this[Wt],this[_i]);this[vr](null,t)}[_t](){if(this[_n]&&typeof this[de]=="number"){let t=this[de];this[de]=void 0,Qe.closeSync(t),this.emit("close")}}[Os](t){let e=!0;try{this[wr](null,Qe.writeSync(this[de],t,0,t.length,this[hn])),e=!1}finally{if(e)try{this[_t]()}catch{}}}},Cm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),Rm=t=>!!t.sync&&!!t.file,km=t=>!t.sync&&!!t.file,Pm=t=>!!t.sync&&!t.file,Dm=t=>!t.sync&&!t.file,Om=t=>!!t.file,Lm=t=>Cm.get(t)||t,Rc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Lm(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Ci=(t,e,r,i,o)=>Object.assign((c=[],l,u)=>{Array.isArray(c)&&(l=c,c={}),typeof l=="function"&&(u=l,l=void 0),l=l?Array.from(l):[];let x=Rc(c);if(o?.(x,l),Rm(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(x,l)}else if(km(x)){let h=e(x,l);return u?h.then(()=>u(),u):h}else if(Pm(x)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(x,l)}else if(Dm(x)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(x,l)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),Bm=Mm.constants||{ZLIB_VERNUM:4736},Pt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Bm)),Fm=Hn.concat,uu=Object.getOwnPropertyDescriptor(Hn,"concat"),zm=t=>t,ja=uu?.writable===!0||uu?.set!==void 0?t=>{Hn.concat=t?zm:Fm}:t=>{},Gn=Symbol("_superWrite"),Ss=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Wa=Symbol("flushFlag"),kc=class extends jn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof lu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new lu[e](t)}catch(r){throw new Ss(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ss(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return cc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Wa]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[Gn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;cc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},ja(!0);let l;try{let x=typeof t[Wa]=="number"?t[Wa]:this.#r;l=this.#t._processChunk(t,x),ja(!1)}catch(x){ja(!1),this.#o(new Ss(x,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",x=>this.#o(new Ss(x,this.write)));let u;if(l)if(Array.isArray(l)&&l.length>0){let x=l[0];u=this[Gn](Hn.from(x));for(let h=1;h<l.length;h++)u=this[Gn](l[h])}else u=this[Gn](Hn.from(l));return r&&r(),u}},ju=class extends kc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Pt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Pt.Z_FINISH,t.fullFlushFlag=Pt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Pt.Z_SYNC_FLUSH),cc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},Um=class extends ju{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[Gn](t){return this.#e?(this.#e=!1,t[9]=255,super[Gn](t)):super[Gn](t)}},Hm=class extends ju{constructor(t){super(t,"Unzip")}},Wu=class extends kc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Pt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Pt.BROTLI_OPERATION_FLUSH,super(t,e)}},Gm=class extends Wu{constructor(t){super(t,"BrotliCompress")}},qm=class extends Wu{constructor(t){super(t,"BrotliDecompress")}},Ku=class extends kc{constructor(t,e){t=t||{},t.flush=t.flush||Pt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Pt.ZSTD_e_end,t.fullFlushFlag=Pt.ZSTD_e_flush,super(t,e)}},jm=class extends Ku{constructor(t){super(t,"ZstdCompress")}},Wm=class extends Ku{constructor(t){super(t,"ZstdDecompress")}},Km=(t,e)=>{if(Number.isSafeInteger(t))t<0?Vm(t,e):$m(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},$m=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Vm=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),r?e[i-1]=$u(o):o===0?e[i-1]=0:(r=!0,e[i-1]=Vu(o))}},Zm=t=>{let e=t[0],r=e===128?Ym(t.subarray(1,t.length)):e===255?Jm(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},Jm=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),l;i?l=$u(c):c===0?l=c:(i=!0,l=Vu(c)),l!==0&&(r-=l*Math.pow(256,e-o-1))}return r},Ym=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},$u=t=>(255^t)&255,Vu=t=>(255^t)+1&255,Xm={};um(Xm,{code:()=>Pc,isCode:()=>Ns,isName:()=>Qm,name:()=>Js,normalFsTypes:()=>Zu});var Ns=t=>Js.has(t),Qm=t=>Pc.has(t),Zu=new Set(["0","","1","2","3","4","5","6","7","D"]),Js=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Pc=new Map(Array.from(Js).map(t=>[t[1],t[0]])),qn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Ln(t,e+156,1),c=Zu.has(o),l=c?r:void 0,u=c?i:void 0;if(this.path=l?.path??Ln(t,e,100),this.mode=l?.mode??u?.mode??pn(t,e+100,8),this.uid=l?.uid??u?.uid??pn(t,e+108,8),this.gid=l?.gid??u?.gid??pn(t,e+116,8),this.size=l?.size??u?.size??pn(t,e+124,12),this.mtime=l?.mtime??u?.mtime??Ka(t,e+136,12),this.cksum=pn(t,e+148,12),u&&this.#n(u,!0),l&&this.#n(l),Ns(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Ln(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=l?.uname??u?.uname??Ln(t,e+265,32),this.gname=l?.gname??u?.gname??Ln(t,e+297,32),this.devmaj=l?.devmaj??u?.devmaj??pn(t,e+329,8)??0,this.devmin=l?.devmin??u?.devmin??pn(t,e+337,8)??0,t[e+475]!==0){let h=Ln(t,e+345,155);this.path=h+"/"+this.path}else{let h=Ln(t,e+345,130);h&&(this.path=h+"/"+this.path),this.atime=r?.atime??i?.atime??Ka(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Ka(t,e+488,12)}let x=256;for(let h=e;h<e+148;h++)x+=t[h];for(let h=e+156;h<e+512;h++)x+=t[h];this.cksumValid=x===this.cksum,this.cksum===void 0&&x===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=ew(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Nn(t,e,100,o)||this.needPax,this.needPax=gn(t,e+100,8,this.mode)||this.needPax,this.needPax=gn(t,e+108,8,this.uid)||this.needPax,this.needPax=gn(t,e+116,8,this.gid)||this.needPax,this.needPax=gn(t,e+124,12,this.size)||this.needPax,this.needPax=$a(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Nn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Nn(t,e+265,32,this.uname)||this.needPax,this.needPax=Nn(t,e+297,32,this.gname)||this.needPax,this.needPax=gn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=gn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Nn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Nn(t,e+345,155,c)||this.needPax:(this.needPax=Nn(t,e+345,130,c)||this.needPax,this.needPax=$a(t,e+476,12,this.atime)||this.needPax,this.needPax=$a(t,e+488,12,this.ctime)||this.needPax);let l=256;for(let u=e;u<e+148;u++)l+=t[u];for(let u=e+156;u<e+512;u++)l+=t[u];return this.cksum=l,gn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Js.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Pc.get(t));if(Ns(e)||e==="Unsupported")this.#e=e;else if(Ns(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},ew=(t,e)=>{let r=t,i="",o,c=xr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=xr.dirname(r),r=xr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=xr.join(xr.basename(i),r),i=xr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Ln=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Ka=(t,e,r)=>tw(pn(t,e,r)),tw=t=>t===void 0?void 0:new Date(t*1e3),pn=(t,e,r)=>Number(t[e])&128?Zm(t.subarray(e,e+r)):rw(t,e,r),nw=t=>isNaN(t)?void 0:t,rw=(t,e,r)=>nw(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),iw={12:8589934591,8:2097151},gn=(t,e,r,i)=>i===void 0?!1:i>iw[r]||i<0?(Km(i,t.subarray(e,e+r)),!0):(sw(t,e,r,i),!1),sw=(t,e,r,i)=>t.write(ow(i,r),e,r,"ascii"),ow=(t,e)=>aw(Math.floor(t).toString(8),e),aw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",$a=(t,e,r,i)=>i===void 0?!1:gn(t,e,r,i.getTime()/1e3),cw=new Array(156).join("\0"),Nn=(t,e,r,i)=>i===void 0?!1:(t.write(i+cw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),js=class Ju{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new qn({path:("PaxHeader/"+dw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
- `,c=Buffer.byteLength(o),l=Math.floor(Math.log(c)/Math.log(10))+1;return c+l>=Math.pow(10,l)&&(l+=1),l+c+o}static parse(e,r,i=!1){return new Ju(lw(uw(e),r),i)}},lw=(t,e)=>e?Object.assign({},e,t):t,uw=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(fw,Object.create(null)),fw=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),l=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(l)*1e3):/^[0-9]+$/.test(l)?+l:l,t},xw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Y=xw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),hw=class extends jn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=Y(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?Y(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=Y(t.path)),t.linkpath&&(t.linkpath=Y(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},Ys=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},pw=1024*1024,dc=Buffer.from([31,139]),lc=Buffer.from([40,181,47,253]),gw=Math.max(dc.length,lc.length),dt=Symbol("state"),Mn=Symbol("writeEntry"),Gt=Symbol("readEntry"),Va=Symbol("nextEntry"),fu=Symbol("processEntry"),Ct=Symbol("extendedHeader"),li=Symbol("globalExtendedHeader"),ln=Symbol("meta"),xu=Symbol("emitMeta"),pe=Symbol("buffer"),qt=Symbol("queue"),un=Symbol("ended"),Za=Symbol("emittedEnd"),Bn=Symbol("emit"),Te=Symbol("unzip"),Is=Symbol("consumeChunk"),As=Symbol("consumeChunkSub"),Ja=Symbol("consumeBody"),hu=Symbol("consumeMeta"),pu=Symbol("consumeHeader"),ui=Symbol("consuming"),Ya=Symbol("bufferConcat"),Ts=Symbol("maybeEnd"),hr=Symbol("writing"),fn=Symbol("aborted"),Cs=Symbol("onDone"),Fn=Symbol("sawValidEntry"),Rs=Symbol("sawNullBlock"),ks=Symbol("sawEOF"),gu=Symbol("closeStream"),mw=()=>!0,Ti=class extends Nm{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[qt]=[];[pe];[Gt];[Mn];[dt]="begin";[ln]="";[Ct];[li];[un]=!1;[Te];[fn]=!1;[Fn];[Rs]=!1;[ks]=!1;[hr]=!1;[ui]=!1;[Za]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Cs,()=>{(this[dt]==="begin"||this[Fn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Cs,t.ondone):this.on(Cs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||pw,this.filter=typeof t.filter=="function"?t.filter:mw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[gu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){Ys(this,t,e,r)}[pu](t,e){this[Fn]===void 0&&(this[Fn]=!1);let r;try{r=new qn(t,e,this[Ct],this[li])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Rs]?(this[ks]=!0,this[dt]==="begin"&&(this[dt]="header"),this[Bn]("eof")):(this[Rs]=!0,this[Bn]("nullBlock"));else if(this[Rs]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Mn]=new hw(r,this[Ct],this[li]);if(!this[Fn])if(o.remain){let c=()=>{o.invalid||(this[Fn]=!0)};o.on("end",c)}else this[Fn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Bn]("ignoredEntry",o),this[dt]="ignore",o.resume()):o.size>0&&(this[ln]="",o.on("data",c=>this[ln]+=c),this[dt]="meta"):(this[Ct]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Bn]("ignoredEntry",o),this[dt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[dt]="body":(this[dt]="header",o.end()),this[Gt]?this[qt].push(o):(this[qt].push(o),this[Va]())))}}}[gu](){queueMicrotask(()=>this.emit("close"))}[fu](t){let e=!0;if(!t)this[Gt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[Gt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Va]()),e=!1);return e}[Va](){do;while(this[fu](this[qt].shift()));if(this[qt].length===0){let t=this[Gt];!t||t.flowing||t.size===t.remain?this[hr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Ja](t,e){let r=this[Mn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[dt]="header",this[Mn]=void 0,r.end()),o.length}[hu](t,e){let r=this[Mn],i=this[Ja](t,e);return!this[Mn]&&r&&this[xu](r),i}[Bn](t,e,r){this[qt].length===0&&!this[Gt]?this.emit(t,e,r):this[qt].push([t,e,r])}[xu](t){switch(this[Bn]("meta",this[ln]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ct]=js.parse(this[ln],this[Ct],!1);break;case"GlobalExtendedHeader":this[li]=js.parse(this[ln],this[li],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ct]??Object.create(null);this[Ct]=e,e.path=this[ln].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ct]||Object.create(null);this[Ct]=e,e.linkpath=this[ln].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[fn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[fn])return r?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[pe]&&(t=Buffer.concat([this[pe],t]),this[pe]=void 0),t.length<gw)return this[pe]=t,r?.(),!0;for(let l=0;this[Te]===void 0&&l<dc.length;l++)t[l]!==dc[l]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let l=0;l<lc.length;l++)if(t[l]!==lc[l]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Te]===!1&&c)if(t.length<512)if(this[un])this.brotli=!0;else return this[pe]=t,r?.(),!0;else try{new qn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||o)){let l=this[un];this[un]=!1,this[Te]=this[Te]===void 0?new Hm({}):o?new Wm({}):new qm({}),this[Te].on("data",x=>this[Is](x)),this[Te].on("error",x=>this.abort(x)),this[Te].on("end",()=>{this[un]=!0,this[Is]()}),this[hr]=!0;let u=!!this[Te][l?"end":"write"](t);return this[hr]=!1,r?.(),u}}this[hr]=!0,this[Te]?this[Te].write(t):this[Is](t),this[hr]=!1;let i=this[qt].length>0?!1:this[Gt]?this[Gt].flowing:!0;return!i&&this[qt].length===0&&this[Gt]?.once("drain",()=>this.emit("drain")),r?.(),i}[Ya](t){t&&!this[fn]&&(this[pe]=this[pe]?Buffer.concat([this[pe],t]):t)}[Ts](){if(this[un]&&!this[Za]&&!this[fn]&&!this[ui]){this[Za]=!0;let t=this[Mn];if(t&&t.blockRemain){let e=this[pe]?this[pe].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[pe]&&t.write(this[pe]),t.end()}this[Bn](Cs)}}[Is](t){if(this[ui]&&t)this[Ya](t);else if(!t&&!this[pe])this[Ts]();else if(t){if(this[ui]=!0,this[pe]){this[Ya](t);let e=this[pe];this[pe]=void 0,this[As](e)}else this[As](t);for(;this[pe]&&this[pe]?.length>=512&&!this[fn]&&!this[ks];){let e=this[pe];this[pe]=void 0,this[As](e)}this[ui]=!1}(!this[pe]||this[un])&&this[Ts]()}[As](t){let e=0,r=t.length;for(;e+512<=r&&!this[fn]&&!this[ks];)switch(this[dt]){case"begin":case"header":this[pu](t,e),e+=512;break;case"ignore":case"body":e+=this[Ja](t,e);break;case"meta":e+=this[hu](t,e);break;default:throw new Error("invalid state: "+this[dt])}e<r&&(this[pe]=this[pe]?Buffer.concat([t.subarray(e),this[pe]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[fn]||(this[Te]?(t&&this[Te].write(t),this[Te].end()):(this[un]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Ts]())),this}},yi=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},ww=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Yu=(t,e)=>{let r=new Map(e.map(c=>[yi(c),!0])),i=t.filter,o=(c,l="")=>{let u=l||Tm(c).root||".",x;if(c===u)x=!1;else{let h=r.get(c);x=h!==void 0?h:o(Am(c),u)}return r.set(c,x),x};t.filter=i?(c,l)=>i(c,l)&&o(yi(c)):c=>o(yi(c))},_w=t=>{let e=new Ti(t),r=t.file,i;try{i=yr.openSync(r,"r");let o=yr.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let l=Buffer.allocUnsafe(o.size),u=yr.readSync(i,l,0,o.size,0);e.end(u===l.byteLength?l:l.subarray(0,u))}else{let l=0,u=Buffer.allocUnsafe(c);for(;l<o.size;){let x=yr.readSync(i,u,0,c,l);if(x===0)break;l+=x,e.write(u.subarray(0,x))}e.end()}}finally{if(typeof i=="number")try{yr.closeSync(i)}catch{}}},yw=(t,e)=>{let r=new Ti(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("end",c),yr.stat(o,(u,x)=>{if(u)l(u);else{let h=new Cc(o,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},Sr=Ci(_w,yw,t=>new Ti(t),t=>new Ti(t),(t,e)=>{e?.length&&Yu(t,e),t.noResume||ww(t)}),Xu=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:Ew,parse:wu}=bw,Dc=t=>{let e="",r=wu(t);for(;Ew(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=wu(t)}return[e,t]},Xs=["|","<",">","?",":"],Oc=Xs.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),vw=new Map(Xs.map((t,e)=>[t,Oc[e]])),Sw=new Map(Oc.map((t,e)=>[t,Xs[e]])),_u=t=>Xs.reduce((e,r)=>e.split(r).join(vw.get(r)),t),Iw=t=>Oc.reduce((e,r)=>e.split(r).join(Sw.get(r)),t),Qu=(t,e)=>e?(t=Y(t).replace(/^\.(\/|$)/,""),yi(e)+"/"+t):Y(t),Aw=16*1024*1024,yu=Symbol("process"),bu=Symbol("file"),Eu=Symbol("directory"),uc=Symbol("symlink"),vu=Symbol("hardlink"),fi=Symbol("header"),Ms=Symbol("read"),fc=Symbol("lstat"),Bs=Symbol("onlstat"),xc=Symbol("onread"),hc=Symbol("onreadlink"),pc=Symbol("openfile"),gc=Symbol("onopenfile"),mn=Symbol("close"),Ks=Symbol("mode"),mc=Symbol("awaitDrain"),Xa=Symbol("ondrain"),kt=Symbol("prefix"),ef=class extends jn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Rc(e);super(),this.path=Y(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||Aw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=Y(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?Y(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,l]=Dc(this.path);c&&typeof l=="string"&&(this.path=l,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Iw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=Y(r.absolute||mu.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[Bs](o):this[fc]()}warn(t,e,r={}){return Ys(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[fc](){Rt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Bs](e)})}[Bs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Rw(t),this.emit("stat",t),this[yu]()}[yu](){switch(this.type){case"File":return this[bu]();case"Directory":return this[Eu]();case"SymbolicLink":return this[uc]();default:return this.end()}}[Ks](t){return Xu(t,this.type==="Directory",this.portable)}[kt](t){return Qu(t,this.prefix)}[fi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new qn({path:this[kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kt](this.linkpath):this.linkpath,mode:this[Ks](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new js({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Eu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[fi](),this.end()}[uc](){Rt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[hc](e)})}[hc](t){this.linkpath=Y(t),this[fi](),this.end()}[vu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=Y(mu.relative(this.cwd,t)),this.stat.size=0,this[fi](),this.end()}[bu](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[vu](e);this.linkCache.set(t,this.absolute)}if(this[fi](),this.stat.size===0)return this.end();this[pc]()}[pc](){Rt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[gc](e)})}[gc](t){if(this.fd=t,this.#e)return this[mn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Ms]()}[Ms](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Rt.read(t,e,r,i,o,(c,l)=>{if(c)return this[mn](()=>this.emit("error",c));this[xc](l)})}[mn](t=()=>{}){this.fd!==void 0&&Rt.close(this.fd,t)}[xc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[mn](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[mn](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[Xa]():this[mc](()=>this[Xa]())}[mc](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[Xa](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[mn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Ms]()}},Tw=class extends ef{sync=!0;[fc](){this[Bs](Rt.lstatSync(this.absolute))}[uc](){this[hc](Rt.readlinkSync(this.absolute))}[pc](){this[gc](Rt.openSync(this.absolute,"r"))}[Ms](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let l=Rt.readSync(e,r,i,o,c);this[xc](l),t=!1}finally{if(t)try{this[mn](()=>{})}catch{}}}[mc](t){t()}[mn](t=()=>{}){this.fd!==void 0&&Rt.closeSync(this.fd),t()}},Cw=class extends jn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return Ys(this,t,e,r)}constructor(t,e={}){let r=Rc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=Y(t.path),this.mode=t.mode!==void 0?this[Ks](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?Y(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[l,u]=Dc(this.path);l&&typeof u=="string"&&(this.path=u,o=l)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new qn({path:this[kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new js({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[kt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[kt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[kt](t){return Qu(t,this.prefix)}[Ks](t){return Xu(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},Rw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",kw=class br{tail;head;length=0;static create(e=[]){return new br(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)Dw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)Ow(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new br;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new br;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new br;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new br;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let l=0;o&&l<e;l++)o=o.next;let c=[];for(let l=0;o&&l<r;l++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let l of i)o=Pw(this,o,l);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function Pw(t,e,r){let i=e,o=e?e.next:t.head,c=new Lc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Dw(t,e){t.tail=new Lc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Ow(t,e){t.head=new Lc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Lc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Iu=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Au=Buffer.alloc(1024),Fs=Symbol("onStat"),xi=Symbol("ended"),gt=Symbol("queue"),hi=Symbol("pendingLinks"),xn=Symbol("current"),zn=Symbol("process"),pi=Symbol("processing"),Ps=Symbol("processJob"),mt=Symbol("jobs"),Qa=Symbol("jobDone"),zs=Symbol("addFSEntry"),Tu=Symbol("addTarEntry"),wc=Symbol("stat"),_c=Symbol("readdir"),Us=Symbol("onreaddir"),Hs=Symbol("pipe"),Cu=Symbol("entry"),ec=Symbol("entryOpt"),Gs=Symbol("writeEntryClass"),tf=Symbol("write"),tc=Symbol("ondrain"),Qs=class extends jn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[Gs];onWriteEntry;[gt];[hi]=new Map;[mt]=0;[pi]=!1;[xi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=Y(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[Gs]=ef,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new Um(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Gm(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new jm(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[tc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[tc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[gt]=new kw,this[mt]=0,this.jobs=Number(t.jobs)||4,this[pi]=!1,this[xi]=!1}[tf](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[xi]=!0,this[zn](),r&&r(),this}write(t){if(this[xi])throw new Error("write after end");return typeof t=="string"?this[zs](t):this[Tu](t),this.flowing}[Tu](t){let e=Y(Su.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Iu(t.path,e);r.entry=new Cw(t,this[ec](r)),r.entry.on("end",()=>this[Qa](r)),this[mt]+=1,this[gt].push(r)}this[zn]()}[zs](t){let e=Y(Su.resolve(this.cwd,t));this[gt].push(new Iu(t,e)),this[zn]()}[wc](t){t.pending=!0,this[mt]+=1;let e=this.follow?"stat":"lstat";Ws[e](t.absolute,(r,i)=>{t.pending=!1,this[mt]-=1,r?this.emit("error",r):this[Fs](t,i)})}[Fs](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[xn])this[Ps](t);else{let r=`${e.dev}:${e.ino}`,i=this[hi].get(r);i?i.push(t):this[hi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[zn]()}[_c](t){t.pending=!0,this[mt]+=1,Ws.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[mt]-=1,e)return this.emit("error",e);this[Us](t,r)})}[Us](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[zn]()}[zn](){if(!this[pi]){this[pi]=!0;for(let t=this[gt].head;t&&this[mt]<this.jobs;t=t.next)if(this[Ps](t.value),t.value.ignore){let e=t.next;this[gt].removeNode(t),t.next=e}this[pi]=!1,this[xi]&&this[gt].length===0&&this[mt]===0&&(this.zip?this.zip.end(Au):(super.write(Au),super.end()))}}get[xn](){return this[gt]&&this[gt].head&&this[gt].head.value}[Qa](t){this[gt].shift(),this[mt]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[hi].get(r);if(i){this[hi].delete(r);for(let o of i)o.pending=!1,this[Ps](o)}}this[zn]()}[Ps](t){if(t.pending&&t.pendingLink&&t===this[xn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[xn]&&!t.piped&&this[Hs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Fs](t,e):this[wc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Us](t,e):this[_c](t),!t.readdir)return}if(t.entry=this[Cu](t),!t.entry){t.ignore=!0;return}t===this[xn]&&!t.piped&&this[Hs](t)}}}[ec](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Cu](t){this[mt]+=1;try{return new this[Gs](t.path,this[ec](t)).on("end",()=>this[Qa](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[tc](){this[xn]&&this[xn].entry&&this[xn].entry.resume()}[Hs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[zs](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){Ys(this,t,e,r)}},Nc=class extends Qs{sync=!0;constructor(t){super(t),this[Gs]=Tw}pause(){}resume(){}[wc](t){let e=this.follow?"statSync":"lstatSync";this[Fs](t,Ws[e](t.absolute))}[_c](t){this[Us](t,Ws.readdirSync(t.absolute))}[Hs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[zs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[tf](i)})}},Lw=(t,e)=>{let r=new Nc(t),i=new Gu(t.file,{mode:t.mode||438});r.pipe(i),nf(r,e)},Nw=(t,e)=>{let r=new Qs(t),i=new Zs(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,l)=>{i.on("error",l),i.on("close",c),r.on("error",l)});return rf(r,e).catch(c=>r.emit("error",c)),o},nf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Sr({file:qu.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},rf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Sr({file:qu.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},Mw=(t,e)=>{let r=new Nc(t);return nf(r,e),r},Bw=(t,e)=>{let r=new Qs(t);return rf(r,e).catch(i=>r.emit("error",i)),r},sI=Ci(Lw,Nw,Mw,Bw,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),zw=process.env.__FAKE_PLATFORM__||process.platform,cf=zw==="win32",{O_CREAT:df,O_NOFOLLOW:Ru,O_TRUNC:lf,O_WRONLY:uf}=af.constants,ff=Number(process.env.__FAKE_FS_O_FILENAME__)||af.constants.UV_FS_O_FILEMAP||0,Uw=cf&&!!ff,Hw=512*1024,Gw=ff|lf|df|uf,ku=!cf&&typeof Ru=="number"?Ru|lf|df|uf:null,xf=ku!==null?()=>ku:Uw?t=>t<Hw?Gw:"w":()=>"w",yc=(t,e,r)=>{try{return eo.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},$s=(t,e,r,i)=>{eo.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},qw=(t,e,r,i,o)=>{if(e.isDirectory())hf(bi.resolve(t,e.name),r,i,c=>{if(c)return o(c);let l=bi.resolve(t,e.name);$s(l,r,i,o)});else{let c=bi.resolve(t,e.name);$s(c,r,i,o)}},hf=(t,e,r,i)=>{eo.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return $s(t,e,r,i);let l=c.length,u=null,x=h=>{if(!u){if(h)return i(u=h);if(--l===0)return $s(t,e,r,i)}};for(let h of c)qw(t,h,e,r,x)})},jw=(t,e,r,i)=>{e.isDirectory()&&pf(bi.resolve(t,e.name),r,i),yc(bi.resolve(t,e.name),r,i)},pf=(t,e,r)=>{let i;try{i=eo.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return yc(t,e,r);throw c}for(let o of i)jw(t,o,e,r);return yc(t,e,r)},gf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},to=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},Kw=(t,e)=>{it.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new gf(t,r?.code||"ENOTDIR")),e(r)})},$w=(t,e,r)=>{t=Y(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,l=e.uid,u=e.gid,x=typeof l=="number"&&typeof u=="number"&&(l!==e.processUid||u!==e.processGid),h=e.preserve,w=e.unlink,_=Y(e.cwd),v=(E,I)=>{E?r(E):I&&x?hf(I,l,u,A=>v(A)):c?it.chmod(t,o,r):r()};if(t===_)return Kw(t,v);if(h)return Ww.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let y=Y(Vs.relative(_,t)).split("/");bc(_,y,o,w,_,void 0,v)},bc=(t,e,r,i,o,c,l)=>{if(e.length===0)return l(null,c);let u=e.shift(),x=Y(Vs.resolve(t+"/"+u));it.mkdir(x,r,mf(x,e,r,i,o,c,l))},mf=(t,e,r,i,o,c,l)=>u=>{u?it.lstat(t,(x,h)=>{if(x)x.path=x.path&&Y(x.path),l(x);else if(h.isDirectory())bc(t,e,r,i,o,c,l);else if(i)it.unlink(t,w=>{if(w)return l(w);it.mkdir(t,r,mf(t,e,r,i,o,c,l))});else{if(h.isSymbolicLink())return l(new to(t,t+"/"+e.join("/")));l(u)}}):(c=c||t,bc(t,e,r,i,o,c,l))},Vw=t=>{let e=!1,r;try{e=it.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new gf(t,r??"ENOTDIR")}},Zw=(t,e)=>{t=Y(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,l=e.gid,u=typeof c=="number"&&typeof l=="number"&&(c!==e.processUid||l!==e.processGid),x=e.preserve,h=e.unlink,w=Y(e.cwd),_=E=>{E&&u&&pf(E,c,l),o&&it.chmodSync(t,i)};if(t===w)return Vw(w),_();if(x)return _(it.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=Y(Vs.relative(w,t)).split("/"),y;for(let E=v.shift(),I=w;E&&(I+="/"+E);E=v.shift()){I=Y(Vs.resolve(I));try{it.mkdirSync(I,i),y=y||I}catch{let A=it.lstatSync(I);if(A.isDirectory())continue;if(h){it.unlinkSync(I),it.mkdirSync(I,i),y=y||I;continue}else if(A.isSymbolicLink())return new to(I,I+"/"+v.join("/"))}}return _(y)},nc=Object.create(null),Pu=1e4,pr=new Set,Jw=t=>{pr.has(t)?pr.delete(t):nc[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),pr.add(t);let e=nc[t],r=pr.size-Pu;if(r>Pu/10){for(let i of pr)if(pr.delete(i),delete nc[i],--r<=0)break}return e},Yw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Xw=Yw==="win32",Qw=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=wf(i,r)),e.push(r||"/"),e},[]),e_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=Xw?["win32 parallelization disabled"]:t.map(i=>yi(wf(Jw(i))));let r=new Set(t.map(i=>Qw(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let l=this.#e.get(c);if(!l||l?.[0]!==t)continue;let u=l[1];if(!u){this.#e.delete(c);continue}if(l.shift(),typeof u=="function")o.add(u);else for(let x of u)o.add(x)}for(let c of i){let l=this.#e.get(c),u=l?.[0];if(!(!l||!(u instanceof Set)))if(u.size===1&&l.length===1){this.#e.delete(c);continue}else if(u.size===1){l.shift();let x=l[0];typeof x=="function"&&o.add(x)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},t_=()=>process.umask(),Du=Symbol("onEntry"),Ec=Symbol("checkFs"),Ou=Symbol("checkFs2"),vc=Symbol("isReusable"),lt=Symbol("makeFs"),Sc=Symbol("file"),Ic=Symbol("directory"),qs=Symbol("link"),Lu=Symbol("symlink"),Nu=Symbol("hardlink"),wi=Symbol("ensureNoSymlink"),Mu=Symbol("unsupported"),Bu=Symbol("checkPath"),rc=Symbol("stripAbsolutePath"),wn=Symbol("mkdir"),ze=Symbol("onError"),Ds=Symbol("pending"),Fu=Symbol("pend"),gr=Symbol("unpend"),ic=Symbol("ended"),sc=Symbol("maybeClose"),Ac=Symbol("skip"),Ei=Symbol("doChown"),vi=Symbol("uid"),Si=Symbol("gid"),Ii=Symbol("checkedCwd"),n_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ai=n_==="win32",r_=1024,i_=(t,e)=>{if(!Ai)return re.unlink(t,e);let r=t+".DELETE."+of(16).toString("hex");re.rename(t,r,i=>{if(i)return e(i);re.unlink(r,e)})},s_=t=>{if(!Ai)return re.unlinkSync(t);let e=t+".DELETE."+of(16).toString("hex");re.renameSync(t,e),re.unlinkSync(e)},zu=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Mc=class extends Ti{[ic]=!1;[Ii]=!1;[Ds]=0;reservations=new e_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[ic]=!0,this[sc]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:r_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ai,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=Y(Oe.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:t_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[Du](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[sc](){this[ic]&&this[Ds]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[rc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Dc(r),l=c.replaceAll(/\\/g,"/").split("/");if(l.includes("..")||Ai&&/^[a-z]:\.\.$/i.test(l[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Oe.posix.dirname(t.path),x=Oe.posix.normalize(Oe.posix.join(u,l.join("/")));if(x.startsWith("../")||x==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[Bu](t){let e=Y(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=Y(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[rc](t,"path")||!this[rc](t,"linkpath"))return!1;if(t.absolute=Oe.isAbsolute(t.path)?Y(Oe.resolve(t.path)):Y(Oe.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:Y(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Oe.win32.parse(String(t.absolute));t.absolute=i+_u(String(t.absolute).slice(i.length));let{root:o}=Oe.win32.parse(t.path);t.path=o+_u(t.path.slice(o.length))}return!0}[Du](t){if(!this[Bu](t))return t.resume();switch(Fw.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Ec](t);default:return this[Mu](t)}}[ze](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[gr](),e.resume())}[wn](t,e,r){$w(Y(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ei](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[vi](t){return zu(this.uid,t.uid,this.processUid)}[Si](t){return zu(this.gid,t.gid,this.processGid)}[Sc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Zs(String(t.absolute),{flags:xf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&re.close(i.fd,()=>{}),i.write=()=>!0,this[ze](u,t),e()});let o=1,c=u=>{if(u){i.fd&&re.close(i.fd,()=>{}),this[ze](u,t),e();return}--o===0&&i.fd!==void 0&&re.close(i.fd,x=>{x?this[ze](x,t):this[gr](),e()})};i.on("finish",()=>{let u=String(t.absolute),x=i.fd;if(typeof x=="number"&&t.mtime&&!this.noMtime){o++;let h=t.atime||new Date,w=t.mtime;re.futimes(x,h,w,_=>_?re.utimes(u,h,w,v=>c(v&&_)):c())}if(typeof x=="number"&&this[Ei](t)){o++;let h=this[vi](t),w=this[Si](t);typeof h=="number"&&typeof w=="number"&&re.fchown(x,h,w,_=>_?re.chown(u,h,w,v=>c(v&&_)):c())}c()});let l=this.transform&&this.transform(t)||t;l!==t&&(l.on("error",u=>{this[ze](u,t),e()}),t.pipe(l)),l.pipe(i)}[Ic](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[wn](String(t.absolute),r,i=>{if(i){this[ze](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[gr](),t.resume())};t.mtime&&!this.noMtime&&(o++,re.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ei](t)&&(o++,re.chown(String(t.absolute),Number(this[vi](t)),Number(this[Si](t)),c)),c()})}[Mu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Lu](t,e){let r=Y(Oe.relative(this.cwd,Oe.resolve(Oe.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[wi](t,this.cwd,r,()=>this[qs](t,String(t.linkpath),"symlink",e),i=>{this[ze](i,t),e()})}[Nu](t,e){let r=Y(Oe.resolve(this.cwd,String(t.linkpath))),i=Y(String(t.linkpath)).split("/");this[wi](t,this.cwd,i,()=>this[qs](t,r,"link",e),o=>{this[ze](o,t),e()})}[wi](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let l=Oe.resolve(e,c);re.lstat(l,(u,x)=>{if(u)return i();if(x?.isSymbolicLink())return o(new to(l,Oe.resolve(l,r.join("/"))));this[wi](t,l,r,i,o)})}[Fu](){this[Ds]++}[gr](){this[Ds]--,this[sc]()}[Ac](t){this[gr](),t.resume()}[vc](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ai}[Ec](t){this[Fu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Ou](t,r))}[Ou](t,e){let r=l=>{e(l)},i=()=>{this[wn](this.cwd,this.dmode,l=>{if(l){this[ze](l,t),r();return}this[Ii]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let l=Y(Oe.dirname(String(t.absolute)));if(l!==this.cwd)return this[wn](l,this.dmode,u=>{if(u){this[ze](u,t),r();return}c()})}c()},c=()=>{re.lstat(String(t.absolute),(l,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Ac](t),r();return}if(l||this[vc](t,u))return this[lt](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let x=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,h=w=>this[lt](w??null,t,r);return x?re.chmod(String(t.absolute),Number(t.mode),h):h()}if(t.absolute!==this.cwd)return re.rmdir(String(t.absolute),x=>this[lt](x??null,t,r))}if(t.absolute===this.cwd)return this[lt](null,t,r);i_(String(t.absolute),x=>this[lt](x??null,t,r))})};this[Ii]?o():i()}[lt](t,e,r){if(t){this[ze](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Sc](e,r);case"Link":return this[Nu](e,r);case"SymbolicLink":return this[Lu](e,r);case"Directory":case"GNUDumpDir":return this[Ic](e,r)}}[qs](t,e,r,i){re[r](e,String(t.absolute),o=>{o?this[ze](o,t):(this[gr](),t.resume()),i()})}},gi=t=>{try{return[null,t()]}catch(e){return[e,null]}},_f=class extends Mc{sync=!0;[lt](t,e){return super[lt](t,e,()=>{})}[Ec](t){if(!this[Ii]){let o=this[wn](this.cwd,this.dmode);if(o)return this[ze](o,t);this[Ii]=!0}if(t.absolute!==this.cwd){let o=Y(Oe.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[wn](o,this.dmode);if(c)return this[ze](c,t)}}let[e,r]=gi(()=>re.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Ac](t);if(e||this[vc](t,r))return this[lt](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[l]=c?gi(()=>{re.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[lt](l,t)}let[o]=gi(()=>re.rmdirSync(String(t.absolute)));this[lt](o,t)}let[i]=t.absolute===this.cwd?[]:gi(()=>s_(String(t.absolute)));this[lt](i,t)}[Sc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=l=>{let u;try{re.closeSync(o)}catch(x){u=x}(l||u)&&this[ze](l||u,t),e()},o;try{o=re.openSync(String(t.absolute),xf(t.size),r)}catch(l){return i(l)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",l=>this[ze](l,t)),t.pipe(c)),c.on("data",l=>{try{re.writeSync(o,l,0,l.length)}catch(u){i(u)}}),c.on("end",()=>{let l=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,x=t.mtime;try{re.futimesSync(o,u,x)}catch(h){try{re.utimesSync(String(t.absolute),u,x)}catch{l=h}}}if(this[Ei](t)){let u=this[vi](t),x=this[Si](t);try{re.fchownSync(o,Number(u),Number(x))}catch(h){try{re.chownSync(String(t.absolute),Number(u),Number(x))}catch{l=l||h}}}i(l)})}[Ic](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[wn](String(t.absolute),r);if(i){this[ze](i,t),e();return}if(t.mtime&&!this.noMtime)try{re.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ei](t))try{re.chownSync(String(t.absolute),Number(this[vi](t)),Number(this[Si](t)))}catch{}e(),t.resume()}[wn](t,e){try{return Zw(Y(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[wi](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let l of r){c=Oe.resolve(c,l);let[u,x]=gi(()=>re.lstatSync(c));if(u)return i();if(x.isSymbolicLink())return o(new to(c,Oe.resolve(e,r.join("/"))))}i()}[qs](t,e,r,i){let o=`${r}Sync`;try{re[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[ze](c,t)}}},o_=t=>{let e=new _f(t),r=t.file,i=sf.statSync(r),o=t.maxReadSize||16*1024*1024;new Im(r,{readSize:o,size:i.size}).pipe(e)},a_=(t,e)=>{let r=new Mc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,l)=>{r.on("error",l),r.on("close",c),sf.stat(o,(u,x)=>{if(u)l(u);else{let h=new Cc(o,{readSize:i,size:x.size});h.on("error",l),h.pipe(r)}})})},yf=Ci(o_,a_,t=>new _f(t),t=>new Mc(t),(t,e)=>{e?.length&&Yu(t,e)}),c_=(t,e)=>{let r=new Nc(t),i=!0,o,c;try{try{o=rt.openSync(t.file,"r+")}catch(x){if(x?.code==="ENOENT")o=rt.openSync(t.file,"w+");else throw x}let l=rt.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<l.size;c+=512){for(let w=0,_=0;w<512;w+=_){if(_=rt.readSync(o,u,w,u.length-w,c+w),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let x=new qn(u);if(!x.cksumValid)break;let h=512*Math.ceil((x.size||0)/512);if(c+h+512>l.size)break;c+=h,t.mtimeCache&&x.mtime&&t.mtimeCache.set(String(x.path),x.mtime)}i=!1,d_(t,r,c,o,e)}finally{if(i)try{rt.closeSync(o)}catch{}}},d_=(t,e,r,i,o)=>{let c=new Gu(t.file,{fd:i,start:r});e.pipe(c),u_(e,o)},l_=(t,e)=>{e=Array.from(e);let r=new Qs(t),i=(o,c,l)=>{let u=(v,y)=>{v?rt.close(o,E=>l(v)):l(null,y)},x=0;if(c===0)return u(null,0);let h=0,w=Buffer.alloc(512),_=(v,y)=>{if(v||y===void 0)return u(v);if(h+=y,h<512&&y)return rt.read(o,w,h,w.length-h,x+h,_);if(x===0&&w[0]===31&&w[1]===139)return u(new Error("cannot append to compressed archives"));if(h<512)return u(null,x);let E=new qn(w);if(!E.cksumValid)return u(null,x);let I=512*Math.ceil((E.size??0)/512);if(x+I+512>c||(x+=I+512,x>=c))return u(null,x);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),h=0,rt.read(o,w,0,512,x,_)};rt.read(o,w,0,512,x,_)};return new Promise((o,c)=>{r.on("error",c);let l="r+",u=(x,h)=>{if(x&&x.code==="ENOENT"&&l==="r+")return l="w+",rt.open(t.file,l,u);if(x||!h)return c(x);rt.fstat(h,(w,_)=>{if(w)return rt.close(h,()=>c(w));i(h,_.size,(v,y)=>{if(v)return c(v);let E=new Zs(t.file,{fd:h,start:y});r.pipe(E),E.on("error",c),E.on("close",o),f_(r,e)})})};rt.open(t.file,l,u)})},u_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Sr({file:bf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},f_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Sr({file:bf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},mi=Ci(c_,l_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Om(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),yI=Ci(mi.syncFile,mi.asyncFile,mi.syncNoFile,mi.asyncNoFile,(t,e=[])=>{mi.validate?.(t,e),x_(t)}),x_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};an();var yt={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",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete"};function no(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Ef(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function ro(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function vf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Sf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Ir(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Kt();je();ne();Pe();je();function bn(t,e){if(no(t)!=="cloud")throw new T("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ri(t){return t.startsWith("http://")||t.startsWith("https://")}function io(t){return t.endsWith("/")?t.slice(0,-1):t}je();ne();var so="1008033",Cf="1289";var Rf="pbbp2",kf="https://www.coze.cn",Pf="/api/coze_claw/resource/get_frontier_key",b_="https://www.coze.cn",E_="wss://frontier.coze.cn";function oo(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??b_}function Df(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??E_}function Ar(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Pi(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ki=G("handshake");async function Bc(t){let e=oo(t.endpoint),r=t.timeoutMs??1e4,i=`${io(e)}${Pf}?aid=${encodeURIComponent(so)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Ar(t.ppeOverride)},c=new AbortController,l=setTimeout(()=>c.abort(),r);ki.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),x=u.headers.get("x-tt-logid")??"",h=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${x}: ${E.slice(0,200)}`)}let w=await u.json();if(w.code!==void 0&&w.code!==0)throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${w.code} msg=${w.msg??"-"} logid=${x}`);let _=w.data??{},v=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,y=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!v||!y){let E=JSON.stringify(w).slice(0,500);throw new T("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${x}: ${E}`)}return ki.info("handshake ok",{remoteDeviceId:y,logid:x,traceId:h}),{accessKey:v,deviceId:y}}catch(u){if(u instanceof T)throw ki.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw ki.warn("handshake timeout",{base:e,timeoutMs:r}),new T("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let x=u.cause;throw ki.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:x?.code,syscall:x?.syscall,cause:String(u).slice(0,300)}),new T("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(l)}}var Fc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",bt="auto",Of=15e4;function Lf(t){return{model:zc(t.model)??bt,...t.modelToken?{modelToken:t.modelToken}:{}}}function Nf(t){return!t||t===bt}var v_=new Set(["auto","\u81EA\u52A8"]);function zc(t){let e=t?.trim();if(e)return v_.has(e.toLowerCase())?bt:e}function Mf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Fc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||bt;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Nf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Bf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||bt}"`):Nf(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Fc}/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"');let r=t.modelInfo?.contextWindow??Of;e.push("-c",`model_context_window=${r}`)}return e}function Ff(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Uc(t,e){let{ttEnv:r,usePpe:i}=Pi(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function zf(t,e,r){if(!t.modelToken)return{};let i=Uc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,l])=>`${c}:${l}`).join(`
92
- `)}}function Hc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Uf(t,e,r){if(!t.modelToken)return null;let i=t.model||bt,o=Uc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let l={baseUrl:`${Fc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Of,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(l.headers=o),l}function Hf(t,e,r){if(!t.modelToken)return[];let i=Uc(e,r),o=[];for(let[c,l]of Object.entries(i))o.push("-c",`model_providers.coze.http_headers.${c}="${l}"`);return o}var Se=G("agent-handlers"),Gf=5*1024*1024,R_=1,k_=6,P_=new Set(["node_modules",".git",".coze","dist","build",".next"]),D_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,O_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,L_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function N_(t){let e=t?.trim();return e?L_.test(e)||O_.test(e)?e:(Se.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function M_(t){return new Promise((e,r)=>{let i=et("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=l=>{o||(o=!0,l?r(l):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",l=>c(l))})}var ao=class{constructor(e){this.opts=e}opts;async listSkills(e){bn(e._meta,"_agent/listSkills");let r=Ir(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ye(r).workspace,c=i?.skills??[],l=[];for(let u of c){let x=Dt(o,u.relPath,"SKILL.md");await A_(x).then(w=>w.isFile()).catch(()=>!1)&&l.push(H_(u))}return{skills:l}}async addSkills(e){let r=Ir(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],l=new Map(c.map((x,h)=>[x.skillId,h])),u=[];for(let x of o){let h=await Vc({agentId:r,workspace:i.workspace,framework:i.framework,skill:x});Zc(c,l,h),u.push(x)}return await us(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){bn(e._meta,"_agent/removeSkills");let r=Ir(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],l=[];for(let u of c){if(!o.has(u.skillId)){l.push(u);continue}let x=Dt(i.workspace,u.relPath);await I_(x,{recursive:!0,force:!0}),Se.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await us(r,l),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let l=c.acpSessionId;if(l&&i.activeTriggers.has(l)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,Se.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l});continue}let x=c.downstream;c.downstream=void 0,Se.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:l}),x.stop(r).catch(h=>Se.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(h)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return Se.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await Ne(r);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return Se.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await cr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw Se.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new T("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Xe(i),Se.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await Ne(r))throw new T("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Ri(e.registry)&&o.push(`--registry=${e.registry}`);let c=N_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let l=e._meta?.cozeEnv;l&&D_.test(l)&&o.push("--env",l);let u=await M_(o);return Se.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new T("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await Ne(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Xe(i),Se.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(Se.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async switchModel(e){if(bn(e._meta,"_agent/switchModel"),!e.agentId)throw new T("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=zc(e.model)??bt,i=await Ne(e.agentId);if(!i)throw new T("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Xe(i),Se.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return Se.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(l=>Se.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(l)}));let c=[];for(let[l,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let x=o.sessions.get(l);x?.downstream&&(await x.downstream.stop(`switchModel: ${r}`).catch(()=>{}),x.downstream=void 0)}));return await Promise.all(c),Se.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(bn(e._meta,yt.RESET),!e.agentId)throw new T("IPC_BAD_REQUEST",`${yt.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,yt.RESET),await this.runDetailSync(e.agentId,yt.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),Se.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,l]of i.sessions)o.set(c,{modelToken:l.modelToken,tokenGeneratedAt:l.tokenGeneratedAt});await ni(e,o)}async clearPersistedAcpSessionIds(e){let r=await Ne(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Xe(r)}async repairAgent(e){if(bn(e._meta,yt.REPAIR),!e.agentId)throw new T("IPC_BAD_REQUEST",`${yt.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new T("IPC_BAD_REQUEST",`${yt.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){Se.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,yt.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){Se.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){Se.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){bn(e._meta,"_agent/getFileTree");let r=e._meta,i=Ir(r),o=await this.resolveWorkspace(i),c=e.filePath??"",l=this.safeJoin(o,c),u=await Gc(l).catch(()=>null);if(!u)throw new T("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ti(l,o))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let x=X_(e.depth);return u.isDirectory()?{tree:await Y_(o,l,c,x)}:{tree:[{name:Q_(c),path:Zf(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){bn(e._meta,"_agent/getFileContent");let r=Ir(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new T("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await Gc(o).catch(()=>null);if(!c||!c.isFile())throw new T("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new T("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ti(o,i))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>Gf)throw new T("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Gf})`);let l=await qf(o);return l.includes(0)?{content:l.toString("base64"),encoding:"base64",size:c.size}:{content:l.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await Ne(e).catch(()=>null))?.workspace??Ye(e).workspace}safeJoin(e,r){let i=Wc(e,r||"."),o=$c(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${jf}`))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return Ne(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new T("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function B_(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new T("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new T("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function F_(t){return t==="claude-code"?Dt(".claude","skills"):Dt(".agents","skills")}var z_=3e4,U_=50*1024*1024,Tr=3e4;async function Vc(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new T("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,l=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!l)throw new T("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=B_(o.skillName),x=F_(i),h=Dt(x,u),w=Dt(r,h);if(await qc(w,{recursive:!0}),c){let v=Buffer.from(o.content,"utf8");Di(v.length),await jc(Dt(w,"SKILL.md"),v,"utf8")}else{let v=await G_(o.downloadUrl);j_(v)?await V_(v,w):W_(v)?await K_(v,w):await jc(Dt(w,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:h,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return Se.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:h,source:c?"content":"downloadUrl"}),_}function Zc(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function H_(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function G_(t){if(!t)throw new T("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Di(e);let r=q_(t);return Di(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await qf(e);return Di(r.length),r}if(Ri(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),z_);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new T("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Di(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new T("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Di(t){if(t>U_)throw new T("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function q_(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new T("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function j_(t){return t.length>=2&&t[0]===31&&t[1]===139}function W_(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function Kc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function K_(t,e){let r,i;try{r=new $f.default(t),i=r.getEntries()}catch(l){throw new T("IPC_BAD_REQUEST",`zip parse failed: ${l.message}`,{cause:l})}for(let l of i){let u=l.entryName;if(!u||Kc(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new T("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(h=>h===".."))throw new T("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let x=l.header.attr>>>16&61440;if(x!==0&&x!==32768&&x!==16384)throw new T("IPC_BAD_REQUEST",`zip entry kind 0x${x.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=$_(i),c=Wc(e);for(let l of i){if(Kc(l.entryName))continue;let u=l.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let x=Wc(e,u),h=$c(c,x);if(h.startsWith("..")||h==="..")throw new T("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(l.isDirectory){await qc(x,{recursive:!0});continue}await qc(T_(x),{recursive:!0});let w;try{w=l.getData()}catch(_){throw new T("IPC_BAD_REQUEST",`zip entry getData failed (${l.entryName}): ${_.message}`,{cause:_})}await jc(x,w)}}function $_(t){let e;for(let r of t){let i=r.entryName;if(!i||Kc(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function V_(t,e){await Z_(t);let r=yf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar extract timeout (${Tr}ms)`))},Tr);try{await Kf(Wf.from(t),r)}catch(c){throw c instanceof T?c:i?new T("IPC_BAD_REQUEST",`tar extract timeout (${Tr}ms)`):new T("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function Z_(t){let e=[],r=Sr({onReadEntry:c=>{let l=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${l.slice(0,100)}`);return}if(l.startsWith("/")||l.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(l)){e.push(`tar entry absolute path: ${l}`);return}l.split(/[/\\]/).some(h=>h==="..")&&e.push(`tar entry contains '..': ${l}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new T("IPC_BAD_REQUEST",`tar list timeout (${Tr}ms)`))},Tr);try{await Kf(Wf.from(t),r)}catch(c){throw i?new T("IPC_BAD_REQUEST",`tar list timeout (${Tr}ms)`):new T("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new T("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var J_=5e3;async function Y_(t,e,r,i){return Vf(t,e,r,i,{count:0})}async function Vf(t,e,r,i,o){if(i<=0)return[];let c;try{c=await S_(e,{withFileTypes:!0})}catch{return[]}let l=[];for(let u of c){if(P_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=J_){l.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let x=Dt(e,u.name),h=C_(Dt(r,u.name)),w=null;try{w=await Gc(x)}catch{continue}if(w.isSymbolicLink())continue;o.count++;let _={name:u.name,path:Zf($c(t,x)),isDir:w.isDirectory(),size:w.size,modifiedAt:Math.floor(w.mtimeMs)};w.isDirectory()&&i>1&&(_.children=await Vf(t,x,h,i-1,o)),l.push(_)}return l.sort((u,x)=>u.isDir!==x.isDir?u.isDir?-1:1:u.name.localeCompare(x.name)),l}function X_(t){return!t||t<=0?R_:Math.min(t,k_)}function Q_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function Zf(t){return t.split(jf).join("/")}ne();import{readFileSync as NA}from"node:fs";import{dirname as BA,join as FA}from"node:path";import{fileURLToPath as UA}from"node:url";var Cr="0.1.104-beta.1";var En=G("agent-health-reporter"),ey=1e4,Oi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??ey}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()}),En.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),En.info("heartbeat stopped"))}async tick(){if(this.inFlight){En.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){En.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let l of this.opts.core.agents.values()){let u=ty(l);if(!u)continue;let x={agentId:l.agentId,status:u};l.patToken&&(x.patToken=l.patToken),l.accountId&&(x.accountId=l.accountId),r.push(x)}if(r.length===0)return;let i={agents:r,bridgeVersion:Cr,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3)}catch(l){En.warn("heartbeat batch send failed",{count:r.length,err:String(l)})}let c=o?.authFailures;if(c&&c.length>0&&(En.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(l=>l.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(l){En.warn("onAuthFailures callback failed (ignored)",{err:String(l)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){En.warn("onTickEnd hook failed",{err:String(r)})}}};function ty(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}an();import{mkdir as td,rm as Ky,stat as $y}from"node:fs/promises";import{homedir as Vy}from"node:os";import{join as v0}from"node:path";rn();import{existsSync as hy}from"node:fs";import{release as py}from"node:os";import{basename as gy,isAbsolute as my}from"node:path";function Li(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Rr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function kr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function vn(t,e){return{jsonrpc:"2.0",id:t,error:e}}je();var co=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)}},ee={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,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32022};function Jf(t){return"method"in t&&"id"in t&&t.id!==void 0}function Yf(t){return"method"in t&&!("id"in t)}function lo(t){return!("method"in t)&&"id"in t}var ny={AGENT_NOT_FOUND:ee.AGENT_NOT_FOUND,AGENT_BUSY:ee.AGENT_BUSY,AGENT_DISCONNECTED:ee.AGENT_DISCONNECTED,AGENT_TIMEOUT:ee.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:ee.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:ee.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:ee.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:ee.INTERNAL_ERROR,BRIDGE_INTERNAL:ee.INTERNAL_ERROR,IPC_AUTH_FAILED:ee.INTERNAL_ERROR,IPC_BAD_REQUEST:ee.INVALID_REQUEST,METHOD_NOT_FOUND:ee.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:ee.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:ee.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:ee.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:ee.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:ee.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:ee.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:ee.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:ee.FILE_TOO_LARGE,UNSUPPORTED_MIME:ee.UNSUPPORTED_MIME,UPLOAD_FAILED:ee.UPLOAD_FAILED,UPSTREAM_NOT_READY:ee.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:ee.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:ee.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:ee.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:ee.AGENT_ENV_NOT_READY};function ry(t){if(t!=null)return t instanceof Error?{name:t.name,message:Ni(t.message)}:typeof t=="string"?Ni(t):typeof t=="object"?sy(t):t}var iy=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Ni(t){let e=t;for(let[r,i]of iy)e=e.replace(r,i);return e}function sy(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Ni(i):e[r]=i;return e}function Mi(t){if(t instanceof T){let e=ry(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(r.reason=e.reason),{code:ny[t.code]??ee.INTERNAL_ERROR,message:Ni(t.message),data:r}}return{code:ee.INTERNAL_ERROR,message:Ni(t instanceof Error?t.message:String(t))}}function Xf(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:l,...u}=e;c=u}return new T(r,o,{retriable:e?.retriable??!1,cause:c})}function e0(t){return`${JSON.stringify(t)}
93
- `}var Qf=10*1024*1024,uo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>Qf){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${Qf} bytes`)}),[]}let r=this.buffer.split(`
94
- `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(l){this.onError?.({line:c,error:l})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var n0={"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","session/set_mode":"session.setMode",initialize:"initialize"},YA=Object.fromEntries(Object.entries(n0).map(([t,e])=>[e,t])),oy={"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"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Pr=class{seq=0;next(e,r){this.seq+=1;let i=n0[e]??ay(e),o=oy[i]??[],c=[i,String(this.seq)];if(o.length>0){let l=o.map(x=>t0(r?.[x]??"")),u=cy(l).join(":");u&&c.push(u)}else r&&Object.values(r).some(l=>l)&&c.push(Object.values(r).filter(Boolean).map(l=>t0(String(l))).join(":"));return c.join("_")}reset(){this.seq=0}};function ay(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function t0(t){return t.replace(/[:_\s]+/g,"-")}function cy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}on();import{readFileSync as dy}from"node:fs";var ly=384;async function Jc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await ar(t.agentEnvFile,r,{mode:ly})}function Yc(t){try{let e=JSON.parse(dy(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function r0(t,e,r={},i=o=>o){return{...i({...t,...Yc(e)}),...r}}Kt();nr();je();ne();Pe();import{execFileSync as uy,spawnSync as fy}from"node:child_process";function Bi(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Fi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),fy("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var Xc=new Set;function i0(t){typeof t=="number"&&t>0&&Xc.add(t)}function s0(t){typeof t=="number"&&Xc.delete(t)}function o0(){for(let t of Xc)Fi(t,"SIGKILL")}var Dr="coze-bridge-daemon";function a0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return uy("pgrep",["-U",String(o),"-f",Dr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
95
- `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function c0(t,e){if(t.length===0)return;let r=e?.killFn??Fi,i=e?.isAliveFn??Bi,o=e?.sleepFn??(u=>new Promise(x=>setTimeout(x,u))),c=e?.graceMs??3e3,l=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(x=>i(x));u+=l)await o(Math.min(l,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var xy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @(zed-industries|agentclientprotocol)\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function d0(t,e){if(!e)return null;for(let r of xy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function l0(t,e){return d0(t,e)}function u0(t,e){return d0(t,e)}function Or(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function f0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let h=t.suspendedMs+o,w=r-t.startedAt-h;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Or(w,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,l=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=l?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Or(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Or(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Or(c,!1,e)}}var x0=qe("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),wy=200,_y=40,yy=qe("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),by=qe("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),Ey=qe("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),vy=qe("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Sy=qe("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Iy=qe("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),h0=500;function Ay(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=h0?t:`${e.slice(0,h0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Ty(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:r}=t;if(typeof r=="string")e.push(r);else if(r&&typeof r=="object")try{e.push(JSON.stringify(r))}catch{}return e.join(" ")}function p0(t){try{return hy(t)}catch{return}}function Cy(t,e){return{platform:process.platform,osRelease:py(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:my(e.command)?p0(e.command):void 0,cwd:e.cwd,cwdExists:p0(e.cwd),envKeys:e.envKeys}}function Ry(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${gy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Ot=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new uo({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Pr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;sanitizeEnv(e){return e}async start(){if(this.child)throw new T("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=r0(process.env,this.opts.agentEnvFile??Q().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o)),i=et(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,i0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>wy&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,s0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,l=Cy(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:l}),this.failAllPending(new T("AGENT_SPAWN_FAILED",Ry(c,l),{cause:l}))}),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.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Fi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Fi(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}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,r){let i={firstUpdateMs:Sy,phase2GateMs:yy,livenessWindowMs:by,absoluteMaxMs:Ey,approvalMaxMs:Iy,suspendThresholdMs:vy,...r};return this.call("session/prompt",e,x0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Rr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(kr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(vn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=x0,o){if(!this.child||this.stopped)return Promise.reject(new T("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),l=Li(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let x=r.sessionId;return typeof x=="string"?x:void 0})();return new Promise((x,h)=>{let w={resolve:x,reject:h,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),v={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Or(0,!1,o),sessionId:u};w.promptTimeout=v;let y=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=f0(E,v.cfg,I),C=P=>{v.armedAt=I,v.expectedIntervalMs=P,w.timer=setTimeout(y,P)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),C(A.rearmMs);return}if(A.action==="continue"){C(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),h(A.awaitingApproval?new T("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new T("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),h(new T("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};w.timer=setTimeout(y,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(w.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),h(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,w);try{this.writeFrame(l)}catch(_){w.timer&&clearTimeout(w.timer),this.pending.delete(c),h(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new T("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(e0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(lo(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new T("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:Ay(e.result)}),r.resolve(e.result));return}if(Yf(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(Jf(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let l=typeof i.status=="string"?i.status:void 0,u=l==="completed"||l==="failed"||l==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(vn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(vn(e.id,Mi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=Xf(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=u0(this.framework,Ty(e));return i?new T(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new T("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(_y).join(`
96
- `),o=l0(this.framework,i);return o?new T(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new T("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function ky(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var fo=class extends Ot{framework="claude-code";constructor(e){let{command:r,args:i}=ei("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return ky(e)}};rn();import{mkdtempSync as Py,rmSync as Dy}from"node:fs";import{tmpdir as Oy}from"node:os";import{join as Ly}from"node:path";var xo=class extends Ot{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ei("codex",e.command,i),l=e.isolateCodexHome?Py(Ly(Oy(),"coze-bridge-codex-home-")):void 0,u=l?{...e.env??{},CODEX_HOME:l}:e.env,x={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(x),this.authMethodId=e.authMethodId,this.codexHomeDir=l}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Dy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};je();var Ny=3e4,Lr=class extends Ot{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,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.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},Ny))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var g0=["default","acceptEdits","plan","auto","bypassPermissions"],m0=["read-only","auto","full-access"];function Sn(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return g0.includes(e);case"codex":return m0.includes(e);case"openclaw":return!1}}function Qc(t){switch(t){case"claude-code":return g0.join("/");case"codex":return m0.join("/");case"openclaw":return""}}on();je();ne();Pe();function ed(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}rn();var In=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((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),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}get isDisposed(){return this.disposed}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 r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var ho=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=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",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new In,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)zi(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function zi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function $t(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Kt();ne();import{constants as w0}from"node:fs";import{access as My}from"node:fs/promises";import{delimiter as By,join as Fy}from"node:path";var Et=G("framework-detector"),_0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},zy=[".exe",".cmd",".bat",".ps1"],Wn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??et,access:e.access??My}}async detect(e){let r=_0[e],i=await this.which(r);if(!i)return Et.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,l]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return l&&(u.defaultAgent=l),u}async detectAll(){let e=await Promise.all(Object.keys(_0).map(async i=>[i,await this.detect(i)])),r={};for(let[i,o]of e)o&&(r[i]=o);return r}async which(e){let r=this.env.pathEnv.split(By).filter(Boolean),i=this.env.platform==="win32"?["",...zy]:[""];for(let o of r)for(let c of i){let l=Fy(o,e+c);if(await this.isExecutable(l))return l}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?w0.F_OK:w0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Et.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Et.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return Et.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return Et.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(l=>l?.isDefault===!0);return c?!c.id||!c.workspace?(Et.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(Et.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return Et.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return Et.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||Et.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let l=JSON.parse(c[0]);typeof l.gateway?.port=="number"&&(o.port=l.gateway.port),typeof l.service?.runtime?.status=="string"&&(o.runtime=l.service.runtime.status),!i&&typeof l.rpc?.error=="string"&&(o.detail=l.rpc.error)}catch(l){Et.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(l)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(Hy(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,l,u=x=>{c||(c=!0,l&&clearTimeout(l),i(x))};try{let x=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});l=setTimeout(()=>{x.kill("SIGKILL"),u(null)},15e3),x.stdout?.on("data",h=>{o+=h.toString("utf8")}),x.on("error",()=>u(null)),x.on("close",h=>u({code:h,stdout:o}))}catch{u(null)}})}},Uy=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Hy(t){return t.replace(Uy,"")}import{homedir as Gy}from"node:os";import{join as qy}from"node:path";on();Kt();nr();je();ne();async function E0(){let t=qy(Gy(),".openclaw/openclaw.json");return(await or(t))?.gateway?.auth?.token??""}var y0=G("openclaw.config"),jy=[0,5e3,5e3],Wy=qe("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),b0="models.providers.",po="agents.defaults.models",go=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new In;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??jy,this.cliTimeoutMs=e.cliTimeoutMs??Wy}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(l=>setTimeout(l,c));try{return await r()}catch(l){i=l,y0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(l)})}}throw new T("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=et(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",l=!1,u=h=>{l||(l=!0,clearTimeout(x),h())};o.stderr?.on("data",h=>{c+=h.toString("utf8")});let x=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);x.unref(),o.on("error",h=>u(()=>i(h))),o.on("close",h=>u(()=>{h===0?r():i(new Error(`exit ${h}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){y0.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${b0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${b0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${po}[${e}]`,()=>this.runCli(["config","set",po,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${po}[${e}]`,`${po}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var le=G("agent-manager"),rd="bypassPermissions",A0="full-access",T0="full-access";function Zy(t){switch(t){case"read-only":return["-c",'sandbox_mode="read-only"',"-c",'approval_policy="on-request"'];case"auto":return["-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-failure"'];case"full-access":return["-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"']}}var Jy=(t,e,r,i,o,c,l,u,x,h)=>{switch(t){case"claude-code":{let w={...o?{...Mf(o),...zf(o,l,u)}:{},...x??{},IS_SANDBOX:"1"};return new fo({cwd:r,env:w,agentId:i})}case"codex":{let w=o?[...Bf(o),...Hf(o,l,u)]:[],_=A0;h!==void 0&&(Sn("codex",h)?_=h:le.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:h}));let v=[...w,...Zy(_)],y={...o?Ff(o):{},...x??{}},E=!!o;return new xo({cwd:r,agentId:i,...v.length>0?{extraArgs:v}:{},...Object.keys(y).length>0?{env:y}:{},...E?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Lr({command:e,cwd:r,agentId:i,...c?{sessionName:ed(c)}:{}})}};function nd(t){return t==="claude-code"||t==="codex"}function Yy(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(Xy(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
89
+ `},configPath(t){return z1(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await hp("schtasks",["/Create","/SC","ONLOGON","/TN",ca,"/TR",r,"/RU",t.userName,"/F"]),Zd.info("task scheduler entry created",{task:ca,logFile:t.logFile})},async uninstall(t){await hp("schtasks",["/Delete","/TN",ca,"/F"]).catch(e=>Zd.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Zd.info("task scheduler entry removed",{task:ca})}}});var pp={};Ea(pp,{buildContext:()=>W1,getSupervisor:()=>H1,launchdSupervisor:()=>Kd,systemdSupervisor:()=>Vd,taskSchedulerSupervisor:()=>Jd});import{homedir as U1,userInfo as G1}from"node:os";function H1(t=process.platform){switch(t){case"darwin":return Kd;case"linux":return Vd;case"win32":return Jd;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function j1(){let t={};for(let e of q1){let r=process.env[e];r&&(t[e]=r)}return t}function W1(){let t=Q();return{nodeBin:process.execPath,entry:Fd(t),logFile:t.logFile,homeDir:U1(),userName:G1().username,isRoot:process.getuid?.()===0,env:j1()}}var q1,gp=Qe(()=>{"use strict";De();Yo();lp();fp();xp();q1=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});te();sn();var kl=G("acp-installer-warmup"),qg=["claude-code","codex"];async function Tl(t={}){let e=t.ensure??ar,i=(await Promise.allSettled(qg.map(async o=>{let c=await e(o);kl.info("acp wrapper warmup ok",{framework:o,path:c})}))).filter(o=>o.status==="rejected");i.length>0&&kl.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:i.length,reasons:i.map(o=>o.reason instanceof Error?o.reason.message:String(o.reason))})}cn();te();import{readdir as sm}from"node:fs/promises";import{mkdir as Dl,readFile as rm,writeFile as Ol}from"node:fs/promises";import{join as Ra}from"node:path";var im={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function lr(t,e,r){await Dl(t,{recursive:!0});let i=im[e],o=Ra(t,i);return await Ol(o,r??"","utf8"),o}async function Ca(t,e,r){let i=Ra(t,".claude");await Dl(i,{recursive:!0});let o=Ra(i,"settings.local.json"),c={};try{let u=await rm(o,"utf8"),f=JSON.parse(u);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(c=f)}catch{}let d=typeof c.permissions=="object"&&c.permissions!==null&&!Array.isArray(c.permissions)?c.permissions:{};if(e==="cloud")d.defaultMode="bypassPermissions",c.autoCompactWindow=15e4;else{if(!r)throw new Error("writeCcPermissionSettings: local deployType requires permissionMode (caller bug)");d.defaultMode===void 0&&(d.defaultMode=r)}return c.permissions=d,await Ol(o,JSON.stringify(c,null,2),"utf8"),o}var Je=G("agent-detail-sync"),om=6e4,am=5*6e4,ps=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,i;try{i=await sm(r)}catch(o){Je.info("agents dir not found, skip detail sync",{root:r,err:String(o)});return}Je.info("starting detail sync",{reason:e,count:i.length}),await Promise.allSettled(i.map(async o=>{let c=await ke(o,this.opts.paths).catch(()=>null);if(c){if(c.disconnectedAt){Je.debug("detail sync: skip disconnected agent",{agentId:o});return}try{await this.syncOne(o,c)}catch(d){Je.warn("detail sync failed for agent, skipping",{agentId:o,err:String(d)})}}})),Je.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[i,o]of this.retryQueue)e>=o.dueAt&&r.push(i);if(r.length!==0){Je.info("retrying pending detail syncs",{count:r.length});for(let i of r)try{await this.syncOne(i)}catch(o){Je.debug("detail sync retry still failing, will try again",{agentId:i,err:String(o)})}}}async syncOne(e,r){let i=r??await ke(e,this.opts.paths);if(!i){Je.info("detail sync: agent config missing, skip",{agentId:e});return}let o;try{o=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(f){Je.warn("detail RPC failed, using local data",{agentId:e,err:String(f)});let x=this.retryQueue.get(e),p=x?Math.min(x.currentDelay*2,am):om;this.retryQueue.set(e,{dueAt:Date.now()+p,currentDelay:p});return}if(o.agentId&&o.agentId!==e){Je.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:o.agentId});return}let c=!1,d=!1;o.agentName&&o.agentName!==i.agentName&&(i.agentName=o.agentName,c=!0),o.description!==void 0&&o.description!==i.description&&(i.description=o.description,c=!0),o.cozeIdentity&&o.cozeIdentity!==i.cozeIdentity&&(i.cozeIdentity=o.cozeIdentity,c=!0,d=!0);let u=!1;if(o.deployType==="cloud"&&i.deployType!=="cloud"?(Je.warn("detail sync: agent demoted to local, repairing to cloud",{agentId:e}),i.deployType="cloud",c=!0,u=!0):o.deployType&&Je.info("detail.deployType",{agentId:e,deployType:o.deployType}),!c){Je.debug("detail sync: no diff",{agentId:e});return}await Me(i,this.opts.paths),Je.info("detail sync: config updated",{agentId:e,identityChanged:d,agentName:i.agentName}),u?(await this.opts.agentManager.createAgent({agentId:e,framework:i.framework,_meta:{cozeDeployType:"cloud"},cozeIdentity:i.cozeIdentity,model:i.model}),Je.info("detail sync: repaired demoted agent back to cloud",{agentId:e})):d&&(await lr(i.workspace,i.framework,i.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Yc=Ut(fu(),1);import{createHash as H_}from"node:crypto";import{lstat as jc,mkdir as Wc,readFile as ao,readdir as Jf,rm as $c,stat as Kf,writeFile as Kc}from"node:fs/promises";import{dirname as q_,join as We,normalize as j_,relative as Jc,resolve as Vc,sep as Yf}from"node:path";import{Readable as Xf}from"node:stream";import{pipeline as Qf}from"node:stream/promises";import Rm from"events";import et from"fs";import{EventEmitter as Rc}from"node:events";import Ku from"node:stream";import{StringDecoder as Cm}from"node:string_decoder";import Ju from"node:path";import Er from"node:fs";import{dirname as qm,parse as jm}from"path";import{EventEmitter as Xm}from"events";import lc from"assert";import{Buffer as Hn}from"buffer";import*as mu from"zlib";import Qm from"zlib";import{posix as pr}from"node:path";import{basename as Aw}from"node:path";import Ks from"fs";import Ct from"fs";import Su from"path";import{win32 as Fw}from"node:path";import Pu from"path";import ff from"node:fs";import t_ from"node:assert";import{randomBytes as hf}from"node:crypto";import re from"node:fs";import Le from"node:path";import xf from"fs";import no from"node:fs";import Si from"node:path";import at from"node:fs";import c_ from"node:fs/promises";import Js from"node:path";import{join as If}from"node:path";import ot from"node:fs";import Tf from"node:path";var km=Object.defineProperty,Tm=(t,e)=>{for(var r in e)km(t,r,{get:e[r],enumerable:!0})},hu=typeof process=="object"&&process?process:{stdout:null,stderr:null},Pm=t=>!!t&&typeof t=="object"&&(t instanceof Wn||t instanceof Ku||Dm(t)||Om(t)),Dm=t=>!!t&&typeof t=="object"&&t instanceof Rc&&typeof t.pipe=="function"&&t.pipe!==Ku.Writable.prototype.pipe,Om=t=>!!t&&typeof t=="object"&&t instanceof Rc&&typeof t.write=="function"&&typeof t.end=="function",Gt=Symbol("EOF"),Ht=Symbol("maybeEmitEnd"),ln=Symbol("emittedEnd"),ys=Symbol("emittingEnd"),ai=Symbol("emittedError"),bs=Symbol("closed"),xu=Symbol("read"),Es=Symbol("flush"),pu=Symbol("flushChunk"),mt=Symbol("encoding"),xr=Symbol("decoder"),Be=Symbol("flowing"),ci=Symbol("paused"),_r=Symbol("resume"),Fe=Symbol("buffer"),Ye=Symbol("pipes"),ze=Symbol("bufferLength"),Ma=Symbol("bufferPush"),vs=Symbol("bufferShift"),Ze=Symbol("objectMode"),Se=Symbol("destroyed"),Ba=Symbol("error"),Fa=Symbol("emitData"),gu=Symbol("emitEnd"),za=Symbol("emitEnd2"),kt=Symbol("async"),Ua=Symbol("abort"),Ss=Symbol("aborted"),di=Symbol("signal"),On=Symbol("dataListeners"),st=Symbol("discarded"),li=t=>Promise.resolve().then(t),Lm=t=>t(),Nm=t=>t==="end"||t==="finish"||t==="prefinish",Mm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Bm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Vu=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[_r](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Fm=class extends Vu{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},zm=t=>!!t.objectMode,Um=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",Wn=class extends Rc{[Be]=!1;[ci]=!1;[Ye]=[];[Fe]=[];[Ze];[mt];[kt];[xr];[Gt]=!1;[ln]=!1;[ys]=!1;[bs]=!1;[ai]=null;[ze]=0;[Se]=!1;[di];[Ss]=!1;[On]=0;[st]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");zm(e)?(this[Ze]=!0,this[mt]=null):Um(e)?(this[mt]=e.encoding,this[Ze]=!1):(this[Ze]=!1,this[mt]=null),this[kt]=!!e.async,this[xr]=this[mt]?new Cm(this[mt]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[Fe]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ye]});let{signal:r}=e;r&&(this[di]=r,r.aborted?this[Ua]():r.addEventListener("abort",()=>this[Ua]()))}get bufferLength(){return this[ze]}get encoding(){return this[mt]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[Ze]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(t){this[kt]=this[kt]||!!t}[Ua](){this[Ss]=!0,this.emit("abort",this[di]?.reason),this.destroy(this[di]?.reason)}get aborted(){return this[Ss]}set aborted(t){}write(t,e,r){if(this[Ss])return!1;if(this[Gt])throw new Error("write after end");if(this[Se])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let i=this[kt]?li:Lm;if(!this[Ze]&&!Buffer.isBuffer(t)){if(Bm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Mm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ze]?(this[Be]&&this[ze]!==0&&this[Es](!0),this[Be]?this.emit("data",t):this[Ma](t),this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be]):t.length?(typeof t=="string"&&!(e===this[mt]&&!this[xr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[mt]&&(t=this[xr].write(t)),this[Be]&&this[ze]!==0&&this[Es](!0),this[Be]?this.emit("data",t):this[Ma](t),this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be]):(this[ze]!==0&&this.emit("readable"),r&&i(r),this[Be])}read(t){if(this[Se])return null;if(this[st]=!1,this[ze]===0||t===0||t&&t>this[ze])return this[Ht](),null;this[Ze]&&(t=null),this[Fe].length>1&&!this[Ze]&&(this[Fe]=[this[mt]?this[Fe].join(""):Buffer.concat(this[Fe],this[ze])]);let e=this[xu](t||null,this[Fe][0]);return this[Ht](),e}[xu](t,e){if(this[Ze])this[vs]();else{let r=e;t===r.length||t===null?this[vs]():typeof r=="string"?(this[Fe][0]=r.slice(t),e=r.slice(0,t),this[ze]-=t):(this[Fe][0]=r.subarray(t),e=r.subarray(0,t),this[ze]-=t)}return this.emit("data",e),!this[Fe].length&&!this[Gt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[Gt]=!0,this.writable=!1,(this[Be]||!this[ci])&&this[Ht](),this}[_r](){this[Se]||(!this[On]&&!this[Ye].length&&(this[st]=!0),this[ci]=!1,this[Be]=!0,this.emit("resume"),this[Fe].length?this[Es]():this[Gt]?this[Ht]():this.emit("drain"))}resume(){return this[_r]()}pause(){this[Be]=!1,this[ci]=!0,this[st]=!1}get destroyed(){return this[Se]}get flowing(){return this[Be]}get paused(){return this[ci]}[Ma](t){this[Ze]?this[ze]+=1:this[ze]+=t.length,this[Fe].push(t)}[vs](){return this[Ze]?this[ze]-=1:this[ze]-=this[Fe][0].length,this[Fe].shift()}[Es](t=!1){do;while(this[pu](this[vs]())&&this[Fe].length);!t&&!this[Fe].length&&!this[Gt]&&this.emit("drain")}[pu](t){return this.emit("data",t),this[Be]}pipe(t,e){if(this[Se])return t;this[st]=!1;let r=this[ln];return e=e||{},t===hu.stdout||t===hu.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ye].push(e.proxyErrors?new Fm(this,t,e):new Vu(this,t,e)),this[kt]?li(()=>this[_r]()):this[_r]()),t}unpipe(t){let e=this[Ye].find(r=>r.dest===t);e&&(this[Ye].length===1?(this[Be]&&this[On]===0&&(this[Be]=!1),this[Ye]=[]):this[Ye].splice(this[Ye].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[st]=!1,this[On]++,!this[Ye].length&&!this[Be]&&this[_r]();else if(t==="readable"&&this[ze]!==0)super.emit("readable");else if(Nm(t)&&this[ln])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[ai]){let i=e;this[kt]?li(()=>i.call(this,this[ai])):i.call(this,this[ai])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[On]=this.listeners("data").length,this[On]===0&&!this[st]&&!this[Ye].length&&(this[Be]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[On]=0,!this[st]&&!this[Ye].length&&(this[Be]=!1)),e}get emittedEnd(){return this[ln]}[Ht](){!this[ys]&&!this[ln]&&!this[Se]&&this[Fe].length===0&&this[Gt]&&(this[ys]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[bs]&&this.emit("close"),this[ys]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Se&&this[Se])return!1;if(t==="data")return!this[Ze]&&!r?!1:this[kt]?(li(()=>this[Fa](r)),!0):this[Fa](r);if(t==="end")return this[gu]();if(t==="close"){if(this[bs]=!0,!this[ln]&&!this[Se])return!1;let o=super.emit("close");return this.removeAllListeners("close"),o}else if(t==="error"){this[ai]=r,super.emit(Ba,r);let o=!this[di]||this.listeners("error").length?super.emit("error",r):!1;return this[Ht](),o}else if(t==="resume"){let o=super.emit("resume");return this[Ht](),o}else if(t==="finish"||t==="prefinish"){let o=super.emit(t);return this.removeAllListeners(t),o}let i=super.emit(t,...e);return this[Ht](),i}[Fa](t){for(let r of this[Ye])r.dest.write(t)===!1&&this.pause();let e=this[st]?!1:super.emit("data",t);return this[Ht](),e}[gu](){return this[ln]?!1:(this[ln]=!0,this.readable=!1,this[kt]?(li(()=>this[za]()),!0):this[za]())}[za](){if(this[xr]){let e=this[xr].end();if(e){for(let r of this[Ye])r.dest.write(e);this[st]||super.emit("data",e)}}for(let e of this[Ye])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ze]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[Ze]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[Ze])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[mt]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Se,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[st]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Gt])return e();let i,o,c=x=>{this.off("data",d),this.off("end",u),this.off(Se,f),e(),o(x)},d=x=>{this.off("error",c),this.off("end",u),this.off(Se,f),this.pause(),i({value:x,done:!!this[Gt]})},u=()=>{this.off("error",c),this.off("data",d),this.off(Se,f),e(),i({done:!0,value:void 0})},f=()=>c(new Error("stream destroyed"));return new Promise((x,p)=>{o=p,i=x,this.once(Se,f),this.once("error",c),this.once("end",u),this.once("data",d)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[st]=!1;let t=!1,e=()=>(this.pause(),this.off(Ba,e),this.off(Se,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(Ba,e),this.once(Se,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Se])return t?this.emit("error",t):this.emit(Se),this;this[Se]=!0,this[st]=!0,this[Fe].length=0,this[ze]=0;let e=this;return typeof e.close=="function"&&!this[bs]&&e.close(),t?this.emit("error",t):this.emit(Se),this}static get isStream(){return Pm}},Gm=et.writev,yn=Symbol("_autoClose"),bt=Symbol("_close"),ui=Symbol("_ended"),ce=Symbol("_fd"),Ga=Symbol("_finished"),$t=Symbol("_flags"),Ha=Symbol("_flush"),cc=Symbol("_handleChunk"),dc=Symbol("_makeBuf"),Ei=Symbol("_mode"),Is=Symbol("_needDrain"),Sr=Symbol("_onerror"),Ir=Symbol("_onopen"),qa=Symbol("_onread"),yr=Symbol("_onwrite"),bn=Symbol("_open"),yt=Symbol("_path"),pn=Symbol("_pos"),Tt=Symbol("_queue"),br=Symbol("_read"),ja=Symbol("_readSize"),Wt=Symbol("_reading"),fi=Symbol("_remain"),Wa=Symbol("_size"),Ns=Symbol("_write"),Ln=Symbol("_writing"),Ms=Symbol("_defaultFlag"),Gn=Symbol("_errored"),Cc=class extends Wn{[Gn]=!1;[ce];[yt];[ja];[Wt]=!1;[Wa];[fi];[yn];constructor(t,e){if(e=e||{},super(e),this.readable=!0,this.writable=!1,typeof t!="string")throw new TypeError("path must be a string");this[Gn]=!1,this[ce]=typeof e.fd=="number"?e.fd:void 0,this[yt]=t,this[ja]=e.readSize||16*1024*1024,this[Wt]=!1,this[Wa]=typeof e.size=="number"?e.size:1/0,this[fi]=this[Wa],this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[ce]=="number"?this[br]():this[bn]()}get fd(){return this[ce]}get path(){return this[yt]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[bn](){et.open(this[yt],"r",(t,e)=>this[Ir](t,e))}[Ir](t,e){t?this[Sr](t):(this[ce]=e,this.emit("open",e),this[br]())}[dc](){return Buffer.allocUnsafe(Math.min(this[ja],this[fi]))}[br](){if(!this[Wt]){this[Wt]=!0;let t=this[dc]();if(t.length===0)return process.nextTick(()=>this[qa](null,0,t));et.read(this[ce],t,0,t.length,null,(e,r,i)=>this[qa](e,r,i))}}[qa](t,e,r){this[Wt]=!1,t?this[Sr](t):this[cc](e,r)&&this[br]()}[bt](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Sr](t){this[Wt]=!0,this[bt](),this.emit("error",t)}[cc](t,e){let r=!1;return this[fi]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[fi]<=0)&&(r=!1,this[bt](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[ce]=="number"&&this[br](),!1;case"error":return this[Gn]?!1:(this[Gn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Hm=class extends Cc{[bn](){let t=!0;try{this[Ir](null,et.openSync(this[yt],"r")),t=!1}finally{t&&this[bt]()}}[br](){let t=!0;try{if(!this[Wt]){this[Wt]=!0;do{let e=this[dc](),r=e.length===0?0:et.readSync(this[ce],e,0,e.length,null);if(!this[cc](r,e))break}while(!0);this[Wt]=!1}t=!1}finally{t&&this[bt]()}}[bt](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.closeSync(t),this.emit("close")}}},Ys=class extends Rm{readable=!1;writable=!0;[Gn]=!1;[Ln]=!1;[ui]=!1;[Tt]=[];[Is]=!1;[yt];[Ei];[yn];[ce];[Ms];[$t];[Ga]=!1;[pn];constructor(t,e){e=e||{},super(e),this[yt]=t,this[ce]=typeof e.fd=="number"?e.fd:void 0,this[Ei]=e.mode===void 0?438:e.mode,this[pn]=typeof e.start=="number"?e.start:void 0,this[yn]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[pn]!==void 0?"r+":"w";this[Ms]=e.flags===void 0,this[$t]=e.flags===void 0?r:e.flags,this[ce]===void 0&&this[bn]()}emit(t,...e){if(t==="error"){if(this[Gn])return!1;this[Gn]=!0}return super.emit(t,...e)}get fd(){return this[ce]}get path(){return this[yt]}[Sr](t){this[bt](),this[Ln]=!0,this.emit("error",t)}[bn](){et.open(this[yt],this[$t],this[Ei],(t,e)=>this[Ir](t,e))}[Ir](t,e){this[Ms]&&this[$t]==="r+"&&t&&t.code==="ENOENT"?(this[$t]="w",this[bn]()):t?this[Sr](t):(this[ce]=e,this.emit("open",e),this[Ln]||this[Ha]())}end(t,e){return t&&this.write(t,e),this[ui]=!0,!this[Ln]&&!this[Tt].length&&typeof this[ce]=="number"&&this[yr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[ui]?(this.emit("error",new Error("write() after end()")),!1):this[ce]===void 0||this[Ln]||this[Tt].length?(this[Tt].push(t),this[Is]=!0,!1):(this[Ln]=!0,this[Ns](t),!0)}[Ns](t){et.write(this[ce],t,0,t.length,this[pn],(e,r)=>this[yr](e,r))}[yr](t,e){t?this[Sr](t):(this[pn]!==void 0&&typeof e=="number"&&(this[pn]+=e),this[Tt].length?this[Ha]():(this[Ln]=!1,this[ui]&&!this[Ga]?(this[Ga]=!0,this[bt](),this.emit("finish")):this[Is]&&(this[Is]=!1,this.emit("drain"))))}[Ha](){if(this[Tt].length===0)this[ui]&&this[yr](null,0);else if(this[Tt].length===1)this[Ns](this[Tt].pop());else{let t=this[Tt];this[Tt]=[],Gm(this[ce],t,this[pn],(e,r)=>this[yr](e,r))}}[bt](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Zu=class extends Ys{[bn](){let t;if(this[Ms]&&this[$t]==="r+")try{t=et.openSync(this[yt],this[$t],this[Ei])}catch(e){if(e?.code==="ENOENT")return this[$t]="w",this[bn]();throw e}else t=et.openSync(this[yt],this[$t],this[Ei]);this[Ir](null,t)}[bt](){if(this[yn]&&typeof this[ce]=="number"){let t=this[ce];this[ce]=void 0,et.closeSync(t),this.emit("close")}}[Ns](t){let e=!0;try{this[yr](null,et.writeSync(this[ce],t,0,t.length,this[pn])),e=!1}finally{if(e)try{this[bt]()}catch{}}}},Wm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),$m=t=>!!t.sync&&!!t.file,Km=t=>!t.sync&&!!t.file,Vm=t=>!!t.sync&&!t.file,Zm=t=>!t.sync&&!t.file,Jm=t=>!!t.file,Ym=t=>Wm.get(t)||t,Pc=(t={})=>{if(!t)return{};let e={};for(let[r,i]of Object.entries(t)){let o=Ym(r);e[o]=i}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Pi=(t,e,r,i,o)=>Object.assign((c=[],d,u)=>{Array.isArray(c)&&(d=c,c={}),typeof d=="function"&&(u=d,d=void 0),d=d?Array.from(d):[];let f=Pc(c);if(o?.(f,d),$m(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return t(f,d)}else if(Km(f)){let x=e(f,d);return u?x.then(()=>u(),u):x}else if(Vm(f)){if(typeof u=="function")throw new TypeError("callback not supported for sync tar functions");return r(f,d)}else if(Zm(f)){if(typeof u=="function")throw new TypeError("callback only supported with file option");return i(f,d)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:i,validate:o}),ew=Qm.constants||{ZLIB_VERNUM:4736},Dt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},ew)),tw=Hn.concat,wu=Object.getOwnPropertyDescriptor(Hn,"concat"),nw=t=>t,$a=wu?.writable===!0||wu?.set!==void 0?t=>{Hn.concat=t?nw:tw}:t=>{},qn=Symbol("_superWrite"),As=class extends Error{code;errno;constructor(t,e){super("zlib: "+t.message,{cause:t}),this.code=t.code,this.errno=t.errno,this.code||(this.code="ZLIB_ERROR"),this.message="zlib: "+t.message,Error.captureStackTrace(this,e??this.constructor)}get name(){return"ZlibError"}},Ka=Symbol("flushFlag"),Dc=class extends Wn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof mu[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new mu[e](t)}catch(r){throw new As(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new As(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return lc(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(Hn.alloc(0),{[Ka]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(r)}get ended(){return this.#n}[qn](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=Hn.from(t,e)),this.#e)return;lc(this.#t,"zlib binding closed");let i=this.#t._handle,o=i.close;i.close=()=>{};let c=this.#t.close;this.#t.close=()=>{},$a(!0);let d;try{let f=typeof t[Ka]=="number"?t[Ka]:this.#r;d=this.#t._processChunk(t,f),$a(!1)}catch(f){$a(!1),this.#o(new As(f,this.write))}finally{this.#t&&(this.#t._handle=i,i.close=o,this.#t.close=c,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",f=>this.#o(new As(f,this.write)));let u;if(d)if(Array.isArray(d)&&d.length>0){let f=d[0];u=this[qn](Hn.from(f));for(let x=1;x<d.length;x++)u=this[qn](d[x])}else u=this[qn](Hn.from(d));return r&&r(),u}},Yu=class extends Dc{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||Dt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Dt.Z_FINISH,t.fullFlushFlag=Dt.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(Dt.Z_SYNC_FLUSH),lc(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(i,o)=>{typeof i=="function"&&(o=i,i=this.flushFlag),this.flush(i),o?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#n=e)}}}},rw=class extends Yu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[qn](t){return this.#e?(this.#e=!1,t[9]=255,super[qn](t)):super[qn](t)}},iw=class extends Yu{constructor(t){super(t,"Unzip")}},Xu=class extends Dc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Dt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Dt.BROTLI_OPERATION_FLUSH,super(t,e)}},sw=class extends Xu{constructor(t){super(t,"BrotliCompress")}},ow=class extends Xu{constructor(t){super(t,"BrotliDecompress")}},Qu=class extends Dc{constructor(t,e){t=t||{},t.flush=t.flush||Dt.ZSTD_e_continue,t.finishFlush=t.finishFlush||Dt.ZSTD_e_end,t.fullFlushFlag=Dt.ZSTD_e_flush,super(t,e)}},aw=class extends Qu{constructor(t){super(t,"ZstdCompress")}},cw=class extends Qu{constructor(t){super(t,"ZstdDecompress")}},dw=(t,e)=>{if(Number.isSafeInteger(t))t<0?uw(t,e):lw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},lw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},uw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var i=e.length;i>1;i--){var o=t&255;t=Math.floor(t/256),r?e[i-1]=ef(o):o===0?e[i-1]=0:(r=!0,e[i-1]=tf(o))}},fw=t=>{let e=t[0],r=e===128?xw(t.subarray(1,t.length)):e===255?hw(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},hw=t=>{for(var e=t.length,r=0,i=!1,o=e-1;o>-1;o--){var c=Number(t[o]),d;i?d=ef(c):c===0?d=c:(i=!0,d=tf(c)),d!==0&&(r-=d*Math.pow(256,e-o-1))}return r},xw=t=>{for(var e=t.length,r=0,i=e-1;i>-1;i--){var o=Number(t[i]);o!==0&&(r+=o*Math.pow(256,e-i-1))}return r},ef=t=>(255^t)&255,tf=t=>(255^t)+1&255,pw={};Tm(pw,{code:()=>Oc,isCode:()=>Bs,isName:()=>gw,name:()=>Xs,normalFsTypes:()=>nf});var Bs=t=>Xs.has(t),gw=t=>Oc.has(t),nf=new Set(["0","","1","2","3","4","5","6","7","D"]),Xs=new Map([["0","File"],["","OldFile"],["1","Link"],["2","SymbolicLink"],["3","CharacterDevice"],["4","BlockDevice"],["5","Directory"],["6","FIFO"],["7","ContiguousFile"],["g","GlobalExtendedHeader"],["x","ExtendedHeader"],["A","SolarisACL"],["D","GNUDumpDir"],["I","Inode"],["K","NextFileHasLongLinkpath"],["L","NextFileHasLongPath"],["M","ContinuationFile"],["N","OldGnuLongPath"],["S","SparseFile"],["V","TapeVolumeHeader"],["X","OldExtendedHeader"]]),Oc=new Map(Array.from(Xs).map(t=>[t[1],t[0]])),jn=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,i){Buffer.isBuffer(t)?this.decode(t,e||0,r,i):t&&this.#n(t)}decode(t,e,r,i){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");let o=Nn(t,e+156,1),c=nf.has(o),d=c?r:void 0,u=c?i:void 0;if(this.path=d?.path??Nn(t,e,100),this.mode=d?.mode??u?.mode??gn(t,e+100,8),this.uid=d?.uid??u?.uid??gn(t,e+108,8),this.gid=d?.gid??u?.gid??gn(t,e+116,8),this.size=d?.size??u?.size??gn(t,e+124,12),this.mtime=d?.mtime??u?.mtime??Va(t,e+136,12),this.cksum=gn(t,e+148,12),u&&this.#n(u,!0),d&&this.#n(d),Bs(o)&&(this.#e=o||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Nn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=d?.uname??u?.uname??Nn(t,e+265,32),this.gname=d?.gname??u?.gname??Nn(t,e+297,32),this.devmaj=d?.devmaj??u?.devmaj??gn(t,e+329,8)??0,this.devmin=d?.devmin??u?.devmin??gn(t,e+337,8)??0,t[e+475]!==0){let x=Nn(t,e+345,155);this.path=x+"/"+this.path}else{let x=Nn(t,e+345,130);x&&(this.path=x+"/"+this.path),this.atime=r?.atime??i?.atime??Va(t,e+476,12),this.ctime=r?.ctime??i?.ctime??Va(t,e+488,12)}let f=256;for(let x=e;x<e+148;x++)f+=t[x];for(let x=e+156;x<e+512;x++)f+=t[x];this.cksumValid=f===this.cksum,this.cksum===void 0&&f===256&&(this.nullBlock=!0)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,i=mw(this.path||"",r),o=i[0],c=i[1];this.needPax=!!i[2],this.needPax=Mn(t,e,100,o)||this.needPax,this.needPax=mn(t,e+100,8,this.mode)||this.needPax,this.needPax=mn(t,e+108,8,this.uid)||this.needPax,this.needPax=mn(t,e+116,8,this.gid)||this.needPax,this.needPax=mn(t,e+124,12,this.size)||this.needPax,this.needPax=Za(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Mn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Mn(t,e+265,32,this.uname)||this.needPax,this.needPax=Mn(t,e+297,32,this.gname)||this.needPax,this.needPax=mn(t,e+329,8,this.devmaj)||this.needPax,this.needPax=mn(t,e+337,8,this.devmin)||this.needPax,this.needPax=Mn(t,e+345,r,c)||this.needPax,t[e+475]!==0?this.needPax=Mn(t,e+345,155,c)||this.needPax:(this.needPax=Mn(t,e+345,130,c)||this.needPax,this.needPax=Za(t,e+476,12,this.atime)||this.needPax,this.needPax=Za(t,e+488,12,this.ctime)||this.needPax);let d=256;for(let u=e;u<e+148;u++)d+=t[u];for(let u=e+156;u<e+512;u++)d+=t[u];return this.cksum=d,mn(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Xs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Oc.get(t));if(Bs(e)||e==="Unsupported")this.#e=e;else if(Bs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},mw=(t,e)=>{let r=t,i="",o,c=pr.parse(t).root||".";if(Buffer.byteLength(r)<100)o=[r,i,!1];else{i=pr.dirname(r),r=pr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(i)<=e?o=[r,i,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(i)<=e?o=[r.slice(0,99),i,!0]:(r=pr.join(pr.basename(i),r),i=pr.dirname(i));while(i!==c&&o===void 0);o||(o=[t.slice(0,99),"",!0])}return o},Nn=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Va=(t,e,r)=>ww(gn(t,e,r)),ww=t=>t===void 0?void 0:new Date(t*1e3),gn=(t,e,r)=>Number(t[e])&128?fw(t.subarray(e,e+r)):yw(t,e,r),_w=t=>isNaN(t)?void 0:t,yw=(t,e,r)=>_w(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),bw={12:8589934591,8:2097151},mn=(t,e,r,i)=>i===void 0?!1:i>bw[r]||i<0?(dw(i,t.subarray(e,e+r)),!0):(Ew(t,e,r,i),!1),Ew=(t,e,r,i)=>t.write(vw(i,r),e,r,"ascii"),vw=(t,e)=>Sw(Math.floor(t).toString(8),e),Sw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Za=(t,e,r,i)=>i===void 0?!1:mn(t,e,r,i.getTime()/1e3),Iw=new Array(156).join("\0"),Mn=(t,e,r,i)=>i===void 0?!1:(t.write(i+Iw,e,r,"utf8"),i.length!==Buffer.byteLength(i)||i.length>r),$s=class rf{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),i=512*Math.ceil(1+r/512),o=Buffer.allocUnsafe(i);for(let c=0;c<512;c++)o[c]=0;new jn({path:("PaxHeader/"+Aw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(o),o.write(e,512,r,"utf8");for(let c=r+512;c<o.length;c++)o[c]=0;return o}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],i=r instanceof Date?r.getTime()/1e3:r,o=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+i+`
90
+ `,c=Buffer.byteLength(o),d=Math.floor(Math.log(c)/Math.log(10))+1;return c+d>=Math.pow(10,d)&&(d+=1),d+c+o}static parse(e,r,i=!1){return new rf(kw(Tw(e),r),i)}},kw=(t,e)=>e?Object.assign({},e,t):t,Tw=t=>t.replace(/\n$/,"").split(`
91
+ `).reduce(Rw,Object.create(null)),Rw=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let i=e.split("="),o=i.shift();if(!o)return t;let c=o.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),d=i.join("=");return t[c]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(c)?new Date(Number(d)*1e3):/^[0-9]+$/.test(d)?+d:d,t},Cw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,X=Cw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Pw=class extends Wn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=X(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?X(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,i=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,i-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=X(t.path)),t.linkpath&&(t.linkpath=X(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,i])=>!(i==null||r==="path"&&e))))}},Qs=(t,e,r,i={})=>{t.file&&(i.file=t.file),t.cwd&&(i.cwd=t.cwd),i.code=r instanceof Error&&r.code||e,i.tarCode=e,!t.strict&&i.recoverable!==!1?(r instanceof Error&&(i=Object.assign(r,i),r=r.message),t.emit("warn",e,r,i)):r instanceof Error?t.emit("error",Object.assign(r,i)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),i))},Dw=1024*1024,uc=Buffer.from([31,139]),fc=Buffer.from([40,181,47,253]),Ow=Math.max(uc.length,fc.length),lt=Symbol("state"),Bn=Symbol("writeEntry"),qt=Symbol("readEntry"),Ja=Symbol("nextEntry"),_u=Symbol("processEntry"),Rt=Symbol("extendedHeader"),hi=Symbol("globalExtendedHeader"),un=Symbol("meta"),yu=Symbol("emitMeta"),ge=Symbol("buffer"),jt=Symbol("queue"),fn=Symbol("ended"),Ya=Symbol("emittedEnd"),Fn=Symbol("emit"),Te=Symbol("unzip"),ks=Symbol("consumeChunk"),Ts=Symbol("consumeChunkSub"),Xa=Symbol("consumeBody"),bu=Symbol("consumeMeta"),Eu=Symbol("consumeHeader"),xi=Symbol("consuming"),Qa=Symbol("bufferConcat"),Rs=Symbol("maybeEnd"),gr=Symbol("writing"),hn=Symbol("aborted"),Cs=Symbol("onDone"),zn=Symbol("sawValidEntry"),Ps=Symbol("sawNullBlock"),Ds=Symbol("sawEOF"),vu=Symbol("closeStream"),Lw=()=>!0,Ci=class extends Xm{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[jt]=[];[ge];[qt];[Bn];[lt]="begin";[un]="";[Rt];[hi];[fn]=!1;[Te];[hn]=!1;[zn];[Ps]=!1;[Ds]=!1;[gr]=!1;[xi]=!1;[Ya]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Cs,()=>{(this[lt]==="begin"||this[zn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Cs,t.ondone):this.on(Cs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Dw,this.filter=typeof t.filter=="function"?t.filter:Lw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[vu]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){Qs(this,t,e,r)}[Eu](t,e){this[zn]===void 0&&(this[zn]=!1);let r;try{r=new jn(t,e,this[Rt],this[hi])}catch(i){return this.warn("TAR_ENTRY_INVALID",i)}if(r.nullBlock)this[Ps]?(this[Ds]=!0,this[lt]==="begin"&&(this[lt]="header"),this[Fn]("eof")):(this[Ps]=!0,this[Fn]("nullBlock"));else if(this[Ps]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let i=r.type;if(/^(Symbolic)?Link$/.test(i)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(i)&&!/^(Global)?ExtendedHeader$/.test(i)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let o=this[Bn]=new Pw(r,this[Rt],this[hi]);if(!this[zn])if(o.remain){let c=()=>{o.invalid||(this[zn]=!0)};o.on("end",c)}else this[zn]=!0;o.meta?o.size>this.maxMetaEntrySize?(o.ignore=!0,this[Fn]("ignoredEntry",o),this[lt]="ignore",o.resume()):o.size>0&&(this[un]="",o.on("data",c=>this[un]+=c),this[lt]="meta"):(this[Rt]=void 0,o.ignore=o.ignore||!this.filter(o.path,o),o.ignore?(this[Fn]("ignoredEntry",o),this[lt]=o.remain?"ignore":"header",o.resume()):(o.remain?this[lt]="body":(this[lt]="header",o.end()),this[qt]?this[jt].push(o):(this[jt].push(o),this[Ja]())))}}}[vu](){queueMicrotask(()=>this.emit("close"))}[_u](t){let e=!0;if(!t)this[qt]=void 0,e=!1;else if(Array.isArray(t)){let[r,...i]=t;this.emit(r,...i)}else this[qt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[Ja]()),e=!1);return e}[Ja](){do;while(this[_u](this[jt].shift()));if(this[jt].length===0){let t=this[qt];!t||t.flowing||t.size===t.remain?this[gr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Xa](t,e){let r=this[Bn];if(!r)throw new Error("attempt to consume body without entry??");let i=r.blockRemain??0,o=i>=t.length&&e===0?t:t.subarray(e,e+i);return r.write(o),r.blockRemain||(this[lt]="header",this[Bn]=void 0,r.end()),o.length}[bu](t,e){let r=this[Bn],i=this[Xa](t,e);return!this[Bn]&&r&&this[yu](r),i}[Fn](t,e,r){this[jt].length===0&&!this[qt]?this.emit(t,e,r):this[jt].push([t,e,r])}[yu](t){switch(this[Fn]("meta",this[un]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Rt]=$s.parse(this[un],this[Rt],!1);break;case"GlobalExtendedHeader":this[hi]=$s.parse(this[un],this[hi],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Rt]??Object.create(null);this[Rt]=e,e.path=this[un].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Rt]||Object.create(null);this[Rt]=e,e.linkpath=this[un].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[hn]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[hn])return r?.(),!1;if((this[Te]===void 0||this.brotli===void 0&&this[Te]===!1)&&t){if(this[ge]&&(t=Buffer.concat([this[ge],t]),this[ge]=void 0),t.length<Ow)return this[ge]=t,r?.(),!0;for(let d=0;this[Te]===void 0&&d<uc.length;d++)t[d]!==uc[d]&&(this[Te]=!1);let o=!1;if(this[Te]===!1&&this.zstd!==!1){o=!0;for(let d=0;d<fc.length;d++)if(t[d]!==fc[d]){o=!1;break}}let c=this.brotli===void 0&&!o;if(this[Te]===!1&&c)if(t.length<512)if(this[fn])this.brotli=!0;else return this[ge]=t,r?.(),!0;else try{new jn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Te]===void 0||this[Te]===!1&&(this.brotli||o)){let d=this[fn];this[fn]=!1,this[Te]=this[Te]===void 0?new iw({}):o?new cw({}):new ow({}),this[Te].on("data",f=>this[ks](f)),this[Te].on("error",f=>this.abort(f)),this[Te].on("end",()=>{this[fn]=!0,this[ks]()}),this[gr]=!0;let u=!!this[Te][d?"end":"write"](t);return this[gr]=!1,r?.(),u}}this[gr]=!0,this[Te]?this[Te].write(t):this[ks](t),this[gr]=!1;let i=this[jt].length>0?!1:this[qt]?this[qt].flowing:!0;return!i&&this[jt].length===0&&this[qt]?.once("drain",()=>this.emit("drain")),r?.(),i}[Qa](t){t&&!this[hn]&&(this[ge]=this[ge]?Buffer.concat([this[ge],t]):t)}[Rs](){if(this[fn]&&!this[Ya]&&!this[hn]&&!this[xi]){this[Ya]=!0;let t=this[Bn];if(t&&t.blockRemain){let e=this[ge]?this[ge].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[ge]&&t.write(this[ge]),t.end()}this[Fn](Cs)}}[ks](t){if(this[xi]&&t)this[Qa](t);else if(!t&&!this[ge])this[Rs]();else if(t){if(this[xi]=!0,this[ge]){this[Qa](t);let e=this[ge];this[ge]=void 0,this[Ts](e)}else this[Ts](t);for(;this[ge]&&this[ge]?.length>=512&&!this[hn]&&!this[Ds];){let e=this[ge];this[ge]=void 0,this[Ts](e)}this[xi]=!1}(!this[ge]||this[fn])&&this[Rs]()}[Ts](t){let e=0,r=t.length;for(;e+512<=r&&!this[hn]&&!this[Ds];)switch(this[lt]){case"begin":case"header":this[Eu](t,e),e+=512;break;case"ignore":case"body":e+=this[Xa](t,e);break;case"meta":e+=this[bu](t,e);break;default:throw new Error("invalid state: "+this[lt])}e<r&&(this[ge]=this[ge]?Buffer.concat([t.subarray(e),this[ge]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[hn]||(this[Te]?(t&&this[Te].write(t),this[Te].end()):(this[fn]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Rs]())),this}},vi=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},Nw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},sf=(t,e)=>{let r=new Map(e.map(c=>[vi(c),!0])),i=t.filter,o=(c,d="")=>{let u=d||jm(c).root||".",f;if(c===u)f=!1;else{let x=r.get(c);f=x!==void 0?x:o(qm(c),u)}return r.set(c,f),f};t.filter=i?(c,d)=>i(c,d)&&o(vi(c)):c=>o(vi(c))},Mw=t=>{let e=new Ci(t),r=t.file,i;try{i=Er.openSync(r,"r");let o=Er.fstatSync(i),c=t.maxReadSize||16*1024*1024;if(o.size<c){let d=Buffer.allocUnsafe(o.size),u=Er.readSync(i,d,0,o.size,0);e.end(u===d.byteLength?d:d.subarray(0,u))}else{let d=0,u=Buffer.allocUnsafe(c);for(;d<o.size;){let f=Er.readSync(i,u,0,c,d);if(f===0)break;d+=f,e.write(u.subarray(0,f))}e.end()}}finally{if(typeof i=="number")try{Er.closeSync(i)}catch{}}},Bw=(t,e)=>{let r=new Ci(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("end",c),Er.stat(o,(u,f)=>{if(u)d(u);else{let x=new Cc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},Ar=Pi(Mw,Bw,t=>new Ci(t),t=>new Ci(t),(t,e)=>{e?.length&&sf(t,e),t.noResume||Nw(t)}),of=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:zw,parse:Iu}=Fw,Lc=t=>{let e="",r=Iu(t);for(;zw(t)||r.root;){let i=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(i.length),e+=i,r=Iu(t)}return[e,t]},eo=["|","<",">","?",":"],Nc=eo.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Uw=new Map(eo.map((t,e)=>[t,Nc[e]])),Gw=new Map(Nc.map((t,e)=>[t,eo[e]])),Au=t=>eo.reduce((e,r)=>e.split(r).join(Uw.get(r)),t),Hw=t=>Nc.reduce((e,r)=>e.split(r).join(Gw.get(r)),t),af=(t,e)=>e?(t=X(t).replace(/^\.(\/|$)/,""),vi(e)+"/"+t):X(t),qw=16*1024*1024,ku=Symbol("process"),Tu=Symbol("file"),Ru=Symbol("directory"),hc=Symbol("symlink"),Cu=Symbol("hardlink"),pi=Symbol("header"),Fs=Symbol("read"),xc=Symbol("lstat"),zs=Symbol("onlstat"),pc=Symbol("onread"),gc=Symbol("onreadlink"),mc=Symbol("openfile"),wc=Symbol("onopenfile"),wn=Symbol("close"),Vs=Symbol("mode"),_c=Symbol("awaitDrain"),ec=Symbol("ondrain"),Pt=Symbol("prefix"),cf=class extends Wn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Pc(e);super(),this.path=X(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||qw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=X(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?X(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[c,d]=Lc(this.path);c&&typeof d=="string"&&(this.path=d,i=c)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=Hw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=X(r.absolute||Su.resolve(this.cwd,t)),this.path===""&&(this.path="./"),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path});let o=this.statCache.get(this.absolute);o?this[zs](o):this[xc]()}warn(t,e,r={}){return Qs(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[xc](){Ct.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[zs](e)})}[zs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=$w(t),this.emit("stat",t),this[ku]()}[ku](){switch(this.type){case"File":return this[Tu]();case"Directory":return this[Ru]();case"SymbolicLink":return this[hc]();default:return this.end()}}[Vs](t){return of(t,this.type==="Directory",this.portable)}[Pt](t){return af(t,this.prefix)}[pi](){if(!this.stat)throw new Error("cannot write header before stat");this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.onWriteEntry?.(this),this.header=new jn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this[Vs](this.stat.mode),uid:this.portable?void 0:this.stat.uid,gid:this.portable?void 0:this.stat.gid,size:this.stat.size,mtime:this.noMtime?void 0:this.mtime||this.stat.mtime,type:this.type==="Unsupported"?void 0:this.type,uname:this.portable?void 0:this.stat.uid===this.myuid?this.myuser:"",atime:this.portable?void 0:this.stat.atime,ctime:this.portable?void 0:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new $s({atime:this.portable?void 0:this.header.atime,ctime:this.portable?void 0:this.header.ctime,gid:this.portable?void 0:this.header.gid,mtime:this.noMtime?void 0:this.mtime||this.header.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?void 0:this.header.uid,uname:this.portable?void 0:this.header.uname,dev:this.portable?void 0:this.stat.dev,ino:this.portable?void 0:this.stat.ino,nlink:this.portable?void 0:this.stat.nlink}).encode());let t=this.header?.block;if(!t)throw new Error("failed to encode header");super.write(t)}[Ru](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[pi](),this.end()}[hc](){Ct.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[gc](e)})}[gc](t){this.linkpath=X(t),this[pi](),this.end()}[Cu](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=X(Su.relative(this.cwd,t)),this.stat.size=0,this[pi](),this.end()}[Tu](){if(!this.stat)throw new Error("cannot create file entry without stat");if(this.stat.nlink>1){let t=`${this.stat.dev}:${this.stat.ino}`,e=this.linkCache.get(t);if(e?.indexOf(this.cwd)===0)return this[Cu](e);this.linkCache.set(t,this.absolute)}if(this[pi](),this.stat.size===0)return this.end();this[mc]()}[mc](){Ct.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[wc](e)})}[wc](t){if(this.fd=t,this.#e)return this[wn]();if(!this.stat)throw new Error("should stat before calling onopenfile");this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let e=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(e),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[Fs]()}[Fs](){let{fd:t,buf:e,offset:r,length:i,pos:o}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ct.read(t,e,r,i,o,(c,d)=>{if(c)return this[wn](()=>this.emit("error",c));this[pc](d)})}[wn](t=()=>{}){this.fd!==void 0&&Ct.close(this.fd,t)}[pc](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[wn](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[wn](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[ec]():this[_c](()=>this[ec]())}[_c](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let i=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",i)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[ec](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[wn](t=>t?this.emit("error",t):this.end());if(!this.buf)throw new Error("buffer lost somehow in ONDRAIN");this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[Fs]()}},jw=class extends cf{sync=!0;[xc](){this[zs](Ct.lstatSync(this.absolute))}[hc](){this[gc](Ct.readlinkSync(this.absolute))}[mc](){this[wc](Ct.openSync(this.absolute,"r"))}[Fs](){let t=!0;try{let{fd:e,buf:r,offset:i,length:o,pos:c}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let d=Ct.readSync(e,r,i,o,c);this[pc](d),t=!1}finally{if(t)try{this[wn](()=>{})}catch{}}}[_c](t){t()}[wn](t=()=>{}){this.fd!==void 0&&Ct.closeSync(this.fd),t()}},Ww=class extends Wn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return Qs(this,t,e,r)}constructor(t,e={}){let r=Pc(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:i}=t;if(i==="Unsupported")throw new Error("writing entry that should be ignored");this.type=i,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=X(t.path),this.mode=t.mode!==void 0?this[Vs](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?X(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let o=!1;if(!this.preservePaths){let[d,u]=Lc(this.path);d&&typeof u=="string"&&(this.path=u,o=d)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new jn({path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?void 0:this.uid,gid:this.portable?void 0:this.gid,size:this.size,mtime:this.noMtime?void 0:this.mtime,type:this.type,uname:this.portable?void 0:this.uname,atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime}),o&&this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new $s({atime:this.portable?void 0:this.atime,ctime:this.portable?void 0:this.ctime,gid:this.portable?void 0:this.gid,mtime:this.noMtime?void 0:this.mtime,path:this[Pt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Pt](this.linkpath):this.linkpath,size:this.size,uid:this.portable?void 0:this.uid,uname:this.portable?void 0:this.uname,dev:this.portable?void 0:this.readEntry.dev,ino:this.portable?void 0:this.readEntry.ino,nlink:this.portable?void 0:this.readEntry.nlink}).encode());let c=this.header?.block;if(!c)throw new Error("failed to encode header");super.write(c),t.pipe(this)}[Pt](t){return af(t,this.prefix)}[Vs](t){return of(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let i=t.length;if(i>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=i,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},$w=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",Kw=class vr{tail;head;length=0;static create(e=[]){return new vr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,i=e.prev;return r&&(r.prev=i),i&&(i.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=i),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,i=e.length;r<i;r++)Zw(this,e[r]);return this.length}unshift(...e){for(var r=0,i=e.length;r<i;r++)Jw(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let i=this.head,o=0;i;o++)e.call(r,i.value,o,this),i=i.next}forEachReverse(e,r){r=r||this;for(let i=this.tail,o=this.length-1;i;o--)e.call(r,i.value,o,this),i=i.prev}get(e){let r=0,i=this.head;for(;i&&r<e;r++)i=i.next;if(r===e&&i)return i.value}getReverse(e){let r=0,i=this.tail;for(;i&&r<e;r++)i=i.prev;if(r===e&&i)return i.value}map(e,r){r=r||this;let i=new vr;for(let o=this.head;o;)i.push(e.call(r,o.value,this)),o=o.next;return i}mapReverse(e,r){r=r||this;var i=new vr;for(let o=this.tail;o;)i.push(e.call(r,o.value,this)),o=o.prev;return i}reduce(e,r){let i,o=this.head;if(arguments.length>1)i=r;else if(this.head)o=this.head.next,i=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var c=0;o;c++)i=e(i,o.value,c),o=o.next;return i}reduceReverse(e,r){let i,o=this.tail;if(arguments.length>1)i=r;else if(this.tail)o=this.tail.prev,i=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let c=this.length-1;o;c--)i=e(i,o.value,c),o=o.prev;return i}toArray(){let e=new Array(this.length);for(let r=0,i=this.head;i;r++)e[r]=i.value,i=i.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,i=this.tail;i;r++)e[r]=i.value,i=i.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new vr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.head,c=0;for(c=0;o&&c<e;c++)o=o.next;for(;o&&c<r;c++,o=o.next)i.push(o.value);return i}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let i=new vr;if(r<e||r<0)return i;e<0&&(e=0),r>this.length&&(r=this.length);let o=this.length,c=this.tail;for(;c&&o>r;o--)c=c.prev;for(;c&&o>e;o--,c=c.prev)i.push(c.value);return i}splice(e,r=0,...i){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let o=this.head;for(let d=0;o&&d<e;d++)o=o.next;let c=[];for(let d=0;o&&d<r;d++)c.push(o.value),o=this.removeNode(o);o?o!==this.tail&&(o=o.prev):o=this.tail;for(let d of i)o=Vw(this,o,d);return c}reverse(){let e=this.head,r=this.tail;for(let i=e;i;i=i.prev){let o=i.prev;i.prev=i.next,i.next=o}return this.head=r,this.tail=e,this}};function Vw(t,e,r){let i=e,o=e?e.next:t.head,c=new Mc(r,i,o,t);return c.next===void 0&&(t.tail=c),c.prev===void 0&&(t.head=c),t.length++,c}function Zw(t,e){t.tail=new Mc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Jw(t,e){t.head=new Mc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Mc=class{list;next;prev;value;constructor(t,e,r,i){this.list=i,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Du=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Ou=Buffer.alloc(1024),Us=Symbol("onStat"),gi=Symbol("ended"),wt=Symbol("queue"),mi=Symbol("pendingLinks"),xn=Symbol("current"),Un=Symbol("process"),wi=Symbol("processing"),Os=Symbol("processJob"),_t=Symbol("jobs"),tc=Symbol("jobDone"),Gs=Symbol("addFSEntry"),Lu=Symbol("addTarEntry"),yc=Symbol("stat"),bc=Symbol("readdir"),Hs=Symbol("onreaddir"),qs=Symbol("pipe"),Nu=Symbol("entry"),nc=Symbol("entryOpt"),js=Symbol("writeEntryClass"),df=Symbol("write"),rc=Symbol("ondrain"),to=class extends Wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[js];onWriteEntry;[wt];[mi]=new Map;[_t]=0;[wi]=!1;[gi]=!1;constructor(t={}){if(super(),this.opt=t,this.file=t.file||"",this.cwd=t.cwd||process.cwd(),this.maxReadSize=t.maxReadSize,this.preservePaths=!!t.preservePaths,this.strict=!!t.strict,this.noPax=!!t.noPax,this.prefix=X(t.prefix||""),this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.readdirCache=t.readdirCache||new Map,this.onWriteEntry=t.onWriteEntry,this[js]=cf,typeof t.onwarn=="function"&&this.on("warn",t.onwarn),this.portable=!!t.portable,t.gzip||t.brotli||t.zstd){if((t.gzip?1:0)+(t.brotli?1:0)+(t.zstd?1:0)>1)throw new TypeError("gzip, brotli, zstd are mutually exclusive");if(t.gzip&&(typeof t.gzip!="object"&&(t.gzip={}),this.portable&&(t.gzip.portable=!0),this.zip=new rw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new sw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new aw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[rc]()),this.on("resume",()=>e.resume())}else this.on("drain",this[rc]);this.noDirRecurse=!!t.noDirRecurse,this.follow=!!t.follow,this.noMtime=!!t.noMtime,t.mtime&&(this.mtime=t.mtime),this.filter=typeof t.filter=="function"?t.filter:()=>!0,this[wt]=new Kw,this[_t]=0,this.jobs=Number(t.jobs)||4,this[wi]=!1,this[gi]=!1}[df](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[gi]=!0,this[Un](),r&&r(),this}write(t){if(this[gi])throw new Error("write after end");return typeof t=="string"?this[Gs](t):this[Lu](t),this.flowing}[Lu](t){let e=X(Pu.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Du(t.path,e);r.entry=new Ww(t,this[nc](r)),r.entry.on("end",()=>this[tc](r)),this[_t]+=1,this[wt].push(r)}this[Un]()}[Gs](t){let e=X(Pu.resolve(this.cwd,t));this[wt].push(new Du(t,e)),this[Un]()}[yc](t){t.pending=!0,this[_t]+=1;let e=this.follow?"stat":"lstat";Ks[e](t.absolute,(r,i)=>{t.pending=!1,this[_t]-=1,r?this.emit("error",r):this[Us](t,i)})}[Us](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[xn])this[Os](t);else{let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);i?i.push(t):this[mi].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[Un]()}[bc](t){t.pending=!0,this[_t]+=1,Ks.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[_t]-=1,e)return this.emit("error",e);this[Hs](t,r)})}[Hs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[Un]()}[Un](){if(!this[wi]){this[wi]=!0;for(let t=this[wt].head;t&&this[_t]<this.jobs;t=t.next)if(this[Os](t.value),t.value.ignore){let e=t.next;this[wt].removeNode(t),t.next=e}this[wi]=!1,this[gi]&&this[wt].length===0&&this[_t]===0&&(this.zip?this.zip.end(Ou):(super.write(Ou),super.end()))}}get[xn](){return this[wt]&&this[wt].head&&this[wt].head.value}[tc](t){this[wt].shift(),this[_t]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,i=this[mi].get(r);if(i){this[mi].delete(r);for(let o of i)o.pending=!1,this[Os](o)}}this[Un]()}[Os](t){if(t.pending&&t.pendingLink&&t===this[xn]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[xn]&&!t.piped&&this[qs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Us](t,e):this[yc](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Hs](t,e):this[bc](t),!t.readdir)return}if(t.entry=this[Nu](t),!t.entry){t.ignore=!0;return}t===this[xn]&&!t.piped&&this[qs](t)}}}[nc](t){return{onwarn:(e,r,i)=>this.warn(e,r,i),noPax:this.noPax,cwd:this.cwd,absolute:t.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix,onWriteEntry:this.onWriteEntry}}[Nu](t){this[_t]+=1;try{return new this[js](t.path,this[nc](t)).on("end",()=>this[tc](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[rc](){this[xn]&&this[xn].entry&&this[xn].entry.resume()}[qs](t){t.piped=!0,t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Gs](c+i)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",i=>{r.write(i)||e.pause()}):e.on("data",i=>{super.write(i)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){Qs(this,t,e,r)}},Bc=class extends to{sync=!0;constructor(t){super(t),this[js]=jw}pause(){}resume(){}[yc](t){let e=this.follow?"statSync":"lstatSync";this[Us](t,Ks[e](t.absolute))}[bc](t){this[Hs](t,Ks.readdirSync(t.absolute))}[qs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(i=>{let o=t.path,c=o==="./"?"":o.replace(/\/*$/,"/");this[Gs](c+i)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",i=>{r.write(i)}):e.on("data",i=>{super[df](i)})}},Yw=(t,e)=>{let r=new Bc(t),i=new Zu(t.file,{mode:t.mode||438});r.pipe(i),lf(r,e)},Xw=(t,e)=>{let r=new to(t),i=new Ys(t.file,{mode:t.mode||438});r.pipe(i);let o=new Promise((c,d)=>{i.on("error",d),i.on("close",c),r.on("error",d)});return uf(r,e).catch(c=>r.emit("error",c)),o},lf=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:Ju.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},uf=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:Ju.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>{t.add(i)}}):t.add(r);t.end()},Qw=(t,e)=>{let r=new Bc(t);return lf(r,e),r},e_=(t,e)=>{let r=new to(t);return uf(r,e).catch(i=>r.emit("error",i)),r},kA=Pi(Yw,Xw,Qw,e_,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),n_=process.env.__FAKE_PLATFORM__||process.platform,pf=n_==="win32",{O_CREAT:gf,O_NOFOLLOW:Mu,O_TRUNC:mf,O_WRONLY:wf}=xf.constants,_f=Number(process.env.__FAKE_FS_O_FILENAME__)||xf.constants.UV_FS_O_FILEMAP||0,r_=pf&&!!_f,i_=512*1024,s_=_f|mf|gf|wf,Bu=!pf&&typeof Mu=="number"?Mu|mf|gf|wf:null,yf=Bu!==null?()=>Bu:r_?t=>t<i_?s_:"w":()=>"w",Ec=(t,e,r)=>{try{return no.lchownSync(t,e,r)}catch(i){if(i?.code!=="ENOENT")throw i}},Zs=(t,e,r,i)=>{no.lchown(t,e,r,o=>{i(o&&o?.code!=="ENOENT"?o:null)})},o_=(t,e,r,i,o)=>{if(e.isDirectory())bf(Si.resolve(t,e.name),r,i,c=>{if(c)return o(c);let d=Si.resolve(t,e.name);Zs(d,r,i,o)});else{let c=Si.resolve(t,e.name);Zs(c,r,i,o)}},bf=(t,e,r,i)=>{no.readdir(t,{withFileTypes:!0},(o,c)=>{if(o){if(o.code==="ENOENT")return i();if(o.code!=="ENOTDIR"&&o.code!=="ENOTSUP")return i(o)}if(o||!c.length)return Zs(t,e,r,i);let d=c.length,u=null,f=x=>{if(!u){if(x)return i(u=x);if(--d===0)return Zs(t,e,r,i)}};for(let x of c)o_(t,x,e,r,f)})},a_=(t,e,r,i)=>{e.isDirectory()&&Ef(Si.resolve(t,e.name),r,i),Ec(Si.resolve(t,e.name),r,i)},Ef=(t,e,r)=>{let i;try{i=no.readdirSync(t,{withFileTypes:!0})}catch(o){let c=o;if(c?.code==="ENOENT")return;if(c?.code==="ENOTDIR"||c?.code==="ENOTSUP")return Ec(t,e,r);throw c}for(let o of i)a_(t,o,e,r);return Ec(t,e,r)},vf=class extends Error{path;code;syscall="chdir";constructor(t,e){super(`${e}: Cannot cd into '${t}'`),this.path=t,this.code=e}get name(){return"CwdError"}},ro=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},d_=(t,e)=>{at.stat(t,(r,i)=>{(r||!i.isDirectory())&&(r=new vf(t,r?.code||"ENOTDIR")),e(r)})},l_=(t,e,r)=>{t=X(t);let i=e.umask??18,o=e.mode|448,c=(o&i)!==0,d=e.uid,u=e.gid,f=typeof d=="number"&&typeof u=="number"&&(d!==e.processUid||u!==e.processGid),x=e.preserve,p=e.unlink,_=X(e.cwd),v=(E,I)=>{E?r(E):I&&f?bf(I,d,u,A=>v(A)):c?at.chmod(t,o,r):r()};if(t===_)return d_(t,v);if(x)return c_.mkdir(t,{mode:o,recursive:!0}).then(E=>v(null,E??void 0),v);let w=X(Js.relative(_,t)).split("/");vc(_,w,o,p,_,void 0,v)},vc=(t,e,r,i,o,c,d)=>{if(e.length===0)return d(null,c);let u=e.shift(),f=X(Js.resolve(t+"/"+u));at.mkdir(f,r,Sf(f,e,r,i,o,c,d))},Sf=(t,e,r,i,o,c,d)=>u=>{u?at.lstat(t,(f,x)=>{if(f)f.path=f.path&&X(f.path),d(f);else if(x.isDirectory())vc(t,e,r,i,o,c,d);else if(i)at.unlink(t,p=>{if(p)return d(p);at.mkdir(t,r,Sf(t,e,r,i,o,c,d))});else{if(x.isSymbolicLink())return d(new ro(t,t+"/"+e.join("/")));d(u)}}):(c=c||t,vc(t,e,r,i,o,c,d))},u_=t=>{let e=!1,r;try{e=at.statSync(t).isDirectory()}catch(i){r=i?.code}finally{if(!e)throw new vf(t,r??"ENOTDIR")}},f_=(t,e)=>{t=X(t);let r=e.umask??18,i=e.mode|448,o=(i&r)!==0,c=e.uid,d=e.gid,u=typeof c=="number"&&typeof d=="number"&&(c!==e.processUid||d!==e.processGid),f=e.preserve,x=e.unlink,p=X(e.cwd),_=E=>{E&&u&&Ef(E,c,d),o&&at.chmodSync(t,i)};if(t===p)return u_(p),_();if(f)return _(at.mkdirSync(t,{mode:i,recursive:!0})??void 0);let v=X(Js.relative(p,t)).split("/"),w;for(let E=v.shift(),I=p;E&&(I+="/"+E);E=v.shift()){I=X(Js.resolve(I));try{at.mkdirSync(I,i),w=w||I}catch{let A=at.lstatSync(I);if(A.isDirectory())continue;if(x){at.unlinkSync(I),at.mkdirSync(I,i),w=w||I;continue}else if(A.isSymbolicLink())return new ro(I,I+"/"+v.join("/"))}}return _(w)},ic=Object.create(null),Fu=1e4,mr=new Set,h_=t=>{mr.has(t)?mr.delete(t):ic[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),mr.add(t);let e=ic[t],r=mr.size-Fu;if(r>Fu/10){for(let i of mr)if(mr.delete(i),delete ic[i],--r<=0)break}return e},x_=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,p_=x_==="win32",g_=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let i=e.at(-1);return i!==void 0&&(r=If(i,r)),e.push(r||"/"),e},[]),m_=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=p_?["win32 parallelization disabled"]:t.map(i=>vi(If(h_(i))));let r=new Set(t.map(i=>g_(i)).reduce((i,o)=>i.concat(o)));this.#n.set(e,{dirs:r,paths:t});for(let i of t){let o=this.#e.get(i);o?o.push(e):this.#e.set(i,[e])}for(let i of r){let o=this.#e.get(i);if(!o)this.#e.set(i,[new Set([e])]);else{let c=o.at(-1);c instanceof Set?c.add(e):o.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(i=>i&&i[0]===t)&&r.every(i=>i&&i[0]instanceof Set&&i[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:i}=e,o=new Set;for(let c of r){let d=this.#e.get(c);if(!d||d?.[0]!==t)continue;let u=d[1];if(!u){this.#e.delete(c);continue}if(d.shift(),typeof u=="function")o.add(u);else for(let f of u)o.add(f)}for(let c of i){let d=this.#e.get(c),u=d?.[0];if(!(!d||!(u instanceof Set)))if(u.size===1&&d.length===1){this.#e.delete(c);continue}else if(u.size===1){d.shift();let f=d[0];typeof f=="function"&&o.add(f)}else u.delete(t)}return this.#r.delete(t),o.forEach(c=>this.#i(c)),!0}},w_=()=>process.umask(),zu=Symbol("onEntry"),Sc=Symbol("checkFs"),Uu=Symbol("checkFs2"),Ic=Symbol("isReusable"),ut=Symbol("makeFs"),Ac=Symbol("file"),kc=Symbol("directory"),Ws=Symbol("link"),Gu=Symbol("symlink"),Hu=Symbol("hardlink"),bi=Symbol("ensureNoSymlink"),qu=Symbol("unsupported"),ju=Symbol("checkPath"),sc=Symbol("stripAbsolutePath"),_n=Symbol("mkdir"),Ue=Symbol("onError"),Ls=Symbol("pending"),Wu=Symbol("pend"),wr=Symbol("unpend"),oc=Symbol("ended"),ac=Symbol("maybeClose"),Tc=Symbol("skip"),Ii=Symbol("doChown"),Ai=Symbol("uid"),ki=Symbol("gid"),Ti=Symbol("checkedCwd"),__=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Ri=__==="win32",y_=1024,b_=(t,e)=>{if(!Ri)return re.unlink(t,e);let r=t+".DELETE."+hf(16).toString("hex");re.rename(t,r,i=>{if(i)return e(i);re.unlink(r,e)})},E_=t=>{if(!Ri)return re.unlinkSync(t);let e=t+".DELETE."+hf(16).toString("hex");re.renameSync(t,e),re.unlinkSync(e)},$u=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Fc=class extends Ci{[oc]=!1;[Ti]=!1;[Ls]=0;reservations=new m_;transform;writable=!0;readable=!1;uid;gid;setOwner;preserveOwner;processGid;processUid;maxDepth;forceChown;win32;newer;keep;noMtime;preservePaths;unlink;cwd;strip;processUmask;umask;dmode;fmode;chmod;constructor(t={}){if(t.ondone=()=>{this[oc]=!0,this[ac]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:y_,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Ri,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=X(Le.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:w_():0,this.umask=typeof t.umask=="number"?t.umask:this.processUmask,this.dmode=t.dmode||511&~this.umask,this.fmode=t.fmode||438&~this.umask,this.on("entry",e=>this[zu](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[ac](){this[oc]&&this[Ls]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[sc](t,e){let r=t[e],{type:i}=t;if(!r||this.preservePaths)return!0;let[o,c]=Lc(r),d=c.replaceAll(/\\/g,"/").split("/");if(d.includes("..")||Ri&&/^[a-z]:\.\.$/i.test(d[0]??"")){if(e==="path"||i==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let u=Le.posix.dirname(t.path),f=Le.posix.normalize(Le.posix.join(u,d.join("/")));if(f.startsWith("../")||f==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return o&&(t[e]=String(c),this.warn("TAR_ENTRY_INFO",`stripping ${o} from absolute ${e}`,{entry:t,[e]:r})),!0}[ju](t){let e=X(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let i=X(String(t.linkpath)).split("/");if(i.length>=this.strip)t.linkpath=i.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[sc](t,"path")||!this[sc](t,"linkpath"))return!1;if(t.absolute=Le.isAbsolute(t.path)?X(Le.resolve(t.path)):X(Le.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:X(t.path),resolvedPath:t.absolute,cwd:this.cwd}),!1;if(t.absolute===this.cwd&&t.type!=="Directory"&&t.type!=="GNUDumpDir")return!1;if(this.win32){let{root:i}=Le.win32.parse(String(t.absolute));t.absolute=i+Au(String(t.absolute).slice(i.length));let{root:o}=Le.win32.parse(t.path);t.path=o+Au(t.path.slice(o.length))}return!0}[zu](t){if(!this[ju](t))return t.resume();switch(t_.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Sc](t);default:return this[qu](t)}}[Ue](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[wr](),e.resume())}[_n](t,e,r){l_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Ii](t){return this.forceChown||this.preserveOwner&&(typeof t.uid=="number"&&t.uid!==this.processUid||typeof t.gid=="number"&&t.gid!==this.processGid)||typeof this.uid=="number"&&this.uid!==this.processUid||typeof this.gid=="number"&&this.gid!==this.processGid}[Ai](t){return $u(this.uid,t.uid,this.processUid)}[ki](t){return $u(this.gid,t.gid,this.processGid)}[Ac](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=new Ys(String(t.absolute),{flags:yf(t.size),mode:r,autoClose:!1});i.on("error",u=>{i.fd&&re.close(i.fd,()=>{}),i.write=()=>!0,this[Ue](u,t),e()});let o=1,c=u=>{if(u){i.fd&&re.close(i.fd,()=>{}),this[Ue](u,t),e();return}--o===0&&i.fd!==void 0&&re.close(i.fd,f=>{f?this[Ue](f,t):this[wr](),e()})};i.on("finish",()=>{let u=String(t.absolute),f=i.fd;if(typeof f=="number"&&t.mtime&&!this.noMtime){o++;let x=t.atime||new Date,p=t.mtime;re.futimes(f,x,p,_=>_?re.utimes(u,x,p,v=>c(v&&_)):c())}if(typeof f=="number"&&this[Ii](t)){o++;let x=this[Ai](t),p=this[ki](t);typeof x=="number"&&typeof p=="number"&&re.fchown(f,x,p,_=>_?re.chown(u,x,p,v=>c(v&&_)):c())}c()});let d=this.transform&&this.transform(t)||t;d!==t&&(d.on("error",u=>{this[Ue](u,t),e()}),t.pipe(d)),d.pipe(i)}[kc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[_n](String(t.absolute),r,i=>{if(i){this[Ue](i,t),e();return}let o=1,c=()=>{--o===0&&(e(),this[wr](),t.resume())};t.mtime&&!this.noMtime&&(o++,re.utimes(String(t.absolute),t.atime||new Date,t.mtime,c)),this[Ii](t)&&(o++,re.chown(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)),c)),c()})}[qu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Gu](t,e){let r=X(Le.relative(this.cwd,Le.resolve(Le.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[bi](t,this.cwd,r,()=>this[Ws](t,String(t.linkpath),"symlink",e),i=>{this[Ue](i,t),e()})}[Hu](t,e){let r=X(Le.resolve(this.cwd,String(t.linkpath))),i=X(String(t.linkpath)).split("/");this[bi](t,this.cwd,i,()=>this[Ws](t,r,"link",e),o=>{this[Ue](o,t),e()})}[bi](t,e,r,i,o){let c=r.shift();if(this.preservePaths||c===void 0)return i();let d=Le.resolve(e,c);re.lstat(d,(u,f)=>{if(u)return i();if(f?.isSymbolicLink())return o(new ro(d,Le.resolve(d,r.join("/"))));this[bi](t,d,r,i,o)})}[Wu](){this[Ls]++}[wr](){this[Ls]--,this[ac]()}[Tc](t){this[wr](),t.resume()}[Ic](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Ri}[Sc](t){this[Wu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Uu](t,r))}[Uu](t,e){let r=d=>{e(d)},i=()=>{this[_n](this.cwd,this.dmode,d=>{if(d){this[Ue](d,t),r();return}this[Ti]=!0,o()})},o=()=>{if(t.absolute!==this.cwd){let d=X(Le.dirname(String(t.absolute)));if(d!==this.cwd)return this[_n](d,this.dmode,u=>{if(u){this[Ue](u,t),r();return}c()})}c()},c=()=>{re.lstat(String(t.absolute),(d,u)=>{if(u&&(this.keep||this.newer&&u.mtime>(t.mtime??u.mtime))){this[Tc](t),r();return}if(d||this[Ic](t,u))return this[ut](null,t,r);if(u.isDirectory()){if(t.type==="Directory"){let f=this.chmod&&t.mode&&(u.mode&4095)!==t.mode,x=p=>this[ut](p??null,t,r);return f?re.chmod(String(t.absolute),Number(t.mode),x):x()}if(t.absolute!==this.cwd)return re.rmdir(String(t.absolute),f=>this[ut](f??null,t,r))}if(t.absolute===this.cwd)return this[ut](null,t,r);b_(String(t.absolute),f=>this[ut](f??null,t,r))})};this[Ti]?o():i()}[ut](t,e,r){if(t){this[Ue](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Ac](e,r);case"Link":return this[Hu](e,r);case"SymbolicLink":return this[Gu](e,r);case"Directory":case"GNUDumpDir":return this[kc](e,r)}}[Ws](t,e,r,i){re[r](e,String(t.absolute),o=>{o?this[Ue](o,t):(this[wr](),t.resume()),i()})}},_i=t=>{try{return[null,t()]}catch(e){return[e,null]}},Af=class extends Fc{sync=!0;[ut](t,e){return super[ut](t,e,()=>{})}[Sc](t){if(!this[Ti]){let o=this[_n](this.cwd,this.dmode);if(o)return this[Ue](o,t);this[Ti]=!0}if(t.absolute!==this.cwd){let o=X(Le.dirname(String(t.absolute)));if(o!==this.cwd){let c=this[_n](o,this.dmode);if(c)return this[Ue](c,t)}}let[e,r]=_i(()=>re.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Tc](t);if(e||this[Ic](t,r))return this[ut](null,t);if(r.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[d]=c?_i(()=>{re.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[ut](d,t)}let[o]=_i(()=>re.rmdirSync(String(t.absolute)));this[ut](o,t)}let[i]=t.absolute===this.cwd?[]:_i(()=>E_(String(t.absolute)));this[ut](i,t)}[Ac](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,i=d=>{let u;try{re.closeSync(o)}catch(f){u=f}(d||u)&&this[Ue](d||u,t),e()},o;try{o=re.openSync(String(t.absolute),yf(t.size),r)}catch(d){return i(d)}let c=this.transform&&this.transform(t)||t;c!==t&&(c.on("error",d=>this[Ue](d,t)),t.pipe(c)),c.on("data",d=>{try{re.writeSync(o,d,0,d.length)}catch(u){i(u)}}),c.on("end",()=>{let d=null;if(t.mtime&&!this.noMtime){let u=t.atime||new Date,f=t.mtime;try{re.futimesSync(o,u,f)}catch(x){try{re.utimesSync(String(t.absolute),u,f)}catch{d=x}}}if(this[Ii](t)){let u=this[Ai](t),f=this[ki](t);try{re.fchownSync(o,Number(u),Number(f))}catch(x){try{re.chownSync(String(t.absolute),Number(u),Number(f))}catch{d=d||x}}}i(d)})}[kc](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,i=this[_n](String(t.absolute),r);if(i){this[Ue](i,t),e();return}if(t.mtime&&!this.noMtime)try{re.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Ii](t))try{re.chownSync(String(t.absolute),Number(this[Ai](t)),Number(this[ki](t)))}catch{}e(),t.resume()}[_n](t,e){try{return f_(X(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[bi](t,e,r,i,o){if(this.preservePaths||r.length===0)return i();let c=e;for(let d of r){c=Le.resolve(c,d);let[u,f]=_i(()=>re.lstatSync(c));if(u)return i();if(f.isSymbolicLink())return o(new ro(c,Le.resolve(e,r.join("/"))))}i()}[Ws](t,e,r,i){let o=`${r}Sync`;try{re[o](e,String(t.absolute)),i(),t.resume()}catch(c){return this[Ue](c,t)}}},v_=t=>{let e=new Af(t),r=t.file,i=ff.statSync(r),o=t.maxReadSize||16*1024*1024;new Hm(r,{readSize:o,size:i.size}).pipe(e)},S_=(t,e)=>{let r=new Fc(t),i=t.maxReadSize||16*1024*1024,o=t.file;return new Promise((c,d)=>{r.on("error",d),r.on("close",c),ff.stat(o,(u,f)=>{if(u)d(u);else{let x=new Cc(o,{readSize:i,size:f.size});x.on("error",d),x.pipe(r)}})})},kf=Pi(v_,S_,t=>new Af(t),t=>new Fc(t),(t,e)=>{e?.length&&sf(t,e)}),I_=(t,e)=>{let r=new Bc(t),i=!0,o,c;try{try{o=ot.openSync(t.file,"r+")}catch(f){if(f?.code==="ENOENT")o=ot.openSync(t.file,"w+");else throw f}let d=ot.fstatSync(o),u=Buffer.alloc(512);e:for(c=0;c<d.size;c+=512){for(let p=0,_=0;p<512;p+=_){if(_=ot.readSync(o,u,p,u.length-p,c+p),c===0&&u[0]===31&&u[1]===139)throw new Error("cannot append to compressed archives");if(!_)break e}let f=new jn(u);if(!f.cksumValid)break;let x=512*Math.ceil((f.size||0)/512);if(c+x+512>d.size)break;c+=x,t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime)}i=!1,A_(t,r,c,o,e)}finally{if(i)try{ot.closeSync(o)}catch{}}},A_=(t,e,r,i,o)=>{let c=new Zu(t.file,{fd:i,start:r});e.pipe(c),T_(e,o)},k_=(t,e)=>{e=Array.from(e);let r=new to(t),i=(o,c,d)=>{let u=(v,w)=>{v?ot.close(o,E=>d(v)):d(null,w)},f=0;if(c===0)return u(null,0);let x=0,p=Buffer.alloc(512),_=(v,w)=>{if(v||w===void 0)return u(v);if(x+=w,x<512&&w)return ot.read(o,p,x,p.length-x,f+x,_);if(f===0&&p[0]===31&&p[1]===139)return u(new Error("cannot append to compressed archives"));if(x<512)return u(null,f);let E=new jn(p);if(!E.cksumValid)return u(null,f);let I=512*Math.ceil((E.size??0)/512);if(f+I+512>c||(f+=I+512,f>=c))return u(null,f);t.mtimeCache&&E.mtime&&t.mtimeCache.set(String(E.path),E.mtime),x=0,ot.read(o,p,0,512,f,_)};ot.read(o,p,0,512,f,_)};return new Promise((o,c)=>{r.on("error",c);let d="r+",u=(f,x)=>{if(f&&f.code==="ENOENT"&&d==="r+")return d="w+",ot.open(t.file,d,u);if(f||!x)return c(f);ot.fstat(x,(p,_)=>{if(p)return ot.close(x,()=>c(p));i(x,_.size,(v,w)=>{if(v)return c(v);let E=new Ys(t.file,{fd:x,start:w});r.pipe(E),E.on("error",c),E.on("close",o),R_(r,e)})})};ot.open(t.file,d,u)})},T_=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Ar({file:Tf.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r)}),t.end()},R_=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Ar({file:Tf.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:i=>t.add(i)}):t.add(r);t.end()},yi=Pi(I_,k_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Jm(t))throw new TypeError("file is required");if(t.gzip||t.brotli||t.zstd||t.file.endsWith(".br")||t.file.endsWith(".tbr"))throw new TypeError("cannot append to compressed archives");if(!e?.length)throw new TypeError("no paths specified to add/replace")}),HA=Pi(yi.syncFile,yi.asyncFile,yi.syncNoFile,yi.asyncNoFile,(t,e=[])=>{yi.validate?.(t,e),C_(t)}),C_=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,i)=>e(r,i)&&!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0)):(r,i)=>!((t.mtimeCache?.get(r)??i.mtime??0)>(i.mtime??0))};cn();var ft={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",UPGRADE:"_agent/upgrade",DELETE:"_agent/delete",PUBLISH_SKILL:"_agent/publishSkill"};function io(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Rf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function so(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Cf(t){let e=t?.permissionMode;if(typeof e!="string")return;let r=e.trim();return r===""?void 0:r}function Pf(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function $n(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Kt();qe();te();De();qe();function kr(t,e){if(io(t)!=="cloud")throw new k("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Di(t){return t.startsWith("http://")||t.startsWith("https://")}function Tr(t){return t.endsWith("/")?t.slice(0,-1):t}import{readFileSync as O2}from"node:fs";import{dirname as N2,join as M2}from"node:path";import{fileURLToPath as F2}from"node:url";var Ot="0.2.0-alpha.0";qe();te();var oo="1008033",Nf="1289";var Mf="pbbp2",Bf="https://www.coze.cn",Ff="/api/coze_claw/resource/get_frontier_key",F_="https://www.coze.cn",z_="wss://frontier.coze.cn";function Rr(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??F_}function zf(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??z_}function En(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,i=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),i&&(e["x-use-ppe"]=i),e}function Li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Oi=G("handshake");async function zc(t){let e=Rr(t.endpoint),r=t.timeoutMs??1e4,i=`${Tr(e)}${Ff}?aid=${encodeURIComponent(oo)}`,o={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...En(t.ppeOverride)},c=new AbortController,d=setTimeout(()=>c.abort(),r);Oi.info("frontier key handshake",{base:e});try{let u=await fetch(i,{method:"GET",headers:o,signal:c.signal}),f=u.headers.get("x-tt-logid")??"",x=u.headers.get("x-tt-trace-id")??"";if(!u.ok){let E=await u.text().catch(()=>"");throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${u.status} logid=${f}: ${E.slice(0,200)}`)}let p=await u.json();if(p.code!==void 0&&p.code!==0)throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${p.code} msg=${p.msg??"-"} logid=${f}`);let _=p.data??{},v=typeof _.access_key=="string"&&_.access_key||typeof _.accessKey=="string"&&_.accessKey||void 0,w=typeof _.device_id=="string"&&_.device_id||typeof _.deviceId=="string"&&_.deviceId||void 0;if(!v||!w){let E=JSON.stringify(p).slice(0,500);throw new k("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${f}: ${E}`)}return Oi.info("handshake ok",{remoteDeviceId:w,logid:f,traceId:x}),{accessKey:v,deviceId:w}}catch(u){if(u instanceof k)throw Oi.error("handshake failed (bridge error)",{base:e,message:u.message,code:u.code}),u;if(u.name==="AbortError")throw Oi.warn("handshake timeout",{base:e,timeoutMs:r}),new k("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:u});let f=u.cause;throw Oi.error("handshake error",{base:e,message:u instanceof Error?u.message:String(u),errno:f?.code,syscall:f?.syscall,cause:String(u).slice(0,300)}),new k("UPSTREAM_HANDSHAKE_FAILED",String(u),{cause:u})}finally{clearTimeout(d)}}var Uc=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Et="auto",Uf=15e4;function Gf(t){return{model:Gc(t.model)??Et,...t.modelToken?{modelToken:t.modelToken}:{}}}function U_(t){return!t||t===Et}var G_=new Set(["auto","\u81EA\u52A8"]);function Gc(t){let e=t?.trim();if(e)return G_.has(e.toLowerCase())?Et:e}function Hf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Uc,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||Et;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,e.ANTHROPIC_DEFAULT_HAIKU_MODEL=r,e.ANTHROPIC_DEFAULT_OPUS_MODEL=r,e.ANTHROPIC_DEFAULT_SONNET_MODEL=r,e.CLAUDE_CODE_SUBAGENT_MODEL=r,e.CLAUDE_CODE_ATTRIBUTION_HEADER="0",t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else U_(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function qf(t,e,r){return t.modelToken?{baseUrl:`${Uc}/v1`,providerName:"coze",headers:{Authorization:`Bearer ${t.modelToken}`,...Hc(e,r)}}:null}function jf(t){if(!t.modelToken)return{};let e={model:t.model||Et,model_context_window:t.modelInfo?.contextWindow??Uf};return{CODEX_CONFIG:JSON.stringify(e)}}function Hc(t,e){let{ttEnv:r,usePpe:i}=Li(t),o={};return r&&(o["x-tt-env"]=r),i&&(o["x-use-ppe"]=i),e&&(o["x-mock-scenario"]=e),o}function Wf(t,e,r){if(!t.modelToken)return{};let i=Hc(e,r);return Object.keys(i).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(i).map(([c,d])=>`${c}:${d}`).join(`
92
+ `)}}function qc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function $f(t,e,r){if(!t.modelToken)return null;let i=t.model||Et,o=Hc(e,r),c=["text"];t.modelInfo?.capabilities?.image===!0&&c.push("image");let d={baseUrl:`${Uc}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:i,name:i,reasoning:!1,input:c,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Uf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(o).length>0&&(d.headers=o),d}var fe=G("agent-handlers"),Vf=5*1024*1024,W_=1,$_=6,K_=new Set(["node_modules",".git",".coze","dist","build",".next"]),V_=/^(ppe|boe)_[A-Za-z0-9_-]{1,120}$/,Z_=/^[A-Za-z][A-Za-z0-9._-]{0,63}$/,J_=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?(?:\+[0-9A-Za-z][0-9A-Za-z.-]*)?$/;function Y_(t){let e=t?.trim();return e?J_.test(e)||Z_.test(e)?e:(fe.warn("_agent/upgrade: invalid targetVersion, fallback to latest",{targetVersion:t}),"latest"):"latest"}function X_(t){return new Promise((e,r)=>{let i=nt("npx",t,{detached:!0,stdio:"ignore",windowsHide:!0}),o=!1,c=d=>{o||(o=!0,d?r(d):e(i.pid??0))};i.once("spawn",()=>{i.unref(),c()}),i.once("error",d=>c(d))})}var co=class{constructor(e){this.opts=e}opts;async listSkills(e){e._meta;let r=$n(e._meta),i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,c=i?.skills??[],d=[],u=new Set;for(let f of c){let x=We(o,f.relPath,"SKILL.md");await Kf(x).then(_=>_.isFile()).catch(()=>!1)&&(d.push(ny(f)),u.add(f.relPath))}if(e.scanLocal){let f=i?.framework??"claude-code",x=await Q_(r,o,f);for(let p of x)u.has(p.relPath)||(u.add(p.relPath),d.push(p.skill))}return{skills:d}}async addSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=e.skills??[],c=[...i.skills??[]],d=new Map(c.map((f,x)=>[f.skillId,x])),u=[];for(let f of o){let x=await lo({agentId:r,workspace:i.workspace,framework:i.framework,skill:f});uo(c,d,x),u.push(f)}return await si(r,c),this.reloadAgentSessions(r,"skills-added"),{installedSkills:u}}async removeSkills(e){e._meta;let r=$n(e._meta),i=await this.requireAgentCfg(r),o=new Set(e.skillIds??[]),c=i.skills??[],d=[];for(let u of c){if(!o.has(u.skillId)){d.push(u);continue}let f=We(i.workspace,u.relPath);await $c(f,{recursive:!0,force:!0}),fe.info("skill removed",{agentId:r,skillId:u.skillId,relPath:u.relPath})}return await si(r,d),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}async publishSkill(e){e._meta;let r=$n(e._meta);if(!e.skillName)throw new k("IPC_BAD_REQUEST","_agent/publishSkill: missing skillName");fe.info("_agent/publishSkill start",{agentId:r,skillId:e.skillId??"",skillName:e.skillName,userId:e.userId??"",accountId:e.accountId??""});let i=await this.loadAgentCfg(r),o=i?.workspace??Ve(r).workspace,c=i?.framework??"claude-code",d=e0(e.skillName),u=We(Xc(c),d),f=We(o,u),x=We(f,"SKILL.md");if(!await Kf(x).then(T=>T.isFile()).catch(()=>!1))throw new k("SKILL_NOT_FOUND",`skill not found locally: ${e.skillName} (${u})`);let _=new Yc.default;_.addLocalFolder(f,d);let v=_.toBuffer();if(v.length>Zf)throw new k("SKILL_ZIP_TOO_LARGE",`skill zip ${v.length} bytes exceeds limit ${Zf}`);let w=await ao(x,{encoding:"utf8"}).then(T=>n0(T).description).catch(()=>{}),E={};this.opts.publishSkillToMarketplace?E=await this.opts.publishSkillToMarketplace({zip:v,...e.skillId?{skillId:e.skillId}:{},skillName:e.skillName,...w?{description:w}:{},agentId:r,...e.userId?{userId:e.userId}:{},...e.accountId?{accountId:e.accountId}:{}}):fe.warn("_agent/publishSkill: publishSkillToMarketplace not injected, skip upload",{agentId:r,skillName:e.skillName});let I=E.version??"v1.0",A=E.skillId??e.skillId??t0(r,u);if(i){let T=i.skills??[],D=T.find(y=>y.relPath===u);D?(D.version=I,D.skillId=A):T.push({skillId:A,skillName:e.skillName,relPath:u,version:I,installedAt:Date.now(),...w?{description:w}:{}}),await si(r,T)}return fe.info("skill published",{agentId:r,skillName:e.skillName,relPath:u,zipBytes:v.length,skillId:A,version:I}),{ok:!0,skillId:A,version:I}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let i=this.opts.agents.get(e);if(i)for(let[o,c]of i.sessions){if(!c.downstream)continue;let d=c.acpSessionId;if(d&&i.activeTriggers.has(d)||this.isRuntimePendingPermission(c)){c.reloadAfterTurn=!0,fe.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d});continue}let f=c.downstream;c.downstream=void 0,fe.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:i.framework,cloudId:o,acpId:d}),f.stop(r).catch(x=>fe.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:o,err:String(x)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return fe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,i=await ke(r);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);if(i.cozeIdentity===e.cozeIdentity)return fe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await lr(i.workspace,i.framework,e.cozeIdentity)}catch(o){throw fe.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:i.framework,workspace:i.workspace,err:String(o)}),new k("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(o)}`,{cause:o})}return i.cozeIdentity=e.cozeIdentity,await Me(i),fe.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:i.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async upgradeBridge(e){let r=e.agentId||e._meta?.cozeAgentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/upgrade: missing agentId");if(!await ke(r))throw new k("AGENT_NOT_FOUND",`agent not found: ${r}`);let o=["-y"];e.registry&&Di(e.registry)&&o.push(`--registry=${e.registry}`);let c=Y_(e.targetVersion);o.push("--ignore-existing",`coze-bridge@${c}`,"connect");let d=e._meta?.cozeEnv;d&&V_.test(d)&&o.push("--env",d);let u=await X_(o);return fe.info("_agent/upgrade: spawned bridge upgrade process",{agentId:r,pid:u,targetVersion:c,currentVersion:e.currentVersion??"",reason:e.reason??""}),{ok:!0,accepted:!0,pid:u,message:"bridge upgrade started"}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let i=await ke(r);return i?(i.disconnectedAt=Date.now(),i.disconnectReason=e.reason??"",await Me(i),fe.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(fe.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async deleteAgent(e){let r=e.agentId;if(!r)throw new k("IPC_BAD_REQUEST",`${ft.DELETE}: missing agentId`);let i=await ke(r),o=e._meta?.cozeDeployType==="cloud"||e._meta?.cozeDeployType==="local"?e._meta.cozeDeployType:void 0,c=e.deployType??o??i?.deployType??"local";this.opts.disposeForDelete&&await this.opts.disposeForDelete(r,e.reason??"delete");let d=Ve(r);return c==="cloud"?await $c(d.root,{recursive:!0,force:!0}):i&&(i.deletedAt=Date.now(),i.deleteReason=e.reason??"deleted",await Me(i)),fe.info("agent deleted",{agentId:r,reason:e.reason??"",deployType:c,configFound:!!i}),{ok:!0}}async switchModel(e){if(kr(e._meta,"_agent/switchModel"),!e.agentId)throw new k("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=Gc(e.model)??Et,i=await ke(e.agentId);if(!i)throw new k("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);i.model=r,e.modelInfo&&(i.modelInfo=e.modelInfo),await Me(i),fe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let o=this.opts.agents.get(e.agentId);if(!o)return fe.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};o.model=r,e.modelInfo&&o.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(o).catch(d=>fe.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(d)}));let c=[];for(let[d,u]of o.allSessionQueues())c.push(u.enqueue(async()=>{let f=o.sessions.get(d);f?.downstream&&(await f.downstream.stop(`switchModel: ${r}`).catch(()=>{}),f.downstream=void 0)}));return await Promise.all(c),fe.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:c.length}),{ok:!0}}async resetAgent(e){if(kr(e._meta,ft.RESET),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,ft.RESET),await this.runDetailSync(e.agentId,ft.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let i=this.opts.agents.get(e);if(!i){await this.clearPersistedAcpSessionIds(e),fe.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await i.killAllRuntimes(r);for(let c of i.sessions.values())c.acpSessionId=void 0,c.replySeq=0,c.loadingSession=!1,c.spawnFailCount=void 0,c.spawnFailedAt=void 0;let o=new Map;for(let[c,d]of i.sessions)o.set(c,{modelToken:d.modelToken,tokenGeneratedAt:d.tokenGeneratedAt});await ii(e,o)}async clearPersistedAcpSessionIds(e){let r=await ke(e).catch(()=>null);if(!r?.sessions)return;let i=!1;for(let o of Object.values(r.sessions))o.acpSessionId&&(o.acpSessionId=void 0,i=!0);i&&await Me(r)}async repairAgent(e){if(kr(e._meta,ft.REPAIR),!e.agentId)throw new k("IPC_BAD_REQUEST",`${ft.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new k("IPC_BAD_REQUEST",`${ft.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(i){fe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(i)})}return await this.runDetailSync(e.agentId,ft.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,i){if(!this.opts.detailSyncer){fe.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(o){fe.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:i,err:String(o)})}}async getFileTree(e){kr(e._meta,"_agent/getFileTree");let r=e._meta,i=$n(r),o=await this.resolveWorkspace(i),c=e.filePath??"",d=this.safeJoin(o,c),u=await jc(d).catch(()=>null);if(!u)throw new k("IPC_BAD_REQUEST",`path not found: ${c}`);if(u.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${c}`);if(!await ri(d,o))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${c}`);let f=xy(e.depth);return u.isDirectory()?{tree:await hy(o,d,c,f)}:{tree:[{name:py(c),path:s0(c||"."),isDir:!1,size:u.size,modifiedAt:Math.floor(u.mtimeMs)}]}}async getFileContent(e){kr(e._meta,"_agent/getFileContent");let r=$n(e._meta),i=await this.resolveWorkspace(r);if(!e.filePath)throw new k("IPC_BAD_REQUEST","filePath required");let o=this.safeJoin(i,e.filePath),c=await jc(o).catch(()=>null);if(!c||!c.isFile())throw new k("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(c.isSymbolicLink())throw new k("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await ri(o,i))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(c.size>Vf)throw new k("IPC_BAD_REQUEST",`file too large: ${c.size} bytes (max ${Vf})`);let d=await ao(o);return d.includes(0)?{content:d.toString("base64"),encoding:"base64",size:c.size}:{content:d.toString("utf8"),encoding:"utf-8",size:c.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await ke(e).catch(()=>null))?.workspace??Ve(e).workspace}safeJoin(e,r){let i=Vc(e,r||"."),o=Jc(e,i);if(o.startsWith("..")||o===".."||o.startsWith(`..${Yf}`))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return i}loadAgentCfg(e){return ke(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new k("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function e0(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new k("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new k("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function Xc(t){return t==="claude-code"?We(".claude","skills"):We(".agents","skills")}function t0(t,e){return(H_("sha256").update(`${t}\0${e}`).digest().readBigUInt64BE(0)&0x7fffffffffffffffn).toString()}function n0(t){if(!t.startsWith("---"))return{};let e=t.indexOf(`
93
+ ---`,3);if(e<0)return{};let r=t.slice(3,e),i={};for(let o of r.split(`
94
+ `)){let c=/^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(o);if(!c||!c[2])continue;let d=c[1],u=c[2].trim();(u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),u&&(i[d]=u)}return i}async function Q_(t,e,r){let i=Xc(r),o=We(e,i),c=await Jf(o,{withFileTypes:!0}).catch(()=>null);if(!c)return[];let d=[];for(let u of c){if(!u.isDirectory())continue;let f=u.name,x=We(i,f),p=We(o,f,"SKILL.md"),_=await ao(p,{encoding:"utf8"}).catch(()=>null);if(_===null)continue;let v=n0(_);d.push({relPath:x,skill:{skillId:t0(t,x),skillName:v.name||f,...v.description?{description:v.description}:{}}})}return d}var ey=3e4,ty=50*1024*1024,Zf=10*1024*1024,Cr=3e4;async function lo(t){let{agentId:e,workspace:r,framework:i,skill:o}=t;if(!o.skillName)throw new k("IPC_BAD_REQUEST","skill missing skillName");let c=typeof o.content=="string"&&o.content.length>0,d=typeof o.downloadUrl=="string"&&o.downloadUrl.length>0;if(!c&&!d)throw new k("IPC_BAD_REQUEST",`skill ${o.skillId} missing both content and downloadUrl`);let u=e0(o.skillName),f=Xc(i),x=We(f,u),p=We(r,x);if(await Wc(p,{recursive:!0}),c){let v=Buffer.from(o.content,"utf8");Ni(v.length),await Kc(We(p,"SKILL.md"),v,"utf8")}else{let v=await iy(o.downloadUrl);oy(v)?await ly(v,p):ay(v)?await cy(v,p):await Kc(We(p,"SKILL.md"),v.toString("utf8"),"utf8")}let _={skillId:o.skillId,skillName:o.skillName,relPath:x,installedAt:Date.now(),...o.description?{description:o.description}:{},...o.icon?{icon:o.icon}:{},...o.version?{version:o.version}:{},...o.downloadUrl?{downloadUrl:o.downloadUrl}:{},...o.config?{config:o.config}:{},...o.builtin?{builtin:o.builtin}:{}};return fe.info("skill installed",{agentId:e,skillId:o.skillId,skillName:o.skillName,relPath:x,source:c?"content":"downloadUrl"}),_}function uo(t,e,r){let i=e.get(r.skillId);if(i!==void 0){t[i]=r;return}e.set(r.skillId,t.length),t.push(r)}function ny(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}function ry(t){return{skillId:t.skillId,skillName:t.skillName,...t.downloadUrl?{downloadUrl:t.downloadUrl}:{},...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function r0(t,e){let r=await ke(t,e);if(!r)return{status:"skipped",count:0};if(r.disconnectedAt)return{status:"skipped",count:0};let i=Ot,o=r.skillsRefreshedForVersion;if(o===i)return{status:"noop",count:0};if(!o)return r.skillsRefreshedForVersion=i,await Me(r,e),{status:"seeded",count:0};let c=[...r.skills??[]],d=new Map(c.map((p,_)=>[p.skillId,_])),u=c.filter(p=>p.builtin===!0&&!!p.downloadUrl);if(u.length===0)return r.skillsRefreshedForVersion=i,await Me(r,e),{status:"noop",count:0};let f=0,x=0;for(let p of u)try{await $c(We(r.workspace,p.relPath),{recursive:!0,force:!0});let _=await lo({agentId:t,workspace:r.workspace,framework:r.framework,skill:ry(p)});uo(c,d,_),f+=1}catch(_){x+=1,fe.warn("refresh builtin skill failed (skipping)",{agentId:t,skillId:p.skillId,skillName:p.skillName,err:String(_)})}return r.skills=c,x===0&&(r.skillsRefreshedForVersion=i),await Me(r,e),fe.info("builtin skills refreshed after bridge upgrade",{agentId:t,from:o,to:i,ok:f,failed:x}),{status:"refreshed",count:f}}async function iy(t){if(!t)throw new k("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Ni(e);let r=sy(t);return Ni(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await ao(e);return Ni(r.length),r}if(Di(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),ey);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new k("IPC_BAD_REQUEST",`fetch skill failed HTTP ${i.status} ${t}`);let o=await i.arrayBuffer();return Ni(o.byteLength),Buffer.from(o)}finally{clearTimeout(r)}}throw new k("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Ni(t){if(t>ty)throw new k("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function sy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new k("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],i=e[3]??"";return r?Buffer.from(i,"base64"):Buffer.from(decodeURIComponent(i),"utf8")}function oy(t){return t.length>=2&&t[0]===31&&t[1]===139}function ay(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function Zc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function cy(t,e){let r,i;try{r=new Yc.default(t),i=r.getEntries()}catch(d){throw new k("IPC_BAD_REQUEST",`zip parse failed: ${d.message}`,{cause:d})}for(let d of i){let u=d.entryName;if(!u||Zc(u))continue;if(u.startsWith("/")||/^[A-Za-z]:[\\/]/.test(u))throw new k("IPC_BAD_REQUEST",`zip entry absolute path: ${u}`);if(u.split(/[/\\]/).some(x=>x===".."))throw new k("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${u}`);let f=d.header.attr>>>16&61440;if(f!==0&&f!==32768&&f!==16384)throw new k("IPC_BAD_REQUEST",`zip entry kind 0x${f.toString(16)} not allowed (symlink/hardlink/special): ${u}`)}let o=dy(i),c=Vc(e);for(let d of i){if(Zc(d.entryName))continue;let u=d.entryName;if(o&&u.startsWith(o)&&(u=u.slice(o.length)),!u)continue;let f=Vc(e,u),x=Jc(c,f);if(x.startsWith("..")||x==="..")throw new k("IPC_BAD_REQUEST",`zip entry escapes destDir: ${u}`);if(d.isDirectory){await Wc(f,{recursive:!0});continue}await Wc(q_(f),{recursive:!0});let p;try{p=d.getData()}catch(_){throw new k("IPC_BAD_REQUEST",`zip entry getData failed (${d.entryName}): ${_.message}`,{cause:_})}await Kc(f,p)}}function dy(t){let e;for(let r of t){let i=r.entryName;if(!i||Zc(i))continue;let o=i.indexOf("/");if(o<=0)return;let c=i.slice(0,o+1);if(e===void 0)e=c;else if(e!==c)return}return e}async function ly(t,e){await uy(t);let r=kf({cwd:e,strip:1}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar extract timeout (${Cr}ms)`))},Cr);try{await Qf(Xf.from(t),r)}catch(c){throw c instanceof k?c:i?new k("IPC_BAD_REQUEST",`tar extract timeout (${Cr}ms)`):new k("IPC_BAD_REQUEST",`tar extract failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}}async function uy(t){let e=[],r=Ar({onReadEntry:c=>{let d=c.path,u=c.type;if(u!=="File"&&u!=="Directory"){e.push(`tar entry kind '${u}' not allowed (symlink/hardlink/special): ${d.slice(0,100)}`);return}if(d.startsWith("/")||d.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(d)){e.push(`tar entry absolute path: ${d}`);return}d.split(/[/\\]/).some(x=>x==="..")&&e.push(`tar entry contains '..': ${d}`)}}),i=!1,o=setTimeout(()=>{i=!0,r.destroy(new k("IPC_BAD_REQUEST",`tar list timeout (${Cr}ms)`))},Cr);try{await Qf(Xf.from(t),r)}catch(c){throw i?new k("IPC_BAD_REQUEST",`tar list timeout (${Cr}ms)`):new k("IPC_BAD_REQUEST",`tar list failed: ${c.message??String(c)}`,{cause:c})}finally{clearTimeout(o)}if(e.length>0)throw new k("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var fy=5e3;async function hy(t,e,r,i){return i0(t,e,r,i,{count:0})}async function i0(t,e,r,i,o){if(i<=0)return[];let c;try{c=await Jf(e,{withFileTypes:!0})}catch{return[]}let d=[];for(let u of c){if(K_.has(u.name)||u.isSymbolicLink())continue;if(o.count>=fy){d.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let f=We(e,u.name),x=j_(We(r,u.name)),p=null;try{p=await jc(f)}catch{continue}if(p.isSymbolicLink())continue;o.count++;let _={name:u.name,path:s0(Jc(t,f)),isDir:p.isDirectory(),size:p.size,modifiedAt:Math.floor(p.mtimeMs)};p.isDirectory()&&i>1&&(_.children=await i0(t,f,x,i-1,o)),d.push(_)}return d.sort((u,f)=>u.isDir!==f.isDir?u.isDir?-1:1:u.name.localeCompare(f.name)),d}function xy(t){return!t||t<=0?W_:Math.min(t,$_)}function py(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function s0(t){return t.split(Yf).join("/")}te();var vn=G("agent-health-reporter"),gy=1e4,my=3,Mi=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??gy,this.livenessFailureThreshold=e.livenessFailureThreshold??my}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;livenessFailureThreshold;consecutiveFailures=0;isLivenessLost(){return this.consecutiveFailures>=this.livenessFailureThreshold}start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),vn.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),vn.info("heartbeat stopped"))}async tick(){if(this.inFlight){vn.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){this.consecutiveFailures=0,vn.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let d of this.opts.core.agents.values()){let u=wy(d);if(!u)continue;let f={agentId:d.agentId,status:u};d.patToken&&(f.patToken=d.patToken),d.accountId&&(f.accountId=d.accountId),r.push(f)}if(r.length===0){this.consecutiveFailures=0;return}let i={agents:r,bridgeVersion:Ot,_meta:{cozeDeviceId:e}},o;try{o=await this.opts.core.sendRequest("_agent/health",i,5e3),this.consecutiveFailures=0}catch(d){this.consecutiveFailures+=1,vn.warn("heartbeat batch send failed",{count:r.length,consecutiveFailures:this.consecutiveFailures,err:String(d)})}let c=o?.authFailures;if(c&&c.length>0&&(vn.warn("heartbeat received authFailures from cloud",{count:c.length,agentIds:c.map(d=>d.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(c)}catch(d){vn.warn("onAuthFailures callback failed (ignored)",{err:String(d)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){vn.warn("onTickEnd hook failed",{err:String(r)})}}};function wy(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}cn();import{mkdir as id,rm as fb,stat as hb}from"node:fs/promises";import{homedir as xb}from"node:os";import{join as od}from"node:path";sn();import{existsSync as Py}from"node:fs";import{release as Dy}from"node:os";import{basename as Oy,isAbsolute as Ly}from"node:path";function Bi(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Pr(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Dr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Sn(t,e){return{jsonrpc:"2.0",id:t,error:e}}qe();var fo=class extends Error{code;data;constructor(e){super(`JSON-RPC error code=${e.code} ${e.message}`),this.name="RemoteRpcError",this.code=e.code,e.data!==void 0&&(this.data=e.data)}},J={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019,AGENT_TURN_ABORTED:-32020,AGENT_ENV_NOT_READY:-32021,SKILL_NOT_FOUND:-32022,SKILL_ZIP_TOO_LARGE:-32023,OPERATION_NOT_ALLOWED_FOR_CLOUD:-32024};function o0(t){return"method"in t&&"id"in t&&t.id!==void 0}function a0(t){return"method"in t&&!("id"in t)}function ho(t){return!("method"in t)&&"id"in t}var _y={AGENT_NOT_FOUND:J.AGENT_NOT_FOUND,AGENT_BUSY:J.AGENT_BUSY,AGENT_DISCONNECTED:J.AGENT_DISCONNECTED,AGENT_TIMEOUT:J.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:J.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:J.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:J.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:J.INTERNAL_ERROR,BRIDGE_INTERNAL:J.INTERNAL_ERROR,IPC_AUTH_FAILED:J.INTERNAL_ERROR,IPC_BAD_REQUEST:J.INVALID_REQUEST,METHOD_NOT_FOUND:J.METHOD_NOT_FOUND,MODEL_TOKEN_GEN_FAILED:J.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:J.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:J.OPERATION_NOT_ALLOWED_FOR_LOCAL,OPERATION_NOT_ALLOWED_FOR_CLOUD:J.OPERATION_NOT_ALLOWED_FOR_CLOUD,UPSTREAM_DISCONNECTED:J.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:J.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:J.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:J.FILE_TOO_LARGE,UNSUPPORTED_MIME:J.UNSUPPORTED_MIME,UPLOAD_FAILED:J.UPLOAD_FAILED,UPSTREAM_NOT_READY:J.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:J.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:J.AGENT_APPROVAL_TIMEOUT,AGENT_TURN_ABORTED:J.AGENT_TURN_ABORTED,AGENT_ENV_NOT_READY:J.AGENT_ENV_NOT_READY,SKILL_NOT_FOUND:J.SKILL_NOT_FOUND,SKILL_ZIP_TOO_LARGE:J.SKILL_ZIP_TOO_LARGE};function yy(t){if(t!=null)return t instanceof Error?{name:t.name,message:Fi(t.message)}:typeof t=="string"?Fi(t):typeof t=="object"?Ey(t):t}var by=[[/\/Users\/[^/\s'"`)]+/g,"/Users/<redacted>"],[/\/home\/[^/\s'"`)]+/g,"/home/<redacted>"],[/[A-Za-z]:\\Users\\[^\\\s'"`)]+/g,"C:\\Users\\<redacted>"],[/(Bearer|Token|Authorization:)\s+[\w._-]+/gi,"$1 <redacted>"],[/\b(sk|pat|ak)[-_][A-Za-z0-9_-]{20,}\b/g,"<redacted-key>"]];function Fi(t){let e=t;for(let[r,i]of by)e=e.replace(r,i);return e}function Ey(t){let e={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=Fi(i):e[r]=i;return e}function zi(t){if(t instanceof k){let e=yy(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),e&&typeof e=="object"&&"reason"in e&&typeof e.reason=="string"&&(r.reason=e.reason),{code:_y[t.code]??J.INTERNAL_ERROR,message:Fi(t.message),data:r}}return{code:J.INTERNAL_ERROR,message:Fi(t instanceof Error?t.message:String(t))}}function c0(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",i=!!e&&typeof e.message=="string"&&!!e.message,o=i?e?.message:t.message,c=t.data;if(i&&e){let{message:d,...u}=e;c=u}return new k(r,o,{retriable:e?.retriable??!1,cause:c})}function l0(t){return`${JSON.stringify(t)}
95
+ `}var d0=10*1024*1024,xo=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>d0){let o=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${o} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${d0} bytes`)}),[]}let r=this.buffer.split(`
96
+ `);this.buffer=r.pop()??"";let i=[];for(let o of r){let c=o.replace(/\r$/,"").trim();if(c)try{i.push(JSON.parse(c))}catch(d){this.onError?.({line:c,error:d})}}return i}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var f0={"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","session/set_mode":"session.setMode",initialize:"initialize"},Ek=Object.fromEntries(Object.entries(f0).map(([t,e])=>[e,t])),vy={"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"],"session.setMode":["agentId","sessionId"],"agent.pair":[],initialize:[]},Or=class{seq=0;next(e,r){this.seq+=1;let i=f0[e]??Sy(e),o=vy[i]??[],c=[i,String(this.seq)];if(o.length>0){let d=o.map(f=>u0(r?.[f]??"")),u=Iy(d).join(":");u&&c.push(u)}else r&&Object.values(r).some(d=>d)&&c.push(Object.values(r).filter(Boolean).map(d=>u0(String(d))).join(":"));return c.join("_")}reset(){this.seq=0}};function Sy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function u0(t){return t.replace(/[:_\s]+/g,"-")}function Iy(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}an();import{readFileSync as Ay}from"node:fs";var ky=384;async function Qc(t,e=process.env){let r={};for(let[i,o]of Object.entries(e))typeof o=="string"&&(r[i]=o);await dr(t.agentEnvFile,r,{mode:ky})}function ed(t){try{let e=JSON.parse(Ay(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function h0(t,e,r={},i=o=>o){return{...i({...t,...ed(e)}),...r}}Kt();ir();qe();te();De();import{execFileSync as Ty,spawnSync as Ry}from"node:child_process";function Ui(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Gi(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Ry("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var td=new Set;function x0(t){typeof t=="number"&&t>0&&td.add(t)}function p0(t){typeof t=="number"&&td.delete(t)}function g0(){for(let t of td)Gi(t,"SIGKILL")}var Lr="coze-bridge-daemon";function m0(t){let e=t?.execFn??(()=>{if(process.platform==="win32")return"";let o=process.getuid?.()??0;return Ty("pgrep",["-U",String(o),"-f",Lr],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3})}),r;try{r=e()}catch{return[]}let i=process.pid;return r.split(`
97
+ `).map(o=>Number.parseInt(o.trim(),10)).filter(o=>Number.isFinite(o)&&o>0&&o!==i)}async function w0(t,e){if(t.length===0)return;let r=e?.killFn??Gi,i=e?.isAliveFn??Ui,o=e?.sleepFn??(u=>new Promise(f=>setTimeout(f,u))),c=e?.graceMs??3e3,d=e?.pollMs??100;for(let u of t)r(u,"SIGTERM");for(let u=0;u<c&&t.some(f=>i(f));u+=d)await o(Math.min(d,c-u));for(let u of t)i(u)&&r(u,"SIGKILL")}var Cy=[{reason:"openclaw_scope_approval_pending",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/scope upgrade pending approval/i,message:"openclaw \u9700\u8981\u4F60\u5728\u672C\u673A\u6279\u51C6\u4E00\u6B21\u6743\u9650\u5347\u7EA7 (scope upgrade)\uFF0C\u8BF7\u5728\u672C\u673A openclaw \u5B8C\u6210\u6388\u6743\u540E\u91CD\u8BD5"},{reason:"openclaw_pairing_required",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/pairing required/i,message:"openclaw \u5C1A\u672A\u5B8C\u6210\u914D\u5BF9\uFF0C\u8BF7\u5148\u5728\u672C\u673A\u5B8C\u6210 openclaw \u914D\u5BF9\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_token_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway\.auth\.token.*(unavailable|secret reference)/i,message:"openclaw gateway token \u914D\u7F6E\u4E0D\u53EF\u7528 (\u914D\u6210\u4E86 secret \u5F15\u7528\u4F46\u5F53\u524D\u8DEF\u5F84\u53D6\u4E0D\u5230)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A openclaw \u7684 gateway.auth.token \u914D\u7F6E"},{reason:"openclaw_version_mismatch",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/protocol mismatch/i,message:"openclaw \u7248\u672C\u4E0E\u672C\u673A gateway \u4E0D\u517C\u5BB9 (protocol mismatch)\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A openclaw \u5230\u6700\u65B0\u7248\u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_not_ready",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/gateway closed (before ready|\(\d+\))/i,message:"openclaw gateway \u672A\u5C31\u7EEA (\u53EF\u80FD\u6B63\u5728\u542F\u52A8)\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"},{reason:"openclaw_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/OpenClaw config is invalid|Config invalid|Invalid config at|config was written by version/i,message:"\u4F60\u7684\u672C\u673A openclaw \u914D\u7F6E\u975E\u6CD5 (~/.openclaw/openclaw.json)\uFF0C\u8BF7\u8FD0\u884C `openclaw doctor --fix` \u6216 `openclaw config validate` \u4FEE\u590D\u540E\u91CD\u8BD5"},{reason:"openclaw_tls_self_signed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/self-signed certificate/i,message:"openclaw \u8FDE\u63A5\u88AB\u81EA\u7B7E\u8BC1\u4E66/\u4F01\u4E1A\u4EE3\u7406\u62E6\u622A (self-signed certificate)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A\u7F51\u7EDC/\u4EE3\u7406\u6216\u8BC1\u4E66\u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"openclaw_node_binary_not_found",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/\[qclaw-cli\] Error: (Node binary not found|QCLAW_CLI_NODE_BINARY not set)/i,message:"\u672C\u673A\u627E\u4E0D\u5230 node \u4E8C\u8FDB\u5236 (qclaw \u542F\u52A8\u5931\u8D25)\uFF0C\u8BF7\u68C0\u67E5\u672C\u673A Node \u5B89\u88C5\u4E0E PATH \u540E\u91CD\u8BD5"},{reason:"openclaw_gateway_unavailable",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["openclaw"],match:/ECONNREFUSED|\[object ErrorEvent\]|gateway connect failed|gateway (not connected|disconnected)/i,message:"openclaw gateway \u672A\u8FD0\u884C/\u672A\u8FDE\u63A5 (\u8FDE\u63A5\u672C\u673A gateway \u88AB\u62D2\u6216\u4F1A\u8BDD\u671F\u95F4\u65AD\u5F00)\uFF0C\u8BF7\u5728\u672C\u673A\u542F\u52A8 openclaw gateway \u540E\u91CD\u8BD5"},{reason:"openclaw_shim_bug",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["openclaw"],match:/openclaw-shim\/bin\/openclaw.*unbound variable/i,message:"openclaw \u542F\u52A8 shim \u811A\u672C\u5F02\u5E38 (unbound variable)\uFF0C\u8BF7\u53CD\u9988\u73AF\u5883\u7EF4\u62A4\u65B9\u4FEE\u590D shim"},{reason:"codex_user_config_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config:.*config\.toml|model_catalog_json|wire_api/i,message:"\u4F60\u7684\u672C\u673A ~/.codex/config.toml \u914D\u7F6E\u6709\u8BEF\uFF0C\u8BF7\u6309 codex \u62A5\u9519\u63D0\u793A\u4FEE\u6B63\u540E\u91CD\u8BD5"},{reason:"codex_provider_invalid",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/error loading config: Model provider .* not found/i,message:"\u4F60\u7684\u672C\u673A codex \u914D\u7F6E\u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684 model provider\uFF0C\u8BF7\u4FEE\u6B63 ~/.codex \u914D\u7F6E\u540E\u91CD\u8BD5"},{reason:"codex_path_update_failed",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["codex"],match:/could not update PATH[\s\S]*Operation not permitted/i,message:"codex \u56E0\u672C\u673A\u6743\u9650\u9650\u5236\u65E0\u6CD5\u66F4\u65B0 PATH/\u8BFB\u53D6\u914D\u7F6E (Operation not permitted)\uFF0C\u8BF7\u68C0\u67E5 ~/.codex \u76EE\u5F55\u6743\u9650\u6216\u91CD\u65B0\u6388\u4E88\u7EC8\u7AEF\u5B8C\u5168\u78C1\u76D8\u8BBF\u95EE\u540E\u91CD\u8BD5"},{reason:"codex_acp_exec_failed",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to execute[\s\S]*codex-acp|spawnSync[\s\S]*codex-acp/i,message:"codex ACP \u4E8C\u8FDB\u5236\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"codex_platform_binary_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["codex"],match:/Failed to locate @(zed-industries|agentclientprotocol)\/codex-acp|optional dependency was not installed|\.resolve is not a function/i,message:"codex ACP \u4F9D\u8D56\u7684\u5E73\u53F0\u4E8C\u8FDB\u5236\u7F3A\u5931\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u5B89\u88C5"},{reason:"acp_module_missing",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code","codex"],match:/Cannot find module[^\n]*node_modules[\\/]@(agentclientprotocol[\\/](claude-agent-acp|codex-acp)|zed-industries[\\/]codex-acp)/i,message:"ACP \u4F9D\u8D56\u672A\u6B63\u786E\u5B89\u88C5 (wrapper \u5165\u53E3\u7F3A\u5931)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect \u89E6\u53D1\u4F9D\u8D56\u91CD\u88C5"},{reason:"node_version_too_old",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code","openclaw"],match:/import .* with \{ type: ["']json["'] \}|import assertion|import attribute|openclaw\.mjs[\s\S]*Unexpected token '\.'/i,message:"\u672C\u673A Node \u7248\u672C\u8FC7\u4F4E (ACP \u9700\u8981\u8F83\u65B0 Node \u624D\u652F\u6301 import attributes / \u53EF\u9009\u94FE)\uFF0C\u8BF7\u5347\u7EA7 Node \u5230 \u2265 20.10 \u540E\u91CD\u8BD5"},{reason:"acp_cmd_misexec",bridgeCode:"AGENT_SPAWN_FAILED",frameworks:["claude-code"],match:/claude-agent-acp\.cmd.*@ECHO off|\.cmd:\d+/i,message:"claude ACP wrapper \u542F\u52A8\u65B9\u5F0F\u5F02\u5E38 (Windows .cmd \u88AB\u8BEF\u5F53\u811A\u672C\u6267\u884C)\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C pair/connect"},{reason:"prompt_too_long",bridgeCode:"AGENT_ENV_NOT_READY",frameworks:["claude-code"],match:/Prompt is too long|bad request: failed to read body: length limit exceeded/i,message:"\u672C\u8F6E\u8F93\u5165\u8FC7\u957F\uFF0C\u8D85\u8FC7\u6A21\u578B\u4E0A\u4E0B\u6587\u4E0A\u9650\uFF0C\u8BF7\u7CBE\u7B80\u8F93\u5165\u6216\u5F00\u542F\u65B0\u4F1A\u8BDD\u540E\u91CD\u8BD5"}];function _0(t,e){if(!e)return null;for(let r of Cy)if(!(r.frameworks&&!r.frameworks.includes(t))&&r.match.test(e))return{bridgeCode:r.bridgeCode,reason:r.reason,message:r.message};return null}function y0(t,e){return _0(t,e)}function b0(t,e){return _0(t,e)}function Nr(t,e,r){return!e&&r.firstUpdateMs>0&&t<r.firstUpdateMs?Math.max(1,r.firstUpdateMs-t):t<r.phase2GateMs?Math.max(1,r.phase2GateMs-t):Math.max(1,r.livenessWindowMs)}function E0(t,e,r){let o=r-t.armedAt-t.expectedIntervalMs;if(o>e.suspendThresholdMs){let x=t.suspendedMs+o,p=r-t.startedAt-x;return{action:"suspend",suspendedDeltaMs:o,rearmMs:Nr(p,t.firstFrameSeen,e)}}let c=r-t.startedAt-t.suspendedMs,d=t.awaitingApproval?e.approvalMaxMs:e.absoluteMaxMs;return c>=d?{action:"reject-backstop",awaitingApproval:t.awaitingApproval}:t.firstFrameSeen?c<e.phase2GateMs?{action:"continue",rearmMs:Nr(c,!0,e)}:r-t.lastActivityAt<e.livenessWindowMs||t.hasActiveTool||t.awaitingApproval?{action:"continue",rearmMs:Nr(c,!0,e)}:{action:"reject-idle"}:e.firstUpdateMs>0&&c>=e.firstUpdateMs&&!t.awaitingApproval?{action:"reject-idle"}:{action:"continue",rearmMs:Nr(c,!1,e)}}var v0=Ke("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),Ny=200,My=40,By=Ke("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Fy=Ke("COZE_BRIDGE_SESSION_PROMPT_IDLE_MS",600*1e3),zy=Ke("COZE_BRIDGE_SESSION_PROMPT_ABSOLUTE_MAX_MS",7200*1e3),Uy=Ke("COZE_BRIDGE_SUSPEND_THRESHOLD_MS",60*1e3),Gy=Ke("COZE_BRIDGE_SESSION_PROMPT_FIRST_UPDATE_MS",600*1e3),Hy=Ke("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),S0=500;function qy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=S0?t:`${e.slice(0,S0)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function jy(t){let e=[];typeof t.message=="string"&&e.push(t.message);let{data:r}=t;if(typeof r=="string")e.push(r);else if(r&&typeof r=="object")try{e.push(JSON.stringify(r))}catch{}return e.join(" ")}function I0(t){try{return Py(t)}catch{return}}function Wy(t,e){return{platform:process.platform,osRelease:Dy(),code:t.code,errno:t.errno,syscall:t.syscall,errPath:t.path,command:e.command,commandExists:Ly(e.command)?I0(e.command):void 0,cwd:e.cwd,cwdExists:I0(e.cwd),envKeys:e.envKeys}}function $y(t,e){return`${t.message} [diag: platform=${e.platform} os=${e.osRelease} code=${e.code} errno=${e.errno} syscall=${e.syscall} cmd=${Oy(e.command)} cmdExists=${e.commandExists} cwdExists=${e.cwdExists} envKeys=${e.envKeys}]`}var Lt=class{constructor(e){this.opts=e;this.log=G(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new xo({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Or;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stopReason;stderrRing=[];now=Date.now;spawnEnv={};sanitizeEnv(e){return e}async start(){if(this.child)throw new k("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=h0(process.env,this.opts.agentEnvFile??Q().agentEnvFile,this.opts.env,o=>this.sanitizeEnv(o));this.spawnEnv=r;let i=nt(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:e});this.child=i,x0(i.pid),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",o=>{try{for(let c of this.decoder.push(o))this.dispatch(c)}catch(c){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(c)})}}),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",o=>{let c=o.trimEnd();this.stderrRing.push(c),this.stderrRing.length>Ny&&this.stderrRing.shift(),this.log.debug("stderr",{text:c})}),i.stdin?.on("error",o=>{this.log.warn("child stdin error",{err:String(o)})}),i.stdout?.on("error",o=>{this.log.warn("child stdout error",{err:String(o)})}),i.stderr?.on("error",o=>{this.log.warn("child stderr error",{err:String(o)})}),i.on("exit",(o,c)=>{this.stopped=!0,p0(i.pid),(o!==0||c!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:o,signal:c,recentStderr:[...this.stderrRing]});try{for(let u of this.decoder.flush())this.dispatch(u)}catch(u){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(u)})}this.failAllPending(this.buildExitError(o,c));for(let u of this.exitHandlers)u(o,c)}),i.on("error",o=>{let c=o,d=Wy(c,{command:this.opts.command,cwd:this.opts.cwd,envKeys:Object.keys(r).length});this.log.error("child error",{err:String(o),diag:d}),this.failAllPending(new k("AGENT_SPAWN_FAILED",$y(c,d),{cause:d}))}),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.stopReason=e??"stopped",this.log.info("downstream stopping",{reason:e});let r=this.child,i=new Promise(c=>r.once("exit",()=>c()));Gi(r.pid,"SIGTERM");let o=setTimeout(()=>{r.killed||Gi(r.pid,"SIGKILL")},5e3);try{await i}finally{clearTimeout(o)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(e){return e===void 0?[...this.stderrRing]:this.stderrRing.slice(-e)}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,r){let i={firstUpdateMs:Gy,phase2GateMs:By,livenessWindowMs:Fy,absoluteMaxMs:zy,approvalMaxMs:Hy,suspendThresholdMs:Uy,...r};return this.call("session/prompt",e,v0,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Pr("session/cancel",e))}setSessionMode(e){return this.call("session/set_mode",e)}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Dr(e,r))}catch(i){this.log.warn("respondAgentRequest write failed",{id:e,err:String(i)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Sn(e,r))}catch(i){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(i)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,i=v0,o){if(!this.child||this.stopped)return Promise.reject(new k("AGENT_PROTOCOL_ERROR","downstream not started"));let c=this.idAllocator.next(e),d=Bi(c,e,r),u=(()=>{if(typeof r!="object"||r===null)return;let f=r.sessionId;return typeof f=="string"?f:void 0})();return new Promise((f,x)=>{let p={resolve:f,reject:x,timer:null,method:e,promptTimeout:null};if(o){let _=this.now(),v={cfg:o,startedAt:_,lastActivityAt:_,firstFrameSeen:!1,activeToolCalls:new Set,suspendedMs:0,armedAt:_,expectedIntervalMs:Nr(0,!1,o),sessionId:u};p.promptTimeout=v;let w=()=>{let E={startedAt:v.startedAt,lastActivityAt:v.lastActivityAt,firstFrameSeen:v.firstFrameSeen,hasActiveTool:v.activeToolCalls.size>0,awaitingApproval:this.inflightAgentRequests.size>0,suspendedMs:v.suspendedMs,armedAt:v.armedAt,expectedIntervalMs:v.expectedIntervalMs},I=this.now(),A=E0(E,v.cfg,I),T=D=>{v.armedAt=I,v.expectedIntervalMs=D,p.timer=setTimeout(w,D)};if(A.action==="suspend"){v.suspendedMs+=A.suspendedDeltaMs,v.lastActivityAt=I,this.log.warn("downstream prompt timer: suspend detected",{id:c,method:e,gapMs:A.suspendedDeltaMs,suspendedMs:v.suspendedMs,...v.sessionId?{sessionId:v.sessionId}:{}}),T(A.rearmMs);return}if(A.action==="continue"){T(A.rearmMs);return}this.pending.delete(c),A.action==="reject-backstop"?(this.log.warn("downstream prompt absolute timeout",{id:c,method:e,awaitingApproval:A.awaitingApproval,...v.sessionId?{sessionId:v.sessionId}:{}}),x(A.awaitingApproval?new k("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${v.cfg.approvalMaxMs}ms`):new k("AGENT_TIMEOUT",`${e} timed out after ${v.cfg.absoluteMaxMs}ms`))):(this.log.warn("downstream prompt idle timeout",{id:c,method:e,...v.sessionId?{sessionId:v.sessionId}:{}}),x(new k("AGENT_FRAME_IDLE_TIMEOUT",`${e} no progress within ${v.cfg.livenessWindowMs}ms`)))};p.timer=setTimeout(w,v.expectedIntervalMs)}else i>0&&Number.isFinite(i)&&(p.timer=setTimeout(()=>{this.pending.delete(c),this.log.warn("downstream call timeout",{id:c,method:e,timeoutMs:i}),x(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i));this.pending.set(c,p);try{this.writeFrame(d)}catch(_){p.timer&&clearTimeout(p.timer),this.pending.delete(c),x(_)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new k("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(l0(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(ho(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(this.wireErrorToBridge(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new k("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:qy(e.result)}),r.resolve(e.result));return}if(a0(e)){if(e.method==="session/update"){let r=e.params;for(let i of this.pending.values()){let o=i.promptTimeout;o&&(o.firstFrameSeen=!0,o.lastActivityAt=this.now(),this.trackToolCall(o,r))}for(let i of this.updateHandlers)try{Promise.resolve(i(r)).catch(o=>this.log.warn("update handler failed (async)",{err:String(o)}))}catch(o){this.log.warn("update handler threw sync, swallowed",{err:String(o)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(o0(e)){let r=e;try{this.handleAgentRequest(r).catch(i=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(i)}))}catch(i){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(i)})}}}trackToolCall(e,r){let i=r.update,o=i?.sessionUpdate;if(o!=="tool_call"&&o!=="tool_call_update")return;let c=typeof i.toolCallId=="string"?i.toolCallId:void 0;if(!c)return;let d=typeof i.status=="string"?i.status:void 0,u=d==="completed"||d==="failed"||d==="cancelled";o==="tool_call"&&!u?e.activeToolCalls.add(c):u&&e.activeToolCalls.delete(c)}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Sn(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(i){this.log.error("agentRequestHandler threw",{method:e.method,err:String(i)});try{this.writeFrame(Sn(e.id,zi(i)))}catch{}this.inflightAgentRequests.delete(e.id)}}wireErrorToBridge(e){let r=c0(e);if(r.code!=="AGENT_PROTOCOL_ERROR")return r;let i=b0(this.framework,jy(e));return i?new k(i.bridgeCode,i.message,{cause:{reason:i.reason,wireCode:e.code,wireMessage:e.message,wireData:e.data}}):r}buildExitError(e,r){if(this.stopReason!==void 0)return new k("AGENT_TURN_ABORTED",`turn aborted: ${this.stopReason}`,{cause:{reason:this.stopReason}});let i=this.getStderrTail(My).join(`
98
+ `),o=y0(this.framework,i);return o?new k(o.bridgeCode,o.message,{cause:{reason:o.reason,code:e,signal:r,stderrTail:i}}):new k("AGENT_PROTOCOL_ERROR",`agent exited (${e}/${r})`,{cause:{code:e,signal:r,stderrTail:i}})}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function Ky(t){let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=i));return e}var po=class extends Lt{framework="claude-code";constructor(e){let{command:r,args:i}=ni("claude-code",e.command,e.args??[]),o={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o)}sanitizeEnv(e){return Ky(e)}};sn();import{mkdtempSync as Yy,rmSync as Xy}from"node:fs";import{tmpdir as Qy}from"node:os";import{join as eb}from"node:path";import{readFileSync as k0}from"node:fs";import{homedir as Vy}from"node:os";import{join as A0}from"node:path";function T0(t){let e=t.CODEX_HOME?.trim()||A0(t.HOME?.trim()||Vy(),".codex");return A0(e,"config.toml")}function Zy(t){let e=null;for(let r=0;r<t.length;r++){let i=t[r];if(e)i===e&&(e=null);else if(i==='"'||i==="'")e=i;else if(i==="#")return t.slice(0,r)}return t}function Jy(t){let e=t.trim();if(e.length>=2){let r=e[0];if((r==='"'||r==="'")&&e[e.length-1]===r)return e.slice(1,-1)}return e}function R0(t){let e={},r={},i=e;for(let o of t.split(/\r?\n/)){let c=Zy(o).trim();if(!c)continue;let d=/^\[([^\]]+)\]$/.exec(c);if(d){let x=(d[1]??"").trim(),p=r[x]??{};r[x]=p,i=p;continue}let u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim();f&&(i[f]=Jy(c.slice(u+1)))}return{root:e,tables:r}}function C0(t){let e=t.root.model_provider;if(!e||e==="openai")return null;let r=t.tables[`model_providers.${e}`];return r?{providerId:e,baseUrl:r.base_url,envKey:r.env_key,bearerToken:r.experimental_bearer_token}:null}function P0(t){let e;try{e=k0(T0(t),"utf8")}catch{return null}return C0(R0(e))?.providerId??null}function D0(t){let e;try{e=k0(T0(t),"utf8")}catch{return null}let r=C0(R0(e));if(!r?.baseUrl)return null;let i=r.bearerToken||(r.envKey?t[r.envKey]?.trim():void 0);return i?{baseUrl:r.baseUrl,providerName:r.providerId,headers:{Authorization:`Bearer ${i}`}}:null}var go=class t extends Lt{framework="codex";authRequest;resolveLocalGatewayAuth;codexHomeDir;constructor(e){let r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,{command:o,args:c}=ni("codex",e.command,i),d=e.isolateCodexHome?Yy(eb(Qy(),"coze-bridge-codex-home-")):void 0,u=d?{...e.env??{},CODEX_HOME:d}:e.env,f={command:o,args:c,cwd:e.cwd,agentId:e.agentId,...u?{env:u}:{}};super(f),this.authRequest=e.authRequest,this.resolveLocalGatewayAuth=e.resolveLocalGatewayAuth??!1,this.codexHomeDir=d}async initialize(e){let r=await super.initialize(e),i=this.authRequest??this.localGatewayAuthRequest();return i&&await this.call("authenticate",i),r}localGatewayAuthRequest(){if(!this.resolveLocalGatewayAuth)return null;let e=D0(this.spawnEnv);return e?(this.log.info("codex local: \u7528 config.toml custom provider \u8D70 gateway \u8BA4\u8BC1",{providerName:e.providerName,baseUrl:e.baseUrl}),{methodId:"gateway",_meta:{gateway:e}}):null}static MODE_ID_MAP={"read-only":"read-only",auto:"agent","full-access":"agent-full-access"};setSessionMode(e){let r=t.MODE_ID_MAP[e.modeId]??e.modeId;return super.setSessionMode({...e,modeId:r})}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Xy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};qe();var tb=3e4,Mr=class extends Lt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",i=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&i.push("--token",e.gatewayToken);let o={command:e.command,args:i,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(o),this.agentId=e.agentId,this.sessionName=r,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.call("session/prompt",{sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},tb))}get acpSessionName(){return this.sessionName}setSessionMode(e){return Promise.reject(new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"))}};var O0=["default","acceptEdits","plan","auto","bypassPermissions"],L0=["read-only","auto","full-access"];function In(t,e){if(typeof e!="string")return!1;switch(t){case"claude-code":return O0.includes(e);case"codex":return L0.includes(e);case"openclaw":return!1}}function nd(t){switch(t){case"claude-code":return O0.join("/");case"codex":return L0.join("/");case"openclaw":return""}}an();qe();te();De();function rd(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}sn();var An=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((r,i)=>{this.slots.push({task:e,resolve:r,reject:i}),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}get isDisposed(){return this.disposed}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 r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var mo=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=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",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new An,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let i of this.sessionQueues.values())i.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,i]of this.sessions)Hi(i),i.downstream&&(r.push(i.downstream.stop(e).catch(()=>{})),i.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Hi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}function Vt(t){return t.deployType!=="local"?!1:t.framework==="claude-code"||t.framework==="codex"}Kt();te();import{constants as N0}from"node:fs";import{access as nb}from"node:fs/promises";import{delimiter as rb,join as ib}from"node:path";var vt=G("framework-detector"),M0={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},sb=[".exe",".cmd",".bat",".ps1"],Kn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??nt,access:e.access??nb}}async detect(e){let r=M0[e],i=await this.which(r);if(!i)return vt.debug("framework binary not found",{framework:e,bin:r}),null;let o=e==="openclaw"?["--log-level","silent"]:[],[c,d]=await Promise.all([this.probeVersion(i,o),e==="openclaw"?this.probeOpenclawDefaultAgent(i):Promise.resolve(null)]),u={path:i,version:c};return d&&(u.defaultAgent=d),u}async detectAll(){let e=await Promise.all(Object.keys(M0).map(async i=>[i,await this.detect(i)])),r={};for(let[i,o]of e)o&&(r[i]=o);return r}async which(e){let r=this.env.pathEnv.split(rb).filter(Boolean),i=this.env.platform==="win32"?["",...sb]:[""];for(let o of r)for(let c of i){let d=ib(o,e+c);if(await this.isExecutable(d))return d}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?N0.F_OK:N0.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return vt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return vt.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let i=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!i)return vt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let o=JSON.parse(i[0]);if(!Array.isArray(o))return vt.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let c=o.find(d=>d?.isDefault===!0);return c?!c.id||!c.workspace?(vt.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!c.id,hasWorkspace:!!c.workspace}),null):{id:c.id,workspace:c.workspace}:(vt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:o.length}),null)}catch(o){return vt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(o),matchHead:i[0].slice(0,200)}),null}}async probeOpenclawGateway(e){let r=await this.runProbe(e,["--log-level","silent","gateway","status","--json","--require-rpc","--timeout","5000"]);if(!r)return vt.warn("openclaw gateway probe: runProbe returned null (spawn err / timeout)",{path:e}),{reachable:!1};let i=r.code===0;i||vt.warn("openclaw gateway probe: non-zero exit (gateway unreachable)",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)});let o={reachable:i},c=r.stdout.match(/\{[\s\S]*\}/);if(c)try{let d=JSON.parse(c[0]);typeof d.gateway?.port=="number"&&(o.port=d.gateway.port),typeof d.service?.runtime?.status=="string"&&(o.runtime=d.service.runtime.status),!i&&typeof d.rpc?.error=="string"&&(o.detail=d.rpc.error)}catch(d){vt.warn("openclaw gateway probe: JSON.parse failed (detail omitted, gate by exit code)",{path:e,err:String(d)})}return o}async probeVersion(e,r=[]){let i=await this.runProbe(e,[...r,"--version"]);return i&&(ab(i.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(i=>{let o="",c=!1,d,u=f=>{c||(c=!0,d&&clearTimeout(d),i(f))};try{let f=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});d=setTimeout(()=>{f.kill("SIGKILL"),u(null)},15e3),f.stdout?.on("data",x=>{o+=x.toString("utf8")}),f.on("error",()=>u(null)),f.on("close",x=>u({code:x,stdout:o}))}catch{u(null)}})}},ob=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function ab(t){return t.replace(ob,"")}import{homedir as cb}from"node:os";import{join as db}from"node:path";an();Kt();ir();qe();te();async function z0(){let t=db(cb(),".openclaw/openclaw.json");return(await cr(t))?.gateway?.auth?.token??""}var B0=G("openclaw.config"),lb=[0,5e3,5e3],ub=Ke("COZE_BRIDGE_OPENCLAW_CLI_TIMEOUT_MS",15e3),F0="models.providers.",wo="agents.defaults.models",_o=class{command;env;retryDelaysMs;cliTimeoutMs;queue=new An;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??lb,this.cliTimeoutMs=e.cliTimeoutMs??ub}async withRetry(e,r){let i;for(let o=0;o<this.retryDelaysMs.length;o++){let c=this.retryDelaysMs[o]??0;c>0&&await new Promise(d=>setTimeout(d,c));try{return await r()}catch(d){i=d,B0.warn("openclaw cli failed, will retry",{label:e,attempt:o+1,err:String(d)})}}throw new k("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${i?.message??"unknown"}`)}runCli(e){return new Promise((r,i)=>{let o=nt(this.command,e,{stdio:["ignore","ignore","pipe"],env:this.env}),c="",d=!1,u=x=>{d||(d=!0,clearTimeout(f),x())};o.stderr?.on("data",x=>{c+=x.toString("utf8")});let f=setTimeout(()=>{u(()=>{o.kill("SIGTERM"),setTimeout(()=>o.kill("SIGKILL"),250).unref(),i(new Error(`timeout after ${this.cliTimeoutMs}ms: ${e.join(" ")}`))})},this.cliTimeoutMs);f.unref(),o.on("error",x=>u(()=>i(x))),o.on("close",x=>u(()=>{x===0?r():i(new Error(`exit ${x}: ${c.trim().slice(0,500)}`))}))})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(i){let o=String(i);if(r.some(c=>o.includes(c)))return;throw i}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(i){B0.warn(`${e} failed (best-effort)`,{configPath:r,err:String(i)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${F0}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${F0}${e}`)}addModelToAllowlist(e,r){let i={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${wo}[${e}]`,()=>this.runCli(["config","set",wo,JSON.stringify(i),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${wo}[${e}]`,`${wo}.${e}`)}ensureAgent(e,r,i){let o=["agents","add",e,"--workspace",r,"--non-interactive"];return i&&o.push("--model",i),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(o,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var de=G("agent-manager"),ad="bypassPermissions",H0="full-access",q0="full-access";function pb(t){switch(t){case"read-only":return"read-only";case"auto":return"agent";case"full-access":return"agent-full-access"}}var gb=(t,e,r,i,o,c,d,u,f,x)=>{switch(t){case"claude-code":{let p={...o?{...Hf(o),...Wf(o,d,u)}:{},...f??{},IS_SANDBOX:"1"};return new po({cwd:r,env:p,agentId:i})}case"codex":{let p=H0;x!==void 0&&(In("codex",x)?p=x:de.warn("codex spawn: invalid codexPermissionMode, falling back to full-access",{agentId:i,received:x}));let _=o?null:P0(process.env),v={...o?jf(o):{},INITIAL_AGENT_MODE:pb(p),...process.env.COZE_BRIDGE_CODEX_APP_SERVER_LOGS==="1"?{APP_SERVER_LOGS:od(r,"..","logs","codex-app-server")}:{},..._?{MODEL_PROVIDER:_}:{},...f??{}},w=o?qf(o,d,u):null,E=w?{methodId:"gateway",_meta:{gateway:w}}:void 0,I=!!o,A=!I&&process.env.COZE_BRIDGE_CODEX_LOCAL_GATEWAY_AUTH==="1";return new go({cwd:r,agentId:i,...Object.keys(v).length>0?{env:v}:{},...E?{authRequest:E}:{},...I?{isolateCodexHome:!0}:{},...A?{resolveLocalGatewayAuth:!0}:{}})}case"openclaw":return new Mr({command:e,cwd:r,agentId:i,...c?{sessionName:rd(c)}:{}})}};function sd(t){return t==="claude-code"||t==="codex"}function mb(t){let e=[],r=Object.keys(t).sort();for(let i of r){let o=t[i];o!==void 0&&(wb(o)||e.push(`${i}=${o}`))}return e.length===0?"":`${e.join(`
97
99
  `)}
98
- `}function Xy(t){if(t.includes(`
99
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var Qy={path:"",version:"cloud-deployed"},S0="openclaw_gateway_unavailable",eb="openclaw_default_agent_missing";function I0(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var tb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},nb=6e4,mo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??Jy,this.createTimeoutMs=e.createTimeoutMs??nb,this.detectorFactory=e.detectorFactory??(()=>new Wn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new go({command:r})),this.openclawConfigDir=e.openclawConfigDir??v0(Vy(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{le.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=v0(e,".env");if(await $y(r).then(c=>c.isFile()).catch(()=>!1)){le.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=Yy({...process.env,...Yc(this.paths.agentEnvFile)});await sn(r,o,{mode:384}),le.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),le.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new T("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new T("IPC_BAD_REQUEST","framework required");let i=await Ne(e.agentId,this.paths).catch(()=>null),o=no(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new T("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")le.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(C=>le.warn("dispose stale agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")le.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(C=>le.warn("dispose drifted agent failed (ignored)",{err:String(C)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){le.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let C=await Ne(e.agentId,this.paths).catch(()=>null);C&&(C.patToken=e.patToken,await Xe(C,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){le.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let C=await Ne(e.agentId,this.paths).catch(()=>null);C&&(C.modelInfo=e.modelInfo,await Xe(C,this.paths))}return le.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ye(e.agentId,this.paths),x=o?"cloud":"local",h=e.framework==="openclaw"&&x==="local",w;h&&!r?.revive&&(w=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=w??(h?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??_??u.workspace,y=new AbortController,E=setTimeout(()=>y.abort(new T("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&nd(e.framework)&&await sr(e.framework,y.signal);let C=()=>{if(y.signal.aborted)throw y.signal.reason instanceof Error?y.signal.reason:new T("AGENT_TIMEOUT","_agent/create aborted")};await td(u.root,{recursive:!0}),await td(v,{recursive:!0}),await td(u.logs,{recursive:!0}),C(),h||await cr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(x==="cloud"?await Ca(v,"cloud"):await Ca(v,"local",rd)),C();let P=i,b=Lf({model:e.model??P?.model}),k=Ef(e._meta)??P?.accountId,D=e.patToken??P?.patToken,z=x==="cloud"?e.modelInfo??P?.modelInfo:void 0;if(I=new ho({agentId:e.agentId,framework:e.framework,workspace:v,model:b.model??bt,deployType:x,...k?{accountId:k}:{},...D?{patToken:D}:{},...z?{modelInfo:z}:{}}),I.status="ok",P?.sessions){let V=x==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[J,ie]of Object.entries(P.sessions)){let oe={acpSessionId:ie.acpSessionId,modelToken:ie.modelToken,tokenGeneratedAt:ie.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};V?ie.permissionMode===void 0?(oe.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",le.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:J,framework:e.framework,fallback:oe.permissionMode})):Sn(e.framework,ie.permissionMode)?oe.permissionMode=ie.permissionMode:le.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:J,framework:e.framework,value:ie.permissionMode}):ie.permissionMode!==void 0&&le.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:J,framework:e.framework,deployType:x}),ie.cozeGroupId&&(oe.cozeGroupId=ie.cozeGroupId),I.sessions.set(J,oe)}let te=Object.keys(P.sessions).length;te>0&&le.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:te})}this.registry.register(I),A=!0;let M={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:P?.createdAt??Date.now(),sessions:P?.sessions??{},model:b.model};x==="cloud"&&(M.deployType="cloud"),k&&(M.accountId=k),D&&(M.patToken=D),z&&(M.modelInfo=z),P?.skills&&(M.skills=P.skills),P?.agentName&&(M.agentName=P.agentName),P?.description&&(M.description=P.description),e.framework==="openclaw"&&x==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):le.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Z=e.initialSkills??[];if(Z.length>0){let V=[...M.skills??[]],te=new Map(V.map((oe,O)=>[oe.skillId,O])),J=await Promise.allSettled(Z.map(oe=>Vc({agentId:e.agentId,workspace:v,framework:e.framework,skill:oe}))),ie=0;for(let[oe,O]of J.entries()){let q=Z[oe];q&&(O.status==="fulfilled"?(Zc(V,te,O.value),ie++):le.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:q.skillId,skillName:q.skillName,err:String(O.reason)}))}ie>0&&(M.skills=V,le.info("initialSkills installed",{agentId:e.agentId,installed:ie,requested:Z.length}))}return await Xe(M,this.paths),le.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:x}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(C){throw le.error("agent create failed, rolling back",{agentId:e.agentId,err:String(C)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await Ky(u.root,{recursive:!0,force:!0}).catch(P=>le.warn("rm agent dir failed (ignored)",{err:String(P)})),C instanceof T?C:new T("AGENT_SPAWN_FAILED",String(C),{cause:C})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&nd(e.framework))u=Qy;else throw new T("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);nd(e.framework)&&!cs(e.framework)&&(le.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await sr(e.framework));let x=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,h;if(e.framework==="openclaw")h=await this.buildOpenclawDownstream({session:e,modelConfig:x,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let w=e.sessions.get(i),_=$t(e)?w?.permissionMode??A0:"full-access";h=this.factory(e.framework,u.path,e.workspace,e.agentId,x,i,o,c,this.buildBinShimPathEnv(),_)}try{return await h.start(),await h.initialize(tb),h}catch(w){let _=h instanceof Ot?h.getStderrTail():[];throw _.length>0&&le.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:w instanceof T?w.code:"unknown",recentStderr:_}),await h.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,w)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new T("AGENT_ENV_NOT_READY",I0(o),{cause:{reason:S0}})}catch(o){le.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof T?i:new T("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};le.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return le.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new T("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:eb}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new T("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new T("AGENT_ENV_NOT_READY",I0(r),{cause:{reason:S0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:l,command:u}=e,x=ed(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Lr({command:u,cwd:v.workspace,agentId:v.id,sessionName:x})}let h=await E0(),w=i?Uf(i,c,l):null,_;if(w){let v=Hc(o),E=w.models[0]?.id??bt,I=`${v}/${E}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(v,w),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}_=I}return new Lr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:x,...h?{gatewayToken:h}:{},..._?{slashModelOnStart:_}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=Hc(i),c=`${o}/${e.model}`,l=!0;try{await r.removeProvider(o)}catch(u){l=!1,le.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){l=!1,le.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}l&&this.ensuredProviders.delete(c)}}};import{randomUUID as D0}from"node:crypto";import{promises as lb}from"node:fs";import{basename as O0}from"node:path";je();ne();import{promises as ib}from"node:fs";import{basename as sb}from"node:path";var C0=G("file-upload"),ob="/api/coze_claw/file/agent_upload",ab=6e4;async function R0(t,e={}){let i=`${io(oo(e.handshakeBase))}${ob}`,o=e.timeoutMs??ab,c=await ib.readFile(t.path),l=new FormData;l.append("agent_id",t.agentId),l.append("session_id",t.sessionId),l.append("file_name",t.name),l.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Ar(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},x=new AbortController,h=setTimeout(()=>x.abort(),o);C0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let w=await fetch(i,{method:"POST",headers:u,body:l,signal:x.signal}),_=w.headers.get("x-tt-logid")??"";if(!w.ok){let E=await w.text().catch(()=>"");throw new T("UPLOAD_FAILED",`upload HTTP ${w.status} logid=${_}: ${E.slice(0,200)}`)}let v=await w.json();if(v.code!==void 0&&v.code!==0)throw new T("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${_}`);let y=v.data?.file?.file_url;if(!y)throw new T("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(v).slice(0,200)}`);return C0.info("file upload ok",{uri:y,logid:_}),{uri:y}}catch(w){throw w instanceof T?w:w.name==="AbortError"?new T("UPLOAD_FAILED",`upload timeout (${o}ms) for ${sb(t.path)}`):new T("UPLOAD_FAILED",String(w),{cause:w})}finally{clearTimeout(h)}}je();ne();import{extname as cb}from"node:path";var db={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function k0(t){let e=cb(t).toLowerCase();return db[e]??"application/octet-stream"}Pe();var wo=G("agent-send"),P0=50*1024*1024;function L0(t,e,r){let i=t.get(e);if(!i)throw new T("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new T("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new T("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function N0(t,e,r,i,o,c){let u;for(let x=0;x<=2;x++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(h){u=h,x<2&&(wo.warn("sendAgentFileUpdate failed, retrying",{attempt:x+1,err:String(h)}),await new Promise(w=>setTimeout(w,5e3)))}throw new T("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function M0(t,e){let{session:r,runtime:i}=L0(e.core,t.agentId,t.sessionId);if(!await ti(t.path,r.workspace))throw new T("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await lb.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new T("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>P0)throw new T("FILE_TOO_LARGE",`${o.size} bytes > limit ${P0}`);let c=await k0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new T("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let l=t.name??O0(t.path),u;try{u=await R0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:l,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(h){throw wo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:h instanceof T?h.code:"UNKNOWN",message:h instanceof Error?h.message:String(h)}),h}let x={sessionUpdate:"agent_file",messageId:D0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:l,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await N0(e,r,i,t.sessionId,x,"agent file uploaded to cloud but sendAgentFileUpdate failed"),wo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:l,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function B0(t,e){let{session:r,runtime:i}=L0(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new T("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new T("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??O0(t.path),c={sessionUpdate:"group_file",messageId:D0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await N0(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),wo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function F0(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let l=r[c]??0,u=i[c]??0;if(l<u)return!0;if(l>u)return!1}return!1}rn();Kt();ne();var Lt=G("coze-cli-installer"),z0="@coze/cli@latest",ub="coze",U0="0.1.8",fb=5e3,xb=5e3,hb=9e4,H0=1e4,Ui=null,_o=!1;async function id(t,e={}){if(_o)return;if(Ui)return Ui;let r=e.exec??Tf;return Ui=(async()=>{try{let i=await pb(ub,r),o=!1;if(i){let l=await gb(r);if(l===void 0)Lt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(F0(l,U0))Lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:l,min:U0}),o=!0;else{Lt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:l}),_o=!0;return}}let c=o?"upgrade-only":"full";Lt.info("coze-cli install start",{package:z0,mode:c});try{await r("npm",["i","-g","--prefer-online",z0],{timeout:hb,maxBuffer:10*1024*1024}),Lt.info("coze-cli install ok")}catch(l){Lt.warn("coze-cli install failed (skip subsequent steps)",{err:String(l)});return}if(o){_o=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:H0}),Lt.info("coze config set xTTEnv ok",{env:t.env})}catch(l){Lt.warn("coze config set failed (continue to auth login)",{err:String(l)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:H0}),Lt.info("coze auth login ok")}catch(l){Lt.warn("coze auth login failed",{err:String(l)});return}_o=!0}finally{Ui=null}})(),Ui}async function pb(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:fb});return Aa(i)}catch{return}}async function gb(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:xb});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}on();Pe();var mb=10*6e4;function G0(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?mb:e}function yo(t){return or(t??Q().configFile)}function Hi(t,e){return ar(e??Q().configFile,t)}import{randomBytes as Bb}from"node:crypto";nr();je();ne();import{createReadStream as wb}from"node:fs";import{mkdir as _b,readFile as yb,realpath as bb,stat as Eb,writeFile as vb}from"node:fs/promises";import{basename as Sb,dirname as sd,isAbsolute as Ib,join as Ab,relative as Tb,resolve as q0,sep as Cb}from"node:path";import{createInterface as Rb}from"node:readline";var W0=G("fs-rpc"),Gi=qe("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function K0(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Gi)throw new T("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Gi} bytes`);let i=await V0(t.path,e);return await _b(sd(i),{recursive:!0}),await vb(i,t.content,"utf8"),W0.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function $0(t,e){let r=await V0(t.path,e),i=await Eb(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Gi&&!o)throw new T("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Gi} bytes`);let c;if(o&&i.size>Gi)c=await kb(r,t.line??1,t.limit);else{let l=await yb(r,"utf8");if(o){let u=l.split(`
100
- `),x=Math.max(0,(t.line??1)-1),h=typeof t.limit=="number"?x+t.limit:void 0;c=u.slice(x,h).join(`
101
- `)}else c=l}return W0.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function kb(t,e,r){let i=Rb({input:wb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,l=[],u=0;try{for await(let x of i)if(u>=o&&u<c&&l.push(x),u++,u>=c)break}finally{i.close()}return l.join(`
102
- `)}async function V0(t,e){if(typeof t!="string"||t.length===0)throw new T("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([j0(q0(e)),j0(q0(t))]),o=Tb(r,i);if(Pb(o,Cb,Ib(o)))throw new T("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Pb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function j0(t){let e=[],r=t;for(;r!==sd(r);)try{let i=await bb(r);return e.length?Ab(i,...e.reverse()):i}catch{e.push(Sb(r)),r=sd(r)}return t}ne();var Z0=G("prompt-multimodal"),J0=10*1024*1024,Db=15e3,Ob=6;async function Y0(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,l=t[c];l!==void 0&&(e[c]=await Lb(l))}}let o=Array.from({length:Math.min(Ob,t.length)},()=>i());return await Promise.all(o),e}function X0(t){return t.some(e=>e.type==="image")}async function Lb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ri(e.uri))return t;try{let{buf:r,contentType:i}=await Mb(e.uri),o=e.mimeType||Nb(i)||"application/octet-stream";return Z0.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:o}),{type:"image",data:r.toString("base64"),mimeType:o}}catch(r){return Z0.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Nb(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function Mb(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Db);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>J0)throw new Error(`image too large: ${o.byteLength} bytes (max ${J0})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}an();je();ne();var W=G("core"),Fb=3e4,zb=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Ub="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",Hb="\u5BA1\u6279\u5DF2\u8D85\u65F6",Gb=3e4,bo=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Pr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=G0(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,l)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:l}),zi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(vn(o,{code:ee.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(l=>W.debug("send error response to upstream failed (ignored)",{err:String(l)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:ee.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:ee.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new T("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(lo(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&zb.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,ee.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(kr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(kr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(kr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,ee.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(o){W.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(vn(r,Mi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new T("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new T("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new T("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new T("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let x=o.sessions.get(c);if(x?.pendingPermission){let h=r._meta?.cozeTriggerMsgId,w=ro(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,x,c,Ub,h,w)}}let l=Date.now(),u=!1;try{let x=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,x}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-l,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Sf(i);switch(r){case"session/new":{let c=qb();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,l=c.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=$t(e)?vf(i._meta):void 0;if(u!==void 0&&!Sn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${Qc(e.framework)}`);let x=await this.ensureRuntime(e,l);if(u!==void 0&&x.permissionMode===void 0&&(x.permissionMode=u,await this.persistSessionMapping(e)),x.replySeq=0,await this.ensureDownstream(e,l,x),!x.downstream||!x.acpSessionId)throw new T("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&x.permissionMode!==void 0&&x.permissionMode!==u){let v=x.permissionMode;x.permissionMode=u,await this.persistSessionMapping(e);try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(y){throw x.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),y}}let h=i._meta?.cozeTriggerMsgId;h?e.activeTriggers.set(x.acpSessionId,h):e.activeTriggers.delete(x.acpSessionId);let w=ro(i._meta);if(w?e.activeGroupIds.set(x.acpSessionId,w):e.activeGroupIds.delete(x.acpSessionId),w&&x.cozeGroupId!==w&&(x.cozeGroupId=w,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&X0(c.prompt))throw new T("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await Y0(c.prompt);try{let v=await x.downstream.sessionPrompt({...c,sessionId:x.acpSessionId,prompt:_});return x.lastActiveAt=Date.now(),v}catch(v){if(v instanceof T&&v.code==="AGENT_APPROVAL_TIMEOUT"){let y=x.pendingPermission;y&&(y.downstream.respondAgentRequest(y.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(y.upstreamId),x.pendingPermission=void 0);let E=x.acpSessionId,I=E?e.activeTriggers.get(E):void 0,A=E?e.activeGroupIds.get(E):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:l}),await this.synthesizePromptReply(e,x,l,Hb,I,A)}throw v}finally{if(e.activeTriggers.delete(x.acpSessionId),e.activeGroupIds.delete(x.acpSessionId),x.pendingPermission=void 0,x.reloadAfterTurn){x.reloadAfterTurn=!1;let v=x.downstream;v&&(x.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:l,acpId:x.acpSessionId}),v.stop("reload-after-turn").catch(y=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:l,err:String(y)})))}else x.downstream?.isAlive()&&this.armIdleTimer(e,l,x)}}case"session/cancel":{let l=o.sessionId;if(!l)throw new T("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(l);if(e.hasSessionQueue(l)){let x=e.getSessionQueue(l);x.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:l,queuedCount:x.size}),x.dispose(new T("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${l}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,l=c.sessionId,u=c.modeId,x=ro(i._meta);if(!l)throw new T("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!$t(e))throw e.framework==="openclaw"?new T("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new T("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!Sn(e.framework,u))throw new T("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${Qc(e.framework)}`);if(x)return await this.handleGroupSetMode(e,x,u);let h=e.sessions.get(l)??await this.ensureRuntime(e,l);if(h.permissionMode===u)return{};let w=h.permissionMode;if(h.permissionMode=u,await this.persistSessionMapping(e),h.downstream?.isAlive()&&h.acpSessionId)try{await h.downstream.setSessionMode({sessionId:h.acpSessionId,modeId:u})}catch(_){throw h.permissionMode=w,await this.persistSessionMapping(e).catch(()=>{}),_}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:l,modeId:u});return{}}default:throw new T("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[l,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:l,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let l of o)l.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let l of o){let u=l.runtime.downstream,x=l.runtime.acpSessionId;u?.isAlive()&&x&&c.push({downstream:u,acpSessionId:x,oldMode:l.oldMode,runtime:l.runtime})}for(let l of c)try{await l.downstream.setSessionMode({sessionId:l.acpSessionId,modeId:i})}catch(u){for(let x of o)x.runtime.permissionMode=x.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return $t(e)&&(c.permissionMode=e.framework==="claude-code"?rd:T0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(yt.GEN_MODEL_TOKEN,i,Gb);if(!o?.modelToken)throw new T("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof T&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new T("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(zi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new T("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,l=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(l>=o&&Date.now()-u<c)throw new T("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${l} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let x;try{x=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(h){throw i.spawnFailCount=l+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),h}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=x,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await x.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(h){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),i.acpSessionId=void 0;let w=await x.sessionNew({cwd:e.workspace});i.acpSessionId=w.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let h=await x.sessionNew({cwd:e.workspace});i.acpSessionId=h.sessionId,await this.persistSessionMapping(e)}}catch(h){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(h)}),await x.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,h}if(x.afterSessionEstablished&&i.acpSessionId&&await x.afterSessionEstablished(i.acpSessionId),$t(e)&&i.acpSessionId&&i.permissionMode)try{await x.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(h){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(h)})}}armIdleTimer(e,r,i){if(zi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let l=e.activeTriggers.get(r.acpSessionId);l&&(c.cozeTriggerMsgId=l);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Rr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,l){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),l&&(u.cozeGroupId=l),await this.upstream.send(Rr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(x=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(x)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(Kb(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let l=r.update;if(l&&typeof l=="object"&&l.sessionUpdate==="current_mode_update"&&$t(e)){let w=l.currentModeId;Sn(e.framework,w)&&c.permissionMode!==w?(c.permissionMode=w,this.persistSessionMapping(e).catch(_=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof w=="string"&&!Sn(e.framework,w)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:w})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},x=e.activeTriggers.get(i);x&&(u.cozeTriggerMsgId=x);let h=e.activeGroupIds.get(i);h&&(u.cozeGroupId=h),this.upstream.send(Rr("session/update",{...r,sessionId:o,_meta:u})).catch(w=>W.warn("forward update failed",{agentId:e.agentId,err:String(w)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:ee.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},l=await K0(c,o);r.respondAgentRequest(i.id,l)}else{let c=i.params??{},l=await $0(c,o);r.respondAgentRequest(i.id,l)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,Mi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,x=u?e.activeTriggers.get(u):void 0,h={cozeAgentId:e.agentId};x&&(h.cozeTriggerMsgId=x);let w=u?e.activeGroupIds.get(u):void 0;w&&(h.cozeGroupId=w);let _=u?this.reverseSessionId(e,u):void 0,v=_?e.sessions.get(_):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let y={...c,..._?{sessionId:_}:{},_meta:h};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(Li(o,"session/request_permission",y)).catch(E=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:ee.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&jb(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new co(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),l=e.get(c);if(l)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:l,key:c}}}sendRequest(e,r,i=Fb){let o=this.upstreamIds.next(e);return new Promise((c,l)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),l(new T("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:l,timer:u}),this.upstream.send(Li(o,e,r)).catch(x=>{let h=this.pendingBridge.get(o);h&&(clearTimeout(h.timer),this.pendingBridge.delete(o)),l(x)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&$t(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ni(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(vn(e,{code:r,message:i,data:{bridgeVersion:Cr}}))}};function qb(){return Bb(16).toString("hex")}function jb(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var Wb=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function Kb(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return Wb.some(c=>o.startsWith(c))}on();ne();Pe();import{randomBytes as $b}from"node:crypto";import{createServer as Vb}from"node:http";var Zb=1e6,Q0=G("ipc"),Eo=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Q()}async start(){this.token=$b(32).toString("hex");let e=Vb((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),Q0.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await sn(this.paths.portFile,String(this.port)),await sn(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){qi(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){qi(r,404,{error:"not found"});return}let l=null;if(e.method==="POST")try{l=await Jb(e)}catch(u){qi(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(l,e);qi(r,200,u??{ok:!0})}catch(u){Q0.error("IPC handler failed",{key:o,err:String(u)}),qi(r,500,{error:u instanceof Error?u.message:String(u)})}}};function qi(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function Jb(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>Zb)throw new Error("body too large");e.push(c)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var mv=zt(Zx(),1),wv=zt(Po(),1),_v=zt(Br(),1),yv=zt(gd(),1),bv=zt(_d(),1),Ev=zt(Id(),1),ih=zt(No(),1),vv=zt(rh(),1);var sh=ih.default;je();ne();var{FWS:zv}=gh(),Re=G("upstream.frontier"),wh="application/json",_h="none",Uv=15e3;function Hv(t){class e extends sh{constructor(i){super(i,Rf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Re.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(xl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let l=Buffer.from(c.slice(0,128)).toString("hex");Re.debug("WS raw frame out",{bytes:c.byteLength,headHex:l})}catch(c){Re.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var Xi=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Re.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:kf,...Ar(this.opts.ppeOverride)},r=Hv(e),i=Df(this.opts.urlOverride),o={url:i,ws:r,fpID:Cf,aID:so,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:wh,force:!0},payloadEncoding:{encoding:_h,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new zv(o),l=!1,u=null,x,h,w=new Promise((y,E)=>{x=y,h=E}),_=y=>{l||(l=!0,u&&(clearTimeout(u),u=null),y?h(y):x())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let y=this.openCount===1;Re.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:y,openCount:this.openCount}),y&&_();for(let E of this.connectHandlers)Promise.resolve(E({initial:y})).catch(I=>Re.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=y=>{this.opened=!1,Re.info("frontier closed",{code:y.code,reason:y.reason,willReconnect:y.willReconnect})},c.onerror=y=>{Re.warn("frontier error",{code:y.code,msg:y.message}),_(new T("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${y.code} msg=${y.message??""}`))},c.onmessage=y=>this.handleMessage(y),this.fws=c;let v=this.opts.openTimeoutMs??Uv;u=setTimeout(()=>{_(new T("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await w}catch(y){try{c.close(1e3,"open failed")}catch(E){Re.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,y}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Re.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Re.warn("frontier send refused: upstream not started",{method:i}),new T("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Re.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new T("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;yh(c)||Re.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:wh,payloadEncoding:_h})}catch(u){throw Re.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new T("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Re.debug("drop non-adapter frontier frame",{service:r});return}let i=jv(e);if(!i){Re.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Re.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(l){Re.warn("frontier message JSON parse failed",{err:String(l),head:i.slice(0,80)});return}let c=o;yh(c)||Re.info("frontier frame in",{logid:qv(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:Gv(i)}),Promise.resolve(this.handler(o)).catch(l=>Re.warn("frontier frame handler threw",{err:String(l)}))}};function yh(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var bh=2e3;function Gv(t){return t.length<=bh?t:`${t.slice(0,bh)}...<truncated, total ${t.length} chars>`}function qv(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function jv(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}ne();var Rd=G("upstream.switchable"),jo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Rd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Rd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Rd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}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.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};ne();var kd=G("upstream"),qr=class{handler=null;async start(){kd.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){kd.info("NoopUpstream stopped",{reason:e})}async send(e){kd.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)}};je();ne();on();ne();Pe();import{promises as Wv}from"node:fs";var Eh=G("pat-token-store");async function Wo(t=Q()){try{let r=(await Wv.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(Eh.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&Eh.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function Qi(t,e=Q()){if(!t)throw new Error("writePatToken: empty patToken");await sn(e.patTokenFile,t,{mode:384})}Pe();Pe();import{promises as Ko}from"node:fs";import{join as Kv}from"node:path";function $v(t,e){return`#!/bin/sh
100
+ `}function wb(t){if(t.includes(`
101
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var _b={path:"",version:"cloud-deployed"},U0="openclaw_gateway_unavailable",yb="openclaw_default_agent_missing";function G0(t){let e=[t.port!==void 0?`port=${t.port}`:"",t.runtime?`runtime=${t.runtime}`:"",t.detail??""].filter(Boolean).join(", ");return`openclaw gateway \u672A\u8FD0\u884C/\u4E0D\u53EF\u8FBE${e?` (${e})`:""}; \u8BF7\u542F\u52A8 openclaw gateway`}var bb={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},Eb=6e4,yo=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??gb,this.createTimeoutMs=e.createTimeoutMs??Eb,this.detectorFactory=e.detectorFactory??(()=>new Kn),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new _o({command:r})),this.openclawConfigDir=e.openclawConfigDir??od(xb(),".openclaw")}buildBinShimPathEnv(){let e=process.platform==="win32"?";":":";return{PATH:`${this.paths.binDir}${e}${process.env.PATH??""}`}}getOpenclawConfig(){if(!this.openclawConfigCache){let e=this.config.frameworksCache?.openclaw;if(!e?.path)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");this.openclawConfigCache=this.openclawConfigFactory(e.path)}return this.openclawConfigCache}bootstrapOpenclawEnvIfNeeded(){return this.openclawEnvBootstrapPromise?this.openclawEnvBootstrapPromise:(this.openclawEnvBootstrapPromise=this.doBootstrapOpenclawEnv().catch(e=>{de.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=od(e,".env");if(await hb(r).then(c=>c.isFile()).catch(()=>!1)){de.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}let o=mb({...process.env,...ed(this.paths.agentEnvFile)});await on(r,o,{mode:384}),de.info("openclaw .env bootstrapped",{envFile:r,bytes:o.length}),await this.getOpenclawConfig().restartGateway(),de.info("openclaw gateway restarted after env bootstrap")}async createAgent(e,r){if(!e.agentId)throw new k("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new k("IPC_BAD_REQUEST","framework required");let i=await ke(e.agentId,this.paths).catch(()=>null),o=io(e._meta)==="cloud"||i?.deployType==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let c=this.registry.get(e.agentId);if(c){if(c.framework!==e.framework)throw new k("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${c.framework})`);if(c.status==="error")de.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await c.dispose("rebuild after error").catch(T=>de.warn("dispose stale agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else if(o&&c.deployType!=="cloud")de.warn("existing agent deployType drifted to local, rebuilding as cloud",{agentId:e.agentId}),await c.dispose("rebuild after deployType drift").catch(T=>de.warn("dispose drifted agent failed (ignored)",{err:String(T)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==c.patToken){de.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),c.setPatToken(e.patToken);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.patToken=e.patToken,await Me(T,this.paths))}if(c.deployType==="cloud"&&e.modelInfo){de.info("updating agent modelInfo on re-create",{agentId:e.agentId}),c.setModelInfo(e.modelInfo);let T=await ke(e.agentId,this.paths).catch(()=>null);T&&(T.modelInfo=e.modelInfo,await Me(T,this.paths))}return de.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:c.agentId,workspace:c.workspace,framework:c.framework}}}if(!o&&!this.config.frameworksCache?.[e.framework])throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let u=Ve(e.agentId,this.paths),f=o?"cloud":"local",x=e.framework==="openclaw"&&f==="local",p;x&&!r?.revive&&(p=(await this.ensureOpenclawDefaultAgent()).workspace,await this.ensureOpenclawGatewayReachable());let _=p??(x?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0),v=e.workspace??_??u.workspace,w=new AbortController,E=setTimeout(()=>w.abort(new k("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),I,A=!1;try{o&&sd(e.framework)&&await ar(e.framework,w.signal);let T=()=>{if(w.signal.aborted)throw w.signal.reason instanceof Error?w.signal.reason:new k("AGENT_TIMEOUT","_agent/create aborted")};await id(u.root,{recursive:!0}),await id(v,{recursive:!0}),await id(u.logs,{recursive:!0}),T(),x||await lr(v,e.framework,e.cozeIdentity),e.framework==="claude-code"&&(f==="cloud"?await Ca(v,"cloud"):await Ca(v,"local",ad)),T();let D=i,y=Gf({model:e.model??D?.model}),C=Rf(e._meta)??D?.accountId,O=e.patToken??D?.patToken,M=f==="cloud"?e.modelInfo??D?.modelInfo:void 0;if(I=new mo({agentId:e.agentId,framework:e.framework,workspace:v,model:y.model??Et,deployType:f,...C?{accountId:C}:{},...O?{patToken:O}:{},...M?{modelInfo:M}:{}}),I.status="ok",D?.sessions){let K=f==="local"&&(e.framework==="claude-code"||e.framework==="codex");for(let[Y,ie]of Object.entries(D.sessions)){let se={acpSessionId:ie.acpSessionId,modelToken:ie.modelToken,tokenGeneratedAt:ie.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};K?ie.permissionMode===void 0?(se.permissionMode=e.framework==="claude-code"?"bypassPermissions":"full-access",de.info("autoRevive: legacy session (no permissionMode) \u2192 fallback to D80/D84 default",{agentId:e.agentId,cloudId:Y,framework:e.framework,fallback:se.permissionMode})):In(e.framework,ie.permissionMode)?se.permissionMode=ie.permissionMode:de.warn("autoRevive: dropping invalid persisted permissionMode",{agentId:e.agentId,cloudId:Y,framework:e.framework,value:ie.permissionMode}):ie.permissionMode!==void 0&&de.info("autoRevive: dropping persisted permissionMode (gate disabled)",{agentId:e.agentId,cloudId:Y,framework:e.framework,deployType:f}),ie.cozeGroupId&&(se.cozeGroupId=ie.cozeGroupId),I.sessions.set(Y,se)}let ne=Object.keys(D.sessions).length;ne>0&&de.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:ne})}this.registry.register(I),A=!0;let N={agentId:e.agentId,framework:e.framework,workspace:v,cozeIdentity:e.cozeIdentity,createdAt:D?.createdAt??Date.now(),sessions:D?.sessions??{},model:y.model};f==="cloud"&&(N.deployType="cloud"),C&&(N.accountId=C),O&&(N.patToken=O),M&&(N.modelInfo=M),D?.skills&&(N.skills=D.skills),D?.agentName&&(N.agentName=D.agentName),D?.description&&(N.description=D.description),N.skillsRefreshedForVersion=D?.skillsRefreshedForVersion??Ot,e.framework==="openclaw"&&f==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,v)):de.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let Z=e.initialSkills??[];if(Z.length>0){let K=[...N.skills??[]],ne=new Map(K.map((se,P)=>[se.skillId,P])),Y=await Promise.allSettled(Z.map(se=>lo({agentId:e.agentId,workspace:v,framework:e.framework,skill:se}))),ie=0;for(let[se,P]of Y.entries()){let U=Z[se];U&&(P.status==="fulfilled"?(uo(K,ne,P.value),ie++):de.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:U.skillId,skillName:U.skillName,err:String(P.reason)}))}ie>0&&(N.skills=K,de.info("initialSkills installed",{agentId:e.agentId,installed:ie,requested:Z.length}))}return await Me(N,this.paths),de.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:f}),{ok:!0,agentId:e.agentId,workspace:v,framework:e.framework}}catch(T){throw de.error("agent create failed, rolling back",{agentId:e.agentId,err:String(T)}),A&&I&&(await I.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await fb(u.root,{recursive:!0,force:!0}).catch(D=>de.warn("rm agent dir failed (ignored)",{err:String(D)})),T instanceof k?T:new k("AGENT_SPAWN_FAILED",String(T),{cause:T})}finally{clearTimeout(E)}}async spawnSessionDownstream(e,r,i,o,c){let u=this.config.frameworksCache?.[e.framework];if(!u)if(e.deployType==="cloud"&&sd(e.framework))u=_b;else throw new k("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);sd(e.framework)&&!us(e.framework)&&(de.info("spawn: resolving acp wrapper",{agentId:e.agentId,framework:e.framework}),await ar(e.framework));let f=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,x;if(e.framework==="openclaw")x=await this.buildOpenclawDownstream({session:e,modelConfig:f,cloudSessionId:i,cozeEnv:o,mockScenario:c,command:u.path});else{let p=e.sessions.get(i),_=Vt(e)?p?.permissionMode??H0:"full-access";x=this.factory(e.framework,u.path,e.workspace,e.agentId,f,i,o,c,this.buildBinShimPathEnv(),_)}try{return await x.start(),await x.initialize(bb),x}catch(p){let _=x instanceof Lt?x.getStderrTail():[];throw _.length>0&&de.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:p instanceof k?p.code:"unknown",recentStderr:_}),await x.stop("spawnSessionDownstream failed").catch(()=>{}),await this.resolveSpawnFailure(e,u.path,p)}}async resolveSpawnFailure(e,r,i){if(e.framework==="openclaw"&&e.deployType==="local"&&r)try{let o=await this.detectorFactory().probeOpenclawGateway(r);if(!o.reachable)return new k("AGENT_ENV_NOT_READY",G0(o),{cause:{reason:U0}})}catch(o){de.warn("openclaw gateway diagnose failed (ignored, fall through to original error)",{agentId:e.agentId,err:String(o)})}return i instanceof k?i:new k("AGENT_SPAWN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}async ensureOpenclawDefaultAgent(){let e=this.config.frameworksCache?.openclaw?.defaultAgent;if(e?.id&&e.workspace)return{id:e.id,workspace:e.workspace};de.warn("openclaw default agent stale or missing, attempting lazy re-detect");let r=await this.detectorFactory().detect("openclaw");if(r?.defaultAgent?.id&&r.defaultAgent.workspace)return de.info("openclaw lazy re-detect success",{agentId:r.defaultAgent.id,workspace:r.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=r,{id:r.defaultAgent.id,workspace:r.defaultAgent.workspace};throw new k("AGENT_ENV_NOT_READY","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent",{cause:{reason:yb}})}async ensureOpenclawGatewayReachable(){let e=this.config.frameworksCache?.openclaw?.path;if(!e)throw new k("AGENT_SPAWN_FAILED","openclaw binary not detected on this machine");let r=await this.detectorFactory().probeOpenclawGateway(e);if(!r.reachable)throw new k("AGENT_ENV_NOT_READY",G0(r),{cause:{reason:U0}})}async buildOpenclawDownstream(e){let{session:r,modelConfig:i,cloudSessionId:o,cozeEnv:c,mockScenario:d,command:u}=e,f=rd(o);if(r.deployType==="local"){let v=await this.ensureOpenclawDefaultAgent();return new Mr({command:u,cwd:v.workspace,agentId:v.id,sessionName:f})}let x=await z0(),p=i?$f(i,c,d):null,_;if(p){let v=qc(o),E=p.models[0]?.id??Et,I=`${v}/${E}`;if(!this.ensuredProviders.has(I)){let A=this.getOpenclawConfig();await A.ensureProvider(v,p),await A.addModelToAllowlist(I),this.ensuredProviders.add(I)}_=I}return new Mr({command:u,cwd:r.workspace,agentId:r.agentId,sessionName:f,...x?{gatewayToken:x}:{},..._?{slashModelOnStart:_}:{}})}async openclawRepair(e,r){let i=this.getOpenclawConfig();await i.deleteAgent(e),await i.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let i of e.sessions.keys()){let o=qc(i),c=`${o}/${e.model}`,d=!0;try{await r.removeProvider(o)}catch(u){d=!1,de.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:o,err:String(u)})}try{await r.removeModelFromAllowlist(c)}catch(u){d=!1,de.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:c,err:String(u)})}d&&this.ensuredProviders.delete(c)}}};import{randomUUID as V0}from"node:crypto";import{promises as Rb}from"node:fs";import{basename as Z0}from"node:path";qe();te();import{promises as vb}from"node:fs";import{basename as Sb}from"node:path";var j0=G("file-upload"),Ib="/api/coze_claw/file/agent_upload",Ab=6e4;async function W0(t,e={}){let i=`${Tr(Rr(e.handshakeBase))}${Ib}`,o=e.timeoutMs??Ab,c=await vb.readFile(t.path),d=new FormData;d.append("agent_id",t.agentId),d.append("session_id",t.sessionId),d.append("file_name",t.name),d.append("file_content",new Blob([c],{type:t.mimeType}),t.name);let u={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...En(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},f=new AbortController,x=setTimeout(()=>f.abort(),o);j0.info("file upload start",{url:i,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let p=await fetch(i,{method:"POST",headers:u,body:d,signal:f.signal}),_=p.headers.get("x-tt-logid")??"";if(!p.ok){let E=await p.text().catch(()=>"");throw new k("UPLOAD_FAILED",`upload HTTP ${p.status} logid=${_}: ${E.slice(0,200)}`)}let v=await p.json();if(v.code!==void 0&&v.code!==0)throw new k("UPLOAD_FAILED",`upload code=${v.code} msg=${v.msg??"-"} logid=${_}`);let w=v.data?.file?.file_url;if(!w)throw new k("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${_}: ${JSON.stringify(v).slice(0,200)}`);return j0.info("file upload ok",{uri:w,logid:_}),{uri:w}}catch(p){throw p instanceof k?p:p.name==="AbortError"?new k("UPLOAD_FAILED",`upload timeout (${o}ms) for ${Sb(t.path)}`):new k("UPLOAD_FAILED",String(p),{cause:p})}finally{clearTimeout(x)}}qe();te();import{extname as kb}from"node:path";var Tb={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".heic":"image/heic",".heif":"image/heif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".json":"application/json",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".html":"text/html",".htm":"text/html",".xml":"application/xml",".log":"text/plain",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".tgz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm"};async function $0(t){let e=kb(t).toLowerCase();return Tb[e]??"application/octet-stream"}De();var bo=G("agent-send"),K0=50*1024*1024;function J0(t,e,r){let i=t.get(e);if(!i)throw new k("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new k("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let o=i.sessions.get(r);if(!o)throw new k("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:i,runtime:o}}async function Y0(t,e,r,i,o,c){let u;for(let f=0;f<=2;f++)try{await t.core.sendAgentFileUpdate(e,r,i,o);return}catch(x){u=x,f<2&&(bo.warn("sendAgentFileUpdate failed, retrying",{attempt:f+1,err:String(x)}),await new Promise(p=>setTimeout(p,5e3)))}throw new k("UPSTREAM_NOT_READY",`${c} after 3 attempts: ${String(u)}`,{cause:u})}async function X0(t,e){let{session:r,runtime:i}=J0(e.core,t.agentId,t.sessionId);if(!await ri(t.path,r.workspace))throw new k("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let o=await Rb.stat(t.path).catch(()=>null);if(!o||!o.isFile())throw new k("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(o.size>K0)throw new k("FILE_TOO_LARGE",`${o.size} bytes > limit ${K0}`);let c=await $0(t.path);if(t.kind==="image"&&!c.startsWith("image/"))throw new k("UNSUPPORTED_MIME",`kind=image but mime=${c}`);if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let d=t.name??Z0(t.path),u;try{u=await W0({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:c,name:d,sizeBytes:o.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(x){throw bo.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:o.size,mime:c,code:x instanceof k?x.code:"UNKNOWN",message:x instanceof Error?x.message:String(x)}),x}let f={sessionUpdate:"agent_file",messageId:V0(),content:{type:t.kind==="image"?"image":"resource",uri:u.uri,mimeType:c,name:d,sizeBytes:o.size,...u.fileId!==void 0?{fileId:u.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await Y0(e,r,i,t.sessionId,f,"agent file uploaded to cloud but sendAgentFileUpdate failed"),bo.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:d,bytes:o.size,mime:c,uri:u.uri}),{ok:!0,uri:u.uri,bytes:o.size,mimeType:c,...u.fileId!==void 0?{fileId:u.fileId}:{}}}async function Q0(t,e){let{session:r,runtime:i}=J0(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new k("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new k("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??Z0(t.path),c={sessionUpdate:"group_file",messageId:V0(),content:{uri:t.path,name:o,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Y0(e,r,i,t.sessionId,c,"agent group file sendAgentFileUpdate failed"),bo.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:o,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function eh(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number),o=Math.max(r.length,i.length);for(let c=0;c<o;c++){let d=r[c]??0,u=i[c]??0;if(d<u)return!0;if(d>u)return!1}return!1}sn();Kt();te();var Nt=G("coze-cli-installer"),th="@coze/cli@latest",Cb="coze",nh="0.1.8",Pb=5e3,Db=5e3,Ob=9e4,rh=1e4,qi=null,Eo=!1;async function dd(t,e={}){if(Eo)return;if(qi)return qi;let r=e.exec??Lf;return qi=(async()=>{try{let i=await Lb(Cb,r),o=!1;if(i){let d=await Nb(r);if(d===void 0)Nt.warn("coze-cli found but version unparseable, fall through to full install",{path:i});else if(eh(d,nh))Nt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:i,version:d,min:nh}),o=!0;else{Nt.info("coze-cli already on PATH with sufficient version, skip",{path:i,version:d}),Eo=!0;return}}let c=o?"upgrade-only":"full";Nt.info("coze-cli install start",{package:th,mode:c});try{await r("npm",["i","-g","--prefer-online",th],{timeout:Ob,maxBuffer:10*1024*1024}),Nt.info("coze-cli install ok")}catch(d){Nt.warn("coze-cli install failed (skip subsequent steps)",{err:String(d)});return}if(o){Eo=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:rh}),Nt.info("coze config set xTTEnv ok",{env:t.env})}catch(d){Nt.warn("coze config set failed (continue to auth login)",{err:String(d)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:rh}),Nt.info("coze auth login ok")}catch(d){Nt.warn("coze auth login failed",{err:String(d)});return}Eo=!0}finally{qi=null}})(),qi}async function Lb(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:i}=await e(r,[t],{timeout:Pb});return Ta(i)}catch{return}}async function Nb(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:Db});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}an();De();var Mb=10*6e4;function ih(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Mb:e}function vo(t){return cr(t??Q().configFile)}function ji(t,e){return dr(e??Q().configFile,t)}import{randomBytes as nE}from"node:crypto";ir();qe();te();import{createReadStream as Bb}from"node:fs";import{mkdir as Fb,readFile as zb,realpath as Ub,stat as Gb,writeFile as Hb}from"node:fs/promises";import{basename as qb,dirname as ld,isAbsolute as jb,join as Wb,relative as $b,resolve as sh,sep as Kb}from"node:path";import{createInterface as Vb}from"node:readline";var ah=G("fs-rpc"),Wi=Ke("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function ch(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Wi)throw new k("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Wi} bytes`);let i=await lh(t.path,e);return await Fb(ld(i),{recursive:!0}),await Hb(i,t.content,"utf8"),ah.info("fs/write_text_file ok",{path:i,size:t.content.length}),null}async function dh(t,e){let r=await lh(t.path,e),i=await Gb(r),o=typeof t.line=="number"||typeof t.limit=="number";if(i.size>Wi&&!o)throw new k("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${i.size} bytes > ${Wi} bytes`);let c;if(o&&i.size>Wi)c=await Zb(r,t.line??1,t.limit);else{let d=await zb(r,"utf8");if(o){let u=d.split(`
102
+ `),f=Math.max(0,(t.line??1)-1),x=typeof t.limit=="number"?f+t.limit:void 0;c=u.slice(f,x).join(`
103
+ `)}else c=d}return ah.info("fs/read_text_file ok",{path:r,size:c.length}),{content:c}}async function Zb(t,e,r){let i=Vb({input:Bb(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),o=Math.max(0,e-1),c=typeof r=="number"?o+r:Number.POSITIVE_INFINITY,d=[],u=0;try{for await(let f of i)if(u>=o&&u<c&&d.push(f),u++,u>=c)break}finally{i.close()}return d.join(`
104
+ `)}async function lh(t,e){if(typeof t!="string"||t.length===0)throw new k("IPC_BAD_REQUEST","path must be a non-empty string");let[r,i]=await Promise.all([oh(sh(e)),oh(sh(t))]),o=$b(r,i);if(Jb(o,Kb,jb(o)))throw new k("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return i}function Jb(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function oh(t){let e=[],r=t;for(;r!==ld(r);)try{let i=await Ub(r);return e.length?Wb(i,...e.reverse()):i}catch{e.push(qb(r)),r=ld(r)}return t}te();var uh=G("prompt-multimodal"),fh=10*1024*1024,Yb=15e3,Xb=6;async function hh(t){let e=new Array(t.length),r=0;async function i(){for(;r<t.length;){let c=r++,d=t[c];d!==void 0&&(e[c]=await Qb(d))}}let o=Array.from({length:Math.min(Xb,t.length)},()=>i());return await Promise.all(o),e}function xh(t){return t.some(e=>e.type==="image")}async function Qb(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Di(e.uri))return t;try{let{buf:r,contentType:i}=await tE(e.uri),o=e.mimeType||eE(i)||"application/octet-stream";return uh.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:o}),{type:"image",data:r.toString("base64"),mimeType:o}}catch(r){return uh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function eE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function tE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Yb);try{let i=await fetch(t,{signal:e.signal});if(!i.ok)throw new Error(`HTTP ${i.status} ${i.statusText}`);let o=await i.arrayBuffer();if(o.byteLength>fh)throw new Error(`image too large: ${o.byteLength} bytes (max ${fh})`);return{buf:Buffer.from(o),contentType:i.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}cn();qe();te();var W=G("core"),rE=3e4,iE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,sE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",oE="\u5BA1\u6279\u5DF2\u8D85\u65F6",aE=3e4,So=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Or;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=ih(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),W.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){W.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}async reloadAgents(e){let r=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let i of r)await this.agents.get(i)?.killAllRuntimes("reload");return r}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),W.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(i){W.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(i)})}}onAgentRegister(e){return this.registerHandlers.add(e),()=>this.registerHandlers.delete(e)}registerHandlers=new Set;unregister(e){this.agents.delete(e)}reviveIfDisconnected(e){this.disconnectedAgents.delete(e)&&W.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,i){let o=i.downstream;o&&(o.onUpdate(c=>{i.loadingSession||this.forwardUpdate(e,c)}),o.onAgentRequest(c=>{this.handleAgentRequest(e,o,c)}),o.onExit((c,d)=>{W.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:c,signal:d}),Hi(i),i.downstream=void 0,i.replySeq=0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),this.rejectPendingForDownstream(o,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let i=[];for(let[o,c]of this.pendingUpstream)c.downstream===e&&i.push(o);if(i.length!==0){W.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:i.length});for(let o of i){let c=this.pendingUpstream.get(o);if(c){this.pendingUpstream.delete(o),this.upstream.send(Sn(o,{code:J.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(d=>W.debug("send error response to upstream failed (ignored)",{err:String(d)}));try{c.downstream.respondAgentRequestError(c.agentRequestId,{code:J.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){W.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,i]of this.pendingUpstream){try{i.downstream.respondAgentRequestError(i.agentRequestId,{code:J.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(i)}this.pendingUpstream.clear();for(let[,i]of this.pendingBridge)clearTimeout(i.timer),i.reject(new k("UPSTREAM_DISCONNECTED",`${i.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(ho(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,i=e.params?._meta?.cozeEnv;i&&iE.test(i)?this.currentCozeEnv=i:i&&W.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:i});try{if(e.method.startsWith("_agent/")){let o=this.extensions[e.method];if(!o){r!==null?await this.sendError(r,J.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):W.warn("drop notification: extension not registered",{method:e.method});return}let c=await o(e,this);r!==null&&await this.upstream.send(Dr(r,c));return}if(e.method.startsWith("session/")){let o=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Dr(r,o));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Dr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,J.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):W.warn("drop unknown notification",{method:e.method})}catch(o){W.error("handleFrame failed",{method:e.method,err:String(o)}),r!==null&&await this.upstream.send(Sn(r,zi(o)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new k("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,i=r._meta?.cozeAgentId;if(!i)throw new k("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let o=this.agents.get(i);if(!o)throw this.disconnectedAgents.has(i)?new k("AGENT_DISCONNECTED",`agent ${i} has been disconnected; cloud must _agent/create to revive`):new k("AGENT_NOT_FOUND",`agent not found: ${i}`);let c=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||e.method==="session/set_mode"||!c)return this.dispatchSessionCall(o,e.method,r);if(e.method==="session/prompt"){let f=o.sessions.get(c);if(f?.pendingPermission){let x=r._meta?.cozeTriggerMsgId,p=so(r._meta);return W.info("session in pendingPermission, bouncing new prompt",{agentId:o.agentId,cloudSessionId:c}),this.synthesizePromptReply(o,f,c,sE,x,p)}}let d=Date.now(),u=!1;try{let f=await o.getSessionQueue(c).enqueue(()=>this.dispatchSessionCall(o,e.method,r));return u=!0,f}finally{W.info("session call done",{agentId:o.agentId,method:e.method,durationMs:Date.now()-d,ok:u})}}async dispatchSessionCall(e,r,i){e.lastActiveAt=Date.now();let{stripped:o}=Pf(i);switch(r){case"session/new":{let c=cE();return W.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:c}),{sessionId:c}}case"session/load":{let c=o;return W.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:c.sessionId}),{}}case"session/prompt":{let c=o,d=c.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/prompt: missing sessionId");let u=Vt(e)?Cf(i._meta):void 0;if(u!==void 0&&!In(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported permissionMode for ${e.framework}: ${u}; allowed: ${nd(e.framework)}`);let f=await this.ensureRuntime(e,d);if(u!==void 0&&f.permissionMode===void 0&&(f.permissionMode=u,await this.persistSessionMapping(e)),f.replySeq=0,await this.ensureDownstream(e,d,f),!f.downstream||!f.acpSessionId)throw new k("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");if(u!==void 0&&f.permissionMode!==void 0&&f.permissionMode!==u){let v=f.permissionMode;f.permissionMode=u,await this.persistSessionMapping(e);try{await f.downstream.setSessionMode({sessionId:f.acpSessionId,modeId:u})}catch(w){throw f.permissionMode=v,await this.persistSessionMapping(e).catch(()=>{}),w}}let x=i._meta?.cozeTriggerMsgId;x?e.activeTriggers.set(f.acpSessionId,x):e.activeTriggers.delete(f.acpSessionId);let p=so(i._meta);if(p?e.activeGroupIds.set(f.acpSessionId,p):e.activeGroupIds.delete(f.acpSessionId),p&&f.cozeGroupId!==p&&(f.cozeGroupId=p,await this.persistSessionMapping(e)),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&xh(c.prompt))throw new k("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let _=await hh(c.prompt);try{let v=await f.downstream.sessionPrompt({...c,sessionId:f.acpSessionId,prompt:_});return f.lastActiveAt=Date.now(),v}catch(v){if(v instanceof k&&v.code==="AGENT_APPROVAL_TIMEOUT"){let w=f.pendingPermission;w&&(w.downstream.respondAgentRequest(w.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(w.upstreamId),f.pendingPermission=void 0);let E=f.acpSessionId,I=E?e.activeTriggers.get(E):void 0,A=E?e.activeGroupIds.get(E):void 0;return W.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:d}),await this.synthesizePromptReply(e,f,d,oE,I,A)}throw v}finally{if(e.activeTriggers.delete(f.acpSessionId),e.activeGroupIds.delete(f.acpSessionId),f.pendingPermission=void 0,f.reloadAfterTurn){f.reloadAfterTurn=!1;let v=f.downstream;v&&(f.downstream=void 0,W.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:d,acpId:f.acpSessionId}),v.stop("reload-after-turn").catch(w=>W.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:d,err:String(w)})))}else f.downstream?.isAlive()&&this.armIdleTimer(e,d,f)}}case"session/cancel":{let d=o.sessionId;if(!d)throw new k("IPC_BAD_REQUEST","session/cancel: missing sessionId");let u=e.sessions.get(d);if(e.hasSessionQueue(d)){let f=e.getSessionQueue(d);f.size>0&&(W.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:d,queuedCount:f.size}),f.dispose(new k("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${d}`)))}return u?.downstream?.isAlive()&&u.acpSessionId&&await u.downstream.sessionCancel({sessionId:u.acpSessionId}),{ok:!0}}case"session/set_mode":{let c=o,d=c.sessionId,u=c.modeId,f=so(i._meta);if(!d)throw new k("IPC_BAD_REQUEST","session/set_mode: missing sessionId");if(!Vt(e))throw e.framework==="openclaw"?new k("METHOD_NOT_FOUND","session/set_mode not supported on openclaw"):new k("OPERATION_NOT_ALLOWED_FOR_CLOUD","session/set_mode is local-deploy only in this iteration");if(!In(e.framework,u))throw new k("IPC_BAD_REQUEST",`unsupported modeId for ${e.framework}: ${String(u)}; allowed: ${nd(e.framework)}`);if(f)return await this.handleGroupSetMode(e,f,u);let x=e.sessions.get(d)??await this.ensureRuntime(e,d);if(x.permissionMode===u)return{};let p=x.permissionMode;if(x.permissionMode=u,await this.persistSessionMapping(e),x.downstream?.isAlive()&&x.acpSessionId)try{await x.downstream.setSessionMode({sessionId:x.acpSessionId,modeId:u})}catch(_){throw x.permissionMode=p,await this.persistSessionMapping(e).catch(()=>{}),_}else W.info("session/set_mode: runtime not active, persisted only",{framework:e.framework,agentId:e.agentId,cloudId:d,modeId:u});return{}}default:throw new k("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async handleGroupSetMode(e,r,i){let o=[];for(let[d,u]of e.sessions)u.cozeGroupId===r&&u.permissionMode!==i&&o.push({cloudId:d,runtime:u,oldMode:u.permissionMode});if(o.length===0)return W.info("group session/set_mode: no active runtime (db-only path)",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i}),{};W.info("group session/set_mode: applying to runtimes",{framework:e.framework,agentId:e.agentId,groupId:r,modeId:i,targets:o.length});for(let d of o)d.runtime.permissionMode=i;await this.persistSessionMapping(e);let c=[];for(let d of o){let u=d.runtime.downstream,f=d.runtime.acpSessionId;u?.isAlive()&&f&&c.push({downstream:u,acpSessionId:f,oldMode:d.oldMode,runtime:d.runtime})}for(let d of c)try{await d.downstream.setSessionMode({sessionId:d.acpSessionId,modeId:i})}catch(u){for(let f of o)f.runtime.permissionMode=f.oldMode;throw await this.persistSessionMapping(e).catch(()=>{}),u}return{}}async ensureRuntime(e,r){let i=e.sessions.get(r);if(i)return i;let c={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return Vt(e)&&(c.permissionMode=e.framework==="claude-code"?ad:q0),e.sessions.set(r,c),await this.persistSessionMapping(e),c}async requestSessionToken(e,r){let i={sessionId:r,_meta:{cozeAgentId:e}};try{let o=await this.sendRequest(ft.GEN_MODEL_TOKEN,i,aE);if(!o?.modelToken)throw new k("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return o.modelToken}catch(o){throw o instanceof k&&o.code==="MODEL_TOKEN_GEN_FAILED"?o:new k("MODEL_TOKEN_GEN_FAILED",o instanceof Error?o.message:String(o),{cause:o})}}async ensureDownstream(e,r,i){if(Hi(i),i.downstream?.isAlive())return;if(!this.sessionSpawner)throw new k("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let o=3,c=3e4,d=i.spawnFailCount??0,u=i.spawnFailedAt??0;if(d>=o&&Date.now()-u<c)throw new k("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${d} times in a row; please check framework binary / network and retry after ${Math.ceil((c-(Date.now()-u))/1e3)}s`);let f;try{f=await this.sessionSpawner(e,i.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(x){throw i.spawnFailCount=d+1,i.spawnFailedAt=Date.now(),i.spawnFailCount>=o&&i.acpSessionId&&(W.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:i.acpSessionId}),i.acpSessionId=void 0),x}i.spawnFailCount=0,i.spawnFailedAt=void 0,i.downstream=f,this.attachRuntimeHooks(e,r,i);try{if(i.acpSessionId){i.loadingSession=!0;try{await f.sessionLoad({sessionId:i.acpSessionId,cwd:e.workspace}),W.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId})}catch(x){W.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),i.acpSessionId=void 0;let p=await f.sessionNew({cwd:e.workspace});i.acpSessionId=p.sessionId,await this.persistSessionMapping(e)}finally{i.loadingSession=!1}}else{let x=await f.sessionNew({cwd:e.workspace});i.acpSessionId=x.sessionId,await this.persistSessionMapping(e)}}catch(x){throw W.warn("session init failed after spawn, tearing down half-spawned runtime",{agentId:e.agentId,cloudId:r,acpId:i.acpSessionId,err:String(x)}),await f.stop("session-init-failed").catch(()=>{}),i.downstream=void 0,i.acpSessionId=void 0,x}if(f.afterSessionEstablished&&i.acpSessionId&&await f.afterSessionEstablished(i.acpSessionId),Vt(e)&&i.acpSessionId&&i.permissionMode)try{await f.setSessionMode({sessionId:i.acpSessionId,modeId:i.permissionMode})}catch(x){W.warn("post-spawn set_mode failed, framework using its own startup default",{framework:e.framework,agentId:e.agentId,cloudId:r,mode:i.permissionMode,err:String(x)})}}armIdleTimer(e,r,i){if(Hi(i),this.isRuntimeBusy(e,i)){W.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}i.idleTimer=setTimeout(()=>{if(i.idleTimer=void 0,this.isRuntimeBusy(e,i)){W.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,i);return}W.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let o=i.downstream;i.downstream=void 0,i.acpSessionId&&e.activeTriggers.delete(i.acpSessionId),o&&o.stop("idle timeout").catch(c=>W.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(c)}))},this.sessionIdleTimeoutMs),i.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let i=r.downstream;if(!i)return!1;for(let o of this.pendingUpstream.values())if(o.downstream===i)return!0;return!1}async sendAgentFileUpdate(e,r,i,o){let c={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let d=e.activeTriggers.get(r.acpSessionId);d&&(c.cozeTriggerMsgId=d);let u=e.activeGroupIds.get(r.acpSessionId);u&&(c.cozeGroupId=u)}await this.upstream.send(Pr("session/update",{sessionId:i,update:o,_meta:c}))}async synthesizePromptReply(e,r,i,o,c,d){let u={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};return c&&(u.cozeTriggerMsgId=c),d&&(u.cozeGroupId=d),await this.upstream.send(Pr("session/update",{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}},_meta:u})).catch(f=>W.warn("synthesizePromptReply update send failed (ignored)",{err:String(f)})),{stopReason:"end_turn"}}forwardUpdate(e,r){let i=r.sessionId,o=this.reverseSessionId(e,i);if(!o){W.debug("drop update for unknown session",{agentId:e.agentId,acpId:i});return}let c=e.sessions.get(o);if(!c){W.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:o});return}if(uE(r)){W.debug("drop codex noise chunk",{agentId:e.agentId,acpId:i});return}let d=r.update;if(d&&typeof d=="object"&&d.sessionUpdate==="current_mode_update"&&Vt(e)){let p=d.currentModeId;In(e.framework,p)&&c.permissionMode!==p?(c.permissionMode=p,this.persistSessionMapping(e).catch(_=>W.warn("persist mode (from current_mode_update) failed",{framework:e.framework,agentId:e.agentId,err:String(_)}))):typeof p=="string"&&!In(e.framework,p)&&W.warn("current_mode_update with invalid modeId for framework, not persisting",{framework:e.framework,agentId:e.agentId,modeId:p})}let u={cozeAgentId:e.agentId,cozeReplySeqID:++c.replySeq},f=e.activeTriggers.get(i);f&&(u.cozeTriggerMsgId=f);let x=e.activeGroupIds.get(i);x&&(u.cozeGroupId=x),this.upstream.send(Pr("session/update",{...r,sessionId:o,_meta:u})).catch(p=>W.warn("forward update failed",{agentId:e.agentId,err:String(p)}))}handleAgentRequest(e,r,i){if(i.method==="session/request_permission"){this.forwardPermissionRequest(e,r,i);return}if(i.method==="fs/write_text_file"||i.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,i);return}W.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:i.method}),r.respondAgentRequestError(i.id,{code:J.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${i.method}`})}async handleFsRpcRequest(e,r,i){try{let o=e.workspace;if(i.method==="fs/write_text_file"){let c=i.params??{},d=await ch(c,o);r.respondAgentRequest(i.id,d)}else{let c=i.params??{},d=await dh(c,o);r.respondAgentRequest(i.id,d)}}catch(o){W.warn("fs rpc handler failed",{agentId:e.agentId,method:i.method,err:String(o)}),r.respondAgentRequestError(i.id,zi(o))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let r=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);r&&(r.pendingPermission=void 0)}forwardPermissionRequest(e,r,i){let o=this.upstreamIds.next("session/request_permission"),c=i.params??{},u=c.sessionId,f=u?e.activeTriggers.get(u):void 0,x={cozeAgentId:e.agentId};f&&(x.cozeTriggerMsgId=f);let p=u?e.activeGroupIds.get(u):void 0;p&&(x.cozeGroupId=p);let _=u?this.reverseSessionId(e,u):void 0,v=_?e.sessions.get(_):void 0;v&&(v.pendingPermission={downstream:r,agentRequestId:i.id,upstreamId:o});let w={...c,..._?{sessionId:_}:{},_meta:x};this.pendingUpstream.set(o,{agentRequestId:i.id,agentId:e.agentId,downstream:r,method:i.method,cloudSessionId:_}),W.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:o,acpSessionId:u,cloudSessionId:_,toolCallId:c.toolCall?.toolCallId,options:c.options?.map(E=>({optionId:E.optionId,kind:E.kind,name:E.name}))}),this.upstream.send(Bi(o,"session/request_permission",w)).catch(E=>{this.pendingUpstream.delete(o),W.error("forward permission request failed",{agentId:e.agentId,err:String(E)}),r.respondAgentRequestError(i.id,{code:J.INTERNAL_ERROR,message:`upstream send failed: ${String(E)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let o=r.value;this.clearPendingPermissionFor(o),e.error?(W.info("upstream \u2192 permission response (error)",{agentId:o.agentId,upstreamId:e.id,method:o.method,error:e.error}),o.downstream.respondAgentRequestError(o.agentRequestId,e.error)):(o.method==="session/request_permission"&&dE(e.result,o),W.info("upstream \u2192 permission response (result)",{agentId:o.agentId,upstreamId:e.id,method:o.method,result:e.result}),o.downstream.respondAgentRequest(o.agentRequestId,e.result));return}let i=this.lookupPending(this.pendingBridge,e.id,"bridge");if(i){this.pendingBridge.delete(i.key),clearTimeout(i.value.timer),e.error?i.value.reject(new fo(e.error)):i.value.resolve(e.result);return}W.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,i){let o=e.get(r);if(o)return{value:o,key:r};if(typeof r=="number"){let c=String(r),d=e.get(c);if(d)return W.warn(`${i} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:c}),{value:d,key:c}}}sendRequest(e,r,i=rE){let o=this.upstreamIds.next(e);return new Promise((c,d)=>{let u=setTimeout(()=>{this.pendingBridge.delete(o),d(new k("AGENT_TIMEOUT",`${e} timed out after ${i}ms`))},i);this.pendingBridge.set(o,{method:e,resolve:c,reject:d,timer:u}),this.upstream.send(Bi(o,e,r)).catch(f=>{let x=this.pendingBridge.get(o);x&&(clearTimeout(x.timer),this.pendingBridge.delete(o)),d(f)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[i,o]of e.sessions){let c={modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt};o.acpSessionId&&(c.acpSessionId=o.acpSessionId),o.permissionMode&&Vt(e)&&(c.permissionMode=o.permissionMode),o.cozeGroupId&&(c.cozeGroupId=o.cozeGroupId),r.set(i,c)}await ii(e.agentId,r,this.paths)}catch(r){W.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[i,o]of e.sessions.entries())if(o.acpSessionId===r)return i}sendError(e,r,i){return this.upstream.send(Sn(e,{code:r,message:i,data:{bridgeVersion:Ot}}))}};function cE(){return nE(16).toString("hex")}function dE(t,e){if(!t||typeof t!="object"){W.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){W.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let i=r.outcome;if(!i||typeof i!="object"){W.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let c=i.outcome;(typeof c!="string"||c!=="selected"&&c!=="cancelled")&&W.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:c,result:t})}var lE=["Model metadata for `","Falling back from WebSockets to HTTPS transport.","Heads up: Long threads and multiple compactions can cause the model to be less accurate."];function uE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let i=r;if(i.type!=="text"||typeof i.text!="string")return!1;let{text:o}=i;return lE.some(c=>o.startsWith(c))}an();te();De();import{randomBytes as fE}from"node:crypto";import{createServer as hE}from"node:http";var xE=1e6,ph=G("ipc"),Io=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??Q()}async start(){this.token=fE(32).toString("hex");let e=hE((i,o)=>{this.dispatch(i,o)});this.server=e,await new Promise((i,o)=>{e.once("error",o),e.listen(0,"127.0.0.1",()=>i())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),ph.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,i)=>{e.close(o=>o?i(o):r())}),this.server=null)}async persistAuthFiles(){await on(this.paths.portFile,String(this.port)),await on(this.paths.tokenFile,this.token,{mode:384})}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){$i(r,401,{error:"unauthorized"});return}let o=`${e.method} ${(e.url??"").split("?")[0]}`,c=this.routes.get(o);if(!c){$i(r,404,{error:"not found"});return}let d=null;if(e.method==="POST")try{d=await pE(e)}catch(u){$i(r,400,{error:"invalid json",detail:String(u)});return}try{let u=await c.handler(d,e);$i(r,200,u??{ok:!0})}catch(u){ph.error("IPC handler failed",{key:o,err:String(u)}),$i(r,500,{error:u instanceof Error?u.message:String(u)})}}};function $i(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function pE(t){let e=[],r=0;for await(let o of t){let c=o;if(r+=c.length,r>xE)throw new Error("body too large");e.push(c)}let i=Buffer.concat(e).toString("utf8");return i?JSON.parse(i):null}import"node:module";var Mv=Ut(lx(),1),Bv=Ut(Lo(),1),Fv=Ut(zr(),1),zv=Ut(bd(),1),Uv=Ut(Sd(),1),Gv=Ut(Cd(),1),yx=Ut(Fo(),1),Hv=Ut(_x(),1);var bx=yx.default;qe();te();var{FWS:iS}=Dx(),Ce=G("upstream.frontier"),Lx="application/json",Nx="none",sS=15e3;function oS(t){class e extends bx{constructor(i){super(i,Mf,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",i=>Ce.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:i instanceof Error?i.message:String(i)}))}close(i,o){this.guardTeardown(),super.close(i,o)}terminate(){this.guardTeardown(),super.terminate()}send(i,...o){if(yl("debug"))try{let c;typeof i=="string"?c=Buffer.from(i,"utf8"):i instanceof Buffer?c=i:i instanceof ArrayBuffer?c=new Uint8Array(i):ArrayBuffer.isView(i)?c=new Uint8Array(i.buffer,i.byteOffset,i.byteLength):c=new Uint8Array(0);let d=Buffer.from(c.slice(0,128)).toString("hex");Ce.debug("WS raw frame out",{bytes:c.byteLength,headHex:d})}catch(c){Ce.warn("WS raw frame dump failed",{err:String(c)})}super.send(i,...o)}}return e}var ts=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){Ce.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Bf,...En(this.opts.ppeOverride)},r=oS(e),i=zf(this.opts.urlOverride),o={url:i,ws:r,fpID:Nf,aID:oo,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Lx,force:!0},payloadEncoding:{encoding:Nx,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},c=new iS(o),d=!1,u=null,f,x,p=new Promise((w,E)=>{f=w,x=E}),_=w=>{d||(d=!0,u&&(clearTimeout(u),u=null),w?x(w):f())};c.onopen=()=>{this.opened=!0,this.openCount+=1;let w=this.openCount===1;Ce.info("frontier opened",{url:i,remoteDeviceId:this.opts.handshake.deviceId,initial:w,openCount:this.openCount}),w&&_();for(let E of this.connectHandlers)Promise.resolve(E({initial:w})).catch(I=>Ce.warn("onConnect handler threw (ignored)",{err:String(I)}))},c.onclose=w=>{this.opened=!1,Ce.info("frontier closed",{code:w.code,reason:w.reason,willReconnect:w.willReconnect})},c.onerror=w=>{Ce.warn("frontier error",{code:w.code,msg:w.message}),_(new k("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${w.code} msg=${w.message??""}`))},c.onmessage=w=>this.handleMessage(w),this.fws=c;let v=this.opts.openTimeoutMs??sS;u=setTimeout(()=>{_(new k("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${v}ms (handshake or upgrade slow)`))},v),await c.connect();try{await p}catch(w){try{c.close(1e3,"open failed")}catch(E){Ce.warn("fws close during start failure threw (ignored)",{err:String(E)})}throw this.fws=null,this.opened=!1,w}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(i){Ce.warn("frontier close threw (ignored)",{err:String(i)})}}}async send(e){let r=this.fws,i=e.method;if(!r)throw Ce.warn("frontier send refused: upstream not started",{method:i}),new k("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let u=Date.now();throw u-this.lastSendRefusedLogAt>1e3?(Ce.warn("frontier send refused: ws not open",{method:i,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=u,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new k("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let o=JSON.stringify(e),c=e;Mx(c)||Ce.info("frontier frame out",{method:c.method,jsonrpcId:c.id,size:o.length});try{await r.send(o,{service:33555712,method:1,payloadType:Lx,payloadEncoding:Nx})}catch(u){throw Ce.warn("frontier frame send failed",{method:c.method,jsonrpcId:c.id,err:String(u)}),new k("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(u)}`,{cause:u})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let i=e.params?._meta;if(!i?.cozeAgentId)return;let o=r(i.cozeAgentId);o&&(i.cozePatToken=o)}handleMessage(e){let r=e.message?.service;if(r!==33555712){Ce.debug("drop non-adapter frontier frame",{service:r});return}let i=dS(e);if(!i){Ce.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){Ce.debug("frame received but no onFrame handler",{size:i.length});return}let o;try{o=JSON.parse(i)}catch(d){Ce.warn("frontier message JSON parse failed",{err:String(d),head:i.slice(0,80)});return}let c=o;Mx(c)||Ce.info("frontier frame in",{logid:cS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:c.id,method:c.method,body:aS(i)}),Promise.resolve(this.handler(o)).catch(d=>Ce.warn("frontier frame handler threw",{err:String(d)}))}};function Mx(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Bx=2e3;function aS(t){return t.length<=Bx?t:`${t.slice(0,Bx)}...<truncated, total ${t.length} chars>`}function cS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function dS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}qe();te();var Ld=G("skill-publish"),lS="/api/marketplace/product/skill/publish_with_assets",uS=15e4;async function Fx(t,e={}){let i=`${Tr(Rr(e.handshakeBase))}${lS}`,o=e.timeoutMs??uS,c=new FormData;c.append("skill_id",t.skillId??""),c.append("skill_name",t.skillName),c.append("skill_description",t.description??""),c.append("agent_id",t.agentId),c.append("zip_file",new Blob([t.zip],{type:"application/zip"}),"skill.zip");let d={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...En(e.ppeOverride),...t.accountId&&t.accountId!=="0"?{"x-coze-account":t.accountId}:{}},u=new AbortController,f=setTimeout(()=>u.abort(),o);Ld.info("skill publish start",{url:i,method:"POST",form:{skill_id:t.skillId??"",skill_name:t.skillName,skill_description:t.description??"",agent_id:t.agentId,zip_file_bytes:t.zip.length},headers:{...d,Authorization:`Bearer ${t.patToken.slice(0,8)}...`}});try{let x=await fetch(i,{method:"POST",headers:d,body:c,signal:u.signal}),p=x.headers.get("x-tt-logid")??"";if(!x.ok){let w=await x.text().catch(()=>"");throw new k("UPLOAD_FAILED",`skill publish HTTP ${x.status} logid=${p}: ${w.slice(0,200)}`)}let _=await x.json();if(Ld.info("skill publish response",{logid:p,httpStatus:x.status,code:_.code,msg:_.msg,dataSkillId:_.data?.skill_id??"",dataVersion:_.data?.version??""}),_.code!==void 0&&_.code!==0)throw new k("UPLOAD_FAILED",`skill publish code=${_.code} msg=${_.msg??"-"} logid=${p}`);let v={};return _.data?.skill_id!==void 0&&_.data.skill_id!==""&&(v.skillId=String(_.data.skill_id)),_.data?.version&&(v.version=_.data.version),Ld.info("skill publish ok",{logid:p,skillId:v.skillId??"",version:v.version??""}),v}catch(x){throw x instanceof k?x:x.name==="AbortError"?new k("UPLOAD_FAILED",`skill publish timeout (${o}ms): ${t.skillName}`):new k("UPLOAD_FAILED",String(x),{cause:x})}finally{clearTimeout(f)}}te();var Nd=G("upstream.switchable"),Ko=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Nd.info("swap upstream",{reason:r});let i=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let o of this.connectHandlers)e.onConnect(o);try{await e.start()}catch(o){throw Nd.error("swap target start failed, reverting",{err:String(o)}),this.inner=i,o}await i.stop(r??"swapped").catch(o=>Nd.warn("previous upstream stop threw (ignored)",{err:String(o)}))}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.connectHandlers.push(e),this.inner.onConnect?.(e)}isConnected(){return this.inner.isConnected()}};te();var Md=G("upstream"),Wr=class{handler=null;async start(){Md.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Md.info("NoopUpstream stopped",{reason:e})}async send(e){Md.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)}};qe();te();an();te();De();import{promises as fS}from"node:fs";var zx=G("pat-token-store");async function Vo(t=Q()){try{let r=(await fS.readFile(t.patTokenFile,"utf8")).trim();return r.length===0?(zx.warn("pat-token exists but empty (treating as missing; likely interrupted write)",{path:t.patTokenFile}),null):r}catch(e){let r=e?.code;return r!=="ENOENT"&&zx.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function ns(t,e=Q()){if(!t)throw new Error("writePatToken: empty patToken");await on(e.patTokenFile,t,{mode:384})}De();De();import{promises as Zo}from"node:fs";import{join as hS}from"node:path";function xS(t,e){return`#!/bin/sh
103
105
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
104
- `}function Vv(t,e){return`@echo off\r
106
+ `}function pS(t,e){return`@echo off\r
105
107
  "${e}" "${t}" %*\r
106
- `}async function vh(t,e=Q()){let r=e.binDir;await Ko.mkdir(r,{recursive:!0});let i=Kv(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?Vv(t,o):$v(t,o);return await Ko.readFile(i,"utf8").catch(()=>null)===c||(await Ko.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Ko.chmod(i,493)),r}ne();Pe();import{execSync as Sh}from"node:child_process";import{readFileSync as Ih,unlinkSync as Zv}from"node:fs";import{mkdir as Jv,open as Yv,readFile as Ah,unlink as Pd,writeFile as Xv}from"node:fs/promises";import{dirname as Qv}from"node:path";var eS=G("single-instance"),tS=t=>new Promise(e=>setTimeout(e,t)),$o=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Q().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Bi(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&eS.warn("removing stale pid file",{stalePid:i}),await Xv(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return r.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),r}async release(){if(this.acquired){try{(await Ah(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Pd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await Ah(e,"utf8"),i=Number.parseInt(r.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(r){if(r.code==="ENOENT")return null;throw r}}async withClaimLock(e){let r=`${this.pidFile}.lock`;await Jv(Qv(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await Yv(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=await this.readPidFrom(r);if(l!==null&&l!==this.selfPid&&this.probe.isAlive(l)){await tS(this.claimLockIntervalMs);continue}await Pd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Pd(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Ih(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Dr)||r.includes("lib/index.js"))}catch{}try{let r=Sh(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Dr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Sh(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Ih(this.pidFile,"utf8").trim()===String(this.selfPid)&&Zv(this.pidFile)}catch{}})}};Vo();ne();var Yn=G("daemon.upstream-watchdog"),dS=12e4,lS=9e5,uS=3e4;function Od(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var Zo=class{constructor(e){this.opts=e;this.softMs=e.softMs??Od("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",dS),this.hardMs=e.hardMs??Od("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",lS),this.intervalMs=e.intervalMs??Od("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",uS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),Yn.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&Yn.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&Yn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,Yn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){Yn.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,Yn.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>Yn.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var j=G("daemon");async function Rh(){let t=Q();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){ul({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:O=>Ye(O,t).logs,listAgentIds:()=>ds(t)});try{let{writeFileSync:O}=await import("node:fs");O(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
108
+ `}async function Ux(t,e=Q()){let r=e.binDir;await Zo.mkdir(r,{recursive:!0});let i=hS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),o=process.execPath,c=process.platform==="win32"?pS(t,o):xS(t,o);return await Zo.readFile(i,"utf8").catch(()=>null)===c||(await Zo.writeFile(i,c,"utf8"),process.platform!=="win32"&&await Zo.chmod(i,493)),r}te();De();import{execSync as Gx}from"node:child_process";import{readFileSync as Hx,unlinkSync as gS}from"node:fs";import{mkdir as mS,open as wS,readFile as qx,unlink as Bd,writeFile as _S}from"node:fs/promises";import{dirname as yS}from"node:path";var bS=G("single-instance"),ES=t=>new Promise(e=>setTimeout(e,t)),Jo=class{pidFile;selfPid;probe;claimLockMaxAttempts;claimLockIntervalMs;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??Q().pidFile,this.selfPid=e.selfPid??process.pid,this.claimLockMaxAttempts=e.claimLockMaxAttempts??50,this.claimLockIntervalMs=e.claimLockIntervalMs??20,this.probe=e.probe??{isAlive:r=>Ui(r),isDaemon:r=>this.matchesDaemonTitle(r)},e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();if(e!==null&&e!==this.selfPid&&this.isLiveDaemon(e))return{kind:"already-running",pid:e};let r=await this.withClaimLock(async()=>{let i=await this.readExistingPid();return i!==null&&i!==this.selfPid&&this.isLiveDaemon(i)?{kind:"already-running",pid:i}:(i!==null&&i!==this.selfPid&&bS.warn("removing stale pid file",{stalePid:i}),await _S(this.pidFile,String(this.selfPid),"utf8"),{kind:"acquired"})});return r.kind==="acquired"&&(this.acquired=!0,this.installCleanupHooks()),r}async release(){if(this.acquired){try{(await qx(this.pidFile,"utf8")).trim()===String(this.selfPid)&&await Bd(this.pidFile)}catch{}this.acquired=!1}}isLiveDaemon(e){return this.probe.isAlive(e)&&this.probe.isDaemon(e)}async readExistingPid(){return this.readPidFrom(this.pidFile)}async readPidFrom(e){try{let r=await qx(e,"utf8"),i=Number.parseInt(r.trim(),10);return Number.isFinite(i)&&i>0?i:null}catch(r){if(r.code==="ENOENT")return null;throw r}}async withClaimLock(e){let r=`${this.pidFile}.lock`;await mS(yS(r),{recursive:!0});for(let i=0;i<this.claimLockMaxAttempts;i++){let o;try{o=await wS(r,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let d=await this.readPidFrom(r);if(d!==null&&d!==this.selfPid&&this.probe.isAlive(d)){await ES(this.claimLockIntervalMs);continue}await Bd(r).catch(()=>{});continue}try{return await o.writeFile(String(this.selfPid)),await e()}finally{await o.close().catch(()=>{}),await Bd(r).catch(()=>{})}}throw new Error(`failed to acquire claim lock: ${r} (after ${this.claimLockMaxAttempts} attempts)`)}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Hx(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes(Lr)||r.includes("lib/index.js"))}catch{}try{let r=Gx(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes(Lr)||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let i=Gx(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!i||/^(INFO|信息)[::]/.test(i))return!1;let o=i.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return o.includes("node")||o.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Hx(this.pidFile,"utf8").trim()===String(this.selfPid)&&gS(this.pidFile)}catch{}})}};Yo();te();var Qn=G("daemon.upstream-watchdog"),CS=12e4,PS=9e5,DS=3e4;function zd(t,e){let r=process.env[t];if(!r)return e;let i=Number(r);return Number.isFinite(i)&&i>0?i:e}var Xo=class{constructor(e){this.opts=e;this.softMs=e.softMs??zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",CS),this.hardMs=e.hardMs??zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",PS),this.intervalMs=e.intervalMs??zd("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",DS),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),Qn.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&Qn.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&Qn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,Qn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let r=e-this.downSince;if(r>=this.hardMs){Qn.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:r,hardMs:this.hardMs}),this.opts.onFatal(r);return}r>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,Qn.warn("upstream watchdog: forcing reconnect",{downMs:r,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(i=>Qn.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(i)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var H=G("daemon");async function $x(){let t=Q();if(process.env.COZE_BRIDGE_LOG_MODE!=="legacy"){wl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:P=>Ve(P,t).logs,listAgentIds:()=>fs(t)});try{let{writeFileSync:P}=await import("node:fs");P(t.logFile,`\u8FD0\u884C\u65E5\u5FD7\u5DF2\u8FC1\u79FB\u5230 dated \u6587\u4EF6, \u6B64\u6587\u4EF6 (bridge.log) \u4E0D\u518D\u5199\u5165\u8FD0\u884C\u65E5\u5FD7\u3002
107
109
  \u8BF7\u67E5\u770B: ${t.bridgeLogsDir}/bridge-<YYYY-MM-DD>.log
108
110
  \u6216\u4F7F\u7528: coze-bridge log [-f] [--lines N]
109
- `)}catch{}}let e=new $o({processTitle:Dr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await yo(),o=i??{};as({pid:process.pid}),j.info(i?"loaded bridge config":"initialized bridge config");let c=new jo(new qr),l=null,u=new bo({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(O,q,K,se)=>{if(!l)throw new Error("agentManager not ready");return l.spawnSessionDownstream(O,q,K,se)}}),x=new mo({paths:t,config:o,registry:u});l=x;let h,w,_=null,v={},y,E=null,I=null,A=null,C=new In;function P(O,q){return C.enqueue(()=>k(O,q))}function b(){I||(I=new Zo({isConnected:()=>c.isConnected(),forceReconnect:()=>A?P(A,{force:!0}):void 0,onFatal:O=>{if(process.env[es]==="1"){j.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:O});return}j.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:O}),process.exit(1)}})),I.start()}async function k(O,q){let K=O,se=K?.privatecode;if(!se)throw new T("IPC_BAD_REQUEST","/connect requires privatecode");let Ve=Pi(K.env),xe=K.handshake_url,he=K.frontier_url,St=Ch(K.env,xe,he);if(A=K,!q?.force&&h===se&&w===St){let me=await fS(t);return u.agents.size===0&&me?(j.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Yo(t,x).catch(Ie=>j.warn("connect-noop auto-revive error (ignored)",{err:String(Ie)}))):j.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let xt=!!h&&h!==se,Qt=w!==void 0&&w!==St,Ft=xt||Qt,en=await Bc({privatecode:se,...xe?{endpoint:xe}:{},ppeOverride:Ve});if(Ft){j.warn("connect config switched, resetting agents",{pcChanged:xt,envChanged:Qt,previousPc:h?Jo(h):"",nextPc:Jo(se)});for(let me of[...u.agents.values()])await me.dispose("connect config switch").catch(()=>{}),u.agents.delete(me.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new qr,"connect switch").catch(()=>{})}_=en.deviceId,as({deviceId:_,pid:process.pid}),id({patToken:se,env:K.env}).catch(me=>j.warn("coze-cli setup error (ignored)",{err:String(me)}));let Vr=new Xi({handshake:en,privatecode:se,...he?{urlOverride:he}:{},ppeOverride:Ve,getPatTokenForAgent:me=>u.agents.get(me)?.patToken});return await c.swap(Vr,"connect"),h=se,w=St,v=Ve,y=xe,K.mock_scenario!==void 0&&(u.setMockScenario(K.mock_scenario),j.info("mock scenario set",{scenario:K.mock_scenario})),E||(E=new Oi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(me=>j.warn("detailSync.retryPending failed (ignored)",{err:String(me)})),onAuthFailures:Z})),E.start(),b(),Ft&&Yo(t,x).catch(me=>j.warn("post-connect-switch auto-revive error (ignored)",{err:String(me)})),Qi(se,t).catch(me=>j.warn("writePatToken after /connect failed (ignored)",{err:String(me)})),j.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async O=>x.createAgent(O.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let D={},z=new ao({agents:u.agents,disposeAndMarkDisconnected:async(O,q)=>{let K=u.agents.get(O);if(K){await x.cleanupOpenclawSessionProviders(K).catch(Ve=>j.warn("cleanup openclaw providers failed (ignored)",{agentId:O,err:String(Ve)}));let se=!0;try{await K.dispose(`disconnect: ${q}`)}catch(Ve){se=!1,j.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:O,err:String(Ve)}),K.status="error"}se&&(K.status="disconnected",u.unregister(O),u.disconnectedAgents.add(O))}else u.disconnectedAgents.add(O)},detailSyncer:async O=>{if(!D.ref)throw new Error("agent-detail-sync not initialized yet");await D.ref.syncOne(O)},cleanupOpenclawProviders:async O=>{await x.cleanupOpenclawSessionProviders(O)},openclawRepair:async(O,q)=>{await x.openclawRepair(O,q)},isRuntimePendingPermission:O=>u.hasPendingPermissionFor(O)});u.registerExtension("_agent/listSkills",O=>z.listSkills(O.params)),u.registerExtension("_agent/addSkills",O=>z.addSkills(O.params)),u.registerExtension("_agent/removeSkills",O=>z.removeSkills(O.params)),u.registerExtension("_agent/getFileTree",O=>z.getFileTree(O.params)),u.registerExtension("_agent/getFileContent",O=>z.getFileContent(O.params)),u.registerExtension("_agent/update",O=>z.updateAgent(O.params)),u.registerExtension("_agent/disconnect",O=>z.disconnectAgent(O.params)),u.registerExtension("_agent/switchModel",O=>z.switchModel(O.params)),u.registerExtension("_agent/reset",O=>z.resetAgent(O.params)),u.registerExtension("_agent/repair",O=>z.repairAgent(O.params)),u.registerExtension("_agent/upgrade",O=>z.upgradeBridge(O.params));let M=new xs({paths:t,handlers:z,agentManager:x,sendDetail:O=>u.sendRequest("_agent/detail",O)});D.ref=M;let Z=async O=>{await Promise.allSettled(O.map(async q=>{try{await z.disconnectAgent({agentId:q.agentId,reason:`auth_failure: code=${q.code} ${q.message}`}),j.info("agent disconnected due to auth failure from heartbeat response",{agentId:q.agentId,code:q.code,message:q.message})}catch(K){j.warn("disconnect during authFailure handling failed (ignored)",{agentId:q.agentId,err:String(K)})}}))};c.onConnect(({initial:O})=>{j.info("frontier upstream connected, triggering detail sync",{initial:O}),M.syncAll(O?"initial-connect":"reconnect").catch(q=>j.warn("detail sync top-level error (ignored)",{err:String(q)}))});let V=new Eo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let O=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[es]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...O?{mockScenario:O}:{}}}},{method:"POST",path:"/pair",handler:async O=>{let q=O,K=q?.privatecode,se=q?.pairing_code;if(!K||!se)throw new T("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ve=Pi(q.env),xe=q.handshake_url,he=q.frontier_url,St=Ch(q.env,xe,he),xt=!!h&&h!==K,Qt=w!==void 0&&w!==St,Ft=xt||Qt,en=await Bc({privatecode:K,...xe?{endpoint:xe}:{},ppeOverride:Ve});if(Ft){j.warn("pair config switched, resetting agents",{pcChanged:xt,envChanged:Qt,previousPc:h?Jo(h):"",nextPc:Jo(K),previousEnvKey:w??"",nextEnvKey:St});for(let Ie of[...u.agents.values()])await Ie.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ie.agentId);u.disconnectedAgents.size>0&&(j.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new qr,"pair switch").catch(()=>{})}_=en.deviceId,as({deviceId:_,pid:process.pid}),id({patToken:K,env:q.env}).catch(Ie=>j.warn("coze-cli setup error (ignored)",{err:String(Ie)}));let Vr=new Xi({handshake:en,privatecode:K,...he?{urlOverride:he}:{},ppeOverride:Ve,getPatTokenForAgent:Ie=>u.agents.get(Ie)?.patToken});await c.swap(Vr,"pair");try{let Ie=new Wn;o.frameworksCache=await Ie.detectAll(),await Hi(o),j.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ie){j.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ie)})}let me=Object.keys(o.frameworksCache??{});try{let Ie=await u.sendRequest("_agent/pair",{pairCode:se,patToken:K,frameworks:me,_meta:{cozeDeviceId:_}});j.info("_agent/pair ok",{pairResult:Ie}),h=K,w=St,v=Ve,y=xe,q.mock_scenario!==void 0&&(u.setMockScenario(q.mock_scenario),j.info("mock scenario set",{scenario:q.mock_scenario})),Qi(K,t).catch(ke=>j.warn("writePatToken after /pair failed (ignored)",{err:String(ke)})),E||(E=new Oi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>M.retryPending().catch(ke=>j.warn("detailSync.retryPending failed (ignored)",{err:String(ke)})),onAuthFailures:Z})),E.start(),b(),Ft&&Yo(t,x).catch(ke=>j.warn("post-pair-switch auto-revive error (ignored)",{err:String(ke)}));let Xn;return q.agent_id&&(Xn=await hS(q.agent_id,t,x,ke=>u.sendRequest("_agent/detail",ke),K).catch(ke=>(j.error("--agent-id ensureAgent failed",{agentId:q.agent_id,err:String(ke)}),{ok:!1,agentId:q.agent_id??"",note:String(ke)}))),{ok:!0,note:"paired with cloud",...Xn?{agent:Xn}:{}}}catch(Ie){return j.error("_agent/pair failed",{err:String(Ie)}),{ok:!1,note:`pair failed: ${String(Ie)}`}}}},{method:"POST",path:"/connect",handler:O=>P(O)},{method:"POST",path:"/_agent/create",handler:async O=>{let q=O;return{ok:!0,result:await x.createAgent(q)}}},{method:"POST",path:"/agent/send",handler:async O=>{let q=O;if(!q?.agentId||!q?.sessionId||!q?.kind||!q?.path)throw new T("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!h)throw new T("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let K=q;return await(K.groupFile?B0:M0)(K,{core:u,patToken:h,handshakeBase:y,ppeOverride:v})}catch(K){if(K instanceof T)return{ok:!1,code:K.code,message:K.message};throw K}}},{method:"POST",path:"/reload",handler:async O=>{let q=O?.agent_id,K=await u.reloadAgents(q);return j.info("IPC /reload: recycled agent subprocesses",{agentId:q??"(all)",recycled:K}),{ok:!0,recycled:K}}},{method:"POST",path:"/shutdown",handler:async()=>(j.info("IPC /shutdown received"),setImmediate(()=>{oe.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:te,token:J}=await V.start();try{await vh(t.libEntry,t)}catch(O){j.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(O)})}await u.start(),pS({paths:t,core:u,agentManager:x,detectAll:async()=>(o.frameworksCache=await new Wn().detectAll(),await Hi(o),o.frameworksCache)}).catch(O=>j.warn("startup warmup error (ignored)",{err:String(O)})),bl().then(async()=>{let{probeAcpVersion:O}=await Promise.resolve().then(()=>(rn(),_l));for(let q of["claude-code","codex"]){let K=await O(q);K&&j.info("acp wrapper version",{framework:q,version:K})}}).catch(O=>j.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(O)}));let ie=null,oe={port:te,token:J,core:u,ipc:V,shutdown(O){return ie||(j.info("daemon shutdown",{reason:O}),ie=(async()=>{E?.stop(),I?.stop(),await u.stop(O),await V.stop(),await e.release()})(),ie)}};for(let O of["SIGTERM","SIGINT"])process.on(O,()=>{oe.shutdown(O).then(()=>process.exit(0))});return process.on("exit",()=>o0()),process.on("unhandledRejection",O=>{j.error("unhandledRejection",{reason:O instanceof Error?O.message:String(O),stack:O instanceof Error?O.stack:void 0})}),process.on("uncaughtException",O=>{j.error("uncaughtException (will exit, supervisor will restart)",{message:O.message,stack:O.stack,name:O.name});try{process.stderr.write(`FATAL uncaughtException: ${O.stack??O.message}
110
- `)}catch{}process.exit(1)}),j.info("daemon ready",{port:te,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),gS({cliSpawned:process.env[es]==="1",readPatToken:()=>Wo(t),connect:P}).catch(O=>j.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(O)})),oe}async function fS(t){return ds(t).length>0}function Jo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Ch(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function xS(t,e){let r=ds(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(an(),fs));for(let c of r){await o(c,t).catch(l=>j.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(l)}));try{let l=await i(c,t);l?.disconnectedAt&&(e.disconnectedAgents.add(c),j.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:l.disconnectedAt,reason:l.disconnectReason??""}))}catch(l){j.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(l)})}}}async function hS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(an(),fs)),l=await c(t,e);if(l){j.info("--agent-id: local config found, reconnecting",{agentId:t,framework:l.framework,hadDisconnect:!!l.disconnectedAt});let w=kh(l),_={agentId:l.agentId,framework:l.framework,...l.cozeIdentity?{cozeIdentity:l.cozeIdentity}:{},...l.model?{model:l.model}:{},...o?{patToken:o}:{},...w?{_meta:w}:{}};return await r.createAgent(_),{ok:!0,agentId:t,note:l.disconnectedAt?"revived from local config":"connected from local config"}}j.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new T("AGENT_NOT_FOUND",`agent ${t} \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 x={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(x);let h=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:h?"cloud agent acknowledged":"created from cloud detail"}}async function pS(t){let e=t.logger??j;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await xS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await Yo(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)}))}async function Yo(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(an(),fs));j.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,l=0;for(let u of i){let x;try{x=await o(u,t)}catch(h){j.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(h)}),l+=1;continue}if(!x){l+=1;continue}if(x.disconnectedAt){j.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:x.disconnectedAt}),l+=1;continue}try{j.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:x.framework});let h=kh(x);await e.createAgent({agentId:x.agentId,framework:x.framework,...x.cozeIdentity?{cozeIdentity:x.cozeIdentity}:{},...x.model?{model:x.model}:{},...h?{_meta:h}:{}},{revive:!0}),c+=1}catch(h){j.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:x.framework,err:String(h)}),l+=1}}return j.info("auto-revive: done",{revived:c,skipped:l,total:i.length}),{revived:c,skipped:l,total:i.length}}async function gS(t){let e=t.logger??j;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function kh(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Vo();Pe();import{readFile as Ph}from"node:fs/promises";var Xt=class{paths;constructor(e){this.paths=e??Q()}async probe(e=1e3){let r=await Xo(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:wS(i)}}}async request(e){let r=await Xo(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,l=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),x=await u.text();return{status:u.status,body:mS(x)}}finally{clearTimeout(l)}}};async function Xo(t){try{let[e,r]=await Promise.all([Ph(t.portFile,"utf8"),Ph(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function mS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function wS(t){return t instanceof Error?t.message:String(t)}Kt();ne();nr();import{spawn as _S}from"node:child_process";import{userInfo as Oh}from"node:os";var Ld="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",yS=new Set(["bash","zsh","sh","dash","ksh"]),Dh=qe("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),bS=2e3;function ES(t,e=Ld){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let l of o.split(`
111
- `)){let u=l.indexOf("=");u<=0||(c[l.slice(0,u)]=l.slice(u+1))}return c}function vS(){let t=(process.env.SHELL??"").trim()||(Oh().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return yS.has(e)?t:null}function SS(t){return new Promise(e=>{let r=`printf '%s' '${Ld}'; env; printf '%s' '${Ld}'`,i;try{i=_S(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Oh().homedir}})}catch{e(null);return}let o="",c=!1,l=w=>{try{i.pid&&process.kill(-i.pid,w)}catch{}},u=w=>{c||(c=!0,clearTimeout(x),clearTimeout(h),e(w))};i.stdout?.on("data",w=>{o+=w.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let x=setTimeout(()=>l("SIGTERM"),Dh),h=setTimeout(()=>{l("SIGKILL"),u(o.length>0?o:null)},Dh+bS)})}async function Nd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=vS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??SS)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=ES(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}Pe();function Cn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],l=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,l=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),l=!0;break}}l||r.push(c)}return{value:i,rest:r}}rn();import{chmod as IS,copyFile as Lh,mkdir as Mh,readFile as Qo,rename as Nh,rm as Md,stat as Bh,writeFile as AS}from"node:fs/promises";import{homedir as yk}from"node:os";import{dirname as TS,join as jr,resolve as Bd,sep as ts}from"node:path";import{fileURLToPath as CS}from"node:url";Kt();ne();Pe();var Fd=G("dist-install");function RS(t){let e=CS(t),r=TS(e),i=`${ts}src${ts}`;if(r.includes(i)||r.endsWith(`${ts}src${ts}cli`))return null;let o=Bd(r,"index.js"),c=Bd(r,"..","package.json");return{dist:o,pkgJson:c}}async function Ud(t={}){let e=t.paths??Q(),r=RS(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,l;try{let v=JSON.parse(await Qo(o,"utf8"));c=v.version??"unknown",l=v.dependencies??{}}catch(v){return Fd.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=Qr.map(v=>`${v}@${l[v]??"latest"}`),x=await yo(e.configFile)??{},h=x.libVersion,w=await Qo(e.libEntry).then(()=>!0).catch(()=>!1),_=h===c;if(_&&w&&await zd(e))return{kind:"already-current",libVersion:c};if(!_||!w){await Mh(e.libDir,{recursive:!0}),await Lh(i,e.libEntry),await Lh(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=Bd(e.libDir,"package.json"),y=`${JSON.stringify({type:"module"},null,2)}
112
- `;await Qo(v,"utf8").catch(()=>null)!==y&&await AS(v,y)}return(!_||!await zd(e))&&await(t.installWrappers??kS)(e,u),x.libVersion=c,await Hi(x,e.configFile),Fd.info("dist installed",{libEntry:e.libEntry,fromVersion:h,toVersion:c}),_&&w?{kind:"already-current",libVersion:c}:h?{kind:"version-changed",fromVersion:h,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function zd(t){for(let e of Qr){let r=jr(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await Bh(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function kS(t,e){await OS(t.installLock,async()=>{if(await zd(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${ts}.staging-${process.pid}-${r}`,o=jr(i,"node_modules"),c=jr(t.libDir,"node_modules");try{await Mh(i,{recursive:!0}),await PS(e,i),await DS(o);let l=`${c}.trash-${r}`;await Nh(c,l).catch(()=>{}),await Nh(o,c),await Md(l,{recursive:!0,force:!0}).catch(()=>{}),Fd.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Md(i,{recursive:!0,force:!0}).catch(()=>{})}})}function PS(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=et("npm",r,{stdio:["ignore","pipe","pipe"]}),l="";c.stderr?.on("data",x=>{l.length<8192&&(l+=x.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",x=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(x)}`))}),c.once("close",x=>{clearTimeout(u),x===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${x}: ${l.trim().slice(0,2e3)}`))})})}async function DS(t){for(let e of Qr){let r=jr(t,...e.split("/")),i=JSON.parse(await Qo(jr(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=jr(t,".bin",o),l=await Bh(c);process.platform!=="win32"&&!(l.mode&73)&&await IS(c,l.mode|73).catch(()=>{})}}async function OS(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Md(t,{force:!0}).catch(()=>{})}}Ea();ne();Pe();import{closeSync as zh,fstatSync as Uh,openSync as Hh,readFileSync as LS,readSync as NS,readdirSync as MS,statSync as BS}from"node:fs";import{join as ea}from"node:path";var FS=new Set(["debug","info","warn","error"]);function Gh(t){let e=t,r=Cn(e,"--agent-id");e=r.rest;let i=Cn(e,"--date");e=i.rest;let o=Cn(e,"-n","--lines");e=o.rest;let c=Cn(e,"--level");e=c.rest;let l=Cn(e,"--grep");e=l.rest;let u=o.value===void 0?200:Number(o.value),x=Number.isInteger(u)&&u>=0?u:200,h=c.value&&FS.has(c.value)?c.value:void 0,w={lines:x,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(w.agentId=r.value),i.value&&(w.date=i.value),h&&(w.level=h),l.value&&(w.grep=l.value),w}function zS(t,e){return t.agentId?ea(Ye(t.agentId,e).logs,rr("agent",t.date)):ea(e.bridgeLogsDir,rr("bridge",t.date))}function US(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function HS(t,e){let r;try{r=MS(t)}catch{return[]}let i=[];for(let o of r){let c=ba(o,e);if(!c)continue;let l=0;try{l=BS(ea(t,o)).size}catch{}i.push({file:ea(t,o),date:c,size:l})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function qh(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!hl(r,e.level))return!1}return!0}var Fh={debug:"90",info:"36",warn:"33",error:"31"},GS=new Set(["ts","level","module","msg"]);function qS(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function jh(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=qS(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&Fh[o]&&(c=`\x1B[${Fh[o]}m${c}\x1B[0m`);let l=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",x=Object.entries(r).filter(([h])=>!GS.has(h)).map(([h,w])=>` ${h}=${typeof w=="string"?w:JSON.stringify(w)}`).join("");return`${i} ${c} ${l} ${u}${x}`}function jS(t,e,r){let c=LS(t,"utf8").split(`
113
- `).filter(l=>l.length>0).filter(l=>qh(l,{level:e.level,grep:e.grep}));for(let l of US(c,e.lines))process.stdout.write(`${jh(l,{raw:e.raw,color:r})}
114
- `)}async function Wh(t,e){let r=e.paths??Q(),i=process.stdout.isTTY===!0;if(t.list){let l=t.agentId?Ye(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",x=HS(l,u);if(x.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${l}
115
- `),1;for(let h of x)process.stdout.write(`${h.date} ${(h.size/1024).toFixed(1)}KB ${h.file}
116
- `);return 0}let o=t.date??kn(new Date),c=zS({agentId:t.agentId,date:o},r);try{jS(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
111
+ `)}catch{}}let e=new Jo({processTitle:Lr}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let i=await vo(),o=i??{};ls({pid:process.pid}),H.info(i?"loaded bridge config":"initialized bridge config");let c=new Ko(new Wr),d=null,u=new So({upstream:c,paths:t,bridgeConfig:o,sessionSpawner:async(P,U,j,ee)=>{if(!d)throw new Error("agentManager not ready");return d.spawnSessionDownstream(P,U,j,ee)}}),f=new yo({paths:t,config:o,registry:u});d=f;let x,p,_=null,v={},w,E=null,I=null,A=null,T=new An;function D(P,U){return T.enqueue(()=>C(P,U))}function y(){I||(I=new Xo({isConnected:()=>c.isConnected()&&!(E?.isLivenessLost()??!1),forceReconnect:()=>A?D(A,{force:!0}):void 0,onFatal:P=>{if(process.env[rs]==="1"){H.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:P});return}H.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:P}),process.exit(1)}})),I.start()}async function C(P,U){let j=P,ee=j?.privatecode;if(!ee)throw new k("IPC_BAD_REQUEST","/connect requires privatecode");let Xe=Li(j.env),he=j.handshake_url,xe=j.frontier_url,It=Wx(j.env,he,xe);if(A=j,!U?.force&&x===ee&&p===It){let we=await OS(t);return u.agents.size===0&&we?(H.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),ea(t,f).catch(Ie=>H.warn("connect-noop auto-revive error (ignored)",{err:String(Ie)}))):H.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let pt=!!x&&x!==ee,en=p!==void 0&&p!==It,zt=pt||en,tn=await zc({privatecode:ee,...he?{endpoint:he}:{},ppeOverride:Xe});if(zt){H.warn("connect config switched, resetting agents",{pcChanged:pt,envChanged:en,previousPc:x?Qo(x):"",nextPc:Qo(ee)});for(let we of[...u.agents.values()])await we.dispose("connect config switch").catch(()=>{}),u.agents.delete(we.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on connect config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"connect switch").catch(()=>{})}_=tn.deviceId,ls({deviceId:_,pid:process.pid}),dd({patToken:ee,env:j.env}).catch(we=>H.warn("coze-cli setup error (ignored)",{err:String(we)}));let Jr=new ts({handshake:tn,privatecode:ee,...xe?{urlOverride:xe}:{},ppeOverride:Xe,getPatTokenForAgent:we=>u.agents.get(we)?.patToken});return await c.swap(Jr,"connect"),x=ee,p=It,v=Xe,w=he,j.mock_scenario!==void 0&&(u.setMockScenario(j.mock_scenario),H.info("mock scenario set",{scenario:j.mock_scenario})),E||(E=new Mi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>N.retryPending().catch(we=>H.warn("detailSync.retryPending failed (ignored)",{err:String(we)})),onAuthFailures:Z})),E.start(),y(),zt&&ea(t,f).catch(we=>H.warn("post-connect-switch auto-revive error (ignored)",{err:String(we)})),ns(ee,t).catch(we=>H.warn("writePatToken after /connect failed (ignored)",{err:String(we)})),H.info("/connect: WS established",{deviceId:_}),{ok:!0,note:"connected"}}u.registerExtension("_agent/create",async P=>f.createAgent(P.params)),u.registerExtension("_agent/health",async()=>({ok:!0}));let O={},M=new co({agents:u.agents,publishSkillToMarketplace:async P=>{let U=u.agents.get(P.agentId)?.patToken??x;if(!U)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");return Fx({patToken:U,zip:P.zip,...P.skillId?{skillId:P.skillId}:{},skillName:P.skillName,...P.description?{description:P.description}:{},agentId:P.agentId,...P.accountId?{accountId:P.accountId}:{}},{handshakeBase:w,ppeOverride:v})},disposeAndMarkDisconnected:async(P,U)=>{let j=u.agents.get(P);if(j){await f.cleanupOpenclawSessionProviders(j).catch(Xe=>H.warn("cleanup openclaw providers failed (ignored)",{agentId:P,err:String(Xe)}));let ee=!0;try{await j.dispose(`disconnect: ${U}`)}catch(Xe){ee=!1,H.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:P,err:String(Xe)}),j.status="error"}ee&&(j.status="disconnected",u.unregister(P),u.disconnectedAgents.add(P))}else u.disconnectedAgents.add(P)},disposeForDelete:async(P,U)=>{let j=u.agents.get(P);j&&(await f.cleanupOpenclawSessionProviders(j).catch(ee=>H.warn("cleanup openclaw providers during delete failed (ignored)",{agentId:P,err:String(ee)})),await j.dispose(`delete: ${U}`).catch(ee=>H.warn("dispose during delete failed (ignored)",{agentId:P,err:String(ee)})),u.unregister(P)),u.disconnectedAgents.delete(P)},detailSyncer:async P=>{if(!O.ref)throw new Error("agent-detail-sync not initialized yet");await O.ref.syncOne(P)},cleanupOpenclawProviders:async P=>{await f.cleanupOpenclawSessionProviders(P)},openclawRepair:async(P,U)=>{await f.openclawRepair(P,U)},isRuntimePendingPermission:P=>u.hasPendingPermissionFor(P)});u.registerExtension("_agent/listSkills",P=>M.listSkills(P.params)),u.registerExtension("_agent/addSkills",P=>M.addSkills(P.params)),u.registerExtension("_agent/removeSkills",P=>M.removeSkills(P.params)),u.registerExtension("_agent/publishSkill",P=>M.publishSkill(P.params)),u.registerExtension("_agent/getFileTree",P=>M.getFileTree(P.params)),u.registerExtension("_agent/getFileContent",P=>M.getFileContent(P.params)),u.registerExtension("_agent/update",P=>M.updateAgent(P.params)),u.registerExtension("_agent/disconnect",P=>M.disconnectAgent(P.params)),u.registerExtension("_agent/switchModel",P=>M.switchModel(P.params)),u.registerExtension("_agent/reset",P=>M.resetAgent(P.params)),u.registerExtension("_agent/repair",P=>M.repairAgent(P.params)),u.registerExtension("_agent/delete",P=>M.deleteAgent(P.params)),u.registerExtension("_agent/upgrade",P=>M.upgradeBridge(P.params));let N=new ps({paths:t,handlers:M,agentManager:f,sendDetail:P=>u.sendRequest("_agent/detail",P)});O.ref=N;let Z=async P=>{await Promise.allSettled(P.map(async U=>{try{await M.disconnectAgent({agentId:U.agentId,reason:`auth_failure: code=${U.code} ${U.message}`}),H.info("agent disconnected due to auth failure from heartbeat response",{agentId:U.agentId,code:U.code,message:U.message})}catch(j){H.warn("disconnect during authFailure handling failed (ignored)",{agentId:U.agentId,err:String(j)})}}))};c.onConnect(({initial:P})=>{H.info("frontier upstream connected, triggering detail sync",{initial:P}),N.syncAll(P?"initial-connect":"reconnect").catch(U=>H.warn("detail sync top-level error (ignored)",{err:String(U)}))});let K=new Io({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let P=u.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[rs]==="1"?"manual":"supervisor",agents:[...u.agents.keys()],deviceId:_??"",frameworksCache:o.frameworksCache??{},...P?{mockScenario:P}:{}}}},{method:"POST",path:"/pair",handler:async P=>{let U=P,j=U?.privatecode,ee=U?.pairing_code;if(!j||!ee)throw new k("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Xe=Li(U.env),he=U.handshake_url,xe=U.frontier_url,It=Wx(U.env,he,xe),pt=!!x&&x!==j,en=p!==void 0&&p!==It,zt=pt||en,tn=await zc({privatecode:j,...he?{endpoint:he}:{},ppeOverride:Xe});if(zt){H.warn("pair config switched, resetting agents",{pcChanged:pt,envChanged:en,previousPc:x?Qo(x):"",nextPc:Qo(j),previousEnvKey:p??"",nextEnvKey:It});for(let Ie of[...u.agents.values()])await Ie.dispose("pair config switch").catch(()=>{}),u.agents.delete(Ie.agentId);u.disconnectedAgents.size>0&&(H.info("clearing disconnectedAgents set on pair config switch",{count:u.disconnectedAgents.size}),u.disconnectedAgents.clear()),await c.swap(new Wr,"pair switch").catch(()=>{})}_=tn.deviceId,ls({deviceId:_,pid:process.pid}),dd({patToken:j,env:U.env}).catch(Ie=>H.warn("coze-cli setup error (ignored)",{err:String(Ie)}));let Jr=new ts({handshake:tn,privatecode:j,...xe?{urlOverride:xe}:{},ppeOverride:Xe,getPatTokenForAgent:Ie=>u.agents.get(Ie)?.patToken});await c.swap(Jr,"pair");try{let Ie=new Kn;o.frameworksCache=await Ie.detectAll(),await ji(o),H.info("frameworks_cache refreshed before pair",{detected:Object.keys(o.frameworksCache)})}catch(Ie){H.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Ie)})}let we=Object.keys(o.frameworksCache??{});try{let Ie=await u.sendRequest("_agent/pair",{pairCode:ee,patToken:j,frameworks:we,_meta:{cozeDeviceId:_}});H.info("_agent/pair ok",{pairResult:Ie}),x=j,p=It,v=Xe,w=he,U.mock_scenario!==void 0&&(u.setMockScenario(U.mock_scenario),H.info("mock scenario set",{scenario:U.mock_scenario})),ns(j,t).catch(Pe=>H.warn("writePatToken after /pair failed (ignored)",{err:String(Pe)})),E||(E=new Mi({core:u,getDeviceId:()=>_??"",onTickEnd:()=>N.retryPending().catch(Pe=>H.warn("detailSync.retryPending failed (ignored)",{err:String(Pe)})),onAuthFailures:Z})),E.start(),y(),zt&&ea(t,f).catch(Pe=>H.warn("post-pair-switch auto-revive error (ignored)",{err:String(Pe)}));let er;return U.agent_id&&(er=await NS(U.agent_id,t,f,Pe=>u.sendRequest("_agent/detail",Pe),j).catch(Pe=>(H.error("--agent-id ensureAgent failed",{agentId:U.agent_id,err:String(Pe)}),{ok:!1,agentId:U.agent_id??"",note:String(Pe)}))),{ok:!0,note:"paired with cloud",...er?{agent:er}:{}}}catch(Ie){return H.error("_agent/pair failed",{err:String(Ie)}),{ok:!1,note:`pair failed: ${String(Ie)}`}}}},{method:"POST",path:"/connect",handler:P=>D(P)},{method:"POST",path:"/_agent/create",handler:async P=>{let U=P;return{ok:!0,result:await f.createAgent(U)}}},{method:"POST",path:"/agent/send",handler:async P=>{let U=P;if(!U?.agentId||!U?.sessionId||!U?.kind||!U?.path)throw new k("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!x)throw new k("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let j=U;return await(j.groupFile?Q0:X0)(j,{core:u,patToken:x,handshakeBase:w,ppeOverride:v})}catch(j){if(j instanceof k)return{ok:!1,code:j.code,message:j.message};throw j}}},{method:"POST",path:"/reload",handler:async P=>{let U=P?.agent_id,j=await u.reloadAgents(U);return H.info("IPC /reload: recycled agent subprocesses",{agentId:U??"(all)",recycled:j}),{ok:!0,recycled:j}}},{method:"POST",path:"/shutdown",handler:async()=>(H.info("IPC /shutdown received"),setImmediate(()=>{se.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:ne,token:Y}=await K.start();try{await Ux(t.libEntry,t)}catch(P){H.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(P)})}await u.start(),MS({paths:t,core:u,agentManager:f,detectAll:async()=>(o.frameworksCache=await new Kn().detectAll(),await ji(o),o.frameworksCache)}).catch(P=>H.warn("startup warmup error (ignored)",{err:String(P)})),Tl().then(async()=>{let{probeAcpVersion:P}=await Promise.resolve().then(()=>(sn(),Al));for(let U of["claude-code","codex"]){let j=await P(U);j&&H.info("acp wrapper version",{framework:U,version:j})}}).catch(P=>H.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(P)}));let ie=null,se={port:ne,token:Y,core:u,ipc:K,shutdown(P){return ie||(H.info("daemon shutdown",{reason:P}),ie=(async()=>{E?.stop(),I?.stop(),await u.stop(P),await K.stop(),await e.release()})(),ie)}};for(let P of["SIGTERM","SIGINT"])process.on(P,()=>{se.shutdown(P).then(()=>process.exit(0))});return process.on("exit",()=>g0()),process.on("unhandledRejection",P=>{H.error("unhandledRejection",{reason:P instanceof Error?P.message:String(P),stack:P instanceof Error?P.stack:void 0})}),process.on("uncaughtException",P=>{H.error("uncaughtException (will exit, supervisor will restart)",{message:P.message,stack:P.stack,name:P.name});try{process.stderr.write(`FATAL uncaughtException: ${P.stack??P.message}
112
+ `)}catch{}process.exit(1)}),H.info("daemon ready",{port:ne,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(o.frameworksCache??{}),libVersion:o.libVersion??"dev"}),FS({cliSpawned:process.env[rs]==="1",readPatToken:()=>Vo(t),connect:D}).catch(P=>H.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(P)})),se}async function OS(t){return fs(t).length>0}function Qo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Wx(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function LS(t,e){let r=fs(t);if(r.length===0)return;let{loadAgentConfig:i,enforceAgentConfigMode:o}=await Promise.resolve().then(()=>(cn(),xs));for(let c of r){await o(c,t).catch(d=>H.warn("enforceAgentConfigMode failed (ignored)",{agentId:c,err:String(d)}));try{let d=await i(c,t);d?.deletedAt?(e.disconnectedAgents.add(c),H.info("agent marked deleted on startup",{agentId:c,deletedAt:d.deletedAt,reason:d.deleteReason??""})):d?.disconnectedAt&&(e.disconnectedAgents.add(c),H.info("agent marked disconnected on startup",{agentId:c,disconnectedAt:d.disconnectedAt,reason:d.disconnectReason??""}))}catch(d){H.warn("failed to load agent config on startup, skipping",{agentId:c,err:String(d)})}}}async function NS(t,e,r,i,o){let{loadAgentConfig:c}=await Promise.resolve().then(()=>(cn(),xs)),d=await c(t,e);if(d){if(d.deletedAt)throw new k("AGENT_NOT_FOUND",`agent ${t} \u5DF2\u88AB\u5220\u9664 (deletedAt=${d.deletedAt}), \u4E0D\u80FD\u901A\u8FC7 --agent-id \u590D\u6D3B`);H.info("--agent-id: local config found, reconnecting",{agentId:t,framework:d.framework,hadDisconnect:!!d.disconnectedAt});let p=Kx(d),_={agentId:d.agentId,framework:d.framework,...d.cozeIdentity?{cozeIdentity:d.cozeIdentity}:{},...d.model?{model:d.model}:{},...o?{patToken:o}:{},...p?{_meta:p}:{}};return await r.createAgent(_),{ok:!0,agentId:t,note:d.disconnectedAt?"revived from local config":"connected from local config"}}H.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let u=await i({_meta:{cozeAgentId:t}});if(!u.framework)throw new k("AGENT_NOT_FOUND",`agent ${t} \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 f={agentId:u.agentId,framework:u.framework,...u.cozeIdentity?{cozeIdentity:u.cozeIdentity}:{},...u.model?{model:u.model}:{},...o?{patToken:o}:{},...u.deployType?{_meta:{cozeDeployType:u.deployType}}:{}};await r.createAgent(f);let x=u.deployType==="cloud"&&u.framework==="openclaw";return{ok:!0,agentId:t,note:x?"cloud agent acknowledged":"created from cloud detail"}}async function MS(t){let e=t.logger??H;try{let r=await t.detectAll();e.info("refreshed frameworks_cache",{detected:Object.keys(r??{})})}catch(r){e.warn("framework detection failed (using cached)",{err:String(r)})}await LS(t.paths,t.core).catch(r=>e.warn("scanAgentsOnStartup failed (ignored)",{err:String(r)})),await ea(t.paths,t.agentManager).catch(r=>e.warn("auto-revive top-level error (ignored)",{err:String(r)})),await BS(t.paths).catch(r=>e.warn("builtin skill refresh top-level error (ignored)",{err:String(r)}))}async function ea(t,e){let{readdir:r}=await import("node:fs/promises"),i;try{i=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(i.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:o}=await Promise.resolve().then(()=>(cn(),xs));H.info("auto-revive: scanning local agents on startup",{count:i.length});let c=0,d=0;for(let u of i){let f;try{f=await o(u,t)}catch(x){H.warn("auto-revive: load config failed (skipping)",{agentId:u,err:String(x)}),d+=1;continue}if(!f){d+=1;continue}if(f.deletedAt){H.info("auto-revive: skip deleted agent",{agentId:u,deletedAt:f.deletedAt}),d+=1;continue}if(f.disconnectedAt){H.info("auto-revive: skip disconnected agent",{agentId:u,disconnectedAt:f.disconnectedAt}),d+=1;continue}try{H.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:u,framework:f.framework});let x=Kx(f);await e.createAgent({agentId:f.agentId,framework:f.framework,...f.cozeIdentity?{cozeIdentity:f.cozeIdentity}:{},...f.model?{model:f.model}:{},...x?{_meta:x}:{}},{revive:!0}),c+=1}catch(x){H.warn("auto-revive: createAgent failed (skipping)",{agentId:u,framework:f.framework,err:String(x)}),d+=1}}return H.info("auto-revive: done",{revived:c,skipped:d,total:i.length}),{revived:c,skipped:d,total:i.length}}async function BS(t){let{readdir:e}=await import("node:fs/promises"),r;try{r=await e(t.agentsRoot)}catch{return{refreshed:0,total:0}}if(r.length===0)return{refreshed:0,total:0};let i=0;for(let o of r)try{(await r0(o,t)).status==="refreshed"&&(i+=1)}catch(c){H.warn("refresh builtin skills failed (skipping agent)",{agentId:o,err:String(c)})}return i>0&&H.info("builtin skills refresh on startup done",{refreshed:i,total:r.length}),{refreshed:i,total:r.length}}async function FS(t){let e=t.logger??H;if(t.cliSpawned)return"skipped-cli";let r=await t.readPatToken();return r?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:r}).catch(i=>e.warn("startup auto-connect failed (staying idle)",{err:String(i)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function Kx(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Yo();De();import{readFile as Vx}from"node:fs/promises";var Qt=class{paths;constructor(e){this.paths=e??Q()}async probe(e=1e3){let r=await ta(this.paths);if(!r)return{kind:"not-running"};try{let i=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return i.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${i.status}`}}catch(i){return{kind:"stale",reason:US(i)}}}async request(e){let r=await ta(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let i=r.body!==void 0,o={Authorization:`Bearer ${e.token}`};i&&(o["content-type"]="application/json");let c=new AbortController,d=setTimeout(()=>c.abort(),r.timeoutMs??5e3);try{let u=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:o,body:i?JSON.stringify(r.body):void 0,signal:c.signal}),f=await u.text();return{status:u.status,body:zS(f)}}finally{clearTimeout(d)}}};async function ta(t){try{let[e,r]=await Promise.all([Vx(t.portFile,"utf8"),Vx(t.tokenFile,"utf8")]),i=Number.parseInt(e.trim(),10),o=r.trim();return!Number.isFinite(i)||i<=0||!o?null:{port:i,token:o}}catch(e){if(e.code==="ENOENT")return null;throw e}}function zS(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function US(t){return t instanceof Error?t.message:String(t)}Kt();te();ir();import{spawn as GS}from"node:child_process";import{userInfo as Jx}from"node:os";var Ud="__COZE_BRIDGE_ENV_SENTINEL_5f3c91__",HS=new Set(["bash","zsh","sh","dash","ksh"]),Zx=Ke("COZE_BRIDGE_SHELLENV_TIMEOUT_MS",1e4),qS=2e3;function jS(t,e=Ud){let r=t.indexOf(e);if(r===-1)return null;let i=t.indexOf(e,r+e.length);if(i===-1)return null;let o=t.slice(r+e.length,i),c={};for(let d of o.split(`
113
+ `)){let u=d.indexOf("=");u<=0||(c[d.slice(0,u)]=d.slice(u+1))}return c}function WS(){let t=(process.env.SHELL??"").trim()||(Jx().shell??"").trim();if(!t)return null;let e=t.slice(t.lastIndexOf("/")+1);return HS.has(e)?t:null}function $S(t){return new Promise(e=>{let r=`printf '%s' '${Ud}'; env; printf '%s' '${Ud}'`,i;try{i=GS(t,["-ilc",r],{detached:!0,stdio:["ignore","pipe","ignore"],env:{...process.env,HOME:process.env.HOME??Jx().homedir}})}catch{e(null);return}let o="",c=!1,d=p=>{try{i.pid&&process.kill(-i.pid,p)}catch{}},u=p=>{c||(c=!0,clearTimeout(f),clearTimeout(x),e(p))};i.stdout?.on("data",p=>{o+=p.toString("utf8")}),i.on("error",()=>u(null)),i.on("close",()=>u(o.length>0?o:null));let f=setTimeout(()=>d("SIGTERM"),Zx),x=setTimeout(()=>{d("SIGKILL"),u(o.length>0?o:null)},Zx+qS)})}async function Gd(t={}){if((t.platform??process.platform)==="win32")return{kind:"skipped",reason:"windows"};let r=WS();if(!r)return{kind:"skipped",reason:"no-supported-login-shell"};let i=await(t.run??$S)(r);if(i==null)return{kind:"failed",reason:"shell-timeout-or-error"};let o=jS(i);return o==null?{kind:"failed",reason:"unparseable-output"}:{kind:"ok",env:o}}De();function Rn(t,...e){let r=[],i;for(let o=0;o<t.length;o++){let c=t[o],d=!1;for(let u of e){if(c===u){i=t[o+1],o+=1,d=!0;break}if(c.startsWith(`${u}=`)){i=c.slice(u.length+1),d=!0;break}}d||r.push(c)}return{value:i,rest:r}}sn();import{chmod as KS,copyFile as Yx,mkdir as Qx,readFile as na,rename as Xx,rm as Hd,stat as ep,writeFile as VS}from"node:fs/promises";import{homedir as iD}from"node:os";import{dirname as ZS,join as $r,resolve as qd,sep as is}from"node:path";import{fileURLToPath as JS}from"node:url";Kt();te();De();var jd=G("dist-install");function YS(t){let e=JS(t),r=ZS(e),i=`${is}src${is}`;if(r.includes(i)||r.endsWith(`${is}src${is}cli`))return null;let o=qd(r,"index.js"),c=qd(r,"..","package.json");return{dist:o,pkgJson:c}}async function $d(t={}){let e=t.paths??Q(),r=YS(import.meta.url),i=t.sourceDist??r?.dist,o=t.sourcePackageJson??r?.pkgJson;if(!i||!o)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(i===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let c,d;try{let v=JSON.parse(await na(o,"utf8"));c=v.version??"unknown",d=v.dependencies??{}}catch(v){return jd.warn("cannot read source package.json,skip dist install",{err:String(v)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(v)}`}}let u=ti.map(v=>`${v}@${d[v]??"latest"}`),f=await vo(e.configFile)??{},x=f.libVersion,p=await na(e.libEntry).then(()=>!0).catch(()=>!1),_=x===c;if(_&&p&&await Wd(e))return{kind:"already-current",libVersion:c};if(!_||!p){await Qx(e.libDir,{recursive:!0}),await Yx(i,e.libEntry),await Yx(`${i}.map`,`${e.libEntry}.map`).catch(()=>{});let v=qd(e.libDir,"package.json"),w=`${JSON.stringify({type:"module"},null,2)}
114
+ `;await na(v,"utf8").catch(()=>null)!==w&&await VS(v,w)}return(!_||!await Wd(e))&&await(t.installWrappers??XS)(e,u),f.libVersion=c,await ji(f,e.configFile),jd.info("dist installed",{libEntry:e.libEntry,fromVersion:x,toVersion:c}),_&&p?{kind:"already-current",libVersion:c}:x?{kind:"version-changed",fromVersion:x,toVersion:c,libEntry:e.libEntry}:{kind:"first-install",libVersion:c,libEntry:e.libEntry}}async function Wd(t){for(let e of ti){let r=$r(t.libDir,"node_modules",...e.split("/"),"package.json");if(!await ep(r).then(o=>o.isFile()).catch(()=>!1))return!1}return!0}async function XS(t,e){await t1(t.installLock,async()=>{if(await Wd(t))return;let r=Math.random().toString(36).slice(2,10),i=`${t.libDir}${is}.staging-${process.pid}-${r}`,o=$r(i,"node_modules"),c=$r(t.libDir,"node_modules");try{await Qx(i,{recursive:!0}),await QS(e,i),await e1(o);let d=`${c}.trash-${r}`;await Xx(c,d).catch(()=>{}),await Xx(o,c),await Hd(d,{recursive:!0,force:!0}).catch(()=>{}),jd.info("wrapper closure installed",{liveNm:c,specs:e})}finally{await Hd(i,{recursive:!0,force:!0}).catch(()=>{})}})}function QS(t,e){let r=["install",...t,"--prefix",e,"--omit=dev","--prefer-offline","--no-audit","--no-fund"];return new Promise((i,o)=>{let c=nt("npm",r,{stdio:["ignore","pipe","pipe"]}),d="";c.stderr?.on("data",f=>{d.length<8192&&(d+=f.toString("utf8"))});let u=setTimeout(()=>c.kill("SIGKILL"),18e4);c.once("error",f=>{clearTimeout(u),o(new Error(`spawn npm failed: ${String(f)}`))}),c.once("close",f=>{clearTimeout(u),f===0?i():o(new Error(`npm install \u9000\u51FA\u7801 ${f}: ${d.trim().slice(0,2e3)}`))})})}async function e1(t){for(let e of ti){let r=$r(t,...e.split("/")),i=JSON.parse(await na($r(r,"package.json"),"utf8"));if(!i.version)throw new Error(`${e}: package.json \u7F3A version`);let o=typeof i.bin=="string"?e.split("/").pop():Object.keys(i.bin??{})[0];if(!o)throw new Error(`${e}: package.json \u7F3A bin`);let c=$r(t,".bin",o),d=await ep(c);process.platform!=="win32"&&!(d.mode&73)&&await KS(c,d.mode|73).catch(()=>{})}}async function t1(t,e){let{open:r}=await import("node:fs/promises"),i=!1;for(let o=0;o<60&&!i;o++)try{await(await r(t,"wx")).close(),i=!0}catch{await new Promise(c=>setTimeout(c,500))}try{return await e()}finally{i&&await Hd(t,{force:!0}).catch(()=>{})}}Sa();te();De();import{closeSync as np,fstatSync as rp,openSync as ip,readFileSync as n1,readSync as r1,readdirSync as i1,statSync as s1}from"node:fs";import{join as ra}from"node:path";var o1=new Set(["debug","info","warn","error"]);function sp(t){let e=t,r=Rn(e,"--agent-id");e=r.rest;let i=Rn(e,"--date");e=i.rest;let o=Rn(e,"-n","--lines");e=o.rest;let c=Rn(e,"--level");e=c.rest;let d=Rn(e,"--grep");e=d.rest;let u=o.value===void 0?200:Number(o.value),f=Number.isInteger(u)&&u>=0?u:200,x=c.value&&o1.has(c.value)?c.value:void 0,p={lines:f,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return r.value&&(p.agentId=r.value),i.value&&(p.date=i.value),x&&(p.level=x),d.value&&(p.grep=d.value),p}function a1(t,e){return t.agentId?ra(Ve(t.agentId,e).logs,sr("agent",t.date)):ra(e.bridgeLogsDir,sr("bridge",t.date))}function c1(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function d1(t,e){let r;try{r=i1(t)}catch{return[]}let i=[];for(let o of r){let c=va(o,e);if(!c)continue;let d=0;try{d=s1(ra(t,o)).size}catch{}i.push({file:ra(t,o),date:c,size:d})}return i.sort((o,c)=>c.date.localeCompare(o.date)),i}function op(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let r;try{r=JSON.parse(t).level}catch{return!0}if(typeof r=="string"&&!bl(r,e.level))return!1}return!0}var tp={debug:"90",info:"36",warn:"33",error:"31"},l1=new Set(["ts","level","module","msg"]);function u1(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function ap(t,e){if(e.raw)return t;let r;try{r=JSON.parse(t)}catch{return t}let i=u1(r.ts),o=typeof r.level=="string"?r.level:"",c=o.toUpperCase().padEnd(5);e.color&&tp[o]&&(c=`\x1B[${tp[o]}m${c}\x1B[0m`);let d=typeof r.module=="string"?r.module:"",u=typeof r.msg=="string"?r.msg:"",f=Object.entries(r).filter(([x])=>!l1.has(x)).map(([x,p])=>` ${x}=${typeof p=="string"?p:JSON.stringify(p)}`).join("");return`${i} ${c} ${d} ${u}${f}`}function f1(t,e,r){let c=n1(t,"utf8").split(`
115
+ `).filter(d=>d.length>0).filter(d=>op(d,{level:e.level,grep:e.grep}));for(let d of c1(c,e.lines))process.stdout.write(`${ap(d,{raw:e.raw,color:r})}
116
+ `)}async function cp(t,e){let r=e.paths??Q(),i=process.stdout.isTTY===!0;if(t.list){let d=t.agentId?Ve(t.agentId,r).logs:r.bridgeLogsDir,u=t.agentId?"agent":"bridge",f=d1(d,u);if(f.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${d}
117
+ `),1;for(let x of f)process.stdout.write(`${x.date} ${(x.size/1024).toFixed(1)}KB ${x.file}
118
+ `);return 0}let o=t.date??Pn(new Date),c=a1({agentId:t.agentId,date:o},r);try{f1(c,t,i)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${c}
117
119
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
118
120
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${r.logFile})
119
- `),1}return t.follow&&await $S(c,t,i),0}var WS=500;function KS(t){try{let e=Hh(t,"r");try{return Uh(e).size}finally{zh(e)}}catch{return 0}}async function $S(t,e,r){let i=KS(t),o="",c=!1,l=()=>{c=!0};process.on("SIGINT",l);try{for(;!c;){let u="";try{let x=Hh(t,"r");try{let h=Uh(x).size;if(h>i){let w=Buffer.allocUnsafe(h-i),_=NS(x,w,0,w.length,i);u=w.subarray(0,_).toString("utf8"),i+=_}}finally{zh(x)}}catch{}if(u){let x=(o+u).split(`
120
- `);o=x.pop()??"";for(let h of x)h.length>0&&qh(h,{level:e.level,grep:e.grep})&&process.stdout.write(`${jh(h,{raw:e.raw,color:r})}
121
- `)}await new Promise(x=>setTimeout(x,WS))}}finally{process.off("SIGINT",l)}}import{basename as VS,resolve as ZS}from"node:path";Pe();var JS=9e4,YS={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1};function XS(t){return YS[t]??1}async function Kh(t,e={}){let r=e.paths??Q();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
121
+ `),1}return t.follow&&await p1(c,t,i),0}var h1=500;function x1(t){try{let e=ip(t,"r");try{return rp(e).size}finally{np(e)}}catch{return 0}}async function p1(t,e,r){let i=x1(t),o="",c=!1,d=()=>{c=!0};process.on("SIGINT",d);try{for(;!c;){let u="";try{let f=ip(t,"r");try{let x=rp(f).size;if(x>i){let p=Buffer.allocUnsafe(x-i),_=r1(f,p,0,p.length,i);u=p.subarray(0,_).toString("utf8"),i+=_}}finally{np(f)}}catch{}if(u){let f=(o+u).split(`
122
+ `);o=f.pop()??"";for(let x of f)x.length>0&&op(x,{level:e.level,grep:e.grep})&&process.stdout.write(`${ap(x,{raw:e.raw,color:r})}
123
+ `)}await new Promise(f=>setTimeout(f,h1))}}finally{process.off("SIGINT",d)}}import{basename as g1,resolve as m1}from"node:path";De();var w1=9e4,_1={PATH_OUTSIDE_WORKSPACE:3,FILE_TOO_LARGE:3,UNSUPPORTED_MIME:3,MODEL_MODALITY_UNSUPPORTED:3,IPC_BAD_REQUEST:3,AGENT_NOT_FOUND:4,IPC_AUTH_FAILED:4,AGENT_DISCONNECTED:5,UPLOAD_FAILED:5,UPSTREAM_NOT_READY:5,UPSTREAM_DISCONNECTED:5,UPSTREAM_HANDSHAKE_FAILED:5,AGENT_BUSY:1,AGENT_SPAWN_FAILED:1,AGENT_TIMEOUT:1,AGENT_FRAME_IDLE_TIMEOUT:1,AGENT_PROTOCOL_ERROR:1,AGENT_TURN_ABORTED:1,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,OPERATION_NOT_ALLOWED_FOR_CLOUD:1,METHOD_NOT_FOUND:1,AGENT_DEPENDENCY_INSTALL_FAILED:1,AGENT_APPROVAL_TIMEOUT:1,AGENT_ENV_NOT_READY:1,SKILL_NOT_FOUND:1,SKILL_ZIP_TOO_LARGE:1};function y1(t){return _1[t]??1}async function dp(t,e={}){let r=e.paths??Q();if(!t.agentId||!t.sessionId)return process.stderr.write(`Error: missing --agent-id and/or --session-id. These IDs come from the <coze-context> block injected at the top of each prompt \u2014 extract agentId and sessionId from there and pass them as flags. Example: coze-bridge send image x.png --agent-id <id> --session-id <id>
122
124
  `),4;if(t.groupFile&&!t.mimeType)return process.stderr.write(`Error: --group-file requires --mime <mimeType> (e.g. application/pdf, image/png). No local file is read in group-file mode, mime cannot be auto-detected.
123
- `),3;let i=await Xo(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
124
- `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:ZS(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await QS(i,"/agent/send",o,JS)}catch(l){return process.stderr.write(`Error: daemon IPC failed: ${l instanceof Error?l.message:String(l)}
125
+ `),3;let i=await ta(r).catch(()=>null);if(!i)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
126
+ `),4;let o={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:m1(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},c;try{c=await b1(i,"/agent/send",o,w1)}catch(d){return process.stderr.write(`Error: daemon IPC failed: ${d instanceof Error?d.message:String(d)}
125
127
  `),4}if(!c.ok)return process.stderr.write(`Error: ${c.code}: ${c.message}
126
- `),XS(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
127
- `);else{let l=t.name??VS(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${l} (uri=${u})
128
- `)}else process.stdout.write(`Sent ${t.kind} ${l} (${e2(c.bytes)})
129
- `)}return 0}async function QS(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let l=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await l.text(),x=u?JSON.parse(u):null;return x&&typeof x=="object"&&"ok"in x?x:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${l.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function e2(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var tp=G("cli");function He(t,e){let{value:r,rest:i}=Cn(t,e);return{value:r,rest:i}}function oa(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
130
- `)}function S2(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:P}=He(e.slice(1),"--agent-id");return P?{mode:"reload",agentId:P}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return I2(e.slice(1));if(e[0]==="log")return{mode:"log",...Gh(e.slice(1))};if(e[0]==="connect")return A2(e.slice(1));if(e.includes("--status"))return oa("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return oa("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return oa("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return oa("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=He(r,"--pat-token");r=o;let{value:c,rest:l}=He(r,"--pair-code");r=l;let{value:u,rest:x}=He(r,"--env");r=x;let{value:h,rest:w}=He(r,"--handshake-url");r=w;let{value:_,rest:v}=He(r,"--frontier-url");r=v;let{value:y,rest:E}=He(r,"--mock-scenario");r=E;let{value:I}=He(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let C={mode:"pair",privatecode:i,pairingCode:c};return u&&(C.env=u),h&&(C.handshakeUrl=h),_&&(C.frontierUrl=_),y&&(C.mockScenario=y),I&&(C.agentId=I),A&&(C.skipRebuildEnv=!0),C}function I2(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=He(i,"--caption");i=c;let{value:l,rest:u}=He(i,"--name");i=u;let{value:x,rest:h}=He(i,"--agent-id");i=h;let{value:w,rest:_}=He(i,"--session-id");i=_;let{value:v,rest:y}=He(i,"--mime");i=y;let E=i.includes("--group-file");i=i.filter(C=>C!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),l&&(A.name=l),x&&(A.agentId=x),w&&(A.sessionId=w),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function A2(t){let e=t,{value:r,rest:i}=He(e,"--pat-token");e=i;let{value:o,rest:c}=He(e,"--env");e=c;let{value:l,rest:u}=He(e,"--handshake-url");e=u;let{value:x,rest:h}=He(e,"--frontier-url");e=h;let{value:w,rest:_}=He(e,"--mock-scenario");e=_;let v=e.includes("--skip-rebuild-env"),y={mode:"connect"};return r&&(y.privatecode=r),o&&(y.env=o),l&&(y.handshakeUrl=l),x&&(y.frontierUrl=x),w&&(y.mockScenario=w),v&&(y.skipRebuildEnv=!0),y}var T2=`
128
+ `),y1(c.code);if(t.json)process.stdout.write(`${JSON.stringify(c)}
129
+ `);else{let d=t.name??g1(o.path);if(t.groupFile){let u=c.uri.length>60?`${c.uri.slice(0,57)}...`:c.uri;process.stdout.write(`Sent group file ${d} (uri=${u})
130
+ `)}else process.stdout.write(`Sent ${t.kind} ${d} (${E1(c.bytes)})
131
+ `)}return 0}async function b1(t,e,r,i){let o=new AbortController,c=setTimeout(()=>o.abort(),i);try{let d=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:o.signal}),u=await d.text(),f=u?JSON.parse(u):null;return f&&typeof f=="object"&&"ok"in f?f:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${d.status}): ${u.slice(0,200)}`}}finally{clearTimeout(c)}}function E1(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var wp=G("cli");function He(t,e){let{value:r,rest:i}=Rn(t,e);return{value:r,rest:i}}function da(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
132
+ `)}function $1(t){let e=t.slice(2);if(e.includes("--version")||e.includes("-v"))return{mode:"version"};if(e.includes("--daemon"))return{mode:"daemon"};if(e[0]==="status")return{mode:"status"};if(e[0]==="stop")return{mode:"stop"};if(e[0]==="reload"){let{value:D}=He(e.slice(1),"--agent-id");return D?{mode:"reload",agentId:D}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return K1(e.slice(1));if(e[0]==="log")return{mode:"log",...sp(e.slice(1))};if(e[0]==="connect")return V1(e.slice(1));if(e.includes("--status"))return da("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return da("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return da("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return da("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:i,rest:o}=He(r,"--pat-token");r=o;let{value:c,rest:d}=He(r,"--pair-code");r=d;let{value:u,rest:f}=He(r,"--env");r=f;let{value:x,rest:p}=He(r,"--handshake-url");r=p;let{value:_,rest:v}=He(r,"--frontier-url");r=v;let{value:w,rest:E}=He(r,"--mock-scenario");r=E;let{value:I}=He(r,"--agent-id"),A=r.includes("--skip-rebuild-env");if(!i||!c)return{mode:"help"};let T={mode:"pair",privatecode:i,pairingCode:c};return u&&(T.env=u),x&&(T.handshakeUrl=x),_&&(T.frontierUrl=_),w&&(T.mockScenario=w),I&&(T.agentId=I),A&&(T.skipRebuildEnv=!0),T}function K1(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let i=t.slice(2),{value:o,rest:c}=He(i,"--caption");i=c;let{value:d,rest:u}=He(i,"--name");i=u;let{value:f,rest:x}=He(i,"--agent-id");i=x;let{value:p,rest:_}=He(i,"--session-id");i=_;let{value:v,rest:w}=He(i,"--mime");i=w;let E=i.includes("--group-file");i=i.filter(T=>T!=="--group-file");let I=i.includes("--json"),A={mode:"send",kind:e,path:r,json:I};return o&&(A.caption=o),d&&(A.name=d),f&&(A.agentId=f),p&&(A.sessionId=p),E&&(A.groupFile=!0),v&&(A.mimeType=v),A}function V1(t){let e=t,{value:r,rest:i}=He(e,"--pat-token");e=i;let{value:o,rest:c}=He(e,"--env");e=c;let{value:d,rest:u}=He(e,"--handshake-url");e=u;let{value:f,rest:x}=He(e,"--frontier-url");e=x;let{value:p,rest:_}=He(e,"--mock-scenario");e=_;let v=e.includes("--skip-rebuild-env"),w={mode:"connect"};return r&&(w.privatecode=r),o&&(w.env=o),d&&(w.handshakeUrl=d),f&&(w.frontierUrl=f),p&&(w.mockScenario=p),v&&(w.skipRebuildEnv=!0),w}var Z1=`
131
133
  coze-bridge - local bridge daemon for cloud Agent Service
132
134
 
133
135
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -208,57 +210,57 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
208
210
 
209
211
  Internal:
210
212
  <node> <entry> --daemon daemon mode (OS supervisor only)
211
- `.trimStart();async function np(t=process.argv,e={}){let r=S2(t);switch(r.mode){case"help":return process.stdout.write(T2),0;case"version":return process.stdout.write(`${Cr}
212
- `),0;case"daemon":{try{await Rh()}catch(i){return tp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return C2(e);case"stop":return ip(e);case"reload":return P2(r.agentId,e);case"log":return Wh(r,e);case"update":return R2(e);case"purge":return D2(e);case"service-install":return O2(e);case"service-uninstall":return L2(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),N2(r.privatecode,r.pairingCode,e,i,r.agentId,r.skipRebuildEnv)}case"connect":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),M2(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return Kh({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function rp(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function C2(t){let e=t.paths??Q(),r=new Xt(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
213
- `),1;if(i.kind==="stale")return await rp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
213
+ `.trimStart();async function _p(t=process.argv,e={}){let r=$1(t);switch(r.mode){case"help":return process.stdout.write(Z1),0;case"version":return process.stdout.write(`${Ot}
214
+ `),0;case"daemon":{try{await $x()}catch(i){return wp.error("daemon start failed",{err:String(i)}),1}return new Promise(()=>{})}case"status":return J1(e);case"stop":return bp(e);case"reload":return Q1(r.agentId,e);case"log":return cp(r,e);case"update":return Y1(e);case"purge":return eI(e);case"service-install":return tI(e);case"service-uninstall":return nI(e);case"pair":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),rI(r.privatecode,r.pairingCode,e,i,r.agentId,r.skipRebuildEnv)}case"connect":{let i={};return r.env&&(i.env=r.env),r.handshakeUrl&&(i.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(i.frontierUrl=r.frontierUrl),r.mockScenario&&(i.mockScenario=r.mockScenario),iI(r.privatecode,e,i,r.skipRebuildEnv)}case"send":return dp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function yp(t){let{unlink:e}=await import("node:fs/promises");await Promise.all([e(t.pidFile).catch(()=>{}),e(t.portFile).catch(()=>{}),e(t.tokenFile).catch(()=>{})])}async function J1(t){let e=t.paths??Q(),r=new Qt(e),i=await r.probe();if(i.kind==="not-running")return process.stdout.write(`coze-bridge: not running
215
+ `),1;if(i.kind==="stale")return await yp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
214
216
  `),1;let o=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
215
217
  ${JSON.stringify(o.body,null,2)}
216
- `),0}async function ip(t){let e=t.paths??Q(),r=new Xt(e),i=t.daemonSweep??(async()=>{let x=a0();return await c0(x),x}),o=async()=>{t.skipProcessKill||await i(e)},c=await rs(t),l=!1;if(c)try{await c.uninstall(),l=!0}catch(x){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(x)}
217
- `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(l?`coze-bridge: stopped
218
+ `),0}async function bp(t){let e=t.paths??Q(),r=new Qt(e),i=t.daemonSweep??(async()=>{let f=m0();return await w0(f),f}),o=async()=>{t.skipProcessKill||await i(e)},c=await os(t),d=!1;if(c)try{await c.uninstall(),d=!0}catch(f){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(f)}
219
+ `)}let u=await r.probe();if(u.kind==="not-running")return await o(),process.stdout.write(d?`coze-bridge: stopped
218
220
  `:`coze-bridge: not running
219
- `),0;if(u.kind==="stale")return await rp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
221
+ `),0;if(u.kind==="stale")return await yp(e),await o(),process.stdout.write(`coze-bridge: not running (cleaned stale state)
220
222
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),await o(),process.stdout.write(`coze-bridge: stopped
221
- `),0}catch(x){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
222
- `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(x)}
223
- `),1)}}async function R2(t){return await ip(t),(t.spawnNpx??k2)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function k2(t){return new Promise(e=>{let r=et("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
224
- `),e(1)})})}async function P2(t,e){let r=new Xt(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
223
+ `),0}catch(f){return(await r.probe()).kind!=="connected"?(await o(),process.stdout.write(`coze-bridge: stopped
224
+ `),0):(await o(),process.stdout.write(`coze-bridge: stop failed: ${String(f)}
225
+ `),1)}}async function Y1(t){return await bp(t),(t.spawnNpx??X1)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function X1(t){return new Promise(e=>{let r=nt("npx",t,{stdio:"inherit"});r.on("exit",i=>e(i??1)),r.on("error",i=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(i)}
226
+ `),e(1)})})}async function Q1(t,e){let r=new Qt(e.paths);if((await r.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
225
227
  `),1;try{let o=await r.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(o.status===200&&o.body?.ok){let c=o.body.recycled??[];return t&&c.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
226
228
  `):process.stdout.write(`coze-bridge: reloaded ${c.length} agent(s): ${c.join(", ")||"(none)"}
227
229
  `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(o.body)}
228
230
  `),1}catch(o){return process.stderr.write(`coze-bridge: reload failed: ${String(o)}
229
- `),1}}async function rs(t){if(t.supervisor){let c=t.supervisor,l={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(l,u),uninstall:()=>c.uninstall(l)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Qh(),Xh)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function sp(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??Th,o=t.waitTimeoutMs??15e3,c=t.sleep??F2,l=t.paths??Q(),u=await rs(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let x=await ep(e,o,c);if(x.kind==="connected")return x;It(l.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(x){It(l.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(x)})}It(l.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await B2(l.pidFile,c)}else u&&await u.install({activate:!1}).catch(x=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(x)}
231
+ `),1}}async function os(t){if(t.supervisor){let c=t.supervisor,d={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:c.platform,install:u=>c.install(d,u),uninstall:()=>c.uninstall(d)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(gp(),pp)),i=e(),o=r();return{platform:i.platform,install:c=>i.install(o,c),uninstall:()=>i.uninstall(o)}}async function Ep(t,e){let r=await e.probe();if(r.kind==="connected")return r;let i=t.spawnDaemon??jx,o=t.waitTimeoutMs??15e3,c=t.sleep??oI,d=t.paths??Q(),u=await os(t);if(u&&(u.platform==="darwin"||u.platform==="linux")){try{await u.install({activate:!0});let f=await mp(e,o,c);if(f.kind==="connected")return f;At(d.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:o})}catch(f){At(d.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(f)})}At(d.bridgeLogsDir,"warn","cli","\u79FB\u9664\u5F00\u673A\u81EA\u542F\u914D\u7F6E (supervisor \u63A5\u7BA1\u672A\u6210\u529F, \u56DE\u9000\u624B\u52A8 spawn; \u4E0B\u6B21\u91CD\u542F\u4E0D\u518D\u81EA\u542F, \u9700\u91CD\u65B0 service install)",{platform:u.platform}),await u.uninstall().catch(()=>{}),await sI(d.pidFile,c)}else u&&await u.install({activate:!1}).catch(f=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(f)}
230
232
  `));return process.stdout.write(`coze-bridge: starting daemon...
231
- `),await i({paths:t.paths}),ep(e,o,c)}async function D2(t){let e=new Xt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
232
- `);try{await e.request({method:"POST",path:"/shutdown"})}catch(l){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(l)}
233
- `)}await new Promise(l=>setTimeout(l,500))}let i=await rs(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
234
- `)}catch(l){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(l)}
233
+ `),await i({paths:t.paths}),mp(e,o,c)}async function eI(t){let e=new Qt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
234
+ `);try{await e.request({method:"POST",path:"/shutdown"})}catch(d){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(d)}
235
+ `)}await new Promise(d=>setTimeout(d,500))}let i=await os(t);if(i)try{await i.uninstall(),process.stdout.write(`coze-bridge: ${i.platform} supervisor unregistered
236
+ `)}catch(d){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(d)}
235
237
  `)}let o=t.paths??Q(),{rm:c}=await import("node:fs/promises");try{await c(o.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${o.bridgeRoot}
236
- `)}catch(l){return process.stderr.write(`coze-bridge: remove failed: ${String(l)}
238
+ `)}catch(d){return process.stderr.write(`coze-bridge: remove failed: ${String(d)}
237
239
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
238
- `),0}async function O2(t){let e=await rs(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
240
+ `),0}async function tI(t){let e=await os(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
239
241
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
240
242
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
241
- `),1}}async function L2(t){let e=await rs(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
243
+ `),1}}async function nI(t){let e=await os(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
242
244
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
243
- `),1}}async function op(t,e,r){if(e)return It(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(It(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(It(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
244
- `),It(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function N2(t,e,r,i={},o,c){let l=new Xt(r.paths),u=r.paths??Q(),x=await op(u,c,r.reconstructEnv??Nd);if(await Jc(u,x).catch(_=>It(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await Ud({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
245
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(y=>setTimeout(y,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
246
- `)}let h=await sp(r,l);if(h.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${h.kind}
247
- `),1;let w={privatecode:t,pairing_code:e};i.env&&(w.env=i.env),i.handshakeUrl&&(w.handshake_url=i.handshakeUrl),i.frontierUrl&&(w.frontier_url=i.frontierUrl),i.mockScenario&&(w.mock_scenario=i.mockScenario),o&&(w.agent_id=o);try{let _=await l.request({method:"POST",path:"/pair",body:w,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let v=_.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
245
+ `),1}}async function vp(t,e,r){if(e)return At(t.bridgeLogsDir,"info","cli","agent-env: skip rebuild, use process.env",{}),process.env;let i=await r();return i.kind==="ok"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuilt from login shell",{vars:Object.keys(i.env).length}),i.env):i.kind==="skipped"?(At(t.bridgeLogsDir,"info","cli","agent-env: rebuild not applicable, use process.env",{reason:i.reason}),process.env):(process.stderr.write(`coze-bridge: \u91CD\u5EFA shell \u73AF\u5883\u5931\u8D25, \u56DE\u9000\u5F53\u524D\u8FDB\u7A0B\u73AF\u5883 (\u53EF\u7528 --skip-rebuild-env \u663E\u5F0F\u8DF3\u8FC7)
246
+ `),At(t.bridgeLogsDir,"warn","cli","reconstructLoginShellEnv failed, fell back to process.env",{reason:i.reason}),process.env)}async function rI(t,e,r,i={},o,c){let d=new Qt(r.paths),u=r.paths??Q(),f=await vp(u,c,r.reconstructEnv??Gd);if(await Qc(u,f).catch(_=>At(u.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(_)})),!r.skipDistInstall){let _=await $d({paths:r.paths});_.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${_.fromVersion} \u2192 ${_.toVersion}
247
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(w=>setTimeout(w,500)))):_.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${_.libVersion}
248
+ `)}let x=await Ep(r,d);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
249
+ `),1;let p={privatecode:t,pairing_code:e};i.env&&(p.env=i.env),i.handshakeUrl&&(p.handshake_url=i.handshakeUrl),i.frontierUrl&&(p.frontier_url=i.frontierUrl),i.mockScenario&&(p.mock_scenario=i.mockScenario),o&&(p.agent_id=o);try{let _=await d.request({method:"POST",path:"/pair",body:p,timeoutMs:35e3});if(_.status===200&&_.body?.ok){let v=_.body.agent;return v&&!v.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${v.agentId}): ${v.note}
248
250
  `),1):(process.stdout.write(`\u5DF2\u914D\u5BF9\u8FDE\u63A5\u5B8C\u6210\uFF0C\u8BF7\u8FD4\u56DE\u5230 coze \u5E73\u53F0\u4E0A\u70B9\u51FB "\u6211\u5DF2\u6267\u884C"
249
251
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(_.body)}
250
252
  `),1}catch(_){return process.stderr.write(`coze-bridge: pair failed: ${String(_)}
251
- `),1}}async function M2(t,e,r={},i){let o=e.paths??Q(),c=t??await Wo(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let l=new Xt(e.paths),u=await op(o,i,e.reconstructEnv??Nd);if(await Jc(o,u).catch(w=>It(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(w)})),!e.skipDistInstall){let w=await Ud({paths:e.paths});w.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${w.fromVersion} \u2192 ${w.toVersion}
252
- `),(await l.probe()).kind==="connected"&&(await l.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):w.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${w.libVersion}
253
- `)}let x=await sp(e,l);if(x.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${x.kind}
254
- `),1;let h={privatecode:c};r.env&&(h.env=r.env),r.handshakeUrl&&(h.handshake_url=r.handshakeUrl),r.frontierUrl&&(h.frontier_url=r.frontierUrl),r.mockScenario&&(h.mock_scenario=r.mockScenario);try{let w=await l.request({method:"POST",path:"/connect",body:h,timeoutMs:35e3});return w.status===200&&w.body?.ok?(process.stdout.write(`coze-bridge: connected (${w.body.note??"ok"})
255
- `),t!==void 0&&await Qi(c,o).catch(_=>tp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(w.body)}
256
- `),1)}catch(w){return process.stderr.write(`coze-bridge: connect failed: ${String(w)}
257
- `),1}}async function ep(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function B2(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let l;try{l=await o(t,"utf8")}catch{return}let u=Number.parseInt(l.trim(),10);if(!Number.isFinite(u)||u<=0||!Bi(u))return;await e(i)}}function F2(t){return new Promise(e=>setTimeout(e,t))}ne();function z2(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function ap(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=z2(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
253
+ `),1}}async function iI(t,e,r={},i){let o=e.paths??Q(),c=t??await Vo(o);if(!c)return process.stderr.write("coze-bridge: \u627E\u4E0D\u5230 patToken \u2014 \u5148\u8DD1\u4E00\u6B21 `coze-bridge --pat-token=<sat_xxx> --pair-code=<xxx>` \u914D\u5BF9, \u6216\u672C\u6B21\u7528 `--pat-token` \u6307\u5B9A\n"),1;let d=new Qt(e.paths),u=await vp(o,i,e.reconstructEnv??Gd);if(await Qc(o,u).catch(p=>At(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(p)})),!e.skipDistInstall){let p=await $d({paths:e.paths});p.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${p.fromVersion} \u2192 ${p.toVersion}
254
+ `),(await d.probe()).kind==="connected"&&(await d.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(v=>setTimeout(v,500)))):p.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${p.libVersion}
255
+ `)}let f=await Ep(e,d);if(f.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${f.kind}
256
+ `),1;let x={privatecode:c};r.env&&(x.env=r.env),r.handshakeUrl&&(x.handshake_url=r.handshakeUrl),r.frontierUrl&&(x.frontier_url=r.frontierUrl),r.mockScenario&&(x.mock_scenario=r.mockScenario);try{let p=await d.request({method:"POST",path:"/connect",body:x,timeoutMs:35e3});return p.status===200&&p.body?.ok?(process.stdout.write(`coze-bridge: connected (${p.body.note??"ok"})
257
+ `),t!==void 0&&await ns(c,o).catch(_=>wp.warn("writePatToken after connect failed (ignored)",{err:String(_)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(p.body)}
258
+ `),1)}catch(p){return process.stderr.write(`coze-bridge: connect failed: ${String(p)}
259
+ `),1}}async function mp(t,e,r){let i=Date.now()+e;for(;Date.now()<i;){let o=await t.probe(500);if(o.kind==="connected")return o;await r(200)}return t.probe(500)}async function sI(t,e,r=60,i=200){let{readFile:o}=await import("node:fs/promises");for(let c=0;c<r;c++){let d;try{d=await o(t,"utf8")}catch{return}let u=Number.parseInt(d.trim(),10);if(!Number.isFinite(u)||u<=0||!Ui(u))return;await e(i)}}function oI(t){return new Promise(e=>setTimeout(e,t))}te();function aI(t){let e=/^v?(\d+)(?:\.(\d+))?/.exec(t.trim());if(!e)return"ok";let r=Number(e[1]),i=Number(e[2]??0);return r<18||r===18&&i<4?"fatal":r<20?"warn":"ok"}function Sp(t=process.versions.node,e=i=>{process.stderr.write(i)},r=i=>process.exit(i)){let i=aI(t);if(i==="ok")return;let o=t.replace(/^v/,"");i==="fatal"?(e(`[coze-bridge] \u5F53\u524D Node.js \u7248\u672C v${o} \u8FC7\u4F4E,\u65E0\u6CD5\u8FD0\u884C(\u6700\u4F4E v18.4.0,\u63A8\u8350 v20+)\u3002\u8BF7\u5347\u7EA7\u540E\u91CD\u8BD5:https://nodejs.org(\u6216\u7528 nvm/fnm)\u3002
258
260
  `),r(1)):e(`[coze-bridge] \u68C0\u6D4B\u5230 Node.js v${o},\u672C\u9879\u76EE\u63A8\u8350 v20+,\u4F4E\u4E8E v20 \u540E\u7EED\u5347\u7EA7\u53EF\u80FD\u6709\u517C\u5BB9\u95EE\u9898,\u5EFA\u8BAE\u5347\u7EA7\u3002
259
261
  \u5347\u7EA7\u5B8C\u540E\u9700\u8981\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u91CD\u65B0\u8FDE\u63A5:
260
262
  npx -y coze-bridge@latest stop
261
263
  npx -y coze-bridge@latest connect
262
264
 
263
- `)}ap();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&fl("warn");np(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
265
+ `)}Sp();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&_l("warn");_p(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
264
266
  `),process.exit(1)});